diff --git a/Cargo.lock b/Cargo.lock index c3134a01..7bf798f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2331,7 +2331,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "materialcraft" -version = "0.1.3" +version = "0.2.0" dependencies = [ "eframe", "egui", @@ -2347,7 +2347,7 @@ dependencies = [ [[package]] name = "materialcraft-automation" -version = "0.1.3" +version = "0.2.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -2368,7 +2368,7 @@ dependencies = [ [[package]] name = "materialcraft-cli" -version = "0.1.3" +version = "0.2.0" dependencies = [ "materialcraft-automation", "materialcraft-engine", @@ -2379,7 +2379,7 @@ dependencies = [ [[package]] name = "materialcraft-core" -version = "0.1.3" +version = "0.2.0" dependencies = [ "serde", "serde_json", @@ -2388,7 +2388,7 @@ dependencies = [ [[package]] name = "materialcraft-engine" -version = "0.1.3" +version = "0.2.0" dependencies = [ "materialcraft-core", "materialcraft-eval", @@ -2403,7 +2403,7 @@ dependencies = [ [[package]] name = "materialcraft-eval" -version = "0.1.3" +version = "0.2.0" dependencies = [ "materialcraft-core", "materialcraft-image", @@ -2413,7 +2413,7 @@ dependencies = [ [[package]] name = "materialcraft-formats" -version = "0.1.3" +version = "0.2.0" dependencies = [ "base64 0.22.1", "flate2", @@ -2434,7 +2434,7 @@ dependencies = [ [[package]] name = "materialcraft-geom" -version = "0.1.3" +version = "0.2.0" dependencies = [ "glam 0.30.10", "mikktspace", @@ -2445,7 +2445,7 @@ dependencies = [ [[package]] name = "materialcraft-image" -version = "0.1.3" +version = "0.2.0" dependencies = [ "rayon", "thiserror 2.0.21", @@ -2453,7 +2453,7 @@ dependencies = [ [[package]] name = "materialcraft-nodes" -version = "0.1.3" +version = "0.2.0" dependencies = [ "materialcraft-core", "materialcraft-image", @@ -2462,7 +2462,7 @@ dependencies = [ [[package]] name = "materialcraft-render" -version = "0.1.3" +version = "0.2.0" dependencies = [ "materialcraft-core", "materialcraft-geom", @@ -2472,7 +2472,7 @@ dependencies = [ [[package]] name = "materialcraft-ui-egui" -version = "0.1.3" +version = "0.2.0" dependencies = [ "base64 0.22.1", "craft-ui", @@ -2497,7 +2497,7 @@ dependencies = [ [[package]] name = "materialcraft-web" -version = "0.1.3" +version = "0.2.0" dependencies = [ "eframe", "js-sys", @@ -5394,7 +5394,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.1.3" +version = "0.2.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 03d0173d..51ce6420 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ default-members = [ ] [workspace.package] -version = "0.1.3" +version = "0.2.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 08e9dd0a..172445f0 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -57,6 +57,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::annotation_commands::specs()); v.extend(crate::frame_commands::specs()); v.extend(crate::function_commands::specs()); + v.extend(crate::function_info_commands::specs()); v.extend(crate::comment_commands::specs()); v.extend(crate::node_cmds::specs()); v.extend(crate::node_graph_commands::specs()); diff --git a/crates/engine/src/embedded_wire_commands.rs b/crates/engine/src/embedded_wire_commands.rs new file mode 100644 index 00000000..8198c4a6 --- /dev/null +++ b/crates/engine/src/embedded_wire_commands.rs @@ -0,0 +1,55 @@ +use crate::{Result, SelectionTarget, Session, commands::bad, graph_edit}; +use materialcraft_core::Value; +use serde_json::{Value as Json, json}; + +pub(crate) fn execute(session: &mut Session, command: &str, parameters: &Json, swapping: bool) -> Option> { + match SelectionTarget::resolve(session, parameters) { + Ok(Some(target)) => Some(run(session, command, parameters, target, swapping)), + Ok(None) => None, + Err(error) => Some(Err(error)), + } +} + +fn run(session: &mut Session, command: &str, parameters: &Json, target: SelectionTarget, swapping: bool) -> Result { + let entries = parameters.get("wires").and_then(Json::as_array).ok_or_else(|| bad(command, "wires must be a list of {to, toPort}"))?; + if entries.len() > 4096 { + return Err(bad(command, "at most 4096 links")); + } + + let wires = entries + .iter() + .map(|entry| { + let id = entry.get("to").and_then(Json::as_u64).and_then(|id| u32::try_from(id).ok()).ok_or_else(|| bad(command, "invalid node id"))?; + let port = entry.get("toPort").and_then(Json::as_str).ok_or_else(|| bad(command, "missing port"))?; + let slot = match &target { + SelectionTarget::Function(_) => port.parse().ok(), + SelectionTarget::Pattern(owner) => SelectionTarget::pattern(session, *owner)? + .nodes + .iter() + .find(|node| node.id == id) + .and_then(|node| (0..node.children.len()).find(|slot| node.kind.child_port(*slot) == Some(port))), + } + .ok_or_else(|| bad(command, "invalid link port"))?; + Ok((id, slot)) + }) + .collect::>>()?; + let label = if swapping { "Swap links" } else { "Delete links" }; + match target { + SelectionTarget::Function(target) => { + let mut graph = target.current(session)?.clone(); + graph_edit::edit_links(&mut graph, &wires, swapping).map_err(|error| bad(command, error))?; + crate::graph_validation::function(&graph).map_err(|error| bad(command, error))?; + session.edit(label, |session| target.replace(session, graph))?; + } + SelectionTarget::Pattern(owner) => { + let mut graph = SelectionTarget::pattern(session, owner)?.clone(); + graph_edit::edit_links(&mut graph, &wires, swapping).map_err(|error| bad(command, error))?; + crate::graph_validation::pattern(&graph).map_err(|error| bad(command, error))?; + session.edit(label, |session| { + session.graph_mut()?.node_mut(owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph))); + Ok(()) + })?; + } + } + Ok(if swapping { json!({"swapped": wires.len()}) } else { json!({"deleted": wires.len()}) }) +} diff --git a/crates/engine/src/function_edit.rs b/crates/engine/src/function_edit.rs index 24494325..0987985c 100644 --- a/crates/engine/src/function_edit.rs +++ b/crates/engine/src/function_edit.rs @@ -38,6 +38,7 @@ impl FunctionEdit { if graph.nodes.len() >= 4096 { return Err("the function exceeds the 4096-node limit".into()); } + let definition = materialcraft_nodes::function::definition(operation).ok_or("unknown function operation")?; let id = graph.next_id(); graph.nodes.push(FunctionNode { @@ -48,9 +49,6 @@ impl FunctionEdit { value: materialcraft_nodes::function::default_value(operation), pos: crate::graph_grid::snap_position(*at, *snap), }); - if graph.output.is_none() { - graph.output = Some(id); - } return Ok(json!({"id": id})); } Self::Move { ids, by, snap } => { @@ -59,6 +57,7 @@ impl FunctionEdit { return Err(format!("no function node {id}")); } } + for node in &mut graph.nodes { if ids.contains(&node.id) { node.pos = crate::graph_grid::translate(node.pos, *by, *snap); @@ -69,11 +68,13 @@ impl FunctionEdit { if from == to || graph.node(*from).is_none() { return Err("invalid function source".into()); } + let node = graph.nodes.iter_mut().find(|node| node.id == *to).ok_or("missing function destination")?; let count = materialcraft_nodes::function::definition(&node.op).map_or(0, |definition| definition.inputs.len()); if *input >= count { return Err("invalid function input".into()); } + node.inputs.resize(count, None); if let Some(slot) = node.inputs.get_mut(*input) { *slot = Some(*from); @@ -84,15 +85,18 @@ impl FunctionEdit { if node.value.is_none() { return Err("the operation has no editable value".into()); } + node.value = Some(value.clone()); } Self::Output { id } => { if graph.node(*id).is_none() { return Err("missing output node".into()); } + graph.output = Some(*id); } } + Ok(Json::Null) } diff --git a/crates/engine/src/function_info_commands.rs b/crates/engine/src/function_info_commands.rs new file mode 100644 index 00000000..28090052 --- /dev/null +++ b/crates/engine/src/function_info_commands.rs @@ -0,0 +1,30 @@ +use crate::{ + FunctionGraphTarget, Result, Session, cmd, + commands::{CommandSpec, bad, has_graph}, +}; +use serde_json::{Value as Json, json}; + +pub(crate) fn specs() -> Vec { + vec![cmd!( + "graph.function.node.info", + "Copy function node info", + [], + None, + "{id, target?: FunctionGraphTarget} returns text describing a function node without changing the document or node clipboard", + has_graph, + info + )] +} + +fn info(session: &mut Session, parameters: &Json) -> Result { + let command = "graph.function.node.info"; + let target: FunctionGraphTarget = serde_json::from_value(parameters.get("target").cloned().unwrap_or_else(|| json!({"kind": "graph"}))) + .map_err(|error| bad(command, error.to_string()))?; + let id = parameters.get("id").and_then(Json::as_u64).and_then(|id| u32::try_from(id).ok()).ok_or_else(|| bad(command, "id must be a function node id"))?; + let graph = target.current(session)?; + let node = graph.node(id).ok_or_else(|| bad(command, "missing function node"))?; + let label = materialcraft_nodes::function::definition(&node.op).map_or(node.op.as_str(), |definition| definition.label); + let text = serde_json::to_string_pretty(&json!({"target": target, "label": label, "node": node, "output": graph.output == Some(id)})) + .map_err(|error| bad(command, error.to_string()))?; + Ok(json!({"text": text})) +} diff --git a/crates/engine/src/function_inspection.rs b/crates/engine/src/function_inspection.rs new file mode 100644 index 00000000..330f3c41 --- /dev/null +++ b/crates/engine/src/function_inspection.rs @@ -0,0 +1,43 @@ +use crate::FunctionGraphTarget; +use materialcraft_core::{FunctionGraph, Graph, Value}; +use serde_json::{Value as Json, json}; + +pub(crate) fn warnings(graph: &Graph) -> Vec { + let mut entries = Vec::new(); + let mut inspect = |target: FunctionGraphTarget, function: &FunctionGraph| { + let messages = materialcraft_nodes::function::warnings(function); + if !messages.is_empty() { + entries.push(json!({"target": target, "messages": messages})); + } + }; + if let Some(function) = &graph.function { + inspect(FunctionGraphTarget::Graph, function); + } + + for node in &graph.nodes { + for (parameter, function) in &node.functions { + inspect(FunctionGraphTarget::Dynamic { node: node.id, parameter: parameter.clone() }, function); + } + let defaults = materialcraft_nodes::find(&node.def) + .into_iter() + .flat_map(|definition| &definition.params) + .filter(|parameter| !node.params.contains_key(parameter.id)) + .map(|parameter| (parameter.id, ¶meter.default)); + for (parameter, value) in node.params.iter().map(|(parameter, value)| (parameter.as_str(), value)).chain(defaults) { + match value { + Value::Function(function) => inspect(FunctionGraphTarget::Parameter { node: node.id, parameter: parameter.into() }, function), + Value::PatternGraph(pattern) => { + for child in &pattern.nodes { + for (parameter, value) in &child.parameters { + if let Value::Function(function) = value { + inspect(FunctionGraphTarget::Pattern { owner: node.id, node: child.id, parameter: parameter.clone() }, function); + } + } + } + } + _ => {} + } + } + } + entries +} diff --git a/crates/engine/src/graph_edit/links.rs b/crates/engine/src/graph_edit/links.rs new file mode 100644 index 00000000..608d233e --- /dev/null +++ b/crates/engine/src/graph_edit/links.rs @@ -0,0 +1,30 @@ +use super::EditableGraph; +use std::collections::BTreeSet; + +pub(crate) fn edit_links(graph: &mut G, wires: &[(u32, usize)], swapping: bool) -> Result<(), String> { + if swapping && wires.len() != 2 { + return Err("select exactly two links to swap".into()); + } + if wires.is_empty() || wires.len() > 4096 { + return Err("select between 1 and 4096 links".into()); + } + + let mut seen = BTreeSet::new(); + let mut sources = Vec::with_capacity(wires.len()); + for &(id, slot) in wires { + if !seen.insert((id, slot)) { + return Err("a link is listed twice".into()); + } + + let source = graph.nodes().iter().find(|node| G::id(node) == id).and_then(|node| G::links(node).get(slot)).copied().flatten(); + sources.push(source.ok_or_else(|| format!("no link at port {slot} of node {id}"))?); + } + + // Validate the whole exchange afterward so temporary connections cannot create a false cycle + for (&(id, slot), source) in wires.iter().zip(sources.into_iter().rev()) { + if let Some(link) = graph.nodes_mut().iter_mut().find(|node| G::id(node) == id).and_then(|node| G::links_mut(node).get_mut(slot)) { + *link = swapping.then_some(source); + } + } + Ok(()) +} diff --git a/crates/engine/src/graph_edit/mod.rs b/crates/engine/src/graph_edit/mod.rs index 1215fe96..36f1f069 100644 --- a/crates/engine/src/graph_edit/mod.rs +++ b/crates/engine/src/graph_edit/mod.rs @@ -2,8 +2,10 @@ mod editable_graph; mod function_graph; +mod links; mod pattern_graph; mod selection; pub use editable_graph::EditableGraph; +pub(crate) use links::edit_links; pub use selection::{enabled, read, remove, run}; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index b2c9814b..224a78e7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -14,6 +14,7 @@ pub fn session(s: &Session, graph: Option) -> J { "name": g.name, "kind": g.kind(), "function": g.function, + "functionWarnings": crate::function_inspection::warnings(g), "size": g.size_px(), "format": g.format, "seed": g.seed, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a2a8846f..efb825ad 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -77,8 +77,11 @@ pub use annotation_selection::AnnotationSelection; pub use frame_contents::FrameContents; mod embedded_edit_commands; +mod embedded_wire_commands; mod function_edit; mod function_graph_target; +mod function_info_commands; +mod function_inspection; mod pattern_edit; pub use function_edit::FunctionEdit; pub use function_graph_target::FunctionGraphTarget; diff --git a/crates/engine/src/wire_cmds.rs b/crates/engine/src/wire_cmds.rs index 4912b567..079bbeab 100644 --- a/crates/engine/src/wire_cmds.rs +++ b/crates/engine/src/wire_cmds.rs @@ -1,6 +1,6 @@ //! Wire commands: edit wires (connections) of the open graph, each addressed by the input it //! feeds (`to`, `toPort`): split a wire with a reroute dot so it can be repositioned, delete -//! several wires at once, and swap (reverse) where a set of wires come from. +//! several wires at once, and exchange the sources of a pair of wires. use serde_json::{Value as J, json}; @@ -25,7 +25,7 @@ pub(crate) fn specs() -> Vec { "Delete links", [], None, - "{wires: [{to, toPort}, ...]} deletes the wires feeding those inputs, in one undo step", + "{function?: FunctionGraphTarget, pattern?: owner, wires: [{to, toPort}, ...]} deletes the wires feeding those inputs, in one undo step", has_graph, delete ), @@ -34,7 +34,7 @@ pub(crate) fn specs() -> Vec { "Swap links", [], None, - "{wires: [{to, toPort}, ...] (two or more)} reverses where the wires come from: sorted by target node and input order, the first wire's source goes to the last input and so on (two wires swap)", + "{function?: FunctionGraphTarget, pattern?: owner, wires: [{to, toPort}, {to, toPort}]} exchanges the sources of exactly two connected inputs in one undo step", has_graph, swap ), @@ -65,6 +65,10 @@ fn wires_param(s: &Session, id: &str, p: &J) -> Result> { } fn delete(s: &mut Session, p: &J) -> Result { + if let Some(result) = crate::embedded_wire_commands::execute(s, "graph.wire.delete", p, false) { + return result; + } + let wires = wires_param(s, "graph.wire.delete", p)?; if wires.is_empty() { return Err(bad("graph.wire.delete", "no wire given")); @@ -78,24 +82,27 @@ fn delete(s: &mut Session, p: &J) -> Result { }) } -fn swap(s: &mut Session, p: &J) -> Result { +fn swap(session: &mut Session, parameters: &J) -> Result { const ID: &str = "graph.wire.swap"; - let mut wires = wires_param(s, ID, p)?; - if wires.len() < 2 { - return Err(bad(ID, "select two or more wires to swap")); + if let Some(result) = crate::embedded_wire_commands::execute(session, ID, parameters, true) { + return result; } - // A stable order whatever order the wires were picked in: target node, then input order. - let order = |s: &Session, c: &Connection| (c.to.0, s.input_ports(c.to).iter().position(|p| *p == c.to_port).unwrap_or(usize::MAX)); - wires.sort_by_key(|c| order(s, c)); - let sources: Vec<(NodeId, String)> = wires.iter().rev().map(|c| (c.from, c.from_port.clone())).collect(); - s.edit("Swap links", |s| { - let g = s.graph_mut()?; - // Unplug them all first, so no half-swapped state is mistaken for a cycle. - for c in &wires { - g.disconnect(c.to, &c.to_port); + + let wires = wires_param(session, ID, parameters)?; + if wires.len() != 2 { + return Err(bad(ID, "select exactly two links to swap")); + } + + session.edit("Swap links", |session| { + let graph = session.graph_mut()?; + // Disconnect both first so an intermediate connection cannot create a false cycle + for connection in &wires { + graph.disconnect(connection.to, &connection.to_port); } - for (c, (from, port)) in wires.iter().zip(&sources) { - g.connect(*from, port, c.to, &c.to_port).map_err(|_| bad(ID, format!("swapping would feed node {} into itself (a cycle)", c.to.0)))?; + for (connection, source) in wires.iter().zip(wires.iter().rev()) { + graph + .connect(source.from, &source.from_port, connection.to, &connection.to_port) + .map_err(|_| bad(ID, format!("swapping would feed node {} into itself (a cycle)", connection.to.0)))?; } Ok(json!({"swapped": wires.len()})) }) diff --git a/crates/engine/tests/embedded_edit.rs b/crates/engine/tests/embedded_edit.rs index c995c2e0..16a54152 100644 --- a/crates/engine/tests/embedded_edit.rs +++ b/crates/engine/tests/embedded_edit.rs @@ -35,6 +35,138 @@ fn function_session(kind: &str) -> (Session, FunctionGraphTarget) { (session, target) } +#[test] +fn pattern_links_swap_between_parents_and_reject_invalid_pairs_atomically() { + let mut session = new_session(); + let owner = execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap(); + let mut graph = PatternGraph::with_root(PatternNodeKind::Switch); + let a = graph.add(PatternNodeKind::Quadrant).unwrap(); + let b = graph.add(PatternNodeKind::Quadrant).unwrap(); + let other = graph.add(PatternNodeKind::Iterate).unwrap(); + graph.nodes[0].children = vec![Some(a), Some(b)]; + graph.nodes[3].children = vec![Some(b), None]; + execute(&mut session, "graph.pattern.set", &json!({"id": owner, "pattern": graph})).unwrap(); + let before = session.pkg.clone(); + session.reset_history(); + let wires = json!([{"to": 1, "toPort": "output0"}, {"to": other, "toPort": "output0"}]); + let parameters = json!({"pattern": owner, "wires": wires}); + execute(&mut session, "graph.wire.swap", ¶meters).unwrap(); + let Value::PatternGraph(swapped) = &session.graph().unwrap().node(NodeId(owner)).unwrap().params["pattern"] else { panic!() }; + assert_eq!(swapped.nodes[0].children, vec![Some(b), Some(b)]); + assert_eq!(swapped.nodes[3].children, vec![Some(a), None]); + assert_eq!(swapped.root, graph.root); + assert_eq!(session.history().len(), 1); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + session.redo().unwrap(); + execute(&mut session, "graph.wire.swap", ¶meters).unwrap(); + assert_eq!(session.pkg, before); + + for wires in [ + json!([]), + json!([{"to": 1, "toPort": "output0"}]), + json!([{"to": 1, "toPort": "output0"}, {"to": 1, "toPort": "output0"}]), + json!([{"to": 1, "toPort": "output0"}, {"to": 1, "toPort": "output1"}, {"to": other, "toPort": "output0"}]), + json!([{"to": 1, "toPort": "output0"}, {"to": a, "toPort": "output0"}]), + json!([{"to": 1, "toPort": "output0"}, {"to": u32::MAX, "toPort": "output0"}]), + json!([{"to": 1, "toPort": "output0"}, {"to": other, "toPort": "invalid"}]), + ] { + let history = session.history(); + assert!(execute(&mut session, "graph.wire.swap", &json!({"pattern": owner, "wires": wires})).is_err()); + assert_eq!(session.pkg, before); + assert_eq!(session.history(), history); + } + execute(&mut session, "graph.wire.delete", &json!({"pattern": owner, "wires": wires})).unwrap(); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + + execute(&mut session, "graph.pattern.edit", &json!({"id": owner, "edit": {"action": "connect", "parent": a, "slot": 0, "child": b}})).unwrap(); + let before = session.pkg.clone(); + let history = session.history(); + let cycle = json!({"pattern": owner, "wires": [{"to": 1, "toPort": "output0"}, {"to": a, "toPort": "output0"}]}); + assert!(execute(&mut session, "graph.wire.swap", &cycle).is_err()); + assert_eq!(session.pkg, before); + assert_eq!(session.history(), history); +} + +#[test] +fn selected_function_links_swap_sources_and_delete_in_one_undo_step() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let mut graph = FunctionGraph::default(); + let a = graph.add_constant(Value::Float3([1.0, 2.0, 3.0])); + let b = graph.add_constant(Value::Float3([4.0, 5.0, 6.0])); + let subtract = graph.add("sub", &[a, b], None); + let other = graph.add("passthrough", &[b], None); + graph.output = Some(subtract); + execute(&mut session, "graph.function.set", &json!({"target": target, "function": graph})).unwrap(); + session.reset_history(); + let before = session.pkg.clone(); + let parameters = json!({"function": target, "wires": [{"to": subtract, "toPort": "0"}, {"to": subtract, "toPort": "1"}]}); + + execute(&mut session, "graph.wire.swap", ¶meters).unwrap(); + let swapped = target.current(&session).unwrap(); + assert_eq!(swapped.node(subtract).unwrap().inputs, vec![Some(b), Some(a)]); + assert_eq!(swapped.node(other).unwrap().inputs, vec![Some(b)]); + assert_eq!(swapped.output, Some(subtract)); + assert_eq!(session.history().len(), 1); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + session.redo().unwrap(); + execute(&mut session, "graph.wire.swap", ¶meters).unwrap(); + assert_eq!(session.pkg, before); + + execute(&mut session, "graph.wire.delete", ¶meters).unwrap(); + assert_eq!(target.current(&session).unwrap().node(subtract).unwrap().inputs, vec![None, None]); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + + let selection = session.selection.clone(); + let parameters = json!({"function": target, "wires": [{"to": subtract, "toPort": "0"}, {"to": other, "toPort": "0"}]}); + execute(&mut session, "graph.wire.swap", ¶meters).unwrap(); + let swapped = target.current(&session).unwrap(); + assert_eq!(swapped.node(subtract).unwrap().inputs, vec![Some(b), Some(b)]); + assert_eq!(swapped.node(other).unwrap().inputs, vec![Some(a)]); + assert_eq!(session.selection, selection); + session.undo().unwrap(); + assert_eq!(session.pkg, before); + } +} + +#[test] +fn function_link_swap_rejects_cycles_and_invalid_selections_atomically() { + let (mut session, target) = function_session("graph"); + let mut graph = FunctionGraph::default(); + let scalar = graph.add_constant(Value::Float(1.0)); + let vector = graph.add_constant(Value::Float2([1.0, 2.0])); + let first = graph.add("add", &[scalar, scalar], None); + let second = graph.add("add", &[first, scalar], None); + let vector_sum = graph.add("add", &[vector, vector], None); + execute(&mut session, "graph.function.set", &json!({"function": graph})).unwrap(); + let package = session.pkg.clone(); + let history = session.history(); + for wires in [ + json!([]), + json!([{"to": first, "toPort": "0"}]), + json!([{"to": first, "toPort": "0"}, {"to": first, "toPort": "0"}]), + json!([{"to": first, "toPort": "0"}, {"to": first, "toPort": "1"}, {"to": second, "toPort": "1"}]), + json!([{"to": first, "toPort": "0"}, {"to": second, "toPort": "0"}]), + json!([{"to": first, "toPort": "0"}, {"to": u32::MAX, "toPort": "0"}]), + json!([{"to": first, "toPort": "0"}, {"to": second, "toPort": u64::MAX}]), + ] { + assert!(execute(&mut session, "graph.wire.swap", &json!({"function": target, "wires": wires})).is_err(), "{wires}"); + assert_eq!(session.pkg, package); + assert_eq!(session.history(), history); + } + let parameters = json!({"wires": [{"to": second, "toPort": "1"}, {"to": vector_sum, "toPort": "1"}]}); + execute(&mut session, "graph.wire.delete", ¶meters).unwrap(); + let package = session.pkg.clone(); + let history = session.history(); + assert!(execute(&mut session, "graph.wire.swap", ¶meters).is_err()); + assert_eq!(session.pkg, package); + assert_eq!(session.history(), history); +} + #[test] fn creation_and_connections_use_the_same_rules_for_every_function_target() { for kind in ["graph", "parameter", "dynamic", "pattern"] { @@ -52,7 +184,7 @@ fn creation_and_connections_use_the_same_rules_for_every_function_target() { let graph = target.current(&session).unwrap(); assert_eq!(graph.node(ids[1]).unwrap().inputs, vec![None, None]); assert_eq!(graph.node(ids[1]).unwrap().pos, [32.0, -32.0]); - assert_eq!(graph.output, Some(ids[0])); + assert_eq!(graph.output, None); execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": ids[0], "to": ids[1], "input": 0}})) .unwrap(); assert_eq!(target.current(&session).unwrap().node(ids[1]).unwrap().inputs[0], Some(ids[0])); @@ -68,6 +200,95 @@ fn creation_and_connections_use_the_same_rules_for_every_function_target() { } } +#[test] +fn output_designation_is_explicit_and_undoable_for_every_function_target() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let mut ids = Vec::new(); + for operation in ["const_float1", "passthrough"] { + let result = + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": operation, "at": [0, 0]}})) + .unwrap(); + ids.push(result["id"].as_u64().unwrap() as u32); + } + assert_eq!(target.current(&session).unwrap().output, None, "{kind}"); + + for id in &ids { + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": id}})).unwrap(); + assert_eq!(target.current(&session).unwrap().output, Some(*id)); + } + session.undo().unwrap(); + assert_eq!(target.current(&session).unwrap().output, Some(ids[0])); + session.redo().unwrap(); + assert_eq!(target.current(&session).unwrap().output, Some(ids[1])); + + let package = session.pkg.clone(); + let history = session.history(); + assert!(execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": u32::MAX}})).is_err()); + assert_eq!(session.pkg, package); + assert_eq!(session.history(), history); + + execute(&mut session, "edit.delete", &json!({"function": target, "ids": [ids[1]]})).unwrap(); + assert_eq!(target.current(&session).unwrap().output, None); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})).unwrap(); + assert_eq!(target.current(&session).unwrap().output, None, "adding a node must not replace a deleted output"); + + session.undo().unwrap(); + session.undo().unwrap(); + assert_eq!(session.pkg, package); + } +} + +#[test] +fn function_node_info_uses_the_explicit_target_without_editing_the_document() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let added = + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": "const_float1", "at": [0, 0]}})) + .unwrap(); + let id = added["id"].as_u64().unwrap(); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": id}})).unwrap(); + let package = session.pkg.clone(); + let history = session.history(); + let result = execute(&mut session, "graph.function.node.info", &json!({"target": target, "id": id})).unwrap(); + let info: serde_json::Value = serde_json::from_str(result["text"].as_str().unwrap()).unwrap(); + assert_eq!(info["node"]["id"], id); + assert_eq!(info["node"]["op"], "const_float1"); + assert_eq!(info["label"], "Float"); + assert_eq!(info["output"], true); + assert_eq!(info["target"], json!(target)); + for id in [u64::MAX, 999] { + assert!(execute(&mut session, "graph.function.node.info", &json!({"target": target, "id": id})).is_err()); + } + assert_eq!(session.pkg, package); + assert_eq!(session.history(), history); + } +} + +#[test] +fn incomplete_function_warnings_follow_edits_for_every_target() { + for kind in ["graph", "parameter", "dynamic", "pattern"] { + let (mut session, target) = function_session(kind); + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(Value::Float(0.5)); + let multiply = graph.add("mul", &[source], None); + execute(&mut session, "graph.function.set", &json!({"target": target, "function": graph})).unwrap(); + let warning = format!("Multiply (node {multiply}): input b is not connected"); + let expected = json!([{"target": target, "messages": ["No output node defined", warning]}]); + assert_eq!(materialcraft_engine::inspect::session(&session, None)["graph"]["functionWarnings"], expected, "{kind}"); + + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": multiply}})).unwrap(); + assert_eq!(materialcraft_engine::inspect::session(&session, None)["graph"]["functionWarnings"], json!([{"target": target, "messages": [warning]}])); + execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": source, "to": multiply, "input": 1}})) + .unwrap(); + assert_eq!(materialcraft_engine::inspect::session(&session, None)["graph"]["functionWarnings"], json!([])); + + session.undo().unwrap(); + session.undo().unwrap(); + assert_eq!(materialcraft_engine::inspect::session(&session, None)["graph"]["functionWarnings"], expected); + } +} + #[test] fn value_gestures_merge_but_separate_edits_undo_independently() { for kind in ["graph", "parameter", "dynamic", "pattern"] { diff --git a/crates/engine/tests/function_graph.rs b/crates/engine/tests/function_graph.rs index d3b6b39b..dac11466 100644 --- a/crates/engine/tests/function_graph.rs +++ b/crates/engine/tests/function_graph.rs @@ -7,6 +7,25 @@ use materialcraft_engine::{ }; use serde_json::json; +#[test] +fn incomplete_function_round_trip_preserves_nodes_without_choosing_an_output() { + let mut session = new_session(); + execute(&mut session, "file.new", &json!({"kind": "function", "name": "Unfinished"})).unwrap(); + for operation in ["const_float1", "mul"] { + execute(&mut session, "graph.function.edit", &json!({"edit": {"action": "add", "operation": operation, "at": [0, 0]}})).unwrap(); + } + assert_eq!(session.graph().unwrap().function.as_ref().unwrap().output, None); + + let bytes = write_sbs(&session.pkg).unwrap(); + let read = read_sbs(&bytes, "unfinished.sbs", &|_| None).unwrap(); + assert!(read.warnings.is_empty(), "{:?}", read.warnings); + let (_, graph) = read.pkg.graph_by_name("Unfinished").unwrap(); + let function = graph.function.as_ref().unwrap(); + assert_eq!(function.output, None); + assert_eq!(function.nodes.iter().map(|node| node.op.as_str()).collect::>(), vec!["const_float1", "mul"]); + assert_eq!(function.nodes[1].inputs, vec![None, None]); +} + #[test] fn standalone_function_creation_wiring_frame_movement_and_native_round_trip() { let mut session = new_session(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 8ee5d14c..7e8000d4 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -421,51 +421,57 @@ fn every_template_is_opaque_in_the_3d_view() { #[test] fn selected_wires_swap_their_sources_and_delete_together() { use materialcraft_engine::core::NodeId; - let mut s = sample_session(); - run(&mut s, "file.new", json!({"template": "empty"})); - let a = run(&mut s, "graph.node.add", json!({"def": "uniform", "at": [0, 0]}))["id"].as_u64().unwrap(); - let b = run(&mut s, "graph.node.add", json!({"def": "uniform", "at": [0, 200]}))["id"].as_u64().unwrap(); - let m = run(&mut s, "graph.node.add", json!({"def": "uniform", "at": [0, 400]}))["id"].as_u64().unwrap(); - let blend = run(&mut s, "graph.node.add", json!({"def": "blend", "at": [300, 100]}))["id"].as_u64().unwrap(); - run(&mut s, "graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"})); - run(&mut s, "graph.connect", json!({"from": b, "to": blend, "toPort": "background"})); - run(&mut s, "graph.connect", json!({"from": m, "to": blend, "toPort": "mask"})); - let src = |s: &Session, port: &str| s.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; - let fg_bg = json!({"wires": [{"to": blend, "toPort": "background"}, {"to": blend, "toPort": "foreground"}]}); - // Two wires swap, whatever order they are listed in; the other input is left alone - run(&mut s, "graph.wire.swap", fg_bg.clone()); - assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (b, a, m)); - run(&mut s, "graph.wire.swap", fg_bg.clone()); - assert_eq!((src(&s, "foreground"), src(&s, "background")), (a, b)); - // Three wires reverse in input order: foreground <-> mask, background stays + let mut session = sample_session(); + run(&mut session, "file.new", json!({"template": "empty"})); + let foreground = run(&mut session, "graph.node.add", json!({"def": "uniform", "at": [0, 0]}))["id"].as_u64().unwrap(); + let background = run(&mut session, "graph.node.add", json!({"def": "uniform", "at": [0, 200]}))["id"].as_u64().unwrap(); + let mask = run(&mut session, "graph.node.add", json!({"def": "uniform", "at": [0, 400]}))["id"].as_u64().unwrap(); + let blend = run(&mut session, "graph.node.add", json!({"def": "blend", "at": [300, 100]}))["id"].as_u64().unwrap(); + run(&mut session, "graph.connect", json!({"from": foreground, "to": blend, "toPort": "foreground"})); + run(&mut session, "graph.connect", json!({"from": background, "to": blend, "toPort": "background"})); + run(&mut session, "graph.connect", json!({"from": mask, "to": blend, "toPort": "mask"})); + let source = |session: &Session, port: &str| session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0; + let pair = json!({"wires": [{"to": blend, "toPort": "background"}, {"to": blend, "toPort": "foreground"}]}); + + // Swapping the pair leaves the mask link intact + run(&mut session, "graph.wire.swap", pair.clone()); + assert_eq!((source(&session, "foreground"), source(&session, "background"), source(&session, "mask")), (background, foreground, mask)); + run(&mut session, "graph.wire.swap", pair.clone()); + assert_eq!((source(&session, "foreground"), source(&session, "background")), (foreground, background)); + run(&mut session, "edit.undo", json!({})); + assert_eq!((source(&session, "foreground"), source(&session, "background")), (background, foreground)); + run(&mut session, "edit.redo", json!({})); + + // Only a pair can swap, even when three inputs are connected let all = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "background"}, {"to": blend, "toPort": "mask"}]}); - run(&mut s, "graph.wire.swap", all.clone()); - assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (m, b, a)); - // One undo step each - run(&mut s, "edit.undo", json!({})); - assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (a, b, m)); + let history = session.history(); + assert!(execute(&mut session, "graph.wire.swap", &all).is_err()); + assert_eq!(session.history(), history); + assert_eq!((source(&session, "foreground"), source(&session, "background"), source(&session, "mask")), (foreground, background, mask)); + // Bad requests change nothing for bad in [ json!({}), json!({"wires": [{"to": blend, "toPort": "foreground"}]}), json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "foreground"}]}), - json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": a, "toPort": "input"}]}), + json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": foreground, "toPort": "input"}]}), ] { - assert!(execute(&mut s, "graph.wire.swap", &bad).is_err(), "{bad}"); + assert!(execute(&mut session, "graph.wire.swap", &bad).is_err(), "{bad}"); } - assert_eq!(src(&s, "foreground"), a); - // A swap that would make a cycle is refused and rolled back: blend -> levels, then swap the wire into levels with the wire into blend's foreground - let lv = run(&mut s, "graph.node.add", json!({"def": "levels", "at": [600, 100]}))["id"].as_u64().unwrap(); - run(&mut s, "graph.connect", json!({"from": blend, "to": lv})); - let cyc = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": lv, "toPort": "input"}]}); - assert!(execute(&mut s, "graph.wire.swap", &cyc).is_err()); - assert_eq!(src(&s, "foreground"), a); - assert_eq!(s.graph().unwrap().connections.len(), 4); + assert_eq!(source(&session, "foreground"), foreground); + // Reject swaps that introduce a cycle without changing the graph + let levels = run(&mut session, "graph.node.add", json!({"def": "levels", "at": [600, 100]}))["id"].as_u64().unwrap(); + run(&mut session, "graph.connect", json!({"from": blend, "to": levels})); + let cycle = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": levels, "toPort": "input"}]}); + assert!(execute(&mut session, "graph.wire.swap", &cycle).is_err()); + assert_eq!(source(&session, "foreground"), foreground); + assert_eq!(session.graph().unwrap().connections.len(), 4); + // Deleting several wires is one step - run(&mut s, "graph.wire.delete", all); - assert_eq!(s.graph().unwrap().connections.len(), 1); - run(&mut s, "edit.undo", json!({})); - assert_eq!(s.graph().unwrap().connections.len(), 4); + run(&mut session, "graph.wire.delete", all); + assert_eq!(session.graph().unwrap().connections.len(), 1); + run(&mut session, "edit.undo", json!({})); + assert_eq!(session.graph().unwrap().connections.len(), 4); } #[test] diff --git a/crates/formats/src/sbs/constant.rs b/crates/formats/src/sbs/constant.rs index f35e9a96..16a7bea3 100644 --- a/crates/formats/src/sbs/constant.rs +++ b/crates/formats/src/sbs/constant.rs @@ -11,6 +11,7 @@ pub(super) const MAX_NODES: usize = 100_000; pub(super) const MAX_RESOURCES: usize = 4096; pub(super) const FORMAT_VERSION: &str = "1.1.0.202401"; +pub(super) const UPDATER_VERSION: &str = env!("CARGO_PKG_VERSION"); pub const SBS_EXT: &str = "sbs"; pub(super) const MAX_WARNINGS: usize = 600; diff --git a/crates/formats/src/sbs/tests.rs b/crates/formats/src/sbs/tests.rs index ccbc943d..19a085b4 100644 --- a/crates/formats/src/sbs/tests.rs +++ b/crates/formats/src/sbs/tests.rs @@ -60,6 +60,20 @@ fn sniffs_sbs() { assert!(!is_sbs(b"")); } +#[test] +fn saving_refreshes_the_writer_version_without_changing_the_schema_version() { + let old = br#""#; + let reopened = read_sbs(old, "older.sbs", &no_linked_files).unwrap(); + for package in [Package::new("New file"), reopened.pkg] { + let text = String::from_utf8(write_sbs(&package).unwrap()).unwrap(); + let document = roxmltree::Document::parse(&text).unwrap(); + let root = document.root_element(); + assert_eq!(super::xml::child_value(root, "updaterVersion"), Some(env!("CARGO_PKG_VERSION"))); + assert_eq!(super::xml::child_value(root, "formatVersion"), Some(super::constant::FORMAT_VERSION)); + assert!(!text.contains("0.0.1")); + } +} + #[test] fn structural_round_trip() { let pkg = sample_package(); diff --git a/crates/formats/src/sbs/write.rs b/crates/formats/src/sbs/write.rs index dbed6974..f98e2352 100644 --- a/crates/formats/src/sbs/write.rs +++ b/crates/formats/src/sbs/write.rs @@ -1,5 +1,5 @@ use super::{ - constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY}, + constant::{FIRST_UID, FORMAT_VERSION, SELF_DEPENDENCY, UPDATER_VERSION}, embedded::encode_embedded, sbs_writer::SbsWriter, xml::xml_escape, @@ -43,7 +43,7 @@ pub fn write_sbs(pkg: &Package) -> Result> { let mut out = String::with_capacity(content.len() + 4096); let _ = write!( out, - "", + "", xml_escape(&pkg.name) ); let write_dependency = |out: &mut String, file: &str, uid: u64| { diff --git a/crates/nodes/src/function/mod.rs b/crates/nodes/src/function/mod.rs index 2b36446e..fb4127f6 100644 --- a/crates/nodes/src/function/mod.rs +++ b/crates/nodes/src/function/mod.rs @@ -15,6 +15,7 @@ mod processor; mod program; pub mod value_type; mod vector; +mod warnings; pub use catalog::{FUNCTIONS, default_value, definition}; pub use compile::compile; @@ -25,6 +26,7 @@ pub use node_types::node_types; pub use processor::default_pixel_function; pub(crate) use processor::pixel_processor; pub use program::Program; +pub use warnings::warnings; #[cfg(test)] mod tests; diff --git a/crates/nodes/src/function/warnings.rs b/crates/nodes/src/function/warnings.rs new file mode 100644 index 00000000..ec7caaaa --- /dev/null +++ b/crates/nodes/src/function/warnings.rs @@ -0,0 +1,48 @@ +use materialcraft_core::FunctionGraph; + +pub fn warnings(graph: &FunctionGraph) -> Vec { + let mut messages = Vec::new(); + if graph.output.and_then(|output| graph.node(output)).is_none() { + messages.push("No output node defined".into()); + } + + for node in &graph.nodes { + let Some(definition) = super::definition(&node.op) else { continue }; + + for (index, input) in definition.inputs.iter().enumerate() { + if node.inputs.get(index).copied().flatten().is_none() { + messages.push(format!("{} (node {}): input {input} is not connected", definition.label, node.id)); + } + } + } + messages +} + +#[cfg(test)] +mod tests { + use super::*; + use materialcraft_core::Value; + + #[test] + fn warnings_include_disconnected_nodes_and_absent_input_slots() { + let mut graph = FunctionGraph::constant(Value::Float(0.5)); + let multiply = graph.add("mul", &[], None); + graph.nodes.last_mut().unwrap().inputs = vec![None]; + assert_eq!( + warnings(&graph), + vec![format!("Multiply (node {multiply}): input a is not connected"), format!("Multiply (node {multiply}): input b is not connected")] + ); + graph.nodes.last_mut().unwrap().inputs = vec![graph.output, graph.output]; + assert!(warnings(&graph).is_empty()); + } + + #[test] + fn empty_and_dangling_outputs_warn_without_preventing_editing() { + let mut graph = FunctionGraph::default(); + assert_eq!(warnings(&graph), vec!["No output node defined"]); + graph.output = Some(1); + assert_eq!(warnings(&graph), vec!["No output node defined"]); + graph.add_constant(Value::Float(0.5)); + assert!(warnings(&graph).is_empty()); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 8ec0d36d..d145aac5 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -296,9 +296,9 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p "inspectedNode": app.graph.inspected_node, "subgraph": match target { crate::graph::editor_target::EditorTarget::Function => app.function_editor.as_ref() - .map(|editor| json!({"kind": "function", "graph": app.session.graph, "node": editor.node, "target": editor.command_target(), "selection": editor.selection, "inspectedNode": editor.inspected_node})), + .map(|editor| json!({"kind": "function", "graph": app.session.graph, "node": editor.node, "target": editor.command_target(), "selection": editor.selection, "selectedWires": editor.selected_wires, "inspectedNode": editor.inspected_node})), crate::graph::editor_target::EditorTarget::Pattern => app.pattern_editor.as_ref() - .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "inspectedNode": editor.inspected_node})), + .map(|editor| json!({"kind": "pattern", "graph": editor.graph, "node": editor.node.0, "selection": editor.selection, "selectedWires": editor.selected_wires, "inspectedNode": editor.inspected_node})), crate::graph::editor_target::EditorTarget::Material => None, }, "annotationSelection": app.session.annotation_selection, diff --git a/crates/ui-egui/src/function/actions.rs b/crates/ui-egui/src/function/actions.rs index 0f55c9bd..a7767cd6 100644 --- a/crates/ui-egui/src/function/actions.rs +++ b/crates/ui-egui/src/function/actions.rs @@ -2,6 +2,9 @@ use super::{FunctionEditor, FunctionTarget}; use crate::MaterialCraftApp; pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, command: &str) -> Option { + if let Some(enabled) = crate::graph::wire_actions::enabled(command, editor.selected_wires.len()) { + return Some(enabled && editor.current(app).is_some()); + } let standalone = matches!(editor.target, FunctionTarget::Graph); if standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") { return None; @@ -35,8 +38,18 @@ pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut FunctionEdi return true; } + if command.starts_with("graph.wire.") || (command == "edit.delete" && !editor.selected_wires.is_empty()) { + let command = if command == "edit.delete" { "graph.wire.delete" } else { command }; + let target = editor.command_target().map(materialcraft_engine::SelectionTarget::Function); + crate::graph::wire_actions::edit(app, &mut editor.selected_wires, target, command); + return true; + } + let parameters = editor.selection_parameters(command); crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters); + if matches!(command, "edit.selectAll" | "edit.selectNone" | "edit.paste" | "edit.pasteWithoutLinks" | "edit.duplicate" | "edit.duplicateWithoutLinks") { + editor.selected_wires.clear(); + } true } diff --git a/crates/ui-egui/src/function/canvas.rs b/crates/ui-egui/src/function/canvas.rs index 1ee7ba7e..36978e0c 100644 --- a/crates/ui-egui/src/function/canvas.rs +++ b/crates/ui-egui/src/function/canvas.rs @@ -1,5 +1,5 @@ use super::{FunctionEditor, FunctionTarget}; -use crate::{MaterialCraftApp, graph::GraphCamera, i18n::tr}; +use crate::{MaterialCraftApp, graph::GraphCamera}; use egui::Ui; use materialcraft_engine::FunctionEdit; use serde_json::json; @@ -27,18 +27,13 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui editor.menu_at = frame.camera.to_graph(pointer); } response.context_menu(|ui| { - super::context_menu::show(app, editor, ui); - ui.separator(); - if ui.button(format!("{} {}", egui_phosphor::regular::STAR, tr("Set as output node"))).clicked() { - editor.edit(app, FunctionEdit::Output { id: *id }, false); - ui.close(); - } + super::context_menu::show(app, editor, ui, Some(*id)); }); } let on_annotation = ui .input(|input| input.pointer.hover_pos()) .is_some_and(|pointer| frame.frames.iter().any(|frame| frame.contains(pointer)) || frame.comments.iter().any(|(_, rect)| rect.contains(pointer))); - super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry.rects, on_annotation); + super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry, on_annotation); frame.geometry.publish(&mut app.graph, frame.response.rect); if standalone { if editor.drag.is_none() { @@ -46,6 +41,7 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui crate::graph::annotation_input::handle(app, ui, &camera, &frame.frames, &frame.comments); if app.session.annotation_selection.is_some() { editor.selection.clear(); + editor.selected_wires.clear(); } } app.ui.graph_camera = crate::state::GraphCamera { pan: editor.pan.into(), zoom: editor.zoom }; diff --git a/crates/ui-egui/src/function/context_menu.rs b/crates/ui-egui/src/function/context_menu.rs index 8a49ded0..8e3f57de 100644 --- a/crates/ui-egui/src/function/context_menu.rs +++ b/crates/ui-egui/src/function/context_menu.rs @@ -4,12 +4,45 @@ use egui::Ui; use materialcraft_engine::FunctionEdit; use serde_json::json; -pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { +pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui, node: Option) { + ui.set_min_width(290.0); + if let Some(node) = node { + node_actions(app, editor, ui, node); + } else { + background_actions(app, editor, ui); + } + selection_actions(app, editor, ui); +} + +fn node_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui, node: u32) { + annotations(app, editor, ui); + if ui.button(tr("Copy info to clipboard")).clicked() { + if let Some(info) = app.run("graph.function.node.info", json!({"target": editor.command_target(), "id": node})) + && let Some(text) = info.get("text").and_then(serde_json::Value::as_str) + { + ui.ctx().copy_text(text.into()); + } + ui.close(); + } + ui.separator(); + let output = editor.current(app).is_some_and(|graph| graph.output == Some(node)); + if ui.add_enabled(editor.selection.len() == 1 && !output, egui::Button::new(tr("Set as output node"))).clicked() { + editor.edit(app, FunctionEdit::Output { id: node }, false); + ui.close(); + } + ui.separator(); + let label = format!("{} ({})", tr("Create graph from selection"), editor.selection.len()); + let command = "graph.createFromSelection"; + if edit_menu::button(ui, &label, command, super::actions::editor_enabled(app, editor, command).unwrap_or(false)) { + super::actions::invoke_editor(app, editor, command); + } +} + +fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { let Some(target) = editor.command_target() else { return }; let mut add = None; let standalone = matches!(editor.target, FunctionTarget::Graph); - ui.set_min_width(290.0); ui.menu_button(tr("Add node"), |ui| { let entries = target .available_operations(&app.session) @@ -17,17 +50,10 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: .map(|operation| (operation.id, operation.label, operation.category)); add = crate::graph::add_node_menu::show(ui, entries); }); - if standalone { - for (label, command, parameters) in [ - ("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), - ("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})), - ("Add Navigation pin", "graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), - ] { - if edit_menu::button(ui, label, command, true) { - app.run(command, parameters); - editor.selection.clear(); - } - } + annotations(app, editor, ui); + if edit_menu::button(ui, "Add Navigation pin", "graph.pin.add", standalone) { + app.run("graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})); + editor.selection.clear(); } if ui.button(tr("Add Dot node")).clicked() { add = Some("passthrough"); @@ -37,21 +63,57 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: if edit_menu::button(ui, "Save package", "file.save", menus::enabled(app, "file.save")) { menus::invoke(app, ui.ctx(), "file.save"); } - if let Some(command) = - edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or_else(|| menus::enabled(app, command))) - && !super::actions::invoke_editor(app, editor, command) - { - app.run(command, json!({})); + for (label, command) in [("Paste", "edit.paste"), ("Paste without link", "edit.pasteWithoutLinks"), ("Select all", "edit.selectAll")] { + selection_action(app, editor, ui, label, command); } - if standalone { - for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] { - if edit_menu::button(ui, label, command, menus::enabled(app, command)) { - crate::graph::actions::invoke(app, command); - editor.set_camera(app.ui.graph_camera); - } + for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] { + if edit_menu::button(ui, label, command, standalone && menus::enabled(app, command)) { + crate::graph::actions::invoke(app, command); + editor.set_camera(app.ui.graph_camera); } } + ui.separator(); if let Some(operation) = add { editor.edit(app, FunctionEdit::Add { operation: operation.into(), at: editor.menu_at.into(), snap: app.ui.prefs.snap_to_grid }, false); } } + +fn annotations(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { + let standalone = matches!(editor.target, FunctionTarget::Graph); + for (label, command, parameters) in [ + ("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})), + ("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})), + ] { + if edit_menu::button(ui, label, command, standalone) { + app.run(command, parameters); + editor.selection.clear(); + } + } +} + +fn selection_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) { + for (label, command) in [ + ("Copy selection", "edit.copy"), + ("Delete selection", "edit.delete"), + ("Delete and relink", "edit.deleteRelink"), + ("Duplicate selection", "edit.duplicate"), + ("Duplicate selection without link", "edit.duplicateWithoutLinks"), + ("Select upstream nodes", "graph.selectUpstream"), + ("Select downstream nodes", "graph.selectDownstream"), + ] { + selection_action(app, editor, ui, label, command); + } + if crate::graph::wire_actions::swap_button(ui, editor.selected_wires.len()) { + let target = editor.command_target().map(materialcraft_engine::SelectionTarget::Function); + crate::graph::wire_actions::edit(app, &mut editor.selected_wires, target, "graph.wire.swap"); + ui.close(); + } + selection_action(app, editor, ui, "Disable selection", "graph.node.disable"); +} + +fn selection_action(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui, label: &str, command: &str) { + let enabled = super::actions::editor_enabled(app, editor, command).unwrap_or_else(|| menus::enabled(app, command)); + if edit_menu::button(ui, label, command, enabled) && !super::actions::invoke_editor(app, editor, command) { + app.run(command, json!({})); + } +} diff --git a/crates/ui-egui/src/function/function_editor.rs b/crates/ui-egui/src/function/function_editor.rs index b6d8eeee..0e196bb4 100644 --- a/crates/ui-egui/src/function/function_editor.rs +++ b/crates/ui-egui/src/function/function_editor.rs @@ -10,6 +10,7 @@ pub struct FunctionEditor { pub node: Option, pub graph: usize, pub(crate) selection: Vec, + pub(crate) selected_wires: Vec, pub(crate) inspected_node: Option, pub target: FunctionTarget, pub(super) pan: Vec2, @@ -39,6 +40,7 @@ impl FunctionEditor { node, target, selection: Vec::new(), + selected_wires: Vec::new(), inspected_node: None, pan: vec2(-40.0, -40.0), zoom: 1.0, @@ -76,6 +78,7 @@ impl FunctionEditor { && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) { self.selection = vec![id]; + self.selected_wires.clear(); if self.target == FunctionTarget::Graph { app.session.selection = vec![NodeId(u64::from(id))]; app.session.annotation_selection = None; diff --git a/crates/ui-egui/src/function/geometry.rs b/crates/ui-egui/src/function/geometry.rs index 605c186f..7eec1520 100644 --- a/crates/ui-egui/src/function/geometry.rs +++ b/crates/ui-egui/src/function/geometry.rs @@ -3,10 +3,6 @@ use crate::{MaterialCraftApp, graph::node_card}; use egui::{Color32, Pos2, Rect, vec2}; use materialcraft_engine::core::FunctionNode; -pub(super) fn arity(op: &str) -> usize { - materialcraft_engine::nodes::function::definition(op).map_or(0, |o| o.inputs.len()) -} - pub(super) fn category_color(category: &str) -> Color32 { match category { "Constant" => Color32::from_rgb(0x5c, 0x62, 0x6e), @@ -19,17 +15,16 @@ pub(super) fn category_color(category: &str) -> Color32 { } } -pub(super) fn visible_inputs(node: &FunctionNode) -> usize { - let count = arity(&node.op); - crate::graph::input_visibility::count((0..count).map(|index| node.inputs.get(index).is_some_and(Option::is_some)), 1) +fn input_count(node: &FunctionNode) -> usize { + materialcraft_engine::nodes::function::definition(&node.op).map_or(0, |definition| definition.inputs.len()) } pub(super) fn node_rect(node: &FunctionNode, previews: bool) -> Rect { - node_card::bounds(node.pos, visible_inputs(node), 1, previews, node.op == "passthrough") + node_card::bounds(node.pos, input_count(node), 1, previews, node.op == "passthrough") } pub(super) fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 { - node_card::port(bounds, index, visible_inputs(node), false, node.op == "passthrough") + node_card::port(bounds, index, input_count(node), false, node.op == "passthrough") } pub(super) fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 { diff --git a/crates/ui-egui/src/function/input.rs b/crates/ui-egui/src/function/input.rs index 0eb41449..fbf647ee 100644 --- a/crates/ui-egui/src/function/input.rs +++ b/crates/ui-egui/src/function/input.rs @@ -1,8 +1,12 @@ use super::function_port::FunctionPort; use super::{FunctionDrag, FunctionEditor}; -use crate::{MaterialCraftApp, graph::GraphCamera, theme::Tokens}; -use egui::{Pos2, Rect, Stroke, Ui}; -use materialcraft_engine::{FunctionEdit, core::NodeId}; +use crate::{ + MaterialCraftApp, + graph::{GraphCamera, canvas_geometry::CanvasGeometry}, + theme::Tokens, +}; +use egui::{Pos2, Stroke, Ui}; +use materialcraft_engine::FunctionEdit; pub(super) fn handle( app: &mut MaterialCraftApp, @@ -10,7 +14,7 @@ pub(super) fn handle( ui: &mut Ui, response: &egui::Response, ports: &[FunctionPort], - rectangles: &[(NodeId, Rect)], + geometry: &CanvasGeometry, on_annotation: bool, ) { let canvas_bounds = response.rect; @@ -22,6 +26,18 @@ pub(super) fn handle( editor.drag = None; return; } + let on_wire = editor.drag.is_none() + && !on_annotation + && !ui.input(|input| input.modifiers.alt) + && crate::graph::wire_selection::handle(&mut editor.selected_wires, &mut editor.selection, ui, response, &geometry.wires); + if on_wire + && matches!(editor.target, super::FunctionTarget::Graph) + && app.session.annotation_selection.is_some() + && (ui.input(|input| input.pointer.primary_pressed()) || response.secondary_clicked()) + { + app.run("graph.annotation.select", serde_json::json!({})); + } + // Gestures: wires from output dots, panning let near = |pointer: Pos2| crate::graph::port_hit::nearest_by(ports, pointer, |port| (port.position, port.radius)).map(|port| (port.node, port.slot)); if editor.drag.is_none() && GraphCamera::pan_started(ui, canvas_bounds) { @@ -42,11 +58,13 @@ pub(super) fn handle( && ui.input(|input| input.pointer.primary_pressed()) && let Some(start) = pointer && !on_annotation + && !on_wire { if matches!(editor.target, super::FunctionTarget::Graph) && app.session.annotation_selection.is_some() { app.run("graph.annotation.select", serde_json::json!({})); } editor.drag = Some(FunctionDrag::Box { start }); + crate::graph::node_selection::select(&mut editor.selected_wires, None, ui.input(|input| input.modifiers)); } let delta = ui.input(|input| input.pointer.delta()); @@ -83,7 +101,7 @@ pub(super) fn handle( } Some(FunctionDrag::Box { start }) => { if let Some(pointer) = pointer { - let nodes = rectangles.iter().map(|(id, bounds)| (id.0 as u32, *bounds)); + let nodes = geometry.rects.iter().map(|(id, bounds)| (id.0 as u32, *bounds)); crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, ui.input(|input| input.modifiers)); } } @@ -99,8 +117,9 @@ pub(super) fn handle( } } - if response.clicked() && !ui.input(|input| input.modifiers.alt) { + if response.clicked() && !on_wire && !ui.input(|input| input.modifiers.alt) { crate::graph::node_selection::select(&mut editor.selection, None, ui.input(|input| input.modifiers)); + crate::graph::node_selection::select(&mut editor.selected_wires, None, ui.input(|input| input.modifiers)); } let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom }; @@ -120,6 +139,6 @@ pub(super) fn handle( egui::Popup::open_id(ui.ctx(), response.id.with("menu")); } response.context_menu(|ui| { - super::context_menu::show(app, editor, ui); + super::context_menu::show(app, editor, ui, None); }); } diff --git a/crates/ui-egui/src/function/mod.rs b/crates/ui-egui/src/function/mod.rs index 136b0db8..b7b5c4e5 100644 --- a/crates/ui-egui/src/function/mod.rs +++ b/crates/ui-egui/src/function/mod.rs @@ -16,8 +16,10 @@ pub(crate) use panel::show_graph; mod actions; mod geometry; mod input; +mod node_canvas; mod panel; mod function_canvas; mod function_port; mod render; +mod warning_banner; diff --git a/crates/ui-egui/src/function/node_canvas.rs b/crates/ui-egui/src/function/node_canvas.rs new file mode 100644 index 00000000..2c60e2f5 --- /dev/null +++ b/crates/ui-egui/src/function/node_canvas.rs @@ -0,0 +1,48 @@ +use super::geometry::category_color; +use crate::{graph::node_card, theme::Tokens}; +use egui::{Align2, Color32, FontId, Painter, Rect, Stroke}; +use materialcraft_engine::{core::FunctionNode, nodes::function::FunctionDefinition}; + +const OUTPUT_COLOR: Color32 = Color32::from_rgb(255, 163, 26); + +pub(super) fn paint( + painter: &Painter, + bounds: Rect, + zoom: f32, + node: &FunctionNode, + definition: Option<&FunctionDefinition>, + selected: bool, + output: bool, + tokens: &Tokens, +) { + let dot = node.op == "passthrough"; + let outline = if selected { + tokens.accent + } else if dot { + Color32::from_gray(0xb4) + } else { + Color32::from_gray(0x10) + }; + + if dot { + node_card::paint_dot(painter, bounds, outline); + if output { + painter.circle_filled(bounds.center(), (bounds.width() * 0.5 - 1.5).max(0.0), OUTPUT_COLOR); + } + return; + } + + let label = definition.map_or("?", |definition| definition.label); + let category = definition.map_or("", |definition| definition.category); + node_card::paint(painter, bounds, zoom, label, category_color(category)); + let body = node_card::body(bounds, zoom); + if output { + painter.rect_filled(body, 0.0, OUTPUT_COLOR); + } + node_card::outline(painter, bounds, zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); + + if node.value.is_none() { + let text_color = if output { Color32::from_gray(0x20) } else { tokens.text_dim }; + painter.text(body.center(), Align2::CENTER_CENTER, egui_phosphor::regular::CODE, FontId::proportional(30.0 * zoom), text_color); + } +} diff --git a/crates/ui-egui/src/function/panel.rs b/crates/ui-egui/src/function/panel.rs index a4334b1c..7541ae26 100644 --- a/crates/ui-egui/src/function/panel.rs +++ b/crates/ui-egui/src/function/panel.rs @@ -8,6 +8,9 @@ pub(crate) fn show_graph(app: &mut MaterialCraftApp, ui: &mut Ui) { if editor.target == FunctionTarget::Graph { editor.selection = app.session.selection.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(); } + if let Some(graph) = editor.current(app) { + super::warning_banner::show(ui, graph); + } canvas(app, &mut editor, ui); app.function_editor = Some(editor); } diff --git a/crates/ui-egui/src/function/render.rs b/crates/ui-egui/src/function/render.rs index 60a320bc..675d8f18 100644 --- a/crates/ui-egui/src/function/render.rs +++ b/crates/ui-egui/src/function/render.rs @@ -1,10 +1,9 @@ -use super::geometry::{category_color, in_port, node_rect, out_port, preview_rect, visible_inputs}; +use super::geometry::{in_port, node_rect, out_port, preview_rect}; use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label}; use super::{function_canvas::FunctionCanvas, function_port::FunctionPort}; use crate::graph::canvas_geometry::CanvasGeometry; use crate::{MaterialCraftApp, graph::node_card, theme::Tokens}; -use egui::{Align2, Color32, FontId, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; -use egui_phosphor::regular as icon; +use egui::{Align2, Color32, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2}; use std::collections::{BTreeMap, BTreeSet}; pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option { @@ -14,6 +13,13 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu let layouts: BTreeMap<_, _> = graph.nodes.iter().map(|node| (node.id, (node, preview_rect(app, editor, node, snap, selected.contains(&node.id))))).collect(); editor.selection.retain(|id| layouts.contains_key(id)); + editor.selected_wires.retain(|(id, port)| { + u32::try_from(id.0) + .ok() + .and_then(|id| layouts.get(&id)) + .and_then(|(node, _)| port.parse::().ok().and_then(|slot| node.inputs.get(slot))) + .is_some_and(Option::is_some) + }); editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node); let standalone = matches!(editor.target, FunctionTarget::Graph); let tokens = Tokens::get(ui.ctx()); @@ -67,18 +73,17 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu let destination = camera.to_screen(in_port(node, *bounds, input_index)); let points = crate::graph::wire_geometry::bezier_points(source_position, destination); geometry.wires.push(((materialcraft_engine::core::NodeId(u64::from(node.id)), input_index.to_string()), points)); + let selected = editor.selected_wires.contains(&(materialcraft_engine::core::NodeId(u64::from(node.id)), input_index.to_string())); painter.add(egui::epaint::CubicBezierShape::from_points_stroke( points, false, Color32::TRANSPARENT, - Stroke::new(2.0, Color32::from_gray(0xb4)), + crate::graph::wire_selection::stroke(selected, 2.0, Color32::from_gray(0xb4), tokens.accent), )); } } } - // Nodes - let font = FontId::proportional((11.0 * editor.zoom).min(16.0)); let mut ports = Vec::new(); for node in &graph.nodes { let id = node.id; @@ -92,35 +97,12 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu let label = definition.map_or("?", |definition| definition.label); let dot = node.op == "passthrough"; let show_labels = crate::graph::port_label::visible(ui, screen_rect); - let is_output = graph.output == Some(id); - let selected = selected.contains(&id); - let outline = if selected { - tokens.accent - } else if dot { - Color32::from_gray(0xb4) - } else { - Color32::from_gray(0x10) - }; - - if dot { - node_card::paint_dot(&painter, screen_rect, outline); - } else { - node_card::paint(&painter, screen_rect, editor.zoom, label, category_color(definition.map_or("", |definition| definition.category))); - node_card::outline(&painter, screen_rect, editor.zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline)); - let body = node_card::body(screen_rect, editor.zoom); - if node.value.is_none() { - painter.text(body.center(), Align2::CENTER_CENTER, icon::CODE, FontId::proportional(30.0 * editor.zoom), tokens.text_dim); - } - if is_output { - let header = node_card::header(screen_rect, editor.zoom); - painter.text(header.right_center() - vec2(4.0, 0.0), Align2::RIGHT_CENTER, icon::STAR, font.clone(), Color32::GOLD); - } - } + super::node_canvas::paint(&painter, screen_rect, editor.zoom, node, definition, selected.contains(&id), graph.output == Some(id), &tokens); let port_radius = (4.5 * editor.zoom).clamp(2.5, 7.0); let port_color = crate::graph::port_color(materialcraft_engine::nodes::PortKind::Value); if let Some(definition) = definition { - for (input_index, identifier) in definition.inputs.iter().take(visible_inputs(node)).enumerate() { + for (input_index, identifier) in definition.inputs.iter().enumerate() { let position = camera.to_screen(in_port(node, bounds, input_index)); painter.circle(position, port_radius, port_color, Stroke::new(1.0, Color32::from_gray(0x18))); if show_labels { @@ -179,8 +161,12 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed() && !input.modifiers.alt)) || body.secondary_clicked() { let modifiers = if body.secondary_clicked() { egui::Modifiers::NONE } else { ui.input(|input| input.modifiers) }; + let keep_wires = modifiers.ctrl || modifiers.command || modifiers.shift || (body.secondary_clicked() && editor.selection.contains(&id)); crate::graph::node_selection::select(&mut editor.selection, Some(id), modifiers); + if !keep_wires { + editor.selected_wires.clear(); + } if standalone && app.session.annotation_selection.is_some() { clear_annotation = true; } diff --git a/crates/ui-egui/src/function/warning_banner.rs b/crates/ui-egui/src/function/warning_banner.rs new file mode 100644 index 00000000..47744ed6 --- /dev/null +++ b/crates/ui-egui/src/function/warning_banner.rs @@ -0,0 +1,28 @@ +use crate::{i18n::tr, theme::Tokens}; +use egui::Ui; +use materialcraft_engine::core::FunctionGraph; + +pub(super) fn show(ui: &mut Ui, graph: &FunctionGraph) { + let messages = materialcraft_engine::nodes::function::warnings(graph); + if messages.is_empty() { + return; + } + + let tokens = Tokens::get(ui.ctx()); + egui::Frame::NONE.fill(tokens.panel).inner_margin(egui::Margin::symmetric(8, 4)).show(ui, |ui| { + ui.set_width(ui.available_width()); + for message in messages.iter().take(3) { + ui.colored_label(tokens.warning, format!("{} {message}", egui_phosphor::regular::WARNING)) + .on_hover_text(tr("Connect the missing inputs and right-click a node to set it as the output")); + } + if messages.len() > 3 { + ui.collapsing(format!("{} ({})", tr("More warnings"), messages.len() - 3), |ui| { + egui::ScrollArea::vertical().max_height(120.0).show(ui, |ui| { + for message in messages.iter().skip(3) { + ui.colored_label(tokens.warning, message); + } + }); + }); + } + }); +} diff --git a/crates/ui-egui/src/graph/canvas.rs b/crates/ui-egui/src/graph/canvas.rs index cf2788ee..03ff3fb9 100644 --- a/crates/ui-egui/src/graph/canvas.rs +++ b/crates/ui-egui/src/graph/canvas.rs @@ -75,10 +75,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let mut layouts: Vec = Vec::with_capacity(graph.nodes.len()); for node in &graph.nodes { - let (mut ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); - let visible = - super::input_visibility::count(ins.iter().map(|port| index.input_of(node.id, &port.id).is_some()), if node.def == "fx_map" { 2 } else { 1 }); - ins.truncate(visible); + let (ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied()); let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails); if selection.contains(&node.id) && node_delta.length() > 0.5 { let position = materialcraft_engine::graph_grid::translate(node.pos, node_delta.into(), app.ui.prefs.snap_to_grid); @@ -164,13 +161,15 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) { let picked = app.graph.selected_wires.contains(w); let hovered = wire_hover.as_ref() == Some(w); let base = (2.0 * camera.zoom).clamp(1.0, 3.0); - let stroke = if picked { - Stroke::new(base + 2.0, theme.accent) - } else if hovered { - Stroke::new(base + 1.0, Color32::WHITE) + let width = if hovered && !picked { base + 1.0 } else { base }; + let color = if hovered { + Color32::WHITE + } else if hot { + theme.accent } else { - Stroke::new(base, if hot { theme.accent } else { Color32::from_gray(0xb4) }) + Color32::from_gray(0xb4) }; + let stroke = super::wire_selection::stroke(picked, width, color, theme.accent); painter.add(egui::epaint::CubicBezierShape::from_points_stroke(*ctrl, false, Color32::TRANSPARENT, stroke)); } diff --git a/crates/ui-egui/src/graph/context_menu.rs b/crates/ui-egui/src/graph/context_menu.rs index 194d0404..124f4603 100644 --- a/crates/ui-egui/src/graph/context_menu.rs +++ b/crates/ui-egui/src/graph/context_menu.rs @@ -47,6 +47,10 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, at: Pos2, node: Opti let parameters = if matches!(command, "edit.paste" | "edit.pasteWithoutLinks") { json!({"at": [at.x, at.y]}) } else { Value::Null }; app.run(command, parameters); } + if super::wire_actions::swap_button(ui, app.graph.selected_wires.len()) { + super::wire_actions::swap_selected_wires(app); + ui.close(); + } action(app, ui, "Previous pin", "ui.graph.previousPin", Value::Null); action(app, ui, "Next pin", "ui.graph.nextPin", Value::Null); } diff --git a/crates/ui-egui/src/graph/input.rs b/crates/ui-egui/src/graph/input.rs index 9092987e..dd00f45d 100644 --- a/crates/ui-egui/src/graph/input.rs +++ b/crates/ui-egui/src/graph/input.rs @@ -43,9 +43,8 @@ pub(super) fn handle( let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p)); let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card); - // Any press other than on a wire drops the wire selection if wire.is_none() { - app.graph.selected_wires.clear(); + super::node_selection::select(&mut app.graph.selected_wires, None, mods); } if let Some(w) = wire { app.graph.drag = Some(GraphDrag::WirePress { wire: w.clone(), start: p }); @@ -101,18 +100,7 @@ pub(super) fn handle( match drag { GraphDrag::Pan(_) => {} GraphDrag::WirePress { wire, .. } => { - app.session.selection.clear(); - let sel = &mut app.graph.selected_wires; - if mods.ctrl && sel.contains(&wire) { - // Ctrl+click toggles a wire out of the selection - sel.retain(|w| *w != wire); - } else if mods.ctrl || mods.shift { - if !sel.contains(&wire) { - sel.push(wire); - } - } else { - *sel = vec![wire]; - } + super::wire_selection::select(&mut app.graph.selected_wires, &mut app.session.selection, wire, mods, false); } GraphDrag::Nodes { delta } => { if delta.length() > 0.5 { @@ -205,12 +193,8 @@ pub(super) fn handle( app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id})); } app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node); - // Right-clicking a selected wire keeps the selection (to swap or delete them all) - if let Some(w) = &app.graph.menu_wire - && !app.graph.selected_wires.contains(w) - { - app.session.selection.clear(); - app.graph.selected_wires = vec![w.clone()]; + if let Some(wire) = app.graph.menu_wire.clone() { + super::wire_selection::select(&mut app.graph.selected_wires, &mut app.session.selection, wire, egui::Modifiers::NONE, true); } } let at = app.graph.menu_at; diff --git a/crates/ui-egui/src/graph/input_visibility.rs b/crates/ui-egui/src/graph/input_visibility.rs deleted file mode 100644 index d45c1af4..00000000 --- a/crates/ui-egui/src/graph/input_visibility.rs +++ /dev/null @@ -1,11 +0,0 @@ -pub(crate) fn count(connections: impl IntoIterator, minimum: usize) -> usize { - let mut visible = minimum; - let mut total = 0; - for (index, connected) in connections.into_iter().enumerate() { - total = index + 1; - if connected { - visible = index + 2; - } - } - visible.min(total) -} diff --git a/crates/ui-egui/src/graph/interaction_tests.rs b/crates/ui-egui/src/graph/interaction_tests.rs index 0eca8e42..ff27ebdf 100644 --- a/crates/ui-egui/src/graph/interaction_tests.rs +++ b/crates/ui-egui/src/graph/interaction_tests.rs @@ -316,16 +316,16 @@ fn pin_labels_follow_node_hover_while_pins_stay_visible() { let multiply = function.add("mul", &[], None); frames.app.run("graph.function.set", json!({"function": function})); frames.run(vec![Event::PointerGone], Modifiers::NONE); - let labels = ["A", "Output"]; + let labels = ["A", "B", "Output"]; assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); - assert_eq!(frames.app.graph.ports.len(), 2); + assert_eq!(frames.app.graph.ports.len(), 3); let position = frames.center(NodeId(u64::from(multiply))); frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE); assert!(labels.iter().all(|label| frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); frames.run(vec![Event::PointerGone], Modifiers::NONE); assert!(labels.iter().all(|label| !frames.canvas_text.iter().any(|text| text == label)), "{:?}", frames.canvas_text); - assert_eq!(frames.app.graph.ports.len(), 2); + assert_eq!(frames.app.graph.ports.len(), 3); } #[test] @@ -355,7 +355,7 @@ fn function_dots_wire_move_and_save_with_regular_card_geometry() { assert_eq!(dot_ports.len(), 2); assert!((dot_ports[0].pos.y - dot_ports[1].pos.y).abs() < 0.01); assert!(dot_ports[0].pos.x < dot_ports[1].pos.x); - assert!(!frames.app.graph.ports.iter().any(|port| port.node.0 == u64::from(multiply) && port.port == "1")); + assert!(frames.app.graph.ports.iter().any(|port| port.node.0 == u64::from(multiply) && port.port == "1")); for (from, to, input) in [(source, dot, "0"), (dot, multiply, "0"), (dot, multiply, "1")] { let start = frames.app.graph.ports.iter().find(|port| port.node.0 == u64::from(from) && port.output).unwrap().pos; @@ -386,7 +386,7 @@ fn function_dots_wire_move_and_save_with_regular_card_geometry() { } #[test] -fn regular_inputs_expand_on_connection_and_keep_saved_later_connections_visible() { +fn fixed_material_inputs_remain_visible_and_stationary_when_connected() { let mut frames = Frames::new(new_session()); let source = frames.app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0]})).unwrap()["id"].as_u64().unwrap(); let target = frames.app.run("graph.node.add", json!({"def": "blend", "at": [320, 0]})).unwrap()["id"].as_u64().unwrap(); @@ -395,10 +395,12 @@ fn regular_inputs_expand_on_connection_and_keep_saved_later_connections_visible( let visible = |frames: &Frames| frames.app.graph.ports.iter().filter(|port| port.node.0 == target && !port.output).map(|port| port.port.clone()).collect::>(); let inputs = frames.app.session.input_ports(NodeId(target)); - assert_eq!(visible(&frames), inputs[..1]); + let positions: Vec<_> = frames.app.graph.ports.iter().filter(|port| port.node.0 == target).map(|port| port.pos).collect(); + assert_eq!(visible(&frames), inputs); for input in &inputs { frames.app.run("graph.connect", json!({"from": source, "to": target, "toPort": input})).unwrap(); frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(frames.app.graph.ports.iter().filter(|port| port.node.0 == target).map(|port| port.pos).collect::>(), positions); } assert_eq!(visible(&frames), inputs); frames.app.run("graph.disconnect", json!({"to": target, "toPort": inputs[0]})).unwrap(); @@ -408,7 +410,44 @@ fn regular_inputs_expand_on_connection_and_keep_saved_later_connections_visible( frames.app.run("graph.disconnect", json!({"to": target, "toPort": input})).unwrap(); } frames.run(Vec::new(), Modifiers::NONE); - assert_eq!(visible(&frames), inputs[..1]); + assert_eq!(visible(&frames), inputs); +} + +#[test] +fn processor_image_inputs_reveal_the_next_slot_and_keep_later_connections_visible() { + for definition in ["pixel_processor", "value_processor", "fx_map"] { + let mut frames = Frames::new(new_session()); + let source = frames.app.run("graph.node.add", json!({"def": "uniform", "at": [0, 0]})).unwrap()["id"].as_u64().unwrap(); + let target = frames.app.run("graph.node.add", json!({"def": definition, "at": [320, 0]})).unwrap()["id"].as_u64().unwrap(); + frames.app.ui.frame_all = true; + frames.run(Vec::new(), Modifiers::NONE); + let prefix = materialcraft_engine::nodes::image_input_prefix(definition).unwrap(); + let visible = |frames: &Frames| { + frames + .app + .graph + .ports + .iter() + .filter(|port| port.node.0 == target && !port.output && port.port.starts_with(prefix)) + .map(|port| port.port.clone()) + .collect::>() + }; + assert_eq!(visible(&frames), [format!("{prefix}0")], "{definition}"); + frames.app.run("graph.connect", json!({"from": source, "to": target, "toPort": format!("{prefix}0")})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(visible(&frames), [format!("{prefix}0"), format!("{prefix}1")], "{definition}"); + for slot in 1..=3 { + frames.app.run("graph.connect", json!({"from": source, "to": target, "toPort": format!("{prefix}{slot}")})).unwrap(); + } + for slot in 0..3 { + frames.app.run("graph.disconnect", json!({"to": target, "toPort": format!("{prefix}{slot}")})).unwrap(); + } + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(visible(&frames), (0..=4).map(|slot| format!("{prefix}{slot}")).collect::>(), "{definition}"); + frames.app.run("graph.disconnect", json!({"to": target, "toPort": format!("{prefix}3")})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(visible(&frames), [format!("{prefix}0")], "{definition}"); + } } #[test] @@ -562,3 +601,146 @@ fn dots_move_from_their_body_and_still_wire_from_just_outside_at_any_zoom() { assert_eq!(graph.connections.len(), 1); assert_eq!((graph.connections[0].from, graph.connections[0].to), (ids[0], ids[1])); } + +#[test] +fn pattern_links_use_the_shared_pair_shortcut_and_preserve_node_selection() { + use materialcraft_engine::core::{PatternGraph, PatternNodeKind, Value}; + + let mut session = new_session(); + let owner = NodeId(materialcraft_engine::execute(&mut session, "graph.node.add", &json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::with_root(PatternNodeKind::Switch); + let first = graph.add(PatternNodeKind::Quadrant).unwrap(); + let second = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].children = vec![Some(first), Some(second)]; + for (node, position) in graph.nodes.iter_mut().zip([[0.0, 0.0], [-200.0, 300.0], [200.0, 300.0]]) { + node.position = position; + } + materialcraft_engine::execute(&mut session, "graph.pattern.set", &json!({"id": owner.0, "pattern": graph})).unwrap(); + let original = session.pkg.clone(); + let mut frames = Frames::new(session); + frames.app.pattern_editor = Some(crate::pattern::PatternEditor::new(frames.app.session.graph, owner)); + frames.run(Vec::new(), Modifiers::NONE); + for (port, modifiers) in [("output0", Modifiers::NONE), ("output1", Modifiers::SHIFT)] { + let curve = frames.app.graph.wires.iter().find(|(wire, _)| wire.0 == NodeId(1) && wire.1 == port).unwrap().1; + frames.click(super::wire_geometry::bezier_at(&curve, 0.5), modifiers); + } + frames.click(frames.center(NodeId(1)), Modifiers::SHIFT); + assert_eq!(frames.app.pattern_editor.as_ref().unwrap().selected_wires.len(), 2); + assert_eq!(frames.app.pattern_editor.as_ref().unwrap().selection, vec![1]); + let key = |key| Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + frames.run(vec![key(egui::Key::X)], Modifiers::NONE); + let Value::PatternGraph(swapped) = &frames.app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!() }; + assert_eq!(swapped.nodes[0].children, vec![Some(second), Some(first)]); + assert_eq!(frames.app.pattern_editor.as_ref().unwrap().selection, vec![1]); + frames.run(vec![key(egui::Key::X)], Modifiers::NONE); + assert_eq!(frames.app.session.pkg, original); + frames.run(vec![key(egui::Key::Delete)], Modifiers::NONE); + let Value::PatternGraph(deleted) = &frames.app.session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!() }; + assert_eq!(deleted.nodes[0].children, vec![None, None]); + frames.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(frames.app.session.pkg, original); +} + +#[test] +fn fixed_function_inputs_remain_visible_and_stationary_when_connected() { + use materialcraft_engine::{FunctionGraphTarget, core::FunctionGraph}; + + for definition in ["function", "pixel_processor", "value_processor"] { + let mut session = new_session(); + let (target, owner) = if definition == "function" { + materialcraft_engine::execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + (FunctionGraphTarget::Graph, None) + } else { + let id = materialcraft_engine::execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap(); + (FunctionGraphTarget::Parameter { node: NodeId(id), parameter: "function".into() }, Some(NodeId(id))) + }; + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(materialcraft_engine::core::Value::Float(0.5)); + let greater = graph.add("gt", &[], None); + let interpolation = graph.add("lerp", &[], None); + for (node, position) in graph.nodes.iter_mut().zip([[0.0, 100.0], [350.0, 0.0], [350.0, 220.0]]) { + node.pos = position; + } + materialcraft_engine::execute(&mut session, "graph.function.set", &json!({"target": target, "function": graph})).unwrap(); + let mut frames = Frames::new(session); + if let Some(owner) = owner { + super::subgraph_navigation::open_function(&mut frames.app, owner, crate::function::FunctionTarget::Parameter("function".into())); + frames.run(Vec::new(), Modifiers::NONE); + } + let inputs = |frames: &Frames, id: u32| { + frames + .app + .graph + .ports + .iter() + .filter(|port| port.node == NodeId(u64::from(id)) && !port.output) + .map(|port| (port.label.clone(), port.pos)) + .collect::>() + }; + let greater_ports = inputs(&frames, greater); + let interpolation_ports = inputs(&frames, interpolation); + assert_eq!(greater_ports.iter().map(|(label, _)| label.as_str()).collect::>(), ["A", "B"], "{definition}"); + assert_eq!(interpolation_ports.iter().map(|(label, _)| label.as_str()).collect::>(), ["A", "B", "Factor"], "{definition}"); + for (id, slot) in [(greater, 1), (interpolation, 2)] { + let from = frames.app.graph.ports.iter().find(|port| port.node == NodeId(u64::from(source)) && port.output).unwrap().pos; + let to = inputs(&frames, id)[slot].1; + drag(&mut frames, from, to); + assert_eq!(target.current(&frames.app.session).unwrap().node(id).unwrap().inputs[slot], Some(source)); + assert_eq!(inputs(&frames, greater), greater_ports); + assert_eq!(inputs(&frames, interpolation), interpolation_ports); + } + frames.app.run("edit.undo", json!({})).unwrap(); + frames.run(Vec::new(), Modifiers::NONE); + assert_eq!(inputs(&frames, interpolation), interpolation_ports); + } +} + +#[test] +fn function_links_swap_and_delete_without_editing_the_parent_graph() { + use materialcraft_engine::{FunctionGraphTarget, core::FunctionGraph}; + + for definition in ["function", "pixel_processor", "value_processor"] { + let mut session = materialcraft_engine::new_session(); + let (target, owner) = if definition == "function" { + materialcraft_engine::execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap(); + (FunctionGraphTarget::Graph, None) + } else { + let id = materialcraft_engine::execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap(); + (FunctionGraphTarget::Parameter { node: NodeId(id), parameter: "function".into() }, Some(NodeId(id))) + }; + let mut graph = FunctionGraph::default(); + let a = graph.add_constant(materialcraft_engine::core::Value::Float(1.0)); + let b = graph.add_constant(materialcraft_engine::core::Value::Float(2.0)); + let subtract = graph.add("sub", &[a, b], None); + graph.output = Some(subtract); + for (node, position) in graph.nodes.iter_mut().zip([[0.0, -150.0], [0.0, 150.0], [450.0, 0.0]]) { + node.pos = position; + } + materialcraft_engine::execute(&mut session, "graph.function.set", &json!({"target": target, "function": graph})).unwrap(); + let mut frames = Frames::new(session); + if let Some(owner) = owner { + super::subgraph_navigation::open_function(&mut frames.app, owner, crate::function::FunctionTarget::Parameter("function".into())); + frames.run(Vec::new(), egui::Modifiers::NONE); + } + let original = frames.app.session.pkg.clone(); + frames.app.session.reset_history(); + for (input, modifiers) in [("0", egui::Modifiers::NONE), ("1", egui::Modifiers::SHIFT)] { + let curve = frames.app.graph.wires.iter().find(|(wire, _)| wire.0 == NodeId(u64::from(subtract)) && wire.1 == input).unwrap().1; + frames.click(super::wire_geometry::bezier_at(&curve, 0.5), modifiers); + } + let header = frames.app.graph.rects.iter().find(|(id, _)| *id == NodeId(u64::from(a))).unwrap().1.min + vec2(12.0, 12.0); + frames.click(header, egui::Modifiers::SHIFT); + assert_eq!(frames.app.function_editor.as_ref().unwrap().selection, vec![a]); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + frames.run(vec![key(egui::Key::X)], egui::Modifiers::NONE); + assert_eq!(target.current(&frames.app.session).unwrap().node(subtract).unwrap().inputs, vec![Some(b), Some(a)], "{definition}"); + assert_eq!(frames.app.function_editor.as_ref().unwrap().selection, vec![a]); + assert_eq!(frames.app.session.history().len(), 1); + frames.run(vec![key(egui::Key::X)], egui::Modifiers::NONE); + assert_eq!(frames.app.session.pkg, original); + frames.run(vec![key(egui::Key::Delete)], egui::Modifiers::NONE); + assert_eq!(target.current(&frames.app.session).unwrap().node(subtract).unwrap().inputs, vec![None, None]); + frames.app.run("edit.undo", json!({})).unwrap(); + assert_eq!(frames.app.session.pkg, original); + } +} diff --git a/crates/ui-egui/src/graph/mod.rs b/crates/ui-egui/src/graph/mod.rs index fe7a93c3..920f7a20 100644 --- a/crates/ui-egui/src/graph/mod.rs +++ b/crates/ui-egui/src/graph/mod.rs @@ -11,7 +11,6 @@ mod graph_camera; mod graph_drag; pub(crate) mod graph_parent; mod graph_view; -pub(crate) mod input_visibility; #[cfg(test)] mod interaction_tests; mod library_drag; @@ -44,8 +43,9 @@ mod node_style; mod search; pub(crate) mod selection_commands; pub(crate) mod toolbar; -mod wire_actions; +pub(crate) mod wire_actions; pub(crate) mod wire_geometry; +pub(crate) mod wire_selection; #[cfg(test)] mod review_tests; diff --git a/crates/ui-egui/src/graph/navigation.rs b/crates/ui-egui/src/graph/navigation.rs index 04d9f9e7..9bf06fb9 100644 --- a/crates/ui-egui/src/graph/navigation.rs +++ b/crates/ui-egui/src/graph/navigation.rs @@ -36,8 +36,7 @@ pub(super) fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool } let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n); - let visible = super::input_visibility::count(inputs.iter().map(|port| g.input_of(n.id, &port.id).is_some()), if n.def == "fx_map" { 2 } else { 1 }); - r = r.union(node_rect(n, visible, outputs.len(), thumbs)); + r = r.union(node_rect(n, inputs.len(), outputs.len(), thumbs)); } for f in &g.frames { if !only_selection { diff --git a/crates/ui-egui/src/graph/node_selection.rs b/crates/ui-egui/src/graph/node_selection.rs index eaacf56c..f3df7f64 100644 --- a/crates/ui-egui/src/graph/node_selection.rs +++ b/crates/ui-egui/src/graph/node_selection.rs @@ -1,6 +1,6 @@ use egui::Modifiers; -pub(crate) fn select(selection: &mut Vec, node: Option, modifiers: Modifiers) { +pub(crate) fn select(selection: &mut Vec, node: Option, modifiers: Modifiers) { let toggle = modifiers.ctrl || modifiers.command; let additive = toggle || modifiers.shift; let Some(node) = node else { diff --git a/crates/ui-egui/src/graph/toolbar.rs b/crates/ui-egui/src/graph/toolbar.rs index 086c66fb..c880127d 100644 --- a/crates/ui-egui/src/graph/toolbar.rs +++ b/crates/ui-egui/src/graph/toolbar.rs @@ -91,11 +91,7 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) { } } else { thumbnails(app, ui); - if function { - if app.function_editor.as_ref().and_then(|editor| editor.current(app)).is_some_and(|graph| graph.output.is_none()) { - ui.label(tr("Set a node as the output")); - } - } else { + if !function { parent_size(app, ui); } } diff --git a/crates/ui-egui/src/graph/wire_actions.rs b/crates/ui-egui/src/graph/wire_actions.rs index 74834581..b8abf468 100644 --- a/crates/ui-egui/src/graph/wire_actions.rs +++ b/crates/ui-egui/src/graph/wire_actions.rs @@ -4,29 +4,84 @@ use egui::{Pos2, Ui}; use egui_phosphor::regular as icon; use serde_json::json; -/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands -fn wires_json(wires: &[WireRef]) -> serde_json::Value { - json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::>()}) +pub(crate) fn edit(app: &mut MaterialCraftApp, wires: &mut Vec, target: Option, command: &str) -> bool { + if wires.is_empty() || (command == "graph.wire.swap" && wires.len() != 2) { + return false; + } + + let mut parameters = json!({"graph": app.session.graph, "wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::>()}); + match target { + Some(materialcraft_engine::SelectionTarget::Function(target)) => parameters["function"] = json!(target), + Some(materialcraft_engine::SelectionTarget::Pattern(owner)) => parameters["pattern"] = json!(owner.0), + None => {} + } + if app.run(command, parameters).is_some() && command == "graph.wire.delete" { + wires.clear(); + } + true +} + +fn invoke_selected(app: &mut MaterialCraftApp, command: &str) -> bool { + match super::editor_target::EditorTarget::resolve(app) { + super::editor_target::EditorTarget::Function => { + let Some(mut editor) = app.function_editor.take() else { return false }; + let target = editor.command_target().map(materialcraft_engine::SelectionTarget::Function); + let handled = edit(app, &mut editor.selected_wires, target, command); + app.function_editor = Some(editor); + handled + } + super::editor_target::EditorTarget::Pattern => { + let Some(mut editor) = app.pattern_editor.take() else { return false }; + let target = Some(materialcraft_engine::SelectionTarget::Pattern(editor.node)); + let handled = edit(app, &mut editor.selected_wires, target, command); + app.pattern_editor = Some(editor); + handled + } + super::editor_target::EditorTarget::Material => { + let mut wires = std::mem::take(&mut app.graph.selected_wires); + let handled = edit(app, &mut wires, None, command); + app.graph.selected_wires = wires; + handled + } + } } -/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none is selected pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool { - let wires = std::mem::take(&mut app.graph.selected_wires); - if wires.is_empty() { - return false; - } - app.run("graph.wire.delete", wires_json(&wires)); - true + invoke_selected(app, "graph.wire.delete") } -/// Reverse the sources of selected wires so pressing X again restores them pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool { - if app.graph.selected_wires.is_empty() { - return false; + invoke_selected(app, "graph.wire.swap") +} + +pub(crate) fn swap_button(ui: &mut Ui, selected_count: usize) -> bool { + selected_count == 2 && ui.add(egui::Button::new(tr("Swap links")).shortcut_text("X")).clicked() +} + +pub(crate) fn enabled(command: &str, selected_count: usize) -> Option { + match command { + "graph.wire.swap" => Some(selected_count == 2), + "graph.wire.delete" => Some(selected_count > 0), + "edit.delete" if selected_count > 0 => Some(true), + _ => None, + } +} + +pub(crate) fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { + let count = match super::editor_target::EditorTarget::resolve(app) { + super::editor_target::EditorTarget::Function => app.function_editor.as_ref().map_or(0, |editor| editor.selected_wires.len()), + super::editor_target::EditorTarget::Pattern => app.pattern_editor.as_ref().map_or(0, |editor| editor.selected_wires.len()), + super::editor_target::EditorTarget::Material => app.graph.selected_wires.len(), + }; + if count == 0 { + return; + } + + if ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | input.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { + delete_selected_wires(app); + } else if ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::X)) && count == 2 { + swap_selected_wires(app); } - let params = wires_json(&app.graph.selected_wires); - app.run("graph.wire.swap", params); - true } pub(super) fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) { @@ -36,7 +91,7 @@ pub(super) fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): Wir app.graph.selected_wires.clear(); ui.close(); } - if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() { + if swap_button(ui, n) { swap_selected_wires(app); ui.close(); } diff --git a/crates/ui-egui/src/graph/wire_geometry.rs b/crates/ui-egui/src/graph/wire_geometry.rs index 7bfb10a6..0eaca257 100644 --- a/crates/ui-egui/src/graph/wire_geometry.rs +++ b/crates/ui-egui/src/graph/wire_geometry.rs @@ -41,7 +41,7 @@ pub(super) fn bezier_distance(c: &[Pos2; 4], p: Pos2) -> f32 { } /// The wire nearest `p` within [`WIRE_HIT`] points -pub(super) fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { +pub(crate) fn wire_at(wires: &[(WireRef, [Pos2; 4])], p: Pos2) -> Option<&WireRef> { wires .iter() .filter(|(_, c)| Rect::from_points(c).expand(WIRE_HIT).contains(p)) diff --git a/crates/ui-egui/src/graph/wire_selection.rs b/crates/ui-egui/src/graph/wire_selection.rs new file mode 100644 index 00000000..216dc703 --- /dev/null +++ b/crates/ui-egui/src/graph/wire_selection.rs @@ -0,0 +1,25 @@ +use super::{WireRef, node_selection, wire_geometry}; +use egui::{Color32, Modifiers, Pos2, Response, Stroke, Ui}; + +pub(crate) fn select(wires: &mut Vec, nodes: &mut Vec, wire: WireRef, modifiers: Modifiers, secondary: bool) { + let keep_nodes = modifiers.ctrl || modifiers.command || modifiers.shift || (secondary && wires.contains(&wire)); + node_selection::select(wires, Some(wire), modifiers); + if !keep_nodes { + nodes.clear(); + } +} + +pub(crate) fn handle(wires: &mut Vec, nodes: &mut Vec, ui: &Ui, response: &Response, curves: &[(WireRef, [Pos2; 4])]) -> bool { + let wire = ui.input(|input| input.pointer.hover_pos()).and_then(|pointer| wire_geometry::wire_at(curves, pointer)); + let Some(wire) = wire.filter(|_| response.hovered()) else { return false }; + + if ui.input(|input| input.pointer.primary_pressed()) || response.secondary_clicked() { + let modifiers = if response.secondary_clicked() { Modifiers::NONE } else { ui.input(|input| input.modifiers) }; + select(wires, nodes, wire.clone(), modifiers, response.secondary_clicked()); + } + true +} + +pub(crate) fn stroke(selected: bool, width: f32, color: Color32, accent: Color32) -> Stroke { + if selected { Stroke::new(width + 1.0, accent) } else { Stroke::new(width, color) } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index bcbaa5f2..864bd0b4 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -278,14 +278,7 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) { return; } - // Selected wires handle deletion and swapping before nodes - if crate::graph::editor_target::EditorTarget::resolve(app) == crate::graph::editor_target::EditorTarget::Material && !app.graph.selected_wires.is_empty() { - if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) { - crate::graph::delete_selected_wires(app); - } else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) { - crate::graph::swap_selected_wires(app); - } - } + crate::graph::wire_actions::shortcuts(app, ctx); let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect(); for c in materialcraft_engine::command_specs() { diff --git a/crates/ui-egui/src/pattern/actions.rs b/crates/ui-egui/src/pattern/actions.rs index 65b1ea09..68853032 100644 --- a/crates/ui-egui/src/pattern/actions.rs +++ b/crates/ui-egui/src/pattern/actions.rs @@ -46,11 +46,24 @@ pub(super) fn invoke_editor(app: &mut MaterialCraftApp, editor: &mut PatternEdit if editor_enabled(app, editor, command) != Some(true) { return; } + if command.starts_with("graph.wire.") || (command == "edit.delete" && !editor.selected_wires.is_empty()) { + let command = if command == "edit.delete" { "graph.wire.delete" } else { command }; + let target = Some(materialcraft_engine::SelectionTarget::Pattern(editor.node)); + crate::graph::wire_actions::edit(app, &mut editor.selected_wires, target, command); + return; + } + let parameters = editor.selection_parameters(command); crate::graph::selection_commands::invoke(app, &mut editor.selection, command, parameters); + if matches!(command, "edit.selectAll" | "edit.selectNone" | "edit.paste" | "edit.pasteWithoutLinks" | "edit.duplicate" | "edit.duplicateWithoutLinks") { + editor.selected_wires.clear(); + } } pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &PatternEditor, command: &str) -> Option { + if let Some(enabled) = crate::graph::wire_actions::enabled(command, editor.selected_wires.len()) { + return Some(enabled && editor.current(app).is_some()); + } materialcraft_engine::selection_commands::enabled_for( &app.session, &materialcraft_engine::SelectionTarget::Pattern(editor.node), diff --git a/crates/ui-egui/src/pattern/canvas.rs b/crates/ui-egui/src/pattern/canvas.rs index 296eb3a4..62e580d1 100644 --- a/crates/ui-egui/src/pattern/canvas.rs +++ b/crates/ui-egui/src/pattern/canvas.rs @@ -73,6 +73,7 @@ fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Opt editor.pan = camera.pan; editor.zoom = camera.zoom; crate::graph::grid::paint(&painter, &camera, bounds); + let tokens = Tokens::get(ui.ctx()); let rectangles: BTreeMap<_, _> = graph .nodes .iter() @@ -81,19 +82,27 @@ fn paint(app: &MaterialCraftApp, editor: &mut PatternEditor, ui: &mut Ui) -> Opt (node.id, Rect::from_min_max(camera.to_screen(bounds.min), camera.to_screen(bounds.max))) }) .collect(); + editor.selected_wires.retain(|(id, port)| { + graph + .nodes + .iter() + .find(|node| u64::from(node.id) == id.0) + .is_some_and(|node| node.children.iter().enumerate().any(|(slot, child)| child.is_some() && node.kind.child_port(slot) == Some(port.as_str()))) + }); for node in &graph.nodes { let Some(bounds) = rectangles.get(&node.id) else { continue }; for (slot, child) in node.children.iter().enumerate() { if let Some(child_bounds) = child.and_then(|id| rectangles.get(&id)) { let points = geometry::wire(geometry::port(*bounds, Some(slot), node.children.len()), child_bounds.center_top()); - painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, Stroke::new(2.0, PORT_COLOR))); - geometry.wires.push(((NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()), points)); + let wire = (NodeId(u64::from(node.id)), node.kind.child_port(slot).unwrap_or_default().to_string()); + let stroke = crate::graph::wire_selection::stroke(editor.selected_wires.contains(&wire), 2.0, PORT_COLOR, tokens.accent); + painter.add(egui::epaint::CubicBezierShape::from_points_stroke(points, false, Color32::TRANSPARENT, stroke)); + geometry.wires.push((wire, points)); } } } - let tokens = Tokens::get(ui.ctx()); for node in &graph.nodes { let Some(bounds) = rectangles.get(&node.id).copied() else { continue }; diff --git a/crates/ui-egui/src/pattern/context_menu.rs b/crates/ui-egui/src/pattern/context_menu.rs index b0a4b54b..4b29360a 100644 --- a/crates/ui-egui/src/pattern/context_menu.rs +++ b/crates/ui-egui/src/pattern/context_menu.rs @@ -31,6 +31,11 @@ pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: & if let Some(command) = edit_menu::selection(ui, |command| super::actions::editor_enabled(app, editor, command).unwrap_or(false)) { super::actions::invoke_editor(app, editor, command); } + if crate::graph::wire_actions::swap_button(ui, editor.selected_wires.len()) { + let target = Some(materialcraft_engine::SelectionTarget::Pattern(editor.node)); + crate::graph::wire_actions::edit(app, &mut editor.selected_wires, target, "graph.wire.swap"); + ui.close(); + } ui.separator(); if ui.button(tr("Frame all")).clicked() { editor.framed = false; diff --git a/crates/ui-egui/src/pattern/input.rs b/crates/ui-egui/src/pattern/input.rs index 89a0ed0e..2a570c14 100644 --- a/crates/ui-egui/src/pattern/input.rs +++ b/crates/ui-egui/src/pattern/input.rs @@ -21,12 +21,19 @@ pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: let node = app.graph.rects.iter().rev().find(|(_, bounds)| bounds.contains(pointer)).map(|(id, _)| id.0 as u32); let modifiers = ui.input(|input| input.modifiers); + let on_wire = editor.drag.is_none() + && port.is_none() + && node.is_none() + && !modifiers.alt + && crate::graph::wire_selection::handle(&mut editor.selected_wires, &mut editor.selection, ui, response, &app.graph.wires); + if editor.drag.is_none() && GraphCamera::pan_started(ui, response.rect) && !(port.is_some() && modifiers.alt && ui.input(|input| input.pointer.primary_pressed())) { editor.drag = Some(PatternDrag::Pan(crate::graph::gesture::pan_button(ui))); - } else if editor.drag.is_none() && response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { + } else if editor.drag.is_none() && !on_wire && response.hovered() && ui.input(|input| input.pointer.button_pressed(PointerButton::Primary)) { + crate::graph::node_selection::select(&mut editor.selected_wires, None, modifiers); if let Some((id, slot)) = port { if modifiers.alt { editor.edit(app, PatternEdit::Disconnect { node: id, slot }, false); @@ -86,6 +93,7 @@ pub(super) fn handle(app: &mut MaterialCraftApp, editor: &mut PatternEditor, ui: && !editor.selection.contains(&id) { crate::graph::node_selection::select(&mut editor.selection, Some(id), egui::Modifiers::NONE); + editor.selected_wires.clear(); } } if response.hovered() && !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space)) { diff --git a/crates/ui-egui/src/pattern/pattern_editor.rs b/crates/ui-egui/src/pattern/pattern_editor.rs index 772ccfe1..ccb1b6cb 100644 --- a/crates/ui-egui/src/pattern/pattern_editor.rs +++ b/crates/ui-egui/src/pattern/pattern_editor.rs @@ -9,6 +9,7 @@ pub struct PatternEditor { pub node: NodeId, pub graph: usize, pub(crate) selection: Vec, + pub(crate) selected_wires: Vec, pub(crate) inspected_node: Option, pub(super) pan: Vec2, pub(super) zoom: f32, @@ -19,7 +20,18 @@ pub struct PatternEditor { impl PatternEditor { pub fn new(graph: usize, node: NodeId) -> Self { - Self { node, graph, selection: Vec::new(), inspected_node: None, pan: Vec2::ZERO, zoom: 1.0, framed: false, drag: None, menu_at: Pos2::ZERO } + Self { + node, + graph, + selection: Vec::new(), + selected_wires: Vec::new(), + inspected_node: None, + pan: Vec2::ZERO, + zoom: 1.0, + framed: false, + drag: None, + menu_at: Pos2::ZERO, + } } pub(crate) fn current<'a>(&self, app: &'a MaterialCraftApp) -> Option<&'a PatternGraph> { @@ -57,6 +69,7 @@ impl PatternEditor { && let Some(id) = result.get("id").and_then(serde_json::Value::as_u64).and_then(|id| u32::try_from(id).ok()) { self.selection = vec![id]; + self.selected_wires.clear(); } } } diff --git a/crates/ui-egui/tests/snapshot.rs b/crates/ui-egui/tests/snapshot.rs index b1327e9f..2bdc465c 100644 --- a/crates/ui-egui/tests/snapshot.rs +++ b/crates/ui-egui/tests/snapshot.rs @@ -32,6 +32,364 @@ fn save(h: &mut Harness<'static, MaterialCraftApp>, dir: &std::path::Path, name: println!("wrote {}", dir.join(format!("{name}.png")).display()); } +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn function_output_highlight_follows_context_menu_and_undo() { + use materialcraft_engine::core::{FunctionGraph, Value}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.dock.close(materialcraft_ui_egui::docking::Panel::Library); + app.run("file.new", json!({"kind": "function", "name": "Output selection"})).unwrap(); + let mut function = FunctionGraph::default(); + let input = function.add_constant(Value::Float(0.5)); + let add = function.add("add", &[input, input], None); + let multiply = function.add("mul", &[input, input], None); + let dot = function.add("passthrough", &[multiply], None); + for (node, position) in function.nodes.iter_mut().zip([[0.0, 64.0], [256.0, 0.0], [256.0, 224.0], [480.0, 272.0]]) { + node.pos = position; + } + function.output = Some(add); + app.run("graph.function.set", json!({"function": function})).unwrap(); + app.session.reset_history(); + + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 6); + 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 query = |label| By::new().role(egui::accesskit::Role::Button).label(label); + let assert_highlight = |harness: &mut Harness<'static, MaterialCraftApp>, label, output| { + let bounds = harness.get(query(label)).rect(); + let sample = if label == "Dot" { bounds.center() } else { bounds.min + bounds.size() * egui::vec2(0.2, 0.4) }; + let image = harness.render().unwrap(); + let pixel = image.get_pixel(sample.x as u32, sample.y as u32).0; + assert_eq!(pixel == [255, 163, 26, 255], output, "{label}: {pixel:?}"); + }; + + harness.get(query("Multiply")).click_secondary(); + settle(&mut harness, 3); + let labels = [ + "Add Comment", + "Add Frame", + "Copy info to clipboard", + "Set as output node", + "Create graph from selection (1)", + "Copy selection Ctrl+C", + "Delete selection Delete", + "Delete and relink Backspace", + "Duplicate selection Ctrl+D", + "Duplicate selection without link Ctrl+Shift+D", + "Select upstream nodes", + "Select downstream nodes", + "Disable selection Shift+D", + ]; + let rows: Vec<_> = labels.iter().map(|label| harness.get(query(label)).rect().center().y).collect(); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1])); + let menu_column = harness.get(query("Copy info to clipboard")).rect(); + for label in ["Add node", "Add Dot node", "Add Navigation pin", "Save package", "Paste", "Cut selection", "Select all", "Previous pin", "Next pin"] { + assert!( + harness.query_all(By::new().role(egui::accesskit::Role::Button).label_contains(label)).all(|button| { + let center = button.rect().center(); + center.x < menu_column.left() || center.x > menu_column.right() || center.y < rows[0] || center.y > *rows.last().unwrap() + }), + "unexpected node action {label}" + ); + } + save(&mut harness, &directory, "function-output-context-menu"); + assert_highlight(&mut harness, "Add", true); + harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("Set as output node")).click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().output, Some(multiply)); + assert_eq!(harness.state().session.history().len(), 1); + + harness.get(query("Add")).click(); + settle(&mut harness, 3); + assert_highlight(&mut harness, "Add", false); + assert_highlight(&mut harness, "Multiply", true); + save(&mut harness, &directory, "function-output-separate-selection"); + + harness.state_mut().run("edit.undo", json!({})).unwrap(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().output, Some(add)); + assert_highlight(&mut harness, "Add", true); + assert_highlight(&mut harness, "Multiply", false); + harness.state_mut().run("edit.redo", json!({})).unwrap(); + settle(&mut harness, 3); + assert_highlight(&mut harness, "Multiply", true); + + harness.get(query("Dot")).click_secondary(); + settle(&mut harness, 3); + harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("Set as output node")).click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().output, Some(dot)); + assert_highlight(&mut harness, "Dot", true); + assert_highlight(&mut harness, "Multiply", false); + save(&mut harness, &directory, "function-output-dot"); + + harness.get(query("Dot")).click_secondary(); + settle(&mut harness, 3); + assert!(harness.get(query("Set as output node")).accesskit_node().is_disabled()); + let history = harness.state().session.history(); + harness.get(query("Copy info to clipboard")).click(); + let mut copied = None; + for _ in 0..3 { + harness.step(); + for command in &harness.output().platform_output.commands { + if let egui::OutputCommand::CopyText(text) = command { + copied = Some(serde_json::from_str::(text).unwrap()); + } + } + } + assert_eq!(copied.unwrap()["node"]["id"], dot); + assert_eq!(harness.state().session.history(), history); + + harness.state_mut().run("graph.select", json!({"ids": [add, multiply]})).unwrap(); + settle(&mut harness, 2); + harness.get(query("Multiply")).click_secondary(); + settle(&mut harness, 3); + assert!(harness.get(query("Set as output node")).accesskit_node().is_disabled()); + harness.get(query("Create graph from selection (2)")); + assert!(harness.query(query("Swap links X")).is_none()); + save(&mut harness, &directory, "function-multiple-node-context-menu"); + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + + harness.state_mut().run("edit.selectNone", json!({})).unwrap(); + settle(&mut harness, 2); + let background = harness.get(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).rect().min + vec2(24.0, 24.0); + harness.event(egui::Event::PointerMoved(background)); + harness.event(egui::Event::PointerButton { pos: background, button: egui::PointerButton::Secondary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.step(); + harness.event(egui::Event::PointerButton { pos: background, button: egui::PointerButton::Secondary, pressed: false, modifiers: egui::Modifiers::NONE }); + settle(&mut harness, 3); + let labels = [ + "Add node", + "Add Comment", + "Add Frame", + "Add Navigation pin", + "Add Dot node", + "Save package Ctrl+S", + "Paste Ctrl+V", + "Paste without link Ctrl+Shift+V", + "Select all Ctrl+A", + "Previous pin Shift+F2", + "Next pin F2", + "Copy selection Ctrl+C", + "Delete selection Delete", + "Delete and relink Backspace", + "Duplicate selection Ctrl+D", + "Duplicate selection without link Ctrl+Shift+D", + "Select upstream nodes", + "Select downstream nodes", + "Disable selection Shift+D", + ]; + let rows: Vec<_> = labels.iter().map(|label| harness.get(query(label)).rect().center().y).collect(); + assert!(rows.windows(2).all(|pair| pair[0] < pair[1])); + for label in &labels[11..] { + assert!(harness.get(query(label)).accesskit_node().is_disabled(), "{label}"); + } + for label in ["Copy info to clipboard", "Set as output node", "Cut selection"] { + assert!(harness.query(query(label)).is_none()); + } + save(&mut harness, &directory, "function-background-context-menu"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn selected_function_links_expose_swap_in_the_context_menu() { + use materialcraft_engine::core::{FunctionGraph, NodeId, Value}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.dock.close(materialcraft_ui_egui::docking::Panel::Library); + app.run("file.new", json!({"kind": "function", "name": "Swap links"})).unwrap(); + let mut graph = FunctionGraph::default(); + let a = graph.add_constant(Value::Float(1.0)); + let b = graph.add_constant(Value::Float(2.0)); + let subtract = graph.add("sub", &[a, b], None); + let interpolation = graph.add("lerp", &[b], None); + graph.output = Some(subtract); + for (node, position) in graph.nodes.iter_mut().zip([[0.0, -150.0], [0.0, 150.0], [450.0, -100.0], [450.0, 180.0]]) { + node.pos = position; + } + app.run("graph.function.set", json!({"function": graph})).unwrap(); + app.session.reset_history(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + let click = |harness: &mut Harness<'static, MaterialCraftApp>, node, input: &str, button, modifiers| { + let curve = harness.state().graph.wires.iter().find(|(wire, _)| wire.0 == NodeId(u64::from(node)) && wire.1 == input).unwrap().1; + let position = curve[0].lerp(curve[3], 0.5); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button, pressed, modifiers }); + harness.step(); + } + settle(harness, 2); + }; + let query = || By::new().role(egui::accesskit::Role::Button).label("Swap links X"); + click(&mut harness, subtract, "0", egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(harness.query(query()).is_none()); + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + click(&mut harness, subtract, "1", egui::PointerButton::Primary, egui::Modifiers::SHIFT); + save(&mut harness, &directory, "function-swap-links-before"); + click(&mut harness, subtract, "0", egui::PointerButton::Secondary, egui::Modifiers::NONE); + assert!(!harness.get(query()).accesskit_node().is_disabled()); + save(&mut harness, &directory, "function-selected-links-context-menu"); + harness.get(query()).click(); + settle(&mut harness, 3); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().node(subtract).unwrap().inputs, vec![Some(b), Some(a)]); + assert_eq!(harness.state().session.history().len(), 1); + save(&mut harness, &directory, "function-swap-links-after"); + harness.key_press(egui::Key::X); + settle(&mut harness, 2); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap().node(subtract).unwrap().inputs, vec![Some(a), Some(b)]); + + click(&mut harness, subtract, "1", egui::PointerButton::Primary, egui::Modifiers::CTRL); + click(&mut harness, interpolation, "0", egui::PointerButton::Primary, egui::Modifiers::SHIFT); + click(&mut harness, interpolation, "0", egui::PointerButton::Secondary, egui::Modifiers::NONE); + harness.get(query()).click(); + settle(&mut harness, 3); + let function = harness.state().session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.node(subtract).unwrap().inputs, vec![Some(b), Some(b)]); + assert_eq!(function.node(interpolation).unwrap().inputs, vec![Some(a)]); + save(&mut harness, &directory, "function-cross-node-swap-links-after"); + harness.key_press(egui::Key::X); + settle(&mut harness, 2); + let function = harness.state().session.graph().unwrap().function.as_ref().unwrap(); + assert_eq!(function.node(subtract).unwrap().inputs, vec![Some(a), Some(b)]); + assert_eq!(function.node(interpolation).unwrap().inputs, vec![Some(b)]); + click(&mut harness, interpolation, "0", egui::PointerButton::Primary, egui::Modifiers::CTRL); + click(&mut harness, subtract, "1", egui::PointerButton::Primary, egui::Modifiers::SHIFT); + + let mut graph = harness.state().session.graph().unwrap().function.clone().unwrap(); + let node = graph.nodes.iter_mut().find(|node| node.id == subtract).unwrap(); + node.op = "lerp".into(); + node.inputs.push(Some(a)); + harness.state_mut().run("graph.function.set", json!({"function": graph})).unwrap(); + settle(&mut harness, 3); + click(&mut harness, subtract, "2", egui::PointerButton::Primary, egui::Modifiers::SHIFT); + click(&mut harness, subtract, "0", egui::PointerButton::Secondary, egui::Modifiers::NONE); + let inspection = materialcraft_ui_egui::control::handle(harness.state_mut(), &egui::Context::default(), "ui.inspect", &json!({})); + assert_eq!(inspection["result"]["subgraph"]["selectedWires"].as_array().unwrap().len(), 3); + assert!(harness.query(query()).is_none()); + save(&mut harness, &directory, "function-three-selected-links-context-menu"); + harness.key_press(egui::Key::Escape); + settle(&mut harness, 2); + let history = harness.state().session.history(); + harness.key_press(egui::Key::X); + settle(&mut harness, 2); + assert_eq!(harness.state().session.history(), history); + assert_eq!(harness.state().session.graph().unwrap().function.as_ref().unwrap(), &graph); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn pattern_links_share_the_pair_context_menu() { + use materialcraft_engine::core::{NodeId, PatternGraph, PatternNodeKind, Value}; + + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.dock.close(materialcraft_ui_egui::docking::Panel::Library); + let owner = NodeId(app.run("graph.node.add", json!({"def": "fx_map"})).unwrap()["id"].as_u64().unwrap()); + let mut graph = PatternGraph::with_root(PatternNodeKind::Switch); + let a = graph.add(PatternNodeKind::Quadrant).unwrap(); + let b = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].children = vec![Some(a), Some(b)]; + for (node, position) in graph.nodes.iter_mut().zip([[0.0, 0.0], [-200.0, 300.0], [200.0, 300.0]]) { + node.position = position; + } + app.run("graph.pattern.set", json!({"id": owner.0, "pattern": graph})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + let context = harness.ctx.clone(); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "graph.node.edit"); + settle(&mut harness, 3); + for (port, button, modifiers) in [ + ("output0", egui::PointerButton::Primary, egui::Modifiers::NONE), + ("output1", egui::PointerButton::Primary, egui::Modifiers::SHIFT), + ("output0", egui::PointerButton::Secondary, egui::Modifiers::NONE), + ] { + let curve = harness.state().graph.wires.iter().find(|(wire, _)| wire.0 == NodeId(1) && wire.1 == port).unwrap().1; + let position = curve[0].lerp(curve[3], 0.5); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerMoved(position)); + harness.step(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: position, button, pressed, modifiers }); + harness.step(); + } + settle(&mut harness, 2); + } + let query = By::new().role(egui::accesskit::Role::Button).label("Swap links X"); + assert!(!harness.get(query.clone()).accesskit_node().is_disabled()); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, "pattern-selected-links-context-menu"); + harness.get(query).click(); + settle(&mut harness, 3); + let Value::PatternGraph(swapped) = &harness.state().session.graph().unwrap().node(owner).unwrap().params["pattern"] else { panic!() }; + assert_eq!(swapped.nodes[0].children, vec![Some(b), Some(a)]); + save(&mut harness, &directory, "pattern-swap-links-after"); +} + +#[test] +#[ignore = "requires an offscreen GPU; run explicitly with --ignored"] +fn incomplete_functions_warn_in_standalone_and_processor_canvases() { + use materialcraft_engine::{ + FunctionGraphTarget, + core::{FunctionGraph, NodeId, Value}, + }; + + for definition in ["function", "pixel_processor", "value_processor"] { + let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()); + app.ui.dock.close(materialcraft_ui_egui::docking::Panel::Library); + let target = if definition == "function" { + app.run("file.new", json!({"kind": "function", "name": "Incomplete function"})).unwrap(); + FunctionGraphTarget::Graph + } else { + let owner = NodeId(app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap()); + FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() } + }; + let mut graph = FunctionGraph::default(); + let source = graph.add_constant(Value::Float(0.5)); + let multiply = graph.add("mul", &[source], None); + graph.nodes[1].pos = [256.0, 0.0]; + app.run("graph.function.set", json!({"target": target, "function": graph})).unwrap(); + let mut harness = harness(app, 1600.0, 960.0); + settle(&mut harness, 4); + if definition != "function" { + let context = harness.ctx.clone(); + materialcraft_ui_egui::menus::invoke(harness.state_mut(), &context, "graph.node.edit"); + settle(&mut harness, 3); + } + let missing_output = || By::new().label_contains("No output node defined"); + let missing_input = || By::new().label_contains("input b is not connected"); + assert!(harness.query(missing_output()).is_some(), "{definition}"); + assert!(harness.query(missing_input()).is_some(), "{definition}"); + let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap()); + std::fs::create_dir_all(&directory).unwrap(); + save(&mut harness, &directory, &format!("{definition}-warnings")); + + harness.get(By::new().role(egui::accesskit::Role::Button).label("Multiply")).click_secondary(); + settle(&mut harness, 2); + harness.get(By::new().role(egui::accesskit::Role::Button).label_contains("Set as output node")).click(); + settle(&mut harness, 3); + assert!(harness.query(missing_output()).is_none()); + assert!(harness.query(missing_input()).is_some()); + harness + .state_mut() + .run("graph.function.edit", json!({"target": target, "edit": {"action": "connect", "from": source, "to": multiply, "input": 1}})) + .unwrap(); + settle(&mut harness, 3); + assert!(harness.query(missing_input()).is_none()); + harness.state_mut().run("edit.undo", json!({})).unwrap(); + settle(&mut harness, 3); + assert!(harness.query(missing_input()).is_some()); + } +} + #[test] #[ignore = "requires an offscreen GPU; run explicitly with --ignored"] fn explorer_export_opens_the_clicked_graph() { diff --git a/docs/atomic-workflow.md b/docs/atomic-workflow.md index a7380038..990a50ac 100644 --- a/docs/atomic-workflow.md +++ b/docs/atomic-workflow.md @@ -13,15 +13,23 @@ output and a value output. Use the library or Space search to add primitives and drag between ports to connect them. Select a Value Processor or Pixel Processor and choose **Edit function** in Properties. -The function editor supports adding operations, editing constants, wiring ports and choosing -the result. Select an FX-Map and press **Ctrl+E**, or right-click it and choose **Edit graph**. +The function editor supports adding operations, editing constants and wiring ports. Right-click +a function node and choose **Set as output node** to designate the result. Its body turns orange, +independently of selection. Choosing another output replaces the previous designation; deleting +the output leaves the function without a result until one is explicitly chosen. Adding nodes does +not automatically designate an output. Incomplete functions can be saved and reopened. The canvas +warns when an output is missing or an input is unconnected, including in both processor editors. +Select an FX-Map and press **Ctrl+E**, or right-click it and choose **Edit graph**. This enters its subgraph in the main canvas. Add Quadrant, Switch, Iterate or vertical Dot nodes, drag from bottom ports to top ports, and choose **Set as root** from a node’s context menu. Alt-click a port to disconnect it. Selected-node parameters appear in Properties. Click the parent breadcrumb or press **Alt+Left** to return. Positions and connections are saved in SBS. New FX-Map nodes start with a Quadrant root. Their main-graph inputs start with Background and -Input image 0; connecting an image exposes the next image input. Inputs appear progressively as they are connected; connected pins stay visible. Main and Function Graph pin names appear on node hover. Internal FX-Map pins have no visible names. +Input image 0; connecting an image exposes the next image input. Pixel Processor and Value Processor +also reveal image inputs as they are connected. Function operations and other fixed-input nodes show +all of their input pins from creation; connecting or disconnecting them does not hide or move pins. +Main and Function Graph pin names appear on node hover. Internal FX-Map pins have no visible names. Value inputs on processors have explicit types. A connection with an incompatible type is rejected. All edits use engine commands and support undo. Save and reopen through the usual diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 9e81085e..3c5d2068 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -23,6 +23,9 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands: engine-command authority, including host file access. Set `MATERIALCRAFT_NO_PREFS=1` for scripted runs so the user's layout is left alone. +Every SBS save writes MaterialCraft's workspace release version to `updaterVersion`, including +when resaving a file from an older release. `formatVersion` identifies the SBS schema separately. + ## Methods | Method | Where | What | @@ -75,7 +78,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` | | `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` | | `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}, ...]}`: swap (two) or reverse (more, in input order) where the wires come from / delete them, one undo step each | +| `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}` | @@ -123,6 +126,24 @@ Both `graph.function.set` and `graph.function.edit` accept an optional `target`: `graph.function.edit` accepts `edit: {action: add|move|connect|value|output, ...}`. For example, `{"edit":{"action":"add","operation":"mul","at":[256,0],"snap":true}}` creates and returns a node ID using the same defaults as library and context-menu insertion. +Adding an operation leaves the function's output unchanged. Use +`{"edit":{"action":"output","id":12}}` to designate its single output node; deleting that +node clears the designation. These edits support undo for every Function target. +`session.inspect` reports incomplete functions in `graph.functionWarnings`, with a `target` and +`messages` for each affected function. Missing outputs and unconnected inputs are warnings that +do not prevent editing or saving, including inside Pixel Processor and Value Processor nodes. +`graph.function.node.info {id, target?}` returns a `text` field with the node's operation, values, +connections and output designation. The node context menu copies this text to the system clipboard; +the document, undo history and node clipboard remain unchanged. +`graph.wire.swap {function?, pattern?, wires: [{to, toPort}, {to, toPort}]}` exchanges the +sources feeding any two selected links across all graph canvases. For functions, pass a +`FunctionGraphTarget` in `function` and a zero-based input index string in `toPort`. For FX-Map, +pass the owner node ID in `pattern`; `to` is the internal parent and `toPort` its child port +(`output0`, `output1`, or `output` for a Dot). The command preserves other connections, rejects +cycles atomically and supports undo. `graph.wire.delete` uses the same target and wire addresses. +Click a link and Shift-click another, then use **Swap links** or **X**. The menu action appears +only when exactly two links are selected, independently of node selection. `ui.inspect` exposes +embedded selections as `subgraph.selectedWires`. `graph.pattern.edit` accepts the FX-Map owner `id` and `edit: {action: add|move|connect|disconnect|root|value, ...}`. Use `command.list` for command descriptions and the serialized `FunctionEdit`/`PatternEdit` types diff --git a/docs/wires-and-alpha.md b/docs/wires-and-alpha.md index 693c4091..6ed5af52 100644 --- a/docs/wires-and-alpha.md +++ b/docs/wires-and-alpha.md @@ -24,10 +24,10 @@ named by the input it feeds: the target node and its input port (`to`, `toPort`) | **Shift**+click a wire | Adds it to the wire selection | | **Ctrl**+click a wire | Adds it to the wire selection, or removes it when it is already selected | | **Delete** or **Backspace** with wires selected | Deletes every selected wire (one undo step) | -| **X** with two or more wires selected | Swaps where the selected wires come from (see below); they stay selected, so **X** again swaps back | +| **X** with exactly two wires selected | Swaps where the selected wires come from (see below); they stay selected, so **X** again swaps back | | Drag a wire | Pulls a reroute **Dot** out of the wire where it was pressed and moves it with the pointer, in one gesture | | Double-click a wire | Drops a reroute Dot at that point | -| Right-click a wire | Opens the wire menu: **Insert reroute dot**, **Swap selected links (X)** (with two or more selected), **Delete link** / **Delete selected links**. Right-clicking a wire that is already selected keeps the selection | +| Right-click a wire | Opens the wire menu: **Insert reroute dot**, **Swap selected links (X)** (with exactly two selected), **Delete link** / **Delete selected links**. Right-clicking a wire that is already selected keeps the selection | | Click anywhere else | Drops the wire selection | A wire is hit within 5 points of its curve. Node cards, ports and comments sit on top of wires, so @@ -36,20 +36,15 @@ canvas. ### Swapping wires -Select the wires going into a node and press **X** to swap their sources. On a **Blend** node, select +Select any two wires and press **X** to swap their sources. On a **Blend** node, select the *Foreground* and *Background* wires and press **X**: what fed the foreground now feeds the background and the other way around, so the two layers trade places without rewiring by hand. - **Two wires** trade sources. -- **More than two** reverse their sources. The wires are ordered by target node, then by the order - of the inputs on the node (top to bottom), and the first wire's source goes to the last input, - the second's to the one before it, and so on. With *Foreground*, *Background* and *Opacity* - selected on a Blend, the foreground and opacity sources trade places and the background keeps - its own. +- The action is hidden unless exactly two wires are selected. - The order you click the wires in does not matter, so the result is predictable. - Wires into different nodes can be swapped too. A swap that would feed a node into itself (a cycle) is refused with a message, and nothing changes. -- One wire alone cannot be swapped: the editor says to select two or more. - The swap is one undo step. ### Reroute dots @@ -65,7 +60,7 @@ restores the straight wire. | Command | Params | Result | |---|---|---| | `graph.wire.insertDot` | `{to, toPort, at?: [x, y]}` | Splits the wire feeding `to.toPort` with a Dot centered at `at` (graph space; default: midway between the two nodes). Returns `{"id": }` and selects the dot. Errors when no wire feeds that input. | -| `graph.wire.swap` | `{wires: [{to, toPort}, ...]}` | Swaps (two wires) or reverses (more) the sources of the listed wires, as described above. Returns `{"swapped": n}`. Errors with fewer than two wires, a wire listed twice, a missing wire or a cycle; nothing changes then. | +| `graph.wire.swap` | `{wires: [{to, toPort}, ...]}` | Exchanges the sources of exactly two listed wires. Returns `{"swapped": 2}`. Errors unless exactly two wires are supplied, a wire listed twice, a missing wire or a cycle; nothing changes then. | | `graph.wire.delete` | `{wires: [{to, toPort}, ...]}` | Deletes the listed wires in one undo step (what the Delete key and the menu run). Returns `{"deleted": n}`. | | `graph.disconnect` | `{to, toPort}` | Deletes the single wire feeding `to.toPort`. | @@ -166,7 +161,7 @@ Headless renders (`materialcraft-cli render`, the `render` RPC) use the same set - `a_wire_splits_with_a_reroute_dot_and_deletes` (engine): insertion, wiring, selection, cooking through the dot, single-step undo, the error with no wire, deletion. - `selected_wires_swap_their_sources_and_delete_together` (engine): two-wire swap in any order, - three-wire reverse, single-step undo, refused requests (one wire, duplicates, missing wires), + single-step undo, refused requests (one or three wires, duplicates, missing wires), a refused cycle that leaves the graph unchanged, deleting several wires in one step. - `graph_view::tests::clicked_wires_swap_with_x_and_delete_together`: real clicks on a Blend node's two wires (the second with Shift), X swaps, X again swaps back, Delete removes both.