From 85e0bf924742372427b0e071e75529e84de9fda4 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 04:07:54 -0500 Subject: [PATCH 1/3] Add parameter-owned function graphs --- Cargo.lock | 1 + assets/sbs/functions.sbs | 2 +- crates/core/src/base_parameter.rs | 140 +++++++ crates/core/src/base_parameters.rs | 16 +- crates/core/src/exposed_parameter.rs | 23 +- crates/core/src/function_graph.rs | 32 ++ crates/core/src/graph.rs | 18 +- crates/core/src/lib.rs | 4 + crates/core/src/parameter_editor.rs | 43 ++ crates/engine/src/commands.rs | 2 + crates/engine/src/exposed_input_commands.rs | 180 ++++++++ crates/engine/src/function_graph_target.rs | 16 +- crates/engine/src/function_inspection.rs | 3 + crates/engine/src/function_output.rs | 10 +- crates/engine/src/function_variables.rs | 2 +- crates/engine/src/graph_cmds.rs | 94 +---- crates/engine/src/inspect.rs | 151 +++---- crates/engine/src/lib.rs | 4 + crates/engine/src/linked_packages.rs | 1 + crates/engine/src/node_cmds.rs | 177 +++----- .../engine/src/parameter_function_commands.rs | 163 ++++++++ crates/engine/src/parameter_target.rs | 136 ++++++ crates/engine/tests/it/exposed_inputs.rs | 112 ++++- crates/engine/tests/it/function_instances.rs | 4 + crates/engine/tests/it/main.rs | 1 + crates/engine/tests/it/parameter_functions.rs | 391 ++++++++++++++++++ crates/engine/tests/session.rs | 37 +- crates/eval/Cargo.toml | 1 + crates/eval/src/graph_execution.rs | 2 +- crates/eval/src/graph_instance.rs | 1 + crates/eval/src/lib.rs | 2 + crates/eval/src/node_execution.rs | 136 +++--- crates/eval/src/node_result.rs | 4 + crates/eval/src/node_size.rs | 42 +- crates/eval/src/options.rs | 2 + crates/eval/src/parameter.rs | 77 ++-- crates/eval/src/parameter_function.rs | 25 ++ crates/eval/src/prepared_graph.rs | 44 +- crates/eval/src/resolved_base_parameters.rs | 97 ++++- crates/eval/src/tests.rs | 37 ++ .../standard_function_library/convert.rs | 3 + crates/formats/src/material/archive.rs | 4 + crates/formats/src/sbs/base_parameters.rs | 123 ++---- crates/formats/src/sbs/function_graph.rs | 19 +- crates/formats/src/sbs/mod.rs | 1 + crates/formats/src/sbs/parameter_widget.rs | 94 +++++ crates/formats/src/sbs/sbs_reader.rs | 24 +- crates/formats/src/sbs/sbs_writer.rs | 13 +- crates/formats/tests/function_library.rs | 9 +- crates/nodes/src/atomic/blend.rs | 1 + crates/nodes/src/lib.rs | 2 + crates/nodes/src/node_definition.rs | 2 + crates/nodes/src/node_definition_builder.rs | 6 + crates/nodes/src/parameter_descriptor.rs | 93 +++++ crates/ui-egui/src/cook.rs | 14 +- .../ui-egui/src/function/function_editor.rs | 1 + .../ui-egui/src/function/function_target.rs | 2 + crates/ui-egui/src/graph/canvas.rs | 2 +- crates/ui-egui/src/graph/review_tests.rs | 2 +- .../ui-egui/src/graph/subgraph_navigation.rs | 9 +- crates/ui-egui/src/material_craft_app.rs | 14 + .../src/property/expose_parameter_dialog.rs | 216 ++++++++++ crates/ui-egui/src/property/input.rs | 172 ++++++-- crates/ui-egui/src/property/mod.rs | 17 +- crates/ui-egui/src/property/node.rs | 168 ++++---- crates/ui-egui/src/property/parameter.rs | 192 +++------ .../ui-egui/src/property/parameter_control.rs | 158 +++++++ crates/ui-egui/src/shell/modality.rs | 3 +- crates/ui-egui/src/view2d.rs | 9 +- crates/ui-egui/src/widgets.rs | 41 +- crates/ui-egui/src/windows.rs | 1 + crates/ui-egui/tests/snapshot.rs | 3 + .../tests/snapshot/function_library.rs | 3 +- crates/ui-egui/tests/snapshot/library.rs | 2 +- .../tests/snapshot/parameter_functions.rs | 158 +++++++ docs/architecture.md | 13 +- docs/control-protocol.md | 27 +- docs/gaps.md | 2 +- docs/helpful-pr-review-guidelines.md | 2 + docs/target-app-parity.md | 4 +- 80 files changed, 3035 insertions(+), 827 deletions(-) create mode 100644 crates/core/src/base_parameter.rs create mode 100644 crates/core/src/parameter_editor.rs create mode 100644 crates/engine/src/exposed_input_commands.rs create mode 100644 crates/engine/src/parameter_function_commands.rs create mode 100644 crates/engine/src/parameter_target.rs create mode 100644 crates/engine/tests/it/parameter_functions.rs create mode 100644 crates/eval/src/parameter_function.rs create mode 100644 crates/formats/src/sbs/parameter_widget.rs create mode 100644 crates/nodes/src/parameter_descriptor.rs create mode 100644 crates/ui-egui/src/property/expose_parameter_dialog.rs create mode 100644 crates/ui-egui/src/property/parameter_control.rs create mode 100644 crates/ui-egui/tests/snapshot/parameter_functions.rs diff --git a/Cargo.lock b/Cargo.lock index 79cc47d..bb61929 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2681,6 +2681,7 @@ dependencies = [ "materialcraft-core", "materialcraft-image", "materialcraft-nodes", + "serde", "serde_json", ] diff --git a/assets/sbs/functions.sbs b/assets/sbs/functions.sbs index c9713d3..39203b9 100644 --- a/assets/sbs/functions.sbs +++ b/assets/sbs/functions.sbs @@ -1 +1 @@ - + diff --git a/crates/core/src/base_parameter.rs b/crates/core/src/base_parameter.rs new file mode 100644 index 0000000..cbef563 --- /dev/null +++ b/crates/core/src/base_parameter.rs @@ -0,0 +1,140 @@ +use serde::{Deserialize, Serialize}; + +use crate::{BaseParameters, OutputFormat, ParameterInheritance, SizeMode, Value, ValueType}; + +/// Native base-parameter identities are distinct from node-specific parameter identifiers +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum BaseParameter { + OutputSize, + Format, + PixelSize, + PixelRatio, + Tiling, + RandomSeed, +} + +impl BaseParameter { + pub const ALL: [Self; 6] = [Self::OutputSize, Self::Format, Self::PixelSize, Self::PixelRatio, Self::Tiling, Self::RandomSeed]; + + pub fn named(name: &str) -> Option { + Self::ALL.into_iter().find(|parameter| parameter.identifier() == name) + } + + pub fn identifier(self) -> &'static str { + match self { + Self::OutputSize => "outputsize", + Self::Format => "format", + Self::PixelSize => "pixelsize", + Self::PixelRatio => "pixelratio", + Self::Tiling => "tiling", + Self::RandomSeed => "randomseed", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::OutputSize => "Output size", + Self::Format => "Output format", + Self::PixelSize => "Pixel size", + Self::PixelRatio => "Pixel ratio", + Self::Tiling => "Tiling mode", + Self::RandomSeed => "Random seed", + } + } + + pub fn value_type(self) -> ValueType { + match self { + Self::OutputSize => ValueType::Integer2, + Self::PixelSize => ValueType::Float2, + _ => ValueType::Integer, + } + } + + pub fn value(self, base: &BaseParameters) -> Value { + match self { + Self::OutputSize => Value::Int2(base.size), + Self::Format => Value::Int(match base.format { + OutputFormat::U8 => 0, + OutputFormat::Inherit | OutputFormat::U16 => 1, + OutputFormat::F16 => 2, + OutputFormat::F32 => 3, + }), + Self::PixelSize => Value::Float2(base.pixel_size), + Self::PixelRatio => Value::Int(base.pixel_ratio), + Self::Tiling => Value::Int(i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1)), + Self::RandomSeed => Value::Int(base.seed), + } + } + + pub fn set_value(self, base: &mut BaseParameters, value: &Value) -> Result<(), String> { + if ValueType::of(value) != Some(self.value_type()) { + return Err(format!("{} requires {}", self.label(), self.value_type().label())); + } + + match (self, value) { + (Self::OutputSize, Value::Int2(size)) => base.size = size.map(|component| component.clamp(-12, 13)), + (Self::Format, Value::Int(format)) => { + base.format = match format { + 0 => OutputFormat::U8, + 1 => OutputFormat::U16, + 2 => OutputFormat::F16, + 3 => OutputFormat::F32, + _ => return Err("Output format must be between 0 and 3".into()), + }; + } + (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()); + } + + base.pixel_size = *size; + } + (Self::PixelRatio, Value::Int(ratio)) if (0..=1).contains(ratio) => base.pixel_ratio = *ratio, + (Self::Tiling, Value::Int(tiling)) if (0..=3).contains(tiling) => base.tiling = [tiling & 1 != 0, tiling & 2 != 0], + (Self::RandomSeed, Value::Int(seed)) => base.seed = *seed, + _ => return Err(format!("{} is outside its supported range", self.label())), + } + + Ok(()) + } + + pub fn inheritance(self, base: &BaseParameters) -> ParameterInheritance { + match self { + Self::OutputSize => match base.size_mode { + SizeMode::Absolute => ParameterInheritance::Absolute, + SizeMode::RelativeToInput => ParameterInheritance::RelativeToInput, + SizeMode::RelativeToParent => ParameterInheritance::RelativeToParent, + }, + Self::Format if base.format == OutputFormat::Inherit => ParameterInheritance::RelativeToInput, + Self::Format => base.format_mode, + Self::PixelSize => base.pixel_size_mode, + Self::PixelRatio => base.pixel_ratio_mode, + Self::Tiling => base.tiling_mode, + Self::RandomSeed => base.seed_mode, + } + } + + pub fn set_inheritance(self, base: &mut BaseParameters, inheritance: ParameterInheritance) { + match self { + Self::OutputSize => { + base.size_mode = match inheritance { + ParameterInheritance::Absolute => SizeMode::Absolute, + ParameterInheritance::RelativeToInput => SizeMode::RelativeToInput, + ParameterInheritance::RelativeToParent => SizeMode::RelativeToParent, + }; + } + Self::Format => { + if base.format == OutputFormat::Inherit { + base.format = OutputFormat::U16; + } + + base.format_mode = inheritance; + } + Self::PixelSize => base.pixel_size_mode = inheritance, + Self::PixelRatio => base.pixel_ratio_mode = inheritance, + Self::Tiling => base.tiling_mode = inheritance, + Self::RandomSeed => base.seed_mode = inheritance, + } + } +} diff --git a/crates/core/src/base_parameters.rs b/crates/core/src/base_parameters.rs index ed0f58d..4db8979 100644 --- a/crates/core/src/base_parameters.rs +++ b/crates/core/src/base_parameters.rs @@ -1,6 +1,7 @@ use serde::{Deserialize, Serialize}; -use crate::{OutputFormat, ParameterInheritance, SizeMode}; +use crate::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance, SizeMode}; +use std::collections::BTreeMap; /// Parameters every node has ("Base parameters") #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -10,8 +11,14 @@ pub struct BaseParameters { /// log2 offset per axis (relative modes) or log2 size (absolute) pub size: [i32; 2], pub format: OutputFormat, - /// Added to the graph's random seed for this node + pub format_mode: ParameterInheritance, + /// Added to the inherited seed, or used directly in absolute mode pub seed: i32, + pub seed_mode: ParameterInheritance, + pub pixel_size: [f32; 2], + pub pixel_size_mode: ParameterInheritance, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub functions: BTreeMap, /// Whether sampling wraps at the edges (horizontal, vertical) pub tiling: [bool; 2], pub tiling_mode: ParameterInheritance, @@ -26,7 +33,12 @@ impl Default for BaseParameters { size_mode: SizeMode::RelativeToInput, size: [0, 0], format: OutputFormat::Inherit, + format_mode: ParameterInheritance::Absolute, seed: 0, + seed_mode: ParameterInheritance::RelativeToInput, + pixel_size: [1.0; 2], + pixel_size_mode: ParameterInheritance::RelativeToInput, + functions: BTreeMap::new(), tiling: [true, true], tiling_mode: ParameterInheritance::default(), pixel_ratio: 0, diff --git a/crates/core/src/exposed_parameter.rs b/crates/core/src/exposed_parameter.rs index 43d663a..d8320b4 100644 --- a/crates/core/src/exposed_parameter.rs +++ b/crates/core/src/exposed_parameter.rs @@ -1,6 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::Value; +use crate::{ParameterEditor, Value}; /// The kind of value an exposed graph input carries #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -12,6 +12,14 @@ pub struct ExposedParameter { #[serde(default, skip_serializing_if = "String::is_empty")] pub group: String, pub default: Value, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub description: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub editor: Option, + #[serde(default)] + pub clamp: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub step: Option, #[serde(default)] pub min: f32, #[serde(default = "one")] @@ -24,3 +32,16 @@ pub struct ExposedParameter { fn one() -> f32 { 1.0 } + +impl ExposedParameter { + pub fn editor(&self) -> ParameterEditor { + self.editor.filter(|editor| ParameterEditor::choices(&self.default).contains(editor)).unwrap_or_else(|| ParameterEditor::for_value(&self.default)) + } + + pub fn step(&self) -> f32 { + self.step.filter(|step| step.is_finite() && *step > 0.0).unwrap_or(match self.default { + Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_) | Value::Enum(_) => 1.0, + _ => 0.01, + }) + } +} diff --git a/crates/core/src/function_graph.rs b/crates/core/src/function_graph.rs index 84addc0..02eac7c 100644 --- a/crates/core/src/function_graph.rs +++ b/crates/core/src/function_graph.rs @@ -53,6 +53,38 @@ impl FunctionGraph { graph } + pub fn input(identifier: &str, value_type: crate::ValueType) -> FunctionGraph { + use crate::ValueType; + + let operation = match value_type { + ValueType::Boolean => "get_bool", + ValueType::Integer => "get_integer1", + ValueType::Integer2 => "get_integer2", + ValueType::Integer3 => "get_integer3", + ValueType::Integer4 => "get_integer4", + ValueType::Float => "get_float1", + ValueType::Float2 => "get_float2", + ValueType::Float3 => "get_float3", + ValueType::Float4 => "get_float4", + ValueType::String => "get_string", + }; + let mut graph = FunctionGraph::default(); + graph.output = Some(graph.add(operation, &[], Some(Value::Text(identifier.into())))); + graph + } + + pub fn input_identifier(&self) -> Option<&str> { + let output = self.node(self.output?)?; + if self.nodes.len() != 1 || !output.op.starts_with("get_") { + return None; + } + + match &output.value { + Some(Value::Text(identifier)) => Some(identifier), + _ => None, + } + } + pub fn add_constant(&mut self, value: Value) -> u32 { let operation = match &value { Value::Float(_) => "const_float1", diff --git a/crates/core/src/graph.rs b/crates/core/src/graph.rs index a277554..61a6a23 100644 --- a/crates/core/src/graph.rs +++ b/crates/core/src/graph.rs @@ -105,13 +105,19 @@ impl Graph { /// All editable Function canvases, including processor and parameter functions pub fn functions(&self) -> impl Iterator { - self.function.iter().chain(self.nodes.iter().flat_map(|node| node.functions.values().chain(node.params.values().flat_map(value_functions)))) + self.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))), + ) } pub fn functions_mut(&mut self) -> impl Iterator { - self.function - .iter_mut() - .chain(self.nodes.iter_mut().flat_map(|node| node.functions.values_mut().chain(node.params.values_mut().flat_map(value_functions_mut)))) + self.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)) + }), + ) } pub fn instances(&self) -> impl Iterator { @@ -125,8 +131,10 @@ impl Graph { 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| { node.instance.iter_mut().chain( - node.functions + node.base + .functions .values_mut() + .chain(node.functions.values_mut()) .chain(node.params.values_mut().flat_map(value_functions_mut)) .flat_map(|function| function.nodes.iter_mut().filter_map(|node| node.instance.as_mut())), ) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index b02cfa3..f9ac317 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -2,6 +2,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod attributes; +mod base_parameter; mod base_parameters; mod canvas_annotations; mod color; @@ -29,6 +30,7 @@ mod node; mod node_id; mod output_format; mod package; +mod parameter_editor; mod parameter_inheritance; mod pattern_graph; mod pattern_node; @@ -43,6 +45,7 @@ mod value; mod value_type; pub use attributes::Attributes; +pub use base_parameter::BaseParameter; pub use base_parameters::BaseParameters; pub use color::{linear_to_srgb, parse_color, srgb_to_linear}; pub use comment::Comment; @@ -69,6 +72,7 @@ pub use node::Node; pub use node_id::NodeId; pub use output_format::OutputFormat; pub use package::{PACKAGE_EXT, Package}; +pub use parameter_editor::ParameterEditor; pub use parameter_inheritance::ParameterInheritance; pub use pattern_graph::PatternGraph; pub use pattern_node::PatternNode; diff --git a/crates/core/src/parameter_editor.rs b/crates/core/src/parameter_editor.rs new file mode 100644 index 0000000..b6db985 --- /dev/null +++ b/crates/core/src/parameter_editor.rs @@ -0,0 +1,43 @@ +use crate::Value; +use serde::{Deserialize, Serialize}; + +/// Presentation of an exposed value in Properties +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ParameterEditor { + Slider, + Input, + Color, + Dropdown, + Toggle, + Text, +} + +impl ParameterEditor { + pub fn choices(value: &Value) -> &'static [Self] { + match value { + Value::Bool(_) => &[Self::Toggle], + Value::Text(_) => &[Self::Text], + Value::Enum(_) => &[Self::Dropdown], + Value::Color(_) => &[Self::Color, Self::Input], + Value::Float3(_) | Value::Float4(_) => &[Self::Slider, Self::Input, Self::Color], + Value::Float(_) | Value::Float2(_) | Value::Int(_) | Value::Int2(_) | Value::Int3(_) | Value::Int4(_) => &[Self::Slider, Self::Input], + _ => &[], + } + } + + pub fn for_value(value: &Value) -> Self { + Self::choices(value).first().copied().unwrap_or(Self::Input) + } + + pub fn label(self) -> &'static str { + match self { + Self::Slider => "Slider", + Self::Input => "Input field", + Self::Color => "Color", + Self::Dropdown => "Drop down list", + Self::Toggle => "Toggle", + Self::Text => "Text", + } + } +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 51ccc34..b5f4582 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -68,6 +68,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::document_history_commands::specs()); v.extend(crate::embedded_edit_commands::specs()); v.extend(crate::graph_cmds::specs()); + v.extend(crate::exposed_input_commands::specs()); v.extend(crate::graph_property_commands::specs()); v.extend(crate::alignment_commands::specs()); v.extend(crate::annotation_commands::specs()); @@ -79,6 +80,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::comment_commands::specs()); v.extend(crate::pin_commands::specs()); v.extend(crate::node_cmds::specs()); + v.extend(crate::parameter_function_commands::specs()); v.extend(crate::node_graph_commands::specs()); v.extend(crate::pattern_graph_commands::specs()); v.extend(crate::connection_commands::specs()); diff --git a/crates/engine/src/exposed_input_commands.rs b/crates/engine/src/exposed_input_commands.rs new file mode 100644 index 0000000..f9bba42 --- /dev/null +++ b/crates/engine/src/exposed_input_commands.rs @@ -0,0 +1,180 @@ +use crate::{ + Result, Session, cmd, + commands::{CommandSpec, bad, has_graph, strp}, + parameter_target::ParameterTarget, +}; +use materialcraft_core::{ExposedParameter, FunctionGraph, ParameterEditor, Value, ValueType}; +use serde_json::{Value as J, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "graph.exposed.prepare", + "Prepare graph input", + [], + None, + "{bind: {node, param}, default?} returns input settings without changing the graph", + has_graph, + prepare + ), + cmd!( + "graph.exposed.add", + "Expose parameter", + [], + None, + "{id?, label?, group?, description?, default?, min?, max?, editor?, clamp?, step?, bind?: {node, param}}", + has_graph, + add + ), + ] +} + +fn prepare(session: &mut Session, parameters: &J) -> Result { + let (input, _) = prepare_input(session, parameters)?; + Ok(json!(input)) +} + +fn add(session: &mut Session, parameters: &J) -> Result { + let (input, target) = prepare_input(session, parameters)?; + let value_type = ValueType::of(&input.default).ok_or_else(|| bad("graph.exposed.add", "input must have a scalar or vector type"))?; + let identifier = input.id.clone(); + session.edit("Expose parameter", |session| { + let graph = session.graph_mut()?; + graph.exposed.push(input); + if let Some(target) = target { + target.set_function(graph, FunctionGraph::input(&identifier, value_type))?; + } + + Ok(json!({"id": identifier})) + }) +} + +fn number(parameters: &J, name: &str) -> Result> { + parameters + .get(name) + .filter(|value| !value.is_null()) + .map(|value| { + value + .as_f64() + .map(|value| value as f32) + .filter(|value| value.is_finite()) + .ok_or_else(|| bad("graph.exposed.add", format!("{name} must be a finite number"))) + }) + .transpose() +} + +fn prepare_input(session: &Session, parameters: &J) -> Result<(ExposedParameter, Option)> { + let command = "graph.exposed.add"; + let target = parameters + .get("bind") + .map(|binding| { + ParameterTarget::resolve( + session, + command, + &json!({ + "id": binding.get("node"), "param": binding.get("param"), "base": binding.get("base").and_then(J::as_bool).unwrap_or(false) + }), + ) + }) + .transpose()?; + if matches!(target, Some(ParameterTarget::Base { .. })) { + return Err(bad(command, "only Specific Parameters can be exposed as graph inputs")); + } + + let identifier = match strp(parameters, "id").map(str::trim).filter(|identifier| !identifier.is_empty()) { + Some(identifier) => { + if session.graph()?.exposed.iter().any(|input| input.id == identifier) { + return Err(bad(command, format!("an input is already called `{identifier}`"))); + } + + identifier.to_string() + } + None => { + let target = target.as_ref().ok_or_else(|| bad(command, "id is required"))?; + let graph = session.graph()?; + let base = target.identifier(); + (0..=graph.exposed.len()) + .map(|suffix| if suffix == 0 { base.to_string() } else { format!("{base}_{suffix}") }) + .find(|candidate| !graph.exposed.iter().any(|input| input.id == *candidate)) + .ok_or_else(|| bad(command, "cannot allocate an input identifier"))? + } + }; + if !identifier.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') { + return Err(bad(command, "identifier must contain only letters, digits and underscores")); + } + + let descriptor = target.as_ref().map(|target| target.descriptor(session, command)).transpose()?; + if descriptor.as_ref().is_some_and(|descriptor| !descriptor.supports_function) { + return Err(bad(command, "this parameter cannot be exposed")); + } + + let default = if let Some(value) = parameters.get("default").filter(|value| !value.is_null()) { + let template = descriptor.as_ref().map_or(Value::Float(0.5), |descriptor| descriptor.default.clone()); + serde_json::from_value::(value.clone()).ok().or_else(|| template.coerce_json(value)).ok_or_else(|| bad(command, "invalid default"))? + } else { + match (&target, &descriptor) { + (Some(target), Some(descriptor)) => target.current_value(session, descriptor)?, + _ => Value::Float(0.5), + } + }; + let value_type = materialcraft_core::ValueType::of(&default).ok_or_else(|| bad(command, "input must have a scalar or vector type"))?; + if descriptor.as_ref().is_some_and(|descriptor| materialcraft_core::ValueType::of(&descriptor.default) != Some(value_type)) { + return Err(bad(command, "input type does not match the parameter")); + } + + if default.as_vec4().is_some_and(|values| values.iter().any(|value| !value.is_finite())) { + return Err(bad(command, "default must be finite")); + } + + let default = descriptor.as_ref().and_then(|descriptor| descriptor.default.coerce_json(&json!(default))).unwrap_or(default); + let source_input = target.as_ref().and_then(|target| { + let node = session.graph().ok()?.node(target.node()).ok()?; + let (_, source) = materialcraft_eval::instance_graph(&session.pkg, node)?; + source.exposed.iter().find(|input| input.id == target.identifier()) + }); + let editor = parameters + .get("editor") + .filter(|value| !value.is_null()) + .map(|value| serde_json::from_value::(value.clone()).map_err(|_| bad(command, "unknown parameter editor"))) + .transpose()? + .or_else(|| source_input.and_then(|input| input.editor)); + if editor.is_some_and(|editor| !ParameterEditor::choices(&default).contains(&editor)) { + return Err(bad(command, "editor does not support this parameter type")); + } + + let default = if editor == Some(ParameterEditor::Color) { + match default { + Value::Float4(value) => Value::Color(value), + value => value, + } + } else { + default + }; + let input = ExposedParameter { + id: identifier.clone(), + 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") + .map(str::to_string) + .unwrap_or_else(|| source_input.map_or_else(String::new, |input| input.description.clone())), + editor: editor.filter(|editor| *editor != ParameterEditor::for_value(&default)), + clamp: parameters + .get("clamp") + .map(|value| value.as_bool().ok_or_else(|| bad(command, "clamp must be a boolean"))) + .transpose()? + .unwrap_or_else(|| source_input.is_some_and(|input| input.clamp)), + step: number(parameters, "step")?.or_else(|| source_input.and_then(|input| input.step)), + default, + min: number(parameters, "min")?.unwrap_or_else(|| descriptor.as_ref().map_or(0.0, |descriptor| descriptor.min)), + max: number(parameters, "max")?.unwrap_or_else(|| descriptor.as_ref().map_or(1.0, |descriptor| descriptor.max)), + options: descriptor.map_or_else(Vec::new, |descriptor| descriptor.options), + }; + if input.min > input.max { + return Err(bad(command, "minimum must not exceed maximum")); + } + if input.step.is_some_and(|step| step <= 0.0) { + return Err(bad(command, "step must be greater than zero")); + } + + Ok((input, target)) +} diff --git a/crates/engine/src/function_graph_target.rs b/crates/engine/src/function_graph_target.rs index 644b3ac..96c127e 100644 --- a/crates/engine/src/function_graph_target.rs +++ b/crates/engine/src/function_graph_target.rs @@ -1,5 +1,5 @@ use crate::{Result, Session, commands::bad}; -use materialcraft_core::{FunctionGraph, NodeId, Value}; +use materialcraft_core::{BaseParameter, FunctionGraph, NodeId, Value}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] @@ -15,6 +15,10 @@ pub enum FunctionGraphTarget { node: NodeId, parameter: String, }, + Base { + node: NodeId, + parameter: BaseParameter, + }, Pattern { owner: NodeId, node: u32, @@ -39,6 +43,9 @@ impl FunctionGraphTarget { Self::Dynamic { node, parameter } => { return document.node(*node)?.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing parameter function")); } + Self::Base { node, parameter } => { + return document.node(*node)?.base.functions.get(parameter).ok_or_else(|| bad("graph.function.edit", "missing base parameter function")); + } Self::Parameter { node, parameter } => { let node = document.node(*node)?; node.params.get(parameter).or_else(|| materialcraft_nodes::find(&node.def)?.param(parameter).map(|parameter| ¶meter.default)) @@ -64,7 +71,12 @@ impl FunctionGraphTarget { match self { Self::Graph => document.function = Some(function), Self::Dynamic { node, parameter } => { - document.node_mut(*node)?.functions.insert(parameter.clone(), function); + let owner = document.node_mut(*node)?; + owner.bindings.remove(parameter); + owner.functions.insert(parameter.clone(), function); + } + Self::Base { node, parameter } => { + document.node_mut(*node)?.base.functions.insert(*parameter, function); } Self::Parameter { node, parameter } => { document.node_mut(*node)?.params.insert(parameter.clone(), Value::Function(Box::new(function))); diff --git a/crates/engine/src/function_inspection.rs b/crates/engine/src/function_inspection.rs index 499b1a0..ccd424c 100644 --- a/crates/engine/src/function_inspection.rs +++ b/crates/engine/src/function_inspection.rs @@ -24,6 +24,9 @@ pub fn warnings(graph: &Graph) -> Vec<(FunctionGraphTarget, Vec)> { } for node in &graph.nodes { + for (parameter, function) in &node.base.functions { + inspect(FunctionGraphTarget::Base { node: node.id, parameter: *parameter }, function); + } for (parameter, function) in &node.functions { inspect(FunctionGraphTarget::Dynamic { node: node.id, parameter: parameter.clone() }, function); } diff --git a/crates/engine/src/function_output.rs b/crates/engine/src/function_output.rs index fb31cf3..811ab80 100644 --- a/crates/engine/src/function_output.rs +++ b/crates/engine/src/function_output.rs @@ -6,8 +6,16 @@ pub fn expected_type(document: &Graph, target: &FunctionGraphTarget) -> Option None, FunctionGraphTarget::Dynamic { node, parameter } => { let node = document.node(*node).ok()?; - ValueType::of(&materialcraft_nodes::find(&node.def)?.param(parameter)?.default) + let default = if node.def == "graph_instance" { + node.instance.as_ref()?.defaults.get(parameter)? + } else if node.def == "input_value" && parameter == "default" { + node.params.get(parameter).unwrap_or(&materialcraft_nodes::find(&node.def)?.param(parameter)?.default) + } else { + &materialcraft_nodes::find(&node.def)?.param(parameter)?.default + }; + ValueType::of(default) } + FunctionGraphTarget::Base { parameter, .. } => Some(parameter.value_type()), FunctionGraphTarget::Parameter { node, parameter } => { let node = document.node(*node).ok()?; if node.def != "pixel_processor" || parameter != "function" { diff --git a/crates/engine/src/function_variables.rs b/crates/engine/src/function_variables.rs index 676f607..f21989a 100644 --- a/crates/engine/src/function_variables.rs +++ b/crates/engine/src/function_variables.rs @@ -44,7 +44,7 @@ pub(crate) fn suggestions(target: &FunctionGraphTarget, session: &Session, id: u } let owner = match target { - FunctionGraphTarget::Parameter { node, .. } | FunctionGraphTarget::Dynamic { node, .. } => Some(*node), + FunctionGraphTarget::Parameter { node, .. } | FunctionGraphTarget::Dynamic { node, .. } | FunctionGraphTarget::Base { node, .. } => Some(*node), FunctionGraphTarget::Pattern { owner, .. } => Some(*owner), FunctionGraphTarget::Graph => None, }; diff --git a/crates/engine/src/graph_cmds.rs b/crates/engine/src/graph_cmds.rs index ecf8077..5f115af 100644 --- a/crates/engine/src/graph_cmds.rs +++ b/crates/engine/src/graph_cmds.rs @@ -2,9 +2,9 @@ use serde_json::{Value as J, json}; -use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value}; +use materialcraft_core::{MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value}; -use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, boolp, has_graph, has_selection, i64p, ids_param, strp, u64p}; use crate::{Result, Session, cmd}; pub(crate) fn specs() -> Vec { @@ -31,15 +31,6 @@ pub(crate) fn specs() -> Vec { has_graph, cook ), - cmd!( - "graph.exposed.add", - "Expose parameter", - [], - None, - "{id (optional with bind: then named after the parameter and kept unique), label?, default (a typed value or number), min?, max?, group?, bind?: {node, param}}", - has_graph, - exposed_add - ), cmd!("graph.exposed.set", "Set input value", [], None, "{id, value}", has_graph, exposed_set), cmd!("graph.exposed.delete", "Delete input", [], None, "{id}", has_graph, exposed_delete), cmd!( @@ -192,66 +183,6 @@ pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> { (r[0] < f32::MAX).then(|| [r[0], r[1], r[2] - r[0], r[3] - r[1]]) } -fn exposed_add(s: &mut Session, p: &J) -> Result { - // From a bound node parameter: its value, range and options become the input's - let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string()))); - let id = match strp(p, "id").map(str::trim).filter(|i| !i.is_empty()) { - Some(id) => { - if s.graph()?.exposed.iter().any(|e| e.id == id) { - return Err(bad("graph.exposed.add", format!("an input is already called `{id}`"))); - } - id.to_string() - } - // Without an `id`, a bound input is named after its parameter, kept unique across nodes - None => { - let (_, param) = bind.as_ref().ok_or_else(|| bad("graph.exposed.add", "`id` is required"))?; - unique_exposed_id(s.graph()?, param) - } - }; - let mut default = Value::Float(0.5); - let (mut min, mut max, mut options) = (0.0f32, 1.0f32, Vec::new()); - if let Some((node, param)) = &bind { - let g = s.graph()?; - let n = g.node(*node).map_err(|_| bad("graph.exposed.add", format!("no node {}", node.0)))?; - let def = materialcraft_nodes::find(&n.def).ok_or_else(|| bad("graph.exposed.add", "unknown node type"))?; - let pd = def.param(param).ok_or_else(|| bad("graph.exposed.add", format!("`{}` has no parameter `{param}`", n.def)))?; - default = n.params.get(param.as_str()).cloned().unwrap_or_else(|| pd.default.clone()); - (min, max) = (pd.min, pd.max); - options = pd.options.iter().map(|o| o.to_string()).collect(); - } - if let Some(d) = p.get("default") { - default = - serde_json::from_value::(d.clone()).ok().or_else(|| default.coerce_json(d)).ok_or_else(|| bad("graph.exposed.add", "bad `default`"))?; - } - let ep = ExposedParameter { - id: id.clone(), - label: strp(p, "label").unwrap_or(&id).to_string(), - group: strp(p, "group").unwrap_or("").to_string(), - default, - min: f32p(p, "min").unwrap_or(min), - max: f32p(p, "max").unwrap_or(max), - options, - }; - - s.edit("Expose parameter", |s| { - let g = s.graph_mut()?; - g.exposed.push(ep); - if let Some((node, param)) = bind { - g.node_mut(node)?.bindings.insert(param, id.clone()); - } - Ok(json!({"id": id})) - }) -} - -/// An input id not used in `graph`: `base`, `base_1`, `base_2`… -fn unique_exposed_id(graph: &Graph, base: &str) -> String { - let taken = |id: &str| graph.exposed.iter().any(|e| e.id == id); - if !taken(base) { - return base.to_string(); - } - (1..).map(|i| format!("{base}_{i}")).find(|id| !taken(id)).unwrap_or_else(|| base.to_string()) -} - fn exposed_set(s: &mut Session, p: &J) -> Result { let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.set", "`id` is required"))?.to_string(); let v = p.get("value").ok_or_else(|| bad("graph.exposed.set", "`value` is required"))?; @@ -263,15 +194,20 @@ fn exposed_set(s: &mut Session, p: &J) -> Result { }) } -fn exposed_delete(s: &mut Session, p: &J) -> Result { - let id = strp(p, "id").ok_or_else(|| bad("graph.exposed.delete", "`id` is required"))?.to_string(); - s.edit("Delete input", |s| { - let g = s.graph_mut()?; - g.exposed.retain(|e| e.id != id); - g.inputs.remove(&id); - for n in &mut g.nodes { - n.bindings.retain(|_, v| *v != id); +fn exposed_delete(session: &mut Session, parameters: &J) -> Result { + let identifier = strp(parameters, "id").ok_or_else(|| bad("graph.exposed.delete", "`id` is required"))?.to_string(); + session.edit("Delete input", |session| { + let graph = session.graph_mut()?; + graph.exposed.retain(|input| input.id != identifier); + graph.inputs.remove(&identifier); + for node in &mut graph.nodes { + node.bindings.retain(|_, input| *input != identifier); + + // Detach direct input links without discarding user-authored function logic + node.functions.retain(|_, function| function.input_identifier() != Some(identifier.as_str())); + node.base.functions.retain(|_, function| function.input_identifier() != Some(identifier.as_str())); } + Ok(J::Null) }) } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 71942eb..d410c29 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -4,92 +4,95 @@ use serde_json::{Value as J, json}; use crate::Session; -pub fn session(s: &Session, graph: Option) -> J { - let gi = graph.unwrap_or(s.graph); - let g = s.pkg.graphs.get(gi); - let cooked = (gi == s.graph).then_some(&s.cooked); - let graph_json = g.map(|g| { +pub fn session(session: &Session, requested_graph: Option) -> J { + let graph_index = requested_graph.unwrap_or(session.graph); + let graph = session.pkg.graphs.get(graph_index); + let cooked = (graph_index == session.graph).then_some(&session.cooked); + let graph_json = graph.map(|graph| { let mut result = json!({ - "index": gi, - "name": g.name, - "path": g.sbs_path(), - "kind": g.kind(), - "function": g.function, - "functionWarnings": crate::function_inspection::warnings(g).into_iter().map(|(target, messages)| json!({"target": target, "messages": messages})).collect::>(), - "size": g.size_px(), - "format": g.format, - "seed": g.seed, - "attributes": g.attributes, - "exposed": g.exposed, - "presets": g.presets, - "inputs": g.inputs, - "inputImages": g.input_images, - "inputImagesLinear": g.input_images_linear, - "nodes": g.nodes.iter().map(|n| { - let r = cooked.and_then(|c| c.nodes.get(&n.id)); - let (ins, outs) = materialcraft_eval::ports(&s.pkg, g, n); + "index": graph_index, + "name": graph.name, + "path": graph.sbs_path(), + "kind": graph.kind(), + "function": graph.function, + "functionWarnings": crate::function_inspection::warnings(graph).into_iter().map(|(target, messages)| json!({"target": target, "messages": messages})).collect::>(), + "size": graph.size_px(), + "format": graph.format, + "seed": graph.seed, + "attributes": graph.attributes, + "exposed": graph.exposed, + "presets": graph.presets, + "inputs": graph.inputs, + "inputImages": graph.input_images, + "inputImagesLinear": graph.input_images_linear, + "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); + let node_cooked = entry.map(|entry| json!({ + "error": entry.error, "ms": entry.ms, "cached": entry.cached, + "base": entry.base, "baseValues": entry.base_values, "parameters": entry.parameters, + "value": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value), + "size": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| [image.w, image.h]), + "kind": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| if image.is_gray() { "gray" } else { "color" }), + "mean": entry.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|image| image.mean()), + })); json!({ - "id": n.id.0, - "def": n.def, - "instance": n.instance, - "label": if n.label.is_empty() { materialcraft_nodes::find(&n.def).map_or(n.def.as_str(), |d| d.label).to_string() } else { n.label.clone() }, - "pos": n.pos, - "params": n.params, - "bindings": n.bindings, - "functions": n.functions, - "inputValues": n.input_values, - "base": n.base, - "disabled": n.disabled, - "inputs": ins.iter().map(|p| &p.id).collect::>(), - "outputs": outs.iter().map(|p| &p.id).collect::>(), - "cooked": r.map(|r| json!({ - "error": r.error, "ms": r.ms, "cached": r.cached, - "value": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_value), - "size": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| [i.w, i.h]), - "kind": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| if i.is_gray() { "gray" } else { "color" }), - "mean": r.outputs.first().and_then(materialcraft_eval::NodeOutput::as_image).map(|i| i.mean()), - })), + "id": node.id.0, + "def": node.def, + "instance": node.instance, + "label": if node.label.is_empty() { materialcraft_nodes::find(&node.def).map_or(node.def.as_str(), |definition| definition.label).to_string() } else { node.label.clone() }, + "pos": node.pos, + "params": node.params, + "bindings": node.bindings, + "functions": node.functions, + "inputValues": node.input_values, + "base": node.base, + "disabled": node.disabled, + "inputs": inputs.iter().map(|port| &port.id).collect::>(), + "outputs": outputs.iter().map(|port| &port.id).collect::>(), + "cooked": node_cooked, }) }).collect::>(), - "connections": g.connections, - "frames": g.frames, - "comments": g.comments, - "pins": g.pins, + "connections": graph.connections, + "frames": graph.frames, + "comments": graph.comments, + "pins": graph.pins, }); - result["physicalSize"] = json!(g.physical_size); - result["pixelRatio"] = json!(g.pixel_ratio); - result["pixelRatioMode"] = json!(g.pixel_ratio_mode); - result["tiling"] = json!(g.tiling); - result["tilingMode"] = json!(g.tiling_mode); + result["physicalSize"] = json!(graph.physical_size); + result["pixelRatio"] = json!(graph.pixel_ratio); + result["pixelRatioMode"] = json!(graph.pixel_ratio_mode); + result["tiling"] = json!(graph.tiling); + result["tilingMode"] = json!(graph.tiling_mode); result }); + json!({ - "documents": s.inspect_documents(), - "package": s.has_package().then(|| json!({"name": s.pkg.name, "path": s.path, "modified": s.modified, "folders": s.pkg.folder_paths(), "folderDescriptions": s.pkg.folder_descriptions, "warnings": s.load_warnings, "resources": s.pkg.resources.iter().map(|r| json!({"name": r.name, "folder": r.folder, "file": r.file, "missing": r.bytes.is_empty(), "bytes": r.bytes.len()})).collect::>()})), - "graphs": s.pkg.graphs.iter().enumerate().map(|(i, g)| json!({"index": i, "name": g.name, "path": g.sbs_path(), "nodes": g.nodes.len(), "kind": g.kind()})).collect::>(), - "openGraph": g.map(|_| s.graph), + "documents": session.inspect_documents(), + "package": session.has_package().then(|| json!({"name": session.pkg.name, "path": session.path, "modified": session.modified, "folders": session.pkg.folder_paths(), "folderDescriptions": session.pkg.folder_descriptions, "warnings": session.load_warnings, "resources": session.pkg.resources.iter().map(|entry| json!({"name": entry.name, "folder": entry.folder, "file": entry.file, "missing": entry.bytes.is_empty(), "bytes": entry.bytes.len()})).collect::>()})), + "graphs": session.pkg.graphs.iter().enumerate().map(|(index, graph)| json!({"index": index, "name": graph.name, "path": graph.sbs_path(), "nodes": graph.nodes.len(), "kind": graph.kind()})).collect::>(), + "openGraph": graph.map(|_| session.graph), "graph": graph_json, - "annotationSelection": s.annotation_selection, - "annotationTarget": s.annotation_target, - "selection": s.selection.iter().map(|i| i.0).collect::>(), - "view2d": s.view2d, - "view3d": s.view3d, + "annotationSelection": session.annotation_selection, + "annotationTarget": session.annotation_target, + "selection": session.selection.iter().map(|index| index.0).collect::>(), + "view2d": session.view2d, + "view3d": session.view3d, "material3d": { - "assignments": s.material_preview, - "channels": s.material_preview.sources(&s.pkg).into_iter().map(|(channel, source)| { - let image = s.material_image(&source); + "assignments": session.material_preview, + "channels": session.material_preview.sources(&session.pkg).into_iter().map(|(channel, source)| { + let image = session.material_image(&source); json!({"channel": channel, "source": source, "size": image.map(|image| [image.w, image.h]), "mean": image.map(|image| image.mean())}) }).collect::>(), }, - "previewSize": s.preview_size, - "camera": s.camera, - "environment": s.environment, - "cookMs": s.cooked.ms, - "dirty": s.dirty, - "history": s.history(), - "historyPreferences": s.history_prefs, - "canUndo": s.can_undo(), - "canRedo": s.can_redo(), - "log": s.log.iter().rev().take(20).collect::>(), + "previewSize": session.preview_size, + "camera": session.camera, + "environment": session.environment, + "cookMs": session.cooked.ms, + "dirty": session.dirty, + "history": session.history(), + "historyPreferences": session.history_prefs, + "canUndo": session.can_undo(), + "canRedo": session.can_redo(), + "log": session.log.iter().rev().take(20).collect::>(), }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 31c0ae1..01636d1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -125,7 +125,11 @@ mod function_graph_target; mod function_info_commands; pub mod function_inspection; pub mod function_output; +mod parameter_function_commands; +mod parameter_target; mod pattern_edit; pub use function_edit::FunctionEdit; pub use function_graph_target::FunctionGraphTarget; pub use pattern_edit::PatternEdit; + +mod exposed_input_commands; diff --git a/crates/engine/src/linked_packages.rs b/crates/engine/src/linked_packages.rs index f0038f3..edafd83 100644 --- a/crates/engine/src/linked_packages.rs +++ b/crates/engine/src/linked_packages.rs @@ -70,6 +70,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - } instance.inputs = inputs; instance.outputs = outputs; + instance.defaults = graph.exposed.iter().map(|parameter| (parameter.id.clone(), parameter.default.clone())).collect(); instance.label = graph.display_name().into(); (node.instance.as_ref() != Some(&instance)).then_some((graph_index, node_index, instance)) }) diff --git a/crates/engine/src/node_cmds.rs b/crates/engine/src/node_cmds.rs index 66a590f..5791c22 100644 --- a/crates/engine/src/node_cmds.rs +++ b/crates/engine/src/node_cmds.rs @@ -30,29 +30,18 @@ pub(crate) fn specs() -> Vec { [], None, "{id?, param, value} (numbers, [x, y], \"#rrggbb\", enum index, typed {t, v})", - has_selection, + has_graph, set_param ), - cmd!("graph.node.reset", "Reset parameters", [], None, "{id?, param? (default: all)}", has_selection, reset), cmd!( "graph.node.base", "Set base parameters", [], None, - "{id?, sizeMode? (relativeToInput|relativeToParent|absolute), size? [w, h] (log2 offset, or log2 size when absolute), format? (inherit|u8|u16|f16|f32), seed?, tiling?: bool|[bool,bool], pixelRatio?: 0|1, tilingMode?, pixelRatioMode? (relativeToInput|relativeToParent|absolute)}", - has_selection, + "{id?, param?: outputsize|format|pixelsize|pixelratio|tiling|randomseed, value?, inheritance?: relativeToInput|relativeToParent|absolute}; legacy fields: {sizeMode?, size?: [w, h] (log2), format?: inherit|u8|u16|f16|f32, seed?, tiling?: bool|[bool,bool], pixelRatio?: 0|1, tilingMode?, pixelRatioMode?}", + has_graph, base ), - cmd!("graph.node.bind", "Bind parameter to input", [], None, "{id?, param, input (exposed id); input null unbinds}", has_selection, bind), - cmd!( - "graph.node.function", - "Set parameter function", - [], - None, - "{id?, param, function?: {nodes, output} (default: a constant of the current value), remove?: bool} drives a parameter with a function graph of the graph's inputs", - has_selection, - set_function - ), ] } @@ -166,71 +155,83 @@ fn disable(s: &mut Session, p: &J) -> Result { }) } -fn set_param(s: &mut Session, p: &J) -> Result { - let id = node_param(s, "graph.node.param", p, "id")?; - let param = strp(p, "param").ok_or_else(|| bad("graph.node.param", "`param` is required"))?.to_string(); - let v = p.get("value").ok_or_else(|| bad("graph.node.param", "`value` is required"))?; - let node = s.graph()?.node(id)?.clone(); - let value = if node.def == "input_value" && param == "default" { +fn set_param(session: &mut Session, parameters: &J) -> Result { + let id = node_param(session, "graph.node.param", parameters, "id")?; + let parameter = strp(parameters, "param").ok_or_else(|| bad("graph.node.param", "`param` is required"))?.to_string(); + let supplied = parameters.get("value").ok_or_else(|| bad("graph.node.param", "`value` is required"))?; + let node = session.graph()?.node(id)?.clone(); + let value = if node.def == "input_value" && parameter == "default" { let current = node.params.get("default").cloned().unwrap_or(Value::Float(0.0)); - serde_json::from_value::(v.clone()) + serde_json::from_value::(supplied.clone()) .ok() - .or_else(|| current.coerce_json(v)) + .or_else(|| current.coerce_json(supplied)) .filter(|value| materialcraft_core::ValueType::of(value).is_some()) .ok_or_else(|| bad("graph.node.param", "default must be a scalar or vector value"))? } else if node.def == "graph_instance" { - // Instance parameters: the sub-graph's exposed inputs (and `graph`) - if param == "graph" { - Value::Text(v.as_str().ok_or_else(|| bad("graph.node.param", "`graph` is a graph name"))?.into()) + // Instance parameters come from the source graph's exposed inputs + if parameter == "graph" { + Value::Text(supplied.as_str().ok_or_else(|| bad("graph.node.param", "`graph` is a graph name"))?.into()) } else { - let sub = - materialcraft_eval::instance_graph(&s.pkg, &node).map(|(_, g)| g).ok_or_else(|| bad("graph.node.param", "the instanced graph is missing"))?; - let e = sub.exposed.iter().find(|e| e.id == param).ok_or_else(|| bad("graph.node.param", format!("the graph has no input `{param}`")))?; - e.default.coerce_json(v).ok_or_else(|| bad("graph.node.param", format!("`{param}` takes a {}", e.default.type_name())))? + let source = materialcraft_eval::instance_graph(&session.pkg, &node) + .map(|(_, g)| g) + .ok_or_else(|| bad("graph.node.param", "the instanced graph is missing"))?; + let input = source + .exposed + .iter() + .find(|input| input.id == parameter) + .ok_or_else(|| bad("graph.node.param", format!("the graph has no input `{parameter}`")))?; + input.default.coerce_json(supplied).ok_or_else(|| bad("graph.node.param", format!("`{parameter}` takes a {}", input.default.type_name())))? } } else { - let def = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.param", format!("unknown node `{}`", node.def)))?; - let pd = def.param(¶m).ok_or_else(|| bad("graph.node.param", format!("`{}` has no parameter `{param}`", node.def)))?; - let mut v = pd.default.coerce_json(v).ok_or_else(|| bad("graph.node.param", format!("`{param}` takes a {}", pd.default.type_name())))?; - if let Value::Enum(i) = &mut v - && !pd.options.is_empty() + let definition = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.param", format!("unknown node `{}`", node.def)))?; + let descriptor = definition.param(¶meter).ok_or_else(|| bad("graph.node.param", format!("`{}` has no parameter `{parameter}`", node.def)))?; + let mut value = descriptor + .default + .coerce_json(supplied) + .ok_or_else(|| bad("graph.node.param", format!("`{parameter}` takes a {}", descriptor.default.type_name())))?; + if let Value::Enum(i) = &mut value + && !descriptor.options.is_empty() { - *i = (*i).min(pd.options.len() as u32 - 1); + *i = (*i).min(descriptor.options.len() as u32 - 1); } - v + + value }; crate::graph_validation::value(&value).map_err(|error| bad("graph.node.param", error))?; - s.edit_merged(&format!("param:{}:{param}", id.0), "Set parameter", |s| { - s.graph_mut()?.node_mut(id)?.params.insert(param.clone(), value); - Ok(J::Null) - }) -} - -fn reset(s: &mut Session, p: &J) -> Result { - let id = node_param(s, "graph.node.reset", p, "id")?; - let param = strp(p, "param").map(str::to_string); - s.edit("Reset parameters", |s| { - let n = s.graph_mut()?.node_mut(id)?; - match ¶m { - Some(k) => { - n.params.remove(k); - n.bindings.remove(k); - n.functions.remove(k); - } - None => { - n.params.retain(|k, _| k == "graph" || k == "identifier"); - n.bindings.clear(); - n.functions.clear(); - } - } + session.edit_merged(&format!("param:{}:{parameter}", id.0), "Set parameter", |session| { + let node = session.graph_mut()?.node_mut(id)?; + node.functions.remove(¶meter); + node.bindings.remove(¶meter); + node.params.insert(parameter.clone(), value); Ok(J::Null) }) } fn base(session: &mut Session, parameters: &J) -> Result { let id = node_param(session, "graph.node.base", parameters, "id")?; + if let Some(identifier) = strp(parameters, "param") { + let parameter = materialcraft_core::BaseParameter::named(identifier).ok_or_else(|| bad("graph.node.base", "unknown base parameter"))?; + let mut base = session.graph()?.node(id)?.base.clone(); + let inheritance = parameter.inheritance(&base); + if let Some(value) = parameters.get("value") { + let value = parameter.value(&base).coerce_json(value).ok_or_else(|| bad("graph.node.base", "incorrect base parameter type"))?; + parameter.set_value(&mut base, &value).map_err(|error| bad("graph.node.base", error))?; + parameter.set_inheritance(&mut base, inheritance); + base.functions.remove(¶meter); + } + if let Some(inheritance) = parameters.get("inheritance") { + let inheritance = serde_json::from_value(inheritance.clone()).map_err(|error| bad("graph.node.base", format!("invalid inheritance: {error}")))?; + parameter.set_inheritance(&mut base, inheritance); + } + + return session.edit_merged(&format!("base:{}:{identifier}", id.0), "Set base parameter", |session| { + session.graph_mut()?.node_mut(id)?.base = base; + Ok(J::Null) + }); + } + let mode = match strp(parameters, "sizeMode") { None => None, Some("relativeToInput") => Some(SizeMode::RelativeToInput), @@ -283,15 +284,20 @@ fn base(session: &mut Session, parameters: &J) -> Result { } if let Some(size) = size { base.size = size; + base.functions.remove(&materialcraft_core::BaseParameter::OutputSize); } if let Some(format) = format { base.format = format; + base.format_mode = materialcraft_core::ParameterInheritance::Absolute; + base.functions.remove(&materialcraft_core::BaseParameter::Format); } if let Some(seed) = seed { base.seed = seed; + base.functions.remove(&materialcraft_core::BaseParameter::RandomSeed); } if let Some(tiling) = tiling { base.tiling = tiling; + base.functions.remove(&materialcraft_core::BaseParameter::Tiling); base.tiling_mode = materialcraft_core::ParameterInheritance::Absolute; } if let Some(mode) = tiling_mode { @@ -299,6 +305,7 @@ fn base(session: &mut Session, parameters: &J) -> Result { } if let Some(value) = pixel_ratio { base.pixel_ratio = value; + base.functions.remove(&materialcraft_core::BaseParameter::PixelRatio); base.pixel_ratio_mode = materialcraft_core::ParameterInheritance::Absolute; } if let Some(mode) = pixel_ratio_mode { @@ -308,55 +315,3 @@ fn base(session: &mut Session, parameters: &J) -> Result { Ok(J::Null) }) } - -fn bind(s: &mut Session, p: &J) -> Result { - let id = node_param(s, "graph.node.bind", p, "id")?; - let param = strp(p, "param").ok_or_else(|| bad("graph.node.bind", "`param` is required"))?.to_string(); - let input = strp(p, "input").map(str::to_string); - if let Some(i) = &input - && !s.graph()?.exposed.iter().any(|e| &e.id == i) - { - return Err(bad("graph.node.bind", format!("no input `{i}`"))); - } - s.edit("Bind parameter", |s| { - let n = s.graph_mut()?.node_mut(id)?; - match input { - Some(i) => n.bindings.insert(param, i), - None => n.bindings.remove(¶m), - }; - - Ok(J::Null) - }) -} - -fn set_function(s: &mut Session, p: &J) -> Result { - let id = node_param(s, "graph.node.function", p, "id")?; - let param = strp(p, "param").ok_or_else(|| bad("graph.node.function", "`param` is required"))?.to_string(); - let node = s.graph()?.node(id)?.clone(); - let def = materialcraft_nodes::find(&node.def).ok_or_else(|| bad("graph.node.function", "unknown node type"))?; - let pd = def.param(¶m).ok_or_else(|| bad("graph.node.function", format!("`{}` has no parameter `{param}`", node.def)))?; - if matches!(pd.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_)) { - return Err(bad("graph.node.function", format!("`{param}` is a {} and can't take a function", pd.default.type_name()))); - } - if boolp(p, "remove") == Some(true) { - return s.edit("Remove parameter function", |s| { - s.graph_mut()?.node_mut(id)?.functions.remove(¶m); - Ok(J::Null) - }); - } - let f = match p.get("function") { - Some(f) if !f.is_null() => { - serde_json::from_value::(f.clone()).map_err(|e| bad("graph.node.function", format!("bad function: {e}")))? - } - _ => match node.functions.get(¶m) { - Some(f) => f.clone(), - None => materialcraft_core::FunctionGraph::constant(node.params.get(¶m).cloned().unwrap_or_else(|| pd.default.clone())), - }, - }; - - crate::graph_validation::function(&f).map_err(|error| bad("graph.node.function", error))?; - s.edit_merged(&format!("fn:{}:{param}", id.0), "Set parameter function", |s| { - s.graph_mut()?.node_mut(id)?.functions.insert(param.clone(), f); - Ok(J::Null) - }) -} diff --git a/crates/engine/src/parameter_function_commands.rs b/crates/engine/src/parameter_function_commands.rs new file mode 100644 index 0000000..58a2f8d --- /dev/null +++ b/crates/engine/src/parameter_function_commands.rs @@ -0,0 +1,163 @@ +use crate::{ + Result, Session, cmd, + commands::{CommandSpec, bad, boolp, has_graph, node_param, strp}, + parameter_target::ParameterTarget, +}; +use materialcraft_core::{BaseParameters, FunctionGraph, ValueType}; +use serde_json::{Value as Json, json}; + +pub(crate) fn specs() -> Vec { + vec![ + cmd!( + "graph.node.function", + "Set parameter function", + [], + None, + "{id?, param, base?: false, mode?: empty|constant, value?: constant value, function?: {nodes, output}, remove?: false}", + has_graph, + set_function + ), + cmd!( + "graph.node.function.edit", + "Edit parameter function", + [], + None, + "{id?, param, base?: false} resolves the parameter function to open", + has_graph, + edit + ), + cmd!("graph.node.reset", "Reset parameters", [], None, "{id?, param? (default: all specific parameters), base?: false}", has_graph, reset), + cmd!("graph.node.bind", "Bind parameter to input", [], None, "{id?, param, base?: false, input: exposed id or null}", has_graph, bind), + cmd!( + "graph.node.parameterInfo", + "Inspect parameter", + [], + None, + "{id?, param, base?: false} returns the parameter's type, driver and inheritance", + has_graph, + info + ), + ] +} + +fn set_function(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.node.function"; + let target = ParameterTarget::resolve(session, command, parameters)?; + let descriptor = target.descriptor(session, command)?; + if !descriptor.supports_function { + return Err(bad(command, "this parameter does not support a function")); + } + + if boolp(parameters, "remove") == Some(true) { + return session.edit("Remove parameter function", |session| { + target.clear(session.graph_mut()?, false)?; + Ok(Json::Null) + }); + } + + let mode = strp(parameters, "mode"); + if mode.is_some_and(|mode| !matches!(mode, "empty" | "constant")) { + return Err(bad(command, "mode must be empty or constant")); + } + + let function = if let Some(function) = parameters.get("function").filter(|value| !value.is_null()) { + serde_json::from_value::(function.clone()).map_err(|error| bad(command, error.to_string()))? + } else if mode == Some("empty") { + FunctionGraph::default() + } else if mode.is_none() + && let Some(function) = target.function(session.graph()?) + { + function.clone() + } else { + let value = if let Some(value) = parameters.get("value").filter(|value| !value.is_null()) { + descriptor.default.coerce_json(value).ok_or_else(|| bad(command, "incorrect constant value type"))? + } else { + target.current_value(session, &descriptor)? + }; + FunctionGraph::constant(value) + }; + crate::graph_validation::function(&function).map_err(|error| bad(command, error))?; + session.edit("Set parameter function", |session| { + target.set_function(session.graph_mut()?, function)?; + Ok(json!({"target": target.function_target()})) + }) +} + +fn edit(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.node.function.edit"; + let target = ParameterTarget::resolve(session, command, parameters)?; + target.descriptor(session, command)?; + target.function(session.graph()?).ok_or_else(|| bad(command, "parameter has no function"))?; + + Ok(json!({"target": target.function_target()})) +} + +fn reset(session: &mut Session, parameters: &Json) -> Result { + let node = node_param(session, "graph.node.reset", parameters, "id")?; + let target = parameters.get("param").map(|_| ParameterTarget::resolve(session, "graph.node.reset", parameters)).transpose()?; + if let Some(target) = &target { + target.descriptor(session, "graph.node.reset")?; + } + + session.edit("Reset parameters", |session| { + if let Some(target) = target { + target.clear(session.graph_mut()?, true)?; + } else { + let node = session.graph_mut()?.node_mut(node)?; + if boolp(parameters, "base") == Some(true) { + node.base = BaseParameters::default(); + } else { + node.params.retain(|parameter, _| matches!(parameter.as_str(), "graph" | "identifier")); + node.bindings.clear(); + node.functions.clear(); + } + } + + Ok(Json::Null) + }) +} + +fn bind(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.node.bind"; + let target = ParameterTarget::resolve(session, command, parameters)?; + let descriptor = target.descriptor(session, command)?; + let function = match parameters.get("input") { + Some(Json::Null) => None, + Some(Json::String(identifier)) => { + let input = session.graph()?.exposed.iter().find(|input| &input.id == identifier).ok_or_else(|| bad(command, "no such exposed input"))?; + let expected = + ValueType::of(&descriptor.default).filter(|_| descriptor.supports_function).ok_or_else(|| bad(command, "this parameter cannot be exposed"))?; + if ValueType::of(&input.default) != Some(expected) { + return Err(bad(command, format!("input must be {}", expected.label()))); + } + + Some(FunctionGraph::input(identifier, expected)) + } + _ => return Err(bad(command, "input must be an exposed identifier or null")), + }; + session.edit("Bind parameter", |session| { + match function { + Some(function) => target.set_function(session.graph_mut()?, function)?, + None => target.clear(session.graph_mut()?, false)?, + } + + Ok(Json::Null) + }) +} + +fn info(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.node.parameterInfo"; + let target = ParameterTarget::resolve(session, command, parameters)?; + let descriptor = target.descriptor(session, command)?; + let graph = session.graph()?; + let function = target.function(graph); + let inheritance = match target { + ParameterTarget::Base { node, parameter } => Some(parameter.inheritance(&graph.node(node)?.base)), + _ => None, + }; + let current = target.current_value(session, &descriptor); + Ok(json!({"target": target.function_target(), "label": descriptor.label, "default": descriptor.default, + "expectedType": ValueType::of(&descriptor.default), "supportsFunction": descriptor.supports_function, + "value": current.as_ref().ok(), "error": current.as_ref().err().map(ToString::to_string), "function": function, "input": function.and_then(FunctionGraph::input_identifier), + "inheritance": inheritance, "warnings": function.map(|function| crate::function_inspection::warnings_for(graph, &target.function_target(), function)).unwrap_or_default()})) +} diff --git a/crates/engine/src/parameter_target.rs b/crates/engine/src/parameter_target.rs new file mode 100644 index 0000000..6c9eb7d --- /dev/null +++ b/crates/engine/src/parameter_target.rs @@ -0,0 +1,136 @@ +use crate::{ + FunctionGraphTarget, Result, Session, + commands::{bad, node_param, strp}, +}; +use materialcraft_core::{BaseParameter, BaseParameters, FunctionGraph, Graph, NodeId, Value}; +use materialcraft_nodes::ParameterDescriptor; +use serde_json::Value as Json; + +#[derive(Clone, Debug)] +pub(crate) enum ParameterTarget { + Base { node: NodeId, parameter: BaseParameter }, + Specific { node: NodeId, parameter: String }, +} + +impl ParameterTarget { + pub(crate) fn resolve(session: &Session, command: &str, parameters: &Json) -> Result { + let node = node_param(session, command, parameters, "id")?; + let parameter = strp(parameters, "param").ok_or_else(|| bad(command, "param is required"))?; + if parameters.get("base").and_then(Json::as_bool) == Some(true) { + let parameter = BaseParameter::named(parameter).ok_or_else(|| bad(command, "unknown base parameter"))?; + Ok(Self::Base { node, parameter }) + } else { + Ok(Self::Specific { node, parameter: parameter.into() }) + } + } + + pub(crate) fn node(&self) -> NodeId { + match self { + Self::Base { node, .. } | Self::Specific { node, .. } => *node, + } + } + + pub(crate) fn identifier(&self) -> &str { + match self { + Self::Base { parameter, .. } => parameter.identifier(), + Self::Specific { parameter, .. } => parameter, + } + } + + pub(crate) fn descriptor(&self, session: &Session, command: &str) -> Result { + let node = session.graph()?.node(self.node())?; + match self { + Self::Base { parameter, .. } => Ok(ParameterDescriptor::base(*parameter)), + Self::Specific { parameter, .. } => { + ParameterDescriptor::for_node(&session.pkg, node, parameter).ok_or_else(|| bad(command, format!("{} has no parameter `{parameter}`", node.def))) + } + } + } + + pub(crate) fn function<'a>(&self, graph: &'a Graph) -> Option<&'a FunctionGraph> { + let node = graph.node(self.node()).ok()?; + match self { + Self::Base { parameter, .. } => node.base.functions.get(parameter), + Self::Specific { parameter, .. } => node.functions.get(parameter), + } + } + + pub(crate) fn current_value(&self, session: &Session, descriptor: &ParameterDescriptor) -> Result { + let graph = session.graph()?; + let node = graph.node(self.node())?; + if self.function(graph).is_some() { + let decoder = session.resource_decoder(); + let mut options = materialcraft_eval::Options::new(&decoder); + options.environment = session.environment; + options.max_size = session.preview_size; + options.only = Some(vec![self.node()]); + let cooked = materialcraft_eval::cook(&session.pkg, session.graph, &options, &session.cache); + let result = cooked.nodes.get(&self.node()).ok_or_else(|| bad("graph.node.function", "parameter owner was not evaluated"))?; + if let Some(error) = &result.error { + return Err(bad("graph.node.function", error.clone())); + } + + let value = match self { + Self::Base { parameter, .. } => result.base_values.get(parameter), + Self::Specific { parameter, .. } => result.parameters.get(parameter), + }; + return value.cloned().ok_or_else(|| bad("graph.node.function", "parameter function did not produce a value")); + } + + Ok(match self { + Self::Base { parameter, .. } => parameter.value(&node.base), + Self::Specific { parameter, .. } => node + .bindings + .get(parameter) + .and_then(|input| graph.input_value(input)) + .or_else(|| node.params.get(parameter)) + .cloned() + .unwrap_or_else(|| descriptor.default.clone()), + }) + } + + pub(crate) fn set_function(&self, graph: &mut Graph, function: FunctionGraph) -> Result<()> { + let node = graph.node_mut(self.node())?; + match self { + Self::Base { parameter, .. } => { + node.base.functions.insert(*parameter, function); + } + Self::Specific { parameter, .. } => { + node.bindings.remove(parameter); + node.functions.insert(parameter.clone(), function); + } + } + + Ok(()) + } + + pub(crate) fn clear(&self, graph: &mut Graph, reset: bool) -> Result<()> { + let node = graph.node_mut(self.node())?; + match self { + Self::Base { parameter, .. } => { + node.base.functions.remove(parameter); + if reset { + let defaults = BaseParameters::default(); + parameter.set_value(&mut node.base, ¶meter.value(&defaults)).map_err(|error| bad("graph.node.reset", error))?; + parameter.set_inheritance(&mut node.base, parameter.inheritance(&defaults)); + } + } + Self::Specific { parameter, .. } => { + node.functions.remove(parameter); + node.bindings.remove(parameter); + if reset { + node.params.remove(parameter); + } + } + } + + Ok(()) + } + + pub(crate) fn function_target(&self) -> FunctionGraphTarget { + match self { + Self::Base { node, parameter } => FunctionGraphTarget::Base { node: *node, parameter: *parameter }, + Self::Specific { node, parameter } => FunctionGraphTarget::Dynamic { node: *node, parameter: parameter.clone() }, + } + } +} diff --git a/crates/engine/tests/it/exposed_inputs.rs b/crates/engine/tests/it/exposed_inputs.rs index e11f09d..1439f25 100644 --- a/crates/engine/tests/it/exposed_inputs.rs +++ b/crates/engine/tests/it/exposed_inputs.rs @@ -19,10 +19,120 @@ fn exposing_the_same_parameter_on_two_nodes_gives_each_its_own_input() { let graph = s.graph().unwrap(); assert_eq!(graph.exposed.iter().map(|e| e.id.as_str()).collect::>(), ids); for (node, id) in nodes.iter().zip(&ids) { - assert_eq!(graph.node(*node).unwrap().bindings.get("opacity"), Some(id)); + assert_eq!(graph.node(*node).unwrap().functions["opacity"].input_identifier(), Some(id.as_str())); } // An explicit id still has to be free, and an unbound input still needs one assert!(execute(&mut s, "graph.exposed.add", &json!({"id": "opacity_1", "bind": {"node": nodes[0].0, "param": "opacity"}})).is_err()); assert!(execute(&mut s, "graph.exposed.add", &json!({"default": 0.5})).is_err()); } + +#[test] +fn base_parameters_cannot_be_exposed_as_graph_inputs() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].clone(); + let original = session.graph().unwrap().clone(); + + let result = execute(&mut session, "graph.exposed.add", &json!({"bind": {"node": owner, "param": "randomseed", "base": true}})); + + assert!(result.is_err(), "exposure belongs to Specific Parameters"); + assert_eq!(*session.graph().unwrap(), original); +} + +#[test] +fn exposed_input_settings_survive_sbs_and_undo() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].clone(); + let original = session.graph().unwrap().clone(); + execute( + &mut session, + "graph.exposed.add", + &json!({ + "id": "radius", "label": "Radius", "group": "Surface/Blur", "description": "Controls the radius", + "editor": "input", "default": 10.0, "min": 0.0, "max": 32.0, "clamp": true, "step": 0.25, + "bind": {"node": owner, "param": "intensity"} + }), + ) + .unwrap(); + + let input = serde_json::to_value(&session.graph().unwrap().exposed[0]).unwrap(); + assert_eq!(input["description"], "Controls the radius"); + assert_eq!(input["editor"], "input"); + assert_eq!(input["clamp"], true); + assert_eq!(input["step"], 0.25); + let bytes = materialcraft_engine::formats::sbs::write_sbs(&session.pkg).unwrap(); + let reopened = materialcraft_engine::formats::sbs::read_sbs(&bytes, "exposed.sbs", &|_| None).unwrap(); + assert_eq!(reopened.pkg.graphs[0].exposed, session.graph().unwrap().exposed); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(*session.graph().unwrap(), original); +} + +#[test] +fn preparing_an_input_is_read_only_and_invalid_settings_are_atomic() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].clone(); + execute(&mut session, "graph.node.param", &json!({"id": owner, "param": "intensity", "value": 10.0})).unwrap(); + let original = session.graph().unwrap().clone(); + let binding = json!({"node": owner, "param": "intensity"}); + + let draft = execute(&mut session, "graph.exposed.prepare", &json!({"bind": binding})).unwrap(); + + assert_eq!(draft["id"], "intensity"); + assert_eq!(draft["label"], "Intensity"); + assert_eq!(draft["default"], json!({"t": "float", "v": 10.0})); + assert_eq!(*session.graph().unwrap(), original); + for changes in [ + json!({"step": 0.0}), + json!({"step": -0.01}), + json!({"min": 3.0, "max": 2.0}), + json!({"id": "bad id"}), + json!({"editor": "toggle"}), + json!({"default": {"t": "float", "v": 1e39}}), + ] { + let mut parameters = changes; + parameters["bind"] = binding.clone(); + assert!(execute(&mut session, "graph.exposed.add", ¶meters).is_err(), "{parameters}"); + assert_eq!(*session.graph().unwrap(), original); + } +} + +#[test] +fn color_and_enum_exposure_preserve_their_editors_and_defaults() { + let mut session = new_session(); + let uniform = execute(&mut session, "graph.node.add", &json!({"def": "uniform"})).unwrap()["id"].clone(); + let blend = execute(&mut session, "graph.node.add", &json!({"def": "blend"})).unwrap()["id"].clone(); + execute(&mut session, "graph.exposed.add", &json!({"editor": "input", "bind": {"node": uniform, "param": "color"}})).unwrap(); + execute(&mut session, "graph.exposed.add", &json!({"bind": {"node": blend, "param": "mode"}})).unwrap(); + + let bytes = materialcraft_engine::formats::sbs::write_sbs(&session.pkg).unwrap(); + let reopened = materialcraft_engine::formats::sbs::read_sbs(&bytes, "editors.sbs", &|_| None).unwrap(); + + let mut inputs = reopened.pkg.graphs[0].exposed.clone(); + let expected = &session.graph().unwrap().exposed; + let color = inputs[0].default.as_vec4().unwrap(); + let original = expected[0].default.as_vec4().unwrap(); + assert!(color.iter().zip(original).all(|(left, right)| (left - right).abs() < 1e-6)); + inputs[0].default = expected[0].default.clone(); + assert_eq!(&inputs, expected); + assert_eq!(reopened.pkg.graphs[0].exposed[0].editor(), materialcraft_engine::core::ParameterEditor::Input); + assert_eq!(reopened.pkg.graphs[0].exposed[1].editor(), materialcraft_engine::core::ParameterEditor::Dropdown); +} + +#[test] +fn deleting_an_exposed_input_detaches_its_parameter_functions_and_undo_restores_them() { + let mut session = new_session(); + let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); + execute(&mut session, "graph.node.param", &json!({"id": owner, "param": "intensity", "value": 2.0})).unwrap(); + execute(&mut session, "graph.exposed.add", &json!({"id": "radius", "default": 3.0, "bind": {"node": owner, "param": "intensity"}})).unwrap(); + let original = session.graph().unwrap().clone(); + + execute(&mut session, "graph.exposed.delete", &json!({"id": "radius"})).unwrap(); + session.cook(); + + assert_eq!(session.cooked.nodes[&owner].error, None); + assert!(session.graph().unwrap().node(owner).unwrap().functions.is_empty()); + assert_eq!(session.cooked.nodes[&owner].parameters.get("intensity"), Some(&materialcraft_engine::core::Value::Float(2.0))); + execute(&mut session, "edit.undo", &json!({})).unwrap(); + assert_eq!(*session.graph().unwrap(), original); +} diff --git a/crates/engine/tests/it/function_instances.rs b/crates/engine/tests/it/function_instances.rs index 2c95e06..3554ca5 100644 --- a/crates/engine/tests/it/function_instances.rs +++ b/crates/engine/tests/it/function_instances.rs @@ -11,6 +11,10 @@ fn source() -> Package { let mut package = Package::new("Functions"); let mut graph = Graph::new("Twice"); graph.exposed.push(ExposedParameter { + description: String::new(), + editor: None, + clamp: false, + step: None, id: "amount".into(), label: "Amount".into(), group: String::new(), diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index a1e6be5..e5d2997 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -24,6 +24,7 @@ mod node_library; mod normal_maps; mod open_documents; mod optimization_perf; +mod parameter_functions; mod pattern_graph; mod perf; mod reset_drivers; diff --git a/crates/engine/tests/it/parameter_functions.rs b/crates/engine/tests/it/parameter_functions.rs new file mode 100644 index 0000000..2aed371 --- /dev/null +++ b/crates/engine/tests/it/parameter_functions.rs @@ -0,0 +1,391 @@ +use materialcraft_engine::{ + Session, + core::{FunctionGraph, NodeId, Value}, + execute, formats, new_session, +}; +use serde_json::{Value as Json, json}; + +fn command(session: &mut Session, name: &str, parameters: Json) -> Json { + execute(session, name, ¶meters).unwrap() +} + +fn node(session: &mut Session, definition: &str) -> NodeId { + NodeId(command(session, "graph.node.add", json!({"def": definition}))["id"].as_u64().unwrap()) +} + +#[test] +fn output_size_function_controls_resolution_and_survives_sbs() { + let mut session = new_session(); + session.preview_size = None; + command(&mut session, "graph.size", json!({"width": 64, "height": 64})); + let owner = node(&mut session, "uniform"); + let function = FunctionGraph::constant(Value::Int2([1, -1])); + + command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "function": function})); + + let cooked = session.cook(); + let image = cooked.image(owner, 0).unwrap(); + assert_eq!((image.w, image.h), (128, 32)); + assert!(cooked.nodes[&owner].error.is_none()); + + let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); + let loaded = formats::sbs::read_sbs(&bytes, "parameter-functions.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); + let mut reopened = Session::new(loaded.pkg); + reopened.preview_size = None; + let owner = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "uniform").unwrap().id; + let cooked = reopened.cook(); + let image = cooked.image(owner, 0).unwrap(); + assert_eq!((image.w, image.h), (128, 32)); +} + +#[test] +fn empty_creation_has_no_output_and_constant_creation_uses_the_current_value() { + let mut session = new_session(); + let owner = node(&mut session, "blur"); + command(&mut session, "graph.node.param", json!({"id": owner, "param": "intensity", "value": 7.0})); + + command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "mode": "empty"})); + + let function = &session.graph().unwrap().node(owner).unwrap().functions["intensity"]; + assert!(function.nodes.is_empty()); + assert_eq!(function.output, None); + + command(&mut session, "edit.undo", json!({})); + command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "mode": "constant"})); + + let function = &session.graph().unwrap().node(owner).unwrap().functions["intensity"]; + assert_eq!(function.nodes.len(), 1); + assert_eq!(function.nodes[0].value, Some(Value::Float(7.0))); + assert_eq!(function.output, Some(function.nodes[0].id)); +} + +#[test] +fn exposed_parameters_are_editable_get_functions() { + let mut session = new_session(); + let owner = node(&mut session, "blend"); + + command(&mut session, "graph.exposed.add", json!({"id": "amount", "bind": {"node": owner, "param": "opacity"}})); + + let function = &session.graph().unwrap().node(owner).unwrap().functions["opacity"]; + let output = function.node(function.output.unwrap()).unwrap(); + assert_eq!(output.op, "get_float1"); + assert_eq!(output.value, Some(Value::Text("amount".into()))); +} + +#[test] +fn native_dynamic_output_size_is_not_discarded_on_load() { + let xml = br#" + + + + + + "#; + let loaded = formats::sbs::read_sbs(xml, "original.sbs", &|_| None).unwrap(); + let mut session = Session::new(loaded.pkg); + session.preview_size = None; + let owner = session.graph().unwrap().nodes[0].id; + + let cooked = session.cook(); + + let image = cooked.image(owner, 0).unwrap(); + assert_eq!((image.w, image.h), (64, 32)); +} + +#[test] +fn inherited_size_functions_use_nominal_input_size_before_preview_capping() { + use materialcraft_engine::core::{BaseParameter, ValueType}; + + let mut session = new_session(); + session.preview_size = Some(16); + command(&mut session, "graph.size", json!({"width": 64, "height": 64})); + let source = node(&mut session, "uniform"); + command( + &mut session, + "graph.node.function", + json!({"id": source, "base": true, "param": "outputsize", "function": FunctionGraph::constant(Value::Int2([1, 0]))}), + ); + let owner = NodeId(command(&mut session, "graph.node.add", json!({"def": "blur", "connectFrom": {"node": source}}))["id"].as_u64().unwrap()); + let unrelated = node(&mut session, "uniform"); + let mut function = FunctionGraph::input("$sizelog2", ValueType::Float2); + let size = function.output.unwrap(); + let parent = function.add_constant(Value::Float2([6.0, 6.0])); + let difference = function.add("sub", &[size, parent], None); + function.output = Some(function.add("toint2", &[difference], None)); + command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "function": function})); + + let cooked = session.cook(); + + assert_eq!(cooked.nodes[&owner].error, None); + assert_eq!(cooked.nodes[&owner].base.size, [256, 64]); + assert_eq!(cooked.nodes[&owner].base_values[&BaseParameter::OutputSize], Value::Int2([1, 0])); + assert_eq!((cooked.image(owner, 0).unwrap().w, cooked.image(owner, 0).unwrap().h), (16, 4)); + + command( + &mut session, + "graph.node.function", + json!({"id": source, "base": true, "param": "outputsize", "function": FunctionGraph::constant(Value::Int2([0, 0]))}), + ); + let cooked = session.cook(); + + assert_eq!(cooked.nodes[&owner].base.size, [64, 64]); + assert!(!cooked.nodes[&owner].cached); + assert!(cooked.nodes[&unrelated].cached); +} + +#[test] +fn every_base_function_preserves_its_type_inheritance_and_value_in_sbs() { + use materialcraft_engine::core::{BaseParameter, ParameterInheritance}; + + let mut session = new_session(); + session.preview_size = Some(16); + let owner = node(&mut session, "uniform"); + let cases = [ + (BaseParameter::OutputSize, Value::Int2([6, 5])), + (BaseParameter::Format, Value::Int(3)), + (BaseParameter::PixelSize, Value::Float2([0.25, 0.5])), + (BaseParameter::PixelRatio, Value::Int(1)), + (BaseParameter::Tiling, Value::Int(2)), + (BaseParameter::RandomSeed, Value::Int(23)), + ]; + for (parameter, value) in &cases { + command(&mut session, "graph.node.base", json!({"id": owner, "param": parameter.identifier(), "inheritance": "absolute"})); + command( + &mut session, + "graph.node.function", + json!({"id": owner, "base": true, "param": parameter.identifier(), "function": FunctionGraph::constant(value.clone())}), + ); + } + + let saved = formats::sbs::write_sbs(&session.pkg).unwrap(); + let loaded = formats::sbs::read_sbs(&saved, "base-functions.sbs", &|_| None).unwrap(); + assert!(loaded.warnings.is_empty(), "{:?}", loaded.warnings); + let mut reopened = Session::new(loaded.pkg); + reopened.preview_size = Some(16); + let owner = reopened.graph().unwrap().nodes[0].id; + for (parameter, _) in &cases { + assert_eq!(parameter.inheritance(&reopened.graph().unwrap().node(owner).unwrap().base), ParameterInheritance::Absolute); + } + let result = &reopened.cook().nodes[&owner]; + + assert_eq!(result.error, None); + for (parameter, value) in cases { + assert_eq!(result.base_values[¶meter], value); + } + assert_eq!(result.base.size, [64, 32]); + assert_eq!(result.base.seed, 23); + assert_eq!(result.base.pixel_size, [0.25, 0.5]); + assert_eq!(result.base.tiling, [false, true]); + assert_eq!(result.base.pixel_ratio, 1); + assert_eq!(result.base.format, materialcraft_engine::core::OutputFormat::F32); +} + +#[test] +fn constant_replacement_freezes_the_driven_value_and_reset_is_undoable() { + let mut session = new_session(); + session.preview_size = Some(16); + let owner = node(&mut session, "blur"); + command(&mut session, "graph.exposed.add", json!({"id": "amount", "bind": {"node": owner, "param": "intensity"}})); + command(&mut session, "graph.exposed.set", json!({"id": "amount", "value": 3.0})); + + command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "mode": "constant"})); + command(&mut session, "graph.exposed.set", json!({"id": "amount", "value": 8.0})); + + assert_eq!(session.cook().nodes[&owner].parameters["intensity"], Value::Float(3.0)); + let before = session.pkg.clone(); + command(&mut session, "graph.node.reset", json!({"id": owner, "param": "intensity"})); + assert!(!session.graph().unwrap().node(owner).unwrap().functions.contains_key("intensity")); + command(&mut session, "edit.undo", json!({})); + assert_eq!(session.pkg, before); + command(&mut session, "graph.node.param", json!({"id": owner, "param": "intensity", "value": 2.0})); + assert!(!session.graph().unwrap().node(owner).unwrap().functions.contains_key("intensity")); + assert_eq!(session.cook().nodes[&owner].parameters["intensity"], Value::Float(2.0)); +} + +#[test] +fn empty_and_wrong_type_functions_remain_editable_but_report_cook_errors() { + let mut session = new_session(); + session.preview_size = Some(16); + let owner = node(&mut session, "uniform"); + for function in [FunctionGraph::default(), FunctionGraph::constant(Value::Float(2.0))] { + command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "function": function})); + + assert!(session.cook().nodes[&owner].error.is_some()); + let info = command(&mut session, "graph.node.parameterInfo", json!({"id": owner, "base": true, "param": "outputsize"})); + assert_eq!(info["expectedType"], "Integer2"); + assert!(!info["warnings"].as_array().unwrap().is_empty()); + command(&mut session, "graph.node.function.edit", json!({"id": owner, "base": true, "param": "outputsize"})); + let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); + let loaded = formats::sbs::read_sbs(&bytes, "incomplete.sbs", &|_| None).unwrap(); + assert_eq!(loaded.pkg.graphs[0].nodes[0].base.functions.values().next().unwrap().nodes.len(), function.nodes.len()); + } +} + +#[test] +fn instance_parameter_functions_work_without_stored_literals_and_use_instance_size() { + use materialcraft_engine::core::{Graph, Package, ValueType}; + + let mut source = Graph::new("Source"); + let color = source.add_node("uniform", [0.0; 2]); + 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 { + description: String::new(), + editor: None, + clamp: false, + step: None, + id: "amount".into(), + label: "Amount".into(), + group: String::new(), + default: Value::Float4([0.2; 4]), + min: 0.0, + max: 1.0, + options: Vec::new(), + }); + let output = source.add_node("output", [200.0, 0.0]); + source.connect(color, "output", output, "input").unwrap(); + let dimensions = source.add_node("value_processor", [0.0; 2]); + source.node_mut(dimensions).unwrap().params.insert("function".into(), Value::Function(Box::new(FunctionGraph::input("$size", ValueType::Float2)))); + let size_output = source.add_node("output", [200.0, 200.0]); + source.node_mut(size_output).unwrap().params.insert("identifier".into(), Value::Text("dimensions".into())); + source.connect(dimensions, "output", size_output, "input").unwrap(); + let mut parent = Graph::new("Parent"); + parent.size = [6, 5]; + let owner = parent.add_node("graph_instance", [0.0; 2]); + parent.node_mut(owner).unwrap().params.insert("graph".into(), Value::Text("Source".into())); + let mut package = Package::new("Instances"); + package.graphs = vec![parent, source]; + let mut session = Session::new(package); + session.preview_size = None; + command(&mut session, "graph.node.function", json!({"id": owner, "param": "amount", "function": FunctionGraph::constant(Value::Float4([0.75; 4]))})); + + let result = session.cook(); + + assert_eq!(result.nodes[&owner].error, None); + assert!(result.nodes[&owner].outputs.iter().any(|output| output.as_value() == Some(&Value::Float2([64.0, 32.0])))); + assert!((result.image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6); + assert_eq!((result.image(owner, 0).unwrap().w, result.image(owner, 0).unwrap().h), (64, 32)); + assert!(!session.graph().unwrap().node(owner).unwrap().params.contains_key("amount")); + + let bytes = formats::sbs::write_sbs(&session.pkg).unwrap(); + let loaded = formats::sbs::read_sbs(&bytes, "instance.sbs", &|_| None).unwrap(); + let mut reopened = Session::new(loaded.pkg); + let owner = reopened.graph().unwrap().nodes[0].id; + assert!((reopened.cook().image(owner, 0).unwrap().get_gray(0, 0, false) - 0.75).abs() < 1e-6); +} + +#[test] +fn color_boolean_enum_and_text_parameters_use_typed_function_outputs() { + let mut session = new_session(); + session.preview_size = Some(16); + for (definition, parameter, value) in [ + ("uniform", "color", Value::Float4([0.2, 0.4, 0.6, 1.0])), + ("uniform", "color_mode", Value::Bool(false)), + ("blend", "mode", Value::Int(2)), + ("text", "text", Value::Text("Original".into())), + ] { + let owner = node(&mut session, definition); + command(&mut session, "graph.node.function", json!({"id": owner, "param": parameter, "function": FunctionGraph::constant(value.clone())})); + + let result = &session.cook().nodes[&owner]; + assert_eq!(result.error, None, "{parameter}"); + let expected = materialcraft_engine::nodes::find(definition).unwrap().param(parameter).unwrap().default.coerce_json(&json!(value)).unwrap(); + assert_eq!(result.parameters[parameter], expected); + } + + let owner = node(&mut session, "uniform"); + command(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": FunctionGraph::constant(Value::Float(0.5))})); + assert!(session.cook().nodes[&owner].error.as_ref().unwrap().contains("Float4")); + let bitmap = node(&mut session, "bitmap"); + assert!(execute(&mut session, "graph.node.function", &json!({"id": bitmap, "param": "resource"})).is_err()); +} + +#[test] +fn base_functions_inherit_from_the_primary_input_and_bypasses_keep_input_dimensions() { + let mut session = new_session(); + session.preview_size = Some(16); + let foreground = node(&mut session, "uniform"); + command(&mut session, "graph.node.base", json!({"id": foreground, "sizeMode": "absolute", "size": [7, 6]})); + let background = node(&mut session, "uniform"); + command(&mut session, "graph.node.base", json!({"id": background, "sizeMode": "absolute", "size": [5, 5]})); + let blend = node(&mut session, "blend"); + session.graph_mut().unwrap().connect(foreground, "output", blend, "foreground").unwrap(); + session.graph_mut().unwrap().connect(background, "output", blend, "background").unwrap(); + command( + &mut session, + "graph.node.function", + json!({"id": blend, "param": "outputsize", "base": true, "function": FunctionGraph::constant(Value::Int2([1, 0]))}), + ); + + assert_eq!(session.cook().nodes[&blend].base.size, [64, 32]); + + let blur = NodeId(command(&mut session, "graph.node.add", json!({"def": "blur", "connectFrom": {"node": blend}}))["id"].as_u64().unwrap()); + command( + &mut session, + "graph.node.function", + json!({"id": blur, "param": "outputsize", "base": true, "function": FunctionGraph::constant(Value::Int2([-1, 0]))}), + ); + command(&mut session, "graph.node.disable", json!({"ids": [blur], "disabled": true})); + let output = NodeId(command(&mut session, "graph.node.add", json!({"def": "output", "connectFrom": {"node": blur}}))["id"].as_u64().unwrap()); + + assert_eq!(session.cook().nodes[&output].base.size, [64, 32]); + + command(&mut session, "graph.node.disable", json!({"ids": [blend], "disabled": true})); + + let cooked = session.cook(); + let image = cooked.image(blend, 0).unwrap(); + assert_eq!((image.w, image.h), (16, 16)); + assert_eq!(cooked.nodes[&blend].base.size, [32, 32]); + assert_eq!(cooked.nodes[&output].base.size, [32, 32]); +} + +#[test] +fn setting_a_base_literal_keeps_inheritance_and_removes_only_its_driver() { + use materialcraft_engine::core::{BaseParameter, ParameterInheritance}; + + let mut session = new_session(); + let owner = node(&mut session, "uniform"); + command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "format", "mode": "constant"})); + command(&mut session, "graph.node.function", json!({"id": owner, "base": true, "param": "outputsize", "mode": "constant"})); + + session.selection.clear(); + command(&mut session, "graph.node.base", json!({"id": owner, "param": "format", "value": 3})); + + let base = &session.graph().unwrap().node(owner).unwrap().base; + assert_eq!(BaseParameter::Format.inheritance(base), ParameterInheritance::RelativeToInput); + assert!(!base.functions.contains_key(&BaseParameter::Format)); + assert!(base.functions.contains_key(&BaseParameter::OutputSize)); +} + +#[test] +fn malformed_literals_do_not_change_a_native_parameter_functions_expected_type() { + let mut session = new_session(); + session.preview_size = Some(16); + let owner = node(&mut session, "blur"); + session.graph_mut().unwrap().node_mut(owner).unwrap().params.insert("intensity".into(), Value::Text("invalid".into())); + + command(&mut session, "graph.node.function", json!({"id": owner, "param": "intensity", "function": FunctionGraph::constant(Value::Float(2.0))})); + + let result = &session.cook().nodes[&owner]; + assert_eq!(result.error, None); + assert_eq!(result.parameters["intensity"], Value::Float(2.0)); +} + +#[test] +fn input_value_default_functions_follow_the_selected_value_type() { + let mut session = new_session(); + session.preview_size = Some(16); + let owner = node(&mut session, "input_value"); + session.selection.clear(); + command(&mut session, "graph.node.param", json!({"id": owner, "param": "default", "value": Value::Int2([3, 5])})); + + command(&mut session, "graph.node.function", json!({"id": owner, "param": "default", "mode": "constant"})); + + let info = command(&mut session, "graph.node.parameterInfo", json!({"id": owner, "param": "default"})); + assert_eq!(info["expectedType"], "Integer2"); + assert!(info["warnings"].as_array().unwrap().is_empty()); + let result = &session.cook().nodes[&owner]; + assert_eq!(result.error, None); + assert_eq!(result.outputs[0].as_value(), Some(&Value::Int2([3, 5]))); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 7e8000d..8aeef9b 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -252,23 +252,26 @@ fn panic_hunt() { #[test] fn dynamic_parameters_follow_graph_inputs() { - let mut s = sample_session(); - run(&mut s, "file.new", json!({"template": "empty"})); - let u = run(&mut s, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}}))["id"].as_u64().unwrap(); - run(&mut s, "graph.exposed.add", json!({"id": "level", "default": {"t": "float", "v": 0.25}})); - let f = json!({"nodes": [{"id": 1, "op": "get_float1", "value": {"t": "text", "v": "level"}}], "output": 1}); - run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "function": f})); - s.cook(); - let mean = |s: &Session| s.cooked.image(materialcraft_engine::core::NodeId(u), 0).unwrap().mean()[0]; - assert!((mean(&s) - 0.25).abs() < 1e-4, "{}", mean(&s)); - run(&mut s, "graph.exposed.set", json!({"id": "level", "value": 0.75})); - s.cook(); - assert!((mean(&s) - 0.75).abs() < 1e-4); - // Text parameters can't take functions; removing restores the plain value - assert!(execute(&mut s, "graph.node.function", &json!({"id": u, "param": "nope"})).is_err()); - run(&mut s, "graph.node.function", json!({"id": u, "param": "color", "remove": true})); - s.cook(); - assert!((mean(&s) - 0.5).abs() < 0.05); + use materialcraft_engine::core::{FunctionGraph, NodeId, Value, ValueType}; + + let mut session = sample_session(); + run(&mut session, "file.new", json!({"template": "empty"})); + let owner = NodeId(run(&mut session, "graph.node.add", json!({"def": "uniform", "params": {"color_mode": false}}))["id"].as_u64().unwrap()); + run(&mut session, "graph.exposed.add", json!({"id": "level", "default": Value::Float4([0.25; 4])})); + let function = FunctionGraph::input("level", ValueType::Float4); + run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": function})); + + let mean = session.cook().image(owner, 0).unwrap().mean()[0]; + assert!((mean - 0.25).abs() < 1e-4, "{mean}"); + run(&mut session, "graph.exposed.set", json!({"id": "level", "value": Value::Float4([0.75; 4])})); + let mean = session.cook().image(owner, 0).unwrap().mean()[0]; + assert!((mean - 0.75).abs() < 1e-4); + + // Removing the function restores the plain value + assert!(execute(&mut session, "graph.node.function", &json!({"id": owner, "param": "nope"})).is_err()); + run(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "remove": true})); + let mean = session.cook().image(owner, 0).unwrap().mean()[0]; + assert!((mean - 0.5).abs() < 0.05); } #[test] diff --git a/crates/eval/Cargo.toml b/crates/eval/Cargo.toml index 67db82e..e30a1ef 100644 --- a/crates/eval/Cargo.toml +++ b/crates/eval/Cargo.toml @@ -13,3 +13,4 @@ materialcraft-core = { workspace = true } materialcraft-image = { workspace = true } materialcraft-nodes = { workspace = true } serde_json = { workspace = true } +serde = { workspace = true } diff --git a/crates/eval/src/graph_execution.rs b/crates/eval/src/graph_execution.rs index 7a84fa0..9f1b364 100644 --- a/crates/eval/src/graph_execution.rs +++ b/crates/eval/src/graph_execution.rs @@ -49,7 +49,7 @@ pub fn cook(package: &Package, graph_index: usize, options: &Options, cache: &Mu } let Some(node) = prepared.index.node(id) else { continue }; - let result = cook_node(package, graph_index, graph, &prepared, node, &cooked, &variables, options, cache); + let result = cook_node(package, graph_index, &prepared, node, &cooked, &variables, options, cache); cooked.nodes.insert(id, result); } cooked.ms = (now_ms() - started_ms) as f32; diff --git a/crates/eval/src/graph_instance.rs b/crates/eval/src/graph_instance.rs index d5928db..db0fd83 100644 --- a/crates/eval/src/graph_instance.rs +++ b/crates/eval/src/graph_instance.rs @@ -73,6 +73,7 @@ pub(crate) fn cook_instance( o.environment = opts.environment; o.parent_tiling = Some(base.tiling); o.parent_pixel_ratio = Some(base.pixel_ratio); + o.parent_base = Some(base); o.registry = Some(registry); o.resource_root = Some(root_resource); o.max_size = opts.max_size; diff --git a/crates/eval/src/lib.rs b/crates/eval/src/lib.rs index aee7360..cc1cfdf 100644 --- a/crates/eval/src/lib.rs +++ b/crates/eval/src/lib.rs @@ -14,6 +14,7 @@ mod node_result; mod node_size; mod options; mod parameter; +mod parameter_function; mod port; mod ports; mod prepared_graph; @@ -34,6 +35,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 resolved_base_parameters::ResolvedBaseParameters; pub use resource_decoder::ResourceDecoder; pub use time::now_ms; pub use value_input_label::value_input_label; diff --git a/crates/eval/src/node_execution.rs b/crates/eval/src/node_execution.rs index de70ee8..f94f790 100644 --- a/crates/eval/src/node_execution.rs +++ b/crates/eval/src/node_execution.rs @@ -1,4 +1,4 @@ -use crate::{Cache, Cooked, NodeOutput, NodeResult, Options, identifier, node_size, now_ms}; +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, @@ -6,7 +6,7 @@ use crate::{ prepared_graph::PreparedGraph, value_execution::evaluate_value, }; -use materialcraft_core::{Graph, Node, Package, Value}; +use materialcraft_core::{Node, Package, Value}; use materialcraft_image::{Image, Kind}; use materialcraft_nodes::{CookContext, find}; use std::{ @@ -25,27 +25,27 @@ fn lock(cache: &Mutex) -> std::sync::MutexGuard<'_, Cache> { } pub(crate) fn cook_node( - pkg: &Package, - gi: usize, - graph: &Graph, + package: &Package, + graph_index: usize, prepared: &PreparedGraph<'_>, node: &Node, - done: &Cooked, - vars: &BTreeMap, - opts: &Options, + cooked: &Cooked, + graph_variables: &BTreeMap, + options: &Options, cache: &Mutex, ) -> NodeResult { - let (in_ports, out_ports) = prepared.ports(node.id); - let def = find(&node.def); + 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 incoming = Vec::new(); let mut input_keys = Vec::new(); - let mut variables = std::borrow::Cow::Borrowed(vars); + let mut variables = std::borrow::Cow::Borrowed(graph_variables); let mut input_error = None; - for port in in_ports { + for port in input_ports { let source = prepared.index.input_of(node.id, &port.id).and_then(|connection| { - let result = done.nodes.get(&connection.from)?; + 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))) }); @@ -80,76 +80,98 @@ pub(crate) fn cook_node( incoming.push(output); } - let base = prepared.base_parameters(node); - if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map") { - let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1); - variables.to_mut().insert("$tiling".into(), Value::Int(tiling)); - variables.to_mut().insert("$pixelratio".into(), Value::Int(base.pixel_ratio)); + + 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, &variables) { + 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 + { + base = input; } - let vars = &variables; - let first = prepared.first_input_size(node.id); - let (w, h) = node_size(graph, def, node, first, opts.max_size); - let fail = |msg: String, key: u64| NodeResult { - outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); out_ports.len().max(1)]), - error: Some(msg), + let (w, h) = crate::node_size::limit(base.size, options.max_size); + let fail = |message: String, key: u64| NodeResult { + base, + base_values: base_values.clone(), + parameters: BTreeMap::new(), + outputs: Arc::new(vec![NodeOutput::Image(error_image(w, h)); output_ports.len().max(1)]), + error: Some(message), ms: 0.0, key, cached: false, }; + if let Some(error) = base_error { + return fail(error, 0); + } if let Some(error) = input_error { return fail(error, 0); } - let seed = (graph.seed as u32).wrapping_mul(0x9e37_79b9).wrapping_add(node.base.seed as u32); - let params = match resolve_parameters(node, def, vars, seed, [w, h]) { + if !node.functions.is_empty() || matches!(node.def.as_str(), "pixel_processor" | "value_processor" | "fx_map") { + base.variables(variables.to_mut()); + } + + let variables = &variables; + let seed = base.seed; + let mut parameters = match resolve_parameters(package, node, definition, variables, seed, base.size) { Ok(parameters) => parameters, Err(error) => return fail(error, 0), }; let tile = base.tiling[0] && base.tiling[1]; + // Input nodes read the caller's image for their identifier - let input_img = node.def.starts_with("input_").then(|| opts.inputs.get(&identifier(node))).flatten(); - let res_hash = match params.get("resource") { - Some(Value::Text(name)) => pkg.resource(name).map_or(0, |r| r.bytes.content_hash()), + let input_image = node.def.starts_with("input_").then(|| options.inputs.get(&identifier(node))).flatten(); + let resource_hash = match parameters.get("resource") { + Some(Value::Text(name)) => package.resource(name).map_or(0, |r| r.bytes.content_hash()), _ => 0, }; - let registry = opts.registry.unwrap_or(pkg); - let sub_hash = if node.def == "graph_instance" { - crate::graph_instance::resolve(registry, pkg, node).map_or(0, |(source, index, _)| graph_tree_hash_with_registry(registry, source, index)) + let registry = options.registry.unwrap_or(package); + let subgraph_hash = if node.def == "graph_instance" { + crate::graph_instance::resolve(registry, package, node).map_or(0, |(source, index, _)| graph_tree_hash_with_registry(registry, source, index)) } else { 0 }; let key = hash_of(&( &node.def, - serde_json::to_string(¶ms).unwrap_or_default(), - (w, h, seed, tile, node.disabled, base.tiling, base.pixel_ratio), + 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)), &input_keys, - res_hash, - sub_hash, + resource_hash, + subgraph_hash, // A cached graph instance includes results evaluated with its host environment - (node.def == "graph_instance").then(|| serde_json::to_string(&opts.environment).unwrap_or_default()), - input_img.map(|image| image_key(image, cache)), - variable_key(node, ¶ms, vars), + (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), )); - if let Some(v) = lock(cache).get(key) { - return NodeResult { outputs: v, error: None, ms: 0.0, key, cached: true }; + 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 }; } - let t0 = now_ms(); + + let started_ms = now_ms(); let result: Result, String> = if node.disabled { - let output = incoming.iter().find_map(|output| *output).cloned().unwrap_or_else(|| NodeOutput::Image(Image::filled(w, h, Kind::Gray, [0.0; 4]))); - Ok(vec![output; out_ports.len().max(1)]) + let input = if let Some(primary) = definition.and_then(|definition| definition.primary_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]))); + Ok(vec![output; output_ports.len().max(1)]) } else if node.def == "input_value" { - let value = vars.get(&identifier(node)).or_else(|| params.get("default")).cloned().unwrap_or(Value::Float(0.0)); + 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(¶ms, vars, seed, [w, h], &inputs, tile).map(|value| vec![NodeOutput::Value(value)]) + 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_img { + } else if let Some(image) = input_image { let image = image.resize(w, h, tile); let image = if node.def == "input_grayscale" { image.to_gray() } else { image }; @@ -159,21 +181,23 @@ pub(crate) fn cook_node( Err(format!("unsupported node `{name}`")) } else if node.def == "graph_instance" { - cook_instance(pkg, gi, node, in_ports, out_ports, &incoming, ¶ms, (w, h), base, opts, cache) - } else if let Some(definition) = def { - let context = CookContext { w, h, seed, tile, inputs: &inputs, params: ¶ms, resource: opts.resource, vars }; + 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 { w, h, seed, tile, inputs: &inputs, params: ¶meters, resource: options.resource, vars: variables }; (definition.cook)(&context).map(|images| images.into_iter().map(NodeOutput::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()); match result { - Ok(imgs) if imgs.len() == out_ports.len().max(1) || out_ports.is_empty() => { - let v = Arc::new(imgs); - lock(cache).put(key, v.clone()); - NodeResult { outputs: v, error: None, ms: (now_ms() - t0) as f32, key, cached: false } + 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 } } - Ok(imgs) => fail(format!("`{}` made {} images for {} outputs", node.def, imgs.len(), out_ports.len()), key), - Err(e) => fail(e, key), + Ok(outputs) => fail(format!("`{}` made {} images for {} outputs", node.def, outputs.len(), output_ports.len()), key), + Err(error) => fail(error, key), } } diff --git a/crates/eval/src/node_result.rs b/crates/eval/src/node_result.rs index ae9a373..6dff9e3 100644 --- a/crates/eval/src/node_result.rs +++ b/crates/eval/src/node_result.rs @@ -4,6 +4,10 @@ use std::sync::Arc; /// One node's cooked result #[derive(Clone, Debug)] pub struct NodeResult { + pub base: crate::ResolvedBaseParameters, + pub base_values: std::collections::BTreeMap, + /// Evaluated scalar and vector parameters, excluding authoring graphs and curves + pub parameters: std::collections::BTreeMap, /// One image per output port (empty when the cook failed) pub outputs: Arc>, pub error: Option, diff --git a/crates/eval/src/node_size.rs b/crates/eval/src/node_size.rs index 9de723e..ac6823d 100644 --- a/crates/eval/src/node_size.rs +++ b/crates/eval/src/node_size.rs @@ -1,33 +1,23 @@ -use materialcraft_core::{Graph, Node, SizeMode}; +use materialcraft_core::{Graph, Node}; use materialcraft_nodes::NodeDefinition; -/// Output size of `node` given its first connected input's size -pub fn node_size(graph: &Graph, def: Option<&NodeDefinition>, node: &Node, input: Option<(u32, u32)>, max: Option) -> (u32, u32) { - let parent = graph.size_px(); - let (bw, bh) = match node.base.size_mode { - SizeMode::Absolute => { - let s = |l: i32| 1u32 << l.clamp(4, 13); - (s(node.base.size[0]), s(node.base.size[1])) - } - mode => { - let base = match (mode, input, def.is_some_and(|d| d.generator)) { - (SizeMode::RelativeToInput, Some(i), false) => i, - _ => (parent[0], parent[1]), - }; +/// Literal output size; cooking also evaluates any attached parameter function +pub fn node_size(graph: &Graph, definition: Option<&NodeDefinition>, node: &Node, input: Option<(u32, u32)>, maximum: Option) -> (u32, u32) { + let parent = crate::ResolvedBaseParameters { size: graph.size_px(), ..Default::default() }; + let input = input + .filter(|_| !definition.is_some_and(|definition| definition.generator)) + .map(|(width, height)| crate::ResolvedBaseParameters { size: [width, height], ..parent }); + let resolved = crate::ResolvedBaseParameters::resolve(&node.base, input, parent); - let sh = |v: u32, o: i32| { - let v = v as f64 * 2f64.powi(o.clamp(-12, 12)); - v.round().clamp(16.0, 8192.0) as u32 - }; - (sh(base.0, node.base.size[0]), sh(base.1, node.base.size[1])) - } - }; + limit(resolved.size, maximum) +} - match max { - Some(m) if bw.max(bh) > m => { - let k = m as f64 / bw.max(bh) as f64; - (((bw as f64 * k).round() as u32).max(1), ((bh as f64 * k).round() as u32).max(1)) +pub(crate) fn limit([width, height]: [u32; 2], maximum: Option) -> (u32, u32) { + match maximum { + Some(maximum) if width.max(height) > maximum => { + let scale = f64::from(maximum.max(1)) / f64::from(width.max(height)); + (((f64::from(width) * scale).round() as u32).max(1), ((f64::from(height) * scale).round() as u32).max(1)) } - _ => (bw, bh), + _ => (width, height), } } diff --git a/crates/eval/src/options.rs b/crates/eval/src/options.rs index 91d0bd5..8505d4d 100644 --- a/crates/eval/src/options.rs +++ b/crates/eval/src/options.rs @@ -8,6 +8,7 @@ pub struct Options<'a> { pub environment: materialcraft_core::EvaluationEnvironment, pub parent_tiling: Option<[bool; 2]>, pub parent_pixel_ratio: Option, + pub parent_base: Option, /// Cap on the larger side of every node's output (previews); `None` = full size pub max_size: Option, /// Cook only these nodes and what they depend on (`None` = the whole graph) @@ -34,6 +35,7 @@ impl<'a> Options<'a> { environment: Default::default(), parent_tiling: None, parent_pixel_ratio: None, + parent_base: None, max_size: None, only: None, inputs: BTreeMap::new(), diff --git a/crates/eval/src/parameter.rs b/crates/eval/src/parameter.rs index 4005a93..687e99b 100644 --- a/crates/eval/src/parameter.rs +++ b/crates/eval/src/parameter.rs @@ -1,59 +1,54 @@ -use materialcraft_core::{Node, Value}; -use materialcraft_nodes::{NodeDefinition, clamp_params, resolve_params}; +use materialcraft_core::{Node, Package, Value, ValueType}; +use materialcraft_nodes::{NodeDefinition, ParameterDescriptor, clamp_params, resolve_params}; use std::collections::BTreeMap; pub(crate) fn resolve_parameters( + package: &Package, node: &Node, - def: Option<&NodeDefinition>, - vars: &BTreeMap, + definition: Option<&NodeDefinition>, + variables: &BTreeMap, seed: u32, size: [u32; 2], ) -> Result, String> { - // Parameters: defaults, overrides, then bindings to exposed inputs - let mut params = match def { - Some(d) if node.def != "graph_instance" => resolve_params(d, &node.params), - _ => node.params.clone(), + let mut parameters = match definition { + Some(definition) if node.def != "graph_instance" => resolve_params(definition, &node.params), + _ => { + let mut parameters = node.instance.as_ref().map(|instance| instance.defaults.clone()).unwrap_or_default(); + parameters.extend(node.params.clone()); + parameters + } }; - - for (param, exposed) in &node.bindings { - if let (Some(v), Some(cur)) = (vars.get(exposed), params.get(param)) - && let Some(c) = cur.coerce_json(&serde_json::to_value(v).unwrap_or_default()) + for parameter in node.bindings.keys().chain(node.functions.keys()) { + if !parameters.contains_key(parameter) + && let Some(descriptor) = ParameterDescriptor::for_node(package, node, parameter) { - params.insert(param.clone(), c); + parameters.insert(parameter.clone(), descriptor.default); } } - // Dynamic parameters: functions of the graph's inputs, evaluated once per cook - for (param, f) in &node.functions { - let Some(cur) = params.get(param) else { continue }; - match materialcraft_nodes::function::compile(f, seed) { - Ok(prog) => { - let context = materialcraft_nodes::function::EvaluationContext { - scope: Default::default(), - position: [0.5; 2], - size: size.map(|side| side as f32), - images: &[], - tile: true, - variables: vars, - }; - - let value = match prog.evaluate(&context, &mut materialcraft_nodes::function::EvaluationState::default()) { - Ok(value) => value, - Err(error) => return Err(format!("function of `{param}`: {error}")), - }; - - if let Some(c) = cur.coerce_json(&serde_json::to_value(value).unwrap_or_default()) { - params.insert(param.clone(), c); - } - } - Err(e) => return Err(format!("function of `{param}`: {e}")), + for (parameter, exposed) in &node.bindings { + 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()) + { + parameters.insert(parameter.clone(), coerced); } } - // Hard limits on whatever files, bindings and functions supplied (a value can't hang a cook) - if let Some(d) = def + + 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 value = + crate::parameter_function::evaluate(function, expected, variables, seed, size).map_err(|error| format!("function of `{parameter}`: {error}"))?; + 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); + } + + // Catalog limits keep values from files and functions within safe cook bounds + if let Some(definition) = definition && node.def != "graph_instance" { - clamp_params(d, &mut params); + clamp_params(definition, &mut parameters); } - Ok(params) + + Ok(parameters) } diff --git a/crates/eval/src/parameter_function.rs b/crates/eval/src/parameter_function.rs new file mode 100644 index 0000000..63c09da --- /dev/null +++ b/crates/eval/src/parameter_function.rs @@ -0,0 +1,25 @@ +use materialcraft_core::{FunctionGraph, Value, ValueType}; +use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile}; +use std::collections::BTreeMap; + +pub(crate) fn evaluate(function: &FunctionGraph, expected: ValueType, variables: &BTreeMap, seed: u32, size: [u32; 2]) -> Result { + let program = compile(function, seed)?; + if program.output_type() != expected as u32 { + 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 value = program.evaluate(&context, &mut EvaluationState::default())?; + 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()); + } + + Ok(value) +} diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs index 615b69c..5f4eb92 100644 --- a/crates/eval/src/prepared_graph.rs +++ b/crates/eval/src/prepared_graph.rs @@ -6,9 +6,7 @@ use std::collections::BTreeMap; pub(crate) struct PreparedGraph<'a> { pub index: GraphIndex<'a>, pub order: Vec, - nominal_sizes: BTreeMap, - base_parameters: BTreeMap, - parent_base: crate::resolved_base_parameters::ResolvedBaseParameters, + pub parent_base: crate::resolved_base_parameters::ResolvedBaseParameters, ports: BTreeMap, Vec)>, } @@ -26,42 +24,20 @@ impl<'a> PreparedGraph<'a> { .collect(); let parent_base = crate::resolved_base_parameters::ResolvedBaseParameters::graph(graph, options); - let mut prepared = Self { index, order, ports, nominal_sizes: BTreeMap::new(), base_parameters: BTreeMap::new(), parent_base }; - for &id in &prepared.order { - let Some(node) = prepared.index.node(id) else { continue }; - - let input = prepared.first_input_size(id); - let nominal = if node.disabled { - input.unwrap_or_else(|| crate::node_size(graph, materialcraft_nodes::find(&node.def), node, None, None)) - } else { - crate::node_size(graph, materialcraft_nodes::find(&node.def), node, input, None) - }; - prepared.nominal_sizes.insert(id, nominal); - let input_base = prepared.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| { - let connection = prepared.index.input_of(id, &port.id)?; - prepared.base_parameters.get(&connection.from).copied() - }); - let base = crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, input_base, parent_base); - prepared.base_parameters.insert(id, base); - } - prepared + Self { index, order, ports, parent_base } } - pub fn first_input_size(&self, id: NodeId) -> Option<(u32, u32)> { - self.ports(id).0.iter().filter(|port| port.kind != materialcraft_nodes::PortKind::Value).find_map(|port| { - let connection = self.index.input_of(id, &port.id)?; - self.nominal_sizes.get(&connection.from).copied() - }) + pub fn input_base(&self, id: NodeId, cooked: &crate::Cooked) -> Option { + let primary = self.index.node(id).and_then(|node| materialcraft_nodes::find(&node.def)).and_then(|definition| definition.primary_input); + 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) + }, + ) } pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) { self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice())) } - - pub fn base_parameters(&self, node: &materialcraft_core::Node) -> crate::resolved_base_parameters::ResolvedBaseParameters { - self.base_parameters - .get(&node.id) - .copied() - .unwrap_or_else(|| crate::resolved_base_parameters::ResolvedBaseParameters::resolve(&node.base, None, self.parent_base)) - } } diff --git a/crates/eval/src/resolved_base_parameters.rs b/crates/eval/src/resolved_base_parameters.rs index 94baaa2..1dccb11 100644 --- a/crates/eval/src/resolved_base_parameters.rs +++ b/crates/eval/src/resolved_base_parameters.rs @@ -1,23 +1,106 @@ -use materialcraft_core::{BaseParameters, Graph}; +use materialcraft_core::{BaseParameter, BaseParameters, Graph, OutputFormat, ParameterInheritance, Value}; +use std::collections::BTreeMap; -#[derive(Clone, Copy)] -pub(crate) struct ResolvedBaseParameters { +#[derive(Clone, Copy, Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ResolvedBaseParameters { + pub size: [u32; 2], + pub seed: u32, + pub format: OutputFormat, pub tiling: [bool; 2], pub pixel_ratio: i32, + pub pixel_size: [f32; 2], } impl ResolvedBaseParameters { - pub fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self { + pub(crate) fn graph(graph: &Graph, options: &crate::Options<'_>) -> Self { + let parent = options.parent_base; Self { + size: parent.map_or_else(|| graph.size_px(), |base| base.size), + seed: parent.map_or((graph.seed as u32).wrapping_mul(0x9e37_79b9), |base| base.seed), + format: parent.map_or(graph.format, |base| base.format), 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_size: parent.map_or([1.0; 2], |base| base.pixel_size), } } - pub fn resolve(base: &BaseParameters, input: Option, parent: Self) -> Self { + pub(crate) fn resolve(base: &BaseParameters, input: Option, parent: Self) -> Self { + let size_base = BaseParameter::OutputSize.inheritance(base).resolve([1; 2], input.map(|base| base.size), parent.size); + let size = std::array::from_fn(|axis| (f64::from(size_base[axis]) * 2f64.powi(base.size[axis].clamp(-12, 13))).round().clamp(16.0, 8192.0) as u32); + let inherited_seed = base.seed_mode.resolve(0, input.map(|base| base.seed), parent.seed); + let inherited_pixel_size = base.pixel_size_mode.resolve([1.0; 2], input.map(|base| base.pixel_size), parent.pixel_size); Self { - tiling: base.tiling_mode.resolve(base.tiling, input.map(|input| input.tiling), parent.tiling), - pixel_ratio: base.pixel_ratio_mode.resolve(base.pixel_ratio, input.map(|input| input.pixel_ratio), parent.pixel_ratio), + size, + seed: inherited_seed.wrapping_add(base.seed as u32), + 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)), } } + + pub(crate) fn variables(self, variables: &mut BTreeMap) { + 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)); + } +} + +pub(crate) fn evaluate( + base: &BaseParameters, + input: Option, + parent: ResolvedBaseParameters, + variables: &BTreeMap, +) -> Result<(ResolvedBaseParameters, BTreeMap), String> { + if base.functions.is_empty() { + return Ok((ResolvedBaseParameters::resolve(base, input, parent), BTreeMap::new())); + } + + // Evaluation mutates literals while borrowing the attached function graphs + let mut evaluated = BaseParameters { + size_mode: base.size_mode, + size: base.size, + format: base.format, + format_mode: base.format_mode, + seed: base.seed, + seed_mode: base.seed_mode, + pixel_size: base.pixel_size, + pixel_size_mode: base.pixel_size_mode, + functions: BTreeMap::new(), + tiling: base.tiling, + tiling_mode: base.tiling_mode, + pixel_ratio: base.pixel_ratio, + pixel_ratio_mode: base.pixel_ratio_mode, + }; + let mut values = BTreeMap::new(); + let mut variables = variables.clone(); + let mut resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent); + + // Size and seed establish the context used by the remaining parameter functions + for parameter in [ + BaseParameter::RandomSeed, + BaseParameter::OutputSize, + BaseParameter::Format, + BaseParameter::PixelSize, + BaseParameter::PixelRatio, + BaseParameter::Tiling, + ] { + if let Some(function) = base.functions.get(¶meter) { + resolved.variables(&mut variables); + let size = if parameter == BaseParameter::OutputSize && parameter.inheritance(base) != ParameterInheritance::Absolute { + parameter.inheritance(base).resolve(parent.size, input.map(|base| base.size), parent.size) + } else { + resolved.size + }; + let value = crate::parameter_function::evaluate(function, parameter.value_type(), &variables, resolved.seed, size) + .map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?; + parameter.set_value(&mut evaluated, &value)?; + parameter.set_inheritance(&mut evaluated, parameter.inheritance(base)); + resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent); + } + + values.insert(parameter, parameter.value(&evaluated)); + } + + Ok((resolved, values)) } diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 4684531..06eca79 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -469,3 +469,40 @@ fn bound_input_image_linear_flag_change_recooks_instance() { let third_value = third.image(inst, 0).unwrap().data[0]; assert!((third_value - 0.5).abs() < 1e-4, "linear bound image should reach the instance, got {third_value}"); } + +#[test] +fn cooked_parameters_retain_values_without_processor_graph_copies() { + let mut graph = Graph::new("Parameter results"); + graph.size = [4, 4]; + for _ in 0..12 { + let owner = graph.add_node("value_processor", [0.0; 2]); + let mut function = materialcraft_core::FunctionGraph::constant(Value::Float(0.25)); + let constant = function.output.unwrap(); + for _ in 0..32 { + function.output = Some(function.add("add", &[function.output.unwrap(), constant], None)); + } + graph.node_mut(owner).unwrap().params.insert("function".into(), Value::Function(Box::new(function))); + } + let scalar = graph.add_node("uniform", [0.0; 2]); + graph.node_mut(scalar).unwrap().functions.insert("color".into(), materialcraft_core::FunctionGraph::constant(Value::Color([0.5; 4]))); + let mut package = Package::new("Parameter results"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + + let results = [cook(&package, 0, &Options::new(&no_res), &cache), cook(&package, 0, &Options::new(&no_res), &cache)]; + + assert!(results[1].nodes.values().all(|result| result.cached)); + for result in results { + for (owner, node) in &result.nodes { + assert_eq!(node.error, None); + assert!( + node.parameters.values().all(|value| materialcraft_core::ValueType::of(value).is_some()), + "cooked previews must not retain authoring graphs" + ); + if *owner != scalar { + assert_eq!(result.value(*owner, 0), Some(&Value::Float(8.25))); + } + } + assert_eq!(result.nodes[&scalar].parameters.get("color"), Some(&Value::Color([0.5; 4]))); + } +} diff --git a/crates/formats/examples/standard_function_library/convert.rs b/crates/formats/examples/standard_function_library/convert.rs index 19e7912..8ce9a90 100644 --- a/crates/formats/examples/standard_function_library/convert.rs +++ b/crates/formats/examples/standard_function_library/convert.rs @@ -32,6 +32,9 @@ pub(super) fn package(bytes: &[u8], source: &str) -> Result>().join(", ") }; graph.attributes.description = format!("Evaluates the {} function graph. Result type: {}. Inputs: {inputs}.", graph.name, result.label()); + for input in &mut graph.exposed { + input.description.clear(); + } graph.attributes.author.clear(); graph.attributes.author_url.clear(); graph.attributes.user_data.clear(); diff --git a/crates/formats/src/material/archive.rs b/crates/formats/src/material/archive.rs index 9adc29e..c9938f4 100644 --- a/crates/formats/src/material/archive.rs +++ b/crates/formats/src/material/archive.rs @@ -110,6 +110,10 @@ mod tests { fn manifest() -> Manifest { let param = ExposedParameter { + description: String::new(), + editor: None, + clamp: false, + step: None, id: "rough".into(), label: "Roughness".into(), group: String::new(), diff --git a/crates/formats/src/sbs/base_parameters.rs b/crates/formats/src/sbs/base_parameters.rs index 93a2e29..500da1a 100644 --- a/crates/formats/src/sbs/base_parameters.rs +++ b/crates/formats/src/sbs/base_parameters.rs @@ -1,94 +1,52 @@ -use super::sbs_value::sbs_constant; use super::xml::{child_element, child_value, children_named}; -use materialcraft_core::{BaseParameters, MAX_SIZE_LOG2, OutputFormat, ParameterInheritance, SizeMode}; +use super::{ + function_graph, + sbs_value::{constant_xml, sbs_constant, to_natural_value}, + sbs_writer::SbsWriter, + warnings::Warnings, +}; +use materialcraft_core::{BaseParameter, BaseParameters, ParameterInheritance}; use roxmltree::Node as XmlNode; use std::fmt::Write as _; -pub(super) fn read_base_params(params: Option) -> BaseParameters { +pub(super) fn read_base_params(params: Option, warnings: &mut Warnings) -> BaseParameters { let mut base = BaseParameters::default(); - for param in params.into_iter().flat_map(|p| children_named(p, "parameter")) { - let relative_to = child_value(param, "relativeTo").and_then(|r| r.trim().parse::().ok()).unwrap_or(1); - let inheritance = match relative_to { - 0 => ParameterInheritance::Absolute, - 2 => ParameterInheritance::RelativeToParent, + for element in params.into_iter().flat_map(|parameters| children_named(parameters, "parameter")) { + let Some(parameter) = child_value(element, "name").and_then(BaseParameter::named) else { continue }; + let inheritance = match child_value(element, "relativeTo").unwrap_or("1") { + "0" => ParameterInheritance::Absolute, + "2" => ParameterInheritance::RelativeToParent, _ => ParameterInheritance::RelativeToInput, }; - match child_value(param, "name") { - Some("tiling") => base.tiling_mode = inheritance, - Some("pixelratio") => base.pixel_ratio_mode = inheritance, - _ => {} - } + let Some(value) = child_element(element, "paramValue") else { continue }; - let Some(value) = child_element(param, "paramValue").and_then(sbs_constant) else { continue }; - - match child_value(param, "name") { - Some("outputsize") => { - base.size_mode = match relative_to { - 0 => SizeMode::Absolute, - 2 => SizeMode::RelativeToParent, - _ => SizeMode::RelativeToInput, - }; - - let limit = |log2: i32| log2.clamp(-(MAX_SIZE_LOG2 as i32), MAX_SIZE_LOG2 as i32); - base.size = [limit(value.int(0)), limit(value.int(1))]; - } - Some("format") if relative_to == 0 => { - base.format = match value.int(0) { - 0 => OutputFormat::U8, - 1 => OutputFormat::U16, - 2 => OutputFormat::F16, - 3 => OutputFormat::F32, - _ => OutputFormat::Inherit, + if let Some(dynamic) = child_element(value, "dynamicValue") { + match function_graph::read(dynamic) { + Ok(function) => { + base.functions.insert(parameter, function); } + Err(error) => warnings.add(format!("{} function: {error}", parameter.label())), } - Some("randomseed") if relative_to == 0 => base.seed = value.int(0), - Some("tiling") => base.tiling = [value.int(0) & 1 != 0, value.int(0) & 2 != 0], - Some("pixelratio") => base.pixel_ratio = value.int(0).clamp(0, 1), - _ => {} + } else if let Some(value) = sbs_constant(value) + && let Err(error) = parameter.set_value(&mut base, &to_natural_value(&value)) + { + warnings.add(error); } + + parameter.set_inheritance(&mut base, inheritance); } + base } -pub(super) fn base_params_xml(base: &BaseParameters) -> String { - let mut out = String::new(); - - if base.size_mode != SizeMode::RelativeToInput || base.size != [0, 0] { - let relative_to = match base.size_mode { - SizeMode::Absolute => 0, - SizeMode::RelativeToInput => 1, - SizeMode::RelativeToParent => 2, - }; - - let [width, height] = base.size; - let _ = write!( - out, - "" - ); - } - - let format = match base.format { - OutputFormat::Inherit => None, - OutputFormat::U8 => Some(0), - OutputFormat::U16 => Some(1), - OutputFormat::F16 => Some(2), - OutputFormat::F32 => Some(3), - }; - - if let Some(format) = format { - let _ = write!(out, ""); - } - - if base.seed != 0 { - let _ = write!( - out, - "", - base.seed - ); - } - let tiling = i32::from(base.tiling[0]) | (i32::from(base.tiling[1]) << 1); - for (name, value, inheritance, default) in [("tiling", tiling, base.tiling_mode, 3), ("pixelratio", base.pixel_ratio, base.pixel_ratio_mode, 0)] { - if inheritance == ParameterInheritance::RelativeToInput && value == default { +pub(super) fn base_params_xml(base: &BaseParameters, writer: &mut SbsWriter) -> Result { + let mut output = String::new(); + let defaults = BaseParameters::default(); + for parameter in BaseParameter::ALL { + let function = base.functions.get(¶meter); + let value = parameter.value(base); + let inheritance = parameter.inheritance(base); + if function.is_none() && value == parameter.value(&defaults) && inheritance == parameter.inheritance(&defaults) { continue; } @@ -97,10 +55,13 @@ pub(super) fn base_params_xml(base: &BaseParameters) -> String { ParameterInheritance::RelativeToInput => 1, ParameterInheritance::RelativeToParent => 2, }; - let _ = write!( - out, - "" - ); + let body = match function { + Some(function) => function_graph::write(function, writer)?, + None => constant_xml(&value).ok_or("invalid base parameter value")?, + }; + let _ = + write!(output, "{body}", parameter.identifier()); } - out + + Ok(output) } diff --git a/crates/formats/src/sbs/function_graph.rs b/crates/formats/src/sbs/function_graph.rs index fee5210..806de2b 100644 --- a/crates/formats/src/sbs/function_graph.rs +++ b/crates/formats/src/sbs/function_graph.rs @@ -166,22 +166,7 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result Result { - use materialcraft_core::ValueType; + let value_type = materialcraft_core::ValueType::of(value).ok_or("only scalar and vector parameters can be exposed")?; - let operation = match ValueType::of(value).ok_or("only scalar and vector parameters can be exposed")? { - ValueType::Boolean => "get_bool", - ValueType::Integer => "get_integer1", - ValueType::Integer2 => "get_integer2", - ValueType::Integer3 => "get_integer3", - ValueType::Integer4 => "get_integer4", - ValueType::Float => "get_float1", - ValueType::Float2 => "get_float2", - ValueType::Float3 => "get_float3", - ValueType::Float4 => "get_float4", - ValueType::String => "get_string", - }; - - let mut graph = FunctionGraph::default(); - graph.output = Some(graph.add(operation, &[], Some(Value::Text(identifier.into())))); - Ok(graph) + Ok(FunctionGraph::input(identifier, value_type)) } diff --git a/crates/formats/src/sbs/mod.rs b/crates/formats/src/sbs/mod.rs index 583e6d6..5493f83 100644 --- a/crates/formats/src/sbs/mod.rs +++ b/crates/formats/src/sbs/mod.rs @@ -19,6 +19,7 @@ mod node_identifiers; mod node_parameter; mod output; mod parameter_array; +mod parameter_widget; mod pattern_graph; mod placeholder; mod read_node; diff --git a/crates/formats/src/sbs/parameter_widget.rs b/crates/formats/src/sbs/parameter_widget.rs new file mode 100644 index 0000000..fea17e5 --- /dev/null +++ b/crates/formats/src/sbs/parameter_widget.rs @@ -0,0 +1,94 @@ +use super::xml::{child_element, child_value, children_named, format_float, xml_escape}; +use materialcraft_core::{ExposedParameter, ParameterEditor, Value}; +use roxmltree::Node; +use std::fmt::Write; + +pub(super) fn read(element: Node<'_, '_>, input: &mut ExposedParameter) { + input.description = child_element(element, "attributes").and_then(|attributes| child_value(attributes, "description")).unwrap_or("").into(); + let Some(widget) = child_element(element, "defaultWidget") else { + return; + }; + + let name = child_value(widget, "name").unwrap_or(""); + let mut color = name == "color"; + for option in child_element(widget, "options").into_iter().flat_map(|options| children_named(options, "option")) { + let text = child_value(option, "value").unwrap_or(""); + let number = text.split([' ', ';']).next().and_then(|value| value.parse::().ok()).filter(|value| value.is_finite()); + match child_value(option, "name").unwrap_or("") { + "clamp" => input.clamp = number.is_some_and(|value| value != 0.0), + "step" => input.step = number.filter(|step| *step > 0.0), + "valueInterpretation" if text == "color" => color = true, + "parameters" if name == "dropdownlist" => { + let mut parts = text.split(';').skip(1); + while let (Some(index), Some(label)) = (parts.next(), parts.next()) { + // The model's enum values are contiguous; sparse external lists remain numeric + if index.parse::().ok() != Some(input.options.len()) { + input.options.clear(); + break; + } + input.options.push(label.into()); + } + } + _ => {} + } + } + if name == "dropdownlist" + && !input.options.is_empty() + && let Some(value) = input.default.as_i32() + { + input.default = Value::Enum(value.max(0) as u32); + } + 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") + .and_then(super::sbs_value::sbs_constant) + .and_then(|value| super::sbs_value::to_param_value(&Value::Color([0.0; 4]), &value, 0)) + { + input.default = value; + } + } + + let editor = match name { + "slider" => Some(ParameterEditor::Slider), + "inputfield" => Some(ParameterEditor::Input), + "color" => Some(ParameterEditor::Color), + "dropdownlist" => Some(ParameterEditor::Dropdown), + "buttons" => Some(ParameterEditor::Toggle), + "text" => Some(ParameterEditor::Text), + _ => None, + }; + input.editor = editor.filter(|editor| *editor != ParameterEditor::for_value(&input.default) && ParameterEditor::choices(&input.default).contains(editor)); +} + +pub(super) fn write(out: &mut String, input: &ExposedParameter) { + let name = match input.editor() { + ParameterEditor::Slider => "slider", + ParameterEditor::Input => "inputfield", + ParameterEditor::Color => "color", + ParameterEditor::Dropdown => "dropdownlist", + ParameterEditor::Toggle => "buttons", + ParameterEditor::Text => "text", + }; + let _ = write!(out, ""); + for (name, value) in [("min", format_float(input.min)), ("max", format_float(input.max)), ("clamp", u8::from(input.clamp).to_string())] { + option(out, name, &value); + } + if matches!(input.default, Value::Color(_)) { + option(out, "valueInterpretation", "color"); + } + if let Some(step) = input.step { + option(out, "step", &format_float(step)); + } + if !input.options.is_empty() { + let mut values = input.default.as_i32().unwrap_or(0).to_string(); + for (index, label) in input.options.iter().enumerate() { + let _ = write!(values, ";{index};{label}"); + } + option(out, "parameters", &values); + } + out.push_str(""); +} + +fn option(out: &mut String, name: &str, value: &str) { + let _ = write!(out, "", xml_escape(value)); +} diff --git a/crates/formats/src/sbs/sbs_reader.rs b/crates/formats/src/sbs/sbs_reader.rs index 52552db..d95d183 100644 --- a/crates/formats/src/sbs/sbs_reader.rs +++ b/crates/formats/src/sbs/sbs_reader.rs @@ -146,7 +146,7 @@ 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")); + let base = read_base_params(child_element(element, "baseParameters"), self.warnings); graph.seed = base.seed; graph.pixel_ratio = base.pixel_ratio; graph.pixel_ratio_mode = base.pixel_ratio_mode; @@ -279,7 +279,21 @@ impl<'text> SbsReader<'text, '_> { } let group = child_value(input, "group").unwrap_or("").to_string(); - graph.exposed.push(ExposedParameter { id, label, group, default, min, max, options: Vec::new() }); + let mut exposed = ExposedParameter { + id, + label, + group, + default, + min, + max, + options: Vec::new(), + description: String::new(), + editor: None, + clamp: false, + step: None, + }; + super::parameter_widget::read(input, &mut exposed); + graph.exposed.push(exposed); } image_inputs } @@ -378,7 +392,7 @@ impl<'text> SbsReader<'text, '_> { if let Some(input) = input { node.params.insert("default".into(), input.default.clone()); } - node.base = read_base_params(params); + node.base = read_base_params(params, self.warnings); } ReadNode { id, index, inputs: HashMap::new(), outputs: all_outputs_to("output"), open_inputs: false } } @@ -402,7 +416,7 @@ impl<'text> SbsReader<'text, '_> { if let Some(node) = node { self.read_filter_params(node, filter, params, &graph_name); super::parameter_array::read(node, implementation); - node.base = read_base_params(params); + node.base = read_base_params(params, self.warnings); if filter.sbs == "fxmaps" && let Some(pattern) = child_element(implementation, "paramsGraphs").and_then(|graphs| child_element(graphs, "paramsGraph")) { @@ -487,7 +501,7 @@ impl<'text> SbsReader<'text, '_> { self.set_param(node, child_value(param, "name").unwrap_or(""), &Value::Float(0.0), 0, param, &graph_name); } } - node.base = read_base_params(params); + node.base = read_base_params(params, self.warnings); } return ReadNode { id, index, inputs: HashMap::new(), outputs: bridgings, open_inputs: true }; } diff --git a/crates/formats/src/sbs/sbs_writer.rs b/crates/formats/src/sbs/sbs_writer.rs index 2e9304b..e6b9858 100644 --- a/crates/formats/src/sbs/sbs_writer.rs +++ b/crates/formats/src/sbs/sbs_writer.rs @@ -150,7 +150,7 @@ impl SbsWriter { tiling_mode: graph.tiling_mode, ..Default::default() }; - out.push_str(&super::base_parameters::base_params_xml(&base)); + out.push_str(&super::base_parameters::base_params_xml(&base, self).map_err(FormatError::Io)?); out.push_str(""); write_canvas_items(out, graph, self); @@ -196,14 +196,15 @@ impl SbsWriter { let _ = write!( out, - "{default}{group}", + "{default}", xml_escape(&exposed.id), self.next_uid(), xml_escape(&exposed.label), - exposed_type_code(&exposed.default), - format_float(exposed.min), - format_float(exposed.max) + xml_escape(&exposed.description), + exposed_type_code(&exposed.default) ); + super::parameter_widget::write(out, exposed); + let _ = write!(out, "{group}"); } out.push_str(""); @@ -242,7 +243,7 @@ impl SbsWriter { ids: NodeIdentifiers, package: &Package, ) -> Result<()> { - let base = base_params_xml(&node.base); + let base = base_params_xml(&node.base, self).map_err(FormatError::Io)?; match node.def.as_str() { "output" => { diff --git a/crates/formats/tests/function_library.rs b/crates/formats/tests/function_library.rs index 2a4bd94..511d1b5 100644 --- a/crates/formats/tests/function_library.rs +++ b/crates/formats/tests/function_library.rs @@ -109,10 +109,15 @@ fn supplied_function_package_round_trip() { let replacement = bundled.pkg.graph_by_name(&graph.sbs_path()).unwrap().1; assert_eq!(graph.function_type, replacement.function_type, "{}", graph.sbs_path()); assert_eq!(graph.function_type, other.function_type, "{}", graph.sbs_path()); - assert_eq!(graph.exposed, replacement.exposed, "{}", graph.sbs_path()); + let mut expected_inputs = graph.exposed.clone(); + for input in &mut expected_inputs { + input.description.clear(); + } + assert_eq!(expected_inputs, replacement.exposed, "{}", graph.sbs_path()); assert_ne!(graph.attributes.description, replacement.attributes.description, "{}", graph.sbs_path()); assert!(replacement.attributes.author.is_empty()); - assert!(replacement.attributes.tags.is_empty()); + assert_eq!(replacement.attributes.category, graph.attributes.category); + assert_eq!(replacement.attributes.tags, graph.attributes.tags); assert!(replacement.frames.is_empty() && replacement.comments.is_empty() && replacement.pins.is_empty()); assert_same_body(graph, replacement); assert_eq!(graph.name, other.name); diff --git a/crates/nodes/src/atomic/blend.rs b/crates/nodes/src/atomic/blend.rs index 51bcfbb..3c890e4 100644 --- a/crates/nodes/src/atomic/blend.rs +++ b/crates/nodes/src/atomic/blend.rs @@ -10,6 +10,7 @@ pub(super) fn definition() -> NodeDefinition { .atomic() .any_in("foreground", "Foreground") .any_in("background", "Background") + .primary_input("background") .gray_in("mask", "Opacity") .float("opacity", "Opacity", 1.0, 0.0, 1.0) .choice("mode", "Blending mode", BLEND_MODES, 0) diff --git a/crates/nodes/src/lib.rs b/crates/nodes/src/lib.rs index c99180f..db54747 100644 --- a/crates/nodes/src/lib.rs +++ b/crates/nodes/src/lib.rs @@ -16,6 +16,7 @@ mod node_definition_builder; mod output_value_type; mod parameter; mod parameter_definition; +mod parameter_descriptor; mod port_definition; mod port_kind; mod random; @@ -28,6 +29,7 @@ pub(crate) use node_definition_builder::node; pub use output_value_type::{output_port_value_type, output_value_type}; pub use parameter::{clamp_params, resolve_params}; pub use parameter_definition::ParameterDefinition; +pub use parameter_descriptor::ParameterDescriptor; pub use port_definition::PortDefinition; pub use port_kind::PortKind; diff --git a/crates/nodes/src/node_definition.rs b/crates/nodes/src/node_definition.rs index d8170c6..2ffeedc 100644 --- a/crates/nodes/src/node_definition.rs +++ b/crates/nodes/src/node_definition.rs @@ -9,6 +9,8 @@ pub struct NodeDefinition { pub category: &'static str, pub description: &'static str, pub inputs: Vec, + /// The input supplying inherited base parameters, when it differs from port order + pub primary_input: Option<&'static str>, pub outputs: Vec, pub params: Vec, /// A generator takes its size from the graph, not from an input diff --git a/crates/nodes/src/node_definition_builder.rs b/crates/nodes/src/node_definition_builder.rs index f53a264..b8574d4 100644 --- a/crates/nodes/src/node_definition_builder.rs +++ b/crates/nodes/src/node_definition_builder.rs @@ -15,6 +15,7 @@ pub(crate) fn node(id: &'static str, label: &'static str, category: &'static str category, description: "", inputs: Vec::new(), + primary_input: None, outputs: Vec::new(), params: Vec::new(), generator: false, @@ -44,6 +45,11 @@ impl NodeDefinitionBuilder { self } + pub fn primary_input(mut self, identifier: &'static str) -> Self { + self.0.primary_input = Some(identifier); + self + } + pub fn gray_in(self, id: &'static str, label: &'static str) -> NodeDefinitionBuilder { self.input(id, label, PortKind::Gray) } diff --git a/crates/nodes/src/parameter_descriptor.rs b/crates/nodes/src/parameter_descriptor.rs new file mode 100644 index 0000000..8250288 --- /dev/null +++ b/crates/nodes/src/parameter_descriptor.rs @@ -0,0 +1,93 @@ +use materialcraft_core::{BaseParameter, BaseParameters, Node, Package, Value, ValueType}; + +/// Parameter metadata shared by commands, Properties, and dynamic-value validation +#[derive(Clone, Debug)] +pub struct ParameterDescriptor { + pub id: String, + pub label: String, + pub default: Value, + pub min: f32, + pub max: f32, + pub options: Vec, + pub supports_function: bool, +} + +impl ParameterDescriptor { + pub fn base(parameter: BaseParameter) -> Self { + let (min, max, options): (f32, f32, &[&str]) = match parameter { + BaseParameter::OutputSize => (-12.0, 13.0, &[]), + BaseParameter::Format => (0.0, 3.0, &["8 bits per channel", "16 bits per channel", "16 bit floating point", "32 bit floating point"]), + BaseParameter::PixelSize => (0.001, 16.0, &[]), + BaseParameter::PixelRatio => (0.0, 1.0, &["Stretch", "Square"]), + BaseParameter::Tiling => (0.0, 3.0, &["No tiling", "Horizontal tiling", "Vertical tiling", "H and V tiling"]), + BaseParameter::RandomSeed => (0.0, 1000.0, &[]), + }; + + Self { + id: parameter.identifier().into(), + label: parameter.label().into(), + default: parameter.value(&BaseParameters::default()), + min, + max, + options: options.iter().map(|option| (*option).into()).collect(), + supports_function: true, + } + } + + pub fn for_node(package: &Package, node: &Node, parameter: &str) -> Option { + if node.def == "graph_instance" { + let source = node + .instance + .as_ref() + .filter(|instance| !instance.package.is_empty()) + .map_or(Some(package), |instance| package.dependencies.get(&instance.package).map(AsRef::as_ref)); + let name = node.instance.as_ref().map(|instance| instance.graph.as_str()).or_else(|| match node.params.get("graph") { + Some(Value::Text(name)) => Some(name.as_str()), + _ => None, + }); + if let Some(input) = source + .zip(name) + .and_then(|(source, name)| source.graph_by_name(name)) + .and_then(|(_, graph)| graph.exposed.iter().find(|input| input.id == parameter)) + { + return Some(Self { + id: input.id.clone(), + label: input.label.clone(), + default: input.default.clone(), + min: input.min, + max: input.max, + options: input.options.clone(), + supports_function: ValueType::of(&input.default).is_some(), + }); + } + + let default = node.instance.as_ref()?.defaults.get(parameter)?.clone(); + return Some(Self { + id: parameter.into(), + label: parameter.into(), + supports_function: ValueType::of(&default).is_some(), + default, + min: 0.0, + max: 1.0, + options: Vec::new(), + }); + } + + let definition = crate::find(&node.def)?.param(parameter)?; + let default = if node.def == "input_value" && parameter == "default" { + node.params.get(parameter).filter(|value| ValueType::of(value).is_some()).unwrap_or(&definition.default) + } else { + &definition.default + }; + + Some(Self { + id: parameter.into(), + label: definition.label.into(), + default: default.clone(), + min: definition.min, + max: definition.max, + options: definition.options.iter().map(|option| (*option).into()).collect(), + supports_function: !definition.resource && ValueType::of(&definition.default).is_some() && !matches!(parameter, "identifier" | "graph"), + }) + } +} diff --git a/crates/ui-egui/src/cook.rs b/crates/ui-egui/src/cook.rs index fefb1e8..d9abab2 100644 --- a/crates/ui-egui/src/cook.rs +++ b/crates/ui-egui/src/cook.rs @@ -33,7 +33,19 @@ fn report_failure(app: &mut MaterialCraftApp, msg: String) { let ids: Vec<_> = app.session.graph().map(|g| g.nodes.iter().map(|n| n.id).collect()).unwrap_or_default(); let mut cooked = Cooked::default(); for id in ids { - cooked.nodes.insert(id, NodeResult { outputs: Default::default(), error: Some(msg.clone()), ms: 0.0, key: 0, cached: false }); + cooked.nodes.insert( + id, + NodeResult { + base: Default::default(), + base_values: Default::default(), + parameters: Default::default(), + outputs: Default::default(), + error: Some(msg.clone()), + ms: 0.0, + key: 0, + cached: false, + }, + ); } app.session.accept_preview(PreviewCook { graph: app.session.graph, cooked, ..Default::default() }); app.toast(msg, true); diff --git a/crates/ui-egui/src/function/function_editor.rs b/crates/ui-egui/src/function/function_editor.rs index 0a26e29..0fb521a 100644 --- a/crates/ui-egui/src/function/function_editor.rs +++ b/crates/ui-egui/src/function/function_editor.rs @@ -73,6 +73,7 @@ impl FunctionEditor { FunctionTarget::Graph => FunctionGraphTarget::Graph, FunctionTarget::Parameter(parameter) => FunctionGraphTarget::Parameter { node: self.node?, parameter: parameter.clone() }, FunctionTarget::Dynamic(parameter) => FunctionGraphTarget::Dynamic { node: self.node?, parameter: parameter.clone() }, + FunctionTarget::Base(parameter) => FunctionGraphTarget::Base { node: self.node?, parameter: *parameter }, FunctionTarget::Pattern { node, parameter } => FunctionGraphTarget::Pattern { owner: self.node?, node: *node, parameter: parameter.clone() }, }) } diff --git a/crates/ui-egui/src/function/function_target.rs b/crates/ui-egui/src/function/function_target.rs index e20523b..a682603 100644 --- a/crates/ui-egui/src/function/function_target.rs +++ b/crates/ui-egui/src/function/function_target.rs @@ -3,6 +3,7 @@ pub enum FunctionTarget { Graph, Parameter(String), Dynamic(String), + Base(materialcraft_engine::core::BaseParameter), Pattern { node: u32, parameter: String }, } @@ -10,6 +11,7 @@ impl FunctionTarget { pub fn parameter(&self) -> &str { match self { Self::Graph => "", + Self::Base(parameter) => parameter.identifier(), Self::Parameter(parameter) | Self::Dynamic(parameter) | Self::Pattern { parameter, .. } => parameter, } } diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index 87c8d4b..850b382 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -234,7 +234,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { // Footer: size and format let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max); if let Some(img) = result.and_then(|r| r.outputs.first().and_then(materialcraft_engine::eval::NodeOutput::as_image)) { - let bits = if node.base.format == materialcraft_engine::core::OutputFormat::Inherit { graph.format.bits() } else { node.base.format.bits() }; + let bits = result.map_or(graph.format.bits(), |result| result.base.format.bits()); let format = format!("{}{bits}", if img.is_gray() { "L" } else { "C" }); let txt = if let Some(limit) = app.session.preview_size { diff --git a/crates/ui-egui/src/graph/review_tests.rs b/crates/ui-egui/src/graph/review_tests.rs index b00921c..4f98575 100644 --- a/crates/ui-egui/src/graph/review_tests.rs +++ b/crates/ui-egui/src/graph/review_tests.rs @@ -176,7 +176,7 @@ fn dynamic_parameter_functions_return_to_the_owning_node() { let owner = NodeId(app.run("graph.node.add", json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); app.run("graph.node.function", json!({"id": owner, "param": "intensity"})).unwrap(); super::subgraph_navigation::open_function(&mut app, owner, FunctionTarget::Dynamic("intensity".into())); - assert!(super::subgraph_navigation::breadcrumb(&app).ends_with("Blur / intensity")); + assert!(super::subgraph_navigation::breadcrumb(&app).ends_with("Blur / Intensity")); let context = egui::Context::default(); menus::invoke(&mut app, &context, "edit.selectAll"); menus::invoke(&mut app, &context, "edit.delete"); diff --git a/crates/ui-egui/src/graph/subgraph_navigation.rs b/crates/ui-egui/src/graph/subgraph_navigation.rs index 27e4e00..4c5111e 100644 --- a/crates/ui-egui/src/graph/subgraph_navigation.rs +++ b/crates/ui-egui/src/graph/subgraph_navigation.rs @@ -127,7 +127,14 @@ pub(crate) fn breadcrumb(app: &MaterialCraftApp) -> String { } path.push(parameter.clone()); } - FunctionTarget::Dynamic(parameter) => path.push(parameter.clone()), + FunctionTarget::Dynamic(parameter) => { + let descriptor = editor + .node + .and_then(|id| app.session.graph().ok()?.node(id).ok()) + .and_then(|node| materialcraft_engine::nodes::ParameterDescriptor::for_node(&app.session.pkg, node, parameter)); + path.push(descriptor.map_or_else(|| parameter.clone(), |descriptor| descriptor.label)); + } + FunctionTarget::Base(parameter) => path.push(parameter.label().into()), FunctionTarget::Parameter(parameter) if parameter != "function" => path.push(parameter.clone()), _ => {} } diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index d958caa..d1da6ca 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -25,6 +25,7 @@ pub struct MaterialCraftApp { pub(crate) inspected_graph: Option, pub(crate) inspected_folder: Option<(u64, String)>, pub(crate) folder_property_draft: Option, + pub(crate) expose_parameter_dialog: Option, pub(crate) graph_property_draft: Option, pub(crate) graph_parents: Vec, /// Synthetic input from the control channel, fed to egui on the next frames @@ -98,6 +99,7 @@ impl MaterialCraftApp { inspected_folder: None, folder_property_draft: None, graph_property_draft: None, + expose_parameter_dialog: None, graph_parents: Vec::new(), pattern_editor: None, input_queue: VecDeque::new(), @@ -216,6 +218,18 @@ impl MaterialCraftApp { self.ui.prefs.history = self.session.history_prefs; } self.close_subgraph_after(id); + if id == "graph.node.function.edit" + && let Ok(target) = serde_json::from_value::(v["target"].clone()) + { + let target = match target { + materialcraft_engine::FunctionGraphTarget::Base { node, parameter } => Some((node, function::FunctionTarget::Base(parameter))), + materialcraft_engine::FunctionGraphTarget::Dynamic { node, parameter } => Some((node, function::FunctionTarget::Dynamic(parameter))), + _ => None, + }; + if let Some((node, target)) = target { + crate::graph::subgraph_navigation::open_function(self, node, target); + } + } if matches!(id, "view.3d.assign" | "view.3d.outputs") { self.ui.dock.focus(docking::Panel::View3d); } diff --git a/crates/ui-egui/src/property/expose_parameter_dialog.rs b/crates/ui-egui/src/property/expose_parameter_dialog.rs new file mode 100644 index 0000000..10a2720 --- /dev/null +++ b/crates/ui-egui/src/property/expose_parameter_dialog.rs @@ -0,0 +1,216 @@ +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{RichText, Ui}; +use materialcraft_engine::{ + GraphTarget, + core::{ExposedParameter, NodeId, ParameterEditor, Value, ValueType}, +}; +use serde_json::json; + +pub(crate) struct ExposeParameterDialog { + target: GraphTarget, + node: NodeId, + parameter: String, + input: ExposedParameter, + focus_identifier: bool, +} + +impl ExposeParameterDialog { + pub(super) fn open(app: &mut MaterialCraftApp, node: NodeId, parameter: &str, label: &str, value: Option<&Value>) { + let Some(draft) = app.run("graph.exposed.prepare", json!({"label": label, "default": value, "bind": {"node": node, "param": parameter}})) else { + return; + }; + + let Ok(mut input) = serde_json::from_value::(draft) else { + return; + }; + + input.step = Some(input.step()); + app.expose_parameter_dialog = + Some(Self { target: GraphTarget::active(&app.session), node, parameter: parameter.into(), input, focus_identifier: true }); + } + + pub(crate) fn show(app: &mut MaterialCraftApp, context: &egui::Context) { + let Some(mut dialog) = app.expose_parameter_dialog.take() else { + return; + }; + + // Commands can switch documents while a UI dialog is open + if dialog.target != GraphTarget::active(&app.session) || dialog.target.get(&app.session).is_err() { + return; + } + + let mut confirm = false; + let mut cancel = false; + let response = egui::Modal::new(egui::Id::unique("expose-parameter")).show(context, |ui| { + ui.set_width(620.0_f32.min((context.content_rect().width() - 48.0).max(240.0))); + ui.horizontal(|ui| { + ui.heading(tr("Expose Parameter")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel |= crate::widgets::icon_button(ui, egui_phosphor::regular::X, tr("Close expose parameter"), false, 20.0).clicked(); + }); + }); + ui.separator(); + egui::ScrollArea::vertical().max_height((context.content_rect().height() - 160.0).max(160.0)).show(ui, |ui| { + dialog.fields(app, ui); + }); + ui.add_space(8.0); + ui.label(RichText::new(tr("Changes take effect when the graph input is created.")).italics().color(Tokens::get(context).text_dim)); + let validation = dialog.validation(app); + if let Some(error) = &validation { + ui.colored_label(Tokens::get(context).danger, tr(error)); + } + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + cancel |= ui.add_sized([100.0, 28.0], egui::Button::new(tr("Cancel"))).clicked(); + confirm = ui.add_enabled(validation.is_none(), egui::Button::new(tr("OK")).min_size(egui::vec2(100.0, 28.0))).clicked(); + }); + }); + if cancel || response.should_close() { + return; + } + + if confirm { + let mut parameters = json!(dialog.input); + parameters["bind"] = json!({"node": dialog.node, "param": dialog.parameter}); + if app.run("graph.exposed.add", parameters).is_some() { + return; + } + } + + app.expose_parameter_dialog = Some(dialog); + } + + fn fields(&mut self, app: &MaterialCraftApp, ui: &mut Ui) { + egui::Grid::new("expose-fields").num_columns(2).spacing([16.0, 10.0]).show(ui, |ui| { + ui.label(tr("Identifier")); + let response = text(ui, "Identifier", &mut self.input.id); + if self.focus_identifier { + response.request_focus(); + self.focus_identifier = false; + } + ui.end_row(); + ui.label(tr("Label")); + text(ui, "Label", &mut self.input.label); + ui.end_row(); + ui.label(tr("Group")); + ui.horizontal(|ui| { + let width = (ui.available_width() - 30.0).max(80.0); + let response = ui.add(egui::TextEdit::singleline(&mut self.input.group).desired_width(width)); + crate::widgets::name(&response, egui::Role::TextInput, "Group"); + ui.menu_button(egui_phosphor::regular::CARET_DOWN, |ui| { + let groups: std::collections::BTreeSet<_> = app + .session + .graph() + .into_iter() + .flat_map(|graph| &graph.exposed) + .map(|input| input.group.as_str()) + .filter(|group| !group.is_empty()) + .collect(); + if ui.button(tr("None")).clicked() { + self.input.group.clear(); + ui.close(); + } + for group in groups { + if ui.button(group).clicked() { + self.input.group = group.into(); + ui.close(); + } + } + }); + }); + ui.end_row(); + ui.label(tr("Description")); + let response = ui.add(egui::TextEdit::multiline(&mut self.input.description).desired_width(ui.available_width()).desired_rows(4)); + crate::widgets::name(&response, egui::Role::TextInput, "Description"); + ui.end_row(); + ui.label(tr("Type / Editor")); + ui.horizontal(|ui| { + ui.add_enabled( + false, + egui::Button::new(ValueType::of(&self.input.default).map_or("Value", ValueType::label)).min_size(egui::vec2(160.0, 24.0)), + ); + let selected = self.input.editor(); + let response = egui::ComboBox::from_id_salt("expose-editor").selected_text(tr(selected.label())).width(200.0).show_ui(ui, |ui| { + for editor in ParameterEditor::choices(&self.input.default) { + if ui.selectable_label(selected == *editor, tr(editor.label())).clicked() { + self.input.editor = Some(*editor); + } + } + }); + crate::widgets::name(&response.response, egui::Role::ComboBox, "Editor"); + }); + ui.end_row(); + ui.label(tr("Default")); + let editor = self.input.editor(); + let step = self.input.step(); + match &mut self.input.default { + Value::Float(value) if editor == ParameterEditor::Slider => { + ui.spacing_mut().slider_width = (ui.available_width() - 60.0).max(100.0); + let response = + ui.add(egui::Slider::new(value, self.input.min..=self.input.max).clamping(egui::SliderClamping::Never).step_by(f64::from(step))); + crate::widgets::name(&response, egui::Role::Slider, "Default"); + } + Value::Int(value) if editor == ParameterEditor::Slider => { + ui.spacing_mut().slider_width = (ui.available_width() - 60.0).max(100.0); + let response = ui.add(egui::Slider::new(value, self.input.min as i32..=self.input.max as i32).clamping(egui::SliderClamping::Never)); + crate::widgets::name(&response, egui::Role::Slider, "Default"); + } + _ => { + let mut preview = self.input.clone(); + preview.label = tr("Default").into(); + preview.clamp = false; + if let Some(value) = super::input::input_editor(ui, &preview, &self.input.default) + && let Some(value) = self.input.default.coerce_json(&value) + { + self.input.default = value; + } + } + } + ui.end_row(); + if matches!(self.input.editor(), ParameterEditor::Slider | ParameterEditor::Input | ParameterEditor::Color) { + for (label, value) in [("Min", &mut self.input.min), ("Max", &mut self.input.max)] { + ui.label(tr(label)); + let response = ui.add(egui::DragValue::new(value).speed(0.01)); + crate::widgets::name(&response, egui::Role::SpinButton, label); + ui.end_row(); + } + ui.label(tr("Clamp")); + let response = ui.checkbox(&mut self.input.clamp, tr("Limit values to Min and Max")); + crate::widgets::name(&response, egui::Role::CheckBox, "Clamp"); + ui.end_row(); + ui.label(tr("Step")); + let step = self.input.step.get_or_insert(0.01); + let response = ui.add(egui::DragValue::new(step).speed(0.01).max_decimals(6)); + crate::widgets::name(&response, egui::Role::SpinButton, "Step"); + ui.end_row(); + } + }); + } + + fn validation(&self, app: &MaterialCraftApp) -> Option<&'static str> { + let identifier = self.input.id.trim(); + if identifier.is_empty() || !identifier.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') { + return Some("Use letters, digits and underscores for the identifier."); + } + + if app.session.graph().is_ok_and(|graph| graph.exposed.iter().any(|input| input.id == identifier)) { + return Some("An input already uses this identifier."); + } + + if !self.input.min.is_finite() || !self.input.max.is_finite() || self.input.min > self.input.max { + return Some("Min must not exceed Max."); + } + + if self.input.step.is_some_and(|step| !step.is_finite() || step <= 0.0) { + return Some("Step must be greater than zero."); + } + + None + } +} + +fn text(ui: &mut Ui, label: &str, value: &mut String) -> egui::Response { + let response = ui.add(egui::TextEdit::singleline(value).desired_width(ui.available_width())); + crate::widgets::name(&response, egui::Role::TextInput, label); + response +} diff --git a/crates/ui-egui/src/property/input.rs b/crates/ui-egui/src/property/input.rs index e6d49f4..9fc657e 100644 --- a/crates/ui-egui/src/property/input.rs +++ b/crates/ui-egui/src/property/input.rs @@ -1,45 +1,167 @@ use egui::Ui; -use materialcraft_engine::core::Value; +use materialcraft_engine::core::{ExposedParameter, ParameterEditor, Value}; use serde_json::{Value as JsonValue, json}; /// The editor for one exposed input's value; returns the new value as JSON when it changed pub(super) fn input_editor(ui: &mut Ui, exposed: &materialcraft_engine::core::ExposedParameter, current: &Value) -> Option { + let label = if exposed.label.is_empty() { exposed.id.as_str() } else { exposed.label.as_str() }; + let response = ui.vertical(|ui| edit(ui, exposed, current, label)); + response.response.on_hover_text(&exposed.description); + response.inner +} + +fn edit(ui: &mut Ui, exposed: &ExposedParameter, current: &Value, label: &str) -> Option { + if exposed.editor() == ParameterEditor::Input { + ui.label(label); + let mut value = current.clone(); + return numeric_fields(ui, exposed, &mut value).then(|| json!(value)); + } + + if exposed.editor() == ParameterEditor::Color && matches!(current, Value::Float3(_) | Value::Float4(_)) { + let value = current.as_vec4()?; + let mut rgb = [value[0], value[1], value[2]]; + ui.label(label); + if crate::widgets::color_swatch(ui, &format!("exp-{}", exposed.id), &mut rgb, 80.0) { + return Some(match current { + Value::Float4(value) => json!(Value::Float4([rgb[0], rgb[1], rgb[2], value[3]])), + _ => json!(Value::Float3(rgb)), + }); + } + + return None; + } + match *current { - Value::Float(mut f) => { - let initial = f; - crate::widgets::slider(ui, &exposed.label, &mut f, exposed.min.min(initial)..=exposed.max.max(initial), 3).changed().then(|| json!(f)) + Value::Float(mut value) => crate::widgets::input_slider(ui, label, &mut value, exposed, 3).changed().then(|| json!(value)), + Value::Int(integer) => { + let mut value = integer as f32; + crate::widgets::input_slider(ui, label, &mut value, exposed, 0).changed().then(|| json!(value.round())) } - Value::Int(i) => { - let mut f = i as f32; - let initial = f; - crate::widgets::slider(ui, &exposed.label, &mut f, exposed.min.min(initial)..=exposed.max.max(initial), 0).changed().then(|| json!(f.round())) - } - Value::Bool(mut b) => ui.checkbox(&mut b, &exposed.label).changed().then(|| json!(b)), - Value::Enum(i) => { - let mut out = None; - crate::widgets::combo(ui, &exposed.label, exposed.options.get(i as usize).cloned().unwrap_or_default(), |ui| { - for (k, o) in exposed.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, o).clicked() { - out = Some(json!(k)); + Value::Bool(mut value) => ui.checkbox(&mut value, label).changed().then(|| json!(value)), + Value::Enum(selected) => { + let mut changed = None; + crate::widgets::combo(ui, label, exposed.options.get(selected as usize).cloned().unwrap_or_default(), |ui| { + for (index, option) in exposed.options.iter().enumerate() { + if ui.selectable_label(index as u32 == selected, option).clicked() { + changed = Some(json!(index)); } } }); - out + changed } - Value::Color(c) => { - let mut rgb = [c[0], c[1], c[2]]; - let mut out = None; + Value::Color(color) => { + let mut rgb = [color[0], color[1], color[2]]; + let mut changed = None; ui.horizontal(|ui| { - ui.label(&exposed.label); + ui.label(label); if crate::widgets::color_swatch(ui, &format!("exp-{}", exposed.id), &mut rgb, 80.0) { - out = Some(json!([rgb[0], rgb[1], rgb[2], c[3]])); + changed = Some(json!([rgb[0], rgb[1], rgb[2], color[3]])); } }); - out + changed } ref other => { - ui.label(format!("{}: {}", exposed.label, other.type_name())); - None + ui.label(label); + let mut value = other.clone(); + numeric_fields(ui, exposed, &mut value).then(|| json!(value)) } } } + +fn numeric_fields(ui: &mut Ui, input: &ExposedParameter, value: &mut Value) -> bool { + match value { + Value::Float(value) => number(ui, input, value, "Value"), + Value::Float2(values) => components(ui, input, values), + Value::Float3(values) => components(ui, input, values), + Value::Float4(values) | Value::Color(values) => components(ui, input, values), + Value::Int(value) => number(ui, input, value, "Value"), + Value::Int2(values) => components(ui, input, values), + Value::Int3(values) => components(ui, input, values), + Value::Int4(values) => components(ui, input, values), + _ => crate::value_editor::show(ui, value), + } +} + +fn components(ui: &mut Ui, input: &ExposedParameter, values: &mut [N]) -> bool { + let mut changed = false; + for (value, label) in values.iter_mut().zip(["X", "Y", "Z", "W"]) { + changed |= number(ui, input, value, label); + } + changed +} + +fn number(ui: &mut Ui, input: &ExposedParameter, value: &mut N, label: &str) -> bool { + let range = f64::from(input.min)..=f64::from(input.max); + let response = if input.editor() == ParameterEditor::Slider { + ui.add( + egui::Slider::new(value, N::from_f64(*range.start())..=N::from_f64(*range.end())) + .text(label) + .step_by(f64::from(input.step())) + .clamping(if input.clamp { egui::SliderClamping::Edits } else { egui::SliderClamping::Never }), + ) + } else { + let mut widget = egui::DragValue::new(value).speed(input.step()).clamp_existing_to_range(false); + if input.clamp { + widget = widget.range(range); + } + ui.add(widget) + }; + crate::widgets::name(&response, egui::Role::SpinButton, label); + response.changed() +} + +#[cfg(test)] +mod tests { + use super::*; + use egui_kittest::{ + Harness, + kittest::{By, Queryable}, + }; + + #[test] + fn exposed_sliders_apply_step_and_allow_values_outside_soft_limits() { + for (clamp, expected) in [(false, 1.5), (true, 1.0)] { + let input: ExposedParameter = serde_json::from_value(json!({ + "id": "amount", "label": "Amount", "default": {"t": "float", "v": 0.5}, + "min": 0.0, "max": 1.0, "step": 0.25, "clamp": clamp + })) + .unwrap(); + let mut harness = Harness::new_ui_state( + |ui, value: &mut Value| { + if let Some(edited) = input_editor(ui, &input, value) { + *value = value.coerce_json(&edited).unwrap(); + } + }, + Value::Float(0.5), + ); + harness.run(); + + harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Amount")).click(); + harness.run(); + harness.key_combination_modifiers(egui::Modifiers::COMMAND, &[egui::Key::A]); + harness.event(egui::Event::Text("1.38".into())); + harness.run(); + + assert_eq!(harness.state(), &Value::Float(expected)); + } + } + + #[test] + fn editing_a_slider_with_reversed_imported_limits_does_not_panic() { + let mut harness = Harness::new_ui_state( + |ui, value: &mut f32| { + crate::widgets::slider(ui, "Amount", value, 3.0..=2.0, 3); + }, + 2.5, + ); + harness.run(); + + harness.get(By::new().role(egui::accesskit::Role::TextInput).label("Amount")).click(); + harness.run(); + harness.key_combination_modifiers(egui::Modifiers::COMMAND, &[egui::Key::A]); + harness.event(egui::Event::Text("2.75".into())); + harness.run(); + + assert_eq!(*harness.state(), 2.75); + } +} diff --git a/crates/ui-egui/src/property/mod.rs b/crates/ui-egui/src/property/mod.rs index 9eadab1..10f11b5 100644 --- a/crates/ui-egui/src/property/mod.rs +++ b/crates/ui-egui/src/property/mod.rs @@ -1,4 +1,5 @@ mod curve; +mod expose_parameter_dialog; mod folder_property_draft; mod gradient; mod graph; @@ -7,9 +8,11 @@ mod graph_property_draft; mod input; mod node; mod parameter; +mod parameter_control; mod section; pub use curve::curve_editor; +pub(crate) use expose_parameter_dialog::ExposeParameterDialog; pub(crate) use folder_property_draft::FolderPropertyDraft; pub use gradient::gradient_editor; pub(crate) use graph_property_draft::GraphPropertyDraft; @@ -34,7 +37,15 @@ pub fn title(app: &MaterialCraftApp) -> String { EditorTarget::Pattern if !EditorTarget::annotation_active(app) => return crate::pattern::properties::title(app), EditorTarget::Function if !EditorTarget::annotation_active(app) => { return crate::function::properties::title(app).unwrap_or_else(|| { - let name = app.session.graph().ok().filter(|graph| graph.function.is_some()).map_or(tr("Function Graph"), |graph| graph.name.as_str()); + let owner = app + .function_editor + .as_ref() + .and_then(|editor| editor.node) + .and_then(|id| app.session.graph().ok()?.node(id).ok()) + .map(crate::graph::node_label); + let name = owner + .or_else(|| app.session.graph().ok().filter(|graph| graph.function.is_some()).map(|graph| graph.name.clone())) + .unwrap_or_else(|| tr("Function Graph").into()); format!("{name} - {}", tr("Properties")) }); } @@ -82,6 +93,10 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { if !crate::function::properties::show(app, ui) { if app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, crate::function::FunctionTarget::Graph)) { graph::show(app, ui, materialcraft_engine::GraphTarget::active(&app.session)); + } else if let Some(owner) = + app.function_editor.as_ref().and_then(|editor| editor.node).and_then(|id| app.session.graph().ok()?.node(id).ok()).cloned() + { + node::show(app, ui, &owner); } else { ui.label(tr("Select a node")); } diff --git a/crates/ui-egui/src/property/node.rs b/crates/ui-egui/src/property/node.rs index b784639..9a0023d 100644 --- a/crates/ui-egui/src/property/node.rs +++ b/crates/ui-egui/src/property/node.rs @@ -1,17 +1,15 @@ -use super::{ - input::input_editor, - parameter::{function_row, param_row}, - section, -}; +use super::{input::input_editor, parameter::param_row, section}; use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; use egui::{Rect, RichText, Ui, vec2}; use egui_phosphor::regular as icon; -use materialcraft_engine::core::{OutputFormat, SizeMode}; +use materialcraft_engine::core::{BaseParameter, ExposedParameter, ParameterInheritance, Value}; +use materialcraft_engine::nodes::ParameterDescriptor; use serde_json::json; pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { let tokens = Tokens::get(ui.ctx()); let definition = materialcraft_engine::nodes::find(&node.def); + // Header: label (renamable) and description ui.horizontal(|ui| { ui.painter().rect_filled(Rect::from_min_size(ui.cursor().min + vec2(0.0, 2.0), vec2(4.0, 16.0)), 1.0, crate::graph::header_color(&node.def)); @@ -36,100 +34,120 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft ui.add_space(4.0); section(ui, "base", tr("Base parameters"), |ui| base_params(app, ui, node)); crate::value_input_editor::show(app, ui, node); - if node.def == "input_value" { - crate::value_input_editor::default_value(app, ui, node); + if node.def == "input_value" + && let Some(descriptor) = ParameterDescriptor::for_node(&app.session.pkg, node, "default") + { + super::parameter_control::show(app, ui, node, &descriptor, None, |app, ui| { + ui.label(tr("Default value")); + crate::value_input_editor::default_value(app, ui, node); + }); } if node.def == "graph_instance" { section(ui, "instance", tr("Instance parameters"), |ui| instance_params(app, ui, node)); return; } + let Some(definition) = definition else { return }; if definition.params.is_empty() { return; } + section(ui, "specific", tr("Specific parameters"), |ui| { if node.def == "levels" { crate::levels_editor::show(app, ui, node); ui.add_space(6.0); } - let exposed: Vec<(String, String)> = - app.session.graph().map(|g| g.exposed.iter().map(|entry| (entry.id.clone(), entry.label.clone())).collect()).unwrap_or_default(); for parameter in &definition.params { if node.def == "input_value" && parameter.id == "default" { continue; } + let current = node.params.get(parameter.id).cloned().unwrap_or_else(|| parameter.default.clone()); - if node.functions.contains_key(parameter.id) { - function_row(app, ui, node.id, parameter.id, parameter.label); - continue; + if let Some(descriptor) = ParameterDescriptor::for_node(&app.session.pkg, node, parameter.id) + && descriptor.supports_function + { + super::parameter_control::show(app, ui, node, &descriptor, None, |app, ui| param_row(app, ui, node.id, parameter, current)); + } else { + param_row(app, ui, node.id, parameter, current); } - let bound = node.bindings.get(parameter.id).cloned(); - param_row(app, ui, node.id, parameter, current, bound, &exposed); } }); } fn base_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { - let base = &node.base; - let id = node.id.0; - let modes = [(SizeMode::RelativeToInput, "Relative to input"), (SizeMode::RelativeToParent, "Relative to parent"), (SizeMode::Absolute, "Absolute")]; - let current = modes.iter().find(|mode| mode.0 == base.size_mode).map_or("", |mode| mode.1); - crate::widgets::combo(ui, tr("Output size"), tr(current), |ui| { - for (mode, label) in modes { - if ui.selectable_label(base.size_mode == mode, tr(label)).clicked() { - let key = match mode { - SizeMode::RelativeToInput => "relativeToInput", - SizeMode::RelativeToParent => "relativeToParent", - SizeMode::Absolute => "absolute", - }; + for parameter in BaseParameter::ALL { + let descriptor = ParameterDescriptor::base(parameter); + let driven = super::parameter_control::header(app, ui, node, &descriptor, parameter); + let inheritance = parameter.inheritance(&node.base); + ui.push_id(parameter, |ui| { + if !driven && parameter == BaseParameter::OutputSize { + size_control(app, ui, node); + } else if !driven { + let mut value = parameter.value(&node.base); + let editable = inheritance == ParameterInheritance::Absolute || matches!(parameter, BaseParameter::PixelSize | BaseParameter::RandomSeed); + if !editable && let Some(result) = app.session.cooked.nodes.get(&node.id) { + value = match parameter { + BaseParameter::Format => { + BaseParameter::Format.value(&materialcraft_engine::core::BaseParameters { format: result.base.format, ..Default::default() }) + } + BaseParameter::PixelRatio => Value::Int(result.base.pixel_ratio), + BaseParameter::Tiling => Value::Int(i32::from(result.base.tiling[0]) | (i32::from(result.base.tiling[1]) << 1)), + _ => value, + }; + } - let size = if mode == SizeMode::Absolute { json!([10, 10]) } else { json!([0, 0]) }; - app.run("graph.node.base", json!({"id": id, "sizeMode": key, "size": size})); + let value = if descriptor.options.is_empty() { value } else { Value::Enum(value.as_i32().unwrap_or(0).max(0) as u32) }; + let input = ExposedParameter { + description: String::new(), + editor: None, + clamp: false, + step: None, + id: descriptor.id.clone(), + label: if parameter == BaseParameter::RandomSeed { descriptor.label.clone() } else { tr("Value").into() }, + group: String::new(), + default: descriptor.default, + min: descriptor.min, + max: descriptor.max, + options: descriptor.options, + }; + if let Some(value) = ui.add_enabled_ui(editable, |ui| input_editor(ui, &input, &value)).inner { + app.run("graph.node.base", json!({"id": node.id, "param": parameter.identifier(), "value": value})); + } + if parameter == BaseParameter::RandomSeed && ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { + let seed = (crate::now_ms() as u64 ^ node.id.0).wrapping_mul(2654435761) % 1000; + app.run("graph.node.base", json!({"id": node.id, "param": parameter.identifier(), "value": seed})); + } } - } - }); - let (minimum, maximum) = if base.size_mode == SizeMode::Absolute { (4.0, 13.0) } else { (-6.0, 6.0) }; - for (axis, label) in [(0usize, "Width"), (1, "Height")] { - let mut value = base.size[axis] as f32; - let caption = if base.size_mode == SizeMode::Absolute { - format!("{label} {} px", 1u32 << base.size[axis].clamp(4, 13)) + }); + ui.add_space(4.0); + } +} + +fn size_control(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft_engine::core::Node) { + let link_id = ui.make_persistent_id("size-axes-linked"); + let mut linked = ui.data(|data| data.get_temp::(link_id)).unwrap_or(node.base.size[0] == node.base.size[1]); + if ui.checkbox(&mut linked, tr("Link width and height")).changed() { + ui.data_mut(|data| data.insert_temp(link_id, linked)); + } + + let absolute = node.base.size_mode == materialcraft_engine::core::SizeMode::Absolute; + for (axis, label) in [(0, "Width"), (1, "Height")] { + let mut exponent = node.base.size[axis] as f32; + let caption = if absolute { + format!("{}: {} px", tr(label), 1u32 << node.base.size[axis].clamp(4, 13)) } else { - format!("{label} x {}", 2f32.powi(base.size[axis])) + format!("{}: ×{}", tr(label), 2f32.powi(node.base.size[axis].clamp(-12, 12))) }; - - if crate::widgets::slider(ui, &caption, &mut value, minimum..=maximum, 0).changed() { - let mut size = base.size; - size[axis] = value.round() as i32; - app.run("graph.node.base", json!({"id": id, "size": size})); - } - } - crate::widgets::combo(ui, tr("Output format"), tr(base.format.label()), |ui| { - for format in OutputFormat::ALL { - if ui.selectable_label(base.format == format, tr(format.label())).clicked() { - let key = match format { - OutputFormat::Inherit => "inherit", - OutputFormat::U8 => "u8", - OutputFormat::U16 => "u16", - OutputFormat::F16 => "f16", - OutputFormat::F32 => "f32", - }; - - app.run("graph.node.base", json!({"id": id, "format": key})); + if crate::widgets::slider(ui, &caption, &mut exponent, if absolute { 4.0..=13.0 } else { -12.0..=12.0 }, 0).changed() { + let mut size = node.base.size; + size[axis] = exponent.round() as i32; + if linked { + size[1 - axis] = size[axis]; } + + app.run("graph.node.base", json!({"id": node.id, "param": "outputsize", "value": size})); } - }); - let mut seed = base.seed as f32; - if crate::widgets::slider(ui, tr("Random seed"), &mut seed, 0.0..=1000.0, 0).changed() { - app.run("graph.node.base", json!({"id": id, "seed": seed.round() as i64})); - } - if ui.button(format!("{} {}", icon::SHUFFLE, tr("New random seed"))).clicked() { - let seed = (crate::now_ms() as u64 ^ id).wrapping_mul(2654435761) % 1000; - app.run("graph.node.base", json!({"id": id, "seed": seed})); - } - let mut tiling = base.tiling[0] && base.tiling[1]; - if ui.checkbox(&mut tiling, tr("Tiling (H and V)")).changed() { - app.run("graph.node.base", json!({"id": id, "tiling": tiling})); } } @@ -146,13 +164,23 @@ fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft crate::menus::invoke(app, ui.ctx(), "graph.node.edit"); return; } + if exposed.is_empty() { ui.label(RichText::new(tr("This graph exposes no inputs")).color(tokens.text_dim)); } for entry in exposed { let current = node.params.get(&entry.id).cloned().unwrap_or_else(|| entry.default.clone()); - if let Some(value) = input_editor(ui, &entry, ¤t) { - app.run("graph.node.param", json!({"id": node.id.0, "param": entry.id, "value": value})); + let literal = |app: &mut MaterialCraftApp, ui: &mut Ui| { + if let Some(value) = input_editor(ui, &entry, ¤t) { + app.run("graph.node.param", json!({"id": node.id.0, "param": entry.id, "value": value})); + } + }; + if let Some(descriptor) = ParameterDescriptor::for_node(&app.session.pkg, node, &entry.id) + && descriptor.supports_function + { + super::parameter_control::show(app, ui, node, &descriptor, None, literal); + } else { + literal(app, ui); } } } diff --git a/crates/ui-egui/src/property/parameter.rs b/crates/ui-egui/src/property/parameter.rs index 6d253e5..b1d1245 100644 --- a/crates/ui-egui/src/property/parameter.rs +++ b/crates/ui-egui/src/property/parameter.rs @@ -6,124 +6,69 @@ use materialcraft_engine::core::{NodeId, Value}; use materialcraft_engine::nodes::ParameterDefinition; use serde_json::{Value as JsonValue, json}; -fn set(app: &mut MaterialCraftApp, node: NodeId, param: &str, value: JsonValue) { - app.run("graph.node.param", json!({"id": node.0, "param": param, "value": value})); +fn set(app: &mut MaterialCraftApp, node: NodeId, parameter: &str, value: JsonValue) { + app.run("graph.node.param", json!({"id": node.0, "param": parameter, "value": value})); } -fn typed(v: &Value) -> JsonValue { - serde_json::to_value(v).unwrap_or(JsonValue::Null) +fn typed(value: &Value) -> JsonValue { + serde_json::to_value(value).unwrap_or(JsonValue::Null) } -/// One parameter: its editor, plus the expose/bind menu -pub(super) fn param_row( - app: &mut MaterialCraftApp, - ui: &mut Ui, - node: NodeId, - parameter: &ParameterDefinition, - current: Value, - bound: Option, - exposed: &[(String, String)], -) { +/// The literal editor inside a parameter control +pub(super) fn param_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, parameter: &ParameterDefinition, current: Value) { let tokens = Tokens::get(ui.ctx()); - if let Some(input) = &bound { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - ui.label(RichText::new(format!("{} {input}", icon::LINK)).color(tokens.accent)); - if crate::widgets::icon_button(ui, icon::LINK_BREAK, tr("Unbind"), false, 18.0).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": parameter.id, "input": JsonValue::Null})); - } - }); - return; - } - let show_menu = |app: &mut MaterialCraftApp, resp: &egui::Response| { - resp.context_menu(|ui| { - if ui.button(tr("Reset to default")).clicked() { - app.run("graph.node.reset", json!({"id": node.0, "param": parameter.id})); - ui.close(); - } - let dynamic = !matches!(parameter.default, Value::Text(_) | Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_)); - if dynamic && ui.button(tr("Set function...")).clicked() { - if app.run("graph.node.function", json!({"id": node.0, "param": parameter.id})).is_some() { - crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Dynamic(parameter.id.to_string())); - } - ui.close(); - } - if ui.button(tr("Expose as graph input")).clicked() { - // No `id`: the engine names the input after the parameter and keeps it unique when another node exposed it too - app.run("graph.exposed.add", json!({"label": parameter.label, "bind": {"node": node.0, "param": parameter.id}})); - ui.close(); - } - if !exposed.is_empty() { - ui.menu_button(tr("Bind to input"), |ui| { - for (id, label) in exposed { - if ui.button(label).clicked() { - app.run("graph.node.bind", json!({"id": node.0, "param": parameter.id, "input": id})); - ui.close(); - } - } - }); - } - }); - }; - match current { - Value::Float(mut v) => { + Value::Float(mut value) => { if parameter.angle { - let mut degrees = v * 360.0; + let mut degrees = value * 360.0; let response = crate::widgets::slider(ui, tr(parameter.label), &mut degrees, -360.0..=360.0, 1); if response.changed() { - v = degrees / 360.0; - set(app, node, parameter.id, json!(v)); + value = degrees / 360.0; + set(app, node, parameter.id, json!(value)); } - show_menu(app, &response); } else { - let (minimum, maximum) = (parameter.min.min(v), parameter.max.max(v)); - let response = crate::widgets::slider(ui, tr(parameter.label), &mut v, minimum..=maximum, if maximum - minimum > 20.0 { 1 } else { 3 }); + let (minimum, maximum) = (parameter.min.min(value), parameter.max.max(value)); + let response = crate::widgets::slider(ui, tr(parameter.label), &mut value, minimum..=maximum, if maximum - minimum > 20.0 { 1 } else { 3 }); if response.changed() { - set(app, node, parameter.id, json!(v)); + set(app, node, parameter.id, json!(value)); } - show_menu(app, &response); } } - Value::Int(i) => { - let mut v = i as f32; - let range = parameter.min.min(v)..=parameter.max.max(v); - let response = crate::widgets::slider(ui, tr(parameter.label), &mut v, range, 0); - if response.changed() && v.round() as i32 != i { - set(app, node, parameter.id, json!(v.round() as i32)); + Value::Int(integer) => { + let mut value = integer as f32; + let range = parameter.min.min(value)..=parameter.max.max(value); + let response = crate::widgets::slider(ui, tr(parameter.label), &mut value, range, 0); + if response.changed() && value.round() as i32 != integer { + set(app, node, parameter.id, json!(value.round() as i32)); } - show_menu(app, &response); } - Value::Float2(v) => { + Value::Float2(value) => { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - let mut nv = v; - for (k, axis) in ["X", "Y"].iter().enumerate() { - let range = parameter.min.min(nv[k])..=parameter.max.max(nv[k]); - let response = crate::widgets::slider(ui, axis, &mut nv[k], range, 3); + let mut components = value; + for (index, axis) in ["X", "Y"].iter().enumerate() { + let range = parameter.min.min(components[index])..=parameter.max.max(components[index]); + let response = crate::widgets::slider(ui, axis, &mut components[index], range, 3); if response.changed() { - set(app, node, parameter.id, json!(nv)); + set(app, node, parameter.id, json!(components)); } - show_menu(app, &response); } } - Value::Int2(v) => { + Value::Int2(value) => { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - for k in 0..2 { - let mut f = v[k] as f32; - if crate::widgets::slider(ui, ["X", "Y"][k], &mut f, parameter.min..=parameter.max, 0).changed() { - let mut nv = v; - nv[k] = f.round() as i32; - set(app, node, parameter.id, json!(nv)); + for index in 0..2 { + let mut number = value[index] as f32; + if crate::widgets::slider(ui, ["X", "Y"][index], &mut number, parameter.min..=parameter.max, 0).changed() { + let mut components = value; + components[index] = number.round() as i32; + set(app, node, parameter.id, json!(components)); } } } - Value::Bool(b) => { - let mut v = b; - let response = ui.checkbox(&mut v, tr(parameter.label)); + Value::Bool(mut value) => { + let response = ui.checkbox(&mut value, tr(parameter.label)); if response.changed() { - set(app, node, parameter.id, json!(v)); + set(app, node, parameter.id, json!(value)); } - show_menu(app, &response); } Value::Float3(_) | Value::Float4(_) | Value::Int3(_) | Value::Int4(_) => { ui.label(tr(parameter.label)); @@ -132,33 +77,33 @@ pub(super) fn param_row( set(app, node, parameter.id, serde_json::to_value(value).unwrap_or_default()); } } - Value::Color(c) => { + Value::Color(color) => { ui.horizontal(|ui| { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut rgb = [c[0], c[1], c[2]]; + let mut rgb = [color[0], color[1], color[2]]; if crate::widgets::color_swatch(ui, &format!("{}-{}", node.0, parameter.id), &mut rgb, 90.0) { - set(app, node, parameter.id, json!([rgb[0], rgb[1], rgb[2], c[3]])); + set(app, node, parameter.id, json!([rgb[0], rgb[1], rgb[2], color[3]])); } }); }); } - Value::Enum(i) => { - let current = parameter.options.get(i as usize).copied().unwrap_or("?"); - crate::widgets::combo(ui, tr(parameter.label), tr(current), |ui| { - for (k, o) in parameter.options.iter().enumerate() { - if ui.selectable_label(k as u32 == i, tr(o)).clicked() { - set(app, node, parameter.id, json!(k)); + Value::Enum(selected) => { + let selected_label = parameter.options.get(selected as usize).copied().unwrap_or("?"); + crate::widgets::combo(ui, tr(parameter.label), tr(selected_label), |ui| { + for (index, option) in parameter.options.iter().enumerate() { + if ui.selectable_label(index as u32 == selected, tr(option)).clicked() { + set(app, node, parameter.id, json!(index)); } } }); } - Value::Text(t) if parameter.resource => { + Value::Text(text) if parameter.resource => { let names: Vec = app.session.pkg.resources.iter().map(|response| response.name.clone()).collect(); - crate::widgets::combo(ui, tr(parameter.label), if t.is_empty() { tr("(checker)").to_string() } else { t.clone() }, |ui| { - for n in &names { - if ui.selectable_label(*n == t, n).clicked() { - set(app, node, parameter.id, json!(n)); + crate::widgets::combo(ui, tr(parameter.label), if text.is_empty() { tr("(checker)").to_string() } else { text.clone() }, |ui| { + for name in &names { + if ui.selectable_label(*name == text, name).clicked() { + set(app, node, parameter.id, json!(name)); } } }); @@ -166,50 +111,35 @@ pub(super) fn param_row( crate::menus::invoke(app, ui.ctx(), "file.importBitmap"); } } - Value::Text(t) => { + Value::Text(text) => { ui.horizontal(|ui| { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - let mut s = t.clone(); - let response = ui.add(egui::TextEdit::singleline(&mut s).desired_width(ui.available_width())); + let mut draft = text.clone(); + let response = ui.add(egui::TextEdit::singleline(&mut draft).desired_width(ui.available_width())); crate::widgets::name(&response, egui::Role::TextInput, parameter.label); if response.changed() { - set(app, node, parameter.id, json!(s)); + set(app, node, parameter.id, json!(draft)); } }); } - Value::Curve(c) => { + Value::Curve(curve) => { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - if let Some(nc) = curve_editor(ui, &format!("curve-{}-{}", node.0, parameter.id), &c) { - set(app, node, parameter.id, json!(nc.points.iter().map(|q| [q.x, q.y]).collect::>())); + if let Some(edited_curve) = curve_editor(ui, &format!("curve-{}-{}", node.0, parameter.id), &curve) { + set(app, node, parameter.id, json!(edited_curve.points.iter().map(|point| [point.x, point.y]).collect::>())); } } - Value::Gradient(g) => { + Value::Gradient(gradient) => { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - if let Some(ng) = gradient_editor(ui, &format!("grad-{}-{}", node.0, parameter.id), &g) { - set(app, node, parameter.id, typed(&Value::Gradient(ng))); + if let Some(edited_gradient) = gradient_editor(ui, &format!("grad-{}-{}", node.0, parameter.id), &gradient) { + set(app, node, parameter.id, typed(&Value::Gradient(edited_gradient))); } } Value::PatternGraph(graph) => { ui.label(format!("{}: {} nodes", parameter.label, graph.nodes.len())); } - Value::Function(f) => { + Value::Function(function) => { ui.label(RichText::new(tr(parameter.label)).color(tokens.text)); - crate::windows::function_summary(app, ui, node, parameter.id, &f); + crate::windows::function_summary(app, ui, node, parameter.id, &function); } } } - -/// A parameter driven by a function: its label, Edit and Remove -pub(super) fn function_row(app: &mut MaterialCraftApp, ui: &mut Ui, node: NodeId, param: &str, label: &str) { - let tokens = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr(label)).color(tokens.text)); - ui.label(RichText::new(format!("{} {}", icon::FUNCTION, tr("function"))).color(tokens.accent)); - if ui.small_button(tr("Edit")).clicked() { - crate::graph::subgraph_navigation::open_function(app, node, crate::function::FunctionTarget::Dynamic(param.to_string())); - } - if crate::widgets::icon_button(ui, icon::X, tr("Remove function"), false, 18.0).clicked() { - app.run("graph.node.function", json!({"id": node.0, "param": param, "remove": true})); - } - }); -} diff --git a/crates/ui-egui/src/property/parameter_control.rs b/crates/ui-egui/src/property/parameter_control.rs new file mode 100644 index 0000000..a31ddc4 --- /dev/null +++ b/crates/ui-egui/src/property/parameter_control.rs @@ -0,0 +1,158 @@ +use crate::{MaterialCraftApp, i18n::tr, theme::Tokens}; +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use materialcraft_engine::{ + core::{BaseParameter, FunctionGraph, Node, ParameterInheritance, ValueType}, + nodes::ParameterDescriptor, +}; +use serde_json::json; + +pub(super) fn header(app: &mut MaterialCraftApp, ui: &mut Ui, node: &Node, descriptor: &ParameterDescriptor, base: BaseParameter) -> bool { + show(app, ui, node, descriptor, Some(base), |_, _| {}) +} + +pub(super) fn show( + app: &mut MaterialCraftApp, + ui: &mut Ui, + node: &Node, + descriptor: &ParameterDescriptor, + base: Option, + literal: impl FnOnce(&mut MaterialCraftApp, &mut Ui), +) -> bool { + let function = base.map_or_else(|| node.functions.get(&descriptor.id), |parameter| node.base.functions.get(¶meter)); + let bound = function + .and_then(FunctionGraph::input_identifier) + .filter(|identifier| app.session.graph().is_ok_and(|graph| graph.exposed.iter().any(|input| input.id == *identifier))) + .or_else(|| base.is_none().then(|| node.bindings.get(&descriptor.id).map(String::as_str)).flatten()); + let driven = function.is_some() || bound.is_some(); + let evaluated = (!app.session.dirty && !app.cooker.busy()) + .then(|| app.session.cooked.nodes.get(&node.id)) + .flatten() + .filter(|result| result.error.is_none()) + .and_then(|result| base.map_or_else(|| result.parameters.get(&descriptor.id), |parameter| result.base_values.get(¶meter))) + .cloned(); + let can_capture = function.is_none() || evaluated.is_some(); + let tokens = Tokens::get(ui.ctx()); + ui.push_id((node.id, base.is_some(), &descriptor.id), |ui| { + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), ui.spacing().interact_size.y), egui::Layout::left_to_right(egui::Align::Min), |ui| { + let actions_width = 32.0 + if driven { 26.0 } else { 0.0 } + if base.is_some() { 26.0 } else { 0.0 }; + let content_width = (ui.available_width() - actions_width).max(40.0); + ui.vertical(|ui| { + ui.set_width(content_width); + if base.is_some() || driven { + ui.label(RichText::new(&descriptor.label).color(if driven { tokens.accent } else { tokens.text })); + } else { + literal(app, ui); + } + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let menu = ui.menu_button(icon::DOTS_THREE, |ui| { + for (mode, label) in [("empty", "Empty function"), ("constant", "Constant value")] { + if ui.add_enabled(mode == "empty" || can_capture, egui::Button::new(tr(label))).clicked() { + let parameters = json!({ + "id": node.id, "param": descriptor.id, "base": base.is_some(), "mode": mode, + "value": (mode == "constant").then_some(evaluated.as_ref()).flatten() + }); + if app.run("graph.node.function", parameters).is_some() { + edit(app, node, descriptor, base); + } + ui.close(); + } + } + if driven && ui.button(tr("Edit function")).clicked() { + edit(app, node, descriptor, base); + ui.close(); + } + if let Some(input) = bound + && ui.button(format!("{}: {input}", tr("Edit exposed input"))).clicked() + { + app.inspected_graph = Some(materialcraft_engine::GraphTarget::active(&app.session)); + ui.close(); + } + if base.is_none() { + ui.separator(); + if ui.add_enabled(can_capture, egui::Button::new(tr("Expose as new graph input"))).clicked() { + super::ExposeParameterDialog::open(app, node.id, &descriptor.id, &descriptor.label, evaluated.as_ref()); + ui.close(); + } + let inputs = app + .session + .graph() + .map(|graph| { + graph + .exposed + .iter() + .filter(|input| ValueType::of(&input.default) == ValueType::of(&descriptor.default)) + .map(|input| (input.id.clone(), input.label.clone())) + .collect::>() + }) + .unwrap_or_default(); + if !inputs.is_empty() { + ui.menu_button(tr("Bind to input"), |ui| { + for (identifier, label) in inputs { + if ui.button(label).clicked() { + app.run("graph.node.bind", json!({"id": node.id, "param": descriptor.id, "base": base.is_some(), "input": identifier})); + ui.close(); + } + } + }); + } + } + ui.separator(); + if ui.button(tr("Reset to default")).clicked() { + app.run("graph.node.reset", json!({"id": node.id, "param": descriptor.id, "base": base.is_some()})); + ui.close(); + } + }); + crate::widgets::name(&menu.response, egui::Role::Button, &format!("Parameter actions: {}", descriptor.label)); + if driven && crate::widgets::icon_button(ui, icon::FUNCTION, tr("Edit function"), false, 18.0).clicked() { + edit(app, node, descriptor, base); + } + if let Some(parameter) = base { + inheritance(app, ui, node, parameter); + } + }); + }); + }); + if let Some(input) = bound { + ui.label(RichText::new(format!("{} {input}", icon::LINK)).small().color(tokens.accent)); + } + + driven +} + +fn edit(app: &mut MaterialCraftApp, node: &Node, descriptor: &ParameterDescriptor, base: Option) { + if base.is_none() + && let Some(input) = node.bindings.get(&descriptor.id) + && app.run("graph.node.bind", json!({"id": node.id, "param": descriptor.id, "base": base.is_some(), "input": input})).is_none() + { + return; + } + + app.run("graph.node.function.edit", json!({"id": node.id, "param": descriptor.id, "base": base.is_some()})); +} + +fn inheritance(app: &mut MaterialCraftApp, ui: &mut Ui, node: &Node, parameter: BaseParameter) { + let current = parameter.inheritance(&node.base); + let modes = [ + (ParameterInheritance::RelativeToInput, "Relative to input"), + (ParameterInheritance::RelativeToParent, "Relative to parent"), + (ParameterInheritance::Absolute, "Absolute"), + ]; + let label = modes.iter().find(|(mode, _)| *mode == current).map_or("", |(_, label)| *label); + let symbol = match current { + ParameterInheritance::RelativeToInput => icon::SIGN_IN, + ParameterInheritance::RelativeToParent => icon::TREE_STRUCTURE, + ParameterInheritance::Absolute => icon::EQUALS, + }; + let menu = ui.menu_button(symbol, |ui| { + for (mode, label) in modes { + if ui.selectable_label(mode == current, tr(label)).clicked() { + app.run("graph.node.base", json!({"id": node.id, "param": parameter.identifier(), "inheritance": mode})); + ui.close(); + } + } + }); + crate::widgets::name(&menu.response, egui::Role::Button, &format!("{} inheritance: {label}", parameter.label())); + menu.response.on_hover_text(tr(label)); +} diff --git a/crates/ui-egui/src/shell/modality.rs b/crates/ui-egui/src/shell/modality.rs index cd15d62..cea1969 100644 --- a/crates/ui-egui/src/shell/modality.rs +++ b/crates/ui-egui/src/shell/modality.rs @@ -96,7 +96,8 @@ fn open_blocker(app: &MaterialCraftApp) -> Option { if windows.package_save.is_some() { return Some(Blocker::Dialog); } - (windows.new_graph || windows.export || windows.preferences || windows.about || app.ui.explorer.rename.is_some()).then_some(Blocker::Dialog) + (app.expose_parameter_dialog.is_some() || windows.new_graph || windows.export || windows.preferences || windows.about || app.ui.explorer.rename.is_some()) + .then_some(Blocker::Dialog) } #[cfg(test)] diff --git a/crates/ui-egui/src/view2d.rs b/crates/ui-egui/src/view2d.rs index 0831094..33d4c11 100644 --- a/crates/ui-egui/src/view2d.rs +++ b/crates/ui-egui/src/view2d.rs @@ -180,14 +180,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } // Info line: size, format, zoom and the pixel under the pointer. let info = Rect::from_min_size(pos2(rect.left(), rect.bottom()), vec2(rect.width(), 20.0)); - let bits = app - .session - .graph() - .ok() - .and_then(|g| { - g.node(id).ok().map(|n| if n.base.format == materialcraft_engine::core::OutputFormat::Inherit { g.format.bits() } else { n.base.format.bits() }) - }) - .unwrap_or("16"); + let bits = app.session.cooked.nodes.get(&id).map_or("16", |result| result.base.format.bits()); let mut text = format!("{} x {} ({}, {}bpc) {:.0}%", img.w, img.h, if img.is_gray() { "L" } else { "RGBA" }, bits, cam.zoom * 100.0); if let Some(ptr) = resp.hover_pos() { let local = (ptr - (center - size * 0.5)) / cam.zoom; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 0704943..3601287 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -22,15 +22,44 @@ pub fn dnd_release(resp: &Response) -> Option, decimals: usize) -> Response { + slider_with_settings(ui, label, value, range, decimals, None) +} + +pub(crate) fn input_slider(ui: &mut Ui, label: &str, value: &mut f32, input: &materialcraft_engine::core::ExposedParameter, decimals: usize) -> Response { + let range = if input.clamp { input.min..=input.max } else { input.min.min(*value)..=input.max.max(*value) }; + slider_with_settings(ui, label, value, range, decimals, Some(input)) +} + +fn slider_with_settings( + ui: &mut Ui, + label: &str, + value: &mut f32, + range: std::ops::RangeInclusive, + decimals: usize, + settings: Option<&materialcraft_engine::core::ExposedParameter>, +) -> Response { let tk = Tokens::get(ui.ctx()); - let (lo, hi) = (*range.start(), *range.end()); + + // Imported widget limits may be reversed or non-finite + let first = if range.start().is_finite() { *range.start() } else { 0.0 }; + let last = if range.end().is_finite() { *range.end() } else { 1.0 }; + let (lo, hi) = (first.min(last), first.max(last)); + let constrain = |value: f32, clamp: bool| { + let value = if let Some(step) = settings.and_then(|input| input.step).filter(|step| step.is_finite() && *step > 0.0) { + let snapped = ((f64::from(value) / f64::from(step)).round() * f64::from(step)) as f32; + if snapped.is_finite() { snapped } else { value } + } else { + value + }; + if clamp { value.clamp(lo, hi) } else { value } + }; let w = ui.available_width(); let mut edited = false; ui.horizontal(|ui| { ui.label(RichText::new(label).color(tk.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - // Keep incomplete input (such as "-") across frames while editing. + // Keep incomplete input (such as "-") across frames while editing let draft = id.with("numeric-draft"); let editing = ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id)); let mut text = editing.then(|| ui.data(|d| d.get_temp::(draft))).flatten().unwrap_or_else(|| format!("{:.*}", decimals, value)); @@ -41,7 +70,7 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI && let Ok(v) = text.trim().parse::() && v.is_finite() { - let v = v.clamp(lo, hi); + let v = constrain(v, settings.is_none_or(|input| input.clamp)); edited = v != *value; *value = v; } @@ -68,11 +97,11 @@ pub fn slider(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeI let t = ((x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); f64::from(lo) + (f64::from(hi) - f64::from(lo)) * f64::from(t) }; - // Snap to a round value only within half a physical pixel (in points), so - // round values are reachable by aiming at them while fractional values - // between round steps remain reachable. + + // Snap only within half a pixel so intermediate values remain reachable let radius = 0.5 / ui.ctx().pixels_per_point(); let v = egui::emath::smart_aim::best_in_range_f64(value_at(p.x - radius), value_at(p.x + radius)) as f32; + let v = constrain(v, true); if (v - *value).abs() > f32::EPSILON { *value = v; resp.mark_changed(); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index fb143c6..5d3299a 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -97,6 +97,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { } crate::unsaved::show(app, ctx); crate::explorer::dialogs(app, ctx); + crate::properties::ExposeParameterDialog::show(app, ctx); #[cfg(target_arch = "wasm32")] crate::web_files::save_dialog(app, ctx); #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index 8e948fc..12fa699 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -1,3 +1,6 @@ +#[path = "snapshot/parameter_functions.rs"] +mod parameter_functions; + #[path = "snapshot/graph_items.rs"] mod graph_items; diff --git a/crates/ui-egui/tests/snapshot/function_library.rs b/crates/ui-egui/tests/snapshot/function_library.rs index b91deb3..af41fb9 100644 --- a/crates/ui-egui/tests/snapshot/function_library.rs +++ b/crates/ui-egui/tests/snapshot/function_library.rs @@ -58,7 +58,7 @@ fn bottom_library_drags_functions_into_function_and_processor_canvases() { harness.state_mut().ui.library_search = "GlobalRandom".into(); settle(&mut harness, 3); - drag(&mut harness, "GlobalRandom", vec2(160.0, 0.0)); + drag(&mut harness, "Global random", vec2(160.0, 0.0)); let random = target .current(&harness.state().session) @@ -72,6 +72,7 @@ fn bottom_library_drags_functions_into_function_and_processor_canvases() { let mut missing = harness.state().session.pkg.dependencies["sbs://functions.sbs"].graph_by_name("Functions/Random/GlobalRandom").unwrap().1.clone(); missing.name = "MissingFunction".into(); + missing.attributes.label.clear(); missing.folder = "Functions/Test".into(); missing.function = Some(Default::default()); let mut package = materialcraft_engine::core::Package::new("Missing library"); diff --git a/crates/ui-egui/tests/snapshot/library.rs b/crates/ui-egui/tests/snapshot/library.rs index 2525483..1333c2d 100644 --- a/crates/ui-egui/tests/snapshot/library.rs +++ b/crates/ui-egui/tests/snapshot/library.rs @@ -89,7 +89,7 @@ fn library_tree_shows_every_category_and_adds_what_the_graph_takes() { settle(&mut harness, 3); harness.get(tree("Constant")).click(); settle(&mut harness, 4); - for label in ["Pi", "2Pi"] { + for label in ["Pi", "2 Pi"] { assert!(harness.query(tile(label)).is_some(), "{label}"); } save(&mut harness, &directory, "library-functions-constant"); diff --git a/crates/ui-egui/tests/snapshot/parameter_functions.rs b/crates/ui-egui/tests/snapshot/parameter_functions.rs new file mode 100644 index 0000000..b5267dd --- /dev/null +++ b/crates/ui-egui/tests/snapshot/parameter_functions.rs @@ -0,0 +1,158 @@ +use super::{harness, save, settle}; +use egui_kittest::kittest::{By, Queryable}; +use materialcraft_engine::core::{BaseParameter, NodeId}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::json; + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn parameter_functions_create_edit_reset_and_return_to_the_owner() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = 32; + let owner = NodeId(app.run("graph.node.add", json!({"def": "directional_blur"})).unwrap()["id"].as_u64().unwrap()); + let mut harness = harness(app, 1600.0, 1100.0); + settle(&mut harness, 8); + let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); + for parameter in BaseParameter::ALL { + let label = format!("Parameter actions: {}", parameter.label()); + assert!( + harness.get(By::new().role(egui::accesskit::Role::Button).label(&label)).rect().bottom() < 1000.0, + "{} must fit in Properties", + parameter.label() + ); + } + save(&mut harness, &directory, "parameter-controls"); + + harness.get(button("Parameter actions: Output size")).click(); + settle(&mut harness, 8); + for label in ["Empty function", "Constant value", "Reset to default"] { + assert!(harness.query(button(label)).is_some()); + } + assert!(harness.query(button("Expose as new graph input")).is_none()); + save(&mut harness, &directory, "parameter-function-menu"); + harness.get(button("Empty function")).click(); + settle(&mut harness, 5); + + assert!(harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize].nodes.is_empty()); + assert_eq!(harness.state().function_editor.as_ref().unwrap().node, Some(owner)); + assert!(harness.query(By::new().label_contains("No output node defined")).is_some()); + assert!(harness.query(By::new().label("Expected output: Integer2")).is_some()); + assert!(harness.query(button("Parameter actions: Output size")).is_some(), "owner Properties must remain available"); + save(&mut harness, &directory, "parameter-empty-function"); + + save(&mut harness, &directory, "inheritance-relative-input"); + harness.get(button("Output size inheritance: Relative to input")).click(); + settle(&mut harness, 3); + harness.get_by_label("Relative to parent").click(); + settle(&mut harness, 3); + save(&mut harness, &directory, "inheritance-relative-parent"); + harness.get(button("Output size inheritance: Relative to parent")).click(); + settle(&mut harness, 3); + harness.get(button("Absolute")).click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.graph().unwrap().node(owner).unwrap().base.size_mode, materialcraft_engine::core::SizeMode::Absolute); + save(&mut harness, &directory, "inheritance-absolute"); + harness.get(button("Output size inheritance: Absolute")).click(); + settle(&mut harness, 3); + harness.get_by_label("Relative to parent").click(); + settle(&mut harness, 3); + let base = &harness.state().session.graph().unwrap().node(owner).unwrap().base; + assert_eq!(base.size_mode, materialcraft_engine::core::SizeMode::RelativeToParent); + assert!(base.functions[&BaseParameter::OutputSize].nodes.is_empty()); + + harness.get(button("Return to parent graph")).click(); + settle(&mut harness, 8); + harness.get(button("Parameter actions: Output size")).click(); + settle(&mut harness, 8); + harness.get(button("Reset to default")).click(); + settle(&mut harness, 8); + harness.get(button("Parameter actions: Output size")).click(); + settle(&mut harness, 8); + save(&mut harness, &directory, "parameter-after-reset-menu"); + assert!(harness.query(button("Constant value")).is_some(), "the reset parameter menu must offer a constant"); + harness.get(button("Constant value")).click(); + settle(&mut harness, 4); + + let function = &harness.state().session.graph().unwrap().node(owner).unwrap().base.functions[&BaseParameter::OutputSize]; + assert_eq!(function.nodes.len(), 1); + assert_eq!(function.output, Some(function.nodes[0].id)); + assert!(harness.query(By::new().label_contains("No output node defined")).is_none()); + save(&mut harness, &directory, "parameter-constant-function"); + + harness.get(button("Integer2")).click(); + settle(&mut harness, 3); + assert!(harness.query(By::new().label("Output node")).is_some()); + assert!(harness.query_all(By::new().role(egui::accesskit::Role::SpinButton).label("X")).next().is_some()); + save(&mut harness, &directory, "parameter-constant-properties"); + + harness.get(button("Return to parent graph")).click(); + settle(&mut harness, 5); + harness.get(button("Parameter actions: Angle")).click(); + settle(&mut harness, 3); + harness.get(button("Constant value")).click(); + settle(&mut harness, 4); + assert!(harness.query(By::new().label("Expected output: Float")).is_some()); + assert!(harness.state().session.graph().unwrap().node(owner).unwrap().functions.contains_key("angle")); + save(&mut harness, &directory, "parameter-specific-function"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn exposing_a_specific_parameter_waits_for_confirmation() { + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").expect("set MC_SNAPSHOT_DIR")); + std::fs::create_dir_all(&directory).unwrap(); + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.prefs.preview_size = 32; + let owner = NodeId(app.run("graph.node.add", json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); + app.run("graph.node.param", json!({"id": owner, "param": "intensity", "value": 10.0})); + let original = app.session.graph().unwrap().clone(); + let mut harness = harness(app, 1600.0, 1100.0); + settle(&mut harness, 8); + let button = |label| By::new().role(egui::accesskit::Role::Button).label(label); + let input = |label| By::new().role(egui::accesskit::Role::TextInput).label(label); + + harness.get(button("Parameter actions: Intensity")).click(); + settle(&mut harness, 4); + harness.get(button("Expose as new graph input")).click(); + settle(&mut harness, 4); + + assert_eq!(*harness.state().session.graph().unwrap(), original, "opening the dialog must not edit the graph"); + assert!(harness.query(By::new().label("Expose Parameter")).is_some()); + harness.get(By::new().role(egui::accesskit::Role::Slider).label("Default")).set_value_accesskit(12.0); + settle(&mut harness, 2); + assert_eq!(*harness.state().session.graph().unwrap(), original, "editing the default must remain a draft"); + harness.get(input("Description")).click(); + settle(&mut harness, 1); + harness.get(input("Description")).type_text("Controls the blur radius"); + settle(&mut harness, 2); + save(&mut harness, &directory, "expose-parameter-dialog"); + harness.get(button("Cancel")).click(); + settle(&mut harness, 4); + assert_eq!(*harness.state().session.graph().unwrap(), original); + + harness.get(button("Parameter actions: Intensity")).click(); + settle(&mut harness, 4); + harness.get(button("Expose as new graph input")).click(); + settle(&mut harness, 4); + harness.get(input("Description")).click(); + settle(&mut harness, 1); + harness.get(input("Description")).type_text("Controls the blur radius"); + harness.get(input("Group")).click(); + settle(&mut harness, 1); + harness.get(input("Group")).type_text("Surface/Blur"); + settle(&mut harness, 2); + harness.get(button("OK")).click(); + settle(&mut harness, 6); + + let graph = harness.state().session.graph().unwrap(); + assert_eq!(graph.exposed.len(), 1); + assert_eq!(graph.exposed[0].default, materialcraft_engine::core::Value::Float(10.0)); + assert_eq!(graph.exposed[0].group, "Surface/Blur"); + let exposed = serde_json::to_value(&graph.exposed[0]).unwrap(); + assert_eq!(exposed["description"], "Controls the blur radius"); + assert_eq!(graph.node(owner).unwrap().functions["intensity"].input_identifier(), Some(graph.exposed[0].id.as_str())); + harness.state_mut().run("edit.undo", json!({})); + assert_eq!(*harness.state().session.graph().unwrap(), original, "exposure is one undo step"); +} diff --git a/docs/architecture.md b/docs/architecture.md index b02d32e..80f310a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -130,11 +130,22 @@ the static authoring defaults are zero. These values propagate through nested gr without becoming constants in saved functions. Relevant variable changes invalidate cached cooks. The normal-format integer is passed through without assigning a convention label to an unverified code. +Numeric, Boolean, color, enum and text value parameters can own a Function graph, including +inputs on material graph instances. The six base parameters store their functions separately from +node-specific parameters so native identifiers cannot collide. Size and seed functions establish +the evaluation context before other parameters run; downstream nodes inherit evaluated nominal +sizes rather than capped previews. SBS writes these functions as native dynamic values, including +incomplete graphs. Exposing a parameter creates a typed Get-node function. Properties offers the +same function creation, editing and reset actions for base parameters and instance inputs. +Only Specific Parameters offer exposure: a modal drafts the identifier, label, group, description, +editor, default, limits, clamp and step before one undoable command creates the input and function. +Inheritance buttons show distinct icons for input, parent and absolute modes. + The local `assets/sbs/functions.sbs` is converted from a user-supplied package with `cargo run -p materialcraft-formats --release --example standard_function_library -- assets/sbs/functions.sbs`. The converter preserves all 171 function bodies (2,334 nodes), folder paths, identifiers, inputs, defaults and internal references. It writes new interface-based descriptions, generates node -positions and omits source annotations and icons. It rejects import warnings and functions that +positions and omits source parameter descriptions, annotations and icons. It rejects import warnings and functions that cannot compile instead of substituting empty graphs. The source graph bodies are retained; rewritten metadata does not establish redistribution rights. Local tests compare every converted body and evaluate all 171 functions against the supplied diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 99cfb37..779e773 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -105,9 +105,14 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.wire.insertDot` | `{to, toPort, at?}`: split the wire feeding `to.toPort` with a reroute Dot node at `at` (graph point, default midway), selected | | `graph.wire.swap` / `graph.wire.delete` | `{wires: [{to, toPort}, ...]}`: exchange the sources of exactly two wires / delete any listed wires, one undo step each | | `graph.node.param` | `{id?, param, value}`: numbers, `[x, y]`, `"#rrggbb"`, enum index, curve `[[x, y], …]`, gradient `[[pos, color], …]`, or a typed value `{"t": "function", "v": {...}}` | -| `graph.node.base` | `{id?, sizeMode?, size?, format?, seed?, tiling?}` | -| `graph.exposed.add` / `graph.exposed.set` | `{id, label?, default?, bind?: {node, param}}` (with `bind`, `id` may be omitted: the input is named after the parameter, `opacity`, `opacity_1`…) / `{id, value}` | -| `graph.node.function` | `{id?, param, function}` drives a parameter by a function graph of the graph's inputs (dynamic parameter); `{id?, param, remove: true}` removes it | +| `graph.node.base` | `{id?, param, value?, inheritance?}` edits one base parameter; legacy `{sizeMode?, size?, format?, seed?, tiling?}` fields remain supported | +| `graph.exposed.prepare` | `{bind: {node, param}, default?}` returns editable input settings without changing the graph; only Specific Parameters can be exposed | +| `graph.exposed.add` / `graph.exposed.set` | `{id?, label?, group?, description?, default?, min?, max?, editor?, clamp?, step?, bind?: {node, param}}` (with `bind`, `id` may be omitted: `opacity`, `opacity_1`…) / `{id, value}`; `editor` is `slider`, `input`, `color`, `dropdown`, `toggle` or `text`, subject to the parameter type | +| `graph.node.function` | `{id?, param, base?, mode?: empty\|constant, value?, function?, remove?}` attaches an owned parameter function; constant creation captures its current value, or uses the supplied `value`; empty creation has no output | +| `graph.node.bind` | `{id?, param, base?, input}` attaches a typed input function; `input: null` clears the driver | +| `graph.node.function.edit` | `{id?, param, base?}` resolves the function target and opens it when dispatched by the UI | +| `graph.node.parameterInfo` | `{id?, param, base?}` returns the expected type, current value or error, function, input link, inheritance and warnings | +| `graph.node.reset` | `{id?, param?, base?}` removes the driver and restores defaults; omit `param` to reset the selected parameter section | | `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values | | `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance | | `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `normalYFlip` (interpret DirectX normal maps; default false/OpenGL), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | @@ -201,9 +206,23 @@ Omit `kind`, or use `"material"`, for a Graph. `graph.function.set {"function": the active standalone function through one validated, undoable command. Both `graph.function.set` and `graph.function.edit` accept an optional `target`: `{"kind":"graph"}` (the default), `{"kind":"parameter","node":12,"parameter":"function"}`, -`{"kind":"dynamic","node":12,"parameter":"opacity"}`, or +`{"kind":"dynamic","node":12,"parameter":"opacity"}`, +`{"kind":"base","node":12,"parameter":"outputsize"}`, or `{"kind":"pattern","owner":12,"node":3,"parameter":"patternrotation"}`. +Base function identifiers are `outputsize` (Integer2), `pixelsize` (Float2), and `format`, +`pixelratio`, `tiling`, `randomseed` (Integer). Their inheritance is independent of the driver. +`graph.node.base {id, param, inheritance}` changes inheritance while keeping its function; +add `value` to replace the function with a literal. Output size uses log2 dimensions in absolute +mode and log2 offsets in relative modes. Its relative-mode function reads the inherited nominal +`$size` and `$sizelog2`, before preview limits. Instances pass their resolved size to their child graph. +Exposing or binding a parameter creates an editable, typed Get-node function. Literal edits and +reset remove the old driver. Native parameters and instance inputs require their declared output +type; color parameters use Float4 and enum parameters use Integer. Invalid functions remain editable +and cook with a diagnostic. `session.inspect` includes evaluated `base`, `baseValues` and `parameters` +in each node's `cooked` result; `parameters` contains scalar and vector values, while authoring +graphs and curves remain in `params`. `baseValues` is populated for nodes with base functions. + `graph.function.edit` accepts `edit: {action: add|move|connect|value|output, ...}`. Explicit output selection rejects a type incompatible with the target parameter. Existing functions with mismatched output types remain editable and report the mismatch in diff --git a/docs/gaps.md b/docs/gaps.md index 8ea9e0d..d172809 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -42,7 +42,7 @@ Every known shortfall, most important first. Pick from the top. | 3 | Mesh-based generators and bakers | None | Workflows that start from a mesh | 15 h | target-app-parity (Node library) | | 4 | Portable materials over MCP | `.mcmat` export runs from the app and the CLI; the MCP workspace sandbox refuses `file.*` commands and has no `material_export` tool | Sandboxed agents can't hand a material to TextureCraft | 1 h | target-app-parity (Files) | | 5 | Function loops and reusable functions | Functions live on one parameter or processor | Iterative effects; sharing logic between nodes | 5 h | target-app-parity (Function graphs) | -| 6 | Input visibility conditions, per-instance output sizes | Not implemented | Organizing large graphs' inputs | 4 h | target-app-parity (Graph parameters) | +| 6 | Input visibility conditions | Visibility expressions are not implemented; instance output sizes can use parameter functions | Organizing large graphs' inputs | 4 h | target-app-parity (Graph parameters) | | 7 | `ui.screenshot` times out on this test machine | The window-capture callback never fires here; `view.screenshot` and the offscreen snapshot test work | Agents bridged to the app see views but not the whole window | 1 h | — | | 8 | Translations and keymap editor | English only, fixed shortcuts | Non-English users; custom shortcuts | 8 h | localization-parity | | 9 | Minimap and multi-graph tabs | One graph at a time, no overview | Navigating big graphs | 5 h | target-app-parity (Graph editing, UI and UX) | diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md index 6580c84..098b6ae 100644 --- a/docs/helpful-pr-review-guidelines.md +++ b/docs/helpful-pr-review-guidelines.md @@ -28,6 +28,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Prefer the smallest complete solution that is efficient and easy to understand - Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions - Consider caching, batching, and parallelism when measurements justify their complexity and memory cost - Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads - Compare before and after with the same inputs, build settings, and environment; account for measurement variation and cold or warm state where relevant @@ -77,6 +78,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - For naming, spacing, or organization findings, identify the location and the specific standard being missed - Order findings by severity and distinguish confirmed problems, hypotheses needing verification, and optional improvements - Give measured optimization results with workload, build, and environment details; do not describe an unmeasured change as faster +- For memory-related changes, verify allocation/resampling counts or peak live memory in representative multi-item cases. Final pixel equality and shared output buffers do not prove that temporary allocations are avoided - State remaining limitations and coverage gaps; if no actionable problems were found, say so without implying complete correctness - Before handing back edits, review the final diff for unintended behavior changes, unrelated edits, and claims unsupported by validation diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d50f78b..778444e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -28,8 +28,8 @@ automation + tests), weighted by how much of the day each area carries. **Remain | Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire (from an output or an unconnected input), re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap | | Atomic nodes | 12 | 95% | Bitmap, Blend (16 modes, masks, alpha), Blur, Channels Shuffle, Curve, Directional Blur, Directional Warp, Distance (with color propagation), Emboss, FX-Map (grid, quadtree and scatter modes with per-instance randomness), Gradient (Dynamic), Gradient Map, Grayscale Conversion, HSL, Levels, Normal, Pixel Processor, Value Processor, Sharpen, SVG (path data, fill rules, stroke), Text (own stroke font), Transformation 2D, Uniform Color, Warp, inputs, outputs, dots, graph instances | FX-Map driven by per-iteration functions, SVG arcs and SVG files, font choice for Text | | Node library | 20 | 45% | 227 nodes: noises (tileable 3D Perlin, simplex and Worley, cracks, stones, dirt, grunge maps and more), patterns (tile generator and sampler, bricks, hexagons, weave, shape splatter, paint strokes, scratches), filters (adjustments, blending, blurs, channels, effects, normal map tools, tiling, transforms), the flood fill family, whole-material and height blending, weathering (rust, moss, leaks, edge damage, edge wear, dust) | The rest of the reference library's ~400 graphs: more grunge and scan processing, mesh-based generators and bakers, spline tools, SDF functions | -| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items | -| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages | +| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; parameter-owned functions on base parameters, native values and instance inputs, with typed outputs, exposure and undo | Loops, function graphs as reusable package items | +| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, embedded vs. linked packages | | 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay | | 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer | | Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources | From 131c7b8853795d1a0454248af907b07ee02c162e Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 04:54:21 -0500 Subject: [PATCH 2/3] Fix parameter defaults, sizing and tooltips --- crates/engine/src/linked_packages.rs | 10 ++- crates/engine/tests/it/linked_instances.rs | 83 ++++++++++++++++++++++ crates/eval/src/prepared_graph.rs | 22 ++++-- crates/eval/src/tests.rs | 65 +++++++++++++++++ crates/nodes/src/parameter_descriptor.rs | 8 +-- crates/ui-egui/src/property/input.rs | 36 +++++++++- crates/ui-egui/src/property/node.rs | 53 +++++++++++++- 7 files changed, 263 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/linked_packages.rs b/crates/engine/src/linked_packages.rs index edafd83..7940e18 100644 --- a/crates/engine/src/linked_packages.rs +++ b/crates/engine/src/linked_packages.rs @@ -37,6 +37,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - if node.def != "graph_instance" { return None; } + let materialcraft_core::Value::Text(name) = node.params.get("graph")? else { return None }; Some(GraphInstance { label: String::new(), @@ -52,7 +53,9 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - if graph.function.is_some() { return None; } + let (mut inputs, mut outputs) = materialcraft_nodes::graph_interface::graph_ports(graph); + // Keep connected missing ports so saving cannot silently discard the user's wires for port in &instance.inputs { if owner.connections.iter().any(|wire| wire.to == node.id && wire.to_port == port.identifier) @@ -68,19 +71,23 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - outputs.push(port.clone()); } } + instance.inputs = inputs; instance.outputs = outputs; - instance.defaults = graph.exposed.iter().map(|parameter| (parameter.id.clone(), parameter.default.clone())).collect(); + instance.defaults = + graph.exposed.iter().map(|parameter| (parameter.id.clone(), graph.input_value(¶meter.id).unwrap_or(¶meter.default).clone())).collect(); instance.label = graph.display_name().into(); (node.instance.as_ref() != Some(&instance)).then_some((graph_index, node_index, instance)) }) .collect(); + let mut changed = !updates.is_empty(); for (graph, node, instance) in updates { if let Some(node) = package.graphs.get_mut(graph).and_then(|graph| graph.nodes.get_mut(node)) { node.instance = Some(instance); } } + let local = package.clone(); for function in package.graphs.iter_mut().flat_map(|graph| graph.functions_mut()) { if function.nodes.iter().any(|node| node.instance.is_some()) { @@ -89,6 +96,7 @@ fn interfaces(package: &mut Package, sources: &BTreeMap>) - changed |= *function != previous; } } + changed } diff --git a/crates/engine/tests/it/linked_instances.rs b/crates/engine/tests/it/linked_instances.rs index 1dc9b28..90f91fa 100644 --- a/crates/engine/tests/it/linked_instances.rs +++ b/crates/engine/tests/it/linked_instances.rs @@ -301,3 +301,86 @@ fn saved_dependencies_reopen_without_source_files_in_explorer_and_missing_source assert!(missing.path.is_some()); std::fs::remove_dir_all(directory).unwrap(); } + +fn assert_instance_color(session: &mut Session, instance: NodeId, expected: [f32; 4]) { + let cooked = session.cook(); + assert_eq!(cooked.nodes[&instance].error, None); + let actual = cooked.image(instance, 0).unwrap().get(0, 0, false); + assert!(actual.into_iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-6), "{actual:?} != {expected:?}"); +} + +#[test] +fn instance_defaults_follow_current_source_inputs_before_and_after_save() { + for linked in [false, true] { + let directory = std::env::temp_dir().join(format!("materialcraft-current-inputs-{}-{linked}", std::process::id())); + std::fs::create_dir_all(&directory).unwrap(); + let source_path = directory.join("source.sbs"); + let target_path = directory.join("target.sbs"); + let (package, value) = source(); + let mut session = Session::new(package); + session.path = Some(source_path.to_string_lossy().into_owned()); + execute(&mut session, "graph.exposed.add", &json!({"id": "tint", "bind": {"node": value, "param": "color"}})).unwrap(); + execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": [0.2, 0.3, 0.4, 1.0]})).unwrap(); + let target_document = if linked { + let mut target = Package::new("Target"); + target.graphs.push(Graph::new("Target")); + open(&mut session, &target, target_path.to_str().unwrap()) + } else { + execute(&mut session, "file.new", &json!({"name": "Target", "template": "empty"})).unwrap(); + session.document_id + }; + let target_graph = session.graph; + let instance = NodeId(execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Source"})).unwrap()["id"].as_u64().unwrap()); + session.preview_size = Some(16); + + for expected in [[0.2, 0.3, 0.4, 1.0], [0.8, 0.6, 0.4, 1.0]] { + execute(&mut session, "package.activate", &json!({"document": 0})).unwrap(); + session.graph = 0; + execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": expected})).unwrap(); + execute(&mut session, "package.activate", &json!({"document": target_document})).unwrap(); + session.graph = target_graph; + let cooked = session.cook(); + + assert_eq!(cooked.nodes[&instance].error, None); + assert_eq!(cooked.nodes[&instance].parameters["tint"], Value::Color(expected)); + assert_instance_color(&mut session, instance, expected); + } + + let source_bytes = formats::sbs::write_sbs(session.open_packages().iter().find(|entry| entry.0 == 0).unwrap().1).unwrap(); + std::fs::write(&source_path, source_bytes).unwrap(); + std::fs::write(&target_path, file_cmds::save_bytes(&session).unwrap()).unwrap(); + let mut reopened = Session::new(Package::new("Initial")); + file_cmds::open_file(&mut reopened, target_path.to_str().unwrap()).unwrap(); + assert!(reopened.load_warnings.is_empty(), "{:?}", reopened.load_warnings); + reopened.graph = target_graph; + reopened.preview_size = Some(16); + let instance = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "graph_instance").unwrap().id; + assert_instance_color(&mut reopened, instance, [0.8, 0.6, 0.4, 1.0]); + + execute(&mut reopened, "graph.node.param", &json!({"id": instance, "param": "tint", "value": [0.1, 0.2, 0.3, 1.0]})).unwrap(); + assert_instance_color(&mut reopened, instance, [0.1, 0.2, 0.3, 1.0]); + execute(&mut reopened, "graph.node.reset", &json!({"id": instance, "param": "tint"})).unwrap(); + assert_instance_color(&mut reopened, instance, [0.8, 0.6, 0.4, 1.0]); + std::fs::remove_dir_all(directory).unwrap(); + } +} + +#[test] +fn instance_constant_capture_uses_the_current_source_input_without_a_prior_cook() { + let (package, value) = source(); + let mut session = Session::new(package); + execute(&mut session, "graph.exposed.add", &json!({"id": "tint", "bind": {"node": value, "param": "color"}})).unwrap(); + execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": [0.8, 0.6, 0.4, 1.0]})).unwrap(); + execute(&mut session, "file.new", &json!({"name": "Target", "template": "empty"})).unwrap(); + let instance = NodeId(execute(&mut session, "graph.instance.add", &json!({"document": 0, "graph": "Source"})).unwrap()["id"].as_u64().unwrap()); + + let info = execute(&mut session, "graph.node.parameterInfo", &json!({"id": instance, "param": "tint"})).unwrap(); + assert_eq!(info["value"], json!(Value::Color([0.8, 0.6, 0.4, 1.0]))); + execute(&mut session, "graph.node.function", &json!({"id": instance, "param": "tint", "mode": "constant"})).unwrap(); + session.graph = 0; + execute(&mut session, "graph.exposed.set", &json!({"id": "tint", "value": [0.0, 0.0, 0.0, 1.0]})).unwrap(); + session.graph = 1; + session.preview_size = Some(16); + + assert_instance_color(&mut session, instance, [0.8, 0.6, 0.4, 1.0]); +} diff --git a/crates/eval/src/prepared_graph.rs b/crates/eval/src/prepared_graph.rs index 5f4eb92..056e41a 100644 --- a/crates/eval/src/prepared_graph.rs +++ b/crates/eval/src/prepared_graph.rs @@ -28,13 +28,25 @@ impl<'a> PreparedGraph<'a> { } pub fn input_base(&self, id: NodeId, cooked: &crate::Cooked) -> Option { - let primary = self.index.node(id).and_then(|node| materialcraft_nodes::find(&node.def)).and_then(|definition| definition.primary_input); - 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 node = self.index.node(id)?; + let definition = materialcraft_nodes::find(&node.def); + let primary = definition.and_then(|definition| 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) - }, - ) + })?; + + // 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; + } + + Some(base) } pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) { diff --git a/crates/eval/src/tests.rs b/crates/eval/src/tests.rs index 06eca79..aff7994 100644 --- a/crates/eval/src/tests.rs +++ b/crates/eval/src/tests.rs @@ -506,3 +506,68 @@ fn cooked_parameters_retain_values_without_processor_graph_copies() { assert_eq!(result.nodes[&scalar].parameters.get("color"), Some(&Value::Color([0.5; 4]))); } } + +#[test] +fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters() { + use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, ParameterInheritance, SizeMode, ValueType}; + + for definition in ["svg", "fx_map"] { + for dynamic in [false, true] { + let mut graph = Graph::new("Generator sizes"); + graph.size = [6, 5]; + let background = graph.add_node("uniform", [0.0; 2]); + let base = &mut graph.node_mut(background).unwrap().base; + base.size_mode = SizeMode::Absolute; + base.size = [5, 6]; + base.seed = 17; + base.format = OutputFormat::F32; + base.tiling = [false, true]; + base.tiling_mode = ParameterInheritance::Absolute; + base.pixel_ratio = 1; + base.pixel_ratio_mode = ParameterInheritance::Absolute; + base.pixel_size = [0.25, 0.5]; + base.pixel_size_mode = ParameterInheritance::Absolute; + let generator = graph.add_node(definition, [200.0, 0.0]); + graph.node_mut(generator).unwrap().base.format_mode = ParameterInheritance::RelativeToInput; + if dynamic { + let mut function = FunctionGraph::input("$sizelog2", ValueType::Float2); + let size = function.output.unwrap(); + let parent = function.add_constant(Value::Float2([6.0, 5.0])); + let difference = function.add("sub", &[size, parent], None); + function.output = Some(function.add("toint2", &[difference], None)); + graph.node_mut(generator).unwrap().base.functions.insert(BaseParameter::OutputSize, function); + } + graph.connect(background, "output", generator, "background").unwrap(); + let mut package = Package::new("Generator sizes"); + package.graphs.push(graph); + let cache = Mutex::new(Cache::default()); + let mut options = Options::new(&no_res); + options.max_size = Some(16); + + let cooked = cook(&package, 0, &options, &cache); + let result = &cooked.nodes[&generator]; + + assert_eq!(result.error, None, "{definition}"); + assert_eq!(result.base.size, [64, 32], "{definition}, dynamic: {dynamic}"); + assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((16, 8))); + assert_eq!(result.base.seed, 17); + assert_eq!(result.base.format, OutputFormat::F32); + assert_eq!(result.base.tiling, [false, true]); + assert_eq!(result.base.pixel_ratio, 1); + assert_eq!(result.base.pixel_size, [0.25, 0.5]); + if !dynamic { + assert_eq!( + node_size(&package.graphs[0], materialcraft_nodes::find(definition), package.graphs[0].node(generator).unwrap(), Some((32, 64)), Some(16)), + (16, 8) + ); + } + + package.graphs[0].node_mut(generator).unwrap().disabled = true; + let cooked = cook(&package, 0, &options, &cache); + + assert_eq!(cooked.nodes[&generator].error, None); + assert_eq!(cooked.nodes[&generator].base.size, cooked.nodes[&background].base.size); + assert_eq!(cooked.image(generator, 0).map(|image| (image.w, image.h)), Some((8, 16))); + } + } +} diff --git a/crates/nodes/src/parameter_descriptor.rs b/crates/nodes/src/parameter_descriptor.rs index 8250288..1aba2be 100644 --- a/crates/nodes/src/parameter_descriptor.rs +++ b/crates/nodes/src/parameter_descriptor.rs @@ -45,15 +45,13 @@ impl ParameterDescriptor { Some(Value::Text(name)) => Some(name.as_str()), _ => None, }); - if let Some(input) = source - .zip(name) - .and_then(|(source, name)| source.graph_by_name(name)) - .and_then(|(_, graph)| graph.exposed.iter().find(|input| input.id == parameter)) + if let Some((_, graph)) = source.zip(name).and_then(|(source, name)| source.graph_by_name(name)) + && let Some(input) = graph.exposed.iter().find(|input| input.id == parameter) { return Some(Self { id: input.id.clone(), label: input.label.clone(), - default: input.default.clone(), + default: graph.input_value(parameter).unwrap_or(&input.default).clone(), min: input.min, max: input.max, options: input.options.clone(), diff --git a/crates/ui-egui/src/property/input.rs b/crates/ui-egui/src/property/input.rs index 9fc657e..75159c7 100644 --- a/crates/ui-egui/src/property/input.rs +++ b/crates/ui-egui/src/property/input.rs @@ -6,7 +6,10 @@ use serde_json::{Value as JsonValue, json}; pub(super) fn input_editor(ui: &mut Ui, exposed: &materialcraft_engine::core::ExposedParameter, current: &Value) -> Option { let label = if exposed.label.is_empty() { exposed.id.as_str() } else { exposed.label.as_str() }; let response = ui.vertical(|ui| edit(ui, exposed, current, label)); - response.response.on_hover_text(&exposed.description); + if !exposed.description.is_empty() { + response.response.on_hover_text(&exposed.description); + } + response.inner } @@ -118,6 +121,37 @@ mod tests { kittest::{By, Queryable}, }; + #[test] + fn input_descriptions_only_open_nonempty_tooltips() { + for description in ["", "Controls the amount"] { + let input: ExposedParameter = serde_json::from_value(json!({ + "id": "amount", "label": "Amount", "default": {"t": "bool", "v": false}, "description": description + })) + .unwrap(); + let directory = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from); + let builder = Harness::builder().with_size(egui::vec2(360.0, 160.0)).with_step_dt(1.0 / 60.0); + let builder = if directory.is_some() { builder.wgpu() } else { builder }; + let mut harness = builder.build_ui(|ui| { + input_editor(ui, &input, &input.default); + }); + harness.run(); + let position = harness.get(By::new().role(egui::accesskit::Role::CheckBox).label("Amount")).rect().center(); + + harness.event(egui::Event::PointerMoved(position)); + harness.run_steps(90); + + assert_eq!(egui::Tooltip::seconds_since_last_tooltip(&harness.ctx).is_finite(), !description.is_empty()); + if !description.is_empty() { + assert!(harness.query(By::new().role(egui::accesskit::Role::Label).label(description)).is_some()); + } + if let Some(directory) = directory { + std::fs::create_dir_all(&directory).unwrap(); + let name = if description.is_empty() { "input-without-description" } else { "input-description-tooltip" }; + harness.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + } + } + } + #[test] fn exposed_sliders_apply_step_and_allow_values_outside_soft_limits() { for (clamp, expected) in [(false, 1.5), (true, 1.0)] { diff --git a/crates/ui-egui/src/property/node.rs b/crates/ui-egui/src/property/node.rs index 9a0023d..0e37ecc 100644 --- a/crates/ui-egui/src/property/node.rs +++ b/crates/ui-egui/src/property/node.rs @@ -168,14 +168,16 @@ fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft if exposed.is_empty() { ui.label(RichText::new(tr("This graph exposes no inputs")).color(tokens.text_dim)); } + for entry in exposed { - let current = node.params.get(&entry.id).cloned().unwrap_or_else(|| entry.default.clone()); + let descriptor = ParameterDescriptor::for_node(&app.session.pkg, node, &entry.id); + let current = node.params.get(&entry.id).unwrap_or_else(|| descriptor.as_ref().map_or(&entry.default, |descriptor| &descriptor.default)).clone(); let literal = |app: &mut MaterialCraftApp, ui: &mut Ui| { if let Some(value) = input_editor(ui, &entry, ¤t) { app.run("graph.node.param", json!({"id": node.id.0, "param": entry.id, "value": value})); } }; - if let Some(descriptor) = ParameterDescriptor::for_node(&app.session.pkg, node, &entry.id) + if let Some(descriptor) = descriptor && descriptor.supports_function { super::parameter_control::show(app, ui, node, &descriptor, None, literal); @@ -184,3 +186,50 @@ fn instance_params(app: &mut MaterialCraftApp, ui: &mut Ui, node: &materialcraft } } } + +#[cfg(test)] +mod tests { + use super::*; + use egui_kittest::{ + Harness, + kittest::{By, Queryable}, + }; + use materialcraft_engine::core::NodeId; + + #[test] + fn instance_properties_show_current_source_values_and_local_overrides() { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default()); + app.session.graph_mut().unwrap().name = "Source".into(); + app.run("graph.node.add", json!({"def": "output"})).unwrap(); + app.run("graph.exposed.add", json!({"id": "amount", "label": "Amount", "default": 0.25})).unwrap(); + app.run("graph.exposed.set", json!({"id": "amount", "value": 0.75})).unwrap(); + app.run("file.new", json!({"name": "Target", "template": "empty"})).unwrap(); + let instance = NodeId(app.run("graph.instance.add", json!({"document": 0, "graph": "Source"})).unwrap()["id"].as_u64().unwrap()); + let directory = std::env::var_os("MC_SNAPSHOT_DIR").map(std::path::PathBuf::from); + let builder = Harness::builder().with_size(egui::vec2(420.0, 200.0)).with_context_setup(crate::theme::install); + let builder = if directory.is_some() { builder.wgpu() } else { builder }; + let mut harness = builder.build_ui_state( + move |ui, app: &mut MaterialCraftApp| { + let node = app.session.graph().unwrap().node(instance).unwrap().clone(); + instance_params(app, ui, &node); + }, + app, + ); + harness.run(); + let input = || By::new().role(egui::accesskit::Role::TextInput).label("Amount"); + + assert_eq!(harness.get(input()).value().as_deref(), Some("0.750")); + if let Some(directory) = &directory { + std::fs::create_dir_all(directory).unwrap(); + harness.render().unwrap().save(directory.join("instance-current-input.png")).unwrap(); + } + + harness.state_mut().run("graph.node.param", json!({"id": instance, "param": "amount", "value": 0.5})).unwrap(); + harness.run(); + + assert_eq!(harness.get(input()).value().as_deref(), Some("0.500")); + if let Some(directory) = directory { + harness.render().unwrap().save(directory.join("instance-local-override.png")).unwrap(); + } + } +} From 709cd7f86eee92976517dcedfe4f8cbfbe9de2f2 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 05:15:39 -0500 Subject: [PATCH 3/3] Fix function instance inputs and cache refresh --- crates/engine/tests/it/function_instances.rs | 96 +++++++++++++++++++ crates/eval/src/cache_key.rs | 14 ++- .../nodes/src/function/resolve_instances.rs | 11 ++- 3 files changed, 116 insertions(+), 5 deletions(-) diff --git a/crates/engine/tests/it/function_instances.rs b/crates/engine/tests/it/function_instances.rs index 3554ca5..a76db21 100644 --- a/crates/engine/tests/it/function_instances.rs +++ b/crates/engine/tests/it/function_instances.rs @@ -250,6 +250,102 @@ fn unconnected_instance_inputs_use_the_source_defaults() { assert!(function::warnings(graph).is_empty()); } +#[test] +fn function_instance_inputs_follow_current_source_values() { + for linked in [false, true] { + let mut session = Session::new(source()); + session.path = Some(std::env::temp_dir().join("materialcraft-function-input-source.sbs").to_string_lossy().into_owned()); + execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.25})).unwrap(); + if linked { + let mut package = Package::new("Calls"); + let mut graph = Graph::new("Caller"); + graph.function = Some(FunctionGraph::default()); + package.graphs.push(graph); + file_cmds::open_bytes(&mut session, &formats::sbs::write_sbs(&package).unwrap(), Some("function-input-target.sbs".into())).unwrap(); + } else { + execute(&mut session, "file.new", &json!({"name": "Caller", "kind": "function"})).unwrap(); + } + let document = session.document_id; + 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.5)); + + execute(&mut session, "file.new", &json!({"name": "Outer", "kind": "function"})).unwrap(); + let outer = call(&mut session, document, "Caller", &target); + edit(&mut session, &target, json!({"action": "output", "id": outer})); + execute(&mut session, "package.activate", &json!({"document": 0})).unwrap(); + execute(&mut session, "graph.open", &json!({"graph": "Twice"})).unwrap(); + execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.75})).unwrap(); + execute(&mut session, "package.activate", &json!({"document": document})).unwrap(); + execute(&mut session, "graph.open", &json!({"graph": "Outer"})).unwrap(); + + assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(1.5)); + assert!(function::warnings(session.graph().unwrap().function.as_ref().unwrap()).is_empty()); + + execute(&mut session, "graph.open", &json!({"graph": "Caller"})).unwrap(); + 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.125)})); + edit(&mut session, &target, json!({"action": "connect", "from": constant, "to": instance, "input": 0})); + execute(&mut session, "package.activate", &json!({"document": 0})).unwrap(); + execute(&mut session, "graph.open", &json!({"graph": "Twice"})).unwrap(); + execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 1.0})).unwrap(); + execute(&mut session, "package.activate", &json!({"document": document})).unwrap(); + execute(&mut session, "graph.open", &json!({"graph": "Outer"})).unwrap(); + + assert_eq!(evaluate(session.graph().unwrap().function.as_ref().unwrap()), Value::Float(0.25)); + } +} + +#[test] +fn function_instance_input_changes_recook_parameter_functions_and_processors() { + let mut session = Session::new(source()); + execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.25})).unwrap(); + execute(&mut session, "file.new", &json!({"name": "Material", "template": "empty"})).unwrap(); + let blur = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "blur"})).unwrap()["id"].as_u64().unwrap()); + execute(&mut session, "graph.node.function", &json!({"id": blur, "param": "intensity", "mode": "empty"})).unwrap(); + let processor = NodeId(execute(&mut session, "graph.node.add", &json!({"def": "value_processor"})).unwrap()["id"].as_u64().unwrap()); + for target in [json!({"kind": "dynamic", "node": blur, "parameter": "intensity"}), json!({"kind": "parameter", "node": processor, "parameter": "function"})] + { + let instance = call(&mut session, 0, "Twice", &target); + edit(&mut session, &target, json!({"action": "output", "id": instance})); + } + session.preview_size = Some(16); + let cooked = session.cook(); + + assert_eq!(cooked.nodes[&blur].error, None); + assert_eq!(cooked.nodes[&blur].parameters["intensity"], Value::Float(0.5)); + assert_eq!(cooked.value(processor, 0), Some(&Value::Float(0.5))); + + execute(&mut session, "graph.open", &json!({"graph": "Twice"})).unwrap(); + execute(&mut session, "graph.exposed.set", &json!({"id": "amount", "value": 0.75})).unwrap(); + execute(&mut session, "graph.open", &json!({"graph": "Material"})).unwrap(); + let cooked = session.cook(); + + assert_eq!(cooked.nodes[&blur].error, None); + assert_eq!(cooked.nodes[&blur].parameters["intensity"], Value::Float(1.5)); + assert_eq!(cooked.nodes[&processor].error, None); + assert_eq!(cooked.value(processor, 0), Some(&Value::Float(1.5))); + assert!(!cooked.nodes[&blur].cached); + assert!(!cooked.nodes[&processor].cached); + let cached = session.cook(); + assert!(cached.nodes[&blur].cached); + assert!(cached.nodes[&processor].cached); + assert_eq!(cached.value(processor, 0), Some(&Value::Float(1.5))); + + let saved = formats::sbs::write_sbs(&session.pkg).unwrap(); + let mut reopened = Session::new(formats::sbs::read_sbs(&saved, "function-inputs.sbs", &|_| None).unwrap().pkg); + execute(&mut reopened, "graph.open", &json!({"graph": "Material"})).unwrap(); + reopened.preview_size = Some(16); + let blur = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "blur").unwrap().id; + let processor = reopened.graph().unwrap().nodes.iter().find(|node| node.def == "value_processor").unwrap().id; + let cooked = reopened.cook(); + + assert_eq!(cooked.nodes[&blur].parameters["intensity"], Value::Float(1.5)); + assert_eq!(cooked.value(processor, 0), Some(&Value::Float(1.5))); +} + #[test] fn connected_inputs_survive_source_interface_changes_and_missing_sources() { let mut session = Session::new(source()); diff --git a/crates/eval/src/cache_key.rs b/crates/eval/src/cache_key.rs index aa010c3..fb0d8a2 100644 --- a/crates/eval/src/cache_key.rs +++ b/crates/eval/src/cache_key.rs @@ -94,14 +94,19 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, va let mut pending = vec![graph.as_ref()]; while let Some(graph) = pending.pop() { serde_json::to_string(graph).unwrap_or_default().hash(&mut hasher); - for function in &graph.nodes { - match &function.source { + for function_node in &graph.nodes { + // Resolved call defaults are omitted from graph serialization + if let Some(instance) = &function_node.instance { + serde_json::to_string(&instance.defaults).unwrap_or_default().hash(&mut hasher); + } + + match &function_node.source { Some(Ok(source)) => pending.push(source.as_ref()), Some(Err(error)) => error.hash(&mut hasher), None => {} } - if (function.op.starts_with("get_") || function.op == "isdefined") - && let Some(Value::Text(name)) = &function.value + if (function_node.op.starts_with("get_") || function_node.op == "isdefined") + && let Some(Value::Text(name)) = &function_node.value { names.insert(name.as_str()); } @@ -124,5 +129,6 @@ pub(crate) fn variable_key(node: &Node, parameters: &BTreeMap, va name.hash(&mut hasher); variables.get(name).map(|value| serde_json::to_string(value).unwrap_or_default()).hash(&mut hasher); } + hasher.finish() } diff --git a/crates/nodes/src/function/resolve_instances.rs b/crates/nodes/src/function/resolve_instances.rs index 9816bfc..fedd1fd 100644 --- a/crates/nodes/src/function/resolve_instances.rs +++ b/crates/nodes/src/function/resolve_instances.rs @@ -24,16 +24,20 @@ fn resolve(function: &mut FunctionGraph, local: &Package, sources: &BTreeMap= 8 || body.nodes.len() > *remaining { return Err("Function instances exceed the 8-level or 4096-node limit".into()); } + if graph.exposed.len() > 4096 || graph.exposed.iter().map(|parameter| ¶meter.id).collect::>().len() != graph.exposed.len() { return Err("Function inputs must have unique identifiers and at most 4096 entries".into()); } + let previous: BTreeMap<_, _> = instance.inputs.iter().zip(&node.inputs).map(|(port, value)| (port.identifier.clone(), *value)).collect(); - instance.defaults = graph.exposed.iter().map(|parameter| (parameter.id.clone(), parameter.default.clone())).collect(); + instance.defaults = + graph.exposed.iter().map(|parameter| (parameter.id.clone(), graph.input_value(¶meter.id).unwrap_or(¶meter.default).clone())).collect(); instance.inputs = graph .exposed .iter() @@ -47,15 +51,19 @@ fn resolve(function: &mut FunctionGraph, local: &Package, sources: &BTreeMap