diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 401ce6ab..4bcac3a9 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -35,7 +35,8 @@ images, materials, sample graphs, presets, environments) may ever be added.
| `docs/images/materialcraft-levels-editor.png` | Docs screenshot: the Levels editor with the input histogram | MaterialCraft contributors | Offscreen render of MaterialCraft's UI (`crates/ui-egui/tests/snapshot.rs`) | MIT OR Apache-2.0 |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
| `crates/nodes/src/atomic/text.rs` (`GLYPHS`) | Single-stroke vector font of the Text node (A–Z, a–z, 0–9, punctuation) | MaterialCraft contributors | Original, designed as stroke data in code | MIT OR Apache-2.0 |
-| `assets/sbs/` (every `.sbs` package, recursively), `examples/atomic_sample.sbs` | Procedural node, function graph and material library; atomic sample | ArtCraft Team and the MaterialCraft contributors | Original clean-room recreations of the professional node-based material workflow, created for MaterialCraft; authorship confirmed by the project maintainer | MIT OR Apache-2.0 |
+| `assets/sbs/` (every `.sbs` package, recursively) | Procedural node, function graph and material library | ArtCraft Team and the MaterialCraft contributors | Original work created for MaterialCraft. The project maintainer confirmed authorship of the collection. | MIT OR Apache-2.0 |
+| [examples/atomic_sample.sbs](examples/atomic_sample.sbs) | Atomic sample graph | ArtCraft Team and the MaterialCraft contributors | [Rust graph generator](crates/engine/src/atomic_sample.rs) and [SBS example writer](crates/engine/examples/atomic_sample.rs) | MIT OR Apache-2.0 |
| `assets/sbs/resources/bluenoise_256.png` | 256 × 256 grayscale blue noise, contributor-supplied PNG | Christoph Peters | [Moments in Graphics](https://momentsingraphics.de/BlueNoise.html); contributor-supplied provenance | CC0-1.0 ([license](assets/sbs/resources/LICENSE_BLUE_NOISE.txt)) |
| `assets/sbs/resources/bluenoise_256_c.exr` | 256 × 256 color blue noise, contributor-supplied EXR conversion | Christoph Peters | [Moments in Graphics](https://momentsingraphics.de/BlueNoise.html); contributor-supplied provenance | CC0-1.0 ([license](assets/sbs/resources/LICENSE_BLUE_NOISE.txt)) |
| `assets/sbs/resources/shuf4_64_32.exr` | 64 × 32 sampling lookup, contributor-supplied EXR | Lukas Hosek and Alexander Wilkie | [Skylight Modelling](https://cgg.mff.cuni.cz/projects/SkylightModelling/); contributor-supplied provenance | BSD-3-Clause ([license](assets/sbs/resources/LICENSE_HOSEK_WILKIE.txt)) |
diff --git a/Cargo.lock b/Cargo.lock
index 73a1c441..9cb124cf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3703,6 +3703,7 @@ dependencies = [
"craft-image-codecs",
"craft-mcmat",
"craft-mesh",
+ "craft-mime",
"craft-sbs",
"craft-svg",
"craft-texture",
@@ -3738,9 +3739,16 @@ dependencies = [
name = "materialcraft-nodes"
version = "0.4.1"
dependencies = [
+ "craft-font-catalog",
"craft-texture",
+ "half",
+ "harfrust 0.13.3",
"materialcraft-core",
"rayon",
+ "read-fonts 0.43.3",
+ "serde_json",
+ "unicode-bidi",
+ "vello_common",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index c4934bae..92921ee8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -66,7 +66,8 @@ materialcraft-ui-egui = { path = "crates/ui-egui" }
# external
thiserror = "2"
serde = { version = "1", features = ["derive"] }
-serde_json = "1"
+# Preserve decimal parameter values before converting them to the graph's storage type.
+serde_json = { version = "1", features = ["float_roundtrip"] }
sha2 = "0.10" # MIT OR Apache-2.0; stable content keys for persistent previews.
glam = { version = "0.30", features = ["serde", "bytemuck"] }
rayon = "1"
@@ -100,6 +101,11 @@ craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "d7010
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" }
+craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", default-features = false }
+harfrust = "0.13"
+read-fonts = { version = "0.43", default-features = false }
+unicode-bidi = "0.3.18"
+vello_common = { version = "0.2", default-features = false, features = ["std"] }
# Keyboard bindings (chords, dispatch and display text): storytold/craft-libs, MIT OR Apache-2.0
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", features = ["egui"] }
# Native dialogs that do not block the event loop: storytold/craft-libs, MIT OR Apache-2.0
diff --git a/ROADMAP.md b/ROADMAP.md
index 3fb8c5d6..11f45272 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,14 @@
# MaterialCraft roadmap
-**Current focus (2026-11-16):** node behavior, regression coverage and interoperable save/load.
+**Current focus (2026-11-28):** ship the measured root-graph improvements and validated save/load fixes; carry the remaining parity work into the next release.
+
+The root inventory records **494 exact cases out of 546 measured roots**, not complete
+numerical compatibility. The other 52 remain deferred: [reference variability and remaining
+root differences (#336)](https://github.com/storytold/materialcraft/issues/336) and
+[two older linked-dependency cases (#337)](https://github.com/storytold/materialcraft/issues/337).
+[Review edge cases and older-document rendering compatibility (#338)](https://github.com/storytold/materialcraft/issues/338)
+also need investigation. Corrected SBS conventions can change renders of documents authored
+against earlier MaterialCraft behavior; keep original files when comparing versions.
The old Rust procedural library has been removed. The main catalog has 29 entries: 25 native
primitives and four graph input/output items. Functions have 85 operations; pattern graphs have
diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs
index 1d70ccd1..94cbc45a 100644
--- a/assets/sbs/functions.sbs
+++ b/assets/sbs/functions.sbs
@@ -1 +1 @@
-
+
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index bbf540f2..f30e6a14 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -303,7 +303,7 @@ impl Headless {
let (w, h) = (options.width.unwrap_or(image.width()).clamp(16, maximum_side), options.height.unwrap_or(image.height()).clamp(16, maximum_side));
let image = image.resize(w, h, true);
- Ok((w, h, image.to_rgba8_display()))
+ Ok((w, h, materialcraft_engine::graph_pixels::rgba8(&image, self.session.view2d.srgb)))
}
fn render_3d(&mut self, o: &RenderOptions, max: u32) -> (u32, u32, Vec) {
diff --git a/crates/automation/tests/view_settings.rs b/crates/automation/tests/view_settings.rs
index 404e7665..c1202d7e 100644
--- a/crates/automation/tests/view_settings.rs
+++ b/crates/automation/tests/view_settings.rs
@@ -2,6 +2,22 @@ use materialcraft_automation::headless::{Filesystem, Headless, RenderOptions};
use materialcraft_engine::new_session;
use serde_json::json;
+#[test]
+fn headless_graph_previews_use_the_selected_display_encoding() {
+ let mut headless = Headless::new(new_session(), Filesystem::Denied);
+ headless.session.preview_size = Some(16);
+ let source = headless.command_run("graph.node.add", json!({"def": "uniform", "params": {"color": [0.2, 0.4, 0.8, 1.0]}})).unwrap();
+ headless.command_run("view.2d", json!({"node": source["id"]})).unwrap();
+ let options = RenderOptions { view: Some("2d".into()), width: Some(16), height: Some(16), ..Default::default() };
+ for (srgb, expected) in [(true, [51, 102, 204, 255]), (false, [124, 170, 231, 255])] {
+ headless.command_run("view.2d", json!({"srgb": srgb})).unwrap();
+ let png = headless.render_png(&options).unwrap();
+ let image = image::load_from_memory(&png.png).unwrap().to_rgba8();
+ assert_eq!(image.dimensions(), (16, 16));
+ assert!(image.pixels().all(|pixel| pixel.0 == expected), "{srgb}: {:?}", image.get_pixel(0, 0));
+ }
+}
+
#[test]
fn rejected_view_command_preserves_the_rendered_scene() {
let mut h = Headless::new(new_session(), Filesystem::Denied);
diff --git a/crates/core/src/base_parameter.rs b/crates/core/src/base_parameter.rs
index cbef563c..129ff01f 100644
--- a/crates/core/src/base_parameter.rs
+++ b/crates/core/src/base_parameter.rs
@@ -84,8 +84,8 @@ impl BaseParameter {
};
}
(Self::PixelSize, Value::Float2(size)) => {
- if size.iter().any(|component| !component.is_finite() || *component <= 0.0 || *component > 8192.0) {
- return Err("Pixel size components must be finite and between 0 and 8192, excluding zero".into());
+ if size.iter().any(|component| !component.is_finite() || component.abs() > 8192.0) {
+ return Err("Pixel size components must be finite and between -8192 and 8192".into());
}
base.pixel_size = *size;
diff --git a/crates/core/src/curve.rs b/crates/core/src/curve.rs
index 73e14e9c..dd4378ba 100644
--- a/crates/core/src/curve.rs
+++ b/crates/core/src/curve.rs
@@ -71,8 +71,8 @@ impl Curve {
}
}
- let left_handle = left.right.unwrap_or([left.x + span / 3.0, left.y + slopes[0] * span / 3.0]);
- let right_handle = right.left.unwrap_or([right.x - span / 3.0, right.y - slopes[1] * span / 3.0]);
+ let left_handle = if left.right_broken { [left.x, left.y] } else { left.right.unwrap_or([left.x + span / 3.0, left.y + slopes[0] * span / 3.0]) };
+ let right_handle = if right.left_broken { [right.x, right.y] } else { right.left.unwrap_or([right.x - span / 3.0, right.y - slopes[1] * span / 3.0]) };
Some([[left.x, left.y], left_handle, right_handle, [right.x, right.y]])
}
}
diff --git a/crates/core/src/curve_point.rs b/crates/core/src/curve_point.rs
index e9d53f9e..caedf10f 100644
--- a/crates/core/src/curve_point.rs
+++ b/crates/core/src/curve_point.rs
@@ -9,10 +9,17 @@ pub struct CurvePoint {
pub left: Option<[f32; 2]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub right: Option<[f32; 2]>,
+ /// A broken handle retains its authored position and contributes no tangent.
+ #[serde(default)]
+ pub left_broken: bool,
+ #[serde(default)]
+ pub right_broken: bool,
+ #[serde(default)]
+ pub locked: bool,
}
impl CurvePoint {
pub fn new(x: f32, y: f32) -> Self {
- Self { x, y, left: None, right: None }
+ Self { x, y, left: None, right: None, left_broken: false, right_broken: false, locked: false }
}
}
diff --git a/crates/core/src/exposed_parameter.rs b/crates/core/src/exposed_parameter.rs
index d8320b4d..08ea49d9 100644
--- a/crates/core/src/exposed_parameter.rs
+++ b/crates/core/src/exposed_parameter.rs
@@ -12,6 +12,9 @@ pub struct ExposedParameter {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub group: String,
pub default: Value,
+ /// A standalone SBS function can explicitly declare a wireable argument.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub connectable: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs
index 61a6a23a..ea39707f 100644
--- a/crates/core/src/graph.rs
+++ b/crates/core/src/graph.rs
@@ -28,10 +28,25 @@ pub struct Graph {
pub pins: Vec,
/// log2 of the graph ("parent") size per axis
pub size: [u32; 2],
+ /// An authored absolute output size, in log2 texels, independent of the default parent size.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub absolute_output_size: Option<[i32; 2]>,
+ /// The signed graph output size offset from its caller.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub relative_output_size: Option,
+ /// Authored function supplying the two output size exponents or offsets.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub output_size_function: Option,
#[serde(default)]
pub format: OutputFormat,
#[serde(default)]
pub seed: i32,
+ /// Whether a nested graph starts from its own seed or adds to its instance seed.
+ #[serde(default)]
+ pub seed_mode: crate::ParameterInheritance,
+ /// An authored expression for the graph seed offset.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub seed_function: Option,
#[serde(default)]
pub pixel_ratio: i32,
#[serde(default)]
@@ -54,17 +69,25 @@ pub struct Graph {
pub input_images: BTreeMap,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub input_images_linear: BTreeSet,
+ /// SBS image bindings without an explicit preview interpretation use the resource's file transfer.
+ #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
+ pub input_images_from_file: BTreeSet,
#[serde(default)]
pub attributes: Attributes,
/// The id the next node, frame, comment or pin gets
pub next_id: u64,
}
-/// Smallest and largest graph size, as log2 (16 px .. 8192 px)
-pub const MIN_SIZE_LOG2: u32 = 4;
+/// Bounds for each default parent dimension, as log2 (1 px .. 8192 px)
+pub const MIN_SIZE_LOG2: u32 = 0;
pub const MAX_SIZE_LOG2: u32 = 13;
impl Graph {
+ /// Round a requested parent dimension up to a supported power of two.
+ pub fn parent_size_log2(pixels: u64) -> u32 {
+ pixels.clamp(1 << MIN_SIZE_LOG2, 1 << MAX_SIZE_LOG2).next_power_of_two().ilog2()
+ }
+
/// Display text never changes the identifier used by SBS references
pub fn display_name(&self) -> &str {
if self.attributes.label.is_empty() { &self.name } else { &self.attributes.label }
@@ -82,8 +105,13 @@ impl Graph {
comments: Vec::new(),
pins: Vec::new(),
size: [10, 10],
+ absolute_output_size: None,
+ relative_output_size: None,
+ output_size_function: None,
format: OutputFormat::U16,
seed: 0,
+ seed_mode: crate::ParameterInheritance::default(),
+ seed_function: None,
pixel_ratio: 0,
pixel_ratio_mode: crate::ParameterInheritance::default(),
tiling: [true, true],
@@ -94,6 +122,7 @@ impl Graph {
presets: Vec::new(),
input_images: BTreeMap::new(),
input_images_linear: BTreeSet::new(),
+ input_images_from_file: BTreeSet::new(),
attributes: Attributes::default(),
next_id: 1,
}
@@ -105,7 +134,7 @@ impl Graph {
/// All editable Function canvases, including processor and parameter functions
pub fn functions(&self) -> impl Iterator- {
- self.function.iter().chain(
+ self.function.iter().chain(self.output_size_function.iter()).chain(self.seed_function.iter()).chain(
self.nodes
.iter()
.flat_map(|node| node.base.functions.values().chain(node.functions.values()).chain(node.params.values().flat_map(value_functions))),
@@ -113,7 +142,7 @@ impl Graph {
}
pub fn functions_mut(&mut self) -> impl Iterator
- {
- self.function.iter_mut().chain(
+ self.function.iter_mut().chain(self.output_size_function.iter_mut()).chain(self.seed_function.iter_mut()).chain(
self.nodes.iter_mut().flat_map(|node| {
node.base.functions.values_mut().chain(node.functions.values_mut()).chain(node.params.values_mut().flat_map(value_functions_mut))
}),
@@ -128,8 +157,12 @@ impl Graph {
}
pub fn instances_mut(&mut self) -> impl Iterator
- {
- self.function.iter_mut().flat_map(|function| function.nodes.iter_mut().filter_map(|node| node.instance.as_mut())).chain(self.nodes.iter_mut().flat_map(
- |node| {
+ self.function
+ .iter_mut()
+ .chain(self.output_size_function.iter_mut())
+ .chain(self.seed_function.iter_mut())
+ .flat_map(|function| function.nodes.iter_mut().filter_map(|node| node.instance.as_mut()))
+ .chain(self.nodes.iter_mut().flat_map(|node| {
node.instance.iter_mut().chain(
node.base
.functions
@@ -138,8 +171,7 @@ impl Graph {
.chain(node.params.values_mut().flat_map(value_functions_mut))
.flat_map(|function| function.nodes.iter_mut().filter_map(|node| node.instance.as_mut())),
)
- },
- ))
+ }))
}
pub fn kind(&self) -> GraphKind {
@@ -230,9 +262,44 @@ impl Graph {
self.inputs.get(id).or_else(|| self.exposed.iter().find(|e| e.id == id).map(|e| &e.default))
}
- /// Graph size in pixels
+ /// Default parent size used when the graph has no caller.
+ pub fn parent_size_px(&self) -> [u32; 2] {
+ self.size.map(|axis| 1 << axis.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2))
+ }
+
+ /// Literal graph size in pixels. Cooking also evaluates the output size function.
pub fn size_px(&self) -> [u32; 2] {
- [1 << self.size[0].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), 1 << self.size[1].clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2)]
+ self.resolved_output_size(None, None).0
+ }
+
+ /// Resolve this graph's output for the caller's parent size, including graph instances.
+ pub fn output_size_px(&self, parent: [u32; 2]) -> [u32; 2] {
+ self.resolved_output_size(Some((parent, [0; 2])), None).0
+ }
+
+ /// The SBS size setting before applying it to a particular caller.
+ pub fn output_size_setting(&self) -> (crate::SizeMode, [i32; 2]) {
+ use crate::{GraphSizeOffset, SizeMode};
+ match (self.absolute_output_size, self.relative_output_size) {
+ (Some(size), _) => (SizeMode::Absolute, size),
+ (_, Some(GraphSizeOffset::Parent(offset))) => (SizeMode::RelativeToParent, offset),
+ (_, Some(GraphSizeOffset::Input(offset))) => (SizeMode::RelativeToInput, offset),
+ _ => (SizeMode::RelativeToInput, [0; 2]),
+ }
+ }
+
+ /// Resolve both the allocated dimensions and the portion of the requested size below one texel.
+ pub fn resolved_output_size(&self, parent: Option<([u32; 2], [i32; 2])>, evaluated: Option<[i32; 2]>) -> ([u32; 2], [i32; 2]) {
+ let (mode, literal) = self.output_size_setting();
+ let size = evaluated.unwrap_or(literal);
+ if mode == crate::SizeMode::Absolute {
+ return (size.map(|side| 1 << side.clamp(0, MAX_SIZE_LOG2 as i32)), [0; 2]);
+ }
+ let (extent, underflow) = parent.unwrap_or_else(|| (self.parent_size_px(), [0; 2]));
+ if size == [0; 2] {
+ return (extent, underflow);
+ }
+ crate::offset_dimensions(extent, underflow, size)
}
}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index f9ac3175..79e56c93 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -79,9 +79,9 @@ pub use pattern_node::PatternNode;
pub use pattern_node_kind::PatternNodeKind;
pub use pin::Pin;
pub use preset::Preset;
-pub use resource::Resource;
+pub use resource::{PngRasterInfo, Resource, png_raster_info, png_sample_format};
pub use resource_bytes::ResourceBytes;
-pub use size_mode::SizeMode;
+pub use size_mode::{GraphSizeOffset, SizeMode, offset_dimensions};
pub use value::Value;
pub use value_type::ValueType;
diff --git a/crates/core/src/package.rs b/crates/core/src/package.rs
index 4ff287f5..548be4f0 100644
--- a/crates/core/src/package.rs
+++ b/crates/core/src/package.rs
@@ -7,7 +7,7 @@ pub const PACKAGE_EXT: &str = "sbs";
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Package {
pub name: String,
- /// Baseline version read from SBS. Unversioned packages use the current release on first write.
+ /// Original SBS format header. The writer chooses its schema revision for new packages.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format_version: Option,
pub graphs: Vec,
diff --git a/crates/core/src/pattern_graph.rs b/crates/core/src/pattern_graph.rs
index d1c47bce..06575976 100644
--- a/crates/core/src/pattern_graph.rs
+++ b/crates/core/src/pattern_graph.rs
@@ -46,6 +46,11 @@ impl PatternGraph {
}
pub fn validate(&self) -> Result<(), String> {
+ self.validated_depth().map(|_| ())
+ }
+
+ /// Validate every node and return the maximum quadrant depth connected to the root.
+ pub fn validated_depth(&self) -> Result {
if self.nodes.len() > 4096 {
return Err("pattern graph exceeds the 4096-node limit".into());
}
@@ -59,11 +64,11 @@ impl PatternGraph {
}
let mut active = BTreeSet::new();
- let mut finished = BTreeSet::new();
+ let mut depths = BTreeMap::::new();
for root in &self.nodes {
let mut pending = vec![(root.id, false)];
while let Some((id, visited)) = pending.pop() {
- if finished.contains(&id) {
+ if depths.contains_key(&id) {
continue;
}
@@ -73,7 +78,10 @@ impl PatternGraph {
}
if visited {
active.remove(&id);
- finished.insert(id);
+ // Children are complete. Only a quadrant subdivides the image on its way to a child.
+ let step = u32::from(node.kind == PatternNodeKind::Quadrant);
+ let depth = node.children.iter().flatten().filter_map(|child| depths.get(child)).max().map_or(0, |d| d + step);
+ depths.insert(id, depth);
continue;
}
if !active.insert(id) {
@@ -84,7 +92,7 @@ impl PatternGraph {
pending.extend(node.children.iter().rev().flatten().map(|child| (*child, false)));
}
}
- Ok(())
+ Ok(self.root.and_then(|id| depths.get(&id).copied()).unwrap_or(0))
}
}
diff --git a/crates/core/src/resource.rs b/crates/core/src/resource.rs
index 2c0a6aa9..1d7875a0 100644
--- a/crates/core/src/resource.rs
+++ b/crates/core/src/resource.rs
@@ -1,4 +1,4 @@
-use crate::ResourceBytes;
+use crate::{OutputFormat, ResourceBytes};
use serde::{Deserialize, Serialize};
/// An asset retained in memory until the package is saved: a bitmap or an SVG.
@@ -32,3 +32,28 @@ impl Resource {
fn default_folder() -> String {
"Resources".into()
}
+
+/// Original normalized channel precision of a grayscale or truecolor PNG resource.
+/// The decoded float values alone cannot distinguish a byte from the equivalent repeated-byte word.
+pub fn png_sample_format(bytes: &[u8]) -> Option {
+ png_raster_info(bytes).map(|info| info.format)
+}
+
+/// Raster properties declared in the header of a normalized grayscale or truecolor PNG.
+pub struct PngRasterInfo {
+ pub size: [u32; 2],
+ pub format: OutputFormat,
+ pub grayscale: bool,
+}
+
+pub fn png_raster_info(bytes: &[u8]) -> Option {
+ let header = bytes.strip_prefix(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR")?;
+ let format = match header.get(8..10)? {
+ [8, 0 | 2 | 4 | 6] => OutputFormat::U8,
+ [16, 0 | 2 | 4 | 6] => OutputFormat::U16,
+ _ => return None,
+ };
+ let width = u32::from_be_bytes(*header.first_chunk()?);
+ let height = u32::from_be_bytes(*header.get(4..)?.first_chunk()?);
+ Some(PngRasterInfo { size: [width, height], format, grayscale: matches!(header.get(9), Some(0 | 4)) })
+}
diff --git a/crates/core/src/size_mode.rs b/crates/core/src/size_mode.rs
index 792eb56c..408d1470 100644
--- a/crates/core/src/size_mode.rs
+++ b/crates/core/src/size_mode.rs
@@ -12,3 +12,23 @@ pub enum SizeMode {
/// `offset` is the absolute log2 size (e.g. 10 = 1024 px)
Absolute,
}
+
+/// The authored base for a relative graph output size and its signed offsets in octaves.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum GraphSizeOffset {
+ Input([i32; 2]),
+ Parent([i32; 2]),
+}
+
+/// Apply per-axis log2 offsets and carry requested exponents below a single texel to descendants.
+pub fn offset_dimensions(parent: [u32; 2], underflow: [i32; 2], offset: [i32; 2]) -> ([u32; 2], [i32; 2]) {
+ let shift: [i32; 2] = std::array::from_fn(|axis| underflow[axis].saturating_add(offset[axis].clamp(-12, 13)));
+
+ // Internal images may be one texel; the editor minimum would break size functions
+ let size = std::array::from_fn(|axis| (f64::from(parent[axis]) * 2f64.powi(shift[axis])).round().clamp(1.0, 8192.0) as u32);
+ let size_underflow =
+ std::array::from_fn(|axis| if parent[axis].is_power_of_two() { shift[axis].saturating_add(parent[axis].ilog2() as i32).min(0) } else { 0 });
+
+ (size, size_underflow)
+}
diff --git a/crates/core/src/value_tests.rs b/crates/core/src/value_tests.rs
index 0e655809..2eb5929e 100644
--- a/crates/core/src/value_tests.rs
+++ b/crates/core/src/value_tests.rs
@@ -28,6 +28,13 @@ fn coerce_from_json() {
assert_eq!(Value::Int(0).coerce_json(&serde_json::json!({"t": "text", "v": "x"})), None);
}
+#[test]
+fn decimal_parameter_text_preserves_a_float_midpoint() {
+ let input = serde_json::from_str("[0.37710319459438324, -0.37710319459438324]").unwrap();
+ let rounded = f32::from_bits(0x3ec1_13ac);
+ assert_eq!(Value::Float2([0.0; 2]).coerce_json(&input), Some(Value::Float2([rounded, -rounded])));
+}
+
#[test]
fn coerce_json_int_vectors_accept_floats() {
assert_eq!(Value::Int2([0; 2]).coerce_json(&serde_json::json!([3.0, 4.0])), Some(Value::Int2([3, 4])));
diff --git a/crates/engine/src/decoded_images.rs b/crates/engine/src/decoded_images.rs
index c4e6e018..3cb9d65e 100644
--- a/crates/engine/src/decoded_images.rs
+++ b/crates/engine/src/decoded_images.rs
@@ -1,13 +1,14 @@
use std::collections::{HashMap, HashSet};
use craft_texture::Image;
+use materialcraft_nodes::BitmapColorSpace;
const DEFAULT_LIMIT_BYTES: usize = 128 << 20;
const MAX_ENTRIES: usize = 128;
/// Decoded bitmaps are expendable: resources and active cooks own their source and output data.
pub(crate) struct DecodedImages {
- images: HashMap<(u64, bool), (Image, u64)>,
+ images: HashMap<(u64, BitmapColorSpace), (Image, u64)>,
bytes: usize,
limit: usize,
tick: u64,
@@ -24,7 +25,7 @@ impl DecodedImages {
Self { images: HashMap::new(), bytes: 0, limit, tick: 0 }
}
- pub fn get(&mut self, key: &(u64, bool)) -> Option {
+ pub fn get(&mut self, key: &(u64, BitmapColorSpace)) -> Option {
self.tick = self.tick.saturating_add(1);
self.images.get_mut(key).map(|(image, used)| {
*used = self.tick;
@@ -32,7 +33,7 @@ impl DecodedImages {
})
}
- pub fn insert(&mut self, key: (u64, bool), image: Image) {
+ pub fn insert(&mut self, key: (u64, BitmapColorSpace), image: Image) {
if let Some((old, _)) = self.images.remove(&key) {
self.bytes = self.bytes.saturating_sub(bytes(&old));
}
@@ -82,16 +83,17 @@ mod tests {
let mut cache = DecodedImages::new(128);
let image = Image::filled(4, 4, Kind::Gray, [0.5; 4]);
let weak = Arc::downgrade(image.shared_data());
- cache.insert((0, false), image);
+ cache.insert((0, BitmapColorSpace::Srgb), image);
for key in 1..1_000 {
- cache.insert((key, key % 2 == 0), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
+ let space = if key % 2 == 0 { BitmapColorSpace::Linear } else { BitmapColorSpace::Srgb };
+ cache.insert((key, space), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
assert!(cache.bytes <= 128);
assert!(cache.images.len() <= 2);
}
assert!(weak.upgrade().is_none());
- assert!(cache.get(&(999, false)).is_some());
+ assert!(cache.get(&(999, BitmapColorSpace::Srgb)).is_some());
cache.retain_resources(&HashSet::new());
@@ -103,21 +105,21 @@ mod tests {
fn large_images_bypass_the_cache_and_recent_reads_survive_eviction() {
let mut cache = DecodedImages::new(128);
for key in 0..2 {
- cache.insert((key, false), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
+ cache.insert((key, BitmapColorSpace::Srgb), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
}
- assert!(cache.get(&(0, false)).is_some());
+ assert!(cache.get(&(0, BitmapColorSpace::Srgb)).is_some());
- cache.insert((2, false), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
+ cache.insert((2, BitmapColorSpace::Srgb), Image::filled(4, 4, Kind::Gray, [0.5; 4]));
- assert!(cache.get(&(1, false)).is_none());
+ assert!(cache.get(&(1, BitmapColorSpace::Srgb)).is_none());
let large = Image::filled(16, 16, Kind::Gray, [0.5; 4]);
let weak = Arc::downgrade(large.shared_data());
- cache.insert((3, false), large);
+ cache.insert((3, BitmapColorSpace::Srgb), large);
assert!(weak.upgrade().is_none());
- assert!(cache.get(&(0, false)).is_some());
+ assert!(cache.get(&(0, BitmapColorSpace::Srgb)).is_some());
cache.clear();
diff --git a/crates/engine/src/export_size.rs b/crates/engine/src/export_size.rs
index 883d473e..5ca04629 100644
--- a/crates/engine/src/export_size.rs
+++ b/crates/engine/src/export_size.rs
@@ -9,14 +9,14 @@ pub enum ExportSize {
}
impl ExportSize {
- /// The graph's log2 size at this export size: pixels round down to powers of two from 16 to 8192
+ /// The graph's log2 size at this export size: pixels round down to powers of two from 1 to 8192
pub fn log2_size(self, graph_size: [u32; 2]) -> [u32; 2] {
match self {
ExportSize::LargerSide(pixels) => {
let target = log2_pixels(pixels);
let bounded = graph_size.map(|side| side.clamp(materialcraft_core::MIN_SIZE_LOG2, materialcraft_core::MAX_SIZE_LOG2));
let larger = bounded[0].max(bounded[1]);
- bounded.map(|side| (side + target).saturating_sub(larger).max(materialcraft_core::MIN_SIZE_LOG2))
+ bounded.map(|side| (side + target).saturating_sub(larger))
}
ExportSize::Exact(pixels) => pixels.map(log2_pixels),
}
diff --git a/crates/engine/src/exposed_input_commands.rs b/crates/engine/src/exposed_input_commands.rs
index f9bba423..194a9507 100644
--- a/crates/engine/src/exposed_input_commands.rs
+++ b/crates/engine/src/exposed_input_commands.rs
@@ -152,6 +152,7 @@ fn prepare_input(session: &Session, parameters: &J) -> Result<(ExposedParameter,
};
let input = ExposedParameter {
id: identifier.clone(),
+ connectable: false,
label: strp(parameters, "label").unwrap_or_else(|| descriptor.as_ref().map_or(identifier.as_str(), |descriptor| descriptor.label.as_str())).into(),
group: strp(parameters, "group").unwrap_or("").into(),
description: strp(parameters, "description")
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index d1fab72c..5af83b0b 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -3,7 +3,7 @@ pub use crate::linked_resource::reader as linked_files;
use serde_json::{Value as J, json};
-use materialcraft_core::{Package, Resource, ResourceBytes};
+use materialcraft_core::{Graph, Package, Resource, ResourceBytes};
use materialcraft_formats::{Depth, encode, output_name};
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_package, strp, u64p};
@@ -70,9 +70,9 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result {
} else {
TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1)
};
- let width = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192);
- let height = u64p(parameters, "height").unwrap_or(width).clamp(16, 8192);
- let [width_log2, height_log2] = [width, height].map(|side| 63 - side.leading_zeros());
+ let width = u64p(parameters, "size").unwrap_or(1024);
+ let height = u64p(parameters, "height").unwrap_or(width);
+ let [width_log2, height_log2] = [width, height].map(Graph::parent_size_log2);
let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_"));
let folder = strp(parameters, "folder").unwrap_or("");
let in_new_package = boolp(parameters, "newPackage").unwrap_or(false);
@@ -143,6 +143,7 @@ pub fn replace_package(session: &mut Session, package: Package, path: Option) ->
}
pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option, linked: &dyn Fn(&str) -> Option>) -> Result<()> {
- open_resolved(session, bytes, name, linked, crate::linked_files::load)
+ open_resolved(session, bytes, name, linked, Session::load_file_links)
}
/// Resolve every external graph and its assets through the caller's read capability.
pub fn open_bytes_scoped(session: &mut Session, bytes: &[u8], path: &str, read: &dyn Fn(&str) -> Option>) -> Result<()> {
let assets = |reference: &str| read(&crate::document_path::resolve(path, reference));
- open_resolved(session, bytes, Some(path.into()), &assets, |pkg| crate::linked_files::load_scoped(pkg, read))
+ open_resolved(session, bytes, Some(path.into()), &assets, |_, pkg| crate::linked_files::load_scoped(pkg, read))
}
fn open_resolved(
@@ -192,7 +193,7 @@ fn open_resolved(
bytes: &[u8],
name: Option,
linked: &dyn Fn(&str) -> Option>,
- load: impl FnOnce(&mut Package) -> Vec,
+ load: impl FnOnce(&mut Session, &mut Package) -> Vec,
) -> Result<()> {
let name = name.map(|path| crate::document_path::normalize(&path));
if let Some(name) = &name
@@ -213,10 +214,11 @@ fn open_resolved(
for (path, source) in &session.pkg.dependencies {
read.pkg.dependencies.entry(path.clone()).or_insert_with(|| source.clone());
}
- let link_warnings = load(&mut read.pkg);
- let path = if read.warnings.is_empty() { name } else { None };
+ let link_warnings = load(session, &mut read.pkg);
+ let (path, recovery_origin) = if read.warnings.is_empty() { (name, None) } else { (None, name) };
read.warnings.extend(link_warnings);
session.open_package(read.pkg, path)?;
+ session.recovery_origin = recovery_origin;
for warning in &read.warnings {
session.warn(warning.clone());
}
@@ -249,7 +251,8 @@ pub(crate) fn save_bytes_at(session: &Session, path: Option<&str>) -> Result) -> Package {
@@ -261,15 +264,92 @@ fn package_for_save(session: &Session, path: Option<&str>) -> Package {
}
}
+ let in_place = session.path.as_deref().is_some_and(|current| current == path || current == crate::document_path::normalize(path));
+ let mut packages = std::collections::BTreeMap::new();
for instance in package.graphs.iter_mut().flat_map(|graph| graph.instances_mut()) {
- if !instance.package.is_empty() {
- instance.package = crate::document_path::relative(path, &instance.package);
+ // Catalog links follow the selected library even when the caller is saved inside it.
+ if instance.package.is_empty() || (in_place && instance.package.starts_with("sbs://")) {
+ continue;
}
+ let source = std::mem::take(&mut instance.package);
+ let reference = packages
+ .entry(source)
+ .or_insert_with_key(|source| if in_place { crate::document_path::relative(path, source) } else { package_reference(session, path, source) });
+ instance.package.clone_from(reference);
}
}
package
}
+fn package_reference(_session: &Session, destination: &str, source: &str) -> String {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use materialcraft_formats::sbs::library;
+ use std::path::Path;
+
+ if Path::new(source).is_absolute()
+ && !library::contains_file(Path::new(destination))
+ && let Ok(root) = library::root().canonicalize()
+ && let Some(uri) = verified_library_reference(_session, &root, source)
+ {
+ return uri;
+ }
+ }
+ crate::document_path::relative(destination, source)
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn verified_library_reference(session: &Session, root: &std::path::Path, source: &str) -> Option {
+ use materialcraft_formats::sbs::library;
+ use std::{collections::BTreeMap, path::Path};
+
+ let uri = library::bundled_package_uri(root, Path::new(source))?;
+ let mut names = BTreeMap::from([(source.to_string(), uri.clone())]);
+ let mut pending = vec![source.to_string()];
+ while let Some(key) = pending.pop() {
+ let package = session.pkg.dependencies.get(&key)?;
+ if package.graphs.is_empty() || !package.resources.is_empty() {
+ return None;
+ }
+ let package_uri = names.get(&key)?;
+ let mut reference = match session.library.packages.get(package_uri) {
+ Some(known) => (**known).clone(),
+ None => {
+ let bytes = library::read(package_uri).ok()?;
+ let mut read = materialcraft_formats::sbs::read_sbs(&bytes, package_uri, &linked_files(package_uri)).ok()?;
+ crate::linked_files::normalize_references(&mut read.pkg, package_uri);
+ read.pkg
+ }
+ };
+
+ let mut normalized = (**package).clone();
+ for instance in normalized.graphs.iter_mut().flat_map(|graph| graph.instances_mut()).filter(|instance| !instance.package.is_empty()) {
+ if let Some(uri) = names.get(&instance.package) {
+ instance.package.clone_from(uri);
+ continue;
+ }
+ let path = if instance.package.starts_with("sbs://") {
+ root.join(library::relative_path(&instance.package).ok()?)
+ } else {
+ Path::new(&instance.package).to_path_buf()
+ };
+ let child = library::bundled_package_uri(root, &path)?;
+ let key = std::mem::replace(&mut instance.package, child.clone());
+ names.insert(key.clone(), child);
+ pending.push(key);
+ }
+
+ // Loaded calls carry resolved argument types and bodies. Compare both copies
+ // against the same interfaces so that authored edits remain distinguishable.
+ crate::linked_packages::interfaces(&mut reference, &session.library.packages);
+ crate::linked_packages::interfaces(&mut normalized, &session.library.packages);
+ if normalized.graphs != reference.graphs {
+ return None;
+ }
+ }
+ Some(uri)
+}
+
pub fn save_files_at(session: &Session, path: &str) -> Result {
let active_package = session.package(session.document_id)?;
let filename = std::path::Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or("package.sbs");
@@ -353,7 +433,7 @@ pub(crate) fn save_to_path(s: &mut Session, path: &str) -> Result {
let bytes = write_package_at(s, &path)?;
s.path = Some(path.clone());
- s.refresh_links();
+ s.refresh_saved_links(&path);
s.modified = false;
Ok(json!({"path": path, "bytes": bytes}))
}
diff --git a/crates/engine/src/function_variables.rs b/crates/engine/src/function_variables.rs
index f21989ad..07eba64f 100644
--- a/crates/engine/src/function_variables.rs
+++ b/crates/engine/src/function_variables.rs
@@ -8,10 +8,12 @@ use crate::{FunctionGraphTarget, FunctionVariable, Result, Session, commands::ba
fn variable_scope(target: &FunctionGraphTarget, session: &Session) -> FunctionScope {
match target {
FunctionGraphTarget::Pattern { .. } => FunctionScope::FxMap,
- FunctionGraphTarget::Parameter { node, parameter }
- if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "pixel_processor") =>
- {
- FunctionScope::PixelProcessor
+ FunctionGraphTarget::Parameter { node, parameter } if parameter == "function" => {
+ match session.graph().ok().and_then(|graph| graph.node(*node).ok()).map(|node| node.def.as_str()) {
+ Some("pixel_processor") => FunctionScope::PixelProcessor,
+ Some("value_processor") => FunctionScope::ValueProcessor,
+ _ => FunctionScope::Node,
+ }
}
_ => FunctionScope::Node,
}
diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs
index b6751f3a..8e7592d6 100644
--- a/crates/engine/src/graph_cmds.rs
+++ b/crates/engine/src/graph_cmds.rs
@@ -2,7 +2,7 @@
use serde_json::{Value as J, json};
-use materialcraft_core::{Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value};
+use materialcraft_core::{Graph, MAX_SIZE_LOG2, NodeId, OutputFormat, Value};
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_selection, i64p, ids_param, strp, u64p};
use crate::{Result, Session, cmd};
@@ -12,15 +12,16 @@ pub(crate) fn specs() -> Vec {
cmd!("graph.open", "Open graph", [], None, "{graph: index or name}", always, open),
cmd!("graph.delete", "Delete graph", [], None, "{graph?}", has_graph, delete),
cmd!("graph.duplicate", "Duplicate graph", [], None, "{graph?}", has_graph, duplicate),
- cmd!("graph.size", "Graph size", [], None, "{graph?, document?, width, height} in pixels (powers of two, 16..8192) or {log2: [w, h]}", always, size),
- cmd!("graph.seed", "Random seed", [], None, "{seed, graph?, document?}", always, |s, p| {
- let seed = i64p(p, "seed").ok_or_else(|| bad("graph.seed", "`seed` is required"))?.clamp(0, i32::MAX as i64) as i32;
- let target = crate::GraphTarget::resolve(s, p)?;
- target.edit_merged(s, &format!("graph.seed:{}:{}", target.document, target.graph), "Random seed", |package| {
- package.graph_mut(target.graph)?.seed = seed;
- Ok(J::Null)
- })
- }),
+ cmd!(
+ "graph.size",
+ "Graph size",
+ [],
+ None,
+ "{graph?, document?, width, height} in pixels (rounded up to powers of two, 1..8192) or {log2: [w, h]}",
+ always,
+ size
+ ),
+ cmd!("graph.seed", "Random seed", [], None, "{seed?, inheritance?: absolute|relativeToParent|relativeToInput, graph?, document?}", always, seed),
cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32, graph?, document?}", always, format),
cmd!(
"graph.cook",
@@ -73,6 +74,33 @@ pub(crate) fn graph_index(s: &Session, p: &J) -> Result {
}
}
+fn seed(session: &mut Session, parameters: &J) -> Result {
+ let command = "graph.seed";
+ let seed = parameters
+ .get("seed")
+ .map(|_| i64p(parameters, "seed").map(|n| n.clamp(0, i64::from(i32::MAX)) as i32).ok_or_else(|| bad(command, "expected an integer seed")))
+ .transpose()?;
+ let mode = parameters
+ .get("inheritance")
+ .map(|v| serde_json::from_value(v.clone()).map_err(|error| bad(command, format!("invalid inheritance: {error}"))))
+ .transpose()?;
+ if seed.is_none() && mode.is_none() {
+ return Err(bad(command, "a seed or inheritance mode is required"));
+ }
+ let target = crate::GraphTarget::resolve(session, parameters)?;
+ target.edit_merged(session, &format!("graph.seed:{}:{}", target.document, target.graph), "Random seed", |package| {
+ let graph = package.graph_mut(target.graph)?;
+ if let Some(seed) = seed {
+ graph.seed = seed;
+ graph.seed_function = None;
+ }
+ if let Some(mode) = mode {
+ graph.seed_mode = mode;
+ }
+ Ok(J::Null)
+ })
+}
+
fn open(s: &mut Session, p: &J) -> Result {
let i = graph_index(s, p)?;
s.graph = i;
@@ -120,15 +148,14 @@ fn duplicate(s: &mut Session, p: &J) -> Result {
fn size(s: &mut Session, p: &J) -> Result {
let target = crate::GraphTarget::resolve(s, p)?;
- let log = |px: u64| 63 - px.clamp(1, 1 << 20).leading_zeros();
let (w, h) = if let Some(a) = p.get("log2").and_then(J::as_array) {
- (a.first().and_then(J::as_u64).unwrap_or(10) as u32, a.get(1).and_then(J::as_u64).unwrap_or(10) as u32)
+ let exponent = |axis: usize| a.get(axis).and_then(J::as_u64).unwrap_or(10).min(u64::from(MAX_SIZE_LOG2)) as u32;
+ (exponent(0), exponent(1))
} else {
let w = u64p(p, "width").ok_or_else(|| bad("graph.size", "`width` is required"))?;
- (log(w), log(u64p(p, "height").unwrap_or(w)))
+ (Graph::parent_size_log2(w), Graph::parent_size_log2(u64p(p, "height").unwrap_or(w)))
};
- let (w, h) = (w.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2), h.clamp(MIN_SIZE_LOG2, MAX_SIZE_LOG2));
target.edit(s, "Graph size", |package| {
package.graph_mut(target.graph)?.size = [w, h];
Ok(json!({"width": 1u32 << w, "height": 1u32 << h}))
@@ -294,6 +321,7 @@ fn from_selection(s: &mut Session, p: &J) -> Result {
let mut sub = materialcraft_core::Graph::new(&name);
sub.size = src.size;
sub.seed = src.seed;
+ sub.format = OutputFormat::Inherit;
sub.next_id = src.next_id;
sub.nodes = src.nodes.iter().filter(|n| ids.contains(&n.id)).cloned().collect();
sub.connections = src.connections.iter().filter(|c| ids.contains(&c.from) && ids.contains(&c.to)).cloned().collect();
@@ -328,7 +356,11 @@ fn from_selection(s: &mut Session, p: &J) -> Result {
let g = s.graph_mut()?;
g.remove_nodes(&ids);
let inst = g.add_node("graph_instance", [rect[0], rect[1]]);
- g.node_mut(inst)?.params.insert("graph".into(), Value::Text(name.clone()));
+ let instance = g.node_mut(inst)?;
+ // The extracted graph keeps the source seed for a standalone preview. Cancel
+ // that offset here so later parent seed edits still reach its original nodes.
+ instance.base.seed = src.seed.wrapping_neg();
+ instance.params.insert("graph".into(), Value::Text(name.clone()));
for (from, port, ident) in inputs {
g.connect(from, &port, inst, &ident)?;
}
diff --git a/crates/engine/src/graph_pixels.rs b/crates/engine/src/graph_pixels.rs
new file mode 100644
index 00000000..a2f54c4b
--- /dev/null
+++ b/crates/engine/src/graph_pixels.rs
@@ -0,0 +1,29 @@
+//! Display levels of cooked graph images and node thumbnails.
+
+use crate::image::{Image, linear_to_srgb};
+
+/// Quantize a stored channel, including alpha, to its displayed byte.
+pub fn stored_byte(value: f32) -> u8 {
+ (value.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
+}
+
+/// Interpret a graph channel as sRGB or linear light before displaying it.
+pub fn display_byte(value: f32, srgb: bool) -> u8 {
+ stored_byte(if srgb { value } else { linear_to_srgb(value) })
+}
+
+/// Expand the stored graph pixels into display RGBA, preserving alpha.
+pub fn rgba8(image: &Image, srgb: bool) -> Vec {
+ let mut pixels = Vec::with_capacity(image.data().len() / image.channels() * 4);
+ if let Some(gray) = image.gray_data() {
+ for &value in gray {
+ let level = display_byte(value, srgb);
+ pixels.extend_from_slice(&[level, level, level, 255]);
+ }
+ } else {
+ for &[r, g, b, a] in image.data().as_chunks::<4>().0 {
+ pixels.extend_from_slice(&[display_byte(r, srgb), display_byte(g, srgb), display_byte(b, srgb), stored_byte(a)]);
+ }
+ }
+ pixels
+}
diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs
index 12bcf3a7..ba2ae4d4 100644
--- a/crates/engine/src/inspect.rs
+++ b/crates/engine/src/inspect.rs
@@ -19,12 +19,14 @@ pub fn session(session: &Session, requested_graph: Option) -> J {
"size": graph.size_px(),
"format": graph.format,
"seed": graph.seed,
+ "seedMode": graph.seed_mode,
"attributes": graph.attributes,
"exposed": graph.exposed,
"presets": graph.presets,
"inputs": graph.inputs,
"inputImages": graph.input_images,
"inputImagesLinear": graph.input_images_linear,
+ "inputImagesFromFile": graph.input_images_from_file,
"nodes": graph.nodes.iter().map(|node| {
let entry = cooked.and_then(|cooked| cooked.nodes.get(&node.id));
let (inputs, outputs) = materialcraft_eval::ports(&session.pkg, graph, node);
@@ -59,6 +61,21 @@ pub fn session(session: &Session, requested_graph: Option) -> J {
"pins": graph.pins,
});
result["physicalSize"] = json!(graph.physical_size);
+ if let Some(function) = &graph.output_size_function {
+ result["outputSizeFunction"] = json!(function);
+ match materialcraft_eval::graph_output_size(graph, session.environment) {
+ Ok(size) => result["size"] = json!(size),
+ Err(error) => result["sizeError"] = json!(error),
+ }
+ }
+ if graph.absolute_output_size.is_some() || graph.relative_output_size.is_some() || graph.output_size_function.is_some() {
+ let (mode, value) = graph.output_size_setting();
+ result["outputSizeMode"] = json!(mode);
+ result["outputSizeValue"] = json!(value);
+ }
+ if let Some(function) = &graph.seed_function {
+ result["seedFunction"] = json!(function);
+ }
result["pixelRatio"] = json!(graph.pixel_ratio);
result["pixelRatioMode"] = json!(graph.pixel_ratio_mode);
result["tiling"] = json!(graph.tiling);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 5663974b..e9265fc2 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -69,6 +69,7 @@ pub use history_prefs::HistoryPrefs;
pub use library_cache_prefs::LibraryCachePrefs;
pub mod graph_edit;
pub mod graph_grid;
+pub mod graph_pixels;
pub mod inspect;
pub mod material_bake;
pub mod material_cmds;
diff --git a/crates/engine/src/linked_files.rs b/crates/engine/src/linked_files.rs
index 957e927b..61d5a536 100644
--- a/crates/engine/src/linked_files.rs
+++ b/crates/engine/src/linked_files.rs
@@ -1,5 +1,6 @@
use crate::document_path;
use materialcraft_core::Package;
+use std::{collections::BTreeSet, sync::Arc};
pub(crate) fn normalize_references(package: &mut Package, path: &str) {
for resource in &mut package.resources {
@@ -16,6 +17,60 @@ pub(crate) fn normalize_references(package: &mut Package, path: &str) {
}
impl crate::Session {
+ pub(crate) fn load_file_links(&mut self, package: &mut Package) -> Vec {
+ for (path, source) in &self.pkg.dependencies {
+ package.dependencies.entry(path.clone()).or_insert_with(|| source.clone());
+ }
+ let pending = references(package);
+ self.load_sources(package, pending)
+ }
+
+ fn load_sources(&mut self, package: &mut Package, pending: Vec) -> Vec {
+ read_references(package, pending, |uri, source| {
+ // Only aliases actually read from the catalog are owned by it. A caller can supply its own snapshot.
+ self.library_sources.insert(uri.to_owned(), Arc::clone(source));
+ })
+ }
+
+ #[cfg(not(target_arch = "wasm32"))]
+ pub(crate) fn refresh_saved_links(&mut self, path: &str) {
+ use materialcraft_formats::sbs::library;
+ use std::path::Path;
+
+ let file = Path::new(path);
+ let mut changed = BTreeSet::new();
+ if let Ok(root) = library::root().canonicalize()
+ && file.starts_with(&root)
+ {
+ // The saved path is canonical. The same file may also be reached through a library symlink.
+ let aliases: Vec<_> = self
+ .library_sources
+ .iter()
+ .filter_map(|(uri, owned)| {
+ let relative = library::relative_path(uri).ok()?;
+ (self.linked_sources.get(uri).is_some_and(|source| Arc::ptr_eq(source, owned))
+ && root.join(relative).canonicalize().ok()?.as_path() == file)
+ .then(|| uri.clone())
+ })
+ .collect();
+ if !aliases.is_empty() {
+ let mut registry = Package { dependencies: self.linked_sources.clone(), ..Default::default() };
+ for uri in &aliases {
+ registry.dependencies.remove(uri);
+ }
+ // Read the saved bytes in each alias's own directory so nested links and resources keep their base.
+ for warning in self.load_sources(&mut registry, aliases.clone()) {
+ self.warn(warning);
+ }
+ changed.extend(
+ aliases.into_iter().filter(|uri| registry.dependencies.get(uri).is_some_and(|source| self.linked_sources.get(uri) != Some(source))),
+ );
+ self.linked_sources.extend(registry.dependencies);
+ }
+ }
+ self.refresh_links_from(changed);
+ }
+
pub(crate) fn discard_source_changes(&mut self, path: &str) {
self.linked_sources.remove(path);
self.pkg.dependencies.remove(path);
@@ -30,21 +85,18 @@ impl crate::Session {
// Include inactive dependents so closing a source also refreshes their references
package.graphs.extend(self.documents.values().flat_map(|document| document.pkg.graphs.iter().cloned()));
package.dependencies = self.linked_sources.clone();
- for warning in load(&mut package) {
+ let pending = references(&package);
+ for warning in self.load_sources(&mut package, pending) {
self.warn(warning);
}
self.linked_sources.extend(package.dependencies);
}
- self.refresh_links_from(std::collections::BTreeSet::from([path.to_string()]));
+ self.refresh_links_from(BTreeSet::from([path.to_string()]));
}
}
-pub(crate) fn load(package: &mut Package) -> Vec {
- load_references(package, references(package))
-}
-
fn references(package: &Package) -> Vec {
package.graphs.iter().flat_map(|graph| graph.instances()).filter(|instance| !instance.package.is_empty()).map(|instance| instance.package.clone()).collect()
}
@@ -81,9 +133,20 @@ fn load_file(path: &str) -> Result
const MAX_DEPENDENCY_READS: usize = 4096;
-fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str) -> Result) -> Vec {
- use std::{collections::BTreeSet, sync::Arc};
+fn resolve(package: &mut Package, pending: Vec, read: &dyn Fn(&str) -> Result) -> Vec {
+ resolve_with_catalog(package, pending, read, |_, _| {})
+}
+fn read_references(package: &mut Package, pending: Vec, catalog_read: impl FnMut(&str, &Arc)) -> Vec {
+ resolve_with_catalog(package, pending, &load_file, catalog_read)
+}
+
+fn resolve_with_catalog(
+ package: &mut Package,
+ mut pending: Vec,
+ read: &dyn Fn(&str) -> Result,
+ mut catalog_read: impl FnMut(&str, &Arc),
+) -> Vec {
let mut visited = BTreeSet::new();
let mut warnings = Vec::new();
let mut read_attempts = 0;
@@ -112,7 +175,11 @@ fn resolve(package: &mut Package, mut pending: Vec, read: &dyn Fn(&str)
package.dependencies.entry(name.clone()).or_insert_with(|| dependency.clone());
}
pending.extend(references(&source));
- package.dependencies.insert(path, Arc::new(source));
+ let source = Arc::new(source);
+ if path.starts_with("sbs://") {
+ catalog_read(&path, &source);
+ }
+ package.dependencies.insert(path, source);
}
Err(error) => warnings.push(format!("Could not resolve {path}: {error}")),
}
diff --git a/crates/engine/src/linked_packages.rs b/crates/engine/src/linked_packages.rs
index b0212c7b..bf0c4700 100644
--- a/crates/engine/src/linked_packages.rs
+++ b/crates/engine/src/linked_packages.rs
@@ -29,7 +29,7 @@ fn reaches(package: &Package, changed: &BTreeSet, sources: &BTreeMap>) -> bool {
+pub(crate) fn interfaces(package: &mut Package, sources: &BTreeMap>) -> bool {
let updates: Vec<_> = package
.graphs
.iter()
diff --git a/crates/engine/src/material_cmds.rs b/crates/engine/src/material_cmds.rs
index ec031d66..a28383e3 100644
--- a/crates/engine/src/material_cmds.rs
+++ b/crates/engine/src/material_cmds.rs
@@ -31,7 +31,7 @@ pub(crate) fn specs() -> Vec {
"Set input preview image",
[],
None,
- "{identifier, resource? | path?, linear?} shows a bitmap resource (or an image file, embedded) on the graph's input node `identifier`, e.g. a mesh map baked in TextureCraft",
+ "{identifier, resource? | path?, linear?} shows a bitmap on the graph's input node using its file color interpretation. Set linear to true for data or false for sRGB",
has_graph,
bind
),
@@ -136,13 +136,18 @@ fn bind(s: &mut Session, p: &J) -> Result {
Some((name, bytes)) => crate::file_cmds::push_resource(&mut s.pkg, &name, bytes, Some(&id)),
None => strp(p, "resource").unwrap_or_default().to_string(),
};
- let linear = p.get("linear").and_then(J::as_bool).unwrap_or(false);
let g = s.graph_mut()?;
g.input_images.insert(id.clone(), res.clone());
- if linear {
- g.input_images_linear.insert(id.clone());
- } else {
- g.input_images_linear.remove(&id);
+ g.input_images_linear.remove(&id);
+ g.input_images_from_file.remove(&id);
+ match p.get("linear") {
+ None => {
+ g.input_images_from_file.insert(id.clone());
+ }
+ Some(J::Bool(true)) => {
+ g.input_images_linear.insert(id.clone());
+ }
+ _ => {}
}
Ok(json!({"identifier": id, "resource": res}))
})
@@ -164,8 +169,10 @@ fn read_image_file(cmd: &str, _: &str) -> Result<(String, Vec)> {
fn unbind(s: &mut Session, p: &J) -> Result {
let id = strp(p, "identifier").ok_or_else(|| bad("graph.input.unbind", "`identifier` is required"))?.to_string();
s.edit("Clear input preview image", |s| {
- s.graph_mut()?.input_images_linear.remove(&id);
- Ok(J::Bool(s.graph_mut()?.input_images.remove(&id).is_some()))
+ let graph = s.graph_mut()?;
+ graph.input_images_linear.remove(&id);
+ graph.input_images_from_file.remove(&id);
+ Ok(J::Bool(graph.input_images.remove(&id).is_some()))
})
}
diff --git a/crates/engine/src/material_cmds.test.rs b/crates/engine/src/material_cmds.test.rs
index 5f27fc15..455f4900 100644
--- a/crates/engine/src/material_cmds.test.rs
+++ b/crates/engine/src/material_cmds.test.rs
@@ -435,6 +435,55 @@ fn published_disabled_and_typed_instance_cooks_match_source() {
assert!((restored[0] - 0.2).abs() < 0.01, "disabled levels must preserve its input: {restored:?}");
}
+#[test]
+fn rebinding_the_same_file_preserves_its_authored_color_interpretation() {
+ let mut session = fixture();
+ let bytes = encode(&Image::filled(16, 16, Kind::Color, [0.5, 0.5, 0.5, 1.0]), "png", Depth::U8, true).unwrap();
+ session.pkg.resources.push(Resource::new("bound_input", "input.png", ResourceBytes::new(bytes.clone())));
+ let graph = session.graph_mut().unwrap();
+ graph.input_images.insert("curvature".into(), "bound_input".into());
+ graph.input_images_from_file.insert("curvature".into());
+ let output = graph.nodes.iter().find(|node| node.def == "output" && materialcraft_eval::identifier(node) == "mesh").unwrap().id;
+ let original = MaterialOptions::default().cook(&session, session.graph, None, Some(16)).unwrap();
+ let options = MaterialOptions::from_params(session.graph().unwrap(), &json!({"inputs":{"curvature":"replacement.png"}}), |_| Ok(bytes.clone())).unwrap();
+ let rebound = options.cook(&session, session.graph, None, Some(16)).unwrap();
+ let expected = original.image(output, 0).unwrap();
+ assert!(expected.get(0, 0, false)[0] > 0.4, "the authored file is linear");
+ assert_eq!(rebound.image(output, 0).unwrap().data(), expected.data());
+}
+
+#[test]
+fn material_resize_uses_overridden_size_expression_without_editing_the_document() {
+ use materialcraft_core::{ExposedParameter, FunctionGraph, ValueType};
+
+ let mut session = fixture();
+ let graph = session.graph_mut().unwrap();
+ graph.exposed.push(ExposedParameter {
+ id: "axes".into(),
+ label: "Axes".into(),
+ default: Value::Int2([4, 5]),
+ connectable: false,
+ min: 0.0,
+ max: 13.0,
+ clamp: false,
+ step: None,
+ editor: None,
+ description: String::new(),
+ group: String::new(),
+ options: Vec::new(),
+ });
+ graph.absolute_output_size = Some([4, 5]);
+ graph.output_size_function = Some(FunctionGraph::input("axes", ValueType::Integer2));
+ let before = session.pkg.clone();
+ let options =
+ MaterialOptions { size: Some(crate::ExportSize::LargerSide(64)), values: [("axes".into(), Value::Int2([6, 4]))].into(), ..Default::default() };
+ let cooked = options.cook(&session, session.graph, None, None).unwrap();
+ let output = session.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap();
+ let image = cooked.image(output.id, 0).unwrap();
+ assert_eq!((image.width(), image.height()), (64, 16), "resize must preserve the overridden aspect ratio");
+ assert_eq!(session.pkg, before);
+}
+
#[test]
fn material_options_ignore_stale_presets_but_validate_explicit_values() {
let mut session = fixture();
diff --git a/crates/engine/src/material_options.rs b/crates/engine/src/material_options.rs
index 1b3d8c4c..896121df 100644
--- a/crates/engine/src/material_options.rs
+++ b/crates/engine/src/material_options.rs
@@ -1,6 +1,7 @@
use craft_texture::Image;
-use materialcraft_core::{BaseParameter, Graph, SizeMode, Value};
+use materialcraft_core::{BaseParameter, Graph, OutputFormat, SizeMode, Value};
use materialcraft_eval::{Cooked, Options};
+use materialcraft_nodes::BitmapColorSpace;
use serde_json::Value as J;
use std::{borrow::Cow, collections::BTreeMap};
@@ -13,6 +14,8 @@ pub struct MaterialOptions {
pub size: Option,
pub values: BTreeMap,
pub inputs: BTreeMap,
+ /// Known sample depth of each bound file before decoding to linear floats.
+ pub input_formats: BTreeMap,
}
impl MaterialOptions {
@@ -46,14 +49,26 @@ impl MaterialOptions {
let mut remaining = MAX_DECODED_INPUT_BYTES;
for (id, path) in value.as_object().ok_or_else(|| invalid("inputs must map image identifiers to file paths".into()))? {
let input = declared.iter().find(|input| input.identifier == *id).ok_or_else(|| invalid(format!("unknown image input `{id}`")))?;
- let linear = if graph.input_images.contains_key(id) {
- graph.input_images_linear.contains(id)
+ let space = if graph.input_images.contains_key(id) {
+ if graph.input_images_from_file.contains(id) {
+ BitmapColorSpace::FromFile
+ } else if graph.input_images_linear.contains(id) {
+ BitmapColorSpace::Linear
+ } else {
+ BitmapColorSpace::Srgb
+ }
} else {
let usage = if input.usage == "any" { id } else { &input.usage };
- !materialcraft_formats::material::srgb_usage(usage)
+ if materialcraft_formats::material::srgb_usage(usage) { BitmapColorSpace::Srgb } else { BitmapColorSpace::Linear }
};
let path = path.as_str().ok_or_else(|| invalid(format!("inputs.{id} must be an image path")))?;
- let image = materialcraft_formats::decode(&read(path)?, linear)?;
+ let bytes = read(path)?;
+ let image = materialcraft_formats::decode_with_color_space(&bytes, space)?;
+ if image.integer_sampling()
+ && let Some(format) = materialcraft_core::png_sample_format(&bytes)
+ {
+ options.input_formats.insert(id.clone(), format);
+ }
remaining = remaining.checked_sub(std::mem::size_of_val(image.data())).ok_or_else(|| invalid("decoded image inputs exceed 1 GiB".into()))?;
options.inputs.insert(id.clone(), image);
}
@@ -74,7 +89,18 @@ impl MaterialOptions {
let mut package = Cow::Borrowed(&session.pkg);
if let Some(size) = self.size {
let graph = package.to_mut().graph_mut(index)?;
- graph.size = size.log2_size(graph.size);
+ let basis = match size {
+ ExportSize::LargerSide(_) => {
+ // Size expressions must see the same exposed values as the export cook.
+ graph.inputs.extend(self.values.clone());
+ materialcraft_eval::graph_output_size(graph, session.environment).map_err(|error| bad("material.cook", error))?.map(u32::ilog2)
+ }
+ ExportSize::Exact(_) => graph.size,
+ };
+ graph.size = size.log2_size(basis);
+ graph.output_size_function = None;
+ graph.absolute_output_size = None;
+ graph.relative_output_size = None;
// Fixed-size generators keep their native detail while final output bridges resample to the requested size
for output in graph.nodes.iter_mut().filter(|node| node.def == "output") {
@@ -90,6 +116,7 @@ impl MaterialOptions {
options.max_size = max_size;
options.only = Some(roots);
options.inputs.clone_from(&self.inputs);
+ options.bitmap_formats.clone_from(&self.input_formats);
options.overrides.clone_from(&self.values);
let cooked = materialcraft_eval::cook(&package, index, &options, &session.cache);
diff --git a/crates/engine/src/open_document.rs b/crates/engine/src/open_document.rs
index 868ca824..db28fcef 100644
--- a/crates/engine/src/open_document.rs
+++ b/crates/engine/src/open_document.rs
@@ -6,6 +6,7 @@ pub struct OpenDocument {
pub id: u64,
pub pkg: Package,
pub path: Option,
+ recovery_origin: Option,
pub graph: usize,
pub modified: bool,
selection: Vec,
@@ -90,6 +91,7 @@ impl OpenDocument {
material_preview: if show_outputs { MaterialPreview::for_graph(&pkg, 0) } else { MaterialPreview::default() },
pkg,
path,
+ recovery_origin: None,
graph: 0,
modified: false,
selection: Vec::new(),
@@ -115,6 +117,7 @@ impl OpenDocument {
exchange!(
pkg,
path,
+ recovery_origin,
graph,
modified,
selection,
diff --git a/crates/engine/src/package_file_commands.rs b/crates/engine/src/package_file_commands.rs
index 39e92dd3..e7323288 100644
--- a/crates/engine/src/package_file_commands.rs
+++ b/crates/engine/src/package_file_commands.rs
@@ -36,11 +36,8 @@ fn reload(session: &mut Session, parameters: &Value) -> Result {
let bytes = read_package(&path)?;
let linked = crate::file_cmds::linked_files(&path);
let mut read = crate::file_cmds::read_package_bytes(&bytes, &path, &linked)?;
- for (path, source) in &session.pkg.dependencies {
- read.pkg.dependencies.entry(path.clone()).or_insert_with(|| source.clone());
- }
let safe_path = read.warnings.is_empty().then_some(path.clone());
- read.warnings.extend(crate::linked_files::load(&mut read.pkg));
+ read.warnings.extend(session.load_file_links(&mut read.pkg));
crate::file_cmds::replace_package(session, read.pkg, safe_path);
session.load_warnings = read.warnings;
diff --git a/crates/engine/src/preview_cook.rs b/crates/engine/src/preview_cook.rs
index 1a225f29..101d6e4b 100644
--- a/crates/engine/src/preview_cook.rs
+++ b/crates/engine/src/preview_cook.rs
@@ -2,7 +2,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Arc, Mutex};
use materialcraft_core::Package;
-use materialcraft_eval::{Cache, Cooked, Options};
+use materialcraft_eval::{Cache, Cooked, Options, PreviewSampling};
/// One background result for the editor and the assigned material sources
#[derive(Default)]
@@ -14,13 +14,34 @@ pub struct PreviewCook {
impl PreviewCook {
pub fn run(package: &Package, graph: usize, materials: &BTreeSet, options: &Options<'_>, cache: &Arc>) -> Self {
- let mut result = Self { graph, cooked: materialcraft_eval::cook(package, graph, options, cache), materials: BTreeMap::new() };
+ Self::with_previous(package, graph, materials, options, cache, &BTreeMap::new())
+ }
+
+ pub fn with_previous(
+ package: &Package,
+ graph: usize,
+ materials: &BTreeSet,
+ options: &Options<'_>,
+ cache: &Arc>,
+ previous: &BTreeMap>,
+ ) -> Self {
+ let empty = PreviewSampling::default();
+ let cook = |index| {
+ let mut options = options.clone();
+ options.previous_sampling = Some(previous.get(&index).map_or(&empty, Arc::as_ref));
+ let mut cooked = materialcraft_eval::cook(package, index, &options, cache);
+ if cooked.nodes.values().any(|node| node.error.is_some()) {
+ cooked.preview_sampling = previous.get(&index).cloned();
+ }
+ cooked
+ };
+ let mut result = Self { graph, cooked: cook(graph), materials: BTreeMap::new() };
for &index in materials {
if result.cancelled() {
break;
}
if index != graph && package.graphs.get(index).is_some() {
- result.materials.insert(index, materialcraft_eval::cook(package, index, options, cache));
+ result.materials.insert(index, cook(index));
}
}
result
diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs
index 64c8f51d..2dc78fb2 100644
--- a/crates/engine/src/session.rs
+++ b/crates/engine/src/session.rs
@@ -1,6 +1,7 @@
//! The session: the open package, the graph being edited, selection, views, snapshot undo and
//! the cook cache.
+use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, PoisonError};
use craft_texture::Image;
@@ -59,6 +60,8 @@ pub struct Session {
pub pkg: Package,
/// Where the package was opened from or last saved to.
pub path: Option,
+ /// Original link base when import warnings require a new save destination.
+ pub(crate) recovery_origin: Option,
/// Index of the graph being edited.
pub graph: usize,
pub selection: Vec,
@@ -138,6 +141,7 @@ impl Session {
material_cooked: std::collections::BTreeMap::new(),
pkg,
path: None,
+ recovery_origin: None,
graph: 0,
selection: Vec::new(),
annotation_selection: None,
@@ -251,6 +255,7 @@ impl Session {
if let Some((snap, edited)) = self.group.take()
&& edited
{
+ self.reset_changed_sampling(&snap.pkg);
self.history.record(snap, None, self.history_prefs.undo_limit as usize);
self.refresh_links();
}
@@ -295,6 +300,7 @@ impl Session {
if let Some((_, edited)) = self.group.as_mut() {
*edited = true;
} else {
+ self.reset_changed_sampling(&snapshot.pkg);
self.history.record(snapshot, key, self.history_prefs.undo_limit as usize);
}
self.changed();
@@ -353,6 +359,7 @@ impl Session {
let s = self.history.undo(self.snapshot(""), self.history_prefs.undo_limit as usize)?;
let label = s.label.clone();
+ self.reset_changed_sampling(&s.pkg);
self.restore(s);
self.finish_edit();
self.dirty = true;
@@ -368,6 +375,7 @@ impl Session {
let s = self.history.redo(self.snapshot(""), self.history_prefs.undo_limit as usize)?;
let label = s.label.clone();
+ self.reset_changed_sampling(&s.pkg);
self.restore(s);
self.finish_edit();
self.dirty = true;
@@ -396,14 +404,14 @@ impl Session {
let hashes = resources.iter().map(|(_, bytes)| bytes.content_hash()).collect();
decoded.lock().unwrap_or_else(PoisonError::into_inner).retain_resources(&hashes);
move |requested: &str| {
- let (name, linear) = craft_texture::split_resource_key(requested);
+ let (name, space) = materialcraft_nodes::BitmapColorSpace::split_resource_key(requested);
let (_, bytes) = resources.iter().find(|(name_candidate, _)| name_candidate == name)?;
- let key = (bytes.content_hash(), linear);
+ let key = (bytes.content_hash(), space);
if let Some(image) = decoded.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {
return Some(image);
}
- let image = materialcraft_formats::decode(bytes.as_slice(), linear).ok()?;
+ let image = materialcraft_formats::decode_with_color_space(bytes.as_slice(), space).ok()?;
decoded.lock().unwrap_or_else(PoisonError::into_inner).insert(key, image.clone());
Some(image)
}
@@ -420,13 +428,40 @@ impl Session {
self.decoded = Arc::new(Mutex::new(crate::decoded_images::DecodedImages::new(16 << 20)));
}
+ // An extent or seed edit releases acquired input textures even if another edit restores
+ // the original value before the next preview. A grouped edit publishes only once.
+ fn reset_changed_sampling(&mut self, other: &Package) {
+ let context = |package: &Package, index: usize| package.graphs.get(index).map(|g| (g.size, g.seed, g.seed_mode));
+ let reset = |index, cooked: &mut Cooked| {
+ if cooked.preview_sampling.is_some() && context(&self.pkg, index) != context(other, index) {
+ cooked.preview_sampling = None;
+ }
+ };
+ if let Some(index) = self.cooked_graph {
+ reset(index, &mut self.cooked);
+ }
+ for (&index, cooked) in &mut self.material_cooked {
+ reset(index, cooked);
+ }
+ }
+
+ /// Take the sampling history from published graph previews before starting another cook.
+ pub fn preview_sampling(&self) -> BTreeMap> {
+ self.cooked_graph
+ .into_iter()
+ .map(|graph| (graph, &self.cooked))
+ .chain(self.material_cooked.iter().map(|(&graph, cooked)| (graph, cooked)))
+ .filter_map(|(graph, cooked)| cooked.preview_sampling.clone().map(|sampling| (graph, sampling)))
+ .collect()
+ }
+
/// Cook the open graph now (at the preview size), on this thread.
pub fn cook(&mut self) -> &Cooked {
let dec = self.resource_decoder();
let mut opts = Options::new(&dec);
opts.environment = self.environment;
opts.max_size = self.preview_size;
- let cooked = crate::PreviewCook::run(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache);
+ let cooked = crate::PreviewCook::with_previous(&self.pkg, self.graph, &self.material_preview.graphs(), &opts, &self.cache, &self.preview_sampling());
self.accept_preview(cooked);
self.dirty = false;
self.cook_epoch = self.cook_epoch.wrapping_add(1);
diff --git a/crates/engine/src/session.test.rs b/crates/engine/src/session.test.rs
index e854e088..6f99da45 100644
--- a/crates/engine/src/session.test.rs
+++ b/crates/engine/src/session.test.rs
@@ -23,6 +23,161 @@ fn the_resource_decoder_reads_data_maps_as_stored() {
assert!((data.get(0, 0, false)[2] - 1.0).abs() < 0.01);
}
+fn stamp_package() -> (Package, materialcraft_core::NodeId, [materialcraft_core::NodeId; 2]) {
+ use materialcraft_core::{Graph, OutputFormat, PatternGraph, PatternNodeKind, ResourceBytes, SizeMode, Value};
+
+ let image = Image::gray(128, 128, |x, y| ((13 * x + 7 * y + 3 * x * y) % 253) as f32 / 255.0);
+ let bytes = ResourceBytes::new(encode(&image, "png", Depth::U8, false).unwrap());
+ let mut package = Package::new("Stamp sampling");
+ for name in ["Field", "Copy"] {
+ package.resources.push(Resource::new(name, format!("{name}.png"), bytes.clone()));
+ }
+ let mut graph = Graph::new("Shared image");
+ graph.size = [5; 2];
+ graph.format = OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let base = &mut graph.node_mut(input).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = [5; 2];
+ base.format = OutputFormat::U8;
+ graph.input_images.insert("input".into(), "Field".into());
+ graph.input_images_linear.insert("input".into());
+ let stamps = [0.0, 80.0].map(|y| {
+ let id = graph.add_node("fx_map", [100.0, y]);
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ pattern.nodes[0].parameters.insert("patterntype".into(), Value::Int(1));
+ pattern.nodes[0].parameters.insert("patternsize".into(), Value::Float2([0.5; 2]));
+ let node = graph.node_mut(id).unwrap();
+ node.base.format = OutputFormat::F32;
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert("roughness".into(), Value::Float(0.0));
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+ graph.connect(input, "output", id, "pattern0").unwrap();
+ id
+ });
+ package.graphs.push(graph);
+ (package, input, stamps)
+}
+
+#[test]
+fn preview_stamps_reuse_sampling_levels_independently() {
+ let (package, _, stamps) = stamp_package();
+ let mut session = Session::new(package);
+ let base = 0x3f01_4181;
+ let mip = 0x3f01_8182;
+ let pixels = |cook: &materialcraft_eval::Cooked| {
+ stamps.map(|id| {
+ assert_eq!(cook.nodes[&id].error, None);
+ cook.image(id, 0).unwrap().get_gray(9, 8, false).to_bits()
+ })
+ };
+ assert_eq!(pixels(session.cook()), [base; 2]);
+ let change_precision = |session: &mut Session| {
+ for format in ["u16", "f32"] {
+ crate::execute(session, "graph.node.base", &serde_json::json!({"id":stamps[0].0,"format":format})).unwrap();
+ session.cook();
+ }
+ };
+ change_precision(&mut session);
+ assert_eq!(pixels(session.cook()), [mip, base], "only the edited stamp reacquires its input levels");
+ crate::execute(&mut session, "graph.size", &serde_json::json!({"width":32})).unwrap();
+ assert_eq!(pixels(session.cook()), [mip, base]);
+ assert_eq!(pixels(&session.cook_full(0)), [base; 2]);
+ for extent in [64, 32] {
+ crate::execute(&mut session, "graph.size", &serde_json::json!({"width":extent})).unwrap();
+ }
+ assert_eq!(pixels(session.cook()), [base; 2]);
+ change_precision(&mut session);
+ assert_eq!(pixels(session.cook()), [mip, base]);
+ crate::execute(&mut session, "graph.input.bind", &serde_json::json!({"identifier":"input","resource":"Copy","linear":true})).unwrap();
+ assert_eq!(pixels(session.cook()), [base; 2]);
+}
+
+#[test]
+fn changing_one_instances_precision_updates_its_fixed_precision_stamp() {
+ use materialcraft_core::{Graph, OutputFormat, Value};
+
+ let (mut package, source, stamps) = stamp_package();
+ let child = &mut package.graphs[0];
+ let out = child.add_node("output", [200.0, 0.0]);
+ child.connect(stamps[0], "output", out, "input").unwrap();
+ let mut parent = Graph::new("Paired instances");
+ parent.size = [5; 2];
+ parent.format = OutputFormat::F32;
+ parent.input_images = std::mem::take(&mut child.input_images);
+ parent.input_images_linear = std::mem::take(&mut child.input_images_linear);
+ let input = parent.add_node("input_grayscale", [0.0; 2]);
+ parent.node_mut(input).unwrap().base = child.node(source).unwrap().base.clone();
+ let instances = [0.0, 80.0].map(|y| {
+ let instance = parent.add_node("graph_instance", [100.0, y]);
+ let node = parent.node_mut(instance).unwrap();
+ node.params.insert("graph".into(), Value::Text(child.name.clone()));
+ node.base.format = OutputFormat::F32;
+ parent.connect(input, "output", instance, "input").unwrap();
+ instance
+ });
+ package.graphs.insert(0, parent);
+ let mut session = Session::new(package);
+ let pixels = |cooked: &materialcraft_eval::Cooked| {
+ instances.map(|id| {
+ assert_eq!(cooked.nodes[&id].error, None);
+ cooked.image(id, 0).unwrap().get_gray(9, 8, false).to_bits()
+ })
+ };
+ assert_eq!(pixels(session.cook()), [0x3f01_4181; 2]);
+ for format in ["u16", "f32"] {
+ crate::execute(&mut session, "graph.node.base", &serde_json::json!({"id":instances[0].0,"format":format})).unwrap();
+ assert_eq!(pixels(session.cook()), [0x3f01_8182, 0x3f01_4181]);
+ }
+ assert_eq!(pixels(&session.cook_full(0)), [0x3f01_4181; 2]);
+}
+
+#[test]
+fn bitmap_nodes_read_default_colors_from_the_file_and_keep_explicit_data_reads() {
+ use materialcraft_core::{Graph, OutputFormat, ResourceBytes, Value};
+
+ let field = Image::filled(16, 16, Kind::Color, [64.0, 128.0, 192.0, 97.0].map(|v| v / 255.0));
+ let png = encode(&field, "png", Depth::U8, false).unwrap();
+ for (gamma_chunk, expected) in [(false, [64, 128, 192, 97]), (true, [136, 186, 224, 97])] {
+ let mut bytes = png.clone();
+ if gamma_chunk {
+ // Insert a unit gAMA chunk, including its CRC, immediately after IHDR.
+ bytes.splice(33..33, *b"\0\0\0\x04gAMA\0\x01\x86\xa0\x31\xe8\x96\x5f");
+ }
+ let mut package = Package::new("Bitmap file colors");
+ package.resources.push(Resource::new("field", "field.png", ResourceBytes::new(bytes)));
+ let mut graph = Graph::new("File and data reads");
+ graph.size = [4, 4];
+ graph.format = OutputFormat::U8;
+ let bitmap = graph.add_node("bitmap", [0.0; 2]);
+ let data = graph.add_node("bitmap", [0.0, 80.0]);
+ let input = graph.add_node("input_color", [0.0, 160.0]);
+ graph.input_images.insert("input".into(), "field".into());
+ graph.input_images_from_file.insert("input".into());
+ for id in [bitmap, data] {
+ graph.node_mut(id).unwrap().params.insert("resource".into(), Value::Text("field".into()));
+ }
+ graph.node_mut(data).unwrap().params.insert("colour_space".into(), Value::Enum(1));
+ package.graphs.push(graph);
+ let mut session = Session::new(package);
+ let cook = session.cook();
+ let pixel = |id| cook.image(id, 0).unwrap().get(0, 0, false).map(|v| (v * 255.0).round() as u8);
+ assert_eq!(pixel(bitmap), expected);
+ assert_eq!(pixel(data), [64, 128, 192, 97]);
+ assert_eq!(pixel(input), expected);
+ for (linear, levels) in [(Some(true), [64, 128, 192, 97]), (None, expected), (Some(false), [13, 55, 134, 97]), (None, expected)] {
+ let mut params = serde_json::json!({"identifier": "input", "resource": "field"});
+ if let Some(value) = linear {
+ params["linear"] = value.into();
+ }
+ crate::execute(&mut session, "graph.input.bind", ¶ms).unwrap();
+ assert_eq!(session.graph().unwrap().input_images_from_file.contains("input"), linear.is_none());
+ let rebound = session.cook().image(input, 0).unwrap().get(0, 0, false).map(|v| (v * 255.0).round() as u8);
+ assert_eq!(rebound, levels);
+ }
+ }
+}
+
#[cfg(test)]
mod merge_tests {
use crate::Session;
diff --git a/crates/engine/tests/it/atomics.rs b/crates/engine/tests/it/atomics.rs
index fc13c903..12dc1c99 100644
--- a/crates/engine/tests/it/atomics.rs
+++ b/crates/engine/tests/it/atomics.rs
@@ -132,7 +132,15 @@ fn native_value_types_survive_processors_and_sbs() {
let mut session = Session::new(read.pkg);
session.preview_size = Some(16);
session.cook();
- for (node, expected) in session.graph().unwrap().nodes.iter().zip(values) {
+ for (node, authored) in session.graph().unwrap().nodes.iter().zip(values) {
+ let Some(Value::Function(function)) = node.params.get("function") else { panic!("missing value function") };
+ let constant = function.node(function.output.unwrap()).unwrap();
+ assert_eq!(constant.value.as_ref(), Some(&authored));
+ let expected = match authored {
+ Value::Int(16_777_217) => Value::Int(16_777_216),
+ Value::Int2([i32::MIN, i32::MAX]) => Value::Int2([i32::MIN, i32::MIN]),
+ value => value,
+ };
assert_eq!(session.cooked.value(node.id, 0), Some(&expected), "{:?}", session.cooked.nodes[&node.id].error);
}
}
diff --git a/crates/engine/tests/it/embedded_edit.rs b/crates/engine/tests/it/embedded_edit.rs
index 92cd39c3..8a145fc3 100644
--- a/crates/engine/tests/it/embedded_edit.rs
+++ b/crates/engine/tests/it/embedded_edit.rs
@@ -648,11 +648,11 @@ fn library_samplers_read_image_inputs_in_both_processors() {
session.cook();
if definition == "value_processor" {
- let expected = if sampler == "samplecol" { Value::Float4(color) } else { Value::Float(color[0]) };
+ let expected = if sampler == "samplecol" { Value::Float4(color) } else { Value::Float(0.5) };
assert_eq!(session.cooked.value(owner, 0), Some(&expected));
} else {
- let expected = if sampler == "samplecol" { color } else { [color[0], color[0], color[0], 1.0] };
+ let expected = if sampler == "samplecol" { color } else { [0.5, 0.5, 0.5, 1.0] };
assert_eq!(session.cooked.image(owner, 0).unwrap().get(0, 0, false), expected);
}
diff --git a/crates/engine/tests/it/function_graph.rs b/crates/engine/tests/it/function_graph.rs
index f1deb9fd..09e502af 100644
--- a/crates/engine/tests/it/function_graph.rs
+++ b/crates/engine/tests/it/function_graph.rs
@@ -62,6 +62,7 @@ fn standalone_function_creation_wiring_frame_movement_and_native_round_trip() {
let function = graph.function.as_ref().unwrap();
assert_eq!(function.nodes[0].pos, [32.0, 64.0]);
let variables = Default::default();
- let context = EvaluationContext { scope: Default::default(), position: [0.0; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
+ let context =
+ EvaluationContext { image_formats: &[], scope: Default::default(), position: [0.0; 2], size: [1.0; 2], images: &[], tile: true, variables: &variables };
assert_eq!(compile(function, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Float(6.0));
}
diff --git a/crates/engine/tests/it/function_instances.rs b/crates/engine/tests/it/function_instances.rs
index 0ac105b5..4c9dd7c8 100644
--- a/crates/engine/tests/it/function_instances.rs
+++ b/crates/engine/tests/it/function_instances.rs
@@ -11,6 +11,7 @@ fn source() -> Package {
let mut package = Package::new("Functions");
let mut graph = Graph::new("Twice");
graph.exposed.push(ExposedParameter {
+ connectable: false,
description: String::new(),
editor: None,
clamp: false,
@@ -47,7 +48,15 @@ fn evaluate(graph: &FunctionGraph) -> Value {
function::compile(graph, 0)
.unwrap()
.evaluate(
- &EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() },
+ &EvaluationContext {
+ image_formats: &[],
+ scope: Default::default(),
+ position: [0.5; 2],
+ size: [16.0; 2],
+ images: &[],
+ tile: true,
+ variables: &BTreeMap::new(),
+ },
&mut EvaluationState::default(),
)
.unwrap()
@@ -313,6 +322,24 @@ fn calls_evaluate_arguments_once_and_share_the_variables_they_set() {
assert_eq!(evaluate(&caller), Value::Float(103.0));
}
+#[test]
+fn open_connectable_function_arguments_read_zero_and_preserve_the_source_value() {
+ let mut package = source();
+ package.graphs[0].exposed[0].connectable = true;
+ let mut session = Session::new(package);
+ execute(&mut session, "file.new", &json!({"name": "Caller", "kind": "function"})).unwrap();
+ let target = json!({"kind": "graph"});
+ let instance = call(&mut session, 0, "Twice", &target);
+ edit(&mut session, &target, json!({"action": "output", "id": instance}));
+ assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.0));
+ let constant = edit(&mut session, &target, json!({"action": "add", "operation": "const_float1", "at": [0,0]}))["id"].as_u64().unwrap();
+ edit(&mut session, &target, json!({"action": "value", "id": constant, "value": Value::Float(0.1875)}));
+ edit(&mut session, &target, json!({"action": "connect", "from": constant, "to": instance, "input": 0}));
+ assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.375));
+ execute(&mut session, "package.activate", &json!({"document": 0})).unwrap();
+ assert_eq!(session.pkg.graphs[0].input_value("amount"), Some(&Value::Float(0.5)));
+}
+
#[test]
fn unconnected_instance_inputs_use_the_source_defaults() {
let mut session = Session::new(source());
diff --git a/crates/engine/tests/it/function_library.rs b/crates/engine/tests/it/function_library.rs
index a9f74b7c..77789e0b 100644
--- a/crates/engine/tests/it/function_library.rs
+++ b/crates/engine/tests/it/function_library.rs
@@ -18,7 +18,15 @@ fn session() -> Session {
}
fn value(function: &FunctionGraph) -> Value {
- let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [16.0; 2], images: &[], tile: true, variables: &BTreeMap::new() };
+ let context = EvaluationContext {
+ image_formats: &[],
+ scope: Default::default(),
+ position: [0.5; 2],
+ size: [16.0; 2],
+ images: &[],
+ tile: true,
+ variables: &BTreeMap::new(),
+ };
function::compile(function, 0).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap()
}
@@ -233,8 +241,15 @@ fn supplied_functions_evaluate_before_and_after_save() {
if graph.name == "compute_total_number" {
variables.insert("render_region".into(), Value::Float4([-0.5, 0.5, -0.5, 0.5]));
}
- let context =
- EvaluationContext { scope: Default::default(), position: [0.5; 2], size: [256.0, 128.0], images: &[], tile: true, variables: &variables };
+ let context = EvaluationContext {
+ image_formats: &[],
+ scope: Default::default(),
+ position: [0.5; 2],
+ size: [256.0, 128.0],
+ images: &[],
+ tile: true,
+ variables: &variables,
+ };
match source.evaluate(&context, &mut EvaluationState::default()) {
Ok(expected) => {
assert_eq!(saved.evaluate(&context, &mut EvaluationState::default()).unwrap(), expected, "{}", graph.sbs_path());
diff --git a/crates/engine/tests/it/graph_interaction.rs b/crates/engine/tests/it/graph_interaction.rs
index 974d030d..920e7904 100644
--- a/crates/engine/tests/it/graph_interaction.rs
+++ b/crates/engine/tests/it/graph_interaction.rs
@@ -133,6 +133,9 @@ fn fx_map_starts_with_a_quadrant_and_grows_image_inputs_as_connected() {
let source = add(&mut session, "uniform");
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color", "value": [0.5, 0.5, 0.5, 1.0]})).unwrap();
execute(&mut session, "graph.node.param", &json!({"id": source.0, "param": "color_mode", "value": false})).unwrap();
+ let sixth = add(&mut session, "uniform");
+ execute(&mut session, "graph.node.param", &json!({"id": sixth.0, "param": "color", "value": [0.75, 0.75, 0.75, 1.0]})).unwrap();
+ execute(&mut session, "graph.node.param", &json!({"id": sixth.0, "param": "color_mode", "value": false})).unwrap();
let owner = add(&mut session, "fx_map");
let Value::PatternGraph(pattern) = &session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!("missing default pattern") };
@@ -153,8 +156,10 @@ fn fx_map_starts_with_a_quadrant_and_grows_image_inputs_as_connected() {
assert_eq!(loaded_pattern.nodes[0].kind, PatternNodeKind::Quadrant);
assert_eq!(loaded_pattern.root, Some(loaded_pattern.nodes[0].id));
+ execute(&mut session, "graph.node.param", &json!({"id": owner.0, "param": "color_mode", "value": false})).unwrap();
for index in 0..6 {
- execute(&mut session, "graph.connect", &json!({"from": source.0, "to": owner.0, "toPort": format!("pattern{index}")})).unwrap();
+ let input = if index == 5 { sixth } else { source };
+ execute(&mut session, "graph.connect", &json!({"from": input.0, "to": owner.0, "toPort": format!("pattern{index}")})).unwrap();
assert_eq!(session.input_ports(owner).last(), Some(&format!("pattern{}", index + 1)));
}
@@ -163,12 +168,12 @@ fn fx_map_starts_with_a_quadrant_and_grows_image_inputs_as_connected() {
let mut pattern = (**pattern).clone();
pattern.nodes[0].parameters.insert("patterntype".into(), Value::Int(1));
- pattern.nodes[0].parameters.insert("imageindex".into(), Value::Int(6));
+ pattern.nodes[0].parameters.insert("imageindex".into(), Value::Int(5));
execute(&mut session, "graph.pattern.set", &json!({"id": owner.0, "pattern": pattern})).unwrap();
session.cook();
assert!(session.cooked.nodes[&owner].error.is_none(), "{:?}", session.cooked.nodes[&owner].error);
- assert!((session.cooked.image(owner, 0).unwrap().mean()[0] - 0.5).abs() < 1e-5);
+ assert!((session.cooked.image(owner, 0).unwrap().mean()[0] - 0.75).abs() < 1e-5);
let bytes = write_sbs(&session.pkg).unwrap();
@@ -186,7 +191,7 @@ fn fx_map_starts_with_a_quadrant_and_grows_image_inputs_as_connected() {
loaded.cook();
- assert!((loaded.cooked.image(loaded_owner, 0).unwrap().mean()[0] - 0.5).abs() < 1e-5);
+ assert!((loaded.cooked.image(loaded_owner, 0).unwrap().mean()[0] - 0.75).abs() < 1e-5);
execute(&mut session, "graph.disconnect", &json!({"to": owner.0, "toPort": "pattern5"})).unwrap();
diff --git a/crates/engine/tests/it/graph_properties.rs b/crates/engine/tests/it/graph_properties.rs
index fa115ec7..f2f98afb 100644
--- a/crates/engine/tests/it/graph_properties.rs
+++ b/crates/engine/tests/it/graph_properties.rs
@@ -5,6 +5,20 @@ use materialcraft_engine::{
};
use serde_json::json;
+#[test]
+fn graph_parent_dimensions_round_up_and_include_a_single_texel() {
+ let mut session = Session::new(Package::new("Small"));
+ execute(&mut session, "file.new", &json!({"template": "empty", "size": 3})).unwrap();
+ assert_eq!(session.graph().unwrap().size_px(), [4, 4]);
+ for (requested, expected) in [([1, 1], [1, 1]), ([1, 8], [1, 8]), ([3, 5], [4, 8]), ([6, 9], [8, 16]), ([17, 31], [32, 32]), ([0, u64::MAX], [1, 8192])] {
+ let result = execute(&mut session, "graph.size", &json!({"width": requested[0], "height": requested[1]})).unwrap();
+ assert_eq!(result, json!({"width": expected[0], "height": expected[1]}));
+ assert_eq!(session.graph().unwrap().size_px(), expected);
+ }
+ execute(&mut session, "graph.size", &json!({"log2": [0, 1u64 << 32]})).unwrap();
+ assert_eq!(session.graph().unwrap().size_px(), [1, 8192]);
+}
+
#[path = "graph_property/history_preferences.rs"]
mod history_preferences;
@@ -171,3 +185,14 @@ fn a_function_label_updates_instances_without_renaming_references() {
assert_eq!(materialcraft_engine::nodes::function::node_label(node), "Readable label");
assert_eq!(node.instance.as_ref().unwrap().graph, "Stable_identifier");
}
+
+#[test]
+fn graph_seed_inheritance_can_be_edited_without_changing_the_offset() {
+ let mut session = materialcraft_engine::new_session();
+ execute(&mut session, "graph.seed", &json!({"seed": 17, "inheritance": "absolute"})).unwrap();
+ execute(&mut session, "graph.seed", &json!({"inheritance": "relativeToParent"})).unwrap();
+ let graph = session.graph().unwrap();
+ assert_eq!((graph.seed, graph.seed_mode), (17, materialcraft_engine::core::ParameterInheritance::RelativeToParent));
+ assert!(execute(&mut session, "graph.seed", &json!({"seed": 3, "inheritance": "unknown"})).is_err());
+ assert_eq!(session.graph().unwrap().seed, 17);
+}
diff --git a/crates/engine/tests/it/linked_resources.rs b/crates/engine/tests/it/linked_resources.rs
index 30f1eb9d..f6a354fa 100644
--- a/crates/engine/tests/it/linked_resources.rs
+++ b/crates/engine/tests/it/linked_resources.rs
@@ -71,14 +71,18 @@ fn resource_package(source: &str) -> Package {
#[test]
fn library_resources_resolve_next_to_their_package() {
+ with_library_files("library_resources_resolve_next_to_their_package", verify_library_resources);
+}
+
+fn with_library_files(test: &str, verify: fn(&std::path::Path)) {
const CHILD_ROOT: &str = "MC_LINKED_RESOURCES_TEST_ROOT";
if let Ok(root) = std::env::var(CHILD_ROOT) {
- verify_library_resources(std::path::Path::new(&root));
+ verify(std::path::Path::new(&root));
return;
}
// A child process isolates the library root without mutating the test runner's environment
- let root = std::env::temp_dir().join(format!("materialcraft-linked-resources-{}", std::process::id()));
+ let root = std::env::temp_dir().join(format!("materialcraft-linked-resources-{}-{test}", std::process::id()));
std::fs::create_dir_all(root.join("assets/sbs/resources")).unwrap();
std::fs::create_dir_all(root.join("assets/sbs/nested/resources")).unwrap();
std::fs::write(root.join("assets/sbs/resources/tile.svg"), TILE).unwrap();
@@ -98,7 +102,7 @@ fn library_resources_resolve_next_to_their_package() {
.unwrap();
let status = std::process::Command::new(std::env::current_exe().unwrap())
- .args(["--exact", "linked_resources::library_resources_resolve_next_to_their_package", "--nocapture"])
+ .args(["--exact", &format!("linked_resources::{test}"), "--nocapture"])
.env(CHILD_ROOT, &root)
.env("MATERIALCRAFT_SBS_DIR", root.join("assets/sbs"))
.status()
@@ -108,6 +112,38 @@ fn library_resources_resolve_next_to_their_package() {
assert!(status.success());
}
+#[test]
+fn saving_a_catalog_source_updates_open_callers() {
+ with_library_files("saving_a_catalog_source_updates_open_callers", |root| {
+ use materialcraft_engine::NodeLibrary;
+ use std::sync::Arc;
+
+ let alias = "sbs://nested/source.sbs";
+ let source = root.join("assets/sbs/nested/source.sbs");
+ let caller = root.join("caller.sbs");
+ let original = std::fs::read_to_string(root.join("assets/sbs/nested/caller.sbs")).unwrap();
+ std::fs::write(&caller, original.replace("source.sbs", alias)).unwrap();
+ let check = |project, library, edited, expected| {
+ let mut session = Session::with_library(project, library);
+ file_cmds::open_file(&mut session, caller.to_str().unwrap()).unwrap();
+ let document = session.document_id;
+ file_cmds::open_file(&mut session, source.to_str().unwrap()).unwrap();
+ let body = FunctionGraph::constant(Value::Float(edited));
+ execute(&mut session, "graph.function.set", &json!({"function": body})).unwrap();
+ execute(&mut session, "file.save", &json!({})).unwrap();
+ session.activate_document(document).unwrap();
+ let linked = &session.pkg.dependencies[alias].graphs[0];
+ assert_eq!(linked.function.as_ref().unwrap().nodes[0].value, Some(Value::Float(expected)));
+ assert_eq!(session.graph().unwrap().instances().next().unwrap().package, alias);
+ };
+ check(Package::new("Installed"), NodeLibrary::shared(), 0.375, 0.375);
+ check(Package::new("Loaded by caller"), Arc::default(), 0.625, 0.625);
+ let mut project = Package::new("Explicit override");
+ project.dependencies.insert(alias.into(), Arc::new(resource_package("resources/tile.svg")));
+ check(project, NodeLibrary::shared(), 0.75, 0.5);
+ });
+}
+
fn verify_library_resources(root: &std::path::Path) {
let library =
materialcraft_engine::NodeLibrary::load(&["sbs://nested/caller.sbs".into(), "sbs://nested/source.sbs".into(), "sbs://nested/source.sbs".into()]);
diff --git a/crates/engine/tests/it/optimization_perf.rs b/crates/engine/tests/it/optimization_perf.rs
index 2eb7b8dd..1ed661f6 100644
--- a/crates/engine/tests/it/optimization_perf.rs
+++ b/crates/engine/tests/it/optimization_perf.rs
@@ -41,8 +41,9 @@ fn optimization_baseline() {
parameters.insert("color_mode".into(), Value::Bool(false));
for size in [512, 2048] {
for count in [0, 16] {
- let variables = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect();
+ let variables: BTreeMap<_, _> = (0..count).map(|index| (format!("input_{index}"), Value::Float(index as f32))).collect();
let context = CookContext {
+ input_formats: &[],
format: materialcraft_core::OutputFormat::F32,
w: size,
h: size,
diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs
index aab2fab8..e5fe41bb 100644
--- a/crates/engine/tests/it/parameter_functions.rs
+++ b/crates/engine/tests/it/parameter_functions.rs
@@ -237,6 +237,7 @@ fn instance_parameter_functions_work_without_stored_literals_and_use_instance_si
source.node_mut(color).unwrap().params.insert("color_mode".into(), Value::Bool(false));
source.node_mut(color).unwrap().functions.insert("color".into(), FunctionGraph::input("amount", ValueType::Float4));
source.exposed.push(materialcraft_engine::core::ExposedParameter {
+ connectable: false,
description: String::new(),
editor: None,
clamp: false,
@@ -341,7 +342,8 @@ fn native_channel_parameters_accept_scalar_functions_without_changing_their_bodi
assert_eq!(result.error, None, "{definition}.{parameter}");
- let expected = if definition == "fx_map" { Value::Color([0.25, 0.25, 0.25, 1.0]) } else { Value::Float4([0.25; 4]) };
+ let gray = [0.25, 0.25, 0.25, 1.0];
+ let expected = if definition == "fx_map" { Value::Color(gray) } else { Value::Float4(gray) };
assert_eq!(result.parameters[*parameter], expected);
diff --git a/crates/engine/tests/it/sbs_functions.rs b/crates/engine/tests/it/sbs_functions.rs
index b27eab7c..c1629bd5 100644
--- a/crates/engine/tests/it/sbs_functions.rs
+++ b/crates/engine/tests/it/sbs_functions.rs
@@ -43,24 +43,28 @@ fn imported_expression_cooks_follows_inputs_and_survives_undo_and_save() {
s.cooked.image(levels, 0).unwrap().mean()[0]
};
- assert!(mean(&mut s).abs() < 1e-5);
+ // The default swizzle places the scalar in red. Grayscale Levels averages RGB,
+ // so the lower endpoints are (0.75 - 0.25) / 3 and (0.5 - 0.25) / 3.
+ let original_mean = 2.0 / 5.0;
+ let changed_mean = 5.0 / 11.0;
+ assert!((mean(&mut s) - original_mean).abs() < 1e-5);
execute(&mut s, "graph.exposed.set", &json!({"id": "amount", "value": 0.5})).unwrap();
- assert!((mean(&mut s) - 1.0 / 3.0).abs() < 1e-5);
+ assert!((mean(&mut s) - changed_mean).abs() < 1e-5);
execute(&mut s, "edit.undo", &json!({})).unwrap();
- assert!(mean(&mut s).abs() < 1e-5);
+ assert!((mean(&mut s) - original_mean).abs() < 1e-5);
execute(&mut s, "edit.redo", &json!({})).unwrap();
- assert!((mean(&mut s) - 1.0 / 3.0).abs() < 1e-5);
+ assert!((mean(&mut s) - changed_mean).abs() < 1e-5);
let saved = sbs::write_sbs(&s.pkg).unwrap();
s.pkg = sbs::read_sbs(&saved, "saved.sbs", &|_| None).unwrap().pkg;
s.cache.lock().unwrap().clear();
- assert!((mean(&mut s) - 1.0 / 3.0).abs() < 1e-5);
+ assert!((mean(&mut s) - changed_mean).abs() < 1e-5);
assert!(s.graph().unwrap().nodes.iter().find(|node| node.def == "levels").unwrap().functions.contains_key("in_low"));
}
diff --git a/crates/engine/tests/it/subgraph_seed.rs b/crates/engine/tests/it/subgraph_seed.rs
index c125139c..b1342f53 100644
--- a/crates/engine/tests/it/subgraph_seed.rs
+++ b/crates/engine/tests/it/subgraph_seed.rs
@@ -11,6 +11,7 @@ fn grouping_noise_preserves_pixels_seed_and_undo() {
let mut s = new_session();
s.preview_size = None;
run(&mut s, "graph.size", json!({"width": 64, "height": 32}));
+ run(&mut s, "graph.format", json!({"format": "f32"}));
run(&mut s, "graph.seed", json!({"seed": seed}));
let noise = run(&mut s, "graph.node.add", json!({"def": "pixel_processor"}))["id"].as_u64().unwrap();
let mut function = materialcraft_engine::core::FunctionGraph::default();
@@ -49,5 +50,30 @@ fn grouping_noise_preserves_pixels_seed_and_undo() {
let reopened_output = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "output").unwrap().id;
assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), before.data());
+ run(&mut s, "edit.undo", json!({}));
+ for changed_seed in [5, 89] {
+ run(&mut s, "graph.seed", json!({"seed": changed_seed}));
+ run(&mut reopened, "graph.seed", json!({"seed": changed_seed}));
+ assert_eq!(reopened.cook().image(reopened_output, 0).unwrap().data(), s.cook().image(output, 0).unwrap().data());
+ }
}
}
+
+#[test]
+fn editing_a_computed_graph_seed_preserves_the_expression_until_a_literal_is_set() {
+ use materialcraft_engine::core::{FunctionGraph, ParameterInheritance};
+ let mut session = new_session();
+ let mut function = FunctionGraph::default();
+ function.output = Some(function.add_constant(materialcraft_engine::core::Value::Int(5)));
+ session.pkg.graphs[0].seed_function = Some(function.clone());
+ run(&mut session, "graph.seed", json!({"inheritance": "relativeToParent"}));
+ assert_eq!(session.pkg.graphs[0].seed_mode, ParameterInheritance::RelativeToParent);
+ assert_eq!(session.pkg.graphs[0].seed_function.as_ref(), Some(&function));
+ let inspected = run(&mut session, "session.inspect", json!({}));
+ assert_eq!(inspected["graph"]["seedFunction"], serde_json::to_value(&function).unwrap());
+ run(&mut session, "graph.seed", json!({"seed": 17}));
+ assert_eq!(session.pkg.graphs[0].seed_function, None);
+ assert_eq!(session.pkg.graphs[0].seed, 17);
+ run(&mut session, "edit.undo", json!({}));
+ assert_eq!(session.pkg.graphs[0].seed_function, Some(function));
+}
diff --git a/crates/engine/tests/it/system_variables.rs b/crates/engine/tests/it/system_variables.rs
index 1b6c918c..29b390c2 100644
--- a/crates/engine/tests/it/system_variables.rs
+++ b/crates/engine/tests/it/system_variables.rs
@@ -51,18 +51,18 @@ fn standalone_get_suggestions_match_each_type_and_order() {
}
#[test]
-fn pixel_processor_suggestions_add_position_without_fx_variables() {
- let mut graph = Graph::new("Pixels");
- let owner = graph.add_node("pixel_processor", [0.0; 2]);
- graph.node_mut(owner).unwrap().params.insert("function".into(), Value::Function(Box::new(getter("get_float2", ""))));
- let mut package = Package::new("Pixels");
- package.graphs.push(graph);
- let session = Session::new(package);
- let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() };
-
- let variables = target.variables(&session, 1).unwrap();
-
- assert_eq!(variables.iter().map(|variable| variable.name.as_str()).collect::>(), ["$size", "$sizelog2", "$pos"]);
+fn pixel_and_value_processor_suggestions_include_position() {
+ for processor in ["pixel_processor", "value_processor"] {
+ let mut graph = Graph::new("Position");
+ let owner = graph.add_node(processor, [0.0; 2]);
+ graph.node_mut(owner).unwrap().params.insert("function".into(), Value::Function(Box::new(getter("get_float2", ""))));
+ let mut package = Package::new("Position");
+ package.graphs.push(graph);
+ let session = Session::new(package);
+ let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() };
+ let variables = target.variables(&session, 1).unwrap();
+ assert_eq!(variables.iter().map(|variable| variable.name.as_str()).collect::>(), ["$size", "$sizelog2", "$pos"]);
+ }
}
#[test]
@@ -78,6 +78,14 @@ fn graph_metadata_and_host_values_cook_and_round_trip_as_native_get_nodes() {
("get_float3", "$physicalsize", Value::Float3([20.0, 10.0, 0.5])),
("get_float2", "$size", Value::Float2([32.0, 16.0])),
("get_float2", "$sizelog2", Value::Float2([5.0, 4.0])),
+ ("get_float2", "$pos", Value::Float2([0.0; 2])),
+ ("get_float1", "$depth", Value::Float(0.0)),
+ ("get_float1", "$depthpow2", Value::Float(0.0)),
+ ("get_float1", "$number", Value::Float(0.0)),
+ ("isdefined", "$pos", Value::Bool(true)),
+ ("isdefined", "$depthpow2", Value::Bool(true)),
+ ("isdefined", "$absent", Value::Bool(false)),
+ ("get_integer3", "$absent", Value::Int3([0; 3])),
];
let ids: Vec<_> = cases.iter().map(|(operation, name, _)| processor(&mut graph, operation, name)).collect();
let mut package = Package::new("Context");
@@ -135,7 +143,7 @@ fn pixel_ratio_and_tiling_inherit_and_preserve_native_relative_modes() {
let mut session = Session::new(package);
session.selection = vec![pixel];
- for (mode, expected) in [("relativeToInput", 2.0), ("relativeToParent", 3.0), ("absolute", 0.0)] {
+ for (mode, expected) in [("relativeToInput", 2.0), ("relativeToParent", 4.0), ("absolute", 0.0)] {
execute(&mut session, "graph.node.base", &json!({"pixelRatio": 0, "tiling": false, "pixelRatioMode": mode, "tilingMode": mode})).unwrap();
let bytes = write_sbs(&session.pkg).unwrap();
let read = read_sbs(&bytes, "inheritance.sbs", &|_| None).unwrap();
@@ -279,7 +287,8 @@ fn nested_function_instances_use_the_processing_callers_variable_scope() {
let cooked = session.cook();
assert_eq!(cooked.nodes[&pixel].error, None);
- assert!(cooked.nodes[&value].error.as_deref().unwrap().contains("undefined variable `$pos`"));
+ assert_eq!(cooked.nodes[&value].error, None);
+ assert_eq!(cooked.nodes[&value].outputs[0].as_value(), Some(&Value::Float2([0.0; 2])));
let image = cooked.image(pixel, 0).unwrap();
diff --git a/crates/engine/tests/package_resources.rs b/crates/engine/tests/package_resources.rs
index 3c375309..fa68f5df 100644
--- a/crates/engine/tests/package_resources.rs
+++ b/crates/engine/tests/package_resources.rs
@@ -3,6 +3,20 @@ use serde_json::json;
const SVG: &[u8] = br#""#;
+#[test]
+fn saving_a_recovered_package_keeps_its_missing_resource_link_relative() {
+ let bytes = br#""#;
+ let mut session = Session::new(Package::new("Empty"));
+ file_cmds::open_bytes_linked(&mut session, bytes, Some("materials/example.sbs".into()), &|_| None).unwrap();
+ assert!(session.path.is_none());
+ assert!(!session.load_warnings.is_empty());
+ let first = session.document_id;
+ file_cmds::open_bytes_linked(&mut session, bytes, Some("other/example.sbs".into()), &|_| None).unwrap();
+ execute(&mut session, "package.activate", &json!({"document": first})).unwrap();
+ let saved = String::from_utf8(file_cmds::save_bytes(&session).unwrap()).unwrap();
+ assert!(saved.contains(r#""#));
+}
+
#[test]
fn byte_only_sbs_import_resolves_library_resource_substitutes() {
let xml = br#"
diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs
index c2c0a7ad..6248743d 100644
--- a/crates/engine/tests/session.rs
+++ b/crates/engine/tests/session.rs
@@ -127,7 +127,31 @@ fn export_size_keeps_proportions_and_clamps() {
s.pkg.graphs[0].size = [u32::MAX, u32::MAX];
assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 32)));
- assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (16, 8192)), "sides clamp to 16..8192");
+ assert!(dims(&s, json!([1, u64::MAX])).iter().all(|d| *d == (1, 8192)), "sides clamp to 1..8192");
+
+ s.pkg.graphs[0].absolute_output_size = Some([6, 5]);
+ assert!(dims(&s, json!(0)).iter().all(|d| *d == (64, 32)));
+ assert!(dims(&s, json!(32)).iter().all(|d| *d == (32, 16)));
+ assert_eq!(s.pkg.graphs[0].absolute_output_size, Some([6, 5]));
+
+ s.pkg.graphs[0].absolute_output_size = None;
+ s.pkg.graphs[0].size = [7, 6];
+ let shift = materialcraft_engine::core::GraphSizeOffset::Parent([-1, 1]);
+ s.pkg.graphs[0].relative_output_size = Some(shift);
+ assert!(dims(&s, json!(0)).iter().all(|d| *d == (64, 128)));
+ assert!(dims(&s, json!(32)).iter().all(|d| *d == (16, 32)));
+ assert_eq!(s.pkg.graphs[0].relative_output_size, Some(shift));
+
+ use materialcraft_engine::core::{FunctionGraph, Value as GraphValue};
+ let function = FunctionGraph::constant(GraphValue::Int2([0, 2]));
+ s.pkg.graphs[0].output_size_function = Some(function.clone());
+ assert!(dims(&s, json!(0)).iter().all(|d| *d == (128, 256)));
+ assert!(dims(&s, json!(64)).iter().all(|d| *d == (32, 64)));
+ assert!(dims(&s, json!([32, 16])).iter().all(|d| *d == (32, 16)));
+ assert_eq!(s.pkg.graphs[0].output_size_function.as_ref(), Some(&function));
+ let info = execute(&mut s, "session.inspect", &json!({})).unwrap();
+ assert_eq!(info["graph"]["size"], json!([128, 256]));
+ assert_eq!(info["graph"]["outputSizeMode"], "relativeToParent");
}
/// A scratch folder for one test, removed when dropped
@@ -165,6 +189,149 @@ fn native_sbs_is_the_default_save_format() {
assert_eq!(run(&mut session, "file.save", json!({}))["path"], json!(saved));
}
+#[test]
+fn saving_a_library_graph_opened_from_disk_keeps_its_portable_function_links() {
+ let directory = TempDir::new("library-function-export");
+ let name = "waveform_01_v2.sbs";
+ let library = materialcraft_engine::formats::sbs::library::root();
+ let mut session = sample_session();
+ for (index, source) in [library.join(name).to_str().unwrap().to_string(), format!("sbs://{name}")].into_iter().enumerate() {
+ run(&mut session, "file.open", json!({ "path": source }));
+ let saved = directory.file(&format!("caller-{index}.sbs"));
+ run(&mut session, "file.saveAs", json!({ "path": saved }));
+ let xml = std::fs::read_to_string(&saved).unwrap();
+ for helper in ["functions.sbs", "functions_hash.sbs"] {
+ assert!(xml.contains(&format!(r#" =
+ reopened.pkg.graphs.iter().flat_map(|graph| graph.instances()).map(|instance| instance.package.as_str()).collect();
+ assert!(links.contains("sbs://blend_switch.sbs"));
+ let dependent = library::root().join("non_uniform_blur.sbs").canonicalize().unwrap();
+ assert!(links.contains("sbs://non_uniform_blur.sbs"));
+
+ // A local edit in a shared grandchild keeps the whole branch linked to its source.
+ let functions = library::root().join("functions.sbs").canonicalize().unwrap();
+ let source = library::root().join("bevel.sbs");
+ let mut edited = sample_session();
+ run(&mut edited, "file.open", json!({"path": source}));
+ let dependency = edited.pkg.dependencies.get_mut(functions.to_str().unwrap()).unwrap();
+ std::sync::Arc::make_mut(dependency).graphs[0].name.push_str("_edited");
+ let saved = directory.file("with_edits.sbs");
+ run(&mut edited, "file.saveCopyAs", json!({"path": saved}));
+ let mut reopened = sample_session();
+ run(&mut reopened, "file.open", json!({"path": saved}));
+ assert!(reopened.pkg.graphs.iter().flat_map(|graph| graph.instances()).any(|instance| instance.package == dependent.to_str().unwrap()));
+}
+
+#[test]
+fn saving_in_place_keeps_a_file_reference_to_a_bundled_graph() {
+ use materialcraft_engine::{
+ core::{Graph, GraphInstance, Package},
+ formats::sbs::{library, write_sbs},
+ };
+
+ let directory = TempDir::new("live-library-link");
+ let caller = directory.file("caller.sbs");
+ let source = library::root().join("blend_switch.sbs").canonicalize().unwrap();
+ let mut graph = Graph::new("Caller");
+ let instance = graph.add_node("graph_instance", [0.0; 2]);
+ graph.node_mut(instance).unwrap().instance = Some(GraphInstance {
+ package: source.to_str().unwrap().to_owned(),
+ graph: "switch_grayscale".into(),
+ label: String::new(),
+ inputs: Vec::new(),
+ outputs: Vec::new(),
+ defaults: Default::default(),
+ });
+ let mut package = Package::new("Caller");
+ package.graphs.push(graph);
+ std::fs::write(&caller, write_sbs(&package).unwrap()).unwrap();
+
+ let mut session = sample_session();
+ run(&mut session, "file.open", json!({"path": caller}));
+ run(&mut session, "file.save", json!({}));
+ let mut reopened = sample_session();
+ run(&mut reopened, "file.open", json!({"path": caller}));
+ let saved = reopened.pkg.graphs[0].instances().next().unwrap();
+ assert_eq!(saved.package, source.to_str().unwrap());
+
+ let copy = directory.file("copy.sbs");
+ run(&mut reopened, "file.saveCopyAs", json!({"path": copy}));
+ let xml = std::fs::read_to_string(copy).unwrap();
+ assert!(xml.contains(r#" = parsed.pkg.graphs[0].instances().map(|instance| instance.package.as_str()).collect();
+ assert_eq!(links, [catalog, file]);
+}
+
+#[test]
+fn a_changed_or_detached_function_file_keeps_its_disk_identity() {
+ use materialcraft_engine::formats::sbs::library;
+ use std::path::Path;
+
+ let directory = TempDir::new("local-function-source");
+ let name = "functions_hash.sbs";
+ let path = directory.file(name);
+ let mut changed = library::read(&format!("sbs://{name}")).unwrap();
+ changed[0] = b' ';
+ std::fs::write(&path, changed).unwrap();
+ assert!(library::bundled_package_uri(&directory.0.canonicalize().unwrap(), Path::new(&path)).is_none());
+ std::fs::copy(library::root().join(name), &path).unwrap();
+ assert!(library::bundled_package_uri(&library::root().canonicalize().unwrap(), Path::new(&path)).is_none());
+}
+
/// Saving an SBS file another program wrote must not overwrite it: MaterialCraft can't write back what it couldn't read
#[test]
fn saving_an_sbs_file_from_another_program_needs_a_new_name() {
diff --git a/crates/eval/Cargo.toml b/crates/eval/Cargo.toml
index a5ddc9f0..a352b85f 100644
--- a/crates/eval/Cargo.toml
+++ b/crates/eval/Cargo.toml
@@ -11,7 +11,7 @@ workspace = true
[dependencies]
materialcraft-core = { workspace = true }
craft-texture = { workspace = true }
-materialcraft-nodes = { workspace = true }
half = { workspace = true }
+materialcraft-nodes = { workspace = true }
serde_json = { workspace = true }
serde = { workspace = true }
diff --git a/crates/eval/src/cache.rs b/crates/eval/src/cache.rs
index 2621a8ff..f9807538 100644
--- a/crates/eval/src/cache.rs
+++ b/crates/eval/src/cache.rs
@@ -1,13 +1,19 @@
-use crate::NodeOutput;
+use crate::{NodeOutput, ResolvedBaseParameters};
use std::collections::HashMap;
use std::sync::Arc;
const DEFAULT_LIMIT_BYTES: usize = 256 << 20;
const MAX_ENTRIES: usize = 8192;
+#[derive(Clone)]
+pub(crate) struct CachedOutputs {
+ pub values: Arc>,
+ pub bases: Option>,
+}
+
/// LRU cache of node outputs, bounded by bytes
pub struct Cache {
- entries: HashMap>, usize, u64)>,
+ entries: HashMap,
bytes: usize,
cap: usize,
tick: u64,
@@ -48,7 +54,7 @@ impl Cache {
self.bytes = 0;
}
- pub(crate) fn get(&mut self, key: u64) -> Option>> {
+ pub(crate) fn get(&mut self, key: u64) -> Option {
self.tick = self.tick.saturating_add(1);
let tick = self.tick;
self.entries.get_mut(&key).map(|entry| {
@@ -57,15 +63,16 @@ impl Cache {
})
}
- pub(crate) fn put(&mut self, key: u64, outputs: Arc>) {
- let size = outputs.iter().fold(0_usize, |total, output| total.saturating_add(output.memory_bytes()));
+ pub(crate) fn put(&mut self, key: u64, outputs: Arc>, bases: Option>) {
+ let metadata = bases.as_deref().map_or(0, std::mem::size_of_val);
+ let size = outputs.iter().fold(metadata, |total, output| total.saturating_add(output.memory_bytes()));
if let Some(old) = self.entries.remove(&key) {
self.bytes = self.bytes.saturating_sub(old.1);
}
// Oversized results remain owned by their cooks
// Empty results would permit unbounded zero-byte cache metadata
- if size == 0 || size > self.cap {
+ if outputs.is_empty() || size == 0 || size > self.cap {
return;
}
@@ -77,7 +84,7 @@ impl Cache {
}
self.tick = self.tick.saturating_add(1);
- self.entries.insert(key, (outputs, size, self.tick));
+ self.entries.insert(key, (CachedOutputs { values: outputs, bases }, size, self.tick));
self.bytes += size;
}
}
diff --git a/crates/eval/src/cache.test.rs b/crates/eval/src/cache.test.rs
index 0e26792d..0a01f217 100644
--- a/crates/eval/src/cache.test.rs
+++ b/crates/eval/src/cache.test.rs
@@ -8,10 +8,10 @@ fn output(side: u32) -> Arc> {
#[test]
fn oversized_results_are_not_retained_or_allowed_to_flush_useful_entries() {
let mut cache = Cache::new(64);
- cache.put(1, output(4));
+ cache.put(1, output(4), None);
let large = output(8);
let weak = Arc::downgrade(&large);
- cache.put(2, large);
+ cache.put(2, large, None);
assert!(weak.upgrade().is_none());
assert!(cache.get(1).is_some());
@@ -22,12 +22,12 @@ fn oversized_results_are_not_retained_or_allowed_to_flush_useful_entries() {
#[test]
fn disabled_and_empty_caches_do_not_retain_outputs_or_metadata() {
let mut cache = Cache::new(0);
- cache.put(1, output(4));
+ cache.put(1, output(4), None);
assert!(cache.is_empty());
for key in 0..10_000 {
- cache.put(key, Arc::new(Vec::new()));
+ cache.put(key, Arc::new(Vec::new()), None);
}
assert!(cache.is_empty());
@@ -38,18 +38,18 @@ fn repeated_edits_release_evicted_buffers_and_keep_recent_hits() {
let mut cache = Cache::new(128);
let first = output(4);
let first_weak = Arc::downgrade(&first);
- cache.put(0, first);
- cache.put(1, output(4));
+ cache.put(0, first, None);
+ cache.put(1, output(4), None);
assert!(cache.get(0).is_some());
- cache.put(2, output(4));
+ cache.put(2, output(4), None);
assert!(cache.get(1).is_none());
assert!(first_weak.upgrade().is_some());
for key in 3..1_000 {
- cache.put(key, output(4));
+ cache.put(key, output(4), None);
assert!(cache.bytes() <= 128);
assert!(cache.len() <= 2);
diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs
index 40e0b741..c4fb360a 100644
--- a/crates/eval/src/cache_key.rs
+++ b/crates/eval/src/cache_key.rs
@@ -50,6 +50,10 @@ pub(crate) fn graph_tree_hash(package: &Package, graph_index: usize) -> u64 {
graph_tree_hash_with_registry(package, package, graph_index)
}
+pub(crate) fn resource_parameter(node: &Node) -> &'static str {
+ if node.def == "text" { "fontdata" } else { "resource" }
+}
+
pub(crate) fn graph_tree_hash_with_registry(registry: &Package, package: &Package, graph_index: usize) -> u64 {
let mut hasher = DefaultHasher::new();
let mut pending = vec![(package, graph_index)];
@@ -79,7 +83,14 @@ pub(crate) fn graph_tree_hash_with_registry(registry: &Package, package: &Packag
}
for node in &graph.nodes {
- if let Some(Value::Text(name)) = node.params.get("resource") {
+ let parameter = resource_parameter(node);
+ if node.bindings.contains_key(parameter) || node.functions.contains_key(parameter) {
+ // The caller may select another package resource when this instance runs.
+ for resource in &package.resources {
+ resource.name.hash(&mut hasher);
+ resource.bytes.content_hash().hash(&mut hasher);
+ }
+ } else if let Some(Value::Text(name)) = node.params.get(parameter) {
package.resource(name).map(|resource| resource.bytes.content_hash()).hash(&mut hasher);
}
if node.def == "graph_instance"
@@ -93,12 +104,14 @@ pub(crate) fn graph_tree_hash_with_registry(registry: &Package, package: &Packag
hasher.finish()
}
-pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, variables: &BTreeMap) -> u64 {
+pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, variables: &dyn materialcraft_nodes::GraphVariables) -> u64 {
let mut hasher = DefaultHasher::new();
let mut names = std::collections::BTreeSet::new();
let mut pending: Vec<&Value> = parameters.values().collect();
while let Some(value) = pending.pop() {
match value {
+ // JSON represents all non-finite numbers as null. Their signs change pattern blending.
+ Value::Float(v) if !v.is_finite() => v.to_bits().hash(&mut hasher),
Value::Function(graph) => {
let mut pending = vec![graph.as_ref()];
while let Some(graph) = pending.pop() {
@@ -114,10 +127,12 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, va
Some(Err(error)) => error.hash(&mut hasher),
None => {}
}
- if (function_node.op.starts_with("get_") || function_node.op == "isdefined")
- && let Some(Value::Text(name)) = &function_node.value
- {
- names.insert(name.as_str());
+ if let Some(Value::Text(name)) = &function_node.value {
+ if function_node.op.starts_with("get_") {
+ names.insert(name.strip_prefix('%').unwrap_or(name));
+ } else if function_node.op == "isdefined" {
+ names.insert(name.as_str());
+ }
}
}
}
@@ -137,6 +152,10 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, va
for name in names {
name.hash(&mut hasher);
variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher);
+ variables.literal_inputs().iter().any(|input| input == name).hash(&mut hasher);
+ if node.def == "fx_map" {
+ variables.assigned_integers().iter().any(|input| input == name).hash(&mut hasher);
+ }
}
hasher.finish()
diff --git a/crates/eval/src/cooked.rs b/crates/eval/src/cooked.rs
index 3c7e0759..0d2fedd2 100644
--- a/crates/eval/src/cooked.rs
+++ b/crates/eval/src/cooked.rs
@@ -7,6 +7,7 @@ use std::collections::BTreeMap;
#[derive(Clone, Debug, Default)]
pub struct Cooked {
pub nodes: BTreeMap,
+ pub preview_sampling: Option>,
/// Total wall time of the cook in milliseconds
pub ms: f32,
pub cancelled: bool,
diff --git a/crates/eval/src/external_image.rs b/crates/eval/src/external_image.rs
new file mode 100644
index 00000000..6bfc7553
--- /dev/null
+++ b/crates/eval/src/external_image.rs
@@ -0,0 +1,255 @@
+use crate::NodeOutput;
+use craft_texture::{Image, Kind, Limits, MAX_SIDE};
+use materialcraft_core::{OutputFormat, Package};
+use materialcraft_nodes::CookContext;
+
+/// A power-of-two resize after a bitmap's initial conversion leaves only its base texture level.
+pub(super) fn base_level_only(image: &Image, size: (u32, u32), kind: Kind, source: OutputFormat, output: OutputFormat) -> bool {
+ let axes = [(image.width(), size.0), (image.height(), size.1)];
+ if image.kind() != kind || !axes.iter().all(|(a, b)| a.is_power_of_two() && b.is_power_of_two()) {
+ return false;
+ }
+ let [horizontal, vertical] = axes.map(|(a, b)| a.trailing_zeros().abs_diff(b.trailing_zeros()));
+ let depth = |format| if format == OutputFormat::Inherit { OutputFormat::U16 } else { format };
+ horizontal.max(vertical) > u32::from(depth(source) != depth(output))
+}
+
+/// Odd-sized normalized PNG resources use the same stored and sampled levels as bound rasters.
+pub(super) fn resize_bitmap(context: &CookContext, package: &Package) -> Option {
+ let grayscale = !context.b("color_mode");
+ if !grayscale && context.bitmap_color_space() == materialcraft_nodes::BitmapColorSpace::Srgb {
+ return None;
+ }
+ let name = context.text("resource");
+ let resource = package.resource(name)?;
+ let info = materialcraft_core::png_raster_info(resource.bytes.as_slice())?;
+ let [width, height] = info.size;
+ // Check the header first so ordinary power-of-two bitmaps still request their decoded image only once.
+ if info.grayscale != grayscale || (width.is_power_of_two() && height.is_power_of_two()) || (width, height) == (context.w, context.h) {
+ return None;
+ }
+ let image = context.bitmap_resource(name)?;
+ let kind = if grayscale { Kind::Gray } else { Kind::Color };
+ resize(&image, (context.w, context.h), kind, info.format, context.format)
+}
+
+/// Non-power-of-two external rasters filter each axis directly, storing the result between passes.
+pub(super) fn resize(image: &Image, size: (u32, u32), kind: Kind, source: OutputFormat, output: OutputFormat) -> Option {
+ let size = craft_texture::clamp_size(size.0, size.1);
+ let (width, height) = (image.width(), image.height());
+ if (width.is_power_of_two() && height.is_power_of_two()) || (width, height) == size || width.max(height) > MAX_SIDE || image.kind() != kind {
+ return None;
+ }
+ let input_levels: Option = match (image.integer_sampling(), source) {
+ (true, OutputFormat::U8) => Some(255.0),
+ (true, OutputFormat::U16) => Some(65535.0),
+ (false, OutputFormat::F32) => None,
+ _ => return None,
+ };
+ let output_levels = match output {
+ OutputFormat::U8 => Some(255.0),
+ OutputFormat::Inherit | OutputFormat::U16 => Some(65535.0),
+ OutputFormat::F32 | OutputFormat::F16 => None,
+ };
+ // Keep the lower channel depth through both filter passes. A byte raster sent to
+ // a word or float output still filters at byte precision.
+ let maximum = match (input_levels, output_levels) {
+ (Some(source), Some(output)) => Some(source.min(output)),
+ (source, output) => source.or(output),
+ };
+ let mut filtered = match (input_levels, maximum) {
+ (Some(source), Some(working)) if source == working => image.map(kind, |pixel| pixel.map(|v| (v * source).round())),
+ (_, Some(working)) => dither(image, working, input_levels.is_some())?,
+ _ => image.clone(),
+ };
+ let (w, h) = size;
+ let passes = if w <= width { [(true, w), (false, h)] } else { [(false, h), (true, w)] };
+ for (horizontal, end) in passes {
+ filtered = filter_axis(filtered, horizontal, end, maximum.is_some());
+ }
+ if output == OutputFormat::F16 {
+ return match source {
+ OutputFormat::U8 => {
+ let texture = filtered.map(kind, |p| p.map(|v| v / 255.0)).with_integer_sampling(true);
+ let stored = crate::output_precision::apply(texture.clone(), OutputFormat::F16);
+ Some(NodeOutput::BoundBitmap { stored, texture, texture_format: source })
+ }
+ OutputFormat::U16 => word_to_half(&filtered).map(NodeOutput::Image),
+ // Float rasters are filtered at full precision before the half writer diffuses its rounding error.
+ _ => diffuse(&filtered, |original, received| {
+ let stored = nearest_positive_half(original + received);
+ (stored, original - stored)
+ })
+ .map(NodeOutput::Image),
+ };
+ }
+ let Some(maximum) = maximum else { return Some(NodeOutput::Image(filtered)) };
+ let stored = filtered.map(kind, |p| p.map(|v| v / maximum)).with_integer_sampling(output_levels.is_some());
+ if input_levels.is_some() && output_levels.is_none_or(|levels| levels > maximum) {
+ // A wider bridge can report the same normalized values as the source, yet interpolation
+ // still rounds the weighted sum to normalized integer levels.
+ let texture = stored.clone().with_integer_sampling(true);
+ Some(NodeOutput::BoundBitmap { stored, texture, texture_format: source })
+ } else {
+ Some(NodeOutput::Image(stored))
+ }
+}
+
+fn nearest_positive_half(value: f32) -> f32 {
+ let value = value.max(0.0);
+ let nearest = half::f16::from_f32(value);
+ let lower = nearest.to_f32();
+ if lower < value {
+ let upper = half::f16::from_bits(nearest.to_bits() + 1).to_f32();
+ // The bitmap writer rounds a midpoint to the larger half, including at the subnormal boundary.
+ if value - lower == upper - value {
+ return upper;
+ }
+ }
+ lower
+}
+
+fn filter_axis(image: Image, horizontal: bool, end: u32, integer: bool) -> Image {
+ let start = if horizontal { image.width() } else { image.height() };
+ if start == end {
+ return image;
+ }
+ let scale = f64::from(end) / f64::from(start);
+ let filter_scale = scale.min(1.0);
+ let radius = 1.0 / filter_scale;
+ let taps: Vec<_> = (0..end)
+ .map(|index| {
+ // On enlargement the mapped origin and half-texel offset round independently.
+ let center = if end > start { f64::from(index) / scale + 0.5 / scale } else { (f64::from(index) + 0.5) / scale };
+ let first = (center - 0.5 - radius).ceil().max(0.0) as u32;
+ let last = ((center - 0.5 + radius).floor() as u32).min(start - 1);
+ // Keep the downsampling factor through normalization. Cancelling it changes rounding at close texels.
+ let mut weights: Vec<_> = (first..=last).map(|i| filter_scale * (1.0 - (f64::from(i) + 0.5 - center).abs() * filter_scale).max(0.0)).collect();
+ let sum: f64 = weights.iter().sum();
+ for w in &mut weights {
+ *w /= sum;
+ }
+ (first, weights)
+ })
+ .collect();
+ let (w, h) = if horizontal { (end, image.height()) } else { (image.width(), end) };
+ Image::generate(w, h, image.kind(), |x, y| {
+ let index = if horizontal { x } else { y };
+ let (first, weights) = &taps[index as usize];
+ let mut sum = [0.0_f64; 4];
+ for (offset, &weight) in weights.iter().enumerate() {
+ if weight == 0.0 {
+ continue;
+ }
+ let pos = i64::from(*first) + offset as i64;
+ let pixel = if horizontal { image.get(pos, i64::from(y), false) } else { image.get(i64::from(x), pos, false) };
+ for (value, channel) in sum.iter_mut().zip(pixel) {
+ *value += f64::from(channel) * weight;
+ }
+ }
+ sum.map(|v| if integer { v.round() as f32 } else { v as f32 })
+ })
+}
+
+fn next_fraction(state: &mut u64) -> f32 {
+ *state = (48_271 * *state) % 2_147_483_647;
+ (*state as f64 / 2_147_483_647.0) as f32
+}
+
+fn word_to_half(image: &Image) -> Option {
+ let mut state = 1_u64;
+ diffuse(image, |original, received| {
+ let original = f32::from(original as u16);
+ let word = (original + received + (next_fraction(&mut state) - 0.5) * 16.0) as u16;
+ let (stored, reconstructed) = match word {
+ // The low-end conversion has distinct readback and error values at word three.
+ 0..=2 => (0.0, 0.0),
+ 3 => (2.0 / 65536.0, 3.0),
+ _ => {
+ let stored = crate::output_precision::store_half(f32::from(word) / 65535.0);
+ (stored, (stored * 65536.0).min(65535.0))
+ }
+ };
+ (stored, original - reconstructed)
+ })
+}
+
+fn dither(image: &Image, maximum: f32, word_to_byte: bool) -> Option {
+ let mut state = 1_u64;
+ let unit = maximum.recip();
+ let limit = f32::MAX / (4.0 * maximum);
+ diffuse(image, |value, received| {
+ let random = next_fraction(&mut state);
+ let original = if value.is_finite() { value.clamp(-limit, limit) } else { f32::from(value > 0.0) };
+ let stored = if word_to_byte {
+ // One full byte level expands to 257 word levels. The noise spans one high-byte step.
+ let word = (original * 65535.0).round();
+ ((word + received * 257.0 + (random - 0.5) * 256.0) / 256.0).floor()
+ } else {
+ // The byte writer adds noise in units of 1/256. Diffused error stays in 1/255 units.
+ let offset = if maximum == 255.0 { received * unit + (random - 0.5) / 256.0 } else { (received + (random - 0.5)) * unit };
+ ((original + offset) * maximum).round()
+ }
+ .clamp(0.0, maximum);
+ (stored, original * maximum - stored)
+ })
+}
+
+fn diffuse(image: &Image, mut quantize: impl FnMut(f32, f32) -> (f32, f32)) -> Option {
+ let width = usize::try_from(image.width()).ok()?;
+ let channels = image.channels();
+ let mut samples = Vec::new();
+ samples.try_reserve_exact(image.data().len()).ok()?;
+ samples.extend_from_slice(image.data());
+ let mut errors: [_; 3] = std::array::from_fn(|_| vec![[0.0_f32; 4]; width + 4]);
+ for (y, row) in samples.chunks_exact_mut(width * channels).enumerate() {
+ let current = y % 3;
+ for (x, pixel) in row.chunks_exact_mut(channels).enumerate() {
+ let mut error = [0.0; 4];
+ for (c, value) in pixel.iter_mut().enumerate() {
+ (*value, error[c]) = quantize(*value, errors[current][x + 2][c]);
+ }
+ // Two extra columns on each end absorb error outside the image. Propagate the
+ // original quantization error once, with the three-row Sierra filter.
+ for (dy, column, weight) in [
+ (0, x + 3, 5),
+ (0, x + 4, 3),
+ (1, x, 2),
+ (1, x + 1, 4),
+ (1, x + 2, 5),
+ (1, x + 3, 4),
+ (1, x + 4, 2),
+ (2, x + 1, 2),
+ (2, x + 2, 3),
+ (2, x + 3, 2),
+ ] {
+ let dst = &mut errors[(current + dy) % 3][column];
+ for (v, e) in dst.iter_mut().zip(error).take(channels) {
+ *v += e * (weight as f32 / 32.0);
+ }
+ }
+ }
+ errors[current].fill([0.0; 4]);
+ }
+ Image::from_data(image.width(), image.height(), image.kind(), samples, &Limits::default()).ok()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn odd_float_rasters_keep_exact_byte_levels_and_dither_fractional_levels() {
+ let level = 128.0 / 255.0;
+ let flat = Image::filled(256, 3, Kind::Color, [level; 4]);
+ let out = resize(&flat, (256, 4), Kind::Color, OutputFormat::F32, OutputFormat::U8).unwrap();
+ assert!(out.as_image().unwrap().data().iter().all(|&v| v == level));
+
+ let ramp = Image::generate(256, 3, Kind::Color, |x, _| [(51.0 + x as f32 / 256.0) / 255.0; 4]);
+ let out = resize(&ramp, (256, 4), Kind::Color, OutputFormat::F32, OutputFormat::U8).unwrap();
+ let image = out.as_image().unwrap();
+ for (x, y, channel, expected) in [(16, 1, 1, 51), (219, 1, 2, 52), (18, 3, 1, 52), (105, 3, 3, 51)] {
+ assert_eq!((image.get(x, y, false)[channel] * 255.0).round() as u8, expected);
+ }
+ }
+}
diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs
index 5ad60d26..82217706 100644
--- a/crates/eval/src/graph_execution.rs
+++ b/crates/eval/src/graph_execution.rs
@@ -7,14 +7,52 @@ use std::{
sync::{Mutex, atomic::Ordering},
};
+/// Resolve a document graph's output dimensions without allocating or cooking its textures.
+pub fn graph_output_size(graph: &materialcraft_core::Graph, environment: materialcraft_core::EvaluationEnvironment) -> Result<[u32; 2], String> {
+ if graph.output_size_function.is_none() {
+ return Ok(graph.size_px());
+ }
+ let mut options = Options::new(&|_| None);
+ options.environment = environment;
+ let mut base = crate::ResolvedBaseParameters::graph(graph, &options);
+ base.evaluate_graph_size(graph, &options, &graph_variables(graph, &options))?;
+ Ok(base.size)
+}
+
pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mutex) -> Cooked {
let started_ms = now_ms();
let mut cooked = Cooked::default();
let Some(graph) = package.graphs.get(graph_index) else { return cooked };
let mut previews = BTreeMap::new();
- let prepared = PreparedGraph::new(package, graph, options);
+ let variables = graph_variables(graph, options);
+ let prepared = PreparedGraph::new(package, graph, options, &variables);
+ let mut sampling = crate::PreviewSampling::default();
+ sampling.context = (prepared.parent_base.size, prepared.parent_base.seed, options.max_size);
+ sampling.caller_format = options.parent_base.map(|base| base.format);
+ let previous = options.previous_sampling.filter(|p| p.context == sampling.context);
+ for &id in &prepared.order {
+ if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
+ cooked.cancelled = true;
+ break;
+ }
+
+ let Some(node) = prepared.index.node(id) else { continue };
+
+ let input = input_image(graph, node, options, &mut previews);
+ let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, input, cache, previous, &mut sampling);
+ cooked.nodes.insert(id, result);
+ }
+
+ cooked.ms = (now_ms() - started_ms) as f32;
+ if !sampling.is_empty() && !cooked.cancelled && cooked.nodes.values().all(|result| result.error.is_none()) {
+ cooked.preview_sampling = Some(std::sync::Arc::new(sampling));
+ }
+ cooked
+}
+
+fn graph_variables(graph: &materialcraft_core::Graph, options: &Options) -> BTreeMap {
// Exposed parameter values: the graph's own, then the caller's overrides
let mut variables: BTreeMap =
graph.exposed.iter().filter_map(|exposed| graph.input_value(&exposed.id).map(|value| (exposed.id.clone(), value.clone()))).collect();
@@ -25,22 +63,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu
variables.insert("$uvtile".into(), Value::Int2(options.environment.uv_tile));
variables.insert("$normalformat".into(), Value::Int(options.environment.normal_format));
variables.insert("$physicalsize".into(), Value::Float3(graph.physical_size));
-
- for &id in &prepared.order {
- if options.cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
- cooked.cancelled = true;
- break;
- }
-
- let Some(node) = prepared.index.node(id) else { continue };
-
- let input = input_image(graph, node, options, &mut previews);
- let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, input, cache);
- cooked.nodes.insert(id, result);
- }
-
- cooked.ms = (now_ms() - started_ms) as f32;
- cooked
+ variables
}
fn input_image<'a>(graph: &Graph, node: &Node, options: &'a Options<'_>, previews: &'a mut BTreeMap>) -> Option<&'a Image> {
@@ -54,8 +77,14 @@ fn input_image<'a>(graph: &Graph, node: &Node, options: &'a Options<'_>, preview
}
let resource = graph.input_images.get(&identifier)?;
- let linear = graph.input_images_linear.contains(&identifier);
+ let space = if graph.input_images_from_file.contains(&identifier) {
+ materialcraft_nodes::BitmapColorSpace::FromFile
+ } else if graph.input_images_linear.contains(&identifier) {
+ materialcraft_nodes::BitmapColorSpace::Linear
+ } else {
+ materialcraft_nodes::BitmapColorSpace::Srgb
+ };
// Nodes sharing an input also share its first lookup, including a missing preview
- previews.entry(identifier).or_insert_with(|| (options.resource)(&craft_texture::resource_key(resource, linear))).as_ref()
+ previews.entry(identifier).or_insert_with(|| (options.resource)(&space.resource_key(resource))).as_ref()
}
diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs
index d11e671b..f876e3a1 100644
--- a/crates/eval/src/graph_instance.rs
+++ b/crates/eval/src/graph_instance.rs
@@ -36,19 +36,26 @@ pub(crate) fn instances_reach(pkg: &Package, from: usize, target: usize) -> bool
false
}
+pub(crate) struct CookedInstance {
+ pub ports: Vec<(NodeOutput, crate::ResolvedBaseParameters)>,
+ pub sampling: Option<(std::sync::Arc, u64)>,
+}
+
pub(crate) fn cook_instance(
package: &Package,
graph_index: usize,
node: &Node,
input_ports: &[Port],
output_ports: &[Port],
- inputs: &[Option<&NodeOutput>],
+ inputs: &[Option<(&NodeOutput, crate::ResolvedBaseParameters)>],
+ input_keys: &[u64],
params: &BTreeMap,
- size: (u32, u32),
+ fixed: &[String],
base: crate::resolved_base_parameters::ResolvedBaseParameters,
options: &Options,
cache: &Mutex,
-) -> Result, String> {
+ previous: Option<&crate::PreviewSampling>,
+) -> Result {
if options.depth >= MAX_DEPTH {
return Err("graph instances nest too deep (does a graph use itself?)".into());
}
@@ -67,12 +74,14 @@ pub(crate) fn cook_instance(
let root_resource = options.resource_root.unwrap_or(options.resource);
let resource = |name: &str| match &node.instance {
Some(instance) if !instance.package.is_empty() => {
- let (name, linear) = craft_texture::split_resource_key(name);
- root_resource(&craft_texture::resource_key(&format!("{}\0{name}", instance.package), linear))
+ let (name, space) = materialcraft_nodes::BitmapColorSpace::split_resource_key(name);
+ root_resource(&space.resource_key(&format!("{}\0{name}", instance.package)))
}
_ => (options.resource)(name),
};
let mut source_options = Options::new(&resource);
+ let empty = crate::PreviewSampling::default();
+ source_options.previous_sampling = options.previous_sampling.map(|_| previous.unwrap_or(&empty));
source_options.environment = options.environment;
source_options.parent_tiling = Some(base.tiling);
source_options.parent_pixel_ratio = Some(base.pixel_ratio);
@@ -85,9 +94,42 @@ pub(crate) fn cook_instance(
source_options.graph_stack = options.graph_stack.clone();
source_options.graph_stack.push(identity);
source_options.only = Some(source_graph.nodes.iter().filter(|node| node.def == "output").map(|node| node.id).collect());
- source_options.inputs = input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_image()?.clone()))).collect();
source_options.overrides = params.iter().filter(|(k, _)| source_graph.exposed.iter().any(|e| &e.id == *k)).map(|(k, v)| (k.clone(), v.clone())).collect();
- source_options.overrides.extend(input_ports.iter().zip(inputs).filter_map(|(port, input)| Some((port.id.clone(), input.as_ref()?.as_value()?.clone()))));
+ for exposed in &source_graph.exposed {
+ let name = &exposed.id;
+ if fixed.contains(name) || (!params.contains_key(name) && source_graph.input_value(name).is_some_and(crate::parameter::supports_literal_argument)) {
+ source_options.literal_inputs.push(name.clone());
+ }
+ }
+ for ((port, input), &key) in input_ports.iter().zip(inputs).zip(input_keys) {
+ // A stored argument drives its bridge even when the same port has a wire.
+ if let Some(expected) = port.value_type
+ && (node.params.contains_key(&port.id) || node.bindings.contains_key(&port.id) || node.functions.contains_key(&port.id))
+ && let Some(value) = params.get(&port.id)
+ {
+ if materialcraft_core::ValueType::of(value) != Some(expected) {
+ return Err(format!("input `{}` requires {}", port.id, expected.label()));
+ }
+ source_options.overrides.insert(port.id.clone(), value.clone());
+ source_options.literal_inputs.retain(|name| name != &port.id);
+ continue;
+ }
+ let Some((output, source_base)) = input else { continue };
+ if let Some((image, texture_format)) = output.texture(source_base.format) {
+ source_options.inputs.insert(port.id.clone(), image.clone());
+ source_options.input_formats.insert(port.id.clone(), texture_format);
+ source_options.input_bases.insert(port.id.clone(), *source_base);
+ if matches!(output, NodeOutput::BaseLevel(_)) {
+ source_options.base_level_inputs.insert(port.id.clone());
+ if source_options.previous_sampling.is_some() {
+ source_options.preview_input_keys.insert(port.id.clone(), key);
+ }
+ }
+ } else if let Some(value) = output.as_value() {
+ source_options.overrides.insert(port.id.clone(), value.clone());
+ source_options.literal_inputs.retain(|name| name != &port.id);
+ }
+ }
let cooked = cook(source, source_graph_index, &source_options, cache);
if cooked.cancelled {
return Err("cancelled".into());
@@ -97,20 +139,25 @@ pub(crate) fn cook_instance(
return Err(format!("{}: {error}", source_graph.name));
}
- output_ports
+ let mut keys = Vec::new();
+ let ports = output_ports
.iter()
.map(|port| {
- let output = source_graph
+ let result = source_graph
.nodes
.iter()
.find(|candidate| candidate.def == "output" && identifier(candidate) == port.id)
.and_then(|node| cooked.nodes.get(&node.id))
- .and_then(|result| result.outputs.first())
.ok_or_else(|| format!("the source output `{}` is missing", port.id))?;
- Ok(match output {
- NodeOutput::Image(image) => NodeOutput::Image(image.resize(size.0, size.1, true)),
- NodeOutput::Value(value) => NodeOutput::Value(value.clone()),
- })
+ let output = result.outputs.first().ok_or_else(|| format!("the source output `{}` is empty", port.id))?;
+ if cooked.preview_sampling.is_some() {
+ keys.push(result.key);
+ }
+ // Images carry their source properties across the boundary. The caller owns the random seed.
+ let port_base = crate::ResolvedBaseParameters { seed: base.seed, ..result.base };
+ Ok((output.clone(), port_base))
})
- .collect()
+ .collect::>()?;
+ let sampling = cooked.preview_sampling.map(|state| (state, crate::cache_key::hash_of(&keys)));
+ Ok(CookedInstance { ports, sampling })
}
diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs
index 780a9d03..9ba280fa 100644
--- a/crates/eval/src/lib.rs
+++ b/crates/eval/src/lib.rs
@@ -4,6 +4,7 @@
mod cache;
mod cache_key;
mod cooked;
+mod external_image;
mod graph_execution;
mod graph_instance;
mod graph_output;
@@ -13,12 +14,13 @@ mod node_output;
mod node_result;
mod node_size;
mod options;
-mod output_precision;
+use materialcraft_nodes::output_precision;
mod parameter;
mod parameter_function;
mod port;
mod ports;
mod prepared_graph;
+mod preview_sampling;
mod resolved_base_parameters;
mod resource_decoder;
mod time;
@@ -27,7 +29,7 @@ mod value_input_label;
pub use cache::Cache;
pub use cooked::Cooked;
-pub use graph_execution::cook;
+pub use graph_execution::{cook, graph_output_size};
pub use graph_output::{output_usage, outputs};
pub use node_execution::error_image;
pub use node_output::NodeOutput;
@@ -36,6 +38,7 @@ pub use node_size::node_size;
pub use options::Options;
pub use port::Port;
pub use ports::{identifier, instance_graph, ports, ports_with_connections};
+pub use preview_sampling::PreviewSampling;
pub use resolved_base_parameters::ResolvedBaseParameters;
pub use resource_decoder::ResourceDecoder;
pub use time::now_ms;
diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs
index 2ffeb294..a7bd0d3a 100644
--- a/crates/eval/src/node_execution.rs
+++ b/crates/eval/src/node_execution.rs
@@ -2,18 +2,38 @@ use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, now_ms};
use crate::{
cache_key::{graph_tree_hash_with_registry, hash_of, image_key, variable_key},
graph_instance::cook_instance,
- parameter::resolve_parameters,
+ parameter::{ResolvedParameters, inspection_parameters, resolve_parameters},
prepared_graph::PreparedGraph,
value_execution::evaluate_value,
};
use craft_texture::{Image, Kind};
-use materialcraft_core::{Node, Package, Value};
-use materialcraft_nodes::{CookContext, find};
+use materialcraft_core::{Node, OutputFormat, Package, Value};
+use materialcraft_nodes::{CookContext, GraphVariables, find};
use std::{
collections::BTreeMap,
sync::{Arc, Mutex},
};
+struct BoundVariables<'a> {
+ values: &'a BTreeMap,
+ fixed: &'a [String],
+ assigned_integers: &'a [String],
+}
+
+impl GraphVariables for BoundVariables<'_> {
+ fn graph_values(&self) -> &BTreeMap {
+ self.values
+ }
+
+ fn literal_inputs(&self) -> &[String] {
+ self.fixed
+ }
+
+ fn assigned_integers(&self) -> &[String] {
+ self.assigned_integers
+ }
+}
+
/// The magenta image a failed node shows
pub fn error_image(w: u32, h: u32) -> Image {
Image::filled(w, h, Kind::Color, [1.0, 0.0, 1.0, 1.0])
@@ -34,34 +54,33 @@ pub(crate) fn cook_node(
options: &Options,
input_image: Option<&Image>,
cache: &Mutex,
+ previous: Option<&crate::PreviewSampling>,
+ sampling: &mut crate::PreviewSampling,
) -> NodeResult {
let (input_ports, output_ports) = prepared.ports(node.id);
let definition = find(&node.def);
// Gather inputs by port order, with their keys
let mut inputs = Vec::new();
+ let mut input_formats = Vec::new();
let mut incoming = Vec::new();
let mut input_keys = Vec::new();
+ let mut base_level_only = [false; materialcraft_nodes::MAX_IMAGE_INPUTS + 1];
+ let mut background_source = None;
let mut variables = std::borrow::Cow::Borrowed(graph_variables);
+ let mut fixed = std::borrow::Cow::Borrowed(options.literal_inputs.as_slice());
let mut input_error = None;
for port in input_ports {
- let source = prepared.index.input_of(node.id, &port.id).and_then(|connection| {
+ let connection = prepared.index.input_of(node.id, &port.id);
+ let source = connection.and_then(|connection| {
let result = cooked.nodes.get(&connection.from)?;
let index = prepared.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?;
- Some((result.outputs.get(index)?, result.key ^ hash_of(&index)))
+ Some((result.outputs.get(index)?, result.key ^ hash_of(&index), result.output_base(index)?))
});
input_keys.push(source.as_ref().map_or(0, |source| source.1));
let output = source.map(|source| source.0);
- let expected = node.input_values.get(&port.id).copied().or_else(|| {
- node.instance
- .as_ref()?
- .inputs
- .iter()
- .find(|input| input.identifier == port.id)
- .and_then(|input| materialcraft_core::ValueType::from_code(input.type_code))
- });
- if let Some(expected) = expected {
+ if let Some(expected) = port.value_type {
let value = match output.as_ref() {
Some(NodeOutput::Value(value)) if materialcraft_core::ValueType::of(value) == Some(expected) => value.clone(),
Some(_) => {
@@ -72,22 +91,65 @@ pub(crate) fn cook_node(
};
variables.to_mut().insert(port.id.clone(), value);
+ if fixed.contains(&port.id) {
+ fixed.to_mut().retain(|name| name != &port.id);
+ }
} else {
if output.as_ref().is_some_and(|output| output.as_value().is_some()) && !matches!(node.def.as_str(), "output" | "dot") {
input_error = Some(format!("input `{}` requires an image", port.id));
}
- inputs.push(output.and_then(NodeOutput::as_image).cloned());
+ let wired = if options.depth != 0 && matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map" | "blur" | "directional_blur") {
+ connection.and_then(|edge| prepared.index.node(edge.from)).and_then(|bridge| wired_texture(options, bridge))
+ } else {
+ None
+ };
+ if node.def == "fx_map"
+ && let Some(level) = base_level_only.get_mut(incoming.len())
+ {
+ *level = wired.map_or(matches!(output, Some(NodeOutput::BaseLevel(_))), |(_, _, base_level)| base_level);
+ if port.id == "background" {
+ background_source = if wired.is_some() {
+ connection.and_then(|edge| prepared.index.node(edge.from)).and_then(|bridge| options.input_bases.get(&identifier(bridge))).copied()
+ } else {
+ source.map(|(_, _, base)| base)
+ };
+ }
+ }
+ let stored = source.and_then(|(output, _, base)| output.texture(base.format));
+ let image = wired.map(|(image, format, _)| (image, format)).or(stored);
+ inputs.push(image.map(|(image, _)| image.clone()));
+ input_formats.push(image.map_or(OutputFormat::F32, |(_, format)| format));
}
- incoming.push(output);
+ incoming.push(source.map(|(output, _, base)| (output, base)));
}
- let input_base = prepared.input_base(node.id, cooked);
- let (mut base, base_values, base_error) = match crate::resolved_base_parameters::evaluate(&node.base, input_base, prepared.parent_base, &mut variables) {
- Ok((base, values)) => (base, values, None),
- Err(error) => (crate::ResolvedBaseParameters::resolve(&node.base, input_base, prepared.parent_base), BTreeMap::new(), Some(error)),
- };
+ let input_base = prepared.input_base(node.id, cooked).or_else(|| {
+ if !matches!(node.def.as_str(), "input_color" | "input_grayscale") {
+ return None;
+ }
+ let source = options.input_bases.get(&identifier(node))?;
+ // Relative-to-input size follows this wire. The bridge still resolves its own storage precision.
+ Some(crate::ResolvedBaseParameters {
+ size: source.size,
+ size_underflow: source.size_underflow,
+ dynamic_size: source.dynamic_size,
+ bound_size: source.bound_size,
+ pixel_size: source.pixel_size,
+ pixel_ratio: source.pixel_ratio,
+ tiling: source.tiling,
+ bound_image: source.bound_image,
+ ..prepared.parent_base
+ })
+ });
+ let mut assigned_integers = Vec::new();
+ let mut pattern_writes = (node.def == "fx_map").then_some(&mut assigned_integers);
+ let (mut base, base_values, base_error) =
+ match crate::resolved_base_parameters::evaluate(&node.base, input_base, prepared.parent_base, &mut variables, &fixed, pattern_writes.as_deref_mut()) {
+ Ok((base, values)) => (base, values, None),
+ Err(error) => (crate::ResolvedBaseParameters::resolve(&node.base, input_base, prepared.parent_base), BTreeMap::new(), Some(error)),
+ };
if node.disabled
&& let Some(input) = input_base
@@ -101,14 +163,15 @@ pub(crate) fn cook_node(
base_values: base_values.clone(),
parameters: BTreeMap::new(),
outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); output_ports.len().max(1)]),
+ output_bases: None,
error: Some(message),
ms: 0.0,
key,
cached: false,
};
- if let Some(error) = base_error {
- return fail(error, 0);
+ if let Some(error) = prepared.base_error.as_ref().or(base_error.as_ref()) {
+ return fail(error.clone(), 0);
}
if let Some(error) = input_error {
@@ -116,21 +179,73 @@ 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"
+ | "blend"
+ | "levels"
+ | "blur"
+ | "directional_blur"
+ | "directional_warp"
+ | "warp"
+ | "sharpen"
+ | "distance"
+ | "emboss"
+ )
{
base.variables(variables.to_mut());
}
let seed = base.seed;
- let mut parameters = match resolve_parameters(package, node, definition, &mut variables, seed, base.size) {
- Ok(parameters) => parameters,
- Err(error) => return fail(error, 0),
+ let ResolvedParameters { values: mut parameters, instance_literals, dynamic_blend_opacity, bound_image_property } =
+ match resolve_parameters(package, node, definition, &mut variables, base, &fixed, pattern_writes) {
+ Ok(parameters) => parameters,
+ Err(error) => return fail(error, 0),
+ };
+ let bound_image = if node.disabled {
+ base.bound_image
+ } else {
+ base.bound_size
+ || bound_image_property
+ || dynamic_blend_opacity
+ || (node.def == "fx_map" && base.bound_seed)
+ || input_base.is_some_and(|source| source.bound_image)
+ || incoming.iter().flatten().any(|(_, source)| source.bound_image)
};
+ let base = crate::ResolvedBaseParameters { bound_image, ..base };
+ let background_tiling = background_source.filter(|source| source.dynamic_size == base.dynamic_size).map(|source| source.tiling);
+ if matches!(node.def.as_str(), "blur" | "emboss") {
+ variables.to_mut().insert("$pixelsize".into(), Value::Float2(base.pixel_size));
+ }
let variables = &variables;
+ let bindings = BoundVariables { values: variables, fixed: &fixed, assigned_integers: &assigned_integers };
let tile = base.tiling[0] && base.tiling[1];
- let resource_hash = match parameters.get("resource") {
+ // Reuse the graph's decoded input while retaining its storage and binding metadata.
+ let input_image = input_image.map(|image| {
+ let name = identifier(node);
+ if options.inputs.contains_key(&name) {
+ let format = options.input_formats.get(&name).copied();
+ return (image.clone(), format, options.bitmap_formats.get(&name).copied(), options.base_level_inputs.contains(&name));
+ }
+ let bitmap = if image.integer_sampling() {
+ package
+ .graphs
+ .get(graph_index)
+ .and_then(|graph| graph.input_images.get(&name))
+ .and_then(|binding| package.resource(binding))
+ .and_then(|resource| materialcraft_core::png_sample_format(resource.bytes.as_slice()))
+ } else {
+ None
+ };
+ (image.clone(), None, bitmap, false)
+ });
+ let wired = options.depth != 0 && input_image.as_ref().is_some_and(|(_, upstream, _, _)| upstream.is_some());
+ let resource_hash = match parameters.get(crate::cache_key::resource_parameter(node)) {
Some(Value::Text(name)) => package.resource(name).map_or(0, |r| r.bytes.content_hash()),
_ => 0,
};
@@ -142,94 +257,242 @@ pub(crate) fn cook_node(
0
};
- let key = hash_of(&(
+ let mut key = hash_of(&(
&node.def,
serde_json::to_string(¶meters).unwrap_or_default(),
- (w, h, seed, tile, node.disabled, base.size, base.format, base.tiling, base.pixel_ratio, base.pixel_size.map(f32::to_bits)),
+ (dynamic_blend_opacity, bound_image, background_tiling),
+ (
+ w,
+ h,
+ seed,
+ tile,
+ node.disabled,
+ base.size,
+ base.size_underflow,
+ (base.dynamic_size, base.bound_size),
+ base.format,
+ base.tiling,
+ base.pixel_ratio,
+ base.pixel_size.map(f32::to_bits),
+ ),
&input_keys,
resource_hash,
subgraph_hash,
- // A cached graph instance includes results evaluated with its host environment
- (node.def == "graph_instance").then(|| serde_json::to_string(&options.environment).unwrap_or_default()),
- input_image.map(|image| image_key(image, cache)),
- variable_key(node, ¶meters, variables),
+ // Child outputs can exceed the instance size, so their cap is independent of w/h.
+ (node.def == "graph_instance").then(|| (options.max_size, serde_json::to_string(&options.environment).unwrap_or_default())),
+ input_image.as_ref().map(|(image, upstream, bitmap, base_level)| (image_key(image, cache), upstream, bitmap, wired, base_level)),
+ (variable_key(node, ¶meters, &bindings), &instance_literals),
));
+ if options.previous_sampling.is_some() && input_image.is_some() {
+ let name = identifier(node);
+ if let Some(&upstream) = options.preview_input_keys.get(&name) {
+ key = hash_of(&(key, upstream));
+ } else if let Some(graph) = package.graphs.get(graph_index)
+ && let Some(binding) = graph.input_images.get(&name)
+ {
+ key = hash_of(&(key, binding, graph.input_images_linear.contains(&name), graph.input_images_from_file.contains(&name)));
+ }
+ }
+ let instance_input_key = key;
+ if options.previous_sampling.is_some() && !node.disabled {
+ if node.def == "graph_instance" {
+ key = sampling.reuse_instance(previous, node.id, key);
+ } else if node.def == "fx_map" && base_level_only.contains(&true) {
+ key = sampling.stamp(previous, node.id, key, &input_keys, &mut base_level_only);
+ }
+ }
if let Some(outputs) = lock(cache).get(key) {
- parameters.retain(|_, value| materialcraft_core::ValueType::of(value).is_some());
- return NodeResult { base, base_values, parameters, outputs, error: None, ms: 0.0, key, cached: true };
+ inspection_parameters(node, &mut parameters);
+ let base = outputs.bases.as_deref().and_then(|ports| ports.first()).copied().unwrap_or(base);
+ return NodeResult { base, base_values, parameters, outputs: outputs.values, output_bases: outputs.bases, error: None, ms: 0.0, key, cached: true };
}
let started_ms = now_ms();
+ let mut output_bases: Option> = None;
let result: Result, String> = if node.disabled {
- let input = if let Some(primary) = definition.and_then(|definition| definition.primary_input) {
+ let input = if let Some(primary) = definition.and_then(|definition| definition.bypass_input) {
input_ports.iter().position(|port| port.id == primary).and_then(|index| incoming.get(index)).copied().flatten()
} else {
incoming.iter().find_map(|output| *output)
};
- let output = input.cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4])));
+ let output = input.map(|(output, _)| output.clone()).unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4])));
Ok(vec![output; output_ports.len().max(1)])
} else if node.def == "input_value" {
let value = variables.get(&identifier(node)).or_else(|| parameters.get("default")).cloned().unwrap_or(Value::Float(0.0));
Ok(vec![NodeOutput::Value(value)])
} else if node.def == "value_processor" {
- evaluate_value(¶meters, variables, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)])
- } else if matches!(node.def.as_str(), "output" | "dot") && incoming.first().and_then(Option::as_ref).is_some_and(|output| output.as_value().is_some()) {
- incoming.first().copied().flatten().cloned().map(|output| vec![output]).ok_or("missing value input".into())
- } else if let Some(image) = input_image {
- let mut image = if node.def == "input_grayscale" && image.kind() == Kind::Color {
- // Grayscale bridges use equal RGB weights and preserve fused float order
- let weight = 1.0 / 3.0;
- image.map(Kind::Gray, |pixel| [pixel[2].mul_add(weight, pixel[1].mul_add(weight, pixel[0] * weight)), 0.0, 0.0, 0.0])
- } else if node.def == "input_color" {
- image.to_color()
- } else {
- image.clone()
- };
-
- // Bound resources clamp edges through stored factor-two levels
- // Preserve resampling and storage conversion for HDR bridges
- let resized = image.width() != w || image.height() != h;
- while image.width() != w || image.height() != h {
- let next = |current: u32, target: u32| {
- if current < target { current.saturating_mul(2).min(target) } else { current.div_ceil(2).max(target) }
+ evaluate_value(¶meters, &bindings, seed, [w, h], &inputs, &input_formats, tile).map(|value| vec![NodeOutput::Value(value)])
+ } else if matches!(node.def.as_str(), "output" | "dot")
+ && let Some(Some((output, _))) = incoming.first()
+ && (output.as_value().is_some()
+ || matches!(output, NodeOutput::BaseLevel(stored) | NodeOutput::BoundBitmap { stored, .. } if (stored.width(), stored.height()) == (w, h)))
+ {
+ Ok(vec![(*output).clone()])
+ } else if let Some((image, upstream, bitmap, inherited_base_level)) = input_image {
+ let kind = if node.def == "input_grayscale" { Kind::Gray } else { Kind::Color };
+ let format = upstream.unwrap_or(OutputFormat::F32);
+ let source = bitmap.unwrap_or(format);
+ let external = if wired { None } else { crate::external_image::resize(&image, (w, h), kind, source, base.format) };
+ let tiling = if wired { base.tiling } else { [false; 2] };
+ let output = external.unwrap_or_else(|| {
+ let base_level = if wired {
+ inherited_base_level && image.kind() == kind && (image.width(), image.height()) == (w, h) && format == base.format
+ } else {
+ crate::external_image::base_level_only(&image, (w, h), kind, source, base.format)
};
- image = crate::output_precision::apply(image.resize(next(image.width(), w), next(image.height(), h), false), base.format);
- }
-
- // Resized inputs already store the final level at the declared precision
- let image = if resized { image } else { crate::output_precision::apply(image, base.format) };
- Ok(vec![NodeOutput::Image(image)])
+ let resize = if wired { materialcraft_nodes::resize_connected_image } else { materialcraft_nodes::resize_bound_image };
+ let image = resize(image, (w, h), kind, format, base.format, tiling);
+ if base_level { NodeOutput::BaseLevel(image) } else { NodeOutput::Image(image) }
+ });
+ Ok(vec![output])
} else if node.def == materialcraft_core::MISSING_NODE {
let name = if node.label.is_empty() { "this node" } else { node.label.as_str() };
Err(format!("unsupported node `{name}`"))
} else if node.def == "graph_instance" {
- cook_instance(package, graph_index, node, input_ports, output_ports, &incoming, ¶meters, (w, h), base, options, cache)
- } else if let Some(definition) = definition {
- let context = CookContext { format: base.format, w, h, seed, tile, inputs: &inputs, params: ¶meters, resource: options.resource, vars: variables };
- (definition.cook)(&context).map(|images| {
- images
- .into_iter()
- .map(|image| {
- // Bridges retain their source pixels; filters store their declared precision
- let image = if matches!(node.def.as_str(), "output" | "dot") { image } else { crate::output_precision::apply(image, base.format) };
- NodeOutput::Image(image)
- })
- .collect()
+ cook_instance(
+ package,
+ graph_index,
+ node,
+ input_ports,
+ output_ports,
+ &incoming,
+ &input_keys,
+ ¶meters,
+ &instance_literals,
+ base,
+ options,
+ cache,
+ previous.and_then(|p| p.child(node.id)),
+ )
+ .map(|instance| {
+ if let Some((child, outputs)) = instance.sampling {
+ key = hash_of(&(instance_input_key, outputs));
+ sampling.record_instance(node.id, instance_input_key, key, child);
+ }
+ let (values, bases): (Vec<_>, Vec<_>) = instance.ports.into_iter().unzip();
+ output_bases = Some(bases.into());
+ values
})
+ } else if let Some(definition) = definition {
+ if let (Some(tiling), Some(Some(image)), Some(&source)) = (background_tiling, inputs.first_mut(), input_formats.first())
+ && let Some(filtered) = materialcraft_nodes::pattern::direct_background_sample(image, (w, h), source, tiling)
+ {
+ *image = filtered;
+ }
+ let store_inputs = match base.format {
+ OutputFormat::F16 => matches!(node.def.as_str(), "blend" | "fx_map" | "levels" | "sharpen" | "blur"),
+ OutputFormat::F32 => node.def == "blur",
+ _ => false,
+ };
+ if store_inputs {
+ // When exactly one size is parameter-controlled, these filters store normalized inputs at their working precision.
+ // Images stamped by a pattern keep their sampling precision.
+ for ((image, format), port) in inputs.iter_mut().zip(&mut input_formats).zip(input_ports) {
+ if (node.def != "fx_map" || port.id == "background")
+ && matches!(format, OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit)
+ && let Some(image) = image
+ && (image.width(), image.height()) == (w, h)
+ && prepared.source_base(node.id, &port.id, cooked).is_some_and(|source| source.dynamic_size != base.dynamic_size)
+ {
+ *image = crate::output_precision::apply(image.clone(), base.format);
+ if node.def == "blur" {
+ // Fractional blur taps use the working texture's sampler.
+ *format = base.format;
+ }
+ }
+ }
+ }
+ let context = CookContext {
+ input_formats: &input_formats,
+ format: base.format,
+ w,
+ h,
+ seed,
+ tile,
+ inputs: &inputs,
+ params: ¶meters,
+ resource: options.resource,
+ vars: &bindings,
+ };
+ if node.def == "bitmap"
+ && let Some(output) = crate::external_image::resize_bitmap(&context, package)
+ {
+ Ok(vec![output])
+ } else {
+ let result = if matches!(node.def.as_str(), "fx_map" | "pixel_processor") {
+ let drawing = if node.def == "fx_map" {
+ materialcraft_nodes::pattern::cook_with_image_dependencies(&context, &base_level_only, bound_image)
+ } else {
+ materialcraft_nodes::function::pixel_processor_with_dependencies(&context)
+ };
+ drawing.map(|(image, reads_input)| {
+ // A cached image carries dependencies read by its drawing program along with its pixels.
+ if reads_input && !bound_image {
+ output_bases = Some(Arc::from([crate::ResolvedBaseParameters { bound_image: true, ..base }]));
+ }
+ vec![image]
+ })
+ } else if node.def == "text"
+ && !context.text("fontdata").is_empty()
+ && let Some(font) = package.resource(context.text("fontdata"))
+ {
+ materialcraft_nodes::atomic::text_with_font(&context, font.bytes.as_slice())
+ } else if dynamic_blend_opacity {
+ materialcraft_nodes::atomic::blend_with_opacity(&context, true)
+ } else {
+ (definition.cook)(&context)
+ };
+ let selected = if node.def == "blend" && !dynamic_blend_opacity {
+ materialcraft_nodes::atomic::blend_selected_input(&context).and_then(|slot| incoming.get(slot).copied().flatten())
+ } else {
+ None
+ };
+ result.map(|images| {
+ images
+ .into_iter()
+ .map(|image| {
+ // Bridges retain their source pixels; filters store their declared precision
+ let image = if matches!(node.def.as_str(), "output" | "dot") { image } else { crate::output_precision::apply(image, base.format) };
+ // A Blend that selects a compatible texture retains its available sampling levels.
+ if let Some((NodeOutput::BaseLevel(source), source_base)) = selected
+ && source_base.format == base.format
+ && source.kind() == image.kind()
+ && (source.width(), source.height()) == (w, h)
+ {
+ return NodeOutput::BaseLevel(image);
+ }
+ NodeOutput::Image(image)
+ })
+ .collect()
+ })
+ }
} else {
Err(format!("unknown node `{}`", node.def))
};
// Cooked values serve parameter controls; authoring graphs stay in the document
- parameters.retain(|_, value| materialcraft_core::ValueType::of(value).is_some());
+ inspection_parameters(node, &mut parameters);
match result {
Ok(outputs) if outputs.len() == output_ports.len().max(1) || output_ports.is_empty() => {
let outputs = Arc::new(outputs);
- lock(cache).put(key, outputs.clone());
- NodeResult { base, base_values, parameters, outputs, error: None, ms: (now_ms() - started_ms) as f32, key, cached: false }
+ lock(cache).put(key, outputs.clone(), output_bases.clone());
+ let base = output_bases.as_deref().and_then(|ports| ports.first()).copied().unwrap_or(base);
+ NodeResult { base, base_values, parameters, outputs, output_bases, error: None, ms: (now_ms() - started_ms) as f32, key, cached: false }
}
Ok(outputs) => fail(format!("`{}` made {} images for {} outputs", node.def, outputs.len(), output_ports.len()), key),
Err(error) => fail(error, key),
}
}
+
+// Image reads inside an instance retain the caller texture's dimensions, depth and available mip levels.
+fn wired_texture<'a>(options: &'a Options<'_>, bridge: &Node) -> Option<(&'a Image, OutputFormat, bool)> {
+ let kind = match bridge.def.as_str() {
+ "input_color" => Kind::Color,
+ "input_grayscale" => Kind::Gray,
+ _ => return None,
+ };
+ let name = identifier(bridge);
+ let image = options.inputs.get(&name)?;
+ (!bridge.disabled && image.kind() == kind).then_some((image, *options.input_formats.get(&name)?, options.base_level_inputs.contains(&name)))
+}
diff --git a/crates/eval/src/node_output.rs b/crates/eval/src/node_output.rs
index 15d6e66b..0c2f924c 100644
--- a/crates/eval/src/node_output.rs
+++ b/crates/eval/src/node_output.rs
@@ -1,30 +1,50 @@
use craft_texture::Image;
-use materialcraft_core::Value;
+use materialcraft_core::{OutputFormat, Value};
+use std::sync::Arc;
#[derive(Clone, Debug, PartialEq)]
pub enum NodeOutput {
Image(Image),
+ /// A resized external texture whose automatic filtering can only sample its base level.
+ BaseLevel(Image),
+ /// A bound bitmap can report its bridge precision while filters sample its original integer texture.
+ BoundBitmap {
+ stored: Image,
+ texture: Image,
+ texture_format: OutputFormat,
+ },
Value(Value),
}
impl NodeOutput {
pub fn as_image(&self) -> Option<&Image> {
match self {
- Self::Image(image) => Some(image),
+ Self::Image(image) | Self::BaseLevel(image) | Self::BoundBitmap { stored: image, .. } => Some(image),
Self::Value(_) => None,
}
}
pub fn as_value(&self) -> Option<&Value> {
match self {
- Self::Image(_) => None,
+ Self::Image(_) | Self::BaseLevel(_) | Self::BoundBitmap { .. } => None,
Self::Value(value) => Some(value),
}
}
- pub(crate) fn memory_bytes(&self) -> usize {
+ pub(crate) fn texture(&self, declared: OutputFormat) -> Option<(&Image, OutputFormat)> {
match self {
- Self::Image(image) => image.data().len().saturating_mul(size_of::()),
+ Self::BoundBitmap { texture, texture_format, .. } => Some((texture, *texture_format)),
+ Self::Image(image) | Self::BaseLevel(image) => Some((image, declared)),
+ Self::Value(_) => None,
+ }
+ }
+
+ pub(crate) fn memory_bytes(&self) -> usize {
+ let bytes = |image: &Image| image.data().len().saturating_mul(size_of::());
+ match self {
+ Self::Image(image) | Self::BaseLevel(image) => bytes(image),
+ Self::BoundBitmap { stored, texture, .. } if Arc::ptr_eq(stored.shared_data(), texture.shared_data()) => bytes(stored),
+ Self::BoundBitmap { stored, texture, .. } => bytes(stored).saturating_add(bytes(texture)),
Self::Value(Value::Text(text)) => size_of::().saturating_add(text.len()),
Self::Value(_) => size_of::(),
}
diff --git a/crates/eval/src/node_result.rs b/crates/eval/src/node_result.rs
index 6dff9e3e..f79b465f 100644
--- a/crates/eval/src/node_result.rs
+++ b/crates/eval/src/node_result.rs
@@ -10,9 +10,18 @@ pub struct NodeResult {
pub parameters: std::collections::BTreeMap,
/// One image per output port (empty when the cook failed)
pub outputs: Arc>,
+ /// Instance ports carry the dimensions, format and sampling properties of their source.
+ pub output_bases: Option>,
pub error: Option,
/// Cook time in milliseconds (0 when served from the cache)
pub ms: f32,
pub key: u64,
pub cached: bool,
}
+
+impl NodeResult {
+ pub fn output_base(&self, index: usize) -> Option {
+ self.outputs.get(index)?;
+ Some(self.output_bases.as_deref().and_then(|ports| ports.get(index)).copied().unwrap_or(self.base))
+ }
+}
diff --git a/crates/eval/src/node_size.rs b/crates/eval/src/node_size.rs
index ac6823dc..6d0bd8ea 100644
--- a/crates/eval/src/node_size.rs
+++ b/crates/eval/src/node_size.rs
@@ -3,7 +3,13 @@ use materialcraft_nodes::NodeDefinition;
/// Literal output size; cooking also evaluates any attached parameter function
pub fn node_size(graph: &Graph, definition: Option<&NodeDefinition>, node: &Node, input: Option<(u32, u32)>, maximum: Option) -> (u32, u32) {
- let parent = crate::ResolvedBaseParameters { size: graph.size_px(), ..Default::default() };
+ if node.disabled
+ && let Some((width, height)) = input
+ {
+ return limit([width, height], maximum);
+ }
+ let (size, size_underflow) = graph.resolved_output_size(None, None);
+ let parent = crate::ResolvedBaseParameters { size, size_underflow, ..Default::default() };
let input = input
.filter(|_| !definition.is_some_and(|definition| definition.generator))
.map(|(width, height)| crate::ResolvedBaseParameters { size: [width, height], ..parent });
diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs
index 9beb3f06..ff93046a 100644
--- a/crates/eval/src/options.rs
+++ b/crates/eval/src/options.rs
@@ -1,9 +1,10 @@
use craft_texture::Image;
-use materialcraft_core::{NodeId, Value};
-use std::collections::BTreeMap;
+use materialcraft_core::{NodeId, OutputFormat, Value};
+use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::AtomicBool;
/// What to cook and how
+#[derive(Clone)]
pub struct Options<'a> {
pub environment: materialcraft_core::EvaluationEnvironment,
pub parent_tiling: Option<[bool; 2]>,
@@ -15,8 +16,21 @@ pub struct Options<'a> {
pub only: Option>,
/// Images for the graph's input nodes, by identifier (graph instances)
pub inputs: BTreeMap,
+ /// Upstream storage precision for caller-supplied images. Unspecified floating inputs use full precision.
+ pub input_formats: BTreeMap,
+ /// Resolved source properties for each image wired to a graph instance.
+ pub input_bases: BTreeMap,
+ /// Caller textures which have only their base level when passed through an instance.
+ pub base_level_inputs: BTreeSet,
+ /// Previously accepted samples for this editor graph. Full cooks start without editor state.
+ pub previous_sampling: Option<&'a crate::PreviewSampling>,
+ pub(crate) preview_input_keys: BTreeMap,
+ /// Original storage of decoded external files. Wired graph inputs use their upstream format.
+ pub bitmap_formats: BTreeMap,
/// Values for the graph's exposed parameters (graph instances), over the graph's own
pub overrides: BTreeMap,
+ /// Exposed inputs whose fixed instance arguments can be folded during function evaluation.
+ pub literal_inputs: Vec,
/// Decodes a package resource (bitmap) by name
pub resource: &'a crate::ResourceDecoder<'a>,
/// Set from another thread to stop between nodes
@@ -39,7 +53,14 @@ impl<'a> Options<'a> {
max_size: None,
only: None,
inputs: BTreeMap::new(),
+ input_formats: BTreeMap::new(),
+ input_bases: BTreeMap::new(),
+ base_level_inputs: BTreeSet::new(),
+ previous_sampling: None,
+ preview_input_keys: BTreeMap::new(),
+ bitmap_formats: BTreeMap::new(),
overrides: BTreeMap::new(),
+ literal_inputs: Vec::new(),
resource,
cancel: None,
depth: 0,
diff --git a/crates/eval/src/output_precision.rs b/crates/eval/src/output_precision.rs
deleted file mode 100644
index 9b1a2408..00000000
--- a/crates/eval/src/output_precision.rs
+++ /dev/null
@@ -1,61 +0,0 @@
-use craft_texture::{Image, Limits};
-use materialcraft_core::OutputFormat;
-use std::sync::Arc;
-
-pub(crate) fn apply(image: Image, format: OutputFormat) -> Image {
- const HALF_FLOAT_MAX: f32 = 65504.0;
- const U8_FIXED_SCALE: f64 = 4096.0;
- const U16_FIXED_SCALE: f64 = 1_048_576.0;
-
- let integer = integer_sampling(format);
- if format == OutputFormat::F16 {
- return with_pixels(image, integer, |pixel| {
- // Half-float storage saturates finite overflow and truncates toward zero
- // Leaving the f32 unconverted changes every downstream read and export
- let value = pixel.clamp(-HALF_FLOAT_MAX, HALF_FLOAT_MAX);
- let rounded = half::f16::from_f32(value);
- *pixel = if rounded.to_f32().abs() > value.abs() { half::f16::from_bits(rounded.to_bits().saturating_sub(1)).to_f32() } else { rounded.to_f32() };
- });
- }
-
- let (fraction, maximum) = match format {
- OutputFormat::U8 => (U8_FIXED_SCALE, f64::from(u8::MAX)),
- OutputFormat::Inherit | OutputFormat::U16 => (U16_FIXED_SCALE, f64::from(u16::MAX)),
- OutputFormat::F16 | OutputFormat::F32 => return image.with_integer_sampling(integer),
- };
-
- with_pixels(image, integer, |pixel| {
- // Integer outputs retain four fractional guard bits before conversion
- // Halfway-down rounding affects constants and downstream blends
- let value = if pixel.is_nan() { 0.0 } else { f64::from(*pixel).clamp(0.0, 1.0) };
- let fixed = (value * fraction).floor() / fraction;
- let integer = (fixed * maximum - 0.5).ceil() as u32;
- *pixel = integer as f32 / maximum as f32;
- })
-}
-
-pub(crate) fn integer_sampling(format: OutputFormat) -> bool {
- matches!(format, OutputFormat::Inherit | OutputFormat::U8 | OutputFormat::U16)
-}
-
-/// `image` with `convert` applied to every float and the integer-sampling flag set. The buffer is
-/// changed in place when no other image shares it, and copied once otherwise.
-fn with_pixels(image: Image, integer_sampling: bool, convert: impl Fn(&mut f32)) -> Image {
- let (width, height, kind) = (image.width(), image.height(), image.kind());
-
- // Limits that admit any valid image, so one made with raised limits keeps its size
- let mut limits = Limits::default();
- limits.max_side = u32::MAX;
- limits.max_pixels = u64::MAX;
- limits.max_bytes = u64::MAX;
-
- let mut data = Arc::clone(image.shared_data());
- drop(image);
-
- Arc::make_mut(&mut data).iter_mut().for_each(convert);
-
- // `data` keeps the size and kind of a valid image, so `from_data` accepts it
- Image::from_data(width, height, kind, data, &limits)
- .unwrap_or_else(|_| Image::filled(width, height, kind, [0.0; 4]))
- .with_integer_sampling(integer_sampling)
-}
diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs
index f578411d..4d6682e4 100644
--- a/crates/eval/src/parameter.rs
+++ b/crates/eval/src/parameter.rs
@@ -1,15 +1,38 @@
-use materialcraft_core::{Node, Package, Value, ValueType};
-use materialcraft_nodes::{NodeDefinition, ParameterDescriptor, clamp_params, resolve_params};
+use crate::{ResolvedBaseParameters, parameter_function::ParameterMode};
+use materialcraft_core::{Node, OutputFormat, Package, Value, ValueType};
+use materialcraft_nodes::function::compile_with_literal_inputs;
+use materialcraft_nodes::{NodeDefinition, ParameterDescriptor, accepts_scalar_function, clamp_params, resolve_params};
use std::collections::BTreeMap;
+pub(crate) struct ResolvedParameters {
+ pub values: BTreeMap,
+ pub instance_literals: Vec,
+ pub dynamic_blend_opacity: bool,
+ pub bound_image_property: bool,
+}
+
+pub(crate) fn supports_literal_argument(value: &Value) -> bool {
+ matches!(value, Value::Int(_) | Value::Float(_) | Value::Float2(_) | Value::Float3(_) | Value::Float4(_))
+}
+
+// The color cook needs the operand's original width and whether its channels were folded.
+fn uniform_color_operand(value: &Value, literal: bool) -> Option {
+ match value {
+ Value::Float(_) | Value::Float3(_) => Some(value.clone()),
+ Value::Float4(rgba) | Value::Color(rgba) => Some(if literal { Value::Color(*rgba) } else { Value::Float4(*rgba) }),
+ _ => None,
+ }
+}
+
pub(crate) fn resolve_parameters(
package: &Package,
node: &Node,
definition: Option<&NodeDefinition>,
variables: &mut std::borrow::Cow<'_, BTreeMap>,
- seed: u32,
- size: [u32; 2],
-) -> Result, String> {
+ base: ResolvedBaseParameters,
+ literal_inputs: &[String],
+ mut assigned_integers: Option<&mut Vec>,
+) -> Result {
let mut parameters = match definition {
Some(definition) if node.def != "graph_instance" => resolve_params(definition, &node.params),
_ => {
@@ -27,35 +50,293 @@ pub(crate) fn resolve_parameters(
}
}
+ let mut dynamic = std::collections::BTreeSet::new();
+ let mut dynamic_blend_opacity = false;
+ let mut bound_image_property = false;
+ let mut bound_mip_level = false;
+ let mut record_drawing_input = |name: &str| match (node.def.as_str(), name) {
+ ("blend", "opacity") => dynamic_blend_opacity = true,
+ ("transformation", "mip_level") => bound_mip_level = true,
+ ("transformation", "matte") if base.tiling != [true; 2] => bound_image_property = true,
+ ("uniform", "color")
+ | ("blur" | "directional_blur" | "warp", "intensity")
+ | ("directional_blur", "angle")
+ | ("transformation", "offset" | "matrix")
+ | ("grayscale_conversion", "weights" | "matte")
+ | ("levels", "in_low" | "in_mid" | "in_high" | "out_low" | "out_high")
+ | ("fx_map", "opacity" | "roughness" | "background" | "render_region" | "tiling_region") => bound_image_property = true,
+ _ => {}
+ };
+ let mut uniform_color = None;
for (parameter, exposed) in &node.bindings {
+ if node.def == "uniform" && parameter == "color" {
+ uniform_color = variables.get(exposed).and_then(|value| uniform_color_operand(value, false));
+ }
+ if node.def == "graph_instance" && !literal_inputs.contains(exposed) {
+ dynamic.insert(parameter);
+ }
if let (Some(value), Some(current)) = (variables.get(exposed), parameters.get(parameter))
&& let Some(coerced) = current.coerce_json(&serde_json::to_value(value).unwrap_or_default())
{
+ if !literal_inputs.contains(exposed) && !node.functions.contains_key(parameter) {
+ record_drawing_input(parameter);
+ }
parameters.insert(parameter.clone(), coerced);
}
}
+ let mut gray_pattern_opacity = None;
for (parameter, function) in &node.functions {
let current = parameters.get(parameter).ok_or_else(|| format!("unknown function parameter `{parameter}`"))?;
let expected = ValueType::of(current).ok_or_else(|| format!("parameter `{parameter}` cannot have a function"))?;
- let allow_scalar = materialcraft_nodes::accepts_scalar_function(&node.def, parameter);
- let value = crate::parameter_function::evaluate(function, expected, variables.to_mut(), seed, size, allow_scalar)
+ let mode = match (node.def.as_str(), parameter.as_str(), base.format) {
+ ("uniform", "color", _) => ParameterMode::UniformColor,
+ ("levels", name, format) if accepts_scalar_function("levels", name) => {
+ ParameterMode::Levels { normalized: name != "in_mid" && matches!(format, OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit) }
+ }
+ ("fx_map", "background", _) if matches!(current, Value::Float4(_)) => ParameterMode::Broadcast,
+ ("fx_map", "opacity", _) if parameters.get("color_mode") == Some(&Value::Bool(false)) => ParameterMode::GrayPatternOpacity,
+ _ => ParameterMode::Opaque,
+ };
+ let (value, literal) = compile_with_literal_inputs(function, base.seed, literal_inputs)
+ .and_then(|program| {
+ if program.reads_graph_parameter(variables) {
+ record_drawing_input(parameter);
+ }
+ crate::parameter_function::evaluate(&program, expected, variables.to_mut(), base.size, mode, Some(current), assigned_integers.as_deref_mut())
+ })
.map_err(|error| format!("function of `{parameter}`: {error}"))?;
- let value = match (current, value) {
- (Value::Float4(_), Value::Float(value)) if allow_scalar => Value::Float4([value; 4]),
- (Value::Color(_), Value::Float(value)) if allow_scalar => Value::Float4([value, value, value, 1.0]),
- (_, value) => value,
+ if matches!(mode, ParameterMode::UniformColor) {
+ uniform_color = uniform_color_operand(&value, literal);
+ continue;
+ }
+ if matches!(mode, ParameterMode::GrayPatternOpacity) {
+ // Keep the result in floating point until blending. JSON and slider limits lose signed infinities.
+ gray_pattern_opacity = Some(value);
+ continue;
+ }
+ if node.def == "graph_instance" {
+ if literal {
+ dynamic.remove(parameter);
+ } else {
+ dynamic.insert(parameter);
+ }
+ }
+ let value = if matches!((&mode, &value), (ParameterMode::Levels { .. }, Value::Float(_))) {
+ value
+ } else {
+ current.coerce_json(&serde_json::to_value(value).unwrap_or_default()).ok_or_else(|| format!("invalid function value for `{parameter}`"))?
};
- let value = current.coerce_json(&serde_json::to_value(value).unwrap_or_default()).ok_or_else(|| format!("invalid function value for `{parameter}`"))?;
parameters.insert(parameter.clone(), value);
}
+ if let Some(color) = uniform_color {
+ parameters.insert("color".into(), color);
+ }
// Catalog limits keep values from files and functions within safe cook bounds
if let Some(definition) = definition
&& node.def != "graph_instance"
{
clamp_params(definition, &mut parameters);
}
+ if let Some(opacity) = gray_pattern_opacity {
+ parameters.insert("opacity".into(), opacity);
+ }
+ // A computed mip mode can appear after the level in the property list.
+ bound_image_property |= bound_mip_level && parameters.get("mip_mode").and_then(Value::as_i32) == Some(1);
- Ok(parameters)
+ let fixed = if node.def == "graph_instance" {
+ parameters.iter().filter(|(name, value)| supports_literal_argument(value) && !dynamic.contains(*name)).map(|(name, _)| name.clone()).collect()
+ } else {
+ Vec::new()
+ };
+ Ok(ResolvedParameters { values: parameters, instance_literals: fixed, dynamic_blend_opacity, bound_image_property })
+}
+
+pub(crate) fn inspection_parameters(node: &Node, parameters: &mut BTreeMap) {
+ parameters.retain(|name, value| {
+ if node.def == "uniform" && name == "color" {
+ match value {
+ Value::Float(level) => *value = Value::Color([*level, *level, *level, 1.0]),
+ Value::Float3([r, g, b]) => *value = Value::Color([*r, *g, *b, 1.0]),
+ Value::Float4(rgba) => *value = Value::Color(*rgba),
+ _ => {}
+ }
+ }
+ if let Value::Float(level) = value
+ && node.def == "levels"
+ && accepts_scalar_function("levels", name)
+ {
+ *value = Value::Float4([*level, *level, *level, 1.0]);
+ }
+ ValueType::of(value).is_some()
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::{Cache, Options, cook};
+ use materialcraft_core::{FunctionGraph, Graph, Package, Value, ValueType};
+ use std::sync::Mutex;
+
+ #[test]
+ fn uniform_gray_preserves_the_precision_of_its_color_source() {
+ use materialcraft_core::OutputFormat;
+
+ let mut graph = Graph::new("Uniform precision");
+ graph.size = [2; 2];
+ graph.format = OutputFormat::F32;
+ let uniform = graph.add_node("uniform", [0.0; 2]);
+ graph.node_mut(uniform).unwrap().params.insert("color_mode".into(), Value::Bool(false));
+ let mut package = Package::new("Uniform precision");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ let mut options = Options::new(&|_| None);
+ let scalar = Value::Float(f32::from_bits(0x3ed5_1632));
+ let rgba = Value::Float4([1.0, f32::EPSILON, -1.0, 0.59375]);
+ for (value, bound, expected) in [
+ (rgba.clone(), false, 0x332a_aaab),
+ (rgba.clone(), true, 0x3300_0000),
+ (scalar, true, 0x3ed5_1632),
+ (Value::Float3([0.125, 0.3125, 0.6875]), true, 0),
+ (Value::Float4([-65536.0, 65536.0, 0.001953125, 0.5]), false, 0x3a2a_aaab),
+ (rgba, false, 0x332a_aaab),
+ ] {
+ let function = if bound {
+ let get = FunctionGraph::input("ink", ValueType::of(&value).unwrap());
+ options.overrides.insert("ink".into(), value);
+ get
+ } else {
+ FunctionGraph::constant(value)
+ };
+ package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function);
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&uniform].error, None);
+ assert_eq!(cooked.image(uniform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected);
+ }
+ }
+
+ #[test]
+ fn grayscale_uniform_distinguishes_image_size_from_an_exposed_color_read() {
+ use materialcraft_core::OutputFormat;
+
+ let mut graph = Graph::new("Uniform sources");
+ graph.size = [2; 2];
+ graph.format = OutputFormat::F32;
+ let uniform = graph.add_node("uniform", [0.0; 2]);
+ graph.node_mut(uniform).unwrap().params.insert("color_mode".into(), Value::Bool(false));
+ let mut package = Package::new("Uniform sources");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ let mut options = Options::new(&|_| None);
+ options.overrides.insert("ink".into(), Value::Float4([0.25; 4]));
+
+ for (variable, ty, expected) in [
+ ("$size", ValueType::Float2, 0x332a_aaab),
+ ("$pixelratio", ValueType::Integer, 0x332a_aaab),
+ ("$uvtile", ValueType::Integer2, 0x332a_aaab),
+ ("$physicalsize", ValueType::Float3, 0x332a_aaab),
+ ("unbound_color", ValueType::Float, 0x332a_aaab),
+ ("$time", ValueType::Float, 0x3300_0000),
+ ("$normalformat", ValueType::Integer, 0x3300_0000),
+ ("ink", ValueType::Float4, 0x3300_0000),
+ ] {
+ let mut function = FunctionGraph::input(variable, ty);
+ let read = function.output.unwrap();
+ let rgba = function.add_constant(Value::Float4([1.0, f32::EPSILON, -1.0, 0.59375]));
+ function.output = Some(function.add("sequence", &[read, rgba], None));
+ package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function);
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&uniform].error, None);
+ assert_eq!(cooked.image(uniform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected);
+ }
+ }
+
+ #[test]
+ fn uniform_color_keeps_hdr_channels_and_distinguishes_an_explicit_alpha() {
+ use materialcraft_core::OutputFormat;
+
+ let mut graph = Graph::new("Uniform channels");
+ graph.size = [2; 2];
+ graph.format = OutputFormat::F32;
+ let uniform = graph.add_node("uniform", [0.0; 2]);
+ let mut package = Package::new("Uniform channels");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ let mut options = Options::new(&|_| None);
+ let rgb = [-65536.0, 65536.0, 0.001953125];
+ options.overrides.insert("ink".into(), Value::Float3(rgb));
+ let direct = FunctionGraph::input("ink", ValueType::Float3);
+ let mut with_alpha = direct.clone();
+ let color = with_alpha.output.unwrap();
+ let alpha = with_alpha.add_constant(Value::Float(0.59375));
+ with_alpha.output = Some(with_alpha.add("vector4", &[color, alpha], None));
+ for (function, expected) in [(direct, [0.0, 0.0, 0.0, 1.0]), (with_alpha, [rgb[0], rgb[1], rgb[2], 0.59375])] {
+ package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function);
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&uniform].error, None);
+ assert_eq!(cooked.image(uniform, 0).unwrap().get(0, 0, false), expected);
+ }
+ }
+
+ #[test]
+ fn gray_levels_keep_scalar_endpoints_distinct_from_equal_rgb_controls() {
+ use craft_texture::Image;
+ use materialcraft_core::OutputFormat;
+
+ let mut graph = Graph::new("Endpoint precision");
+ graph.size = [2, 2];
+ graph.format = OutputFormat::F32;
+ let source = graph.add_node("input_grayscale", [0.0; 2]);
+ let levels = graph.add_node("levels", [0.0; 2]);
+ graph.connect(source, "output", levels, "input").unwrap();
+ let mut package = Package::new("Endpoint precision");
+ package.graphs.push(graph);
+ let mut options = Options::new(&|_| None);
+ options.inputs.insert("input".into(), Image::gray(4, 4, |_, _| 1.0));
+ let cache = Mutex::new(Cache::default());
+
+ let scalar = f32::from_bits(0x3ec0c0c2);
+ let rgba = [scalar, scalar, scalar, 1.0];
+ let vector_result = f32::from_bits(0x3ec0c0c3);
+ for (value, expected) in [(Value::Float4(rgba), vector_result), (Value::Float(scalar), scalar), (Value::Float4(rgba), vector_result)] {
+ package.graphs[0].node_mut(levels).unwrap().functions.insert("out_high".into(), FunctionGraph::constant(value));
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&levels].parameters["out_high"], Value::Float4(rgba));
+ assert_eq!(cooked.image(levels, 0).unwrap().get_gray(0, 0, false).to_bits(), expected.to_bits());
+ }
+ }
+
+ #[test]
+ fn missing_direct_level_link_keeps_the_property_value() {
+ let mut graph = Graph::new("Matte");
+ graph.size = [2; 2];
+ let levels = graph.add_node("levels", [0.0; 2]);
+ let mut package = Package::new("Links");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ let reader = FunctionGraph::input("%amount", ValueType::Float);
+ let mut disconnected = reader.clone();
+ disconnected.add_constant(Value::Float(0.75));
+ let mut computed = reader.clone();
+ let value = computed.output.unwrap();
+ let offset = computed.add_constant(Value::Float(0.1875));
+ computed.output = Some(computed.add("add", &[value, offset], None));
+
+ for (function, bound, expected) in [
+ (reader.clone(), None, [1.0; 4]),
+ (disconnected, None, [1.0; 4]),
+ (reader, Some(0.0), [0.0, 0.0, 0.0, 1.0]),
+ (computed, None, [0.1875, 0.1875, 0.1875, 1.0]),
+ ] {
+ package.graphs[0].node_mut(levels).unwrap().functions.insert("out_high".into(), function);
+ let mut options = Options::new(&|_| None);
+ if let Some(level) = bound {
+ options.overrides.insert("amount".into(), Value::Float(level));
+ }
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&levels].error, None);
+ assert_eq!(cooked.nodes[&levels].parameters.get("out_high"), Some(&Value::Float4(expected)));
+ }
+ }
}
diff --git a/crates/eval/src/parameter_function.rs b/crates/eval/src/parameter_function.rs
index e09ce2ff..dcba4d55 100644
--- a/crates/eval/src/parameter_function.rs
+++ b/crates/eval/src/parameter_function.rs
@@ -1,46 +1,80 @@
-use materialcraft_core::{FunctionGraph, Value, ValueType};
-use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile};
+use materialcraft_core::{BaseParameter, Value, ValueType};
+use materialcraft_nodes::function::{EvaluationContext, EvaluationState, FunctionScope, Program};
use std::collections::BTreeMap;
+#[derive(Clone, Copy)]
+pub(crate) enum ParameterMode {
+ Opaque,
+ RandomSeed,
+ Broadcast,
+ UniformColor,
+ GrayPatternOpacity,
+ Levels { normalized: bool },
+}
+
+impl ParameterMode {
+ pub(crate) fn for_base(parameter: BaseParameter) -> Self {
+ if parameter == BaseParameter::RandomSeed { Self::RandomSeed } else { Self::Opaque }
+ }
+}
+
pub(crate) fn evaluate(
- function: &FunctionGraph,
+ program: &Program,
expected: ValueType,
variables: &mut BTreeMap,
- seed: u32,
size: [u32; 2],
- allow_scalar: bool,
-) -> Result {
- let program = compile(function, seed)?;
- let scalar_channel = allow_scalar && expected == ValueType::Float4 && program.output_type() == ValueType::Float as u32;
-
- // A color parameter also takes a gray level or an opaque RGB triple
+ mode: ParameterMode,
+ fallback: Option<&Value>,
+ assigned_integers: Option<&mut Vec>,
+) -> Result<(Value, bool), String> {
let widened = expected == ValueType::Float4 && [ValueType::Float as u32, ValueType::Float3 as u32].contains(&program.output_type());
- if program.output_type() != expected as u32 && !scalar_channel && !widened {
+ if program.output_type() != expected as u32 && !widened {
return Err(format!("output must be {}", expected.label()));
}
-
- let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images: &[], tile: true, variables };
- let mut state = EvaluationState::default();
- let value = program.evaluate(&context, &mut state)?;
- let finite = match &value {
- Value::Float(value) => value.is_finite(),
- Value::Float2(values) => values.iter().all(|value| value.is_finite()),
- Value::Float3(values) => values.iter().all(|value| value.is_finite()),
- Value::Float4(values) | Value::Color(values) => values.iter().all(|value| value.is_finite()),
- _ => true,
- };
-
- if !finite {
- return Err("function returned a non-finite value".into());
+ // A direct link with a missing user input leaves the property's stored setting in effect.
+ if let Some(value) = fallback
+ && program.input_identifier().is_some_and(|name| !name.starts_with('$') && !variables.contains_key(name))
+ {
+ return Ok((value.clone(), matches!(mode, ParameterMode::UniformColor)));
}
+ let context = EvaluationContext {
+ image_formats: &[],
+ scope: if matches!(mode, ParameterMode::RandomSeed) { FunctionScope::RandomSeed } else { FunctionScope::Node },
+ position: [0.5; 2],
+ size: size.map(|side| side as f32),
+ images: &[],
+ tile: true,
+ variables,
+ };
+ let mut state = EvaluationState::default();
+ let value = match mode {
+ ParameterMode::Levels { normalized: true } => program.evaluate_normalized_color(&context, &mut state)?,
+ ParameterMode::GrayPatternOpacity => Value::Float(program.evaluate_pattern_opacity(&context, &mut state)?),
+ _ => program.evaluate(&context, &mut state)?,
+ };
+ // A scalar level is already luminance. Its RGB expansion would introduce a second rounding.
+ let scalar_level = matches!(mode, ParameterMode::Levels { .. }) && program.output_type() == ValueType::Float as u32;
let value = match value {
- Value::Float(level) if !scalar_channel && widened => Value::Float4([level, level, level, 1.0]),
+ value if matches!(mode, ParameterMode::UniformColor) => value,
+ Value::Float(level) | Value::Float4([level, _, _, _]) if scalar_level => Value::Float(level),
+ Value::Float(level) if widened && matches!(mode, ParameterMode::Broadcast) => Value::Float4([level; 4]),
+ Value::Float(level) if widened => Value::Float4([level, level, level, 1.0]),
Value::Float3([red, green, blue]) if widened => Value::Float4([red, green, blue, 1.0]),
value => value,
};
+ let fixed = match mode {
+ ParameterMode::UniformColor => program.uses_fixed_uniform_color(variables),
+ _ => program.output_is_literal(),
+ };
+ if let Some(names) = assigned_integers {
+ for (name, value) in state.assignments() {
+ if matches!(value, Value::Int(_)) && !names.contains(name) {
+ names.push(name.clone());
+ }
+ }
+ }
variables.extend(state.assignments().clone());
-
- Ok(value)
+ Ok((value, fixed))
}
diff --git a/crates/eval/src/port.rs b/crates/eval/src/port.rs
index 2c35bbda..345da7fb 100644
--- a/crates/eval/src/port.rs
+++ b/crates/eval/src/port.rs
@@ -1,3 +1,4 @@
+use materialcraft_core::ValueType;
use materialcraft_nodes::PortKind;
#[derive(Clone, Debug, PartialEq)]
@@ -5,4 +6,6 @@ pub struct Port {
pub id: String,
pub label: String,
pub kind: PortKind,
+ /// Concrete type of a declared value port.
+ pub value_type: Option,
}
diff --git a/crates/eval/src/ports.rs b/crates/eval/src/ports.rs
index f141c8af..7981f15c 100644
--- a/crates/eval/src/ports.rs
+++ b/crates/eval/src/ports.rs
@@ -14,53 +14,38 @@ pub fn ports_with_connections<'a>(
incoming: impl IntoIterator
- ,
) -> (Vec, Vec) {
if node.def == "graph_instance" {
+ let ports = |source: &[materialcraft_core::GraphPort]| {
+ source
+ .iter()
+ .map(|port| Port {
+ id: port.identifier.clone(),
+ label: port.identifier.clone(),
+ kind: match port.type_code {
+ 1 => PortKind::Color,
+ 2 => PortKind::Gray,
+ _ => PortKind::Value,
+ },
+ value_type: materialcraft_core::ValueType::from_code(port.type_code),
+ })
+ .collect()
+ };
if let Some(instance) = &node.instance {
- let ports = |ports: &[materialcraft_core::GraphPort]| {
- ports
- .iter()
- .map(|port| Port {
- id: port.identifier.clone(),
- label: port.identifier.clone(),
- kind: match port.type_code {
- 1 => PortKind::Color,
- 2 => PortKind::Gray,
- _ => PortKind::Value,
- },
- })
- .collect()
- };
return (ports(&instance.inputs), ports(&instance.outputs));
}
let Some((_, graph)) = instance_graph(package, node) else {
return (Vec::new(), Vec::new());
};
-
- let graph_ports = |definition: &str| -> Vec {
- graph
- .nodes
- .iter()
- .filter(|node| node.def == definition || (definition == "input" && node.def.starts_with("input_")))
- .map(|node| {
- let id = identifier(node);
- let kind = match node.def.as_str() {
- "input_grayscale" => PortKind::Gray,
- "input_color" => PortKind::Color,
- _ => PortKind::Any,
- };
-
- Port { label: id.clone(), id, kind }
- })
- .collect()
- };
-
- return (graph_ports("input"), graph_ports("output"));
+ let (inputs, outputs) = materialcraft_nodes::graph_interface::graph_ports(graph);
+ return (ports(&inputs), ports(&outputs));
}
if node.def == materialcraft_core::MISSING_NODE {
let (inputs, outputs) = materialcraft_core::missing_ports(node);
- let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any }).collect();
- let outputs =
- outputs.into_iter().map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color } }).collect();
+ let inputs = inputs.into_iter().map(|id| Port { label: id.clone(), id, kind: PortKind::Any, value_type: None }).collect();
+ let outputs = outputs
+ .into_iter()
+ .map(|(id, grayscale)| Port { label: id.clone(), id, kind: if grayscale { PortKind::Gray } else { PortKind::Color }, value_type: None })
+ .collect();
return (inputs, outputs);
}
@@ -69,7 +54,7 @@ pub fn ports_with_connections<'a>(
return (Vec::new(), Vec::new());
};
- let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind };
+ let catalog_port = |port: &materialcraft_nodes::PortDefinition| Port { id: port.id.into(), label: port.label.into(), kind: port.kind, value_type: None };
let mut inputs: Vec = node
.input_values
.iter()
@@ -77,6 +62,7 @@ pub fn ports_with_connections<'a>(
id: identifier.clone(),
label: format!("{} ({})", crate::value_input_label(identifier), value_type.label()),
kind: PortKind::Value,
+ value_type: Some(*value_type),
})
.collect();
inputs.extend(definition.inputs.iter().map(catalog_port));
@@ -89,7 +75,12 @@ pub fn ports_with_connections<'a>(
.max()
.unwrap_or(1)
.min(materialcraft_nodes::MAX_IMAGE_INPUTS);
- inputs.extend((1..count).map(|index| Port { id: format!("{prefix}{index}"), label: format!("Input image {index}"), kind: PortKind::Any }));
+ inputs.extend((1..count).map(|index| Port {
+ id: format!("{prefix}{index}"),
+ label: format!("Input image {index}"),
+ kind: PortKind::Any,
+ value_type: None,
+ }));
}
(inputs, definition.outputs.iter().map(catalog_port).collect())
diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs
index 056e41a5..dac64ff3 100644
--- a/crates/eval/src/prepared_graph.rs
+++ b/crates/eval/src/prepared_graph.rs
@@ -7,11 +7,12 @@ pub(crate) struct PreparedGraph<'a> {
pub index: GraphIndex<'a>,
pub order: Vec,
pub parent_base: crate::resolved_base_parameters::ResolvedBaseParameters,
+ pub base_error: Option,
ports: BTreeMap, Vec)>,
}
impl<'a> PreparedGraph<'a> {
- pub fn new(package: &Package, graph: &'a Graph, options: &crate::Options<'_>) -> Self {
+ pub fn new(package: &Package, graph: &'a Graph, options: &crate::Options<'_>, variables: &BTreeMap) -> Self {
let index = GraphIndex::new(graph);
let needed = options.only.as_deref().map(|roots| index.required_nodes(roots));
let order: Vec<_> = index.topo_order().into_iter().filter(|id| needed.as_ref().is_none_or(|needed| needed.contains(id))).collect();
@@ -23,32 +24,40 @@ impl<'a> PreparedGraph<'a> {
})
.collect();
- let parent_base = crate::resolved_base_parameters::ResolvedBaseParameters::graph(graph, options);
- Self { index, order, ports, parent_base }
+ let mut parent_base = crate::resolved_base_parameters::ResolvedBaseParameters::graph(graph, options);
+ let base_error =
+ parent_base.evaluate_graph_size(graph, options, variables).and_then(|()| parent_base.evaluate_graph_seed(graph, options, variables)).err();
+ Self { index, order, ports, parent_base, base_error }
}
pub fn input_base(&self, id: NodeId, cooked: &crate::Cooked) -> Option {
let node = self.index.node(id)?;
let definition = materialcraft_nodes::find(&node.def);
- let primary = definition.and_then(|definition| definition.primary_input);
+ let primary = definition.and_then(|definition| if node.disabled { definition.bypass_input } else { definition.primary_input });
let mut base = self
.ports(id)
.0
.iter()
.filter(|port| port.kind != materialcraft_nodes::PortKind::Value && primary.is_none_or(|primary| port.id == primary))
- .find_map(|port| {
- let connection = self.index.input_of(id, &port.id)?;
- cooked.nodes.get(&connection.from).map(|result| result.base)
- })?;
+ .find_map(|port| self.source_base(id, &port.id, cooked))?;
// Only bypassed generators take their image dimensions from the input
if !node.disabled && definition.is_some_and(|definition| definition.generator) {
base.size = self.parent_base.size;
+ base.size_underflow = self.parent_base.size_underflow;
+ base.dynamic_size = self.parent_base.dynamic_size;
+ base.bound_size = self.parent_base.bound_size;
}
Some(base)
}
+ pub fn source_base(&self, id: NodeId, port: &str, cooked: &crate::Cooked) -> Option {
+ let edge = self.index.input_of(id, port)?;
+ let index = self.ports(edge.from).1.iter().position(|output| output.id == edge.from_port)?;
+ cooked.nodes.get(&edge.from)?.output_base(index)
+ }
+
pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) {
self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice()))
}
diff --git a/crates/eval/src/preview_sampling.rs b/crates/eval/src/preview_sampling.rs
new file mode 100644
index 00000000..310269d3
--- /dev/null
+++ b/crates/eval/src/preview_sampling.rs
@@ -0,0 +1,72 @@
+use crate::cache_key::hash_of;
+use materialcraft_core::NodeId;
+use std::{collections::BTreeMap, sync::Arc};
+
+/// Sampling state from one accepted preview. A graph instance owns its child state.
+#[derive(Clone, Debug, Default)]
+pub struct PreviewSampling {
+ pub(crate) context: ([u32; 2], u32, Option),
+ pub(crate) caller_format: Option,
+ stamps: BTreeMap,
+ instances: BTreeMap,
+}
+
+#[derive(Clone, Debug)]
+struct Stamp {
+ cook_key: u64,
+ // Each port keeps the acquired texture identity and whether it used the full mip chain.
+ inputs: BTreeMap,
+}
+
+#[derive(Clone, Debug)]
+struct Instance {
+ input_key: u64,
+ output_key: u64,
+ sampling: Arc,
+}
+
+impl PreviewSampling {
+ pub(crate) fn is_empty(&self) -> bool {
+ self.stamps.is_empty() && self.instances.is_empty()
+ }
+
+ pub(crate) fn child(&self, id: NodeId) -> Option<&PreviewSampling> {
+ self.instances.get(&id).map(|state| state.sampling.as_ref())
+ }
+
+ pub(crate) fn reuse_instance(&mut self, previous: Option<&Self>, id: NodeId, input_key: u64) -> u64 {
+ if let Some(state) = previous.and_then(|p| p.instances.get(&id)).filter(|s| s.input_key == input_key) {
+ self.instances.insert(id, state.clone());
+ state.output_key
+ } else {
+ // Only an instance whose previous evaluation found no retained samplers can hit this key.
+ hash_of(&(input_key, "preview without sampled bridges"))
+ }
+ }
+
+ pub(crate) fn record_instance(&mut self, id: NodeId, input_key: u64, output_key: u64, sampling: Arc) {
+ self.instances.insert(id, Instance { input_key, output_key, sampling });
+ }
+
+ pub(crate) fn stamp(&mut self, previous: Option<&Self>, id: NodeId, cook_key: u64, input_keys: &[u64], base_only: &mut [bool]) -> u64 {
+ // A precision edit on the calling instance resamples retained textures even at a fixed child precision.
+ let caller_changed = previous.is_some_and(|state| state.caller_format != self.caller_format);
+ let previous = previous.and_then(|p| p.stamps.get(&id));
+ let mut inputs = BTreeMap::new();
+ let mut full = Vec::new();
+ for (port, (base_only, &texture)) in base_only.iter_mut().zip(input_keys).enumerate() {
+ if *base_only {
+ let retained = previous.is_some_and(|stamp| {
+ stamp.inputs.get(&port).is_some_and(|&(old, full)| old == texture && (full || caller_changed || stamp.cook_key != cook_key))
+ });
+ inputs.insert(port, (texture, retained));
+ if retained {
+ *base_only = false;
+ full.push(port);
+ }
+ }
+ }
+ self.stamps.insert(id, Stamp { cook_key, inputs });
+ if full.is_empty() { cook_key } else { hash_of(&(cook_key, full)) }
+ }
+}
diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs
index a2588469..a2b2111b 100644
--- a/crates/eval/src/resolved_base_parameters.rs
+++ b/crates/eval/src/resolved_base_parameters.rs
@@ -1,10 +1,26 @@
use materialcraft_core::{BaseParameter, BaseParameters, Graph, OutputFormat, ParameterInheritance, Value};
+use materialcraft_nodes::function::compile_with_literal_inputs;
use std::collections::BTreeMap;
#[derive(Clone, Copy, Debug, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ResolvedBaseParameters {
pub size: [u32; 2],
+ /// This texture inherits or evaluates a size controlled by a runtime parameter.
+ #[serde(skip)]
+ pub dynamic_size: bool,
+ /// The resolved dimensions depend on a live graph input, including through size inheritance.
+ #[serde(skip)]
+ pub bound_size: bool,
+ /// This node's seed expression reads a live graph input.
+ #[serde(skip)]
+ pub bound_seed: bool,
+ /// A drawing property on this image or a connected source reads a live graph input.
+ #[serde(skip)]
+ pub bound_image: bool,
+ /// Negative requested exponents on axes whose allocated texture is one texel.
+ #[serde(skip)]
+ pub size_underflow: [i32; 2],
pub seed: u32,
pub format: OutputFormat,
pub tiling: [bool; 2],
@@ -12,43 +28,126 @@ pub struct ResolvedBaseParameters {
pub pixel_size: [f32; 2],
}
+// An image carries no random stream. Both relative modes add to the parent seed.
+fn resolve_seed(mode: ParameterInheritance, offset: i32, parent: u32) -> u32 {
+ mode.resolve(0, None, parent).wrapping_add(offset as u32)
+}
+
impl ResolvedBaseParameters {
pub(crate) fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self {
let parent = options.parent_base;
+ let parent_ratio = options.parent_pixel_ratio.or_else(|| parent.map(|base| base.pixel_ratio));
+ let (size, size_underflow) = graph.resolved_output_size(parent.map(|base| (base.size, base.size_underflow)), None);
Self {
- size: parent.map_or_else(|| graph.size_px(), |base| base.size),
- seed: parent.map_or(graph.seed as u32, |base| base.seed),
- format: parent.map_or(graph.format, |base| base.format),
+ size,
+ dynamic_size: graph.absolute_output_size.is_none() && parent.is_some_and(|base| base.dynamic_size),
+ bound_size: graph.output_size_setting().0 != materialcraft_core::SizeMode::Absolute && parent.is_some_and(|base| base.bound_size),
+ bound_seed: false,
+ bound_image: false,
+ size_underflow,
+ seed: resolve_seed(graph.seed_mode, graph.seed, parent.map_or(0, |base| base.seed)),
+ format: match graph.format {
+ OutputFormat::Inherit => parent.map_or(OutputFormat::Inherit, |base| base.format),
+ explicit => explicit,
+ },
tiling: graph.tiling_mode.resolve(graph.tiling, options.parent_tiling, options.parent_tiling.unwrap_or(graph.tiling)),
- pixel_ratio: graph.pixel_ratio_mode.resolve(graph.pixel_ratio, options.parent_pixel_ratio, options.parent_pixel_ratio.unwrap_or(graph.pixel_ratio)),
+ pixel_ratio: graph.pixel_ratio_mode.resolve(graph.pixel_ratio, parent_ratio, parent_ratio.unwrap_or(1)),
pixel_size: parent.map_or([1.0; 2], |base| base.pixel_size),
}
}
+ fn graph_function_value(
+ self,
+ parameter: BaseParameter,
+ function: &materialcraft_core::FunctionGraph,
+ options: &crate::Options<'_>,
+ variables: &BTreeMap,
+ ) -> Result<(Value, bool, bool), String> {
+ let mut variables = variables.clone();
+ self.variables(&mut variables);
+ compile_with_literal_inputs(function, self.seed, &options.literal_inputs)
+ .and_then(|program| {
+ let dynamic = !program.output_is_literal() && !program.depends_only_on_image_size();
+ let bound = program.reads_graph_parameter(&variables);
+ let (value, _) = crate::parameter_function::evaluate(
+ &program,
+ parameter.value_type(),
+ &mut variables,
+ self.size,
+ crate::parameter_function::ParameterMode::for_base(parameter),
+ None,
+ None,
+ )?;
+ Ok((value, dynamic, bound))
+ })
+ .map_err(|error| format!("graph {}: {error}", parameter.label().to_ascii_lowercase()))
+ }
+
+ pub(crate) fn evaluate_graph_size(&mut self, graph: &Graph, options: &crate::Options<'_>, variables: &BTreeMap) -> Result<(), String> {
+ let Some(function) = &graph.output_size_function else { return Ok(()) };
+ let parent = options.parent_base.map(|base| (base.size, base.size_underflow));
+ let (size, size_underflow) = if graph.output_size_setting().0 == materialcraft_core::SizeMode::Absolute {
+ ([0; 2], [0; 2])
+ } else {
+ parent.unwrap_or_else(|| (graph.parent_size_px(), [0; 2]))
+ };
+ let context = Self { size, size_underflow, ..*self };
+ let (value, dynamic, bound) = context.graph_function_value(BaseParameter::OutputSize, function, options, variables)?;
+ let Value::Int2(offset) = value else { return Err("graph output size requires an integer pair".into()) };
+ (self.size, self.size_underflow) = graph.resolved_output_size(parent, Some(offset));
+ self.dynamic_size |= dynamic;
+ self.bound_size |= bound;
+ Ok(())
+ }
+
+ pub(crate) fn evaluate_graph_seed(&mut self, graph: &Graph, options: &crate::Options<'_>, variables: &BTreeMap) -> Result<(), String> {
+ let Some(function) = &graph.seed_function else { return Ok(()) };
+ let parent_seed = options.parent_base.map_or(0, |base| base.seed);
+ // Graph seed functions see the allocated dimensions even when descendants retain a negative size exponent.
+ let context = Self { seed: resolve_seed(graph.seed_mode, 0, parent_seed), size_underflow: [0; 2], ..*self };
+ let (value, _, _) = context.graph_function_value(BaseParameter::RandomSeed, function, options, variables)?;
+ let Value::Int(offset) = value else { return Err("graph random seed requires an integer".into()) };
+ self.seed = resolve_seed(graph.seed_mode, offset, parent_seed);
+ Ok(())
+ }
+
pub(crate) fn resolve(base: &BaseParameters, input: Option, parent: Self) -> Self {
- let size_base = BaseParameter::OutputSize.inheritance(base).resolve([1; 2], input.map(|base| base.size), parent.size);
+ let dimensions = |base: Self| (base.size, base.size_underflow);
+ let size_mode = BaseParameter::OutputSize.inheritance(base);
+ let (size_base, underflow) = size_mode.resolve(([1; 2], [0; 2]), input.map(dimensions), dimensions(parent));
+ let (size, size_underflow) = materialcraft_core::offset_dimensions(size_base, underflow, base.size);
- // Internal images may be one texel; the editor minimum would break size functions
- let size = std::array::from_fn(|axis| (f64::from(size_base[axis]) * 2f64.powi(base.size[axis].clamp(-12, 13))).round().clamp(1.0, 8192.0) as u32);
-
- // Images carry size and format, but do not carry a random stream
- // Relative seed modes use the graph seed without accumulating upstream seeds
- let inherited_seed = base.seed_mode.resolve(0, None, parent.seed);
let inherited_pixel_size = base.pixel_size_mode.resolve([1.0; 2], input.map(|base| base.pixel_size), parent.pixel_size);
Self {
size,
- seed: inherited_seed.wrapping_add(base.seed as u32),
+ size_underflow,
+ dynamic_size: size_mode.resolve(false, input.map(|base| base.dynamic_size), parent.dynamic_size),
+ bound_size: size_mode.resolve(false, input.map(|base| base.bound_size), parent.bound_size),
+ bound_seed: false,
+ bound_image: false,
+ seed: resolve_seed(base.seed_mode, base.seed, parent.seed),
format: BaseParameter::Format.inheritance(base).resolve(base.format, input.map(|base| base.format), parent.format),
tiling: base.tiling_mode.resolve(base.tiling, input.map(|base| base.tiling), parent.tiling),
pixel_ratio: base.pixel_ratio_mode.resolve(base.pixel_ratio, input.map(|base| base.pixel_ratio), parent.pixel_ratio),
- pixel_size: std::array::from_fn(|axis| (inherited_pixel_size[axis] * base.pixel_size[axis]).clamp(f32::MIN_POSITIVE, 8192.0)),
+ pixel_size: std::array::from_fn(|axis| (inherited_pixel_size[axis] * base.pixel_size[axis]).clamp(-8192.0, 8192.0)),
}
}
pub(crate) fn variables(self, variables: &mut BTreeMap) {
+ self.size_variables(variables);
variables.insert("$tiling".into(), Value::Int(i32::from(self.tiling[0]) | (i32::from(self.tiling[1]) << 1)));
variables.insert("$pixelratio".into(), Value::Int(self.pixel_ratio));
}
+
+ fn size_variables(self, variables: &mut BTreeMap) {
+ if self.size_underflow == [0; 2] {
+ variables.remove("$sizelog2");
+ } else {
+ let exponents =
+ std::array::from_fn(|axis| if self.size_underflow[axis] < 0 { self.size_underflow[axis] as f32 } else { (self.size[axis] as f32).log2() });
+ variables.insert("$sizelog2".into(), Value::Float2(exponents));
+ }
+ }
}
pub(crate) fn evaluate(
@@ -56,6 +155,8 @@ pub(crate) fn evaluate(
input: Option,
parent: ResolvedBaseParameters,
variables: &mut std::borrow::Cow<'_, BTreeMap>,
+ literal_inputs: &[String],
+ mut assigned_integers: Option<&mut Vec>,
) -> Result<(ResolvedBaseParameters, BTreeMap), String> {
if base.functions.is_empty() {
return Ok((ResolvedBaseParameters::resolve(base, input, parent), BTreeMap::new()));
@@ -78,6 +179,9 @@ pub(crate) fn evaluate(
pixel_ratio_mode: base.pixel_ratio_mode,
};
let mut values = BTreeMap::new();
+ let mut computed_size = false;
+ let mut bound_size = false;
+ let mut bound_seed = false;
let mut resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent);
// Size and seed establish the context used by the remaining parameter functions
@@ -92,12 +196,31 @@ pub(crate) fn evaluate(
if let Some(function) = base.functions.get(¶meter) {
resolved.variables(variables.to_mut());
let size = if parameter == BaseParameter::OutputSize && parameter.inheritance(base) != ParameterInheritance::Absolute {
- parameter.inheritance(base).resolve(parent.size, input.map(|base| base.size), parent.size)
+ let inherited = parameter.inheritance(base).resolve(parent, input, parent);
+ inherited.size_variables(variables.to_mut());
+ inherited.size
} else {
resolved.size
};
- let value = crate::parameter_function::evaluate(function, parameter.value_type(), variables.to_mut(), resolved.seed, size, false)
+ let (value, _) = compile_with_literal_inputs(function, resolved.seed, literal_inputs)
+ .and_then(|program| {
+ if parameter == BaseParameter::OutputSize {
+ computed_size = !program.output_is_literal() && !program.depends_only_on_image_size();
+ bound_size = program.reads_graph_parameter(variables);
+ } else if parameter == BaseParameter::RandomSeed {
+ bound_seed = program.reads_graph_parameter(variables);
+ }
+ crate::parameter_function::evaluate(
+ &program,
+ parameter.value_type(),
+ variables.to_mut(),
+ size,
+ crate::parameter_function::ParameterMode::for_base(parameter),
+ None,
+ assigned_integers.as_deref_mut(),
+ )
+ })
.map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?;
parameter.set_value(&mut evaluated, &value)?;
parameter.set_inheritance(&mut evaluated, parameter.inheritance(base));
@@ -107,5 +230,8 @@ pub(crate) fn evaluate(
values.insert(parameter, parameter.value(&evaluated));
}
+ resolved.dynamic_size |= computed_size;
+ resolved.bound_size |= bound_size;
+ resolved.bound_seed = bound_seed;
Ok((resolved, values))
}
diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs
index 79c6483c..68312cf4 100644
--- a/crates/eval/src/tests.rs
+++ b/crates/eval/src/tests.rs
@@ -1,3 +1,5 @@
+mod font_resource;
+
use crate::{cache_key::graph_tree_hash, graph_instance::instances_reach};
use craft_texture::{Image, Kind, Limits};
use materialcraft_core::{NodeId, Package, Value};
@@ -47,6 +49,99 @@ fn cooks_and_caches() {
assert_eq!(outputs(&p.graphs[0], &c).len(), 1);
}
+#[test]
+fn fixed_filters_preserve_each_tiling_axis_when_resizing_an_input() {
+ use materialcraft_core::{OutputFormat, ParameterInheritance, SizeMode};
+
+ for (filter, port) in [("levels", "input"), ("blend", "foreground"), ("warp", "input")] {
+ let mut graph = Graph::new("Tiling");
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let output = graph.add_node(filter, [100.0, 0.0]);
+ for (id, exponent) in [(input, 2), (output, 3)] {
+ let base = &mut graph.node_mut(id).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = [exponent; 2];
+ base.format = OutputFormat::U16;
+ }
+ graph.connect(input, "output", output, port).unwrap();
+ let mut package = Package::new("Tiling");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(4, 4, |x, y| ((4 * y + x) * 4096) as f32 / 65535.0));
+ let cache = Mutex::new(Cache::default());
+ for (tiling, expected) in [([false, false], 0), ([true, false], 3072), ([false, true], 12288), ([true, true], 15360), ([true, false], 3072)] {
+ let base = &mut package.graphs[0].node_mut(output).unwrap().base;
+ base.tiling_mode = ParameterInheritance::Absolute;
+ base.tiling = tiling;
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&output].error, None);
+ let pixel = result.image(output, 0).unwrap().get_gray(0, 0, false);
+ assert_eq!((pixel * 65535.0).round() as u32, expected, "{filter} {tiling:?}");
+ }
+ }
+}
+
+#[test]
+fn subtexel_size_exponents_survive_allocation_and_cache_reuse() {
+ use materialcraft_core::{FunctionGraph, OutputFormat, SizeMode};
+
+ let mut function = FunctionGraph::default();
+ let size = function.add("get_float2", &[], Some(Value::Text("$size".into())));
+ let log = function.add("get_float2", &[], Some(Value::Text("$sizelog2".into())));
+ function.output = Some(function.add("vector4", &[size, log], None));
+ let mut graph = Graph::new("Reduction");
+ graph.size = [7; 2];
+ graph.format = OutputFormat::F32;
+ let processor = graph.add_node("pixel_processor", [0.0; 2]);
+ let node = graph.node_mut(processor).unwrap();
+ node.params.insert("function".into(), Value::Function(Box::new(function)));
+ node.params.insert("color_mode".into(), Value::Bool(true));
+ node.base.size_mode = SizeMode::RelativeToParent;
+ let transform = graph.add_node("transformation", [120.0, 0.0]);
+ graph.node_mut(transform).unwrap().base.size = [3, 0];
+ graph.connect(processor, "output", transform, "input").unwrap();
+ let mut package = Package::new("Reduction");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+
+ for (offset, first, log, next_width) in [(-8, -2147483648.0, -1.0, 4), (-9, 1073741824.0, -2.0, 2), (-10, 536870912.0, -3.0, 1)] {
+ package.graphs[0].node_mut(processor).unwrap().base.size = [offset, -2];
+ let cooked = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert!(cooked.nodes.values().all(|result| result.error.is_none() && !result.cached));
+ let image = cooked.image(processor, 0).unwrap();
+ assert_eq!((image.width(), image.height()), (1, 32));
+ assert_eq!(image.get(0, 0, false), [first, 32.0, log, 5.0]);
+ assert_eq!(cooked.image(transform, 0).unwrap().width(), next_width);
+ }
+}
+
+#[test]
+fn value_processor_stores_integer_lanes_at_single_precision() {
+ use materialcraft_core::{FunctionGraph, ValueType};
+ let cache = Mutex::new(Cache::default());
+ let mut graph = Graph::new("Integer output");
+ let processor = graph.add_node("value_processor", [0.0; 2]);
+ let mut package = Package::new("Integer output");
+ package.graphs.push(graph);
+ for (kind, input, expected) in [
+ (ValueType::Integer, Value::Int(i32::MAX), Value::Int(i32::MIN)),
+ (ValueType::Integer2, Value::Int2([16_777_217, -16_777_219]), Value::Int2([16_777_216, -16_777_220])),
+ (ValueType::Integer3, Value::Int3([i32::MIN + 1, 2_147_483_583, 2_147_483_584]), Value::Int3([i32::MIN, 2_147_483_520, i32::MIN])),
+ (ValueType::Integer4, Value::Int4([-31, 0, 1, i32::MAX]), Value::Int4([-31, 0, 1, i32::MIN])),
+ ] {
+ for function in [FunctionGraph::input("numbers", kind), FunctionGraph::constant(input.clone())] {
+ package.graphs[0].node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ let mut options = Options::new(&no_res);
+ options.overrides.insert("numbers".into(), input.clone());
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.value(processor, 0), Some(&expected));
+ let cached = cook(&package, 0, &options, &cache);
+ assert!(cached.nodes[&processor].cached);
+ assert_eq!(cached.value(processor, 0), Some(&expected));
+ }
+ }
+}
+
#[test]
fn material_overrides_skip_bound_preview_decodes_and_release_buffers() {
let mut graph = Graph::new("Bound inputs");
@@ -245,6 +340,169 @@ fn preview_cap_and_unknown_nodes() {
assert!(c.nodes[&bad].error.is_some());
}
+#[test]
+fn typed_instance_ports_preserve_explicit_arguments_and_wire_fallbacks() {
+ use materialcraft_core::{FunctionGraph, ValueType};
+
+ let (mut parent, instance) = instancing("Caller", "Echo");
+ let wire = parent.add_node("input_value", [0.0; 2]);
+ parent.node_mut(wire).unwrap().params.insert("default".into(), Value::Int(9));
+ let mut child = Graph::new("Echo");
+ let bridge = child.add_node("input_value", [0.0; 2]);
+ child.node_mut(bridge).unwrap().params.extend([("identifier".into(), Value::Text("count".into())), ("default".into(), Value::Int(5))]);
+ let output = child.add_node("output", [0.0; 2]);
+ child.connect(bridge, "output", output, "input").unwrap();
+
+ let mut package = Package::new("Typed arguments");
+ package.graphs.extend([parent, child]);
+ let cache = Mutex::new(Cache::default());
+ let mut options = Options::new(&no_res);
+ options.overrides.insert("control".into(), Value::Int(-12));
+ for wired in [false, true] {
+ if wired {
+ package.graphs[0].connect(wire, "output", instance, "count").unwrap();
+ }
+ for (literal, function, expected) in [(None, false, if wired { 9 } else { 5 }), (Some(0), false, 0), (Some(-3), false, -3), (None, true, -12)] {
+ let node = package.graphs[0].node_mut(instance).unwrap();
+ node.params.remove("count");
+ node.functions.remove("count");
+ if let Some(value) = literal {
+ node.params.insert("count".into(), Value::Int(value));
+ }
+ if function {
+ node.functions.insert("count".into(), FunctionGraph::input("control", ValueType::Integer));
+ }
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&instance].error, None);
+ assert_eq!(cooked.nodes[&instance].outputs[0].as_value(), Some(&Value::Int(expected)), "wire {wired}, stored {literal:?}, function {function}");
+ }
+ }
+}
+
+#[test]
+fn cached_instances_distinguish_fixed_and_bound_integer_arguments() {
+ use materialcraft_core::{ExposedParameter, FunctionGraph, ValueType};
+ let (parent, instance) = instancing("Parent", "Selector");
+ let mut child = Graph::new("Selector");
+ child.exposed.push(ExposedParameter {
+ connectable: false,
+ id: "index".into(),
+ label: "Index".into(),
+ default: Value::Int(0),
+ description: String::new(),
+ group: String::new(),
+ editor: None,
+ clamp: false,
+ step: None,
+ min: -8.0,
+ max: 8.0,
+ options: Vec::new(),
+ });
+ let mut function = FunctionGraph::input("%index", ValueType::Integer);
+ let input = function.output.unwrap();
+ function.output = Some(function.add("tofloat", &[input], None));
+ let processor = child.add_node("value_processor", [0.0; 2]);
+ child.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ let output = child.add_node("output", [0.0; 2]);
+ child.connect(processor, "output", output, "input").unwrap();
+ let mut package = Package::new("Integer arguments");
+ package.graphs.extend([parent, child]);
+ let mut options = Options::new(&no_res);
+ options.overrides.insert("driver".into(), Value::Int(-5));
+ let cache = Mutex::new(Cache::default());
+ for bound in [false, true, false] {
+ let node = package.graphs[0].node_mut(instance).unwrap();
+ node.params.insert("index".into(), Value::Int(-5));
+ if bound {
+ node.bindings.insert("index".into(), "driver".into());
+ } else {
+ node.bindings.remove("index");
+ }
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&instance].error, None);
+ assert_eq!(result.nodes[&instance].outputs[0].as_value(), Some(&Value::Float(if bound { -5.0 } else { 4_294_967_296.0 })));
+ }
+}
+
+#[test]
+fn instanced_float_angles_keep_their_precision_across_an_unrelated_write() {
+ assert_instance_angle_precision(Value::Float(1.0));
+}
+
+#[test]
+fn instanced_vector_angles_preserve_fixed_and_parent_bound_precision() {
+ for turn in [Value::Float2([1.0, 0.25]), Value::Float3([1.0, 0.25, -0.5]), Value::Float4([1.0, 0.25, -0.5, 0.75])] {
+ assert_instance_angle_precision(turn);
+ }
+}
+
+fn assert_instance_angle_precision(argument: Value) {
+ use materialcraft_core::{ExposedParameter, FunctionGraph, GraphInstance, GraphPort, OutputFormat, ValueType};
+ let (parent, instance) = instancing("Parent", "Angle");
+ let mut child = Graph::new("Angle");
+ child.exposed.push(ExposedParameter {
+ id: "turn".into(),
+ label: "Turn".into(),
+ default: argument.clone(),
+ connectable: false,
+ clamp: false,
+ description: String::new(),
+ group: String::new(),
+ editor: None,
+ step: None,
+ min: -2.0,
+ max: 2.0,
+ options: Vec::new(),
+ });
+ let mut body = FunctionGraph::default();
+ let one = body.add_constant(Value::Float(1.0));
+ body.output = Some(body.add("set", &[one], Some(Value::Text("scratch".into()))));
+ let mut expression = FunctionGraph::input("turn", ValueType::of(&argument).unwrap());
+ let input = expression.output.unwrap();
+ let write = expression.add("instance", &[], None);
+ let call = expression.nodes.last_mut().unwrap();
+ call.instance = Some(GraphInstance {
+ label: String::new(),
+ graph: "Remember".into(),
+ package: String::new(),
+ inputs: Vec::new(),
+ outputs: vec![GraphPort { identifier: "output".into(), type_code: 256 }],
+ defaults: Default::default(),
+ });
+ call.source = Some(Ok(std::sync::Arc::new(body)));
+ let turn = if matches!(argument, Value::Float(_)) { input } else { expression.add("swizzle1", &[input], Some(Value::Int(0))) };
+ let tau = expression.add_constant(Value::Float(std::f32::consts::TAU));
+ let angle = expression.add("mul", &[turn, tau], None);
+ let sine = expression.add("sin", &[angle], None);
+ expression.output = Some(expression.add("sequence", &[write, sine], None));
+ let processor = child.add_node("pixel_processor", [0.0; 2]);
+ let pixel = child.node_mut(processor).unwrap();
+ pixel.base.format = OutputFormat::F32;
+ pixel.params.insert("function".into(), Value::Function(Box::new(expression)));
+ let output = child.add_node("output", [0.0; 2]);
+ child.connect(processor, "output", output, "input").unwrap();
+ let mut package = Package::new("Fixed and bound turns");
+ package.graphs.extend([parent, child]);
+ let mut options = Options::new(&no_res);
+ options.overrides.insert("driver".into(), argument.clone());
+ let cache = Mutex::new(Cache::default());
+ for (explicit, bound) in [(false, false), (true, false), (true, true), (true, false)] {
+ let node = package.graphs[0].node_mut(instance).unwrap();
+ if explicit {
+ node.params.insert("turn".into(), argument.clone());
+ }
+ if bound {
+ node.bindings.insert("turn".into(), "driver".into());
+ } else {
+ node.bindings.remove("turn");
+ }
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&instance].error, None);
+ let red = result.image(instance, 0).unwrap().get(0, 0, false)[0];
+ assert_eq!(red.to_bits(), if bound { (-0.0_f32).to_bits() } else { 0x343b_bd2e }, "{argument:?}, explicit {explicit}, bound {bound}");
+ }
+}
+
#[test]
fn graph_instances_cook_their_subgraph() {
let (mut p, ..) = sample();
@@ -290,6 +548,61 @@ fn instancing(name: &str, target: &str) -> (Graph, NodeId) {
(g, inst)
}
+#[test]
+fn an_instanced_graph_uses_its_declared_absolute_output_size() {
+ let (parent, instance) = instancing("Parent", "Rectangle");
+ let mut child = Graph::new("Rectangle");
+ child.absolute_output_size = Some([6, 5]);
+ let generator = child.add_node("uniform", [0.0; 2]);
+ let output = child.add_node("output", [100.0, 0.0]);
+ child.connect(generator, "output", output, "input").unwrap();
+ let mut package = Package::new("Dimensions");
+ package.graphs.extend([parent, child]);
+ let cache = Mutex::new(Cache::default());
+ for (size, expected) in [(Some([6, 5]), [64, 32]), (Some([5, 0]), [32, 1]), (None, [16, 16])] {
+ package.graphs[1].absolute_output_size = size;
+ let cooked = cook(&package, 0, &Options::new(&no_res), &cache);
+ let image = cooked.image(instance, 0).unwrap();
+ assert_eq!([image.width(), image.height()], expected);
+ assert_eq!(cooked.nodes[&instance].base.size, expected);
+ }
+}
+
+#[test]
+fn instance_outputs_keep_each_sources_dimensions_and_precision() {
+ use materialcraft_core::{OutputFormat, SizeMode};
+ let (mut parent, instance) = instancing("Parent", "TwoOutputs");
+ let mut source = Graph::new("TwoOutputs");
+ let mut consumers = Vec::new();
+ for (name, size, format) in [("output", [6, 5], OutputFormat::F32), ("small", [2, 3], OutputFormat::U8)] {
+ let fill = source.add_node("uniform", [0.0; 2]);
+ let base = &mut source.node_mut(fill).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = size;
+ base.format = format;
+ let bridge = source.add_node("output", [100.0, 0.0]);
+ source.node_mut(bridge).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
+ source.connect(fill, "output", bridge, "input").unwrap();
+ let consumer = parent.add_node("levels", [200.0, 0.0]);
+ parent.connect(instance, name, consumer, "input").unwrap();
+ consumers.push((consumer, size.map(|power| 1u32 << power), format));
+ }
+ let mut package = Package::new("Per-port dimensions");
+ package.graphs.extend([parent, source]);
+ let cache = Mutex::new(Cache::default());
+ for cached in [false, true] {
+ let cooked = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert_eq!(cooked.nodes[&instance].cached, cached);
+ for &(id, size, format) in &consumers {
+ let result = &cooked.nodes[&id];
+ assert_eq!(result.base.size, size);
+ assert_eq!(result.base.format, format);
+ let image = cooked.image(id, 0).unwrap();
+ assert_eq!([image.width(), image.height()], size);
+ }
+ }
+}
+
#[test]
fn editing_a_nested_graph_recooks_the_top() {
let mut c = Graph::new("c");
@@ -389,6 +702,1004 @@ fn same_size_resources_key_differently() {
assert!((second.image(bm, 0).unwrap().mean()[0] - mean).abs() > 0.05);
}
+#[test]
+fn box_blur_uses_the_resolved_pixel_size_on_each_axis() {
+ use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance};
+
+ let mut graph = Graph::new("Blur footprint");
+ graph.size = [5, 5];
+ graph.format = OutputFormat::F32;
+ let source = graph.add_node("input_grayscale", [0.0; 2]);
+ let blur = graph.add_node("blur", [0.0; 2]);
+ let node = graph.node_mut(blur).unwrap();
+ node.params.insert("intensity".into(), Value::Float(1.0));
+ node.base.pixel_size_mode = ParameterInheritance::Absolute;
+ graph.connect(source, "output", blur, "input").unwrap();
+ let mut package = Package::new("Blur footprint");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(32, 32, |x, y| f32::from(x == 16 && y == 16)));
+ let cache = Mutex::new(Cache::default());
+ for (size, expected) in
+ [([64.0, 64.0], [1.0 / 256.0, 1.0 / 512.0, 1.0 / 512.0]), ([1.0, 64.0], [1.0 / 16.0, 0.0, 1.0 / 32.0]), ([64.0, 1.0], [1.0 / 16.0, 1.0 / 32.0, 0.0])]
+ {
+ let base = &mut package.graphs[0].node_mut(blur).unwrap().base;
+ base.functions.insert(BaseParameter::PixelSize, FunctionGraph::constant(Value::Float2(size)));
+ let result = cook(&package, 0, &options, &cache);
+ let image = result.image(blur, 0).unwrap();
+ assert_eq!([(16, 16), (8, 16), (16, 8)].map(|(x, y)| image.get_gray(x, y, false)), expected, "pixel size {size:?}");
+ }
+}
+
+#[test]
+fn box_blur_multiplies_signed_pixel_sizes_before_limiting_its_radius() {
+ use materialcraft_core::{BaseParameter, OutputFormat, ParameterInheritance};
+
+ let mut graph = Graph::new("Inherited footprint");
+ graph.size = [5, 5];
+ graph.format = OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let blur = graph.add_node("blur", [0.0; 2]);
+ graph.node_mut(input).unwrap().base.pixel_size_mode = ParameterInheritance::Absolute;
+ graph.node_mut(blur).unwrap().base.pixel_size_mode = ParameterInheritance::RelativeToInput;
+ graph.node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(1.0));
+ graph.connect(input, "output", blur, "input").unwrap();
+ let mut package = Package::new("Inherited footprint");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(32, 32, |x, y| f32::from(x == 16 && y == 16)));
+ let cache = Mutex::new(Cache::default());
+ for (parent, factor, expected) in [([-2.0, 3.0], [-64.0, 8.0], 1.0 / 192.0), ([-2.0, 3.0], [64.0, -8.0], 1.0), ([0.0, 4.0], [8.0, -4.0], 1.0)] {
+ for (node, size) in [(input, parent), (blur, factor)] {
+ BaseParameter::PixelSize.set_value(&mut package.graphs[0].node_mut(node).unwrap().base, &Value::Float2(size)).unwrap();
+ }
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.image(blur, 0).unwrap().get_gray(16, 16, false), expected);
+ }
+}
+
+#[test]
+fn emboss_uses_the_resolved_pixel_size_on_each_axis() {
+ use materialcraft_core::{OutputFormat, ParameterInheritance};
+
+ let mut graph = Graph::new("Relief");
+ graph.size = [5, 5];
+ graph.format = OutputFormat::F32;
+ let [base, height] = ["base", "height"].map(|name| {
+ let id = graph.add_node("input_grayscale", [0.0; 2]);
+ graph.node_mut(id).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
+ id
+ });
+ let emboss = graph.add_node("emboss", [0.0; 2]);
+ let node = graph.node_mut(emboss).unwrap();
+ node.base.pixel_size_mode = ParameterInheritance::Absolute;
+ node.base.pixel_size = [0.5, 2.0];
+ node.params.insert("intensity".into(), Value::Float(1.0));
+ graph.connect(base, "output", emboss, "input").unwrap();
+ graph.connect(height, "output", emboss, "height").unwrap();
+ let mut package = Package::new("Relief");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("base".into(), Image::filled(32, 32, Kind::Gray, [0.5; 4]));
+ options.inputs.insert("height".into(), Image::gray(32, 32, |x, y| if x == 16 && y == 16 { 1.0 } else { 0.0 }));
+ let cache = Mutex::new(Cache::default());
+ for (angle, east, south, center) in [(0.0, 0.4375, 0.5, 0.5625), (0.25, 0.5, 0.25, 0.75)] {
+ package.graphs[0].node_mut(emboss).unwrap().params.insert("light_angle".into(), Value::Float(angle));
+ let result = cook(&package, 0, &options, &cache);
+ let image = result.image(emboss, 0).unwrap();
+ assert_eq!([image.get_gray(17, 16, false), image.get_gray(16, 17, false), image.get_gray(16, 16, false)], [east, south, center]);
+ }
+}
+
+#[test]
+fn bitmap_growth_maps_the_origin_and_half_texel_offset_separately() {
+ let mut graph = Graph::new("Column");
+ graph.size = [0, 6];
+ graph.format = materialcraft_core::OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let mut package = Package::new("Column");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ let column = Image::gray(1, 49, |_, y| {
+ f32::from_bits(match y {
+ 5 => 0xbeae_712e,
+ 6 => 0x3f90_4fe4,
+ _ => 0,
+ })
+ });
+ options.inputs.insert("input".into(), column);
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ assert_eq!(result.image(input, 0).unwrap().get_gray(0, 7, false).to_bits(), 0x3c73_7400);
+}
+
+#[test]
+fn filters_sample_bound_integer_bitmaps_at_the_source_depth() {
+ use OutputFormat::{F16, F32, U8, U16};
+ use materialcraft_core::{OutputFormat, ParameterInheritance};
+
+ let mut graph = Graph::new("Source precision");
+ graph.size = [5, 5];
+ graph.format = F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let transform = graph.add_node("transformation", [0.0; 2]);
+ let output = graph.add_node("output", [0.0; 2]);
+ let node = graph.node_mut(transform).unwrap();
+ node.base.format_mode = ParameterInheritance::Absolute;
+ node.base.format = F32;
+ node.params.insert("offset".into(), Value::Float2([15.0 / 1024.0, -21.0 / 1024.0]));
+ graph.connect(input, "output", transform, "input").unwrap();
+ graph.connect(input, "output", output, "input").unwrap();
+ let mut package = Package::new("Integer input");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ for (depth, bridge, expected) in [(U8, F16, 0x3eee_4eee), (U8, F32, 0x3eee_4eee), (U16, F32, 0x3eee_92ef), (U16, F16, 0x3eee_8000)] {
+ let node = package.graphs[0].node_mut(input).unwrap();
+ node.base.format_mode = ParameterInheritance::Absolute;
+ node.base.format = bridge;
+ let mut options = Options::new(&no_res);
+ options.bitmap_formats.insert("input".into(), depth);
+ let image = Image::gray(32, 17, |x, y| {
+ let level = if x % 2 == 0 { 9 } else { 243 };
+ if depth == U8 { level as f32 / 255.0 } else { (level * 257 + (7 * x + 3 * y) % 251) as f32 / 65535.0 }
+ });
+ options.inputs.insert("input".into(), image.with_integer_sampling(true));
+ for _ in 0..2 {
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ assert_eq!(result.image(transform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected);
+ if depth == U8 && bridge == F16 {
+ for id in [input, output] {
+ assert_eq!(result.image(id, 0).unwrap().get_gray(0, 0, false).to_bits(), 0x3d10_8000);
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn bitmap_half_storage_uses_the_original_integer_channel_depth() {
+ use materialcraft_core::OutputFormat::{F16, U8, U16};
+
+ let mut graph = Graph::new("Byte and word");
+ graph.size = [5, 5];
+ graph.format = F16;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let mut package = Package::new("Integer source");
+ package.graphs.push(graph);
+ for (depth, level, expected) in [
+ (U8, 9.0 / 255.0, [0x3d10_8000; 3]),
+ (U16, 2313.0 / 65535.0, [0x3d10_0000, 0x3d10_2000, 0x3d10_c000]),
+ (U16, 1.0, [0x3f7f_e000, 0x3f7f_e000, 0x3f80_0000]),
+ ] {
+ let mut options = Options::new(&no_res);
+ options.bitmap_formats.insert("input".into(), depth);
+ options.inputs.insert("input".into(), Image::filled(32, 17, Kind::Gray, [level; 4]).with_integer_sampling(true));
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ let image = result.image(input, 0).unwrap();
+ assert_eq!([0, 1, 2].map(|x| image.get_gray(x, 0, false).to_bits()), expected);
+ }
+}
+
+fn bitmap_impulse_graph() -> (Graph, NodeId, NodeId) {
+ use materialcraft_core::{OutputFormat, ParameterInheritance, PatternGraph, PatternNodeKind};
+
+ let mut graph = Graph::new("Bitmap mip levels");
+ graph.size = [4, 6];
+ graph.format = OutputFormat::U16;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let stamp = graph.add_node("fx_map", [0.0; 2]);
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ pattern.nodes[0].parameters.insert("patterntype".into(), Value::Int(1));
+ pattern.nodes[0].parameters.insert("patternsize".into(), Value::Float2([0.25; 2]));
+ let node = graph.node_mut(stamp).unwrap();
+ node.base.format_mode = ParameterInheritance::Absolute;
+ node.base.format = OutputFormat::U16;
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert("roughness".into(), Value::Float(0.0));
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+ graph.connect(input, "output", stamp, "pattern0").unwrap();
+ (graph, input, stamp)
+}
+
+#[test]
+fn pattern_mips_of_a_resized_bitmap_preserve_the_measured_impulse() {
+ let (graph, input, stamp) = bitmap_impulse_graph();
+ let mut package = Package::new("Impulse");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(32, 16, |x, y| f32::from(x == 10 && y == 8)));
+ let cache = Mutex::new(Cache::default());
+ for expected in [[0, 2048, 12288, 2048, 0], [0, 1280, 5632, 1280, 0]] {
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ let image = result.image(stamp, 0).unwrap();
+ let levels = [30, 31, 32, 33, 34].map(|y| (image.get_gray(7, y, false) * 65535.0).round() as u16);
+ assert_eq!(levels, expected);
+ // Binding the identical bridge pixels at their final size supplies an ordinary mip chain.
+ options.inputs.insert("input".into(), result.image(input, 0).unwrap().clone());
+ }
+}
+
+#[test]
+fn switch_color_storage_depends_on_whether_opacity_reads_a_graph_parameter() {
+ use materialcraft_core::{FunctionGraph, OutputFormat, ValueType};
+
+ let mut graph = Graph::new("Endpoint opacity");
+ graph.size = [2; 2];
+ let blend = graph.add_node("blend", [0.0; 2]);
+ graph.node_mut(blend).unwrap().params.insert("mode".into(), Value::Enum(7));
+ let mut options = Options::new(&no_res);
+ for (port, level) in [("foreground", 0.5), ("background", 0.25)] {
+ let input = graph.add_node("input_color", [0.0; 2]);
+ graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(port.into()));
+ graph.connect(input, "output", blend, port).unwrap();
+ options.inputs.insert(
+ port.into(),
+ Image::generate(4, 4, Kind::Color, |x, _| match x {
+ 0 => [level, -0.0, -0.25, -0.0],
+ 1 => [-level, -0.0, -0.25, -0.0],
+ _ => [f32::from_bits(0x8000_0001), level, 0.125, -0.0],
+ }),
+ );
+ }
+ let mut package = Package::new("Switch selection");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ for format in [OutputFormat::F16, OutputFormat::F32] {
+ package.graphs[0].format = format;
+ for (opacity, level) in [(0.0, 0.25), (1.0, 0.5)] {
+ options.overrides.insert("weight".into(), Value::Float(opacity));
+ for bound in [false, true, false] {
+ let node = package.graphs[0].node_mut(blend).unwrap();
+ node.params.insert("opacity".into(), Value::Float(opacity));
+ if bound {
+ node.functions.insert("opacity".into(), FunctionGraph::input("weight", ValueType::Float));
+ } else {
+ node.functions.remove("opacity");
+ }
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&blend].error, None);
+ assert_eq!(cooked.nodes[&blend].parameters["mode"], Value::Enum(7));
+ let image = cooked.image(blend, 0).unwrap();
+ let zero = if bound { 0.0_f32 } else { -0.0 };
+ assert_eq!(image.get(0, 0, false).map(f32::to_bits), [level, zero, -0.25, zero].map(f32::to_bits), "{format:?} {opacity} bound {bound}");
+ assert_eq!(image.get(1, 0, false).map(f32::to_bits), [-level, -0.0, -0.25, -0.0].map(f32::to_bits));
+ let tiny = if !bound && format == OutputFormat::F32 { f32::from_bits(0x8000_0001) } else { zero };
+ assert_eq!(image.get(2, 0, false).map(f32::to_bits), [tiny, level, 0.125, zero].map(f32::to_bits));
+ }
+ }
+ }
+}
+
+#[test]
+fn blend_preserves_the_selected_texture_levels_at_matching_precision() {
+ use materialcraft_core::{FunctionGraph, OutputFormat, ParameterInheritance, ValueType};
+
+ let (mut graph, input, stamp) = bitmap_impulse_graph();
+ let blend = graph.add_node("blend", [0.0; 2]);
+ graph.connect(input, "output", blend, "foreground").unwrap();
+ graph.connect(blend, "output", stamp, "pattern0").unwrap();
+ let mut package = Package::new("Selected impulse");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(32, 16, |x, y| f32::from(x == 10 && y == 8)));
+ options.overrides.insert("coverage".into(), Value::Float(1.0));
+ let cache = Mutex::new(Cache::default());
+ for (mode, format, bound, expected) in [
+ (7, OutputFormat::U16, false, [0, 2048, 12288, 2048, 0]),
+ (7, OutputFormat::U16, true, [0, 1280, 5632, 1280, 0]),
+ (0, OutputFormat::U16, false, [0, 2048, 12288, 2048, 0]),
+ (7, OutputFormat::U8, false, [0, 1285, 5654, 1285, 0]),
+ (7, OutputFormat::F32, false, [0, 1280, 5632, 1280, 0]),
+ ] {
+ let node = package.graphs[0].node_mut(blend).unwrap();
+ node.params.insert("mode".into(), Value::Enum(mode));
+ node.base.format_mode = ParameterInheritance::Absolute;
+ node.base.format = format;
+ if bound {
+ node.functions.insert("opacity".into(), FunctionGraph::input("coverage", ValueType::Float));
+ } else {
+ node.functions.remove("opacity");
+ }
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ let image = result.image(stamp, 0).unwrap();
+ let levels = [30, 31, 32, 33, 34].map(|y| (image.get_gray(7, y, false) * 65535.0).round() as u16);
+ assert_eq!(levels, expected);
+ }
+}
+
+#[test]
+fn bound_float_bitmap_reduces_close_texels_at_the_measured_filter_precision() {
+ let mut graph = Graph::new("Row reduction");
+ graph.size = [4, 0];
+ graph.format = materialcraft_core::OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let mut package = Package::new("Row reduction");
+ package.graphs.push(graph);
+ for (width, row, sample, expected) in [(47, 15, 11, 0x3f00_001d), (65, 14, 9, 0x3f00_001d), (67, 14, 4, 0x3f00_001f)] {
+ let image = Image::gray(width, 1, |x, _| f32::from_bits(0x3f00_0000 + (13 * x + 7 * row + 3 * x * row + row * row) % 64));
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), image);
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ assert_eq!(result.image(input, 0).unwrap().get_gray(sample, 0, false).to_bits(), expected);
+ }
+}
+
+#[test]
+fn bound_float_bitmap_diffuses_half_rounding_after_resizing() {
+ let mut graph = Graph::new("Half input");
+ graph.size = [5, 5];
+ graph.format = materialcraft_core::OutputFormat::F16;
+ let input = graph.add_node("input_color", [0.0; 2]);
+ let mut package = Package::new("Half input");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::filled(32, 17, Kind::Color, [1.0 + 1.0 / 2048.0, -1.0, 0.125, 0.12505]));
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ let image = result.image(input, 0).unwrap();
+ assert_eq!(image.get(0, 0, false), [1.0 + 1.0 / 1024.0, 0.0, 0.125, 0.125]);
+ assert_eq!(image.get(1, 0, false), [1.0, 0.0, 0.125, 0.125]);
+ assert_eq!(image.get(2, 0, false), [1.0 + 1.0 / 1024.0, 0.0, 0.125, 0.125 + 1.0 / 8192.0]);
+}
+
+#[test]
+fn bitmap_node_filters_odd_rasters_at_their_original_channel_depth() {
+ use materialcraft_core::{OutputFormat, Resource, ResourceBytes};
+
+ let mut graph = Graph::new("Odd bitmap");
+ graph.size = [5, 5];
+ graph.format = OutputFormat::U16;
+ let bitmap = graph.add_node("bitmap", [0.0; 2]);
+ let node = graph.node_mut(bitmap).unwrap();
+ node.params.insert("resource".into(), Value::Text("field".into()));
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ let mut package = Package::new("Grayscale bitmap");
+ package.graphs.push(graph);
+ for (depth, expected) in [(8_u8, [11308, 30326, 40349, 49087]), (16, [419, 4749, 33094, 35028])] {
+ let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
+ header.extend_from_slice(&37_u32.to_be_bytes());
+ header.extend_from_slice(&23_u32.to_be_bytes());
+ header.extend([depth, 0, 0, 0, 0]);
+ package.resources = vec![Resource::new("field", "field.png", ResourceBytes::new(header))];
+ let field = Image::gray(37, 23, |x, y| {
+ if depth == 8 {
+ ((83 * x + 151 * y + 11 * x * y + 29) % 256) as f32 / 255.0
+ } else {
+ ((573 * x + 149 * y + 97 * x * y + 317) % 65536) as f32 / 65535.0
+ }
+ })
+ .with_integer_sampling(true);
+ let resource = |_: &str| Some(field.clone());
+ let result = cook(&package, 0, &Options::new(&resource), &Mutex::new(Cache::default()));
+ let image = result.image(bitmap, 0).unwrap();
+ let levels = [(0, 0), (3, 7), (16, 16), (31, 31)].map(|(x, y)| (image.get_gray(x, y, false) * 65535.0).round() as u16);
+ assert_eq!(levels, expected);
+ }
+}
+
+#[test]
+fn odd_color_bitmap_resources_keep_their_channel_depth_during_filtering() {
+ use materialcraft_core::{OutputFormat, Resource, ResourceBytes};
+
+ let mut graph = Graph::new("Odd color bitmap");
+ graph.size = [4, 4];
+ graph.format = OutputFormat::U16;
+ let bitmap = graph.add_node("bitmap", [0.0; 2]);
+ let node = graph.node_mut(bitmap).unwrap();
+ node.params.insert("resource".into(), Value::Text("field".into()));
+ node.params.insert("colour_space".into(), Value::Enum(1));
+ let mut package = Package::new("Color bitmap");
+ package.graphs.push(graph);
+
+ for (width, height, depth, expected) in [
+ (29_u32, 47_u32, 8, [[26985, 34181, 37522, 33924], [29555, 33667, 31354, 39321]]),
+ (41, 27, 16, [[4100, 4730, 9310, 10498], [39835, 29231, 35098, 11450]]),
+ ] {
+ let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();
+ header.extend_from_slice(&width.to_be_bytes());
+ header.extend_from_slice(&height.to_be_bytes());
+ header.extend([depth, 6, 0, 0, 0]);
+ package.resources = vec![Resource::new("field", "field.png", ResourceBytes::new(header))];
+ let levels = 1_u32 << depth;
+ let field = Image::generate(width, height, Kind::Color, |x, y| {
+ [(583, 191, 371, 3229), (47, 313, 59, 4511), (31, 693, 41, 8943), (997, 811, 97, 9043)]
+ .map(|(a, b, c, d)| ((a * x + b * y + c * x * y + d) % levels) as f32 / (levels - 1) as f32)
+ })
+ .with_integer_sampling(true);
+ let resource = |key: &str| (craft_texture::split_resource_key(key) == ("field", true)).then(|| field.clone());
+ let result = cook(&package, 0, &Options::new(&resource), &Mutex::new(Cache::default()));
+ let image = result.image(bitmap, 0).unwrap();
+ assert_eq!([(0, 0), (6, 11)].map(|(x, y)| image.get(x, y, false).map(|v| (v * 65535.0).round() as u16)), expected);
+ }
+}
+
+#[test]
+fn bound_float_image_filters_an_odd_impulse_on_each_axis() {
+ let mut graph = Graph::new("Impulse");
+ graph.size = [4, 4];
+ graph.format = materialcraft_core::OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let mut package = Package::new("Float input");
+ package.graphs.push(graph);
+ for (width, height, center) in [(3, 3, 0x3f524000), (35, 21, 0x3dbac261)] {
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(width, height, |x, y| f32::from(x == width / 2 && y == height / 2)));
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ assert_eq!(result.image(input, 0).unwrap().get_gray(8, 8, false).to_bits(), center);
+ }
+}
+
+#[test]
+fn bound_float_image_with_an_odd_height_retains_its_stored_word_levels() {
+ let mut graph = Graph::new("Odd height");
+ graph.size = [5, 5];
+ graph.format = materialcraft_core::OutputFormat::U16;
+ let input = graph.add_node("input_color", [0.0; 2]);
+ let mut package = Package::new("Word input");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::filled(32, 17, Kind::Color, [0.21875, 0.25, 0.5, 0.75]));
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ let image = result.image(input, 0).unwrap();
+ let levels = |x, y| image.get(x, y, false).map(|v| (v * 65535.0).round() as u16);
+ assert_eq!(levels(0, 0), [14335, 16383, 32768, 49152]);
+ assert_eq!(levels(1, 0), [14336, 16384, 32767, 49151]);
+ assert_eq!(levels(0, 2), [14336, 16384, 32768, 49151]);
+}
+
+#[test]
+fn bound_image_resizing_filters_normalized_levels_before_float_storage() {
+ let mut graph = Graph::new("levels");
+ graph.size = [4, 4];
+ graph.format = materialcraft_core::OutputFormat::F32;
+ let input = graph.add_node("input_color", [0.0; 2]);
+ let mut package = Package::new("levels");
+ package.graphs.push(graph);
+ let stripe = Image::generate(8, 8, Kind::Color, |x, _| [(x % 2) as f32; 4]);
+ let cache = Mutex::new(Cache::default());
+ for (normalized, expected) in [(true, 16384.0 / 65535.0), (false, 0.25)] {
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), stripe.clone().with_integer_sampling(normalized));
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.image(input, 0).unwrap().get(1, 0, false), [expected; 4]);
+ assert_eq!(result.image(input, 0).unwrap().get(0, 0, false), [0.0; 4]);
+ }
+}
+
+#[test]
+fn bound_image_resizing_filters_rgb_before_grayscale_conversion() {
+ let mut graph = Graph::new("Grayscale input");
+ graph.size = [4, 4];
+ graph.format = materialcraft_core::OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let mut package = Package::new("Channel order");
+ package.graphs.push(graph);
+ let level = 1.0 / 65535.0;
+ let stripe = Image::generate(8, 8, Kind::Color, |x, _| [if x % 2 == 1 { level } else { 0.0 }, 0.0, 0.0, 1.0]);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), stripe.with_integer_sampling(true));
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ let image = result.image(input, 0).unwrap();
+ assert_eq!(image.get(1, 0, false)[0], 0.0);
+ assert_eq!(image.get(2, 0, false)[0], level * (1.0 / 3.0));
+}
+
+fn unchanged_size_after_read(getter: &str, variable: &str) -> materialcraft_core::FunctionGraph {
+ let mut graph = materialcraft_core::FunctionGraph::default();
+ let read = graph.add(getter, &[], Some(Value::Text(variable.into())));
+ let zero = graph.add_constant(Value::Int2([0, 0]));
+ graph.output = Some(graph.add("sequence", &[read, zero], None));
+ graph
+}
+
+#[test]
+fn filters_store_normalized_inputs_at_their_working_precision_when_one_size_is_parameter_controlled() {
+ use materialcraft_core::{BaseParameter, OutputFormat, SizeMode};
+
+ let mut graph = Graph::new("Filter sizing");
+ graph.size = [4, 4];
+ graph.format = OutputFormat::U8;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let source = graph.node_mut(input).unwrap();
+ source.params.insert("identifier".into(), Value::Text("source".into()));
+ source.base.size_mode = SizeMode::RelativeToParent;
+ let levels = graph.add_node("levels", [64.0, 0.0]);
+ let curve = graph.node_mut(levels).unwrap();
+ curve.base.size_mode = SizeMode::RelativeToParent;
+ curve.base.format = OutputFormat::F16;
+ curve.params.insert("in_low".into(), Value::Float4([0.21875; 4]));
+ curve.params.insert("in_high".into(), Value::Float4([0.46875; 4]));
+ graph.connect(input, "output", levels, "input").unwrap();
+ let sharpen = graph.add_node("sharpen", [64.0, 64.0]);
+ let detail = graph.node_mut(sharpen).unwrap();
+ detail.base.size_mode = SizeMode::RelativeToParent;
+ detail.base.format = OutputFormat::F16;
+ graph.connect(input, "output", sharpen, "input").unwrap();
+ let [blur, fractional_half, fractional_float] =
+ [(24.0, OutputFormat::F16), (32.0, OutputFormat::F16), (32.0, OutputFormat::F32)].map(|(intensity, format)| {
+ let blur = graph.add_node("blur", [64.0, 128.0]);
+ let smooth = graph.node_mut(blur).unwrap();
+ smooth.base.size_mode = SizeMode::RelativeToParent;
+ smooth.base.format = format;
+ smooth.params.insert("intensity".into(), Value::Float(intensity));
+ graph.connect(input, "output", blur, "input").unwrap();
+ blur
+ });
+ let mut package = Package::new("Input precision");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ let field = Image::generate(16, 16, Kind::Gray, |x, y| {
+ let byte: u8 = match (x, y) {
+ (7, 8) => 5,
+ (9, 8) => 78,
+ (8, 7) => 31,
+ (8, 9) => 42,
+ _ => 58,
+ };
+ [f32::from(byte) / 255.0; 4]
+ });
+ options.inputs.insert("source".into(), field);
+ options.overrides.insert("gain".into(), Value::Float(0.375));
+ let cache = Mutex::new(Cache::default());
+ let runtime = unchanged_size_after_read("get_float1", "gain");
+ for (source_dynamic, output_dynamic) in [(false, false), (true, false), (false, true), (true, true)] {
+ let [expected_levels, expected_sharpen, expected_blur, expected_half, expected_float] = if source_dynamic == output_dynamic {
+ [0x3d0e8000, 0x3f1e8000, 0x3e3e0000, 0x3e572000, 0x3e673a97]
+ } else {
+ [0x3d0e0000, 0x3f1e6000, 0x3e3de000, 0x3e570000, 0x3e673a99]
+ };
+ for (id, dynamic) in [
+ (input, source_dynamic),
+ (levels, output_dynamic),
+ (sharpen, output_dynamic),
+ (blur, output_dynamic),
+ (fractional_half, output_dynamic),
+ (fractional_float, output_dynamic),
+ ] {
+ let functions = &mut package.graphs[0].node_mut(id).unwrap().base.functions;
+ if dynamic {
+ functions.insert(BaseParameter::OutputSize, runtime.clone());
+ } else {
+ functions.remove(&BaseParameter::OutputSize);
+ }
+ }
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&levels].error, None);
+ assert_eq!(cooked.image(levels, 0).unwrap().get_gray(0, 0, false).to_bits(), expected_levels);
+ assert_eq!(cooked.nodes[&sharpen].error, None);
+ assert_eq!(cooked.image(sharpen, 0).unwrap().get_gray(9, 8, false).to_bits(), expected_sharpen);
+ assert_eq!(cooked.nodes[&blur].error, None);
+ assert_eq!(cooked.image(blur, 0).unwrap().get_gray(7, 8, false).to_bits(), expected_blur);
+ assert_eq!(cooked.nodes[&fractional_half].error, None);
+ assert_eq!(cooked.image(fractional_half, 0).unwrap().get_gray(6, 7, false).to_bits(), expected_half);
+ assert_eq!(cooked.nodes[&fractional_float].error, None);
+ assert_eq!(cooked.image(fractional_float, 0).unwrap().get_gray(6, 5, false).to_bits(), expected_float);
+ }
+}
+
+#[test]
+fn half_blends_store_integer_inputs_on_different_size_paths() {
+ use materialcraft_core::{BaseParameter, OutputFormat, SizeMode};
+
+ let mut graph = Graph::new("Blend sizing");
+ graph.size = [1, 0];
+ graph.format = OutputFormat::U8;
+ let [foreground, background] = ["foreground", "background"].map(|identifier| {
+ let id = graph.add_node("input_grayscale", [0.0; 2]);
+ let node = graph.node_mut(id).unwrap();
+ node.params.insert("identifier".into(), Value::Text(identifier.into()));
+ node.base.size_mode = SizeMode::RelativeToParent;
+ id
+ });
+ let bridge = graph.add_node("dot", [0.0; 2]);
+ let blend = graph.add_node("blend", [0.0; 2]);
+ let node = graph.node_mut(blend).unwrap();
+ node.base.format = OutputFormat::F16;
+ node.params.insert("opacity".into(), Value::Float(0.4));
+ graph.connect(foreground, "output", bridge, "input").unwrap();
+ graph.connect(bridge, "output", blend, "foreground").unwrap();
+ graph.connect(background, "output", blend, "background").unwrap();
+ let mut package = Package::new("Blend sizing");
+ package.graphs.push(graph);
+
+ let dimensions = unchanged_size_after_read("get_float2", "$size");
+ let runtime = unchanged_size_after_read("get_float1", "gain");
+ let mut options = Options::new(&no_res);
+ options.overrides.insert("gain".into(), Value::Float(0.375));
+ for (name, levels) in [("foreground", [71.0, 55.0]), ("background", [155.0, 1.0])] {
+ options.inputs.insert(name.into(), Image::gray(2, 1, |x, _| levels[x as usize] / 255.0));
+ }
+ let cache = Mutex::new(Cache::default());
+ for (front, back, inherit, expected) in [
+ (false, false, false, [0x3ef3c000, 0x3db58000]),
+ (true, false, false, [0x3ef3a000, 0x3db56000]),
+ (false, true, false, [0x3ef38000, 0x3db58000]),
+ (true, true, false, [0x3ef38000, 0x3db56000]),
+ (false, true, true, [0x3ef3a000, 0x3db56000]),
+ (true, true, true, [0x3ef3c000, 0x3db58000]),
+ ] {
+ let graph = &mut package.graphs[0];
+ for (id, dynamic) in [(foreground, front), (background, back)] {
+ graph.node_mut(id).unwrap().base.functions.insert(BaseParameter::OutputSize, if dynamic { runtime.clone() } else { dimensions.clone() });
+ }
+ graph.node_mut(blend).unwrap().base.size_mode = if inherit { SizeMode::RelativeToInput } else { SizeMode::RelativeToParent };
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ let pixels = result.image(blend, 0).unwrap();
+ assert_eq!([0, 1].map(|x| pixels.get_gray(x, 0, false).to_bits()), expected);
+ assert!(cook(&package, 0, &options, &cache).nodes[&blend].cached);
+ }
+}
+
+#[test]
+fn half_pattern_backgrounds_store_integer_inputs_on_different_size_paths() {
+ use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, PatternGraph, PatternNodeKind, SizeMode};
+
+ let mut graph = Graph::new("Pattern background sizing");
+ graph.size = [4, 4];
+ graph.format = OutputFormat::U8;
+ let background = graph.add_node("input_grayscale", [0.0; 2]);
+ let draw = graph.add_node("fx_map", [0.0; 2]);
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ let stamp = &mut pattern.nodes[0].parameters;
+ stamp.insert("patterntype".into(), Value::Int(2));
+ let level = 3.0 / 32768.0;
+ stamp.insert("opacity".into(), Value::Float4([level, level, level, 1.0]));
+ let node = graph.node_mut(draw).unwrap();
+ node.base.size_mode = SizeMode::RelativeToParent;
+ node.base.format = OutputFormat::F16;
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+ graph.connect(background, "output", draw, "background").unwrap();
+
+ let mut package = Package::new("Pattern sizing");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(16, 16, |_, _| 58.0 / 255.0));
+ options.overrides.insert("gain".into(), Value::Float(0.375));
+ let cache = Mutex::new(Cache::default());
+ let fixed = FunctionGraph::constant(Value::Int2([0, 0]));
+ let system = unchanged_size_after_read("get_float2", "$sizelog2");
+ let exposed = unchanged_size_after_read("get_float1", "gain");
+ for (source_size, draw_size, expected) in [(&fixed, &system, 1864.0), (&fixed, &exposed, 1863.0), (&exposed, &fixed, 1863.0), (&exposed, &exposed, 1864.0)]
+ {
+ for (id, size) in [(background, source_size), (draw, draw_size)] {
+ package.graphs[0].node_mut(id).unwrap().base.functions.insert(BaseParameter::OutputSize, size.clone());
+ }
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ assert_eq!(result.image(draw, 0).unwrap().get_gray(8, 8, false), expected / 8192.0);
+ }
+}
+
+#[test]
+fn untiled_pattern_backgrounds_sample_directly_on_the_same_size_path() {
+ use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance, PatternGraph, PatternNodeKind, SizeMode};
+
+ let mut graph = Graph::new("Resized pattern background");
+ graph.size = [4, 5];
+ graph.format = OutputFormat::U8;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let background = graph.add_node("fx_map", [0.0; 2]);
+ let draw = graph.add_node("fx_map", [0.0; 2]);
+ let levels = graph.add_node("levels", [0.0; 2]);
+ for id in [input, background, levels] {
+ let base = &mut graph.node_mut(id).unwrap().base;
+ base.size_mode = SizeMode::RelativeToParent;
+ base.size = [-1, -1];
+ }
+ for id in [background, draw] {
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ if id == draw {
+ let stamp = &mut pattern.nodes[0].parameters;
+ stamp.insert("patterntype".into(), Value::Int(2));
+ stamp.insert("opacity".into(), Value::Float4([0.10067749, 0.10067749, 0.10067749, 1.0]));
+ }
+ let node = graph.node_mut(id).unwrap();
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ }
+ graph.connect(input, "output", background, "background").unwrap();
+ graph.connect(background, "output", levels, "input").unwrap();
+ let mut package = Package::new("Pattern sample precision");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(8, 16, |x, y| ((47 * x + 83 * y + 11 * x * y + 849807) % 256) as f32 / 255.0));
+ options.overrides.insert("gain".into(), Value::Float(0.375));
+ let cache = Mutex::new(Cache::default());
+
+ let fixed = FunctionGraph::constant(Value::Int2([0, 0]));
+ let exposed = unchanged_size_after_read("get_float1", "gain");
+ for (source, tiling, size, byte, half, corner) in [
+ (input, [false, false], &fixed, 128.0, 0.5317383, 169.0),
+ (background, [false, false], &fixed, 128.0, 0.5317383, 169.0),
+ (background, [true, false], &fixed, 129.0, 0.53125, 171.0),
+ (levels, [false, false], &fixed, 128.0, 0.5317383, 169.0),
+ (levels, [true, true], &fixed, 129.0, 0.53125, 171.0),
+ (background, [false, false], &exposed, 129.0, 0.53125, 171.0),
+ ] {
+ let graph = &mut package.graphs[0];
+ graph.connect(source, "output", draw, "background").unwrap();
+ let base = &mut graph.node_mut(source).unwrap().base;
+ base.tiling_mode = ParameterInheritance::Absolute;
+ base.tiling = tiling;
+ let base = &mut graph.node_mut(draw).unwrap().base;
+ base.tiling_mode = ParameterInheritance::Absolute;
+ base.tiling = [true, true];
+ base.size_mode = SizeMode::RelativeToParent;
+ base.functions.insert(BaseParameter::OutputSize, size.clone());
+ for (format, x, expected) in [(OutputFormat::U8, 2, byte / 255.0), (OutputFormat::F16, 4, half)] {
+ package.graphs[0].node_mut(draw).unwrap().base.format = format;
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ let pixels = result.image(draw, 0).unwrap();
+ assert_eq!(pixels.get_gray(x, 2, false), expected, "{format:?}");
+ if format == OutputFormat::U8 {
+ assert_eq!(pixels.get_gray(0, 0, false), corner / 255.0);
+ }
+ }
+ }
+
+ // Enlarge only Y. Repeating X still permits a direct sample.
+ let graph = &mut package.graphs[0];
+ graph.connect(input, "output", draw, "background").unwrap();
+ graph.node_mut(input).unwrap().base.size = [0, -1];
+ let draw_base = &mut graph.node_mut(draw).unwrap().base;
+ draw_base.tiling = [false, false];
+ draw_base.format = OutputFormat::U8;
+ draw_base.functions.insert(BaseParameter::OutputSize, fixed);
+ options.inputs.insert("input".into(), Image::gray(16, 16, |x, y| ((47 * x + 83 * y + 11 * x * y + 849807) % 256) as f32 / 255.0));
+ for (source_tiling, byte) in [([true, false], 149.0), ([false, true], 150.0)] {
+ package.graphs[0].node_mut(input).unwrap().base.tiling = source_tiling;
+ let result = cook(&package, 0, &options, &cache);
+ assert!(result.nodes.values().all(|node| node.error.is_none()));
+ assert_eq!(result.image(draw, 0).unwrap().get_gray(2, 2, false), byte / 255.0);
+ }
+}
+
+#[test]
+fn connected_input_sizes_share_the_last_two_dimensional_filter_pass() {
+ use materialcraft_core::{OutputFormat, SizeMode};
+ let (mut parent, instance) = instancing("Parent", "Resize");
+ let source = parent.add_node("input_color", [0.0; 2]);
+ let source_base = &mut parent.node_mut(source).unwrap().base;
+ source_base.size_mode = SizeMode::Absolute;
+ source_base.format = OutputFormat::F32;
+ parent.connect(source, "output", instance, "input").unwrap();
+ let mut child = Graph::new("Resize");
+ let bridge = child.add_node("input_color", [0.0; 2]);
+ let inner_base = &mut child.node_mut(bridge).unwrap().base;
+ inner_base.size_mode = SizeMode::Absolute;
+ inner_base.size = [4, 3];
+ inner_base.format = OutputFormat::F16;
+ let output = child.add_node("output", [0.0; 2]);
+ child.connect(bridge, "output", output, "input").unwrap();
+ let mut package = Package::new("Rectangular input");
+ package.graphs.extend([parent, child]);
+ let mut options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ let high = 1.0 + 1.0 / 1024.0;
+ for (size, red, green) in [([5, 5], high, 1.0), ([6, 4], 1.0, high), ([5, 4], 1.0, 1.0)] {
+ package.graphs[0].node_mut(source).unwrap().base.size = size;
+ let image = Image::generate(1 << size[0], 1 << size[1], Kind::Color, |x, y| {
+ let r = if x % 2 == 0 { 1.0 } else { high };
+ let g = if y % 2 == 0 { 1.0 } else { high };
+ [r, g, -r, -g]
+ });
+ options.inputs.insert("input".into(), image);
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&instance].error, None);
+ let image = result.image(instance, 0).unwrap();
+ assert_eq!((image.width(), image.height()), (16, 8));
+ assert!(
+ image.data().as_chunks::<4>().0.iter().all(|&pixel| pixel == [red, green, -red, -green]),
+ "source {size:?}, first {:?}",
+ image.get(0, 0, false)
+ );
+ }
+}
+
+#[test]
+fn an_image_bridge_resolves_its_size_against_its_own_wire() {
+ use materialcraft_core::SizeMode;
+
+ let (mut parent, connected) = instancing("Parent", "Bridge");
+ let unconnected = parent.add_node("graph_instance", [0.0, 80.0]);
+ parent.node_mut(unconnected).unwrap().params.insert("graph".into(), Value::Text("Bridge".into()));
+ for id in [connected, unconnected] {
+ let base = &mut parent.node_mut(id).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = [6; 2];
+ }
+ let input = parent.add_node("input_grayscale", [0.0; 2]);
+ let source = &mut parent.node_mut(input).unwrap().base;
+ source.size_mode = SizeMode::Absolute;
+ source.size = [4, 5];
+ parent.connect(input, "output", connected, "input").unwrap();
+
+ let mut child = Graph::new("Bridge");
+ let bridge = child.add_node("input_grayscale", [0.0; 2]);
+ let output = child.add_node("output", [100.0, 0.0]);
+ child.connect(bridge, "output", output, "input").unwrap();
+ let mut package = Package::new("Bridge sizes");
+ package.graphs.extend([parent, child]);
+ let options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ for (mode, size, expected) in [
+ (SizeMode::RelativeToInput, [0, 0], [(16, 32), (64, 64)]),
+ (SizeMode::RelativeToInput, [-1, 1], [(8, 64), (32, 128)]),
+ (SizeMode::RelativeToParent, [0, 0], [(64, 64); 2]),
+ (SizeMode::Absolute, [5, 4], [(32, 16); 2]),
+ ] {
+ let base = &mut package.graphs[1].node_mut(bridge).unwrap().base;
+ base.size_mode = mode;
+ base.size = size;
+ let cooked = cook(&package, 0, &options, &cache);
+ let dimensions = [connected, unconnected].map(|id| {
+ assert_eq!(cooked.nodes[&id].error, None);
+ let image = cooked.image(id, 0).unwrap();
+ (image.width(), image.height())
+ });
+ assert_eq!(dimensions, expected);
+ }
+}
+
+#[test]
+fn bound_image_resizing_reads_the_upstream_float_format_inside_instances() {
+ use materialcraft_core::{OutputFormat, SizeMode};
+ let (mut parent, instance) = instancing("Parent", "Resized");
+ let source = parent.add_node("input_grayscale", [0.0; 2]);
+ let base = &mut parent.node_mut(source).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = [3, 3];
+ parent.connect(source, "output", instance, "input").unwrap();
+ let mut child = Graph::new("Resized");
+ child.absolute_output_size = Some([4, 4]);
+ let bridge = child.add_node("input_grayscale", [0.0; 2]);
+ child.node_mut(bridge).unwrap().base.size_mode = SizeMode::RelativeToParent;
+ child.node_mut(bridge).unwrap().base.format = OutputFormat::F32;
+ let output = child.add_node("output", [100.0, 0.0]);
+ child.connect(bridge, "output", output, "input").unwrap();
+ let mut package = Package::new("Stored levels");
+ package.graphs.extend([parent, child]);
+ let corners = [0x3fd0e000, 0xbfa46000, 0xc02d8000, 0x407f0000];
+ let image = Image::gray(8, 8, |x, y| f32::from_bits(corners[((y % 2) * 2 + x % 2) as usize]));
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), image);
+ let cache = Mutex::new(Cache::default());
+ for (format, expected) in [(OutputFormat::F32, 0x3ed5f000), (OutputFormat::F16, 0x3ed60000), (OutputFormat::F32, 0x3ed5f000)] {
+ package.graphs[0].node_mut(source).unwrap().base.format = format;
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&instance].error, None);
+ assert_eq!(cooked.image(instance, 0).unwrap().get(1, 1, false)[0].to_bits(), expected);
+ }
+}
+
+#[test]
+fn wired_input_sampling_keeps_the_source_texture_and_stores_the_direct_output() {
+ use materialcraft_core::{FunctionGraph, OutputFormat, ParameterInheritance, SizeMode};
+ let (mut parent, instance) = instancing("Parent", "TwoReads");
+ let source = parent.add_node("input_grayscale", [0.0; 2]);
+ let base = &mut parent.node_mut(source).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = [3, 3];
+ base.format = OutputFormat::U8;
+ parent.connect(source, "output", instance, "input").unwrap();
+ let mut child = Graph::new("TwoReads");
+ child.absolute_output_size = Some([4, 4]);
+ let bridge = child.add_node("input_grayscale", [0.0; 2]);
+ child.node_mut(bridge).unwrap().base.size_mode = SizeMode::RelativeToParent;
+ child.node_mut(bridge).unwrap().base.format = OutputFormat::F16;
+ let reader = child.add_node("pixel_processor", [0.0; 2]);
+ let node = child.node_mut(reader).unwrap();
+ node.base.format = OutputFormat::F32;
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ child.connect(bridge, "output", reader, "input0").unwrap();
+ for (name, source) in [("output", reader), ("passed", bridge)] {
+ let output = child.add_node("output", [0.0; 2]);
+ child.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
+ child.connect(source, "output", output, "input").unwrap();
+ }
+ let mut package = Package::new("Wired sampling");
+ package.graphs.extend([parent, child]);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(8, 8, |x, _| (x % 2) as f32));
+ let cache = Mutex::new(Cache::default());
+ for (filter, tile, sample, direct_edge) in [(0, true, 0.0, 0.25), (1, true, 16384.0 / 65535.0, 0.25), (1, false, 16384.0 / 65535.0, 0.0)] {
+ let base = &mut package.graphs[1].node_mut(bridge).unwrap().base;
+ base.tiling_mode = ParameterInheritance::Absolute;
+ base.tiling = [tile, false];
+ let mut function = FunctionGraph::default();
+ let pos = function.add("get_float2", &[], Some(Value::Text("$pos".into())));
+ function.output = Some(function.add("samplelum", &[pos], Some(Value::Int2([0, filter]))));
+ package.graphs[1].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&instance].error, None);
+ assert_eq!(cooked.image(instance, 0).unwrap().get(1, 0, false)[0], sample);
+ assert_eq!(cooked.image(instance, 1).unwrap().get(0, 0, false)[0], direct_edge);
+ }
+}
+
+#[test]
+fn wired_value_and_pattern_functions_read_the_callers_texture() {
+ use materialcraft_core::{FunctionGraph, OutputFormat, PatternGraph, PatternNodeKind};
+ let (mut parent, instance) = instancing("Parent", "Sample");
+ parent.size = [5; 2];
+ let source = parent.add_node("input_color", [0.0; 2]);
+ parent.node_mut(source).unwrap().base.format = OutputFormat::F32;
+ parent.connect(source, "output", instance, "input").unwrap();
+
+ let mut child = Graph::new("Sample");
+ let bridge = child.add_node("input_color", [0.0; 2]);
+ child.node_mut(bridge).unwrap().base.format = OutputFormat::U16;
+ let mut function = FunctionGraph::default();
+ let coord = function.add_constant(Value::Float2([0.375, 0.6875]));
+ function.output = Some(function.add("samplecol", &[coord], Some(Value::Int2([0, 1]))));
+ let reader = child.add_node("value_processor", [0.0; 2]);
+ child.node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(function.clone())));
+ child.connect(bridge, "output", reader, "input0").unwrap();
+
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ pattern.nodes[0].parameters.insert("patterntype".into(), Value::Int(2));
+ pattern.nodes[0].parameters.insert("opacity".into(), Value::Function(Box::new(function)));
+ let draw = child.add_node("fx_map", [0.0; 2]);
+ let node = child.node_mut(draw).unwrap();
+ node.base.format = OutputFormat::F32;
+ node.params.insert("color_mode".into(), Value::Bool(true));
+ node.params.insert("background".into(), Value::Color([0.0; 4]));
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+ child.connect(bridge, "output", draw, "pattern0").unwrap();
+ for (name, source) in [("output", draw), ("sample", reader)] {
+ let output = child.add_node("output", [0.0; 2]);
+ child.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
+ child.connect(source, "output", output, "input").unwrap();
+ }
+ let mut package = Package::new("Wired color sampling");
+ package.graphs.extend([parent, child]);
+ let mut options = Options::new(&no_res);
+ let field = Image::generate(32, 32, Kind::Color, |x, y| {
+ std::array::from_fn(|i| ((37 * x + 41 * y + 7 * x * y + 53 * 19 + 61 * i as u32 + 5 * x * i as u32) % 509) as f32 / 508.0)
+ });
+ options.inputs.insert("input".into(), field);
+ let result = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ assert_eq!(result.nodes[&instance].error, None);
+ let color = [0.44734252, 0.43011808, 0.4128937, 0.64616144];
+ assert_eq!(result.value(instance, 1), Some(&Value::Float4(color)));
+ let drawn = [0.2890555, 0.27792573, 0.266796, 0.64616144];
+ assert_eq!(result.image(instance, 0).unwrap().get(0, 0, false), drawn);
+}
+
+#[test]
+fn value_processor_reads_the_upstream_channel_format_after_a_cache_hit() {
+ use materialcraft_core::{FunctionGraph, OutputFormat};
+
+ let mut function = FunctionGraph::default();
+ let uv = function.add_constant(Value::Float2([0.5, 0.5]));
+ function.output = Some(function.add("samplelum", &[uv], Some(Value::Int2([0, 0]))));
+ let mut graph = Graph::new("Value sample");
+ graph.size = [4; 2];
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ let processor = graph.add_node("value_processor", [0.0; 2]);
+ graph.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ graph.connect(input, "output", processor, "input0").unwrap();
+ let mut package = Package::new("Value sample");
+ package.graphs.push(graph);
+ let mut options = Options::new(&no_res);
+ let channel = 222.0_f32 / 255.0;
+ options.inputs.insert("input".into(), Image::gray(16, 16, |_, _| channel));
+ let cache = Mutex::new(Cache::default());
+ for (format, expected) in [(OutputFormat::U8, 222.0 * (1.0 / 255.0)), (OutputFormat::F32, channel)] {
+ package.graphs[0].node_mut(input).unwrap().base.format = format;
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&processor].error, None);
+ assert_eq!(result.value(processor, 0), Some(&Value::Float(expected)));
+ let cached = cook(&package, 0, &options, &cache);
+ assert!(cached.nodes[&processor].cached);
+ assert_eq!(cached.value(processor, 0), Some(&Value::Float(expected)));
+ }
+}
+
#[test]
fn input_nodes_read_bound_preview_images() {
let mut p = Package::new("p");
@@ -587,7 +1898,10 @@ fn linear_input_images_and_bitmap_nodes_request_data_reads() {
(c.image(i, 0).unwrap().data()[0], c.image(b, 0).unwrap().data()[0])
};
- assert_eq!(first(&p), (0.2, 0.2), "default is sRGB, as before");
+ assert_eq!(first(&p), (0.2, 0.5), "the bitmap defaults to file channels");
+
+ p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(0));
+ assert_eq!(first(&p), (0.2, 0.2), "an explicit sRGB read still decodes the color");
p.graphs[0].input_images_linear.insert("n".into());
p.graphs[0].node_mut(b).unwrap().params.insert("colour_space".into(), Value::Enum(1));
@@ -713,10 +2027,50 @@ fn cooked_parameters_retain_values_without_processor_graph_copies() {
}
#[test]
-fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
+fn a_pattern_uses_only_its_background_for_input_relative_size_and_precision() {
+ use materialcraft_core::{OutputFormat, ParameterInheritance, SizeMode};
+
+ let mut graph = Graph::new("Pattern inputs");
+ graph.size = [5, 4];
+ graph.format = OutputFormat::U8;
+ let stamp = graph.add_node("uniform", [0.0; 2]);
+ let back = graph.add_node("uniform", [0.0; 2]);
+ for (id, size, format) in [(stamp, [6; 2], OutputFormat::F32), (back, [4, 5], OutputFormat::U16)] {
+ let base = &mut graph.node_mut(id).unwrap().base;
+ base.size_mode = SizeMode::Absolute;
+ base.size = size;
+ base.format = format;
+ }
+ let draw = graph.add_node("fx_map", [100.0, 0.0]);
+ graph.node_mut(draw).unwrap().base.format_mode = ParameterInheritance::RelativeToInput;
+ graph.connect(stamp, "output", draw, "pattern0").unwrap();
+ graph.connect(back, "output", draw, "background").unwrap();
+ let mut package = Package::new("Pattern input inheritance");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ let result = |package: &Package| {
+ let cooked = cook(package, 0, &Options::new(&no_res), &cache);
+ let item = &cooked.nodes[&draw];
+ assert_eq!(item.error, None);
+ (item.base.size, item.base.format)
+ };
+ assert_eq!(result(&package), ([16, 32], OutputFormat::U16));
+ package.graphs[0].node_mut(draw).unwrap().base.size = [-1, 1];
+ assert_eq!(result(&package), ([8, 64], OutputFormat::U16));
+ assert!(package.graphs[0].disconnect(draw, "background"));
+ assert_eq!(result(&package), ([16, 32], OutputFormat::U8));
+ // Bypassing this draw still passes through the available stamp texture.
+ package.graphs[0].node_mut(draw).unwrap().disabled = true;
+ assert_eq!(result(&package), ([64, 64], OutputFormat::F32));
+}
+
+#[test]
+fn enabled_nodes_resolve_size_from_the_graph_or_their_primary_image() {
use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance, SizeMode, ValueType};
- for definition in ["svg", "fx_map"] {
+ for (definition, port, size, preview) in
+ [("pixel_processor", "input0", [64_u32, 32], (16, 8)), ("svg", "background", [64, 32], (16, 8)), ("fx_map", "background", [32, 64], (8, 16))]
+ {
for dynamic in [false, true] {
let mut graph = Graph::new("Generator sizes");
graph.size = [6, 5];
@@ -733,16 +2087,20 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
base.pixel_size = [0.25, 0.5];
base.pixel_size_mode = ParameterInheritance::Absolute;
let generator = graph.add_node(definition, [200.0, 0.0]);
- graph.node_mut(generator).unwrap().base.format_mode = ParameterInheritance::RelativeToInput;
+ let node = graph.node_mut(generator).unwrap();
+ node.base.format_mode = ParameterInheritance::RelativeToInput;
+ if definition == "pixel_processor" {
+ node.params.insert("function".into(), Value::Function(Box::new(FunctionGraph::constant(Value::Float4([0.25; 4])))));
+ }
if dynamic {
let mut function = FunctionGraph::input("$sizelog2", ValueType::Float2);
- let size = function.output.unwrap();
- let parent = function.add_constant(Value::Float2([6.0, 5.0]));
- let difference = function.add("sub", &[size, parent], None);
+ let actual = function.output.unwrap();
+ let expected = function.add_constant(Value::Float2(size.map(|axis| axis.ilog2() as f32)));
+ let difference = function.add("sub", &[actual, expected], None);
function.output = Some(function.add("toint2", &[difference], None));
graph.node_mut(generator).unwrap().base.functions.insert(BaseParameter::OutputSize, function);
}
- graph.connect(background, "output", generator, "background").unwrap();
+ graph.connect(background, "output", generator, port).unwrap();
let mut package = Package::new("Generator sizes");
package.graphs.push(graph);
let cache = Mutex::new(Cache::default());
@@ -753,8 +2111,8 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
let result = &cooked.nodes[&generator];
assert_eq!(result.error, None, "{definition}");
- assert_eq!(result.base.size, [64, 32], "{definition}, dynamic: {dynamic}");
- assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((16, 8)));
+ assert_eq!(result.base.size, size, "{definition}, dynamic: {dynamic}");
+ assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some(preview));
assert_eq!(result.base.seed, 0);
assert_eq!(result.base.format, OutputFormat::F32);
assert_eq!(result.base.tiling, [false, true]);
@@ -764,7 +2122,7 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
if !dynamic {
assert_eq!(
node_size(&package.graphs[0], materialcraft_nodes::find(definition), package.graphs[0].node(generator).unwrap(), Some((32, 64)), Some(16)),
- (16, 8)
+ preview
);
}
@@ -774,6 +2132,10 @@ fn enabled_generators_use_parent_size_and_seed_with_input_image_properties() {
assert_eq!(cooked.nodes[&generator].error, None);
assert_eq!(cooked.nodes[&generator].base.size, cooked.nodes[&background].base.size);
assert_eq!(cooked.image(generator, 0).map(|image| (image.width(), image.height())), Some((8, 16)));
+ assert_eq!(
+ node_size(&package.graphs[0], materialcraft_nodes::find(definition), package.graphs[0].node(generator).unwrap(), Some((32, 64)), Some(16)),
+ (8, 16)
+ );
}
}
}
@@ -825,3 +2187,347 @@ fn a_color_parameter_function_may_return_a_gray_level_or_an_rgb_triple() {
assert_eq!(result.parameters.get("color").and_then(Value::as_vec4), Some(expected));
}
}
+
+#[test]
+fn levels_widens_scalar_endpoints_to_opaque_gray_and_normalizes_integer_controls() {
+ use materialcraft_core::{FunctionGraph, OutputFormat};
+
+ for (format, numerator, denominator, expected) in [
+ (OutputFormat::F32, 1.0, 0.125, [8.0, 8.0, 8.0, 1.0]),
+ (OutputFormat::U8, 1.0, 0.0, [1.0; 4]),
+ (OutputFormat::U16, 1.0, -0.0, [0.0, 0.0, 0.0, 1.0]),
+ (OutputFormat::U16, 0.0, 0.0, [0.0, 0.0, 0.0, 1.0]),
+ ] {
+ let mut function = FunctionGraph::default();
+ let a = function.add_constant(Value::Float(numerator));
+ let b = function.add_constant(Value::Float(denominator));
+ function.output = Some(function.add("div", &[a, b], None));
+ let mut graph = Graph::new("Channel control");
+ let levels = graph.add_node("levels", [0.0; 2]);
+ let node = graph.node_mut(levels).unwrap();
+ node.base.format = format;
+ node.functions.insert("in_high".into(), function);
+ let mut package = Package::new("Channel control");
+ package.graphs.push(graph);
+ let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default()));
+ assert_eq!(cooked.nodes[&levels].error, None);
+ assert_eq!(cooked.nodes[&levels].parameters["in_high"], Value::Float4(expected));
+ }
+}
+
+fn instanced_seed_field() -> (Package, NodeId, NodeId) {
+ let (mut parent, instance) = instancing("Parent", "Field");
+ parent.seed = 19;
+ parent.node_mut(instance).unwrap().base.seed = 3;
+ let mut child = Graph::new("Field");
+ child.size = parent.size;
+ let noise = child.add_node("pixel_processor", [0.0; 2]);
+ let mut function = materialcraft_core::FunctionGraph::default();
+ let maximum = function.add_constant(Value::Float(1.0));
+ function.output = Some(function.add("rand", &[maximum], None));
+ child.node_mut(noise).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ let output = child.add_node("output", [100.0, 0.0]);
+ child.connect(noise, "output", output, "input").unwrap();
+ let mut pkg = Package::new("Seed controls");
+ pkg.graphs.extend([parent, child]);
+ (pkg, instance, output)
+}
+
+#[test]
+fn an_instanced_graph_resolves_its_own_seed_after_the_instance() {
+ use materialcraft_core::ParameterInheritance::{Absolute, RelativeToInput, RelativeToParent};
+ let (mut pkg, instance, output) = instanced_seed_field();
+ let cache = Mutex::new(Cache::default());
+ for (mode, offset, expected) in [(Absolute, 0, 0), (Absolute, 5, 5), (RelativeToParent, 5, 27), (RelativeToInput, -3, 19)] {
+ pkg.graphs[1].seed = expected;
+ let direct = cook(&pkg, 1, &Options::new(&no_res), &cache);
+ pkg.graphs[1].seed = offset;
+ pkg.graphs[1].seed_mode = mode;
+ let nested = cook(&pkg, 0, &Options::new(&no_res), &cache);
+ assert_eq!(nested.nodes[&instance].error, None);
+ assert_eq!(nested.image(instance, 0).unwrap().data(), direct.image(output, 0).unwrap().data(), "{mode:?} {offset}");
+ }
+}
+
+#[test]
+fn graph_seed_functions_read_the_resolved_dimensions_of_the_child() {
+ use materialcraft_core::{FunctionGraph, ParameterInheritance, ValueType};
+ let (mut package, instance, output) = instanced_seed_field();
+ package.graphs[1].seed_mode = ParameterInheritance::Absolute;
+ let mut literal = package.clone();
+ let options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ for (name, axis, threshold, parent, absolute, expected_seed) in [
+ ("$size", 0, 20.0, [5, 4], None, 5),
+ ("$size", 1, 20.0, [5, 4], None, 0),
+ ("$sizelog2", 1, 4.5, [4, 5], None, 5),
+ ("$size", 0, 12.0, [5, 4], Some([3, 4]), 0),
+ ("$sizelog2", 1, 3.5, [4, 5], Some([3, 4]), 5),
+ ] {
+ let mut function = FunctionGraph::input(name, ValueType::Float2);
+ let selected = function.add("swizzle1", &[function.output.unwrap()], Some(Value::Int(axis)));
+ let limit = function.add_constant(Value::Float(threshold));
+ let predicate = function.add("gt", &[selected, limit], None);
+ let yes = function.add_constant(Value::Int(5));
+ let no = function.add_constant(Value::Int(0));
+ function.output = Some(function.add("ifelse", &[predicate, yes, no], None));
+ package.graphs[0].size = parent;
+ package.graphs[1].absolute_output_size = absolute;
+ package.graphs[1].seed_function = Some(function);
+ literal.graphs[1].size = parent;
+ literal.graphs[1].absolute_output_size = absolute;
+ literal.graphs[1].seed = expected_seed;
+ let actual = cook(&package, 0, &options, &cache);
+ assert_eq!(actual.nodes[&instance].error, None);
+ let reference = cook(&literal, 1, &options, &cache);
+ assert_eq!(actual.image(instance, 0).unwrap().data(), reference.image(output, 0).unwrap().data(), "{name} {axis} {parent:?} {absolute:?}");
+ }
+}
+
+#[test]
+fn graph_seed_functions_use_the_child_argument_before_cooking_its_nodes() {
+ use materialcraft_core::{ExposedParameter, FunctionGraph, ParameterInheritance, ValueType};
+ let (mut package, instance, output) = instanced_seed_field();
+ let input = ExposedParameter {
+ id: "offset".into(),
+ label: "Offset".into(),
+ default: Value::Int(5),
+ connectable: false,
+ min: -20.0,
+ max: 20.0,
+ clamp: false,
+ step: None,
+ editor: None,
+ description: String::new(),
+ group: String::new(),
+ options: Vec::new(),
+ };
+ package.graphs[1].exposed.push(input);
+ let mut reference = package.clone();
+ let cache = Mutex::new(Cache::default());
+ let options = Options::new(&no_res);
+ let function = FunctionGraph::input("offset", ValueType::Integer);
+ let mut graph = serde_json::to_value(&package.graphs[1]).unwrap();
+ graph["seedFunction"] = serde_json::to_value(&function).unwrap();
+ package.graphs[1] = serde_json::from_value(graph).unwrap();
+ for (mode, input, expected) in [
+ (ParameterInheritance::Absolute, None, 5),
+ (ParameterInheritance::RelativeToParent, None, 27),
+ (ParameterInheritance::RelativeToInput, Some(-3), 19),
+ (ParameterInheritance::Absolute, Some(-3), -3),
+ ] {
+ package.graphs[1].seed_mode = mode;
+ if let Some(value) = input {
+ package.graphs[0].node_mut(instance).unwrap().params.insert("offset".into(), Value::Int(value));
+ }
+ reference.graphs[1].seed = expected;
+ let direct = cook(&reference, 1, &options, &cache);
+ let nested = cook(&package, 0, &options, &cache);
+ assert_eq!(nested.nodes[&instance].error, None);
+ assert_eq!(nested.image(instance, 0).unwrap().data(), direct.image(output, 0).unwrap().data(), "{mode:?} {input:?}");
+ }
+
+ let mut wrong_type = FunctionGraph::default();
+ wrong_type.output = Some(wrong_type.add_constant(Value::Text("invalid".into())));
+ package.graphs[1].seed_function = Some(wrong_type);
+ let invalid = cook(&package, 0, &options, &cache);
+ assert!(invalid.nodes[&instance].error.as_deref().unwrap().contains("graph random seed"));
+}
+
+#[test]
+fn nested_generators_keep_the_child_graph_output_format() {
+ use materialcraft_core::OutputFormat;
+ let (mut parent, instance) = instancing("Parent", "Field");
+ let mut child = Graph::new("Field");
+ child.size = parent.size;
+ let processor = child.add_node("pixel_processor", [0.0; 2]);
+ let mut function = materialcraft_core::FunctionGraph::default();
+ let value = function.add_constant(Value::Float(0.347821));
+ function.output = Some(value);
+ child.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(function)));
+ let output = child.add_node("output", [100.0, 0.0]);
+ child.connect(processor, "output", output, "input").unwrap();
+ parent.format = OutputFormat::F32;
+ let mut package = Package::new("Output precision");
+ package.graphs.extend([parent, child]);
+ let cache = Mutex::new(Cache::default());
+ for caller in [OutputFormat::U8, OutputFormat::F32] {
+ package.graphs[0].node_mut(instance).unwrap().base.format = caller;
+ for child in OutputFormat::ALL {
+ let expected = if child == OutputFormat::Inherit { caller } else { child };
+ package.graphs[1].format = expected;
+ let direct = cook(&package, 1, &Options::new(&no_res), &cache);
+ package.graphs[1].format = child;
+ let nested = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert_eq!(nested.nodes[&instance].error, None);
+ assert_eq!(nested.nodes[&instance].output_base(0).unwrap().format, expected);
+ assert_eq!(nested.image(instance, 0).unwrap().data(), direct.image(output, 0).unwrap().data(), "child {child:?} inside {caller:?}");
+ }
+ }
+}
+
+#[test]
+fn nested_blurs_filter_the_original_caller_texture() {
+ use materialcraft_core::OutputFormat;
+ for filter in ["directional_blur", "blur"] {
+ let (mut parent, instance) = instancing("Parent", "Filtered");
+ let source = parent.add_node("input_grayscale", [0.0; 2]);
+ parent.node_mut(source).unwrap().base.format = OutputFormat::F32;
+ parent.connect(source, "output", instance, "input").unwrap();
+
+ let mut child = Graph::new("Filtered");
+ child.size = parent.size;
+ let bridge = child.add_node("input_grayscale", [0.0; 2]);
+ child.node_mut(bridge).unwrap().base.format = OutputFormat::U16;
+ let add_filter = |graph: &mut Graph, input| {
+ let id = graph.add_node(filter, [0.0; 2]);
+ let node = graph.node_mut(id).unwrap();
+ node.base.format = OutputFormat::U16;
+ node.params.insert("intensity".into(), Value::Float(16.0));
+ graph.connect(input, "output", id, "input").unwrap();
+ id
+ };
+ let direct = add_filter(&mut parent, source);
+ let nested = add_filter(&mut child, bridge);
+ let output = child.add_node("output", [0.0; 2]);
+ child.connect(nested, "output", output, "input").unwrap();
+ let mut package = Package::new("Caller precision");
+ package.graphs.extend([parent, child]);
+ let mut options = Options::new(&no_res);
+ options.inputs.insert("input".into(), Image::gray(16, 16, |x, y| ((97 * x + 31 * y + 13 * x * y) % 251) as f32 / 251.0));
+ let cooked = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ assert_eq!(cooked.nodes[&instance].error, None);
+ let result = cooked.image(instance, 0).unwrap();
+ let expected = cooked.image(direct, 0).unwrap();
+ assert!(result.data().iter().zip(expected.data()).all(|(a, b)| a.to_bits() == b.to_bits()), "{filter}");
+ }
+}
+
+#[test]
+fn relative_graph_size_offsets_resolve_before_the_children_at_each_instance() {
+ let (mut parent, instance) = instancing("Parent", "Field");
+ parent.size = [5, 4];
+ let mut child = Graph::new("Field");
+ let fill = child.add_node("uniform", [0.0; 2]);
+ let output = child.add_node("output", [1.0, 0.0]);
+ child.connect(fill, "output", output, "input").unwrap();
+ let mut pkg = Package::new("Graph dimensions");
+ pkg.graphs.extend([parent, child]);
+ let cache = Mutex::new(Cache::default());
+ use materialcraft_core::GraphSizeOffset::{Input, Parent};
+ for (offset, node_offset, expected) in
+ [(Parent([-1, 1]), [0, 0], [16, 32]), (Input([1, -1]), [0, 0], [64, 8]), (Parent([-7, 0]), [3, 0], [2, 16]), (Input([0, 0]), [0, 0], [32, 16])]
+ {
+ pkg.graphs[1].relative_output_size = Some(offset);
+ pkg.graphs[1].node_mut(fill).unwrap().base.size = node_offset;
+ let result = cook(&pkg, 0, &Options::new(&no_res), &cache);
+ assert_eq!(result.nodes[&instance].error, None);
+ let image = result.image(instance, 0).unwrap();
+ assert_eq!([image.width(), image.height()], expected);
+ }
+}
+
+#[test]
+fn computed_graph_output_sizes_read_instance_arguments_and_parent_axes() {
+ use materialcraft_core::{ExposedParameter, FunctionGraph, GraphSizeOffset, ValueType};
+ let (mut package, instance, _) = instanced_seed_field();
+ package.graphs[0].size = [5, 4];
+ let child = &mut package.graphs[1];
+ let input = ExposedParameter {
+ id: "axes".into(),
+ label: "Axes".into(),
+ default: Value::Int2([-1, 1]),
+ connectable: false,
+ min: -20.0,
+ max: 20.0,
+ clamp: false,
+ step: None,
+ editor: None,
+ description: String::new(),
+ group: String::new(),
+ options: Vec::new(),
+ };
+ child.exposed.push(input);
+ child.output_size_function = Some(FunctionGraph::input("axes", ValueType::Integer2));
+ let options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ for (absolute, mode, axes, expected) in [
+ (None, Some(GraphSizeOffset::Parent([0, 0])), [-1, 1], [16, 32]),
+ (None, Some(GraphSizeOffset::Input([0, 0])), [1, -1], [64, 8]),
+ (Some([0, 0]), None, [3, 4], [8, 16]),
+ ] {
+ package.graphs[1].absolute_output_size = absolute;
+ package.graphs[1].relative_output_size = mode;
+ package.graphs[0].node_mut(instance).unwrap().params.insert("axes".into(), Value::Int2(axes));
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&instance].error, None);
+ let image = result.image(instance, 0).unwrap();
+ assert_eq!([image.width(), image.height()], expected);
+ }
+}
+
+#[test]
+fn computed_graph_output_sizes_test_both_axes_before_applying_their_offsets() {
+ use materialcraft_core::{FunctionGraph, GraphSizeOffset, ValueType};
+ let (mut package, instance, _) = instanced_seed_field();
+ package.graphs[0].size = [5, 4];
+ let options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ for (name, axis, threshold, absolute, expected) in [
+ ("$size", 0, 16.0, false, [64, 8]),
+ ("$size", 1, 16.0, false, [16, 32]),
+ ("$sizelog2", 0, 4.0, false, [64, 8]),
+ ("$sizelog2", 1, 4.0, false, [16, 32]),
+ ("$size", 0, 0.0, true, [8, 16]),
+ ("$size", 0, -0.5, true, [16, 8]),
+ ("$sizelog2", 1, 0.0, true, [8, 16]),
+ ("$sizelog2", 1, -0.5, true, [16, 8]),
+ ] {
+ let mut function = FunctionGraph::input(name, ValueType::Float2);
+ let channel = function.add("swizzle1", &[function.output.unwrap()], Some(Value::Int(axis)));
+ let limit = function.add_constant(Value::Float(threshold));
+ let pass = function.add("gt", &[channel, limit], None);
+ let high = function.add_constant(Value::Int2(if absolute { [4, 3] } else { [1, -1] }));
+ let low = function.add_constant(Value::Int2(if absolute { [3, 4] } else { [-1, 1] }));
+ function.output = Some(function.add("ifelse", &[pass, high, low], None));
+ let child = &mut package.graphs[1];
+ child.absolute_output_size = absolute.then_some([0; 2]);
+ child.relative_output_size = (!absolute).then_some(GraphSizeOffset::Parent([0; 2]));
+ child.output_size_function = Some(function);
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&instance].error, None);
+ let image = result.image(instance, 0).unwrap();
+ assert_eq!([image.width(), image.height()], expected);
+ }
+ package.graphs[1].output_size_function = Some(FunctionGraph::constant(Value::Bool(true)));
+ let invalid = cook(&package, 0, &options, &cache);
+ assert!(invalid.nodes[&instance].error.as_deref().unwrap().contains("graph output size"));
+}
+
+#[test]
+fn graph_seed_functions_use_the_allocated_size_below_one_texel() {
+ use materialcraft_core::{FunctionGraph, GraphSizeOffset, ParameterInheritance, ValueType};
+ let (mut package, instance, _) = instanced_seed_field();
+ package.graphs[0].size = [4, 4];
+ package.graphs[1].relative_output_size = Some(GraphSizeOffset::Parent([-6, 0]));
+ package.graphs[1].seed_mode = ParameterInheritance::Absolute;
+ let mut literal = package.clone();
+ let options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ for (name, limit, expected) in [("$size", 0.5, 5), ("$size", 1.0, 0), ("$sizelog2", -0.5, 5), ("$sizelog2", 0.0, 0)] {
+ let mut function = FunctionGraph::input(name, ValueType::Float2);
+ let axis = function.add("swizzle1", &[function.output.unwrap()], Some(Value::Int(0)));
+ let threshold = function.add_constant(Value::Float(limit));
+ let pass = function.add("gt", &[axis, threshold], None);
+ let yes = function.add_constant(Value::Int(5));
+ let no = function.add_constant(Value::Int(0));
+ function.output = Some(function.add("ifelse", &[pass, yes, no], None));
+ package.graphs[1].seed_function = Some(function);
+ literal.graphs[1].seed = expected;
+ let result = cook(&package, 0, &options, &cache);
+ let control = cook(&literal, 0, &options, &cache);
+ let image = result.image(instance, 0).unwrap();
+ assert_eq!([image.width(), image.height()], [1, 16]);
+ assert_eq!(image.data(), control.image(instance, 0).unwrap().data());
+ }
+}
diff --git a/crates/eval/src/tests/font_resource.rs b/crates/eval/src/tests/font_resource.rs
new file mode 100644
index 00000000..b8002235
--- /dev/null
+++ b/crates/eval/src/tests/font_resource.rs
@@ -0,0 +1,267 @@
+use super::*;
+use materialcraft_core::{OutputFormat, Resource, ResourceBytes};
+
+fn rectangle_font(height: i16, metrics: [i16; 3]) -> Vec {
+ outline_font(metrics, 640, &[(0, 0, true), (0, height, true), (512, height, true), (512, 0, true)])
+}
+
+/// A two-glyph TrueType face with one contour for A. A false flag denotes a quadratic control point.
+fn outline_font(metrics: [i16; 3], advance: i16, contour: &[(i16, i16, bool)]) -> Vec {
+ fn words(values: &[i16]) -> Vec {
+ values.iter().flat_map(|value| value.to_be_bytes()).collect()
+ }
+ fn checksum(data: &[u8]) -> u32 {
+ data.chunks(4).fold(0u32, |sum, chunk| {
+ let mut word = [0; 4];
+ word[..chunk.len()].copy_from_slice(chunk);
+ sum.wrapping_add(u32::from_be_bytes(word))
+ })
+ }
+
+ let mut head = vec![0; 54];
+ head[..4].copy_from_slice(&0x10000u32.to_be_bytes());
+ head[12..16].copy_from_slice(&0x5f0f3cf5u32.to_be_bytes());
+ head[18..20].copy_from_slice(&1024i16.to_be_bytes());
+ let bounds = [
+ contour.iter().map(|p| p.0).min().unwrap(),
+ contour.iter().map(|p| p.1).min().unwrap(),
+ contour.iter().map(|p| p.0).max().unwrap(),
+ contour.iter().map(|p| p.1).max().unwrap(),
+ ];
+ head[36..44].copy_from_slice(&words(&bounds));
+ let mut hhea = vec![0; 36];
+ hhea[..4].copy_from_slice(&0x10000u32.to_be_bytes());
+ hhea[4..12].copy_from_slice(&words(&[metrics[0], metrics[1], metrics[2], advance]));
+ hhea[34..].copy_from_slice(&2i16.to_be_bytes());
+ let mut maxp = vec![0; 32];
+ maxp[..4].copy_from_slice(&0x10000u32.to_be_bytes());
+ let count = i16::try_from(contour.len()).unwrap();
+ maxp[4..10].copy_from_slice(&words(&[2, count, 1]));
+ let mut cmap = words(&[0, 1, 3, 1, 0, 12]);
+ cmap.extend(words(&[4, 32, 0, 4, 4, 1, 0, 65, -1, 0, 65, -1, -64, 1, 0, 0]));
+ let mut glyf = words(&[1, bounds[0], bounds[1], bounds[2], bounds[3], count - 1, 0]);
+ glyf.extend(contour.iter().map(|p| u8::from(p.2)));
+ for axis in 0..2 {
+ let mut previous = 0;
+ for &(x, y, _) in contour {
+ let coordinate = [x, y][axis];
+ glyf.extend((coordinate - previous).to_be_bytes());
+ previous = coordinate;
+ }
+ }
+ glyf.resize(glyf.len().next_multiple_of(2), 0);
+ let loca = words(&[0, 0, (glyf.len() / 2) as i16]);
+ let tables =
+ [(b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", words(&[advance, 0, advance, 0])), (b"loca", loca), (b"maxp", maxp)];
+ let mut font = words(&[1, 0, 7, 64, 2, 48]);
+ font.resize(12 + 16 * tables.len(), 0);
+ let mut head_start = 0;
+ for (index, (tag, data)) in tables.into_iter().enumerate() {
+ let offset = font.len();
+ if tag == b"head" {
+ head_start = offset;
+ }
+ let entry = &mut font[12 + 16 * index..12 + 16 * (index + 1)];
+ entry[..4].copy_from_slice(tag);
+ entry[4..8].copy_from_slice(&checksum(&data).to_be_bytes());
+ entry[8..12].copy_from_slice(&(offset as u32).to_be_bytes());
+ entry[12..].copy_from_slice(&(data.len() as u32).to_be_bytes());
+ font.extend(data);
+ font.resize(font.len().next_multiple_of(4), 0);
+ }
+ let adjustment = 0xb1b0_afba_u32.wrapping_sub(checksum(&font));
+ font[head_start + 8..head_start + 12].copy_from_slice(&adjustment.to_be_bytes());
+ font
+}
+
+#[test]
+fn package_font_outlines_render_and_invalidate_the_parent_instance() {
+ let (mut parent, instance) = instancing("Preview", "Letter");
+ parent.size = [6, 5];
+ parent.format = OutputFormat::F32;
+ let mut child = Graph::new("Letter");
+ child.size = [6, 5];
+ let text = child.add_node("text", [0.0; 2]);
+ child.node_mut(text).unwrap().params.extend([
+ ("text".into(), Value::Text("A".into())),
+ ("fontdata".into(), Value::Text("Ink".into())),
+ ("fontsize".into(), Value::Float(0.5)),
+ ]);
+ let output = child.add_node("output", [100.0, 0.0]);
+ child.connect(text, "output", output, "input").unwrap();
+ let mut package = Package::new("Original lettering");
+ package.graphs = vec![parent, child];
+ package.resources.push(Resource::new("Ink", "Ink.ttf", ResourceBytes::new(rectangle_font(512, [768, -256, 0]))));
+ let cache = Mutex::new(Cache::default());
+ let options = Options::new(&no_res);
+ for (height, first_row) in [(512, 8), (256, 12), (1024, 4)] {
+ package.resources[0].bytes = ResourceBytes::new(rectangle_font(height, [768, -256, 0]));
+ let direct = cook(&package, 1, &options, &cache);
+ assert!(direct.nodes[&text].error.is_none(), "{:?}", direct.nodes[&text].error);
+ let nested = cook(&package, 0, &options, &cache);
+ assert!(!nested.nodes[&instance].cached);
+ let image = nested.image(instance, 0).unwrap();
+ assert_eq!((image.width(), image.height()), (64, 32));
+ for y in 0..32 {
+ for x in 0..64 {
+ let ink = (24..40).contains(&x) && (first_row..16).contains(&y);
+ assert_eq!(image.get_gray(x, y, false), f32::from(ink), "({x}, {y}) at cap height {height}");
+ }
+ }
+ assert!(cook(&package, 0, &options, &cache).nodes[&instance].cached);
+ }
+}
+
+fn text_sample(size: [u32; 2], metrics: [i16; 3], params: &[(&str, Value)]) -> (Package, NodeId) {
+ let mut graph = Graph::new("Print");
+ graph.size = size;
+ graph.format = OutputFormat::F32;
+ let id = graph.add_node("text", [0.0; 2]);
+ let node = graph.node_mut(id).unwrap();
+ node.params.insert("fontdata".into(), Value::Text("Ink".into()));
+ node.params.extend(params.iter().map(|(name, value)| (name.to_string(), value.clone())));
+ let mut package = Package::new("Original type");
+ package.resources.push(Resource::new("Ink", "Ink.ttf", ResourceBytes::new(rectangle_font(512, metrics))));
+ package.graphs.push(graph);
+ (package, id)
+}
+
+#[test]
+fn package_font_uses_horizontal_height_and_line_gap() {
+ let (package, id) = text_sample([6, 6], [1536, -512, 512], &[("text", Value::Text("A\nA".into())), ("fontsize", Value::Float(0.25))]);
+ let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default()));
+ assert_eq!(cooked.nodes[&id].error, None);
+ let image = cooked.image(id, 0).unwrap();
+ for y in 0..64 {
+ for x in 0..64 {
+ let ink = (30..34).contains(&x) && ((28..32).contains(&y) || (48..52).contains(&y));
+ assert_eq!(image.get_gray(x, y, false), f32::from(ink), "({x}, {y})");
+ }
+ }
+}
+
+#[test]
+fn package_font_clips_overhang_at_the_outside_of_the_text_block() {
+ let (mut package, id) = text_sample(
+ [6, 6],
+ [768, -256, 0],
+ &[("text", Value::Text("A\nA".into())), ("fontsize", Value::Float(0.25)), ("position", Value::Float2([0.0, -0.25]))],
+ );
+ package.resources[0].bytes = ResourceBytes::new(rectangle_font(1024, [768, -256, 0]));
+ let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default()));
+ assert_eq!(cooked.nodes[&id].error, None);
+ let image = cooked.image(id, 0).unwrap();
+ for y in 0..64 {
+ for x in 0..64 {
+ let ink = (28..36).contains(&x) && (4..32).contains(&y);
+ assert_eq!(image.get_gray(x, y, false), f32::from(ink), "({x}, {y})");
+ }
+ }
+}
+
+#[test]
+fn package_font_quadratic_detail_tracks_the_text_scale() {
+ let metrics = [768, -256, 0];
+ let (mut package, id) = text_sample([5, 5], metrics, &[("text", Value::Text("A".into())), ("position", Value::Float2([-0.0625, 1.0 / 256.0]))]);
+ let curve = [(0, 0, true), (512, 1024, false), (1024, 0, true)];
+ let options = Options::new(&no_res);
+ let cache = Mutex::new(Cache::default());
+ for (size, segments) in [(0.35, 4), (0.35001, 8)] {
+ package.graphs[0].node_mut(id).unwrap().params.insert("fontsize".into(), Value::Float(size));
+ let chords: Vec<_> = (0..=segments).map(|i| ((1024 * i / segments) as i16, (2048 * i * (segments - i) / (segments * segments)) as i16, true)).collect();
+ let mut render = |contour: &[(i16, i16, bool)]| {
+ package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, 640, contour));
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&id].error, None);
+ result.image(id, 0).unwrap().clone()
+ };
+ let expected = render(&chords);
+ assert!(expected.data().contains(&1.0));
+ let ink = render(&curve);
+ for (pixel, (a, b)) in ink.data().iter().zip(expected.data()).enumerate() {
+ assert_eq!(a, b, "pixel {pixel} at size {size}");
+ }
+ }
+}
+
+#[test]
+fn adjacent_quadratic_controls_place_their_join_in_whole_design_units() {
+ let metrics = [768, -256, 0];
+ let (mut package, id) = text_sample(
+ [7, 6],
+ metrics,
+ &[
+ ("text", Value::Text("A".into())),
+ ("fontsize", Value::Float(0.5)),
+ ("alignment", Value::Enum(0)),
+ ("position", Value::Float2([-0.1875, 1.0 / 256.0])),
+ ],
+ );
+ let implicit = [(0, 0, true), (55, -385, false), (492, 126, false), (675, 612, false), (1010, 0, true)];
+ let explicit = [implicit[0], implicit[1], (273, -130, true), implicit[2], (583, 369, true), implicit[3], implicit[4]];
+ let cache = Mutex::new(Cache::default());
+ let mut render = |contour: &[(i16, i16, bool)]| {
+ package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, 640, contour));
+ let result = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert_eq!(result.nodes[&id].error, None);
+ result.image(id, 0).unwrap().clone()
+ };
+ let expected = render(&explicit);
+ assert!(expected.data().contains(&1.0));
+ let actual = render(&implicit);
+ for (pixel, (a, b)) in actual.data().iter().zip(expected.data()).enumerate() {
+ assert_eq!(a, b, "pixel {pixel} at the implicit join");
+ }
+}
+
+#[test]
+fn overlapping_glyphs_round_each_coverage_composition() {
+ let metrics = [768, -256, 0];
+ let (mut package, id) = text_sample([5, 5], metrics, &[("fontsize", Value::Float(0.5)), ("alignment", Value::Enum(0))]);
+ let cache = Mutex::new(Cache::default());
+ for (width, expected) in [(11, [44u8, 80, 110, 135]), (32, [128, 192, 224, 240])] {
+ let contour = [(0, 0, true), (0, 512, true), (width, 512, true), (width, 0, true)];
+ package.resources[0].bytes = ResourceBytes::new(outline_font(metrics, 0, &contour));
+ for (count, code) in (1..=4).zip(expected) {
+ package.graphs[0].node_mut(id).unwrap().params.insert("text".into(), Value::Text("A".repeat(count)));
+ let cooked = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert_eq!(cooked.nodes[&id].error, None);
+ let ink = cooked.image(id, 0).unwrap();
+ for y in 0..32 {
+ for x in 0..32 {
+ let coverage = if x == 16 && (8..16).contains(&y) { code } else { 0 };
+ assert_eq!(ink.get_gray(x, y, false), f32::from(coverage) / 255.0, "width {width}, {count} glyphs at ({x},{y})");
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn package_font_coverage_interpolates_the_background_channels() {
+ let (mut package, id) = text_sample(
+ [5, 4],
+ [768, -256, 0],
+ &[
+ ("text", Value::Text("A".into())),
+ ("fontsize", Value::Float(0.5)),
+ ("position", Value::Float2([1.0 / 128.0, 0.0])),
+ ("background", Value::Color([1.0, 0.0, 0.0, 0.25])),
+ ],
+ );
+ let cache = Mutex::new(Cache::default());
+ for color in [false, true] {
+ package.graphs[0].node_mut(id).unwrap().params.insert("color_mode".into(), Value::Bool(color));
+ let cooked = cook(&package, 0, &Options::new(&no_res), &cache);
+ assert_eq!(cooked.nodes[&id].error, None);
+ let image = cooked.image(id, 0).unwrap();
+ for (x, code) in [(0, 0), (12, 191), (18, 255), (20, 64)] {
+ let alpha = f32::from(code as u8) / 255.0;
+ if color {
+ assert_eq!(image.get(x, 6, false), [1.0, alpha, alpha, (1.0 - alpha).mul_add(0.25, alpha)]);
+ } else {
+ assert_eq!(image.get_gray(x, 6, false), (1.0 - alpha).mul_add(1.0 / 3.0, alpha));
+ }
+ }
+ }
+}
diff --git a/crates/eval/src/value_execution.rs b/crates/eval/src/value_execution.rs
index 9813f855..f9a1f758 100644
--- a/crates/eval/src/value_execution.rs
+++ b/crates/eval/src/value_execution.rs
@@ -1,23 +1,44 @@
use craft_texture::Image;
-use materialcraft_core::Value;
+use materialcraft_core::{OutputFormat, Value};
use std::collections::BTreeMap;
pub(crate) fn evaluate_value(
parameters: &BTreeMap,
- variables: &BTreeMap,
+ variables: &dyn materialcraft_nodes::GraphVariables,
seed: u32,
size: [u32; 2],
images: &[Option],
+ image_formats: &[OutputFormat],
tile: bool,
) -> Result {
- use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile};
+ use materialcraft_nodes::function::{EvaluationContext, EvaluationState, FunctionScope, compile_with_literal_inputs};
let Some(Value::Function(graph)) = parameters.get("function") else {
return Err("missing value function".into());
};
- let program = compile(graph, seed)?;
- let context = EvaluationContext { scope: Default::default(), position: [0.5; 2], size: size.map(|side| side as f32), images, tile, variables };
+ let program = compile_with_literal_inputs(graph, seed, variables.literal_inputs())?;
+ let context = EvaluationContext {
+ image_formats,
+ scope: FunctionScope::ValueProcessor,
+ position: [0.0; 2],
+ size: size.map(|side| side as f32),
+ images,
+ tile,
+ variables: variables.graph_values(),
+ };
- program.evaluate(&context, &mut EvaluationState::default())
+ let value = program.evaluate(&context, &mut EvaluationState::default())?;
+ Ok(match value {
+ Value::Int(v) => Value::Int(stored_integer(v)),
+ Value::Int2(v) => Value::Int2(v.map(stored_integer)),
+ Value::Int3(v) => Value::Int3(v.map(stored_integer)),
+ Value::Int4(v) => Value::Int4(v.map(stored_integer)),
+ other => other,
+ })
+}
+
+fn stored_integer(value: i32) -> i32 {
+ // The value port rounds to binary32 first. The positive endpoint can round up to 2^31.
+ i32::try_from(value as f32 as i64).unwrap_or(i32::MIN)
}
diff --git a/crates/eval/tests/filter_tiling.rs b/crates/eval/tests/filter_tiling.rs
index 4e76a422..d6a784a7 100644
--- a/crates/eval/tests/filter_tiling.rs
+++ b/crates/eval/tests/filter_tiling.rs
@@ -3,9 +3,72 @@ use materialcraft_core::{Graph, OutputFormat, Package, ParameterInheritance, Val
use materialcraft_eval::{Cache, Options, cook};
use std::sync::Mutex;
+#[test]
+fn rectangular_directional_blur_uses_the_resolved_pixel_ratio() {
+ let mut graph = Graph::new("Directional filter");
+ graph.format = OutputFormat::F32;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text("stripe".into()));
+ let blur = graph.add_node("directional_blur", [100.0, 0.0]);
+ graph.node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(2.4));
+ graph.connect(input, "output", blur, "input").unwrap();
+ let mut package = Package::new("Pixel ratio");
+ package.graphs.push(graph);
+ let resource = |_: &str| None;
+ let mut options = Options::new(&resource);
+ let cache = Mutex::new(Cache::default());
+
+ for (size, angle) in [([5, 6], 0.25), ([6, 5], 0.0)] {
+ let (w, h) = (1 << size[0], 1 << size[1]);
+ package.graphs[0].size = size;
+ let vertical = h > w;
+ let stripe = Image::gray(w, h, |x, y| f32::from(if vertical { y == h / 2 } else { x == w / 2 }));
+ options.inputs.insert("stripe".into(), stripe);
+ package.graphs[0].node_mut(blur).unwrap().params.insert("angle".into(), Value::Float(angle));
+ for (graph_ratio, node_ratio, expected) in [(None, None, 1), (Some(0), None, 0), (Some(0), Some(1), 1), (Some(1), Some(0), 0)] {
+ let graph = &mut package.graphs[0];
+ graph.pixel_ratio = graph_ratio.unwrap_or_default();
+ graph.pixel_ratio_mode = if graph_ratio.is_some() { ParameterInheritance::Absolute } else { ParameterInheritance::RelativeToParent };
+ let base = &mut graph.node_mut(blur).unwrap().base;
+ base.pixel_ratio = node_ratio.unwrap_or_default();
+ base.pixel_ratio_mode = if node_ratio.is_some() { ParameterInheritance::Absolute } else { ParameterInheritance::RelativeToInput };
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&blur].base.pixel_ratio, expected);
+ let image = cooked.image(blur, 0).unwrap();
+ let (x, y) = (i64::from(w / 2), i64::from(h / 2));
+ let center = image.get_gray(x, y, false).to_bits();
+ let neighbor = image.get_gray(x + i64::from(!vertical), y + i64::from(vertical), false).to_bits();
+ let samples = if expected == 1 {
+ [1.0f32.to_bits(), 0]
+ } else if vertical {
+ [0x3f55_5555, 0x3daa_aaac]
+ } else {
+ [0x3f55_5555, 0x3daa_aaad]
+ };
+ assert_eq!([center, neighbor], samples, "{size:?} {graph_ratio:?} {node_ratio:?}");
+ }
+ }
+
+ // The vertical extent is zero here. The transverse projection still reaches the adjacent column.
+ package.graphs[0].node_mut(blur).unwrap().params.insert("angle".into(), Value::Float(0.25));
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.image(blur, 0).unwrap().get_gray(33, 16, false).to_bits(), 0x3216_30f4);
+
+ for (size, strength, expected) in [([5, 6], 4.8, 0x3f52_d2b2), ([6, 5], 9.6, 0x3f0b_996e)] {
+ package.graphs[0].size = size;
+ let params = &mut package.graphs[0].node_mut(blur).unwrap().params;
+ params.insert("angle".into(), Value::Float(0.0625));
+ params.insert("intensity".into(), Value::Float(strength));
+ let field = Image::gray(1 << size[0], 1 << size[1], |x, y| ((47 * x + 73 * y + 13 * x * y + 79) % 509) as f32 / 508.0);
+ options.inputs.insert("stripe".into(), field);
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.image(blur, 0).unwrap().get_gray(7, 13, false).to_bits(), expected);
+ }
+}
+
#[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 +76,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 +99,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);
@@ -39,3 +108,37 @@ fn atomic_filters_wrap_only_the_requested_axes_and_invalidate_cache() {
}
}
}
+
+#[test]
+fn directional_warp_uses_each_graph_tiling_axis() {
+ let mut graph = Graph::new("Warp boundaries");
+ graph.size = [4; 2];
+ graph.format = OutputFormat::F32;
+ graph.tiling_mode = ParameterInheritance::Absolute;
+ let input = graph.add_node("input_grayscale", [0.0; 2]);
+ graph.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text("field".into()));
+ let mask = graph.add_node("input_grayscale", [0.0, 50.0]);
+ graph.node_mut(mask).unwrap().params.insert("identifier".into(), Value::Text("mask".into()));
+ let warp = graph.add_node("directional_warp", [100.0, 0.0]);
+ graph.node_mut(warp).unwrap().params.insert("intensity".into(), Value::Float(16.0));
+ graph.connect(input, "output", warp, "input").unwrap();
+ graph.connect(mask, "output", warp, "intensity_input").unwrap();
+ let mut package = Package::new("Warp boundaries");
+ package.graphs.push(graph);
+ let resource = |_: &str| None;
+ let mut options = Options::new(&resource);
+ options.inputs.insert("field".into(), Image::gray(16, 16, |x, y| f32::from(x == 0 && y == 0)));
+ options.inputs.insert("mask".into(), Image::gray(16, 16, |_, _| 1.0));
+ let cache = Mutex::new(Cache::default());
+
+ for tiling in [[false, false], [true, false], [false, true], [true, true]] {
+ package.graphs[0].tiling = tiling;
+ for (axis, angle, x, y) in [(0, 0.0, 15, 0), (1, 0.25, 0, 15)] {
+ package.graphs[0].node_mut(warp).unwrap().params.insert("angle".into(), Value::Float(angle));
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&warp].error, None);
+ let image = cooked.image(warp, 0).unwrap();
+ assert_eq!(image.get_gray(x, y, false), f32::from(tiling[axis]), "tiling {tiling:?}, angle {angle}");
+ }
+ }
+}
diff --git a/crates/eval/tests/instance_image_properties.rs b/crates/eval/tests/instance_image_properties.rs
new file mode 100644
index 00000000..01c76349
--- /dev/null
+++ b/crates/eval/tests/instance_image_properties.rs
@@ -0,0 +1,98 @@
+use materialcraft_core::{FunctionGraph, Graph, OutputFormat, Package, ParameterInheritance, Value};
+use materialcraft_eval::{Cache, Options, cook};
+use std::sync::Mutex;
+
+#[test]
+fn cached_instances_follow_caps_on_absolute_child_outputs() {
+ let mut parent = Graph::new("Caller");
+ parent.size = [2; 2];
+ let mut child = Graph::new("Large output");
+ let source = child.add_node("uniform", [0.0; 2]);
+ let source_node = child.node_mut(source).unwrap();
+ source_node.base.size_mode = materialcraft_core::SizeMode::Absolute;
+ source_node.base.size = [5; 2];
+ let output = child.add_node("output", [0.0; 2]);
+ child.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text("image".into()));
+ child.connect(source, "output", output, "input").unwrap();
+ let instance = parent.add_node("graph_instance", [0.0; 2]);
+ parent.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text(child.name.clone()));
+ let mut package = Package::new("Capped instance");
+ package.graphs.extend([parent, child]);
+
+ for caps in [[16, 8], [8, 16]] {
+ let cache = Mutex::new(Cache::default());
+ for cap in caps {
+ let mut options = Options::new(&|_| None);
+ options.max_size = Some(cap);
+ let cold = cook(&package, 0, &options, &Mutex::new(Cache::default()));
+ let expected = cold.image(instance, 0).unwrap();
+ assert_eq!((expected.width(), expected.height()), (cap, cap));
+ for cached in [false, true] {
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&instance].cached, cached);
+ let actual = result.image(instance, 0).unwrap();
+ assert_eq!((actual.width(), actual.height()), (expected.width(), expected.height()));
+ assert_eq!(actual.data(), expected.data());
+ }
+ }
+ }
+}
+
+#[test]
+fn each_instance_image_pin_preserves_its_own_sampling_properties() {
+ let mut parent = Graph::new("Caller");
+ let mut child = Graph::new("Two fields");
+ for graph in [&mut parent, &mut child] {
+ graph.size = [6; 2];
+ graph.format = OutputFormat::U16;
+ }
+ let instance = parent.add_node("graph_instance", [0.0; 2]);
+ parent.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text("Two fields".into()));
+ let mut filters = Vec::new();
+ for (name, size, tiling, ratio) in [("first", [2.0, 0.5], [false, true], 0), ("second", [0.5, 2.0], [true, false], 1)] {
+ let mut noise = FunctionGraph::default();
+ let unit = noise.add_constant(Value::Float(1.0));
+ noise.output = Some(noise.add("rand", &[unit], None));
+ let source = parent.add_node("pixel_processor", [0.0; 2]);
+ let field = parent.node_mut(source).unwrap();
+ field.params.insert("function".into(), Value::Function(Box::new(noise)));
+ field.params.insert("color_mode".into(), Value::Bool(false));
+ field.base.pixel_size_mode = ParameterInheritance::Absolute;
+ field.base.pixel_size = size;
+ field.base.tiling_mode = ParameterInheritance::Absolute;
+ field.base.tiling = tiling;
+ field.base.pixel_ratio_mode = ParameterInheritance::Absolute;
+ field.base.pixel_ratio = ratio;
+ parent.connect(source, "output", instance, name).unwrap();
+
+ let input = child.add_node("input_grayscale", [0.0; 2]);
+ child.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
+ let inside = child.add_node("blur", [0.0; 2]);
+ child.node_mut(inside).unwrap().params.insert("intensity".into(), Value::Float(12.0));
+ child.connect(input, "output", inside, "input").unwrap();
+ let output = child.add_node("output", [0.0; 2]);
+ child.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(name.into()));
+ child.connect(inside, "output", output, "input").unwrap();
+
+ let flat = parent.add_node("blur", [0.0; 2]);
+ parent.node_mut(flat).unwrap().params.insert("intensity".into(), Value::Float(12.0));
+ parent.connect(source, "output", flat, "input").unwrap();
+ let receiver = parent.add_node("blur", [0.0; 2]);
+ parent.node_mut(receiver).unwrap().params.insert("intensity".into(), Value::Float(0.0));
+ parent.connect(instance, name, receiver, "input").unwrap();
+ filters.push((receiver, flat, size, tiling, ratio));
+ }
+ let mut package = Package::new("Image pin properties");
+ package.graphs.extend([parent, child]);
+ let cache = Mutex::new(Cache::default());
+ for cached in [false, true] {
+ let cooked = cook(&package, 0, &Options::new(&|_| None), &cache);
+ assert_eq!(cooked.nodes[&instance].error, None);
+ assert_eq!(cooked.nodes[&instance].cached, cached);
+ for &(receiver, flat, size, tiling, ratio) in &filters {
+ let base = cooked.nodes[&receiver].base;
+ assert_eq!((base.pixel_size, base.tiling, base.pixel_ratio), (size, tiling, ratio));
+ assert_eq!(cooked.image(receiver, 0).unwrap().data(), cooked.image(flat, 0).unwrap().data());
+ }
+ }
+}
diff --git a/crates/eval/tests/instance_pixel_size.rs b/crates/eval/tests/instance_pixel_size.rs
new file mode 100644
index 00000000..d4934710
--- /dev/null
+++ b/crates/eval/tests/instance_pixel_size.rs
@@ -0,0 +1,54 @@
+use materialcraft_core::{FunctionGraph, Graph, NodeId, OutputFormat, Package, ParameterInheritance, Value};
+use materialcraft_eval::{Cache, Options, cook};
+use std::sync::Mutex;
+
+fn field(graph: &mut Graph, pixel_size: [f32; 2]) -> NodeId {
+ let mut noise = FunctionGraph::default();
+ let unit = noise.add_constant(Value::Float(1.0));
+ noise.output = Some(noise.add("rand", &[unit], None));
+ let id = graph.add_node("pixel_processor", [0.0; 2]);
+ let node = graph.node_mut(id).unwrap();
+ node.params.insert("function".into(), Value::Function(Box::new(noise)));
+ node.base.pixel_size = pixel_size;
+ node.base.pixel_size_mode = ParameterInheritance::Absolute;
+ id
+}
+
+#[test]
+fn blur_inherits_the_pixel_size_of_each_graph_output_on_cold_and_cached_cooks() {
+ let mut child = Graph::new("Fields");
+ let mut parent = Graph::new("Filtered fields");
+ for graph in [&mut child, &mut parent] {
+ graph.size = [6; 2];
+ graph.format = OutputFormat::U16;
+ }
+ let instance = parent.add_node("graph_instance", [0.0; 2]);
+ parent.node_mut(instance).unwrap().params.insert("graph".into(), Value::Text("Fields".into()));
+ let mut comparisons = Vec::new();
+ for (identifier, size) in [("horizontal", [2.0, 0.5]), ("vertical", [0.5, 2.0])] {
+ let inside = field(&mut child, size);
+ let output = child.add_node("output", [0.0; 2]);
+ child.node_mut(output).unwrap().params.insert("identifier".into(), Value::Text(identifier.into()));
+ child.connect(inside, "output", output, "input").unwrap();
+ let outside = field(&mut parent, size);
+ let [nested, flat] = [(instance, identifier), (outside, "output")].map(|(upstream, port)| {
+ let blur = parent.add_node("blur", [0.0; 2]);
+ parent.node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(4.0));
+ parent.connect(upstream, port, blur, "input").unwrap();
+ blur
+ });
+ comparisons.push((nested, flat, size));
+ }
+ let mut package = Package::new("Pixel sizes");
+ package.graphs.extend([parent, child]);
+ let cache = Mutex::new(Cache::default());
+ for cached in [false, true] {
+ let cooked = cook(&package, 0, &Options::new(&|_| None), &cache);
+ assert_eq!(cooked.nodes[&instance].error, None);
+ assert_eq!(cooked.nodes[&instance].cached, cached);
+ for &(nested, flat, size) in &comparisons {
+ assert_eq!(cooked.nodes[&nested].base.pixel_size, size);
+ assert_eq!(cooked.image(nested, 0).unwrap().data(), cooked.image(flat, 0).unwrap().data());
+ }
+ }
+}
diff --git a/crates/eval/tests/pattern_opacity.rs b/crates/eval/tests/pattern_opacity.rs
new file mode 100644
index 00000000..68589442
--- /dev/null
+++ b/crates/eval/tests/pattern_opacity.rs
@@ -0,0 +1,285 @@
+use materialcraft_core::{FunctionGraph, Graph, OutputFormat, Package, PatternGraph, PatternNodeKind, Value, ValueType};
+use materialcraft_eval::{Cache, Options, cook};
+use std::sync::Mutex;
+
+#[test]
+fn pattern_seeds_distinguish_published_integers_from_assignments() {
+ let mut graph = Graph::new("Integer seed storage");
+ graph.size = [4; 2];
+ graph.format = OutputFormat::F32;
+ let stamp = graph.add_node("fx_map", [0.0; 2]);
+ let node = graph.node_mut(stamp).unwrap();
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert("roughness".into(), Value::Float(0.0));
+ node.params.insert("background".into(), Value::Color([0.0, 0.0, 0.0, 1.0]));
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Iterate);
+ let inner = pattern.add(PatternNodeKind::Iterate).unwrap();
+ let leaf = pattern.add(PatternNodeKind::Quadrant).unwrap();
+ pattern.nodes[0].children[1] = Some(inner);
+ pattern.nodes[1].children[1] = Some(leaf);
+ let fields = &mut pattern.nodes[1].parameters;
+ fields.insert("numberadded".into(), Value::Int(1));
+ fields.insert("randominherited".into(), Value::Bool(false));
+ fields.insert("randomseed".into(), Value::Function(Box::new(FunctionGraph::input("seed_value", ValueType::Integer))));
+ let mut opacity = FunctionGraph::default();
+ let one = opacity.add_constant(Value::Float(1.0));
+ opacity.output = Some(opacity.add("rand", &[one], None));
+ let fields = &mut pattern.nodes[2].parameters;
+ fields.insert("patterntype".into(), Value::Int(2));
+ fields.insert("blendingmode".into(), Value::Int(0));
+ fields.insert("opacity".into(), Value::Function(Box::new(opacity)));
+ let mut package = Package::new("Integer seed storage");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+
+ let write_seed = |result| {
+ let mut f = FunctionGraph::default();
+ let value = f.add_constant(Value::Int(17));
+ let store = f.add("set", &[value], Some(Value::Text("seed_value".into())));
+ let result = f.add_constant(result);
+ f.output = Some(f.add("sequence", &[store, result], None));
+ f
+ };
+ for (scope, expected) in [("input", 0.50918543), ("opacity", 0.26489496), ("iterate", 0.26489496), ("input", 0.50918543)] {
+ let mut options = Options::new(&|_| None);
+ let node = package.graphs[0].node_mut(stamp).unwrap();
+ node.functions.remove("opacity");
+ let count = match scope {
+ "input" => {
+ options.overrides.insert("seed_value".into(), Value::Int(17));
+ Value::Int(1)
+ }
+ "opacity" => {
+ node.functions.insert("opacity".into(), write_seed(Value::Float(1.0)));
+ Value::Int(1)
+ }
+ _ => Value::Function(Box::new(write_seed(Value::Int(1)))),
+ };
+ pattern.nodes[0].parameters.insert("numberadded".into(), count);
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern.clone())));
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&stamp].error, None);
+ assert_eq!(result.image(stamp, 0).unwrap().get_gray(8, 8, false), expected, "{scope}");
+ }
+}
+
+fn first_local_probe() -> (Package, materialcraft_core::NodeId) {
+ let mut graph = Graph::new("First quadrant read");
+ graph.size = [4; 2];
+ graph.format = OutputFormat::F32;
+ let stamp = graph.add_node("fx_map", [0.0; 2]);
+ let node = graph.node_mut(stamp).unwrap();
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert("roughness".into(), Value::Float(0.0));
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ let fields = &mut pattern.nodes[0].parameters;
+ fields.insert("patterntype".into(), Value::Int(2));
+ let mut tint = FunctionGraph::input("local", ValueType::Float);
+ let read = tint.output.unwrap();
+ let equal = tint.add("eq", &[read, read], None);
+ let yes = tint.add_constant(Value::Float(0.375));
+ let no = tint.add_constant(Value::Float(0.625));
+ let choose = tint.add("ifelse", &[equal, yes, no], None);
+ tint.output = Some(tint.add("set", &[choose], Some(Value::Text("local".into()))));
+ fields.insert("opacity".into(), Value::Function(Box::new(tint)));
+ node.params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+
+ let mut package = Package::new("Quadrant parameter origin");
+ package.graphs.push(graph);
+ (package, stamp)
+}
+
+#[test]
+fn bound_pattern_property_changes_the_first_local_read_at_equal_opacity() {
+ let (mut package, stamp) = first_local_probe();
+ let mut options = Options::new(&|_| None);
+ options.overrides.insert("gain".into(), Value::Float(1.0));
+ let cache = Mutex::new(Cache::default());
+ for direct in [true, false] {
+ let node = package.graphs[0].node_mut(stamp).unwrap();
+ if direct {
+ node.bindings.insert("opacity".into(), "gain".into());
+ } else {
+ node.bindings.clear();
+ node.functions.insert("opacity".into(), FunctionGraph::input("gain", ValueType::Float));
+ }
+ for fixed in [true, false, true] {
+ options.literal_inputs = if fixed { vec!["gain".into()] } else { Vec::new() };
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&stamp].error, None);
+ let expected = if fixed { 0.375 } else { 0.625 };
+ assert_eq!(result.image(stamp, 0).unwrap().get_gray(8, 8, false), expected, "direct {direct}, fixed {fixed}");
+ }
+ }
+
+ let graph = &mut package.graphs[0];
+ graph.node_mut(stamp).unwrap().functions.clear();
+ graph.output_size_function = Some(FunctionGraph::input("offset", ValueType::Integer2));
+ options.overrides.insert("offset".into(), Value::Int2([0; 2]));
+ for (mode, expected) in [(materialcraft_core::SizeMode::RelativeToParent, 0.625), (materialcraft_core::SizeMode::Absolute, 0.375)] {
+ let base = &mut package.graphs[0].node_mut(stamp).unwrap().base;
+ base.size_mode = mode;
+ base.size = if mode == materialcraft_core::SizeMode::Absolute { [4; 2] } else { [0; 2] };
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&stamp].error, None);
+ assert_eq!(result.image(stamp, 0).unwrap().get_gray(0, 0, false), expected, "{mode:?}");
+ }
+}
+
+#[test]
+fn connected_image_properties_reach_writable_quadrants() {
+ let (mut package, stamp) = first_local_probe();
+ let graph = &mut package.graphs[0];
+ let uniform = graph.add_node("uniform", [0.0; 2]);
+ let source = graph.node_mut(uniform).unwrap();
+ source.params.insert("color_mode".into(), Value::Bool(false));
+ source.functions.insert("color".into(), FunctionGraph::input("swatch", ValueType::Float4));
+ let blur = graph.add_node("blur", [0.0; 2]);
+ graph.node_mut(blur).unwrap().params.insert("intensity".into(), Value::Float(0.0));
+ graph.connect(uniform, "output", blur, "input").unwrap();
+ let drawing = graph.add_node("fx_map", [0.0; 2]);
+ let mut square = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ square.nodes[0].parameters.insert("patterntype".into(), Value::Int(2));
+ square.nodes[0].parameters.insert("opacity".into(), Value::Function(Box::new(FunctionGraph::input("swatch", ValueType::Float4))));
+ let stage = graph.node_mut(drawing).unwrap();
+ stage.params.insert("color_mode".into(), Value::Bool(false));
+ stage.params.insert("pattern".into(), Value::PatternGraph(Box::new(square)));
+ let mut options = Options::new(&|_| None);
+ options.overrides.insert("swatch".into(), Value::Float4([1.0; 4]));
+ let cache = Mutex::new(Cache::default());
+ for port in ["pattern0", "background"] {
+ for source in [uniform, blur, drawing] {
+ for (connected, fixed) in [(false, false), (true, true), (true, false), (true, true)] {
+ let graph = &mut package.graphs[0];
+ graph.disconnect(stamp, port);
+ if connected {
+ graph.connect(source, "output", stamp, port).unwrap();
+ }
+ options.literal_inputs = if fixed { vec!["swatch".into()] } else { Vec::new() };
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&stamp].error, None);
+ let background = if connected && port == "background" { 1.0 } else { 0.0 };
+ let first = if connected && !fixed { 0.625 } else { 0.375 };
+ assert_eq!(result.image(stamp, 0).unwrap().get_gray(8, 8, false), background + first, "{port}, {source:?}, {connected}, {fixed}");
+ }
+ }
+ package.graphs[0].disconnect(stamp, port);
+ }
+}
+
+#[test]
+fn filter_controls_and_pixel_programs_reach_a_writable_pattern() {
+ let (mut package, stamp) = first_local_probe();
+ let mut options = Options::new(&|_| None);
+ options.only = Some(vec![stamp]);
+ let cache = Mutex::new(Cache::default());
+ for (filter, property, input) in [
+ ("transformation", "offset", Value::Float2([0.0; 2])),
+ ("grayscale_conversion", "weights", Value::Float4([1.0, 0.0, 0.0, 0.0])),
+ ("directional_blur", "angle", Value::Float(0.25)),
+ ("levels", "in_low", Value::Float4([0.0; 4])),
+ ("warp", "intensity", Value::Float(0.0)),
+ ("pixel_processor", "function", Value::Float(0.5)),
+ ] {
+ let graph = &mut package.graphs[0];
+ let source = graph.add_node(filter, [0.0; 2]);
+ let node = graph.node_mut(source).unwrap();
+ let program = FunctionGraph::input("driver", ValueType::of(&input).unwrap());
+ if filter == "pixel_processor" {
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert(property.into(), Value::Function(Box::new(program)));
+ } else {
+ node.functions.insert(property.into(), program);
+ }
+ graph.disconnect(stamp, "pattern0");
+ graph.connect(source, "output", stamp, "pattern0").unwrap();
+ options.overrides.insert("driver".into(), input);
+ for (fixed, expected) in [(true, 0.375), (false, 0.625), (true, 0.375)] {
+ options.literal_inputs = if fixed { vec!["driver".into()] } else { Vec::new() };
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&source].error, None, "{filter}");
+ assert_eq!(result.image(stamp, 0).unwrap().get_gray(8, 8, false), expected, "{filter}, fixed {fixed}");
+ }
+ }
+}
+
+#[test]
+fn transform_matte_and_mip_level_follow_the_resolved_sampling_modes() {
+ let (mut package, stamp) = first_local_probe();
+ let graph = &mut package.graphs[0];
+ let transform = graph.add_node("transformation", [0.0; 2]);
+ graph.connect(transform, "output", stamp, "pattern0").unwrap();
+ let mut options = Options::new(&|_| None);
+ options.overrides.insert("ink".into(), Value::Float4([0.0; 4]));
+ options.overrides.insert("level".into(), Value::Int(0));
+ let cache = Mutex::new(Cache::default());
+ for (property, driver) in [("matte", "ink"), ("mip_level", "level")] {
+ let node = package.graphs[0].node_mut(transform).unwrap();
+ node.bindings.clear();
+ node.bindings.insert(property.into(), driver.into());
+ node.functions.insert("mip_mode".into(), FunctionGraph::input("mode", ValueType::Integer));
+ for axes in [[true, true], [false, true], [true, false], [false, false]] {
+ let base = &mut package.graphs[0].node_mut(transform).unwrap().base;
+ base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute;
+ base.tiling = axes;
+ for mode in [0, 1, 0] {
+ options.overrides.insert("mode".into(), Value::Int(mode));
+ let active = if property == "matte" { axes != [true; 2] } else { mode == 1 };
+ let cooked = cook(&package, 0, &options, &cache);
+ assert_eq!(cooked.nodes[&transform].error, None);
+ assert_eq!(cooked.image(stamp, 0).unwrap().get_gray(8, 8, false), if active { 0.625 } else { 0.375 }, "{property}, {axes:?}, {mode}");
+ }
+ }
+ }
+}
+
+#[test]
+fn gray_pattern_opacity_keeps_signed_and_undefined_contributions_until_blending() {
+ let mut graph = Graph::new("Signed stamp opacity");
+ graph.size = [4; 2];
+ graph.format = OutputFormat::F32;
+ let stamp = graph.add_node("fx_map", [0.0; 2]);
+ let node = graph.node_mut(stamp).unwrap();
+ node.params.insert("color_mode".into(), Value::Bool(false));
+ node.params.insert("roughness".into(), Value::Float(0.0));
+ let mut opacity = FunctionGraph::input("%gain", ValueType::Float);
+ let numerator = opacity.output.unwrap();
+ let denominator = opacity.add_constant(Value::Float(0.0));
+ opacity.output = Some(opacity.add("div", &[numerator, denominator], None));
+ node.functions.insert("opacity".into(), opacity);
+
+ let mut package = Package::new("Stamp storage");
+ package.graphs.push(graph);
+ let cache = Mutex::new(Cache::default());
+ let mut options = Options::new(&|_| None);
+ let mut pattern = PatternGraph::with_root(PatternNodeKind::Quadrant);
+ let fields = &mut pattern.nodes[0].parameters;
+ fields.insert("patterntype".into(), Value::Int(2));
+ fields.insert("patternsize".into(), Value::Float2([0.5; 2]));
+ fields.insert("opacity".into(), Value::Float4([0.25, 0.25, 0.25, 1.0]));
+ for (mode, expected) in [(0, [f32::MAX.to_bits(), f32::MIN.to_bits(), 0x7fff_ffff]), (1, [f32::MAX.to_bits(), 0, 0])] {
+ pattern.nodes[0].parameters.insert("blendingmode".into(), Value::Int(mode));
+ package.graphs[0].node_mut(stamp).unwrap().params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern.clone())));
+ for (gain, bits) in [1.0, -1.0, 0.0].into_iter().zip(expected) {
+ options.overrides.insert("gain".into(), Value::Float(gain));
+ let result = cook(&package, 0, &options, &cache);
+ assert_eq!(result.nodes[&stamp].error, None);
+ let image = result.image(stamp, 0).unwrap();
+ assert_eq!(image.get_gray(8, 8, false).to_bits(), bits);
+ assert_eq!(image.get_gray(0, 0, false).to_bits(), 0);
+ }
+ }
+
+ let child = pattern.add(PatternNodeKind::Quadrant).unwrap();
+ pattern.nodes[0].children[0] = Some(child);
+ pattern.nodes[0].parameters.insert("blendingmode".into(), Value::Int(0));
+ pattern.nodes[0].parameters.insert("patternsize".into(), Value::Float2([1.0; 2]));
+ pattern.nodes[1].parameters = pattern.nodes[0].parameters.clone();
+ pattern.nodes[1].parameters.insert("opacity".into(), Value::Float4([-0.25, -0.25, -0.25, 1.0]));
+ package.graphs[0].node_mut(stamp).unwrap().params.insert("pattern".into(), Value::PatternGraph(Box::new(pattern)));
+ options.overrides.insert("gain".into(), Value::Float(1.0));
+ let result = cook(&package, 0, &options, &cache);
+ let image = result.image(stamp, 0).unwrap();
+ assert_eq!(image.get_gray(4, 4, false), f32::MIN);
+ assert_eq!(image.get_gray(12, 12, false), f32::MAX);
+}
diff --git a/crates/eval/tests/seed_arithmetic.rs b/crates/eval/tests/seed_arithmetic.rs
new file mode 100644
index 00000000..355ac00a
--- /dev/null
+++ b/crates/eval/tests/seed_arithmetic.rs
@@ -0,0 +1,58 @@
+use materialcraft_core::{BaseParameter, FunctionGraph, Graph, OutputFormat, Package, ParameterInheritance, Value, ValueType};
+use materialcraft_eval::{Cache, Options, cook};
+use std::sync::Mutex;
+
+#[test]
+fn graph_and_node_seeds_preserve_dynamic_scalar_words() {
+ let mut graph = Graph::new("Field");
+ graph.size = [4; 2];
+ graph.format = OutputFormat::F32;
+ graph.seed_mode = ParameterInheritance::Absolute;
+ let processor = graph.add_node("pixel_processor", [0.0; 2]);
+ let mut draw = FunctionGraph::default();
+ let one = draw.add_constant(Value::Float(1.0));
+ draw.output = Some(draw.add("rand", &[one], None));
+ graph.node_mut(processor).unwrap().params.insert("function".into(), Value::Function(Box::new(draw)));
+ let mut package = Package::new("Seed arithmetic");
+ package.graphs.push(graph);
+
+ let mut function = FunctionGraph::input("$size", ValueType::Float2);
+ let width = function.add("swizzle1", &[function.output.unwrap()], Some(Value::Int(0)));
+ let scalar_one = function.add_constant(Value::Float(1.0));
+ let sum = function.add("add", &[width, scalar_one], None);
+ let product = function.add("mul", &[width, scalar_one], None);
+ let word = function.add("toint1", &[width], None);
+ let sum_word = function.add("toint1", &[sum], None);
+ let product_word = function.add("toint1", &[product], None);
+ let next_word = function.add("add", &[word, word], None);
+ let negative = function.add_constant(Value::Float(-1.5));
+ let fixed = function.add("toint1", &[negative], None);
+ let width_word = 16.0_f32.to_bits();
+ let cache = Mutex::new(Cache::default());
+ for (result, expected) in
+ [(word, width_word), (sum_word, (-1.0_f32).to_bits()), (product_word, width_word), (next_word, width_word.wrapping_mul(2)), (fixed, (-2_i32) as u32)]
+ {
+ function.output = Some(result);
+ for on_node in [false, true] {
+ let mut driven = package.clone();
+ let mut literal = package.clone();
+ if on_node {
+ let base = &mut driven.graphs[0].node_mut(processor).unwrap().base;
+ base.seed_mode = ParameterInheritance::Absolute;
+ base.functions.insert(BaseParameter::RandomSeed, function.clone());
+ let base = &mut literal.graphs[0].node_mut(processor).unwrap().base;
+ base.seed_mode = ParameterInheritance::Absolute;
+ base.seed = expected as i32;
+ } else {
+ driven.graphs[0].seed_function = Some(function.clone());
+ literal.graphs[0].seed = expected as i32;
+ }
+ let options = Options::new(&|_| None);
+ let actual = cook(&driven, 0, &options, &cache);
+ let control = cook(&literal, 0, &options, &cache);
+ assert_eq!(actual.nodes[&processor].error, None);
+ assert_eq!(actual.nodes[&processor].base.seed, expected, "output {result}, on node {on_node}");
+ assert_eq!(actual.image(processor, 0).unwrap().data(), control.image(processor, 0).unwrap().data());
+ }
+ }
+}
diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml
index 6f99b1de..215c2b30 100644
--- a/crates/formats/Cargo.toml
+++ b/crates/formats/Cargo.toml
@@ -9,6 +9,7 @@ license.workspace = true
workspace = true
[dependencies]
+craft-mime = { workspace = true }
craft-xml = { workspace = true }
craft-sbs = { workspace = true }
craft-zip = { workspace = true }
diff --git a/crates/formats/examples/sbs_library_build/convert.rs b/crates/formats/examples/sbs_library_build/convert.rs
index ed02479c..5e91ecc3 100644
--- a/crates/formats/examples/sbs_library_build/convert.rs
+++ b/crates/formats/examples/sbs_library_build/convert.rs
@@ -98,10 +98,11 @@ pub fn package(text: &str, name: &str, identities: &BTreeMap) ->
let before = semantics(&document);
let mut edits = Vec::new();
- for tag in ["formatVersion", "updaterVersion"] {
+ let format_version = materialcraft_formats::sbs::output_format_version(xml::value(root, "formatVersion"));
+ for (tag, version) in [("formatVersion", format_version), ("updaterVersion", env!("CARGO_PKG_VERSION"))] {
if xml::child(root, tag).is_none() {
let offset = root.first_element_child().ok_or("package has no content")?.range().start;
- edits.push(XmlEdit { range: offset..offset, replacement: xml::leaf(tag, env!("CARGO_PKG_VERSION")) });
+ edits.push(XmlEdit { range: offset..offset, replacement: xml::leaf(tag, version) });
}
}
@@ -137,7 +138,10 @@ pub fn package(text: &str, name: &str, identities: &BTreeMap) ->
"fileUID" if node.parent().is_some_and(|p| p.has_tag_name("package")) => {
xml::set(&mut edits, node, identities.get(name).ok_or("missing package identity")?);
}
- "formatVersion" | "updaterVersion" if node.parent().is_some_and(|p| p.has_tag_name("package")) => {
+ "formatVersion" if node.parent().is_some_and(|p| p.has_tag_name("package")) => {
+ xml::set(&mut edits, node, format_version);
+ }
+ "updaterVersion" if node.parent().is_some_and(|p| p.has_tag_name("package")) => {
xml::set(&mut edits, node, env!("CARGO_PKG_VERSION"));
}
"dependency" => {
diff --git a/crates/formats/examples/sbs_library_build/tests.rs b/crates/formats/examples/sbs_library_build/tests.rs
index 592af389..6413fe0e 100644
--- a/crates/formats/examples/sbs_library_build/tests.rs
+++ b/crates/formats/examples/sbs_library_build/tests.rs
@@ -39,16 +39,19 @@ fn flat_package_inventory_enforces_the_total_file_limit() {
}
#[test]
-fn conversion_starts_both_versions_at_the_workspace_release() {
- let saved = materialcraft_formats::sbs::write_sbs(&materialcraft_core::Package::new("Version check")).unwrap();
- let saved = xml::parse(std::str::from_utf8(&saved).unwrap()).unwrap();
- let expected = xml::value(saved.root_element(), "updaterVersion").unwrap();
- for source in [PACKAGE.to_string(), PACKAGE.replacen("", "", 1)] {
+fn conversion_preserves_the_schema_and_records_the_saving_release() {
+ for (source, schema) in [
+ (PACKAGE.to_string(), "1.1.0.202502"),
+ (PACKAGE.replacen("", "", 1), "1.1.0.202502"),
+ (PACKAGE.replace("", ""), "1.1.0.202401"),
+ (PACKAGE.replace("1.1.0.202502", "0.1.3"), "1.1.0.202401"),
+ ] {
let converted = convert::package(&source, "example.sbs", &identities("example.sbs")).unwrap();
let converted = xml::parse(&converted.xml).unwrap();
- assert_eq!(xml::value(converted.root_element(), "updaterVersion"), Some(expected));
- assert_eq!(xml::value(converted.root_element(), "formatVersion"), Some(expected));
+ assert_eq!(xml::value(converted.root_element(), "updaterVersion"), Some(env!("CARGO_PKG_VERSION")));
+ assert_eq!(xml::value(converted.root_element(), "formatVersion"), Some(schema));
+ assert_eq!(converted.root_element().children().filter(|n| n.has_tag_name("formatVersion")).count(), 1);
assert_eq!(converted.root_element().children().filter(|n| n.has_tag_name("updaterVersion")).count(), 1);
}
}
diff --git a/crates/formats/src/image.rs b/crates/formats/src/image.rs
index fa2a3994..66212d2b 100644
--- a/crates/formats/src/image.rs
+++ b/crates/formats/src/image.rs
@@ -1,16 +1,22 @@
use crate::{Depth, FormatError, Result, guard};
use craft_image_codecs::{ChannelLayout, CodecError, DecodeOptions, EncodeOptions, Format, Limits as CodecLimits, SampleType};
use craft_texture::{Image, Kind, Limits, MAX_SIDE, linear_to_srgb, srgb_to_linear};
+use materialcraft_nodes::BitmapColorSpace;
+
+const MAX_DECODE_BYTES: u64 = 1 << 30;
/// Decode image file bytes into a linear float image (8-bit color is sRGB-decoded; grayscale files stay grayscale)
pub fn decode(bytes: &[u8], linear: bool) -> Result {
+ decode_with_color_space(bytes, if linear { BitmapColorSpace::Linear } else { BitmapColorSpace::Srgb })
+}
+
+/// Decode a bitmap using its file transfer or an explicit interpretation of its stored channels.
+pub fn decode_with_color_space(bytes: &[u8], space: BitmapColorSpace) -> Result {
if bytes.starts_with(b"DDS ") {
- return guard(|| crate::dds_image::decode(bytes, linear), || FormatError::Image("DDS decoder failed".into()));
+ return guard(|| crate::dds_image::decode(bytes, space == BitmapColorSpace::Linear), || FormatError::Image("DDS decoder failed".into()));
}
const SVG_SNIFF_BYTES: usize = 4096;
- const MAX_DECODE_BYTES: u64 = 1 << 30;
-
if std::str::from_utf8(bytes.get(..bytes.len().min(SVG_SNIFF_BYTES)).unwrap_or_default()).is_ok_and(|text| text.contains("