mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-19 22:10:53 +01:00
fix(material): preserve disabled nodes and localized typed inputs
This commit is contained in:
1 parent
6c3026e02a
commit
2a13981ef0
6 files changed
+188
-4
No files matched your search
@@ -353,3 +353,55 @@ fn legacy_grayscale_float_exports_keep_linear_defaults_and_explicit_overrides()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_disabled_and_typed_instance_cooks_match_source() {
|
||||
use materialcraft_core::ValueType;
|
||||
let mut helper = Graph::new("ValueHelper");
|
||||
helper.size = [4, 4];
|
||||
let value = node(&mut helper, "input_value", &[("identifier", Value::Text("amount".into())), ("default", Value::Float(0.25))]);
|
||||
output(&mut helper, value, "output", "number", "height");
|
||||
let mut dependency = Package::new("Dependency");
|
||||
dependency.graphs.push(helper);
|
||||
let mut graph = Graph::new("Root");
|
||||
graph.size = [4, 4];
|
||||
let value = node(&mut graph, "input_value", &[("identifier", Value::Text("source".into())), ("default", Value::Float(0.75))]);
|
||||
let instance = node(&mut graph, "graph_instance", &[]);
|
||||
graph.node_mut(instance).unwrap().instance = Some(GraphInstance {
|
||||
package: "helper.sbs".into(),
|
||||
graph: "ValueHelper".into(),
|
||||
inputs: vec![GraphPort { identifier: "amount".into(), type_code: ValueType::Float as u32 }],
|
||||
outputs: vec![GraphPort { identifier: "number".into(), type_code: ValueType::Float as u32 }],
|
||||
defaults: Default::default(),
|
||||
label: String::new(),
|
||||
});
|
||||
graph.connect(value, "output", instance, "amount").unwrap();
|
||||
output(&mut graph, instance, "number", "number", "height");
|
||||
let color = node(&mut graph, "uniform", &[("color", Value::Color([0.2, 0.3, 0.4, 1.0]))]);
|
||||
let levels = node(&mut graph, "levels", &[("out_low", Value::Float4([1.0; 4])), ("out_high", Value::Float4([0.0; 4]))]);
|
||||
graph.node_mut(levels).unwrap().disabled = true;
|
||||
graph.connect(color, "output", levels, "input").unwrap();
|
||||
output(&mut graph, levels, "output", "image", "baseColor");
|
||||
let mut package = Package::new("Package");
|
||||
package.graphs.push(graph);
|
||||
package.dependencies.insert("helper.sbs".into(), std::sync::Arc::new(dependency));
|
||||
let bytes = materialcraft_formats::material::write_material(&package, 0).unwrap();
|
||||
let (opened, entry) = materialcraft_formats::material::read_material(&bytes).unwrap();
|
||||
let cook = |pkg: Package, entry| {
|
||||
// Cook the decoded package directly: Session::new refreshes interfaces and could mask a serialization defect.
|
||||
let options = materialcraft_eval::Options::new(&|_| None);
|
||||
let cache = std::sync::Mutex::new(materialcraft_eval::Cache::default());
|
||||
let cooked = materialcraft_eval::cook(&pkg, entry, &options, &cache);
|
||||
let graph = &pkg.graphs[entry];
|
||||
let instance = graph.nodes.iter().find(|node| node.def == "graph_instance").unwrap().id;
|
||||
let levels = graph.nodes.iter().find(|node| node.def == "levels").unwrap().id;
|
||||
assert!(cooked.nodes[&instance].error.is_none(), "{:?}", cooked.nodes[&instance].error);
|
||||
assert_eq!(cooked.nodes[&instance].outputs[0].as_value(), Some(&Value::Float(0.75)));
|
||||
assert!(cooked.nodes[&levels].error.is_none());
|
||||
cooked.image(levels, 0).unwrap().get(0, 0, false)
|
||||
};
|
||||
let original = cook(package, 0);
|
||||
let restored = cook(opened, entry);
|
||||
assert_eq!(restored, original);
|
||||
assert!((restored[0] - 0.2).abs() < 0.01, "disabled levels must preserve its input: {restored:?}");
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Retain typed, including unconnected, material graph inputs when references become local.
|
||||
use super::xml::{child_element, child_value, children_named, xml_escape};
|
||||
use materialcraft_core::GraphPort;
|
||||
use roxmltree::Node;
|
||||
use std::{collections::BTreeSet, fmt::Write};
|
||||
|
||||
pub(super) fn read(element: Node<'_, '_>) -> Option<Result<Vec<GraphPort>, String>> {
|
||||
let interface = child_element(element, "materialcraftInterface")?;
|
||||
Some((|| {
|
||||
let mut inputs = Vec::new();
|
||||
let mut names = BTreeSet::new();
|
||||
for port in children_named(interface, "input") {
|
||||
if inputs.len() == 4096 {
|
||||
return Err("Graph instance exceeds the 4096-input limit".into());
|
||||
}
|
||||
let identifier = child_value(port, "identifier").unwrap_or("");
|
||||
if identifier.is_empty() || !names.insert(identifier) {
|
||||
return Err("Invalid or duplicate graph input identifier".into());
|
||||
}
|
||||
let type_code = child_value(port, "type").and_then(|value| value.parse().ok()).ok_or("Invalid graph input type")?;
|
||||
inputs.push(GraphPort { identifier: identifier.into(), type_code });
|
||||
}
|
||||
Ok(inputs)
|
||||
})())
|
||||
}
|
||||
|
||||
pub(super) fn write(out: &mut String, inputs: &[GraphPort]) {
|
||||
out.push_str("<materialcraftInterface>");
|
||||
for port in inputs {
|
||||
let _ = write!(out, "<input><identifier v=\"{}\"/><type v=\"{}\"/></input>", xml_escape(&port.identifier), port.type_code);
|
||||
}
|
||||
out.push_str("</materialcraftInterface>");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn interface_rejects_duplicate_malformed_and_excess_inputs() {
|
||||
let parse = |body: &str| {
|
||||
let xml = format!("<compInstance><materialcraftInterface>{body}</materialcraftInterface></compInstance>");
|
||||
let document = roxmltree::Document::parse(&xml).unwrap();
|
||||
read(document.root_element()).unwrap()
|
||||
};
|
||||
assert!(parse("<input><identifier v=\"a\"/><type v=\"bad\"/></input>").is_err());
|
||||
assert!(parse("<input><identifier v=\"a\"/><type v=\"1\"/></input>".repeat(2).as_str()).is_err());
|
||||
let mut body = String::new();
|
||||
for index in 0..4096 {
|
||||
write!(body, "<input><identifier v=\"p{index}\"/><type v=\"2\"/></input>").unwrap();
|
||||
}
|
||||
assert_eq!(parse(&body).unwrap().len(), 4096);
|
||||
body.push_str("<input><identifier v=\"extra\"/><type v=\"2\"/></input>");
|
||||
assert!(parse(&body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ mod graph_attributes;
|
||||
mod group_layout;
|
||||
mod image_input;
|
||||
mod input_bridge;
|
||||
mod instance_interface;
|
||||
mod layout_frame;
|
||||
mod layout_item;
|
||||
pub mod library;
|
||||
|
||||
@@ -262,6 +262,9 @@ impl<'text> SbsReader<'text, '_> {
|
||||
|
||||
self.node_count += 1;
|
||||
let mut node = self.read_node(&mut graph, *comp_node, &image_inputs, &outputs);
|
||||
if let Some(document_node) = graph.nodes.get_mut(node.index) {
|
||||
document_node.disabled = child_value(*comp_node, "materialcraftDisabled") == Some("1");
|
||||
}
|
||||
for input in child_element(*comp_node, "inputValues").into_iter().flat_map(|inputs| children_named(inputs, "compInputValue")).take(64) {
|
||||
let identifier = child_value(input, "identifier").unwrap_or("");
|
||||
let value_type = child_value(input, "type").and_then(|code| code.parse().ok()).and_then(materialcraft_core::ValueType::from_code);
|
||||
@@ -562,9 +565,19 @@ impl<'text> SbsReader<'text, '_> {
|
||||
if own_graph.is_some() || external.is_some() {
|
||||
let (id, index, node) = push_node(graph, "graph_instance", pos);
|
||||
if let Some(node) = node {
|
||||
if let Some(sub_graph) = own_graph {
|
||||
node.params.insert("graph".into(), Value::Text(sub_graph));
|
||||
} else {
|
||||
let interface = super::instance_interface::read(implementation);
|
||||
let has_interface = interface.is_some();
|
||||
let inputs = match interface.transpose() {
|
||||
Ok(inputs) => inputs.unwrap_or_default(),
|
||||
Err(error) => {
|
||||
self.warnings.add(error);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
if let Some(sub_graph) = &own_graph {
|
||||
node.params.insert("graph".into(), Value::Text(sub_graph.clone()));
|
||||
}
|
||||
if own_graph.is_none() || has_interface {
|
||||
let comp_node = implementation.parent().and_then(|parent| parent.parent());
|
||||
let types: HashMap<_, _> = comp_node
|
||||
.and_then(|node| child_element(node, "compOutputs"))
|
||||
@@ -579,7 +592,7 @@ impl<'text> SbsReader<'text, '_> {
|
||||
defaults: Default::default(),
|
||||
package: external.unwrap_or("").into(),
|
||||
graph: path.clone(),
|
||||
inputs: Vec::new(),
|
||||
inputs,
|
||||
outputs: bridgings
|
||||
.iter()
|
||||
.map(|(uid, identifier)| materialcraft_core::GraphPort {
|
||||
|
||||
@@ -91,6 +91,10 @@ impl SbsWriter {
|
||||
let (x, y) = (node.pos[0] + NODE_HALF_SIZE[0], node.pos[1] + NODE_HALF_SIZE[1]);
|
||||
let _ = write!(out, "<compNode><uid v=\"{uid}\"/><GUILayout><gpos v=\"{} {} 0\"/></GUILayout>", format_float(x), format_float(y));
|
||||
|
||||
if node.disabled {
|
||||
out.push_str("<materialcraftDisabled v=\"1\"/>");
|
||||
}
|
||||
|
||||
if !node.input_values.is_empty() {
|
||||
out.push_str("<inputValues>");
|
||||
for (identifier, value) in &node.input_values {
|
||||
@@ -303,6 +307,9 @@ impl SbsWriter {
|
||||
xml_escape(&sub_graph),
|
||||
dependency
|
||||
);
|
||||
if let Some(instance) = &node.instance {
|
||||
super::instance_interface::write(out, &instance.inputs);
|
||||
}
|
||||
write_bridgings(out, outputs);
|
||||
out.push_str("</compInstance>");
|
||||
}
|
||||
|
||||
@@ -458,3 +458,58 @@ fn input_usage_defaults_and_unknown_metadata_stay_unclassified() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn published_material_preserves_disabled_nodes_and_localized_typed_interfaces() {
|
||||
use crate::material::{read_material, write_material};
|
||||
use materialcraft_core::{GraphInstance, GraphPort, ValueType};
|
||||
|
||||
let mut helper = Graph::new("Helper");
|
||||
let input = helper.add_node("input_grayscale", [0.0; 2]);
|
||||
helper.node_mut(input).unwrap().params.insert("identifier".into(), Value::Text("gray".into()));
|
||||
let out = helper.add_node("output", [0.0; 2]);
|
||||
helper.node_mut(out).unwrap().params.insert("identifier".into(), Value::Text("result".into()));
|
||||
helper.connect(input, "output", out, "input").unwrap();
|
||||
let mut dependency = Package::new("Dependency");
|
||||
dependency.graphs.push(helper);
|
||||
|
||||
let mut graph = Graph::new("Root");
|
||||
let uniform = graph.add_node("uniform", [0.0; 2]);
|
||||
let levels = graph.add_node("levels", [0.0; 2]);
|
||||
graph.node_mut(levels).unwrap().disabled = true;
|
||||
graph.connect(uniform, "output", levels, "input").unwrap();
|
||||
let instance = graph.add_node("graph_instance", [0.0; 2]);
|
||||
let inputs = vec![GraphPort { identifier: "gray".into(), type_code: 2 }, GraphPort { identifier: "unused<&".into(), type_code: ValueType::Float as u32 }];
|
||||
graph.node_mut(instance).unwrap().instance = Some(GraphInstance {
|
||||
package: "dependency.sbs".into(),
|
||||
graph: "Helper".into(),
|
||||
inputs: inputs.clone(),
|
||||
outputs: vec![GraphPort { identifier: "result".into(), type_code: 2 }],
|
||||
defaults: Default::default(),
|
||||
label: String::new(),
|
||||
});
|
||||
graph.connect(levels, "output", instance, "gray").unwrap();
|
||||
let out = graph.add_node("output", [0.0; 2]);
|
||||
graph.connect(instance, "result", out, "input").unwrap();
|
||||
let mut package = Package::new("Package");
|
||||
package.graphs.push(graph);
|
||||
package.dependencies.insert("dependency.sbs".into(), std::sync::Arc::new(dependency));
|
||||
|
||||
let bytes = write_material(&package, 0).unwrap();
|
||||
let (opened, entry) = read_material(&bytes).unwrap();
|
||||
let graph = &opened.graphs[entry];
|
||||
assert!(graph.nodes.iter().find(|node| node.def == "levels").unwrap().disabled);
|
||||
assert!(!graph.nodes.iter().find(|node| node.def == "uniform").unwrap().disabled);
|
||||
let node = graph.nodes.iter().find(|node| node.def == "graph_instance").unwrap();
|
||||
let restored = node.instance.as_ref().expect("localization must retain the typed interface");
|
||||
assert!(restored.package.is_empty());
|
||||
assert_eq!(restored.inputs, inputs);
|
||||
assert_eq!(restored.outputs, vec![GraphPort { identifier: "result".into(), type_code: 2 }]);
|
||||
assert!(opened.graph_by_name(&restored.graph).is_some());
|
||||
assert!(graph.connections.iter().any(|wire| wire.to == node.id && wire.to_port == "gray"));
|
||||
// Republish the already-localized graph as well as the original external reference.
|
||||
let bytes = write_material(&opened, entry).unwrap();
|
||||
let (reopened, entry) = read_material(&bytes).unwrap();
|
||||
assert_eq!(reopened.graphs[entry].nodes.iter().find_map(|node| node.instance.as_ref()).unwrap().inputs, inputs);
|
||||
assert!(reopened.graphs[entry].nodes.iter().find(|node| node.def == "levels").unwrap().disabled);
|
||||
}
|
||||
Reference in new issue
Block a user