mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-28 17:19:17 +01:00
Merge pull request #335 from storytold/parity/root-graph-measurements
Review root graph parity and SBS round-trip corrections
This commit is contained in:
258 files changed
+48215
-1828
No files matched your search
+2
-1
@@ -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)) |
|
||||
|
||||
Generated
+8
@@ -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]]
|
||||
|
||||
+7
-1
@@ -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
|
||||
|
||||
+9
-1
@@ -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
|
||||
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Functions"/><formatVersion v="1.1.0.202401"/><updaterVersion v="0.4.1"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><group><uid v="1000000002"/><identifier v="Functions"/><content><group><uid v="1000000003"/><identifier v="Tonemappers"/><content><function><identifier v="tonemap_Hejl"/><uid v="1000000039"/><attributes><description v="Evaluates the tonemap_Hejl function graph. Result type: Float3. Inputs: input."/><tags v="Color"/><label v="Hejl tonemapper"/></attributes><paraminputs><paraminput><identifier v="input"/><uid v="1000000040"/><attributes><label v="input"/><description v=""/></attributes><type v="1024"/><defaultValue><constantValueFloat3 v="1 1 1"/></defaultValue><defaultWidget><name v="slider"/><options><option><name v="min"/><value v="0"/></option><option><name v="max"/><value v="1"/></option><option><name v="clamp"/><value v="0"/></option><option><name v="step"/><value v="0.01"/></option></options></defaultWidget></paraminput></paraminputs><type v="1024"/><paramValue><dynamicValue><rootnode v="1000000029"/><paramNodes><paramNode><uid v="1000000004"/><function v="max"/><type v="1024"/><GUILayout><gpos v="624 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000018"/></connection><connection><identifier v="b"/><connRef v="1000000011"/></connection></connections></paramNode><paramNode><uid v="1000000005"/><function v="add"/><type v="1024"/><GUILayout><gpos v="1184 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000028"/></connection><connection><identifier v="b"/><connRef v="1000000023"/></connection></connections></paramNode><paramNode><uid v="1000000006"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="scalar"/><connRef v="1000000012"/></connection></connections></paramNode><paramNode><uid v="1000000007"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 64 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="1.25"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000008"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="624 224 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000016"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000009"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="344 64 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000021"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000010"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000019"/></connection><connection><identifier v="scalar"/><connRef v="1000000007"/></connection></connections></paramNode><paramNode><uid v="1000000011"/><function v="const_float3"/><type v="1024"/><GUILayout><gpos v="64 224 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float3"/><constantValue><constantValueFloat3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000012"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 384 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.22"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000013"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000022"/></connection></connections></paramNode><paramNode><uid v="1000000014"/><function v="mul"/><type v="1024"/><GUILayout><gpos v="1464 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="b"/><connRef v="1000000005"/></connection></connections></paramNode><paramNode><uid v="1000000015"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 384 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000032"/></connection></connections></paramNode><paramNode><uid v="1000000016"/><function v="div"/><type v="256"/><GUILayout><gpos v="344 544 0"/></GUILayout><connections><connectionLine truncated
|
||||
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Functions"/><formatVersion v="1.1.0.202401"/><updaterVersion v="0.4.1"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><group><uid v="1000000002"/><identifier v="Functions"/><content><group><uid v="1000000003"/><identifier v="Tonemappers"/><content><function><identifier v="tonemap_Hejl"/><uid v="1000000039"/><attributes><description v="Evaluates the tonemap_Hejl function graph. Result type: Float3. Inputs: input."/><tags v="Color"/><label v="Hejl tonemapper"/></attributes><paraminputs><paraminput><identifier v="input"/><uid v="1000000040"/><attributes><label v="input"/><description v=""/></attributes><type v="1024"/><defaultValue><constantValueFloat3 v="1 1 1"/></defaultValue><defaultWidget><name v="slider"/><options><option><name v="min"/><value v="0"/></option><option><name v="max"/><value v="1"/></option><option><name v="clamp"/><value v="0"/></option><option><name v="step"/><value v="0.01"/></option></options></defaultWidget></paraminput></paraminputs><type v="1024"/><paramValue><dynamicValue><rootnode v="1000000029"/><paramNodes><paramNode><uid v="1000000004"/><function v="max"/><type v="1024"/><GUILayout><gpos v="624 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000018"/></connection><connection><identifier v="b"/><connRef v="1000000011"/></connection></connections></paramNode><paramNode><uid v="1000000005"/><function v="add"/><type v="1024"/><GUILayout><gpos v="1184 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000028"/></connection><connection><identifier v="b"/><connRef v="1000000023"/></connection></connections></paramNode><paramNode><uid v="1000000006"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="scalar"/><connRef v="1000000012"/></connection></connections></paramNode><paramNode><uid v="1000000007"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 64 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="1.25"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000008"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="624 224 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000016"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000009"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="344 64 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000021"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000010"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000019"/></connection><connection><identifier v="scalar"/><connRef v="1000000007"/></connection></connections></paramNode><paramNode><uid v="1000000011"/><function v="const_float3"/><type v="1024"/><GUILayout><gpos v="64 224 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float3"/><constantValue><constantValueFloat3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000012"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 384 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.22"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000013"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000022"/></connection></connections></paramNode><paramNode><uid v="1000000014"/><function v="mul"/><type v="1024"/><GUILayout><gpos v="1464 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="b"/><connRef v="1000000005"/></connection></connections></paramNode><paramNode><uid v="1000000015"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 384 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000032"/></connection></connections></paramNode><paramNode><uid v="1000000016"/><function v="div"/><type v="256"/><GUILayout><gpos v="344 544 0"/></GUILayout><connections><connectionLine truncated
|
||||
@@ -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<u8>) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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]])
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -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")]
|
||||
|
||||
+77
-10
@@ -28,10 +28,25 @@ pub struct Graph {
|
||||
pub pins: Vec<Pin>,
|
||||
/// 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<crate::GraphSizeOffset>,
|
||||
/// Authored function supplying the two output size exponents or offsets.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub output_size_function: Option<crate::FunctionGraph>,
|
||||
#[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<crate::FunctionGraph>,
|
||||
#[serde(default)]
|
||||
pub pixel_ratio: i32,
|
||||
#[serde(default)]
|
||||
@@ -54,17 +69,25 @@ pub struct Graph {
|
||||
pub input_images: BTreeMap<String, String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
pub input_images_linear: BTreeSet<String>,
|
||||
/// 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<String>,
|
||||
#[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<Item = &crate::FunctionGraph> {
|
||||
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<Item = &mut crate::FunctionGraph> {
|
||||
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<Item = &mut crate::GraphInstance> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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<String>,
|
||||
pub graphs: Vec<Graph>,
|
||||
|
||||
@@ -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<u32, String> {
|
||||
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::<u32, u32>::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))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<OutputFormat> {
|
||||
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<PngRasterInfo> {
|
||||
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)) })
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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])));
|
||||
|
||||
@@ -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<Image> {
|
||||
pub fn get(&mut self, key: &(u64, BitmapColorSpace)) -> Option<Image> {
|
||||
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();
|
||||
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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<J> {
|
||||
} 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<Str
|
||||
session.pkg = package;
|
||||
session.document_open = true;
|
||||
session.path = path;
|
||||
session.recovery_origin = None;
|
||||
session.graph = 0;
|
||||
|
||||
session.clipboard = None;
|
||||
@@ -178,13 +179,13 @@ pub fn open_bytes(session: &mut Session, bytes: &[u8], name: Option<String>) ->
|
||||
}
|
||||
|
||||
pub fn open_bytes_linked(session: &mut Session, bytes: &[u8], name: Option<String>, linked: &dyn Fn(&str) -> Option<Vec<u8>>) -> 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<Vec<u8>>) -> 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<String>,
|
||||
linked: &dyn Fn(&str) -> Option<Vec<u8>>,
|
||||
load: impl FnOnce(&mut Package) -> Vec<String>,
|
||||
load: impl FnOnce(&mut Session, &mut Package) -> Vec<String>,
|
||||
) -> 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<Vec
|
||||
}
|
||||
|
||||
// Byte-only consumers (portable materials and recovery) retain standalone embedded SBS
|
||||
Ok(materialcraft_formats::sbs::write_sbs(&package_for_save(session, path))?)
|
||||
// A recovered document still has an import folder for its authored links.
|
||||
Ok(materialcraft_formats::sbs::write_sbs(&package_for_save(session, path.or(session.recovery_origin.as_deref())))?)
|
||||
}
|
||||
|
||||
fn package_for_save(session: &Session, path: Option<&str>) -> 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<String> {
|
||||
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<materialcraft_formats::project::ProjectFiles> {
|
||||
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<J> {
|
||||
|
||||
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}))
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
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<usize> {
|
||||
}
|
||||
}
|
||||
|
||||
fn seed(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
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<J> {
|
||||
let i = graph_index(s, p)?;
|
||||
s.graph = i;
|
||||
@@ -120,15 +148,14 @@ fn duplicate(s: &mut Session, p: &J) -> Result<J> {
|
||||
|
||||
fn size(s: &mut Session, p: &J) -> Result<J> {
|
||||
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<J> {
|
||||
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<J> {
|
||||
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)?;
|
||||
}
|
||||
|
||||
@@ -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<u8> {
|
||||
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
|
||||
}
|
||||
@@ -19,12 +19,14 @@ pub fn session(session: &Session, requested_graph: Option<usize>) -> 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<usize>) -> 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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String> {
|
||||
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<String>) -> Vec<String> {
|
||||
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<String> {
|
||||
load_references(package, references(package))
|
||||
}
|
||||
|
||||
fn references(package: &Package) -> Vec<String> {
|
||||
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<materialcraft_formats::sbs::SbsRead, String>
|
||||
|
||||
const MAX_DEPENDENCY_READS: usize = 4096;
|
||||
|
||||
fn resolve(package: &mut Package, mut pending: Vec<String>, read: &dyn Fn(&str) -> Result<materialcraft_formats::sbs::SbsRead, String>) -> Vec<String> {
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
fn resolve(package: &mut Package, pending: Vec<String>, read: &dyn Fn(&str) -> Result<materialcraft_formats::sbs::SbsRead, String>) -> Vec<String> {
|
||||
resolve_with_catalog(package, pending, read, |_, _| {})
|
||||
}
|
||||
|
||||
fn read_references(package: &mut Package, pending: Vec<String>, catalog_read: impl FnMut(&str, &Arc<Package>)) -> Vec<String> {
|
||||
resolve_with_catalog(package, pending, &load_file, catalog_read)
|
||||
}
|
||||
|
||||
fn resolve_with_catalog(
|
||||
package: &mut Package,
|
||||
mut pending: Vec<String>,
|
||||
read: &dyn Fn(&str) -> Result<materialcraft_formats::sbs::SbsRead, String>,
|
||||
mut catalog_read: impl FnMut(&str, &Arc<Package>),
|
||||
) -> Vec<String> {
|
||||
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<String>, 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}")),
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ fn reaches(package: &Package, changed: &BTreeSet<String>, sources: &BTreeMap<Str
|
||||
false
|
||||
}
|
||||
|
||||
fn interfaces(package: &mut Package, sources: &BTreeMap<String, Arc<Package>>) -> bool {
|
||||
pub(crate) fn interfaces(package: &mut Package, sources: &BTreeMap<String, Arc<Package>>) -> bool {
|
||||
let updates: Vec<_> = package
|
||||
.graphs
|
||||
.iter()
|
||||
|
||||
@@ -31,7 +31,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
"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<J> {
|
||||
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<u8>)> {
|
||||
fn unbind(s: &mut Session, p: &J) -> Result<J> {
|
||||
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()))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<ExportSize>,
|
||||
pub values: BTreeMap<String, Value>,
|
||||
pub inputs: BTreeMap<String, Image>,
|
||||
/// Known sample depth of each bound file before decoding to linear floats.
|
||||
pub input_formats: BTreeMap<String, OutputFormat>,
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -6,6 +6,7 @@ pub struct OpenDocument {
|
||||
pub id: u64,
|
||||
pub pkg: Package,
|
||||
pub path: Option<String>,
|
||||
recovery_origin: Option<String>,
|
||||
pub graph: usize,
|
||||
pub modified: bool,
|
||||
selection: Vec<NodeId>,
|
||||
@@ -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,
|
||||
|
||||
@@ -36,11 +36,8 @@ fn reload(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
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;
|
||||
|
||||
@@ -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<usize>, options: &Options<'_>, cache: &Arc<Mutex<Cache>>) -> 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<usize>,
|
||||
options: &Options<'_>,
|
||||
cache: &Arc<Mutex<Cache>>,
|
||||
previous: &BTreeMap<usize, Arc<PreviewSampling>>,
|
||||
) -> 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
|
||||
|
||||
@@ -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<String>,
|
||||
/// Original link base when import warnings require a new save destination.
|
||||
pub(crate) recovery_origin: Option<String>,
|
||||
/// Index of the graph being edited.
|
||||
pub graph: usize,
|
||||
pub selection: Vec<NodeId>,
|
||||
@@ -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<usize, Arc<materialcraft_eval::PreviewSampling>> {
|
||||
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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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()]);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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::<Vec<_>>(), ["$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::<Vec<_>>(), ["$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();
|
||||
|
||||
|
||||
@@ -3,6 +3,20 @@ use serde_json::json;
|
||||
|
||||
const SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" width="2" height="2"><rect width="2" height="2" fill="red"/></svg>"#;
|
||||
|
||||
#[test]
|
||||
fn saving_a_recovered_package_keeps_its_missing_resource_link_relative() {
|
||||
let bytes = br#"<package><content><resource><identifier v="mask"/><format v="png"/><filepath v="maps/original.png"/></resource></content></package>"#;
|
||||
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#"<filename v="maps/original.png"/>"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_only_sbs_import_resolves_library_resource_substitutes() {
|
||||
let xml = br#"<package><content>
|
||||
|
||||
@@ -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#"<filename v="sbs://{helper}""#)), "{helper}");
|
||||
}
|
||||
let mut reopened = sample_session();
|
||||
run(&mut reopened, "file.open", json!({ "path": saved }));
|
||||
assert!(reopened.pkg.dependencies.contains_key("sbs://functions_hash.sbs"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_a_library_graph_preserves_verified_dependency_trees() {
|
||||
use materialcraft_engine::formats::sbs::library;
|
||||
|
||||
let directory = TempDir::new("library-graph-export");
|
||||
let source = library::root().join("bevel.sbs");
|
||||
let mut session = sample_session();
|
||||
run(&mut session, "file.open", json!({ "path": source }));
|
||||
let saved = directory.file("caller.sbs");
|
||||
run(&mut session, "file.saveAs", json!({ "path": saved }));
|
||||
|
||||
let mut reopened = sample_session();
|
||||
run(&mut reopened, "file.open", json!({ "path": saved }));
|
||||
let links: std::collections::BTreeSet<_> =
|
||||
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#"<filename v="sbs://blend_switch.sbs""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saving_inside_the_library_preserves_distinct_catalog_and_file_references() {
|
||||
use materialcraft_engine::{
|
||||
core::{Graph, GraphInstance, Package},
|
||||
file_cmds::{open_bytes, save_files_at},
|
||||
formats::sbs::{library, read_sbs, write_sbs},
|
||||
};
|
||||
|
||||
let file = "blend_switch.sbs";
|
||||
let catalog = "sbs://blend_switch.sbs";
|
||||
let mut graph = Graph::new("Caller");
|
||||
for reference in [catalog, file] {
|
||||
let id = graph.add_node("graph_instance", [0.0; 2]);
|
||||
graph.node_mut(id).unwrap().instance = Some(GraphInstance {
|
||||
package: reference.into(),
|
||||
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);
|
||||
|
||||
// Exercise the in-library save path entirely in memory.
|
||||
let caller = library::root().join("catalog-link-caller.sbs");
|
||||
let path = caller.to_str().unwrap();
|
||||
let mut session = sample_session();
|
||||
open_bytes(&mut session, &write_sbs(&package).unwrap(), Some(path.into())).unwrap();
|
||||
let saved = save_files_at(&session, session.path.as_deref().unwrap()).unwrap();
|
||||
let parsed = read_sbs(saved.xml().unwrap(), path, &|_| None).unwrap();
|
||||
let links: Vec<_> = 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() {
|
||||
|
||||
@@ -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 }
|
||||
@@ -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<Vec<NodeOutput>>,
|
||||
pub bases: Option<Arc<[ResolvedBaseParameters]>>,
|
||||
}
|
||||
|
||||
/// LRU cache of node outputs, bounded by bytes
|
||||
pub struct Cache {
|
||||
entries: HashMap<u64, (Arc<Vec<NodeOutput>>, usize, u64)>,
|
||||
entries: HashMap<u64, (CachedOutputs, usize, u64)>,
|
||||
bytes: usize,
|
||||
cap: usize,
|
||||
tick: u64,
|
||||
@@ -48,7 +54,7 @@ impl Cache {
|
||||
self.bytes = 0;
|
||||
}
|
||||
|
||||
pub(crate) fn get(&mut self, key: u64) -> Option<Arc<Vec<NodeOutput>>> {
|
||||
pub(crate) fn get(&mut self, key: u64) -> Option<CachedOutputs> {
|
||||
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<Vec<NodeOutput>>) {
|
||||
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<Vec<NodeOutput>>, bases: Option<Arc<[ResolvedBaseParameters]>>) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,10 @@ fn output(side: u32) -> Arc<Vec<NodeOutput>> {
|
||||
#[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);
|
||||
|
||||
@@ -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<String, Value>, variables: &BTreeMap<String, Value>) -> u64 {
|
||||
pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap<String, Value>, 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<String, Value>, 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<String, Value>, 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()
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::collections::BTreeMap;
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Cooked {
|
||||
pub nodes: BTreeMap<NodeId, NodeResult>,
|
||||
pub preview_sampling: Option<std::sync::Arc<crate::PreviewSampling>>,
|
||||
/// Total wall time of the cook in milliseconds
|
||||
pub ms: f32,
|
||||
pub cancelled: bool,
|
||||
|
||||
@@ -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<NodeOutput> {
|
||||
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<NodeOutput> {
|
||||
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<f32> = 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<Image> {
|
||||
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<Image> {
|
||||
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<Image> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Cache>) -> 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<String, Value> {
|
||||
// Exposed parameter values: the graph's own, then the caller's overrides
|
||||
let mut variables: BTreeMap<String, Value> =
|
||||
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<String, Option<Image>>) -> 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()
|
||||
}
|
||||
@@ -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<crate::PreviewSampling>, 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<String, Value>,
|
||||
size: (u32, u32),
|
||||
fixed: &[String],
|
||||
base: crate::resolved_base_parameters::ResolvedBaseParameters,
|
||||
options: &Options,
|
||||
cache: &Mutex<Cache>,
|
||||
) -> Result<Vec<NodeOutput>, String> {
|
||||
previous: Option<&crate::PreviewSampling>,
|
||||
) -> Result<CookedInstance, String> {
|
||||
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::<Result<_, String>>()?;
|
||||
let sampling = cooked.preview_sampling.map(|state| (state, crate::cache_key::hash_of(&keys)));
|
||||
Ok(CookedInstance { ports, sampling })
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String, Value>,
|
||||
fixed: &'a [String],
|
||||
assigned_integers: &'a [String],
|
||||
}
|
||||
|
||||
impl GraphVariables for BoundVariables<'_> {
|
||||
fn graph_values(&self) -> &BTreeMap<String, Value> {
|
||||
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<Cache>,
|
||||
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<Arc<[_]>> = None;
|
||||
let result: Result<Vec<NodeOutput>, 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)))
|
||||
}
|
||||
@@ -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::<f32>()),
|
||||
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::<f32>());
|
||||
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::<Value>().saturating_add(text.len()),
|
||||
Self::Value(_) => size_of::<Value>(),
|
||||
}
|
||||
|
||||
@@ -10,9 +10,18 @@ pub struct NodeResult {
|
||||
pub parameters: std::collections::BTreeMap<String, materialcraft_core::Value>,
|
||||
/// One image per output port (empty when the cook failed)
|
||||
pub outputs: Arc<Vec<NodeOutput>>,
|
||||
/// Instance ports carry the dimensions, format and sampling properties of their source.
|
||||
pub output_bases: Option<Arc<[crate::ResolvedBaseParameters]>>,
|
||||
pub error: Option<String>,
|
||||
/// 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<crate::ResolvedBaseParameters> {
|
||||
self.outputs.get(index)?;
|
||||
Some(self.output_bases.as_deref().and_then(|ports| ports.get(index)).copied().unwrap_or(self.base))
|
||||
}
|
||||
}
|
||||
@@ -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, 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 });
|
||||
|
||||
@@ -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<Vec<NodeId>>,
|
||||
/// Images for the graph's input nodes, by identifier (graph instances)
|
||||
pub inputs: BTreeMap<String, Image>,
|
||||
/// Upstream storage precision for caller-supplied images. Unspecified floating inputs use full precision.
|
||||
pub input_formats: BTreeMap<String, OutputFormat>,
|
||||
/// Resolved source properties for each image wired to a graph instance.
|
||||
pub input_bases: BTreeMap<String, crate::ResolvedBaseParameters>,
|
||||
/// Caller textures which have only their base level when passed through an instance.
|
||||
pub base_level_inputs: BTreeSet<String>,
|
||||
/// 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<String, u64>,
|
||||
/// Original storage of decoded external files. Wired graph inputs use their upstream format.
|
||||
pub bitmap_formats: BTreeMap<String, OutputFormat>,
|
||||
/// Values for the graph's exposed parameters (graph instances), over the graph's own
|
||||
pub overrides: BTreeMap<String, Value>,
|
||||
/// Exposed inputs whose fixed instance arguments can be folded during function evaluation.
|
||||
pub literal_inputs: Vec<String>,
|
||||
/// 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,
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
+294
-13
@@ -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<String, Value>,
|
||||
pub instance_literals: Vec<String>,
|
||||
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<Value> {
|
||||
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<String, Value>>,
|
||||
seed: u32,
|
||||
size: [u32; 2],
|
||||
) -> Result<BTreeMap<String, Value>, String> {
|
||||
base: ResolvedBaseParameters,
|
||||
literal_inputs: &[String],
|
||||
mut assigned_integers: Option<&mut Vec<String>>,
|
||||
) -> Result<ResolvedParameters, String> {
|
||||
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<String, Value>) {
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, Value>,
|
||||
seed: u32,
|
||||
size: [u32; 2],
|
||||
allow_scalar: bool,
|
||||
) -> Result<Value, String> {
|
||||
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<String>>,
|
||||
) -> 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))
|
||||
}
|
||||
@@ -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<ValueType>,
|
||||
}
|
||||
+30
-39
@@ -14,53 +14,38 @@ pub fn ports_with_connections<'a>(
|
||||
incoming: impl IntoIterator<Item = &'a materialcraft_core::Connection>,
|
||||
) -> (Vec<Port>, Vec<Port>) {
|
||||
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<Port> {
|
||||
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<Port> = 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())
|
||||
|
||||
@@ -7,11 +7,12 @@ pub(crate) struct PreparedGraph<'a> {
|
||||
pub index: GraphIndex<'a>,
|
||||
pub order: Vec<NodeId>,
|
||||
pub parent_base: crate::resolved_base_parameters::ResolvedBaseParameters,
|
||||
pub base_error: Option<String>,
|
||||
ports: BTreeMap<NodeId, (Vec<Port>, Vec<Port>)>,
|
||||
}
|
||||
|
||||
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<String, materialcraft_core::Value>) -> 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<crate::ResolvedBaseParameters> {
|
||||
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<crate::ResolvedBaseParameters> {
|
||||
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()))
|
||||
}
|
||||
|
||||
@@ -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<u32>),
|
||||
pub(crate) caller_format: Option<materialcraft_core::OutputFormat>,
|
||||
stamps: BTreeMap<NodeId, Stamp>,
|
||||
instances: BTreeMap<NodeId, Instance>,
|
||||
}
|
||||
|
||||
#[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<usize, (u64, bool)>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Instance {
|
||||
input_key: u64,
|
||||
output_key: u64,
|
||||
sampling: Arc<PreviewSampling>,
|
||||
}
|
||||
|
||||
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>) {
|
||||
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)) }
|
||||
}
|
||||
}
|
||||
@@ -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<String, Value>,
|
||||
) -> 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<String, Value>) -> 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<String, Value>) -> 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<Self>, 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<String, Value>) {
|
||||
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<String, Value>) {
|
||||
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<ResolvedBaseParameters>,
|
||||
parent: ResolvedBaseParameters,
|
||||
variables: &mut std::borrow::Cow<'_, BTreeMap<String, Value>>,
|
||||
literal_inputs: &[String],
|
||||
mut assigned_integers: Option<&mut Vec<String>>,
|
||||
) -> Result<(ResolvedBaseParameters, BTreeMap<BaseParameter, Value>), 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))
|
||||
}
|
||||
+1717
-11
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,267 @@
|
||||
use super::*;
|
||||
use materialcraft_core::{OutputFormat, Resource, ResourceBytes};
|
||||
|
||||
fn rectangle_font(height: i16, metrics: [i16; 3]) -> Vec<u8> {
|
||||
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<u8> {
|
||||
fn words(values: &[i16]) -> Vec<u8> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String, Value>,
|
||||
variables: &BTreeMap<String, Value>,
|
||||
variables: &dyn materialcraft_nodes::GraphVariables,
|
||||
seed: u32,
|
||||
size: [u32; 2],
|
||||
images: &[Option<Image>],
|
||||
image_formats: &[OutputFormat],
|
||||
tile: bool,
|
||||
) -> Result<Value, String> {
|
||||
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)
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -98,10 +98,11 @@ pub fn package(text: &str, name: &str, identities: &BTreeMap<String, String>) ->
|
||||
|
||||
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<String, String>) ->
|
||||
"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" => {
|
||||
|
||||
@@ -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("<content>", "<updaterVersion v=\"1.1.0.202502\"/><content>", 1)] {
|
||||
fn conversion_preserves_the_schema_and_records_the_saving_release() {
|
||||
for (source, schema) in [
|
||||
(PACKAGE.to_string(), "1.1.0.202502"),
|
||||
(PACKAGE.replacen("<content>", "<updaterVersion v=\"0.1.3\"/><content>", 1), "1.1.0.202502"),
|
||||
(PACKAGE.replace("<formatVersion v=\"1.1.0.202502\"/>", ""), "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);
|
||||
}
|
||||
}
|
||||
|
||||
+65
-17
@@ -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<Image> {
|
||||
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<Image> {
|
||||
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("<svg")) {
|
||||
return guard(|| crate::svg::decode(bytes), || FormatError::Image("SVG decoder failed".into()));
|
||||
}
|
||||
@@ -19,34 +25,76 @@ pub fn decode(bytes: &[u8], linear: bool) -> Result<Image> {
|
||||
let opts = DecodeOptions { limits, keep_orientation: true };
|
||||
let format = craft_image_codecs::detect(bytes).unwrap_or(Format::Tga);
|
||||
let failed = || FormatError::Image("the decoder failed on this file".into());
|
||||
let codec_error = |e: CodecError| match e {
|
||||
CodecError::LimitExceeded(msg) => FormatError::Image(msg),
|
||||
e => FormatError::Image(e.to_string()),
|
||||
let codec_error = |error: CodecError| match error {
|
||||
CodecError::LimitExceeded(message) => FormatError::Image(message),
|
||||
error => FormatError::Image(error.to_string()),
|
||||
};
|
||||
|
||||
let decoded = guard(|| craft_image_codecs::decode_as_with(format, bytes, &opts).map_err(codec_error), failed)?;
|
||||
let (w, h) = decoded.dimensions();
|
||||
if w == 0 || h == 0 || w > MAX_SIDE || h > MAX_SIDE {
|
||||
return Err(FormatError::Image(format!("{w}x{h} is outside 1..={MAX_SIDE} pixels")));
|
||||
}
|
||||
|
||||
let png = if space == BitmapColorSpace::FromFile && format == Format::Png { materialcraft_core::png_raster_info(bytes) } else { None };
|
||||
let stored = match space {
|
||||
BitmapColorSpace::Linear => true,
|
||||
BitmapColorSpace::Srgb => false,
|
||||
BitmapColorSpace::FromFile => png.is_some() || matches!(format, Format::Jpeg | Format::Bmp | Format::Tiff | Format::Tga),
|
||||
};
|
||||
let table = png.and_then(|info| {
|
||||
let maximum = if info.format == materialcraft_core::OutputFormat::U8 { 255 } else { 65535 };
|
||||
png_channel_table(bytes, maximum)
|
||||
});
|
||||
let float = decoded.sample_type().is_float();
|
||||
if decoded.layout().is_gray() {
|
||||
let gray = decoded.converted(ChannelLayout::Gray, SampleType::F32);
|
||||
let data = gray.to_f32_samples().ok_or_else(|| FormatError::Image("bad buffer".into()))?;
|
||||
return Image::from_data(w, h, Kind::Gray, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string()));
|
||||
let mut data = gray.to_f32_samples().ok_or_else(|| FormatError::Image("bad buffer".into()))?;
|
||||
if let Some(table) = &table {
|
||||
for value in &mut data {
|
||||
*value = mapped_channel(table, *value);
|
||||
}
|
||||
}
|
||||
return Image::from_data(w, h, Kind::Gray, data, &Limits::default())
|
||||
.map(|image| image.with_integer_sampling(!float))
|
||||
.map_err(|error| FormatError::Image(error.to_string()));
|
||||
}
|
||||
|
||||
let float = decoded.sample_type().is_float();
|
||||
let mut data = decoded.to_rgba_f32(&limits).map_err(codec_error)?;
|
||||
if !(float || linear) {
|
||||
for px in data.as_chunks_mut::<4>().0 {
|
||||
for c in px.iter_mut().take(3) {
|
||||
*c = srgb_to_linear(*c);
|
||||
if let Some(table) = table {
|
||||
for pixel in data.as_chunks_mut::<4>().0 {
|
||||
for channel in &mut pixel[..3] {
|
||||
*channel = mapped_channel(&table, *channel);
|
||||
}
|
||||
}
|
||||
} else if !(float || stored) {
|
||||
for pixel in data.as_chunks_mut::<4>().0 {
|
||||
for channel in &mut pixel[..3] {
|
||||
*channel = srgb_to_linear(*channel);
|
||||
}
|
||||
}
|
||||
}
|
||||
Image::from_data(w, h, Kind::Color, data, &Limits::default())
|
||||
.map(|image| image.with_integer_sampling(stored && !float))
|
||||
.map_err(|error| FormatError::Image(error.to_string()))
|
||||
}
|
||||
|
||||
Image::from_data(w, h, Kind::Color, data, &Limits::default()).map_err(|e| FormatError::Image(e.to_string()))
|
||||
fn png_channel_table(bytes: &[u8], maximum: u32) -> Option<Vec<f32>> {
|
||||
let metadata = craft_image_codecs::png_probe::color_chunks(bytes)?;
|
||||
if metadata.srgb {
|
||||
return None;
|
||||
}
|
||||
// Recover the five-place file gamma before rounding the correction exponent.
|
||||
let gamma = (f64::from(metadata.gamma?) * 100_000.0).round() / 100_000.0;
|
||||
let ratio = gamma * 2.2;
|
||||
let exponent = (100_000.0 / ratio).round() / 100_000.0;
|
||||
if (ratio * 100_000.0).round() >= 95_000.0 && exponent >= 0.95 {
|
||||
return None;
|
||||
}
|
||||
let levels = f64::from(maximum);
|
||||
Some((0..=maximum).map(|v| ((f64::from(v) / levels).powf(exponent) * levels).round() as f32 / maximum as f32).collect())
|
||||
}
|
||||
|
||||
fn mapped_channel(table: &[f32], value: f32) -> f32 {
|
||||
let last = table.len().saturating_sub(1) as f32;
|
||||
table.get((value * last).round() as usize).copied().unwrap_or(value)
|
||||
}
|
||||
|
||||
/// Encode `image` as `ext` (see [`EXPORT_FORMATS`]). `srgb`: color values are written through the sRGB curve (base color); data maps (normal, roughness…) are written linear
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use file::write_atomic;
|
||||
pub use file::{output_name, safe_file_name};
|
||||
pub use format_error::FormatError;
|
||||
pub(crate) use guard::guard;
|
||||
pub use image::{decode, encode};
|
||||
pub use image::{decode, decode_with_color_space, encode};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, FormatError>;
|
||||
pub(crate) const MAX_RESOURCE: u64 = 256 << 20;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
pub use craft_sbs::SBS_EXT;
|
||||
pub(super) use craft_sbs::{MAX_XML_NODES, SELF_DEPENDENCY};
|
||||
|
||||
pub(super) const SELF_DEPENDENCY_UID: u64 = craft_sbs::FIRST_UID + 1;
|
||||
|
||||
pub(crate) const MAX_GRAPHS: usize = 4096;
|
||||
|
||||
pub(crate) const MAX_NODES: usize = 100_000;
|
||||
@@ -13,4 +11,5 @@ pub(super) const MAX_WARNINGS: usize = 600;
|
||||
|
||||
/// Most wires one SBS may carry, across all graphs (audit: MaterialCraft #2).
|
||||
pub(super) const MAX_WIRES: usize = 1_000_000;
|
||||
pub(super) const SELF_DEPENDENCY_UID: u64 = craft_sbs::FIRST_UID + 1;
|
||||
pub(super) const NODE_HALF_SIZE: [f32; 2] = [50.0, 40.0];
|
||||
@@ -32,7 +32,7 @@ pub(super) const FILTERS: &[FilterMap] = &[
|
||||
sbs: "distance",
|
||||
def: "distance",
|
||||
inputs: &[("mask", "mask"), ("source", "source")],
|
||||
params: &[("distance", "distance"), ("combinedistance", "combine")],
|
||||
params: &[("distance", "distance"), ("combinedistance", "combine"), ("distancemode", "metric"), ("colorswitch", "color_mode")],
|
||||
},
|
||||
FilterMap {
|
||||
sbs: "emboss",
|
||||
@@ -46,12 +46,17 @@ pub(super) const FILTERS: &[FilterMap] = &[
|
||||
inputs: &[("input1", "input"), ("input2", "gradient"), ("inputgradient", "gradient")],
|
||||
params: &[("coordinate", "position"), ("uvselector", "orientation")],
|
||||
},
|
||||
FilterMap { sbs: "gradient", def: "gradient_map", inputs: &[("input1", "input")], params: &[("colorswitch", "color_mode")] },
|
||||
FilterMap {
|
||||
sbs: "gradient",
|
||||
def: "gradient_map",
|
||||
inputs: &[("input1", "input")],
|
||||
params: &[("colorswitch", "color_mode"), ("interpmode", "interpolation")],
|
||||
},
|
||||
FilterMap {
|
||||
sbs: "grayscaleconversion",
|
||||
def: "grayscale_conversion",
|
||||
inputs: &[("input1", "input")],
|
||||
params: &[("alphamult", "flatten_alpha"), ("mattelevel", "matte")],
|
||||
params: &[("alphamult", "flatten_alpha"), ("mattelevel", "matte"), ("channelsweights", "weights")],
|
||||
},
|
||||
FilterMap { sbs: "hsl", def: "hsl", inputs: &[("input1", "input")], params: &[("hue", "hue"), ("saturation", "saturation"), ("luminosity", "lightness")] },
|
||||
FilterMap { sbs: "bitmap", def: "bitmap", inputs: &[], params: &[("colorswitch", "color_mode"), ("colorspace", "colour_space")] },
|
||||
@@ -59,7 +64,14 @@ pub(super) const FILTERS: &[FilterMap] = &[
|
||||
sbs: "levels",
|
||||
def: "levels",
|
||||
inputs: &[("input1", "input")],
|
||||
params: &[("levelinlow", "in_low"), ("levelinmid", "in_mid"), ("levelinhigh", "in_high"), ("leveloutlow", "out_low"), ("levelouthigh", "out_high")],
|
||||
params: &[
|
||||
("levelinlow", "in_low"),
|
||||
("levelinmid", "in_mid"),
|
||||
("levelinhigh", "in_high"),
|
||||
("leveloutlow", "out_low"),
|
||||
("levelouthigh", "out_high"),
|
||||
("clampinterm", "clamp_intermediate"),
|
||||
],
|
||||
},
|
||||
FilterMap {
|
||||
sbs: "normal",
|
||||
@@ -79,9 +91,21 @@ pub(super) const FILTERS: &[FilterMap] = &[
|
||||
sbs: "transformation",
|
||||
def: "transformation",
|
||||
inputs: &[("input1", "input")],
|
||||
params: &[("offset", "offset"), ("mattecolor", "matte"), ("matrix22", "matrix"), ("filtering", "filtering")],
|
||||
params: &[
|
||||
("offset", "offset"),
|
||||
("mattecolor", "matte"),
|
||||
("matrix22", "matrix"),
|
||||
("filtering", "filtering"),
|
||||
("mipmapmode", "mip_mode"),
|
||||
("manualmiplevel", "mip_level"),
|
||||
],
|
||||
},
|
||||
FilterMap {
|
||||
sbs: "warp",
|
||||
def: "warp",
|
||||
inputs: &[("input1", "input"), ("inputgradient", "gradient")],
|
||||
params: &[("intensity", "intensity"), ("warpfilter", "nearest")],
|
||||
},
|
||||
FilterMap { sbs: "warp", def: "warp", inputs: &[("input1", "input"), ("inputgradient", "gradient")], params: &[("intensity", "intensity")] },
|
||||
FilterMap { sbs: "passthrough", def: "dot", inputs: &[("input", "input"), ("input1", "input")], params: &[] },
|
||||
FilterMap {
|
||||
sbs: "text",
|
||||
@@ -110,12 +134,12 @@ pub(super) const FILTERS: &[FilterMap] = &[
|
||||
("opacitymult", "opacity"),
|
||||
("renderroi", "render_region"),
|
||||
("tilingroi", "tiling_region"),
|
||||
("culling", "cull_outside"),
|
||||
],
|
||||
},
|
||||
];
|
||||
pub(super) const BASE_PARAMS: &[&str] = &["outputsize", "format", "randomseed", "tiling", "pixelsize", "pixelratio", "quality"];
|
||||
pub(super) const HANDLED_PARAMS: &[(&str, &str)] =
|
||||
&[("bitmap", "bitmapresourcepath"), ("grayscaleconversion", "channelsweights"), ("transformation", "matrix22"), ("curve", "exposecurve")];
|
||||
pub(super) const HANDLED_PARAMS: &[(&str, &str)] = &[("bitmap", "bitmapresourcepath"), ("transformation", "matrix22"), ("curve", "exposecurve")];
|
||||
|
||||
pub(super) fn filter_by_sbs_name(name: &str) -> Option<&'static FilterMap> {
|
||||
FILTERS.iter().find(|f| f.sbs == name)
|
||||
|
||||
@@ -47,6 +47,37 @@ pub fn contains_file(path: &std::path::Path) -> bool {
|
||||
path.parent().and_then(|parent| parent.canonicalize().ok()).is_some_and(|parent| parent.starts_with(root))
|
||||
}
|
||||
|
||||
/// Return a portable package link for an unchanged bundled file beneath the canonical library root.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn bundled_package_uri(canonical_root: &std::path::Path, path: &std::path::Path) -> Option<String> {
|
||||
use std::io::Read;
|
||||
|
||||
if !path.is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let file = path.canonicalize().ok()?;
|
||||
let relative = file.strip_prefix(canonical_root).ok()?.to_str()?.replace('\\', "/");
|
||||
let uri = format!("sbs://{relative}");
|
||||
relative_path(&uri).ok()?;
|
||||
BUNDLED.binary_search(&uri.as_str()).ok()?;
|
||||
|
||||
// A locally edited package at a shipped path must keep pointing to those edits.
|
||||
let mut file = std::fs::File::open(file).ok()?;
|
||||
let expected = read_embedded(&relative).ok()?;
|
||||
if file.metadata().ok()?.len() != expected.len() as u64 {
|
||||
return None;
|
||||
}
|
||||
let mut buffer = [0; 8192];
|
||||
for chunk in expected.chunks(buffer.len()) {
|
||||
let actual = buffer.get_mut(..chunk.len())?;
|
||||
file.read_exact(actual).ok()?;
|
||||
if actual != chunk {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
(file.read(&mut buffer).ok()? == 0).then_some(uri)
|
||||
}
|
||||
|
||||
/// Read a validated library alias from the configured directory or the embedded fallback.
|
||||
pub fn read(uri: &str) -> Result<Vec<u8>, String> {
|
||||
let relative = relative_path(uri)?;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
use super::{
|
||||
LayoutFrame, LayoutItem,
|
||||
filter_map::FILTERS,
|
||||
xml::{child_element, child_value, children_named, parse_floats},
|
||||
xml::{child_element, child_value, children_named, parse_floats, string_parameter},
|
||||
};
|
||||
use crate::{FormatError, Result};
|
||||
use roxmltree::Node as XmlNode;
|
||||
@@ -189,16 +189,6 @@ fn function_item(node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<
|
||||
Some(LayoutItem::FunctionInstance { package, graph })
|
||||
}
|
||||
|
||||
/// Read a named static string parameter from an atomic filter.
|
||||
fn string_parameter<'a>(filter: XmlNode<'a, '_>, name: &str) -> Option<&'a str> {
|
||||
child_element(filter, "parameters")
|
||||
.into_iter()
|
||||
.flat_map(|parameters| children_named(parameters, "parameter"))
|
||||
.find(|parameter| child_value(*parameter, "name") == Some(name))
|
||||
.and_then(|parameter| child_element(parameter, "paramValue"))
|
||||
.and_then(|value| child_value(value, "constantValueString"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod tests {
|
||||
|
||||
@@ -44,7 +44,7 @@ pub use library_layout::read_layout;
|
||||
pub use read::{is_sbs, read_sbs};
|
||||
pub use sbs_document::SbsDocument;
|
||||
pub use sbs_read::SbsRead;
|
||||
pub use write::write_sbs;
|
||||
pub use write::{output_format_version, write_sbs};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -11,6 +11,11 @@ pub(super) fn text_param(node: &Node, key: &str, default: &str) -> String {
|
||||
pub(super) fn param_xml(name: &str, value: &Value) -> Option<String> {
|
||||
Some(format!("<parameter><name v=\"{}\"/><relativeTo v=\"0\"/><paramValue>{}</paramValue></parameter>", xml_escape(name), constant_xml(value)?))
|
||||
}
|
||||
|
||||
pub(super) fn resource_parameter_xml(parameter: &str, name: &str, self_uid: u64, package: &materialcraft_core::Package) -> String {
|
||||
let path = package.resource(name).map_or_else(|| format!("Resources/{name}"), |resource| resource.sbs_path());
|
||||
param_xml(parameter, &Value::Text(format!("pkg:///{path}?dependency={self_uid}"))).unwrap_or_default()
|
||||
}
|
||||
pub(super) fn special_filter_params_xml<'a>(
|
||||
filter: &str,
|
||||
value_of: &dyn Fn(&str) -> Option<&'a Value>,
|
||||
@@ -19,20 +24,11 @@ pub(super) fn special_filter_params_xml<'a>(
|
||||
) -> String {
|
||||
match filter {
|
||||
"bitmap" | "svg" => match value_of("resource") {
|
||||
Some(Value::Text(name)) if !name.is_empty() => param_xml(
|
||||
if filter == "svg" { "vectorresourcepath" } else { "bitmapresourcepath" },
|
||||
&Value::Text(format!(
|
||||
"pkg:///{}?dependency={self_uid}",
|
||||
package.resource(name).map_or_else(|| format!("Resources/{name}"), |resource| resource.sbs_path())
|
||||
)),
|
||||
)
|
||||
.unwrap_or_default(),
|
||||
Some(Value::Text(name)) if !name.is_empty() => {
|
||||
resource_parameter_xml(if filter == "svg" { "vectorresourcepath" } else { "bitmapresourcepath" }, name, self_uid, package)
|
||||
}
|
||||
_ => String::new(),
|
||||
},
|
||||
"grayscaleconversion" => {
|
||||
let weight = |channel: &str| value_of(channel).and_then(Value::as_f32).unwrap_or(0.0);
|
||||
param_xml("channelsweights", &Value::Float4([weight("red"), weight("green"), weight("blue"), weight("alpha")])).unwrap_or_default()
|
||||
}
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,16 @@ pub(super) fn read(node: &mut Node, implementation: XmlNode<'_, '_>) {
|
||||
match child_value(array, "name") {
|
||||
Some("curveluminance") => {
|
||||
let position = vector("position").unwrap_or([0.0; 2]);
|
||||
curve.points.push(CurvePoint { x: position[0], y: position[1], left: vector("left"), right: vector("right") });
|
||||
let flag = |name| parameters.get(name).and_then(Value::as_bool).unwrap_or(false);
|
||||
curve.points.push(CurvePoint {
|
||||
x: position[0],
|
||||
y: position[1],
|
||||
left: vector("left"),
|
||||
right: vector("right"),
|
||||
left_broken: flag("isLeftBroken"),
|
||||
right_broken: flag("isRightBroken"),
|
||||
locked: flag("isLocked"),
|
||||
});
|
||||
}
|
||||
Some("gradientrgba" | "gradientluminance") => {
|
||||
let position = parameters.get("position").and_then(Value::as_f32).unwrap_or(0.0);
|
||||
@@ -31,11 +40,9 @@ pub(super) fn read(node: &mut Node, implementation: XmlNode<'_, '_>) {
|
||||
Some(value) => value.as_vec4().unwrap_or([0.0; 4]),
|
||||
None => [0.0; 4],
|
||||
};
|
||||
let midpoint = parameters.get("midpoint").and_then(Value::as_f32).unwrap_or(0.5);
|
||||
|
||||
// Legacy gradient arrays use zero for their default linear segments
|
||||
// Treating it as a near-zero interpolation fraction clips successive ramps to white
|
||||
let midpoint = if midpoint == 0.0 { 0.5 } else { midpoint };
|
||||
// SBS stores a signed bias. The document uses a centered 0..1 control.
|
||||
let bias = parameters.get("midpoint").and_then(Value::as_f32).unwrap_or(0.0);
|
||||
let midpoint = 0.5 + 0.5 * bias.clamp(-1.0, 1.0);
|
||||
gradient.keys.push(GradientKey { pos: position, color, midpoint });
|
||||
}
|
||||
_ => {}
|
||||
@@ -53,16 +60,10 @@ pub(super) fn read(node: &mut Node, implementation: XmlNode<'_, '_>) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write(value: &Value, color_mode: bool, writer: &mut SbsWriter) -> String {
|
||||
pub(super) fn write(value: &Value, writer: &mut SbsWriter) -> String {
|
||||
let name = match value {
|
||||
Value::Curve(_) => "curveluminance",
|
||||
Value::Gradient(_) => {
|
||||
if color_mode {
|
||||
"gradientrgba"
|
||||
} else {
|
||||
"gradientluminance"
|
||||
}
|
||||
}
|
||||
Value::Gradient(_) => "gradientrgba",
|
||||
_ => return String::new(),
|
||||
};
|
||||
|
||||
@@ -79,22 +80,21 @@ pub(super) fn write(value: &Value, color_mode: bool, writer: &mut SbsWriter) ->
|
||||
Value::Curve(curve) => {
|
||||
for (index, point) in curve.points.iter().enumerate() {
|
||||
let position = [point.x, point.y];
|
||||
let left = index.checked_sub(1).and_then(|index| curve.segment(index)).map_or(position, |segment| segment[2]);
|
||||
let right = curve.segment(index).map_or(position, |segment| segment[1]);
|
||||
let left = point.left.or_else(|| index.checked_sub(1).and_then(|index| curve.segment(index)).map(|s| s[2])).unwrap_or(position);
|
||||
let right = point.right.or_else(|| curve.segment(index).map(|s| s[1])).unwrap_or(position);
|
||||
cell(vec![
|
||||
("position", Value::Float2(position)),
|
||||
("left", Value::Float2(left)),
|
||||
("right", Value::Float2(right)),
|
||||
("isLeftBroken", Value::Bool(true)),
|
||||
("isRightBroken", Value::Bool(true)),
|
||||
("isLocked", Value::Bool(false)),
|
||||
("isLeftBroken", Value::Bool(point.left_broken)),
|
||||
("isRightBroken", Value::Bool(point.right_broken)),
|
||||
("isLocked", Value::Bool(point.locked)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
Value::Gradient(gradient) => {
|
||||
for key in &gradient.keys {
|
||||
let color = if color_mode { Value::Color(key.color) } else { Value::Float(craft_texture::luminance(key.color)) };
|
||||
cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(key.midpoint)), ("value", color)]);
|
||||
cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(2.0 * key.midpoint - 1.0)), ("value", Value::Float4(key.color))]);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -40,7 +40,8 @@ pub(super) fn read(element: Node<'_, '_>, input: &mut ExposedParameter) {
|
||||
}
|
||||
if color && matches!(input.default, Value::Float4(_)) {
|
||||
// Color defaults use the same displayed-to-linear conversion as node colors
|
||||
if let Some(value) = child_element(element, "defaultValue")
|
||||
if let Some(value) = child_element(element, "materialcraftDefault")
|
||||
.or_else(|| child_element(element, "defaultValue"))
|
||||
.and_then(super::sbs_value::sbs_constant)
|
||||
.and_then(|value| super::sbs_value::to_param_value(&Value::Color([0.0; 4]), &value, 0))
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use materialcraft_core::{PatternGraph, PatternNode, PatternNodeKind, Value};
|
||||
use materialcraft_core::{FunctionGraph, PatternGraph, PatternNode, PatternNodeKind, Value};
|
||||
use roxmltree::Node as XmlNode;
|
||||
use std::collections::BTreeMap;
|
||||
use std::fmt::Write;
|
||||
@@ -87,6 +87,13 @@ pub(super) fn write(graph: &PatternGraph, writer: &mut SbsWriter) -> Result<Stri
|
||||
let definition = materialcraft_nodes::pattern::definition(node.kind).ok_or("missing pattern definition")?;
|
||||
let mut parameters: BTreeMap<_, _> = definition.params.iter().map(|parameter| (parameter.id.to_string(), parameter.default.clone())).collect();
|
||||
parameters.extend(node.parameters.clone());
|
||||
if node.kind == PatternNodeKind::Quadrant
|
||||
&& let Some(luminosity @ Value::Float(_)) = parameters.get_mut("opacity")
|
||||
{
|
||||
// The literal swatch has four components. A scalar expression preserves the
|
||||
// luminosity in both grayscale and color patterns when the package is reopened.
|
||||
*luminosity = Value::Function(Box::new(FunctionGraph::constant(luminosity.clone())));
|
||||
}
|
||||
for (name, value) in ¶meters {
|
||||
if let Value::Function(function) = value {
|
||||
let function = function_graph::write(function, writer)?;
|
||||
@@ -122,3 +129,32 @@ pub(super) fn write(graph: &PatternGraph, writer: &mut SbsWriter) -> Result<Stri
|
||||
output.push_str("</paramsGraph></paramsGraphs>");
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn quadrant_scalar_luminosity_uses_a_scalar_function_on_save() {
|
||||
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
|
||||
let original_swatch = Value::Float4([0.25, 0.5, 0.75, 0.875]);
|
||||
let child = graph.add(PatternNodeKind::Quadrant).unwrap();
|
||||
graph.nodes[0].children[1] = Some(child);
|
||||
graph.nodes[0].parameters.insert("opacity".into(), Value::Float(-0.3125));
|
||||
graph.nodes[1].parameters.insert("opacity".into(), original_swatch.clone());
|
||||
let mut writer = SbsWriter { last_uid: 10, external_packages: BTreeMap::new() };
|
||||
let xml = write(&graph, &mut writer).unwrap();
|
||||
let document = roxmltree::Document::parse(&xml).unwrap();
|
||||
let stored = read(document.root_element().first_element_child().unwrap()).unwrap();
|
||||
|
||||
// A literal swatch accepts four components. A one-component function keeps scalar
|
||||
// luminosity semantics in both color modes, including values outside the unit range.
|
||||
let Value::Function(function) = &stored.nodes[0].parameters["opacity"] else { panic!("expected a scalar function") };
|
||||
let scalar = function.node(function.output.unwrap()).unwrap();
|
||||
assert_eq!(scalar.op, "const_float1");
|
||||
assert_eq!(scalar.type_code, 256);
|
||||
assert_eq!(scalar.value, Some(Value::Float(-0.3125)));
|
||||
assert_eq!(function.nodes.len(), 1);
|
||||
assert_eq!(stored.nodes[1].parameters["opacity"], original_swatch);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ const LINEAR_PREFIX: &str = "materialcraft.previewLinear.";
|
||||
|
||||
pub(super) fn write(out: &mut String, graph: &Graph) {
|
||||
for (identifier, resource) in &graph.input_images {
|
||||
if graph.input_images_from_file.contains(identifier) {
|
||||
continue;
|
||||
}
|
||||
let _ = write!(out, "<option><name v=\"{IMAGE_PREFIX}{}\"/><value v=\"{}\"/></option>", xml_escape(identifier), xml_escape(resource));
|
||||
if graph.input_images_linear.contains(identifier) {
|
||||
let _ = write!(out, "<option><name v=\"{LINEAR_PREFIX}{}\"/><value v=\"1\"/></option>", xml_escape(identifier));
|
||||
@@ -15,6 +18,21 @@ pub(super) fn write(out: &mut String, graph: &Graph) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn read_resource(graph: &mut Graph, identifier: &str, resource: Option<String>) {
|
||||
// A matching preview option retains the interpretation explicitly chosen for this resource.
|
||||
if resource.is_some() && graph.input_images.get(identifier) == resource.as_ref() {
|
||||
return;
|
||||
}
|
||||
graph.input_images_linear.remove(identifier);
|
||||
if let Some(name) = resource {
|
||||
graph.input_images.insert(identifier.to_string(), name);
|
||||
graph.input_images_from_file.insert(identifier.to_string());
|
||||
} else {
|
||||
graph.input_images.remove(identifier);
|
||||
graph.input_images_from_file.remove(identifier);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn read(option: XmlNode, graph: &mut Graph) {
|
||||
let Some(name) = child_value(option, "name") else { return };
|
||||
let Some(value) = child_value(option, "value") else { return };
|
||||
@@ -27,3 +45,79 @@ pub(super) fn read(option: XmlNode, graph: &mut Graph) {
|
||||
graph.input_images_linear.insert(identifier.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::sbs::{read_sbs, write_sbs};
|
||||
use materialcraft_core::{Graph, Package, Resource, ResourceBytes, Value};
|
||||
|
||||
#[test]
|
||||
fn image_bridges_write_the_bound_package_resource() {
|
||||
let mut package = Package::new("Input images");
|
||||
let mut resource = Resource::new("grain", "grain.png", ResourceBytes::default());
|
||||
resource.folder = "Inputs/Maps".into();
|
||||
resource.source = "grain.png".into();
|
||||
package.resources.push(resource);
|
||||
let mut graph = Graph::new("Paint");
|
||||
for (definition, identifier) in [("input_grayscale", "height"), ("input_color", "paint"), ("input_color", "open")] {
|
||||
let id = graph.add_node(definition, [0.0; 2]);
|
||||
graph.node_mut(id).unwrap().params.insert("identifier".into(), Value::Text(identifier.into()));
|
||||
}
|
||||
for identifier in ["height", "paint"] {
|
||||
graph.input_images.insert(identifier.into(), "grain".into());
|
||||
}
|
||||
package.graphs.push(graph);
|
||||
|
||||
let bytes = write_sbs(&package).unwrap();
|
||||
let doc = roxmltree::Document::parse(std::str::from_utf8(&bytes).unwrap()).unwrap();
|
||||
let own = doc.descendants().find(|node| node.has_tag_name("dependency") && super::child_value(*node, "filename") == Some("?himself")).unwrap();
|
||||
let url = format!("pkg:///Inputs/Maps/grain?dependency={}", super::child_value(own, "uid").unwrap());
|
||||
let bindings: Vec<_> = doc
|
||||
.descendants()
|
||||
.filter(|node| node.has_tag_name("compInputBridge"))
|
||||
.map(|bridge| {
|
||||
bridge
|
||||
.descendants()
|
||||
.find(|p| p.has_tag_name("parameter") && super::child_value(*p, "name") == Some("bitmapresourcepath"))
|
||||
.and_then(|p| p.descendants().find(|v| v.has_tag_name("constantValueString")))
|
||||
.and_then(|v| v.attribute("v"))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(bindings, [Some(url.as_str()), Some(url.as_str()), None]);
|
||||
let reopened = read_sbs(&bytes, "input.sbs", &|_| None).unwrap().pkg;
|
||||
assert_eq!(reopened.graphs[0].input_images, package.graphs[0].input_images);
|
||||
assert!(reopened.graphs[0].input_images_from_file.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_bridge_binding_takes_precedence_over_a_legacy_preview_name() {
|
||||
let xml = br#"<package><dependencies><dependency><filename v="?himself"/><uid v="1"/></dependency></dependencies>
|
||||
<content><group><identifier v="Masks"/><content><resource><identifier v="grain"/><type v="bitmap"/>
|
||||
<format v="png"/><filepath v="grain.png"/></resource></content></group>
|
||||
<graph><identifier v="Paint"/><paraminputs><paraminput><identifier v="height"/><uid v="12"/><type v="2"/></paraminput></paraminputs>
|
||||
<options><option><name v="materialcraft.previewImage.height"/><value v="old"/></option></options>
|
||||
<compNodes><compNode><uid v="13"/><compImplementation><compInputBridge><entry v="12"/><parameters>
|
||||
<parameter><name v="bitmapresourcepath"/><relativeTo v="0"/><paramValue><constantValueString v="pkg:///Masks/grain?dependency=1"/>
|
||||
</paramValue></parameter></parameters></compInputBridge></compImplementation></compNode></compNodes></graph></content></package>"#;
|
||||
let package = read_sbs(xml, "paint.sbs", &|_| None).unwrap().pkg;
|
||||
assert_eq!(package.graphs[0].input_images.get("height").map(String::as_str), Some("grain"));
|
||||
assert!(package.graphs[0].input_images_from_file.contains("height"));
|
||||
let reopened = read_sbs(&write_sbs(&package).unwrap(), "again.sbs", &|_| None).unwrap().pkg;
|
||||
assert_eq!(package.graphs[0].input_images_from_file, reopened.graphs[0].input_images_from_file);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_the_bridge_resource_clears_its_preview_interpretation() {
|
||||
let mut graph = Graph::new("Paint");
|
||||
graph.input_images.insert("height".into(), "grain".into());
|
||||
graph.input_images_linear.insert("height".into());
|
||||
super::read_resource(&mut graph, "height", Some("grain".into()));
|
||||
assert!(graph.input_images_linear.contains("height"));
|
||||
super::read_resource(&mut graph, "height", Some("different".into()));
|
||||
assert!(graph.input_images_linear.is_empty());
|
||||
assert!(graph.input_images_from_file.contains("height"));
|
||||
super::read_resource(&mut graph, "height", None);
|
||||
assert!(graph.input_images.is_empty());
|
||||
assert!(graph.input_images_from_file.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use super::read_node::ReadNode;
|
||||
use super::sbs_value::{SbsValue, exposed_default, sbs_constant, to_natural_value, to_param_value};
|
||||
use super::type_code;
|
||||
use super::warnings::Warnings;
|
||||
use super::xml::{child_element, child_value, children_named, parse_floats};
|
||||
use super::xml::{child_element, child_value, children_named, parse_floats, string_parameter};
|
||||
use materialcraft_core::{
|
||||
BaseParameter, ComponentUsage, Connection, ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, OutputFormat, Package,
|
||||
ParameterInheritance, Resource, ResourceBytes, Value,
|
||||
@@ -207,9 +207,19 @@ impl<'text> SbsReader<'text, '_> {
|
||||
|
||||
pub(super) fn read_graph(&mut self, element: XmlNode<'_, 'text>, name: String) -> Graph {
|
||||
let mut graph = Graph::new(&name);
|
||||
let base = read_base_params(child_element(element, "baseParameters"), self.warnings);
|
||||
let mut base = read_base_params(child_element(element, "baseParameters"), self.warnings);
|
||||
use materialcraft_core::{GraphSizeOffset, SizeMode};
|
||||
graph.output_size_function = base.functions.remove(&BaseParameter::OutputSize);
|
||||
match base.size_mode {
|
||||
SizeMode::Absolute => graph.absolute_output_size = Some(base.size),
|
||||
SizeMode::RelativeToParent => graph.relative_output_size = Some(GraphSizeOffset::Parent(base.size)),
|
||||
SizeMode::RelativeToInput if base.size != [0; 2] => graph.relative_output_size = Some(GraphSizeOffset::Input(base.size)),
|
||||
SizeMode::RelativeToInput => {}
|
||||
}
|
||||
graph.format = if BaseParameter::Format.inheritance(&base) == ParameterInheritance::Absolute { base.format } else { OutputFormat::Inherit };
|
||||
graph.seed = base.seed;
|
||||
graph.seed_mode = base.seed_mode;
|
||||
graph.seed_function = base.functions.remove(&BaseParameter::RandomSeed);
|
||||
graph.pixel_ratio = base.pixel_ratio;
|
||||
graph.pixel_ratio_mode = base.pixel_ratio_mode;
|
||||
graph.tiling = base.tiling;
|
||||
@@ -325,8 +335,12 @@ impl<'text> SbsReader<'text, '_> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let default = exposed_default(code, child_element(input, "defaultValue").and_then(sbs_constant).as_ref());
|
||||
if child_value(input, "isConnectable") == Some("1") {
|
||||
let default = exposed_default(
|
||||
code,
|
||||
child_element(input, "materialcraftDefault").or_else(|| child_element(input, "defaultValue")).and_then(sbs_constant).as_ref(),
|
||||
);
|
||||
let connectable = child_value(input, "isConnectable") == Some("1");
|
||||
if connectable && !element.has_tag_name("function") {
|
||||
image_inputs.insert(
|
||||
child_value(input, "uid").unwrap_or("").to_string(),
|
||||
InputBridge { identifier: id, type_code: code as u32, usage: component_usage::read(input), default },
|
||||
@@ -353,6 +367,7 @@ impl<'text> SbsReader<'text, '_> {
|
||||
label,
|
||||
group,
|
||||
default,
|
||||
connectable,
|
||||
min,
|
||||
max,
|
||||
options: Vec::new(),
|
||||
@@ -470,6 +485,7 @@ impl<'text> SbsReader<'text, '_> {
|
||||
"compInputBridge" => {
|
||||
let entry = child_value(implementation, "entry").unwrap_or("");
|
||||
let input = image_inputs.get(entry);
|
||||
let identifier = input.map_or("input", |input| input.identifier.as_str());
|
||||
let code = input.map_or(1, |input| input.type_code);
|
||||
let definition = match code {
|
||||
1 => "input_color",
|
||||
@@ -477,9 +493,14 @@ impl<'text> SbsReader<'text, '_> {
|
||||
_ => "input_value",
|
||||
};
|
||||
|
||||
if matches!(code, 1 | 2)
|
||||
&& let Some(url) = string_parameter(implementation, "bitmapresourcepath")
|
||||
{
|
||||
let resource = if url.is_empty() { None } else { self.resource_binding(url, &graph.name) };
|
||||
super::preview_binding::read_resource(graph, identifier, resource);
|
||||
}
|
||||
let (id, index, node) = push_node(graph, definition, pos);
|
||||
if let Some(node) = node {
|
||||
let identifier = input.map_or("input", |input| input.identifier.as_str());
|
||||
node.params.insert("identifier".into(), Value::Text(identifier.to_string()));
|
||||
node.params.insert("usage".into(), Value::Enum(input.map_or(ComponentUsage::ANY_INDEX, |input| input.usage)));
|
||||
if let Some(input) = input {
|
||||
@@ -721,6 +742,16 @@ impl<'text> SbsReader<'text, '_> {
|
||||
}
|
||||
|
||||
if let Some(&(_, mc_name)) = filter.params.iter().find(|(sbs, _)| *sbs == param_name) {
|
||||
if filter.sbs == "grayscaleconversion" && mc_name == "weights" {
|
||||
if let Some(weights) = value {
|
||||
for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() {
|
||||
node.params.insert(channel.into(), Value::Float(weights.float(i)));
|
||||
}
|
||||
} else {
|
||||
self.set_param(node, mc_name, &Value::Float4([0.0; 4]), 0, *param, graph_name);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(param_def) = def.param(mc_name) else { continue };
|
||||
|
||||
self.set_param(node, mc_name, ¶m_def.default, param_def.options.len(), *param, graph_name);
|
||||
@@ -733,11 +764,6 @@ impl<'text> SbsReader<'text, '_> {
|
||||
node.params.insert("resource".into(), Value::Text(name));
|
||||
}
|
||||
}
|
||||
("grayscaleconversion", "channelsweights", Some(weights)) => {
|
||||
for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() {
|
||||
node.params.insert(channel.into(), Value::Float(weights.float(i)));
|
||||
}
|
||||
}
|
||||
_ if HANDLED_PARAMS.contains(&(filter.sbs, param_name)) => {}
|
||||
_ => self.warnings.add(format!("`{}`: SBS parameter `{param_name}` is not supported yet and was ignored", filter.def)),
|
||||
}
|
||||
|
||||
@@ -85,7 +85,16 @@ pub(super) fn exposed_type_code(value: &Value) -> i64 {
|
||||
materialcraft_core::ValueType::of(value).map_or(type_code::FLOAT1, |kind| i64::from(kind as u32))
|
||||
}
|
||||
|
||||
pub(super) fn input_default_xml(value: &Value) -> Option<String> {
|
||||
// Graph input declarations use the one-lane tag to expose a scalar integer default.
|
||||
constant_with_integer_tag(value, "constantValueInt1")
|
||||
}
|
||||
|
||||
pub(super) fn constant_xml(value: &Value) -> Option<String> {
|
||||
constant_with_integer_tag(value, "constantValueInt32")
|
||||
}
|
||||
|
||||
fn constant_with_integer_tag(value: &Value, integer_tag: &str) -> Option<String> {
|
||||
let join = |xs: &[f32]| xs.iter().map(|x| format_float(*x)).collect::<Vec<_>>().join(" ");
|
||||
let (tag, text) = match value {
|
||||
Value::Float(x) => ("constantValueFloat1", format_float(*x)),
|
||||
@@ -93,11 +102,11 @@ pub(super) fn constant_xml(value: &Value) -> Option<String> {
|
||||
Value::Float3(x) => ("constantValueFloat3", join(x)),
|
||||
Value::Float4(x) => ("constantValueFloat4", join(x)),
|
||||
Value::Color(c) => ("constantValueFloat4", join(c)),
|
||||
Value::Int(i) => ("constantValueInt32", i.to_string()),
|
||||
Value::Int(i) => (integer_tag, i.to_string()),
|
||||
Value::Int2(i) => ("constantValueInt2", format!("{} {}", i[0], i[1])),
|
||||
Value::Int3(i) => ("constantValueInt3", format!("{} {} {}", i[0], i[1], i[2])),
|
||||
Value::Int4(i) => ("constantValueInt4", format!("{} {} {} {}", i[0], i[1], i[2], i[3])),
|
||||
Value::Enum(e) => ("constantValueInt32", e.to_string()),
|
||||
Value::Enum(e) => (integer_tag, e.to_string()),
|
||||
Value::Bool(b) => ("constantValueBool", u8::from(*b).to_string()),
|
||||
Value::Text(s) => ("constantValueString", s.clone()),
|
||||
Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => return None,
|
||||
|
||||
@@ -5,13 +5,15 @@ use super::constant::NODE_HALF_SIZE;
|
||||
use super::filter_map::filter_by_def;
|
||||
use super::function_graph;
|
||||
use super::node_identifiers::NodeIdentifiers;
|
||||
use super::node_parameter::{param_xml, special_filter_params_xml, text_param};
|
||||
use super::node_parameter::{param_xml, resource_parameter_xml, special_filter_params_xml, text_param};
|
||||
use super::output::output_type;
|
||||
use super::sbs_value::{constant_xml, exposed_type_code};
|
||||
use super::sbs_value::{constant_xml, exposed_type_code, input_default_xml};
|
||||
use super::type_code;
|
||||
use super::xml::{format_float, is_parameters_element, xml_escape};
|
||||
use crate::{FormatError, Result};
|
||||
use materialcraft_core::{ComponentUsage, Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports};
|
||||
use materialcraft_core::{
|
||||
BaseParameter, ComponentUsage, Connection, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, MISSING_NODE, Node, NodeId, Package, Value, missing_ports,
|
||||
};
|
||||
use materialcraft_nodes::find;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::fmt::Write as _;
|
||||
@@ -145,13 +147,21 @@ impl SbsWriter {
|
||||
|
||||
out.push_str("<compImplementation>");
|
||||
let ids = NodeIdentifiers { input_entry: input_entries.get(&node.id).copied(), graph_output: output_uids.get(&node.id).copied(), self_uid };
|
||||
self.write_implementation(out, node, outputs, ids, pkg)?;
|
||||
self.write_implementation(out, node, outputs, ids, graph, pkg)?;
|
||||
out.push_str("</compImplementation></compNode>");
|
||||
}
|
||||
|
||||
out.push_str("</compNodes><baseParameters>");
|
||||
out.push_str(¶m_xml("randomseed", &Value::Int(graph.seed)).unwrap_or_default());
|
||||
let (size_mode, size) = graph.output_size_setting();
|
||||
let base = materialcraft_core::BaseParameters {
|
||||
size_mode,
|
||||
size,
|
||||
seed: graph.seed,
|
||||
seed_mode: graph.seed_mode,
|
||||
functions: [(BaseParameter::OutputSize, &graph.output_size_function), (BaseParameter::RandomSeed, &graph.seed_function)]
|
||||
.into_iter()
|
||||
.filter_map(|(parameter, function)| function.clone().map(|function| (parameter, function)))
|
||||
.collect(),
|
||||
format: graph.format,
|
||||
format_mode: materialcraft_core::ParameterInheritance::Absolute,
|
||||
pixel_ratio: graph.pixel_ratio,
|
||||
@@ -195,7 +205,7 @@ impl SbsWriter {
|
||||
} else {
|
||||
value
|
||||
};
|
||||
let default = constant_xml(value).unwrap_or_default();
|
||||
let default = input_default_xml(value).unwrap_or_default();
|
||||
let code = match node.def.as_str() {
|
||||
"input_value" => exposed_type_code(value),
|
||||
"input_grayscale" => type_code::GRAY_IMAGE,
|
||||
@@ -215,12 +225,14 @@ impl SbsWriter {
|
||||
for exposed in &graph.exposed {
|
||||
let uid = self.next_uid();
|
||||
exposed_uids.insert(exposed.id.clone(), uid);
|
||||
let default = constant_xml(&exposed.default).unwrap_or_else(|| "<constantValueFloat1 v=\"0\"/>".into());
|
||||
let default =
|
||||
input_default_xml(graph.inputs.get(&exposed.id).unwrap_or(&exposed.default)).unwrap_or_else(|| "<constantValueFloat1 v=\"0\"/>".into());
|
||||
let group = if exposed.group.is_empty() { String::new() } else { format!("<group v=\"{}\"/>", xml_escape(&exposed.group)) };
|
||||
let connection = if graph.function.is_some() && exposed.connectable { "<isConnectable v=\"1\"/>" } else { "" };
|
||||
|
||||
let _ = write!(
|
||||
out,
|
||||
"<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/><attributes><label v=\"{}\"/><description v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue>",
|
||||
"<paraminput><identifier v=\"{}\"/><uid v=\"{}\"/>{connection}<attributes><label v=\"{}\"/><description v=\"{}\"/></attributes><type v=\"{}\"/><defaultValue>{default}</defaultValue>",
|
||||
xml_escape(&exposed.id),
|
||||
uid,
|
||||
xml_escape(&exposed.label),
|
||||
@@ -229,6 +241,11 @@ impl SbsWriter {
|
||||
);
|
||||
if let Some(current) = graph.inputs.get(&exposed.id).and_then(constant_xml) {
|
||||
let _ = write!(out, "<materialcraftValue>{current}</materialcraftValue>");
|
||||
// SBS consumers use the current value as the declared default. Retain the
|
||||
// authored reset value separately for our project and portable-material round trip.
|
||||
if let Some(authored) = input_default_xml(&exposed.default) {
|
||||
let _ = write!(out, "<materialcraftDefault>{authored}</materialcraftDefault>");
|
||||
}
|
||||
}
|
||||
super::parameter_widget::write(out, exposed);
|
||||
let _ = write!(out, "{group}</paraminput>");
|
||||
@@ -271,6 +288,7 @@ impl SbsWriter {
|
||||
node: &Node,
|
||||
outputs: &[(String, u32, u64)],
|
||||
ids: NodeIdentifiers,
|
||||
graph: &Graph,
|
||||
package: &Package,
|
||||
) -> Result<()> {
|
||||
// The reader assigns a native default when a processor omits format
|
||||
@@ -281,7 +299,14 @@ impl SbsWriter {
|
||||
let _ = write!(out, "<compOutputBridge><output v=\"{}\"/></compOutputBridge>", ids.graph_output.unwrap_or(0));
|
||||
}
|
||||
"input_color" | "input_grayscale" | "input_value" => {
|
||||
let _ = write!(out, "<compInputBridge><entry v=\"{}\"/><parameters>{base}</parameters></compInputBridge>", ids.input_entry.unwrap_or(0));
|
||||
let _ = write!(out, "<compInputBridge><entry v=\"{}\"/><parameters>{base}", ids.input_entry.unwrap_or(0));
|
||||
if node.def != "input_value"
|
||||
&& let Some(name) = graph.input_images.get(&text_param(node, "identifier", "input"))
|
||||
&& !name.is_empty()
|
||||
{
|
||||
out.push_str(&resource_parameter_xml("bitmapresourcepath", name, ids.self_uid, package));
|
||||
}
|
||||
out.push_str("</parameters></compInputBridge>");
|
||||
}
|
||||
"graph_instance" => {
|
||||
let sub_graph = node.instance.as_ref().map(|instance| instance.graph.clone()).unwrap_or_else(|| text_param(node, "graph", ""));
|
||||
@@ -339,7 +364,10 @@ impl SbsWriter {
|
||||
def => match (filter_by_def(def), find(def)) {
|
||||
(Some(filter), Some(catalog_def)) => {
|
||||
let _ = write!(out, "<compFilter><filter v=\"{}\"/><parameters>{base}", filter.sbs);
|
||||
let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default));
|
||||
let stored = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default));
|
||||
let weights = (filter.sbs == "grayscaleconversion")
|
||||
.then(|| Value::Float4(["red", "green", "blue", "alpha"].map(|id| stored(id).and_then(Value::as_f32).unwrap_or(0.0))));
|
||||
let value_of = |id: &str| stored(id).or_else(|| if id == "weights" { weights.as_ref() } else { None });
|
||||
for (sbs_name, mc_name) in filter.params {
|
||||
let Some(value) = value_of(mc_name) else { continue };
|
||||
|
||||
@@ -379,7 +407,7 @@ impl SbsWriter {
|
||||
out.push_str("</parameters>");
|
||||
for parameter in ["curve", "gradient"] {
|
||||
if let Some(value) = value_of(parameter) {
|
||||
out.push_str(&super::parameter_array::write(value, value_of("color_mode").and_then(Value::as_bool).unwrap_or(true), self));
|
||||
out.push_str(&super::parameter_array::write(value, self));
|
||||
}
|
||||
}
|
||||
if let Some(Value::PatternGraph(graph)) = value_of("pattern") {
|
||||
|
||||
Loaded 100 of 258 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user