authoravatarclover caruso<git@paperclover.net>2026-12-01 03:03:10-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 03:50:24-08:00
logfb6224d3a024be8921e8596cff792e5930be9edd
tree70f6599a86dab2d3baeea1d150833df644bd10f2
parent71e715aa86519857ed834863da6894fcb5b5c802
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

flow: Fusion auto-rotating handles, right-edge output square, drag-to-wire

Inputs are role-coloured triangles (yellow main, green foreground, blue EffectMask, gray/purple extras) that snap to the edge facing their upstream node and spread along it without overlapping. Outputs are a square on the right edge: white when wired, gray when idle, gold on hover/drag. Wires detour around node bodies instead of cutting through. Dragging an output onto a triangle wires that exact port; onto a body it auto-picks the first open main port and highlights it. Dragging a connected triangle off rewires it or disconnects on empty canvas, and dropping it back leaves no undo entry. Hovering a handle shows its port name. The viewer pill now shows hollow rings for the unlit slot. Assisted-by: claude-sonnet-5.5

4 files changed, 1049 insertions(+), 461 deletions(-)

crates/flow/src/hit.rs+7-272
......@@ -22,51 +22,6 @@ impl FlowView {
2222 [c[0] - hw, c[1] - hh, c[0] + hw, c[1] + hh]
2323 }
2424
25 /// Computes auto-wrapped port geometry for a wire `src -> dst` so ports snap to the
26 /// closest facing sides of each node (Fusion's signature clean multi-directional routing!).
27 pub(crate) fn wire_endpoints(&self, comp: &Comp, src: NodeId, dst: NodeId, role: PortRole) -> ([f32; 2], Edge, [f32; 2], Edge) {
28 let sp = comp.node(src).pos;
29 let dp = comp.node(dst).pos;
30 let sr = self.node_rect_local(sp);
31 let dr = self.node_rect_local(dp);
32
33 let dx = dp[0] - sp[0];
34 let dy = dp[1] - sp[1];
35 // Weight Y slightly more because nodes are wider than tall (~5:1 aspect)!
36 let out_edge = closest_edge(dx, dy);
37 let in_edge = closest_edge_for_input(-dx, -dy, role);
38
39 let a = out_edge.point_on_rect(sr, 0.5);
40 let b = in_edge.point_on_rect(dr, 0.5);
41 (a, out_edge, b, in_edge)
42 }
43
44 /// Computes a node's resting output port edge (average direction of its consumers, defaulting to Right).
45 pub(crate) fn node_output_edge(&self, comp: &Comp, id: NodeId) -> Edge {
46 let name = &comp.node(id).name;
47 let sp = comp.node(id).pos;
48 let mut sx = 0.0_f32;
49 let mut sy = 0.0_f32;
50 let mut count = 0;
51 for other in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
52 for binding in other.inputs.values() {
53 if binding.source_op.as_deref() == Some(name.as_str()) {
54 let dx = other.pos[0] - sp[0];
55 let dy = other.pos[1] - sp[1];
56 let len = (dx * dx + dy * dy).sqrt().max(1.0);
57 sx += dx / len;
58 sy += dy / len;
59 count += 1;
60 }
61 }
62 }
63 if count == 0 {
64 Edge::Right
65 } else {
66 closest_edge(sx, sy)
67 }
68 }
69
7025 pub(crate) fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {
7126 for n in comp.nodes.iter().rev() {
7227 if !self.scope.shows(n) { continue; }
......@@ -78,186 +33,26 @@ impl FlowView {
7833 None
7934 }
8035
81 pub(crate) fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {
82 for n in comp.nodes.iter().rev() {
83 if !self.scope.shows(n) { continue; }
84 let r = self.node_rect_local(n.pos);
85 let edge = self.node_output_edge(comp, n.id);
86 let nrm = edge.normal();
87 let p0 = edge.point_on_rect(r, 0.5);
88 let p = [p0[0] + nrm[0] * 5.0, p0[1] + nrm[1] * 5.0];
89 let dx = local[0] - p[0];
90 let dy = local[1] - p[1];
91 if dx * dx + dy * dy <= 10.0 * 10.0 {
92 return Some(n.id);
93 }
94 }
95 None
96 }
97
98 pub(crate) fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> {
99 for n in comp.nodes.iter().rev() {
100 if !self.scope.shows(n) { continue; }
101 let r = self.node_rect_local(n.pos);
102 if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 {
103 return Some((n.id, drop_port(n, local[1] < r[1] + 2.0, local[1] > r[3] - 2.0)));
104 }
105 }
106 None
107 }
108
109 /// Hit-tests already-connected input port triangles so the user can drag an input off to disconnect/rewire.
110 pub(crate) fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> {
111 let hit_r2 = 10.5_f32 * 10.5_f32;
112 for dst in comp.nodes.iter().rev() {
113 if !self.scope.shows(dst) { continue; }
114 for (port, binding) in &dst.inputs {
115 let Some(src_name) = &binding.source_op else { continue };
116 let Some(src_id) = self.scope.resolve(comp, src_name) else { continue };
117 let role = PortRole::from_input_name(port);
118 let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role);
119 let bn = be.normal();
120 let center = [b[0] + bn[0] * 4.0, b[1] + bn[1] * 4.0];
121 let dx = local[0] - center[0];
122 let dy = local[1] - center[1];
123 if dx * dx + dy * dy <= hit_r2 {
124 return Some((dst.id, port.clone(), src_id));
125 }
126 }
127 }
128 None
129 }
130
13136 pub(crate) fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> {
13237 let mut best: Option<(f32, WireRef)> = None;
13338 for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
13439 if Some(dst.id) == ignore_node {
13540 continue;
13641 }
137 for (port, binding) in &dst.inputs {
138 let Some(src_name) = &binding.source_op else { continue };
139 let Some(src_id) = self.scope.resolve(comp, src_name) else { continue };
140 if Some(src_id) == ignore_node {
141 continue;
142 }
143 let role = PortRole::from_input_name(port);
144 let (a, ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role);
145 let d = dist_to_straight_wire(local, a, ae, b, be, self.zoom);
42 let dr = self.node_rect_local(dst.pos);
43 self.for_each_input(comp, dst, |slot| {
44 let Some(src) = slot.src.filter(|&s| Some(s) != ignore_node) else { return };
45 let route = self.wire_route(self.node_rect_local(comp.node(src).pos), dr, &slot);
46 let d = route.points().windows(2).map(|s| dist_to_seg(local, s[0], s[1])).fold(f32::INFINITY, f32::min);
14647 if d < 10.0 && best.as_ref().is_none_or(|(bd, _)| d < *bd) {
147 best = Some((
148 d,
149 WireRef {
150 src: src_id,
151 dst: dst.id,
152 port: port.clone(),
153 },
154 ));
48 best = Some((d, WireRef { src, dst: dst.id, port: slot.port.to_owned() }));
15549 }
156 }
50 });
15751 }
15852 best.map(|(_, w)| w)
15953 }
16054}
16155
162const SCENE_INPUTS: [&str; 32] = [
163 "SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4", "SceneInput5", "SceneInput6", "SceneInput7", "SceneInput8",
164 "SceneInput9", "SceneInput10", "SceneInput11", "SceneInput12", "SceneInput13", "SceneInput14", "SceneInput15", "SceneInput16",
165 "SceneInput17", "SceneInput18", "SceneInput19", "SceneInput20", "SceneInput21", "SceneInput22", "SceneInput23", "SceneInput24",
166 "SceneInput25", "SceneInput26", "SceneInput27", "SceneInput28", "SceneInput29", "SceneInput30", "SceneInput31", "SceneInput32",
167];
168
169const INPUTS: [&str; 33] = [
170 "Input0", "Input1", "Input2", "Input3", "Input4", "Input5", "Input6", "Input7", "Input8", "Input9", "Input10", "Input11",
171 "Input12", "Input13", "Input14", "Input15", "Input16", "Input17", "Input18", "Input19", "Input20", "Input21", "Input22",
172 "Input23", "Input24", "Input25", "Input26", "Input27", "Input28", "Input29", "Input30", "Input31", "Input32",
173];
174
175/// Port a wire dropped on `n` lands on; `top`/`bottom` are the node's mask/foreground approach bands.
176fn drop_port(n: &model::Node, top: bool, bottom: bool) -> &'static str {
177 let free = |names: &[&'static str]| {
178 names
179 .iter()
180 .copied()
181 .find(|p| n.inputs.get(*p).is_none_or(|b| b.source_op.is_none()))
182 .unwrap_or(names[names.len() - 1])
183 };
184 match n.kind.as_str() {
185 "Merge" | "Dissolve" | "ChannelBoolean" => {
186 if top {
187 "Foreground"
188 } else if bottom {
189 "EffectMask"
190 } else {
191 "Background"
192 }
193 }
194 "Displace" => {
195 if top {
196 "Foreground"
197 } else if bottom {
198 "EffectMask"
199 } else {
200 "Input"
201 }
202 }
203 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => {
204 "SceneInput"
205 }
206 "Merge3D" => free(&SCENE_INPUTS),
207 "sMerge" | "pMerge" => free(&INPUTS[1..]),
208 "sBoolean" => free(&INPUTS[1..=2]),
209 "Fuse.Switch" => free(&INPUTS[1..]),
210 "Switch" => {
211 let zero_indexed = n.inputs.contains_key("Source") || n.inputs.contains_key("Input0") || !n.inputs.contains_key("Which");
212 free(if zero_indexed { &INPUTS[..] } else { &INPUTS[1..] })
213 }
214 "BitmapMask" => "Image",
215 "ImagePlane3D" | "TextureTransformOperator" => "MaterialInput",
216 kind if bottom && kind != "PipeRouter" => "EffectMask",
217 kind => default_main_input_port(kind),
218 }
219}
220
221/// Picks the closest node edge facing vector `(dx, dy)` accounting for thin rectangular bar aspect.
222fn closest_edge(dx: f32, dy: f32) -> Edge {
223 // Nodes are 84x21 (4:1 aspect), so require a balanced X bias so horizontal rows snap Left/Right
224 // while vertical stacks naturally snap Top/Bottom!
225 if dx.abs() * 0.58 >= dy.abs() {
226 if dx >= 0.0 { Edge::Right } else { Edge::Left }
227 } else if dy >= 0.0 {
228 Edge::Bottom
229 } else {
230 Edge::Top
231 }
232}
233
234/// Auto-wraps input port to the closest side facing the producer, gently nudging Mask/FG when needed.
235fn closest_edge_for_input(dx_to_src: f32, dy_to_src: f32, role: PortRole) -> Edge {
236 let primary = closest_edge(dx_to_src, dy_to_src);
237 match role {
238 PortRole::Mask => {
239 // Masks prefer Top/Bottom unless directly horizontal
240 if dy_to_src.abs() >= dx_to_src.abs() * 0.35 {
241 if dy_to_src >= 0.0 { Edge::Bottom } else { Edge::Top }
242 } else {
243 primary
244 }
245 }
246 _ => primary,
247 }
248}
249
250fn dist_to_straight_wire(pt: [f32; 2], a: [f32; 2], ae: Edge, b: [f32; 2], be: Edge, zoom: f32) -> f32 {
251 let stub = (8.0 * zoom).clamp(4.0, 11.0);
252 let an = ae.normal();
253 let bn = be.normal();
254 let a_out = [a[0] + an[0] * stub, a[1] + an[1] * stub];
255 let b_out = [b[0] + bn[0] * stub, b[1] + bn[1] * stub];
256 dist_to_seg(pt, a, a_out)
257 .min(dist_to_seg(pt, a_out, b_out))
258 .min(dist_to_seg(pt, b_out, b))
259}
260
26156pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
26257 let ab = [b[0] - a[0], b[1] - a[1]];
26358 let len2 = ab[0] * ab[0] + ab[1] * ab[1];
......@@ -269,63 +64,3 @@ pub(crate) fn dist_to_seg(p: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
26964 let q = [a[0] + ab[0] * t, a[1] + ab[1] * t];
27065 ((p[0] - q[0]).powi(2) + (p[1] - q[1]).powi(2)).sqrt()
27166}
272
273#[cfg(test)]
274mod tests {
275 use super::*;
276
277 fn port(comp: &Comp, name: &str) -> &'static str {
278 drop_port(comp.node(comp.find_node(name).unwrap()), false, false)
279 }
280
281 fn comp(src: &str) -> Comp {
282 Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ {src} }} }}")).expect("parse comp")
283 }
284
285 #[test]
286 fn single_input_kinds_use_engine_port_names() {
287 let c = comp(
288 "R = Renderer3D { }, D = Displace { }, CB = ChannelBoolean { }, Dis = Dissolve { },
289 BM = BitmapMask { }, T = Transform3D { }, Plane = ImagePlane3D { }",
290 );
291 assert_eq!(port(&c, "R"), "SceneInput");
292 assert_eq!(port(&c, "D"), "Input");
293 assert_eq!(port(&c, "CB"), "Background");
294 assert_eq!(port(&c, "Dis"), "Background");
295 assert_eq!(port(&c, "BM"), "Image");
296 assert_eq!(port(&c, "T"), "SceneInput");
297 assert_eq!(port(&c, "Plane"), "MaterialInput");
298 let d = c.node(c.find_node("D").unwrap());
299 assert_eq!(drop_port(d, true, false), "Foreground");
300 assert_eq!(drop_port(d, false, true), "EffectMask");
301 let cb = c.node(c.find_node("CB").unwrap());
302 assert_eq!(drop_port(cb, true, false), "Foreground");
303 }
304
305 #[test]
306 fn multi_input_kinds_pick_next_free_port() {
307 let c = comp(
308 r#"A = Background { }, B = Background { },
309 M3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output" } } },
310 M3b = Merge3D { },
311 S = Switch { Inputs = { Input0 = Input { SourceOp = "A", Source = "Output" } } },
312 SW = Switch { Inputs = { Which = Input { Value = 1 } } },
313 SB = sBoolean { Inputs = { Input1 = Input { SourceOp = "A", Source = "Output" } } },
314 SB0 = sBoolean { },
315 FS = Fuse.Switch { }"#,
316 );
317 assert_eq!(port(&c, "M3b"), "SceneInput1");
318 assert_eq!(port(&c, "M3"), "SceneInput2");
319 assert_eq!(port(&c, "S"), "Input1");
320 assert_eq!(port(&c, "SW"), "Input1");
321 assert_eq!(port(&c, "SB"), "Input2");
322 assert_eq!(port(&c, "SB0"), "Input1");
323 assert_eq!(port(&c, "FS"), "Input1");
324 }
325
326 #[test]
327 fn native_switch_without_which_starts_at_input0() {
328 let c = comp("S = Switch { }");
329 assert_eq!(port(&c, "S"), "Input0");
330 }
331}
crates/flow/src/lib.rs+230-56
......@@ -1,6 +1,7 @@
11//! Node Flow canvas built on `draw` + `ui`:
22//! - Sleek thin Fusion-style node bars with colored bottom stripe
3//! - Auto-wrapping output/input ports that snap to whichever side faces connected nodes
3//! - Fusion handles: output square on the right edge, role-coloured input triangles that rotate toward their upstream node
4//! - Drag output -> input triangle (or node body) to wire, drag a connected triangle off to rewire or disconnect
45//! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal)
56//! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks
67//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.
......@@ -8,6 +9,7 @@
89
910mod hit;
1011mod paint;
12mod ports;
1113mod scope;
1214
1315use draw::{Glyphs, PathStyle, Primitive};
......@@ -61,15 +63,6 @@ impl Edge {
6163 Edge::Bottom => [0.0, 1.0],
6264 }
6365 }
64
65 fn point_on_rect(self, r: [f32; 4], t: f32) -> [f32; 2] {
66 match self {
67 Edge::Left => [r[0], r[1] + (r[3] - r[1]) * t],
68 Edge::Right => [r[2], r[1] + (r[3] - r[1]) * t],
69 Edge::Top => [r[0] + (r[2] - r[0]) * t, r[1]],
70 Edge::Bottom => [r[0] + (r[2] - r[0]) * t, r[3]],
71 }
72 }
7366}
7467
7568#[derive(Clone, Debug)]
......@@ -85,12 +78,25 @@ struct ModalTransform {
8578struct WireDrag {
8679 src: NodeId,
8780 cursor_local: [f32; 2],
88 /// If hovering a target input port, `(dst, port, creates_cycle)`.
89 target: Option<(NodeId, &'static str, bool)>,
90 /// True when dragging an existing connected input off to disconnect/rewire.
81 target: Option<DropTarget>,
82 /// Set when dragging an existing connected input off to disconnect/rewire.
9183 detached_from: Option<(NodeId, String)>,
9284}
9385
86#[derive(Clone, Debug)]
87struct DropTarget {
88 node: NodeId,
89 port: String,
90 cycle: bool,
91}
92
93/// Handle under the pointer: a node's output square (`port: None`) or one of its input triangles.
94#[derive(Clone, Debug, PartialEq, Eq)]
95struct HandleId {
96 node: NodeId,
97 port: Option<String>,
98}
99
94100#[derive(Clone, Debug)]
95101struct BoxSelect {
96102 start_local: [f32; 2],
......@@ -172,6 +178,7 @@ pub struct FlowView {
172178 pub viewed_nodes: [Option<NodeId>; 2],
173179 pub palette: FlowPalette,
174180 hovered_node: Option<NodeId>,
181 hovered_handle: Option<HandleId>,
175182 hovered_wire: Option<WireRef>,
176183 modal: Option<ModalTransform>,
177184 wire_drag: Option<WireDrag>,
......@@ -197,6 +204,7 @@ impl FlowView {
197204 viewed_nodes: [None, None],
198205 palette: FlowPalette::from_ui(theme),
199206 hovered_node: None,
207 hovered_handle: None,
200208 hovered_wire: None,
201209 modal: None,
202210 wire_drag: None,
......@@ -225,6 +233,7 @@ impl FlowView {
225233 self.selected.clear();
226234 self.primary = None;
227235 self.hovered_node = None;
236 self.hovered_handle = None;
228237 self.hovered_wire = None;
229238 self.modal = None;
230239 self.wire_drag = None;
......@@ -271,6 +280,7 @@ impl FlowView {
271280 self.selected.extend(select);
272281 self.primary = select;
273282 self.hovered_node = None;
283 self.hovered_handle = None;
274284 self.hovered_wire = None;
275285 self.modal = None;
276286 self.wire_drag = None;
......@@ -298,6 +308,7 @@ impl FlowView {
298308 if self.hovered_node.is_some_and(|id| id.0 >= len) {
299309 self.hovered_node = None;
300310 }
311 self.hovered_handle = None;
301312 self.hovered_wire = None;
302313 self.modal = None;
303314 self.wire_drag = None;
......@@ -699,15 +710,17 @@ impl FlowView {
699710 ];
700711 } else if self.modal.is_some() {
701712 self.apply_modal(comp, modifiers.shift_key());
702 } else if let Some(wd) = &mut self.wire_drag {
703 wd.cursor_local = self.pointer_local;
704 let src = wd.src;
705 let target = self.hit_input_port(comp, self.pointer_local).map(|(dst, port)| {
706 let cycle = comp.would_create_cycle(src, dst);
707 (dst, port, cycle)
708 });
709 if let Some(wd_mut) = &mut self.wire_drag {
710 wd_mut.target = target;
713 } else if self.wire_drag.is_some() {
714 let hit = self.hit_drop_target(comp, self.pointer_local);
715 if let Some(wd) = &mut self.wire_drag {
716 wd.cursor_local = self.pointer_local;
717 if wd.target.as_ref().map(|t| (t.node, t.port.as_str())) != hit {
718 wd.target = hit.map(|(node, port)| DropTarget {
719 node,
720 port: port.to_owned(),
721 cycle: comp.would_create_cycle(wd.src, node),
722 });
723 }
711724 }
712725 } else if let Some(bs) = &mut self.box_select {
713726 bs.cur_local = self.pointer_local;
......@@ -726,7 +739,11 @@ impl FlowView {
726739 }
727740 } else {
728741 self.hovered_node = self.hit_node(comp, self.pointer_local);
729 self.hovered_wire = if self.hovered_node.is_none() {
742 let handle = self.hit_handle(comp, self.pointer_local);
743 if self.hovered_handle.as_ref().map(|h| (h.node, h.port.as_deref())) != handle {
744 self.hovered_handle = handle.map(|(node, port)| HandleId { node, port: port.map(str::to_owned) });
745 }
746 self.hovered_wire = if self.hovered_node.is_none() && handle.is_none() {
730747 self.hit_wire(comp, self.pointer_local, None)
731748 } else {
732749 None
......@@ -765,17 +782,23 @@ impl FlowView {
765782 }
766783 } else if button == MouseButton::Left {
767784 if pressed {
785 let handle = self.hit_handle(comp, self.pointer_local).filter(|_| self.scope.is_root());
768786 if self.modal.is_some() {
769787 self.confirm_modal(comp, history, &mut actions);
770 } else if let Some(src) = self.hit_output_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) {
788 } else if let Some((src, None)) = handle {
771789 self.wire_drag = Some(WireDrag {
772790 src,
773791 cursor_local: self.pointer_local,
774792 target: None,
775793 detached_from: None,
776794 });
777 } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) {
778 // Dragging an existing input port detaches it so user can drop to disconnect or rewire!
795 } else if let Some((dst, Some(port), src)) = handle.and_then(|(dst, port)| {
796 let port = port?;
797 let src = self.upstream_of(comp, comp.node(dst), port)?;
798 Some((dst, Some(port.to_owned()), src))
799 }) {
800 // Dragging a connected triangle detaches it: drop on another triangle to move
801 // the wire, or on empty canvas to disconnect.
779802 history.begin_group(comp, "Rewire");
780803 comp.disconnect(dst, &port);
781804 actions.push(FlowAction::GraphMutated(Some(dst)));
......@@ -830,25 +853,28 @@ impl FlowView {
830853 }
831854 if let Some(wd) = self.wire_drag.take() {
832855 let detached = wd.detached_from.is_some();
833 if let Some((dst, port)) = self.hit_input_port(comp, self.pointer_local) {
834 if !detached {
835 history.begin_group(comp, "Connect");
836 }
837 let result = if comp.would_create_cycle(wd.src, dst) {
838 Err("Cycle rejected: cannot connect downstream to upstream".to_owned())
839 } else {
840 comp.connect_output(wd.src, "Output", dst, port)
841 };
842 match result {
843 Ok(()) => {
844 history.commit_group(comp);
856 let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned()));
857 if let Some((dst, port)) = target {
858 if wd.detached_from.as_ref() == Some(&(dst, port.clone())) {
859 // Dropped back where it started: nothing changed, leave no undo entry.
860 if history.cancel_group(comp) {
845861 actions.push(FlowAction::GraphMutated(Some(dst)));
846862 }
847 Err(e) => {
848 if history.cancel_group(comp) && detached {
849 actions.push(FlowAction::GraphMutated(None));
863 } else {
864 if !detached {
865 history.begin_group(comp, "Connect");
866 }
867 match comp.connect_output(wd.src, "Output", dst, &port) {
868 Ok(()) => {
869 history.commit_group(comp);
870 actions.push(FlowAction::GraphMutated(Some(dst)));
871 }
872 Err(e) => {
873 if history.cancel_group(comp) && detached {
874 actions.push(FlowAction::GraphMutated(None));
875 }
876 actions.push(FlowAction::StatusNotice(e));
850877 }
851 actions.push(FlowAction::StatusNotice(e));
852878 }
853879 }
854880 } else if let Some((dst, port)) = wd.detached_from {
......@@ -918,13 +944,13 @@ fn read_only_notice(actions: &mut Vec<FlowAction>) {
918944 actions.push(FlowAction::StatusNotice("Group contents are read-only; press Esc to leave the group".to_owned()));
919945}
920946
921/// Samples a smooth cubic Bezier preview wire leaving `a` along `out_normal` and arriving at `b`.
922pub fn sample_preview_bezier(a: [f32; 2], out_normal: [f32; 2], b: [f32; 2], steps: usize) -> Vec<[f32; 2]> {
947/// Samples a cubic Bezier wire leaving `a` along `a_normal` and arriving at `b` from the side `b_normal` faces.
948pub fn sample_wire_bezier(a: [f32; 2], a_normal: [f32; 2], b: [f32; 2], b_normal: [f32; 2], steps: usize) -> Vec<[f32; 2]> {
923949 let steps = steps.max(2);
924950 let dist = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();
925951 let handle = (dist * 0.42).clamp(24.0, 140.0);
926 let c1 = [a[0] + out_normal[0] * handle, a[1] + out_normal[1] * handle];
927 let c2 = [b[0] - out_normal[0] * handle * 0.65, b[1] - out_normal[1] * handle * 0.65];
952 let c1 = [a[0] + a_normal[0] * handle, a[1] + a_normal[1] * handle];
953 let c2 = [b[0] + b_normal[0] * handle * 0.65, b[1] + b_normal[1] * handle * 0.65];
928954 let mut pts = Vec::with_capacity(steps + 1);
929955 for i in 0..=steps {
930956 let t = i as f32 / steps as f32;
......@@ -962,7 +988,7 @@ mod tests {
962988
963989 #[test]
964990 fn bezier_preview_endpoints_match() {
965 let pts = sample_preview_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], 16);
991 let pts = sample_wire_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], [-1.0, 0.0], 16);
966992 assert_eq!(pts.len(), 17);
967993 assert!((pts[0][0] - 10.0).abs() < 1e-4);
968994 assert!((pts[0][1] - 20.0).abs() < 1e-4);
......@@ -994,11 +1020,14 @@ mod tests {
9941020 let merge_local = flow.world_to_local(comp.node(merge).pos);
9951021 assert_eq!(flow.hit_node(&comp, merge_local), Some(merge));
9961022
997 // Top of Merge hits Foreground; bottom hits EffectMask; middle hits Background
998 let mr = flow.node_rect_local(comp.node(merge).pos);
999 assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[1] - 2.0]), Some((merge, "Foreground")));
1000 assert_eq!(flow.hit_input_port(&comp, [merge_local[0], mr[3] + 2.0]), Some((merge, "EffectMask")));
1001 assert_eq!(flow.hit_input_port(&comp, merge_local), Some((merge, "Background")));
1023 // Each triangle drops on its own port; the body picks the first open main port.
1024 let m = ports::Metrics::at(flow.zoom);
1025 for port in ["Background", "Foreground", "EffectMask"] {
1026 let slot = flow.input_slot(&comp, comp.node(merge), port).unwrap();
1027 assert_eq!(flow.hit_drop_target(&comp, slot.center(m)), Some((merge, port)));
1028 }
1029 assert_eq!(flow.hit_drop_target(&comp, merge_local), Some((merge, "Foreground")));
1030 assert_eq!(flow.hit_drop_target(&comp, [0.0, 0.0]), None);
10021031 }
10031032
10041033 #[test]
......@@ -1243,10 +1272,9 @@ mod tests {
12431272 flow.size = [800.0, 600.0];
12441273 flow.pan = [80.0, 0.0];
12451274 flow.zoom = 1.0;
1246 let (bg, merge) = (id(&comp, "BG1"), id(&comp, "Merge1"));
1247 let (_, _, b, be) = flow.wire_endpoints(&comp, bg, merge, PortRole::Background);
1248 let n = be.normal();
1249 let port = [b[0] + n[0] * 4.0, b[1] + n[1] * 4.0];
1275 let merge = id(&comp, "Merge1");
1276 let m = ports::Metrics::at(flow.zoom);
1277 let port = flow.input_slot(&comp, comp.node(merge), "Background").unwrap().center(m);
12501278 let rect = [0.0, 0.0, 800.0, 600.0];
12511279
12521280 flow.input(
......@@ -1267,6 +1295,152 @@ mod tests {
12671295 assert!(!history.can_undo() && !history.in_group());
12681296 }
12691297
1298 const WIRE_COMP: &str = r#"Composition {
1299 Tools = ordered() {
1300 BG1 = Background { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1301 BG2 = Background { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, },
1302 Merge1 = Merge {
1303 Inputs = { Background = Input { SourceOp = "BG1", Source = "Output" }, },
1304 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1305 },
1306 Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, },
1307 },
1308 }"#;
1309
1310 fn wire_flow() -> (Comp, FlowView, CompHistory) {
1311 let comp = Comp::from_fusion_str(WIRE_COMP).expect("parse comp");
1312 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1313 flow.size = [800.0, 600.0];
1314 flow.pan = [80.0, 60.0];
1315 flow.zoom = 1.0;
1316 (comp, flow, CompHistory::new())
1317 }
1318
1319 fn send(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, event: ui::Event, at: [f32; 2]) -> Vec<FlowAction> {
1320 flow.input(comp, history, event, [0.0, 0.0, 800.0, 600.0], at, ModifiersState::empty())
1321 }
1322
1323 fn drag(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, from: [f32; 2], to: [f32; 2]) -> Vec<FlowAction> {
1324 let button = |pressed| ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() };
1325 send(flow, comp, history, ui::Event::PointerMoved(from), from);
1326 send(flow, comp, history, button(true), from);
1327 send(flow, comp, history, ui::Event::PointerMoved(to), to);
1328 send(flow, comp, history, button(false), to)
1329 }
1330
1331 fn output_center(flow: &FlowView, comp: &Comp, node: NodeId) -> [f32; 2] {
1332 ports::Metrics::at(flow.zoom).output_center(flow.node_rect_local(comp.node(node).pos))
1333 }
1334
1335 fn input_center(flow: &FlowView, comp: &Comp, node: NodeId, port: &str) -> [f32; 2] {
1336 flow.input_slot(comp, comp.node(node), port).unwrap().center(ports::Metrics::at(flow.zoom))
1337 }
1338
1339 fn source(comp: &Comp, node: NodeId, port: &str) -> Option<String> {
1340 comp.node(node).inputs.get(port).and_then(|b| b.source_op.clone())
1341 }
1342
1343 #[test]
1344 fn dragging_an_output_onto_an_input_triangle_wires_that_exact_port() {
1345 let (mut comp, mut flow, mut history) = wire_flow();
1346 let (bg2, merge) = (id(&comp, "BG2"), id(&comp, "Merge1"));
1347 let (from, to) = (output_center(&flow, &comp, bg2), input_center(&flow, &comp, merge, "EffectMask"));
1348
1349 let acts = drag(&mut flow, &mut comp, &mut history, from, to);
1350 assert_eq!(source(&comp, merge, "EffectMask").as_deref(), Some("BG2"));
1351 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1352 assert!(acts.iter().any(|a| matches!(a, FlowAction::GraphMutated(Some(n)) if *n == merge)));
1353 assert!(flow.wire_drag.is_none());
1354 assert!(history.undo(&mut comp));
1355 assert_eq!(source(&comp, merge, "EffectMask"), None);
1356 }
1357
1358 #[test]
1359 fn dropping_on_a_body_auto_picks_and_highlights_the_open_port() {
1360 let (mut comp, mut flow, mut history) = wire_flow();
1361 let (bg2, merge, blur) = (id(&comp, "BG2"), id(&comp, "Merge1"), id(&comp, "Blur1"));
1362 let from = output_center(&flow, &comp, bg2);
1363 let body = flow.world_to_local(comp.node(merge).pos);
1364
1365 let button = |pressed| ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() };
1366 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(from), from);
1367 send(&mut flow, &mut comp, &mut history, button(true), from);
1368 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(body), body);
1369 let target = flow.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).expect("hover target");
1370 assert_eq!((target.node, target.port.as_str(), target.cycle), (merge, "Foreground", false));
1371 send(&mut flow, &mut comp, &mut history, button(false), body);
1372 assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG2"));
1373
1374 // Single-input tools take their main input.
1375 let (from, body) = (output_center(&flow, &comp, bg2), flow.world_to_local(comp.node(blur).pos));
1376 drag(&mut flow, &mut comp, &mut history, from, body);
1377 assert_eq!(source(&comp, blur, "Input").as_deref(), Some("BG2"));
1378 }
1379
1380 #[test]
1381 fn dropping_a_downstream_wire_upstream_is_flagged_as_a_cycle() {
1382 let (mut comp, mut flow, mut history) = wire_flow();
1383 let (bg1, merge) = (id(&comp, "BG1"), id(&comp, "Merge1"));
1384 let from = output_center(&flow, &comp, merge);
1385 let to = input_center(&flow, &comp, bg1, "EffectMask");
1386 let acts = drag(&mut flow, &mut comp, &mut history, from, to);
1387 assert!(acts.iter().any(|a| matches!(a, FlowAction::StatusNotice(_))));
1388 assert_eq!(source(&comp, bg1, "EffectMask"), None);
1389 assert!(!history.can_undo() && !history.in_group());
1390 }
1391
1392 #[test]
1393 fn dragging_a_connected_triangle_off_rewires_or_disconnects() {
1394 let (mut comp, mut flow, mut history) = wire_flow();
1395 let merge = id(&comp, "Merge1");
1396 let bg_tri = input_center(&flow, &comp, merge, "Background");
1397
1398 // Onto another triangle: the wire moves.
1399 let fg_tri = input_center(&flow, &comp, merge, "Foreground");
1400 drag(&mut flow, &mut comp, &mut history, bg_tri, fg_tri);
1401 assert_eq!(source(&comp, merge, "Background"), None);
1402 assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG1"));
1403 assert_eq!(history.undo_len(), 1);
1404
1405 // Dragging the moved triangle off onto empty canvas disconnects it.
1406 let fg_tri = input_center(&flow, &comp, merge, "Foreground");
1407 let acts = drag(&mut flow, &mut comp, &mut history, fg_tri, [700.0, 500.0]);
1408 assert_eq!(source(&comp, merge, "Foreground"), None);
1409 assert!(acts.iter().any(|a| matches!(a, FlowAction::StatusNotice(m) if m.starts_with("Disconnected"))));
1410 assert_eq!(history.undo_len(), 2);
1411 assert!(history.undo(&mut comp));
1412 assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG1"));
1413 }
1414
1415 #[test]
1416 fn dropping_a_detached_wire_back_where_it_started_leaves_no_undo_entry() {
1417 let (mut comp, mut flow, mut history) = wire_flow();
1418 let merge = id(&comp, "Merge1");
1419 let tri = input_center(&flow, &comp, merge, "Background");
1420 drag(&mut flow, &mut comp, &mut history, tri, tri);
1421 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1422 assert!(!history.can_undo() && !history.in_group());
1423 }
1424
1425 #[test]
1426 fn handle_hover_tracks_the_pointer_and_body_clicks_still_select() {
1427 let (mut comp, mut flow, mut history) = wire_flow();
1428 let (bg1, merge) = (id(&comp, "BG1"), id(&comp, "Merge1"));
1429 let out = output_center(&flow, &comp, bg1);
1430 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(out), out);
1431 assert_eq!(flow.hovered_handle, Some(HandleId { node: bg1, port: None }));
1432 let tri = input_center(&flow, &comp, merge, "EffectMask");
1433 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri);
1434 assert_eq!(flow.hovered_handle, Some(HandleId { node: merge, port: Some("EffectMask".to_owned()) }));
1435 let body = flow.world_to_local(comp.node(merge).pos);
1436 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(body), body);
1437 assert_eq!(flow.hovered_handle, None);
1438
1439 press(&mut flow, &mut comp, &mut history, Instant::now(), merge);
1440 assert_eq!(flow.primary, Some(merge));
1441 assert!(flow.wire_drag.is_none());
1442 }
1443
12701444 #[test]
12711445 fn letter_shortcuts_ignore_ctrl_and_alt() {
12721446 let (mut comp, mut flow) = group_flow();
crates/flow/src/paint.rs+137-133
......@@ -20,6 +20,12 @@ impl FlowView {
2020 weight: 600,
2121 italic: false,
2222 };
23 let port_font = text::Font {
24 families: Arc::from([text::Family::Sans]),
25 size: 9.0,
26 weight: 500,
27 italic: false,
28 };
2329 let make_layout = |s: &str, font: &text::Font| {
2430 let styles = [text::Style::new(font.clone())];
2531 text::Paragraph {
......@@ -47,6 +53,15 @@ impl FlowView {
4753 self.badge_cache
4854 .entry("cycle!".to_owned())
4955 .or_insert_with(|| make_layout("cycle!", &tiny_font));
56 let wanted = [
57 self.hovered_handle.as_ref().map(|h| h.port.as_deref().unwrap_or("Output")),
58 self.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).map(|t| t.port.as_str()),
59 ];
60 for name in wanted.into_iter().flatten() {
61 if !self.badge_cache.contains_key(name) {
62 self.badge_cache.insert(name.to_owned(), make_layout(name, &port_font));
63 }
64 }
5065 for key in [
5166 HUD_ROOT,
5267 HUD_GROUP,
......@@ -103,122 +118,94 @@ impl FlowView {
103118 }
104119 }
105120
106 // 3. Straight Fusion wires + crisp white output squares (□) + inward-pointing colored input arrows (▶)!
107 let large_ports = self.zoom >= 0.72;
108 let tri_len = if large_ports { 6.5 } else { 4.5 };
109 let out_half = if large_ports { 2.8 } else { 2.0 };
110 let out_gap = if large_ports { 2.2 } else { 1.5 };
111 let port_outline = [0.04, 0.04, 0.06, 0.92];
121 // 3. Output squares (idle gray; wires overpaint connected ones white), straight Fusion wires
122 // and role-coloured input triangles.
123 let handles = self.zoom >= ports::HANDLE_MIN_ZOOM;
124 let m = ports::Metrics::at(self.zoom);
125 let large = ports::Metrics::large(self.zoom);
126 let on_screen = |r: [f32; 4]| r[2] >= -24.0 && r[0] <= w + 24.0 && r[3] >= -24.0 && r[1] <= h + 24.0;
127 let out_hot = |id: NodeId| {
128 self.wire_drag.as_ref().is_some_and(|wd| wd.src == id)
129 || self.hovered_handle.as_ref().is_some_and(|hh| hh.node == id && hh.port.is_none())
130 };
131 let out_fill = |id: NodeId, connected: bool| {
132 if out_hot(id) {
133 [0.98, 0.84, 0.30, 1.0]
134 } else if connected {
135 [0.96, 0.97, 1.0, 1.0]
136 } else {
137 [0.42, 0.44, 0.50, 1.0]
138 }
139 };
140 if handles {
141 for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
142 let r = self.node_rect_local(n.pos);
143 if on_screen(r) {
144 push_square(&mut out, m.output_center(r), m.out_half, out_fill(n.id, false));
145 }
146 }
147 }
112148
113149 for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
114 // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping
115 let mut used_edges: HashMap<u8, usize> = HashMap::new();
116 let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect();
117 sorted_ports.sort_by_key(|(p, _)| match PortRole::from_input_name(p) {
118 PortRole::Background => 0u8,
119 PortRole::Foreground => 1,
120 PortRole::Mask => 2,
121 PortRole::Scene3D => 3,
122 PortRole::Aux => 4,
123 });
124 for (port, binding) in sorted_ports {
125 let Some(src_name) = &binding.source_op else { continue };
126 let Some(src_id) = self.scope.resolve(comp, src_name) else { continue };
127 let role = PortRole::from_input_name(port);
128 let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role);
129 let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 };
130 let count = used_edges.entry(ekey(be)).or_insert(0);
131 if *count > 0 {
132 // Spread horizontal top/bottom ports (e.g. FG + Mask) like Fusion's ColorCorrector / Merge
133 let dr = self.node_rect_local(dst.pos);
134 if matches!(be, Edge::Top | Edge::Bottom) {
135 let t = if *count == 1 { 0.25 } else { 0.75 };
136 b = be.point_on_rect(dr, t);
137 } else if role == PortRole::Mask {
138 be = Edge::Bottom;
139 b = be.point_on_rect(dr, 0.5);
140 } else {
141 let t = if *count == 1 { 0.30 } else { 0.70 };
142 b = be.point_on_rect(dr, t);
150 let dr = self.node_rect_local(dst.pos);
151 let dst_vis = on_screen(dr);
152 self.for_each_input(comp, dst, |slot| {
153 if let Some(src) = slot.src {
154 let sr = self.node_rect_local(comp.node(src).pos);
155 let (x0, x1) = (sr[0].min(dr[0]), sr[2].max(dr[2]));
156 let (y0, y1) = (sr[1].min(dr[1]), sr[3].max(dr[3]));
157 if x1 >= 0.0 && x0 <= w && y1 >= 0.0 && y0 <= h {
158 let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src && hw.dst == dst.id && hw.port == slot.port);
159 let is_sel = self.selected.contains(&src) || self.selected.contains(&dst.id);
160 let (color, width) = if is_hot {
161 ([0.98, 0.82, 0.24, 1.0], 2.4)
162 } else if is_sel {
163 ([0.92, 0.94, 0.98, 0.96], 1.6)
164 } else {
165 ([0.64, 0.66, 0.72, 0.76], 1.1)
166 };
167 for seg in self.wire_route(sr, dr, &slot).points().windows(2) {
168 out.push(Primitive::Segment { from: seg[0], to: seg[1], width, color });
169 }
170 if handles {
171 push_square(&mut out, m.output_center(sr), m.out_half, out_fill(src, true));
172 }
143173 }
144174 }
145 *count += 1;
146
147 let is_hot = self.hovered_wire.as_ref().is_some_and(|hw| hw.src == src_id && hw.dst == dst.id && hw.port == *port);
148 let is_sel = self.selected.contains(&src_id) || self.selected.contains(&dst.id);
149
150 let wire_col = if is_hot {
151 [0.98, 0.82, 0.24, 1.0]
152 } else if is_sel {
153 [0.92, 0.94, 0.98, 0.96]
154 } else {
155 [0.64, 0.66, 0.72, 0.76]
156 };
157 let width = if is_hot { 2.4 } else if is_sel { 1.6 } else { 1.1 };
158 let an = ae.normal();
159 let bn = be.normal();
160 let op = [a[0] + an[0] * (out_gap + out_half), a[1] + an[1] * (out_gap + out_half)];
161 let ip_base = [b[0] + bn[0] * tri_len, b[1] + bn[1] * tri_len];
162
163 // Straight wire directly from output square center to input triangle base (exact Fusion look!)
164 out.push(Primitive::Segment { from: op, to: ip_base, width, color: wire_col });
165
166 if self.zoom >= 0.36 {
167 // Output port: crisp Fusion white square `□` with thin dark outline
168 out.push(Primitive::RoundedRect {
169 rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half],
170 radius: 0.6,
171 stroke: None,
172 color: [0.94, 0.95, 0.98, 0.98],
173 });
174 out.push(Primitive::RoundedRect {
175 rect: [op[0] - out_half, op[1] - out_half, op[0] + out_half, op[1] + out_half],
176 radius: 0.6,
177 stroke: Some(0.9),
178 color: port_outline,
179 });
180
181 // Input port: crisp Fusion colored triangle pointing INTO `dst`!
182 let pcol = port_color(role);
183 let tri = input_arrow_svg(be, large_ports);
184 out.push(Primitive::Path {
185 data: tri,
186 origin: b,
187 style: PathStyle::Fill,
188 color: pcol,
189 });
190 out.push(Primitive::Path {
191 data: tri,
192 origin: b,
193 style: PathStyle::Stroke(0.9),
194 color: port_outline,
195 });
175 if handles && dst_vis {
176 let target = self.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).filter(|t| t.node == dst.id && t.port == slot.port);
177 let hot = target.is_some() || self.hovered_handle.as_ref().is_some_and(|hh| hh.node == dst.id && hh.port.as_deref() == Some(slot.port));
178 let tri = input_arrow_svg(slot.edge, large);
179 let fill = if slot.src.is_some() || hot { slot.color } else { [slot.color[0], slot.color[1], slot.color[2], 0.78] };
180 out.push(Primitive::Path { data: tri, origin: slot.tip, style: PathStyle::Fill, color: fill });
181 let (outline, outline_w) = match target {
182 Some(t) if t.cycle => ([0.96, 0.30, 0.34, 1.0], 1.6),
183 _ if hot => ([1.0, 1.0, 1.0, 1.0], 1.4),
184 _ => ([0.04, 0.04, 0.06, 0.92], 0.9),
185 };
186 out.push(Primitive::Path { data: tri, origin: slot.tip, style: PathStyle::Stroke(outline_w), color: outline });
196187 }
197 }
188 });
198189 }
199190
200 // Active wire drag preview (smooth cubic bezier + cycle rejection feedback)
191 // Rubber-band wire from the output square, tinted by the hovered input's role
201192 if let Some(wd) = &self.wire_drag {
202193 if wd.src.0 < comp.nodes.len() {
203 let sr = self.node_rect_local(comp.node(wd.src).pos);
204 let edge = self.node_output_edge(comp, wd.src);
205 let a = edge.point_on_rect(sr, 0.5);
206 let (end, is_cycle, target_role) = match wd.target {
207 Some((dst, port, cycle)) if dst.0 < comp.nodes.len() => {
208 let role = PortRole::from_input_name(port);
209 let (_, _, b, _) = self.wire_endpoints(comp, wd.src, dst, role);
210 (b, cycle, Some(role))
211 }
212 _ => (wd.cursor_local, false, None),
194 let a = m.output_tip(self.node_rect_local(comp.node(wd.src).pos));
195 let slot = wd.target.as_ref().filter(|t| t.node.0 < comp.nodes.len()).and_then(|t| {
196 self.input_slot(comp, comp.node(t.node), &t.port)
197 });
198 let is_cycle = wd.target.as_ref().is_some_and(|t| t.cycle);
199 let (end, end_normal) = match &slot {
200 Some(s) => (s.base(m), s.edge.normal()),
201 None => (wd.cursor_local, [-1.0, 0.0]),
213202 };
214 let wire_col = if is_cycle {
215 [0.96, 0.30, 0.34, 1.0]
216 } else if let Some(role) = target_role {
217 port_color(role)
218 } else {
219 [0.98, 0.84, 0.30, 1.0]
203 let wire_col = match &slot {
204 _ if is_cycle => [0.96, 0.30, 0.34, 1.0],
205 Some(s) => s.color,
206 None => [0.98, 0.84, 0.30, 1.0],
220207 };
221 let pts = sample_preview_bezier(a, edge.normal(), end, 16);
208 let pts = sample_wire_bezier(a, [1.0, 0.0], end, end_normal, 16);
222209 for seg in pts.windows(2) {
223210 out.push(Primitive::Segment {
224211 from: seg[0],
......@@ -372,32 +359,23 @@ impl FlowView {
372359 }
373360 }
374361
375 // Fusion-style tiny viewer indicator pill underneath bottom-left (`● ○` for Viewer 1 / Viewer 2!)
362 // Fusion's viewer pill tucked under the bottom-left: left dot = Viewer 1, right dot = Viewer 2.
376363 if v1 || v2 {
377 let pw = 22.0;
378 let ph = 9.0;
379 let px = r[0] + 4.0;
380 let py = r[3] + 1.5;
364 let (px, py) = (r[0] + 4.0, r[3] + 1.0);
381365 out.push(Primitive::RoundedRect {
382 rect: [px, py, px + pw, py + ph],
366 rect: [px, py, px + 22.0, py + 9.0],
383367 radius: 3.0,
384368 stroke: None,
385369 color: [0.02, 0.02, 0.03, 0.92],
386370 });
387 let d1 = if v1 { [0.24, 0.90, 0.82, 1.0] } else { [0.26, 0.28, 0.34, 0.6] };
388 let d2 = if v2 { [0.98, 0.68, 0.28, 1.0] } else { [0.26, 0.28, 0.34, 0.6] };
389 out.push(Primitive::RoundedRect {
390 rect: [px + 3.5, py + 2.0, px + 8.5, py + 7.0],
391 radius: 2.5,
392 stroke: None,
393 color: d1,
394 });
395 out.push(Primitive::RoundedRect {
396 rect: [px + 13.0, py + 2.0, px + 18.0, py + 7.0],
397 radius: 2.5,
398 stroke: None,
399 color: d2,
400 });
371 for (dot, lit, color) in [(px + 3.5, v1, [0.24, 0.90, 0.82, 1.0]), (px + 13.0, v2, [0.98, 0.68, 0.28, 1.0])] {
372 let rect = [dot, py + 2.0, dot + 5.0, py + 7.0];
373 if lit {
374 out.push(Primitive::RoundedRect { rect, radius: 2.5, stroke: None, color });
375 } else {
376 out.push(Primitive::RoundedRect { rect, radius: 2.5, stroke: Some(1.0), color: [0.46, 0.48, 0.55, 0.9] });
377 }
378 }
401379 }
402380
403381 if n.bypassed {
......@@ -411,6 +389,36 @@ impl FlowView {
411389 }
412390 }
413391
392 // Port-name label for the hovered handle or wire-drop target
393 let label = match (&self.wire_drag, &self.hovered_handle) {
394 (Some(wd), _) => wd.target.as_ref().filter(|t| t.node.0 < comp.nodes.len()).and_then(|t| {
395 self.input_slot(comp, comp.node(t.node), &t.port).map(|s| (t.port.as_str(), s.base(m), s.edge.normal()))
396 }),
397 (None, Some(hh)) if hh.node.0 < comp.nodes.len() && handles => match &hh.port {
398 None => Some(("Output", m.output_tip(self.node_rect_local(comp.node(hh.node).pos)), [1.0, 0.0])),
399 Some(port) => self
400 .input_slot(comp, comp.node(hh.node), port)
401 .map(|s| (port.as_str(), s.base(m), s.edge.normal())),
402 },
403 _ => None,
404 };
405 if let Some((name, at, normal)) = label {
406 if let Some(layout) = self.badge_cache.get(name) {
407 let (pw, ph, gap) = (layout.width() + 10.0, 14.0, 3.0);
408 let x0 = if normal[0] < 0.0 { at[0] - gap - pw } else if normal[0] > 0.0 { at[0] + gap } else { at[0] - pw * 0.5 };
409 let y0 = if normal[1] < 0.0 { at[1] - gap - ph } else if normal[1] > 0.0 { at[1] + gap } else { at[1] - ph * 0.5 };
410 let rect = [x0, y0, x0 + pw, y0 + ph];
411 out.push(Primitive::RoundedRect { rect, radius: 3.0, stroke: None, color: [0.02, 0.02, 0.03, 0.94] });
412 out.push(Primitive::RoundedRect { rect, radius: 3.0, stroke: Some(0.8), color: [0.46, 0.48, 0.55, 0.9] });
413 out.push(Primitive::Text {
414 text: layout as &dyn Glyphs,
415 origin: [x0 + 5.0, y0 + (ph - layout.height()) * 0.5],
416 clip: Some(rect),
417 ink: [0.94, 0.95, 0.98, 1.0],
418 });
419 }
420 }
421
414422 // 5. Box select marquee
415423 if let Some(bs) = &self.box_select {
416424 let x0 = bs.start_local[0].min(bs.cur_local[0]);
......@@ -473,14 +481,10 @@ fn input_arrow_svg(edge: Edge, large: bool) -> &'static str {
473481 }
474482}
475483
476fn port_color(role: PortRole) -> [f32; 4] {
477 match role {
478 PortRole::Background => [0.94, 0.76, 0.26, 1.0], // Fusion gold
479 PortRole::Foreground => [0.34, 0.86, 0.46, 1.0], // Fusion green
480 PortRole::Mask => [0.32, 0.64, 0.98, 1.0], // Fusion blue
481 PortRole::Scene3D => [0.30, 0.86, 0.90, 1.0], // Cyan
482 PortRole::Aux => [0.74, 0.58, 0.90, 1.0], // Violet
483 }
484fn push_square(out: &mut Vec<Primitive<'_>>, c: [f32; 2], half: f32, fill: [f32; 4]) {
485 let rect = [c[0] - half, c[1] - half, c[0] + half, c[1] + half];
486 out.push(Primitive::RoundedRect { rect, radius: 0.6, stroke: None, color: fill });
487 out.push(Primitive::RoundedRect { rect, radius: 0.6, stroke: Some(0.9), color: [0.04, 0.04, 0.06, 0.92] });
484488}
485489
486490fn node_accent(kind: &str) -> [f32; 4] {
crates/flow/src/ports.rs created+675
......@@ -0,0 +1,675 @@
1//! Fusion-style node handles: a square output on every node's right edge and role-coloured
2//! input triangles that rotate onto whichever edge faces their upstream node.
3
4use super::*;
5use model::Node;
6
7/// Below this zoom handles are neither drawn nor hit.
8pub(crate) const HANDLE_MIN_ZOOM: f32 = 0.36;
9const HIT_IN: f32 = 9.0;
10const HIT_OUT: f32 = 10.0;
11/// Pointer this deep inside a node border grabs the node, never a handle.
12const BODY_INSET: f32 = 3.0;
13/// A wire dropped this close to a node body lands on its auto-picked port.
14const DROP_MARGIN: f32 = 6.0;
15const STUB: f32 = 6.0;
16
17const YELLOW: [f32; 4] = [0.91, 0.77, 0.23, 1.0];
18const GREEN: [f32; 4] = [0.42, 0.75, 0.23, 1.0];
19const BLUE: [f32; 4] = [0.23, 0.63, 0.91, 1.0];
20const GRAY: [f32; 4] = [0.80, 0.81, 0.86, 1.0];
21const PURPLE: [f32; 4] = [0.72, 0.50, 0.92, 1.0];
22
23static SCENE_INPUTS: [&str; 32] = [
24 "SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4", "SceneInput5", "SceneInput6", "SceneInput7", "SceneInput8",
25 "SceneInput9", "SceneInput10", "SceneInput11", "SceneInput12", "SceneInput13", "SceneInput14", "SceneInput15", "SceneInput16",
26 "SceneInput17", "SceneInput18", "SceneInput19", "SceneInput20", "SceneInput21", "SceneInput22", "SceneInput23", "SceneInput24",
27 "SceneInput25", "SceneInput26", "SceneInput27", "SceneInput28", "SceneInput29", "SceneInput30", "SceneInput31", "SceneInput32",
28];
29
30static INPUTS: [&str; 33] = [
31 "Input0", "Input1", "Input2", "Input3", "Input4", "Input5", "Input6", "Input7", "Input8", "Input9", "Input10", "Input11",
32 "Input12", "Input13", "Input14", "Input15", "Input16", "Input17", "Input18", "Input19", "Input20", "Input21", "Input22",
33 "Input23", "Input24", "Input25", "Input26", "Input27", "Input28", "Input29", "Input30", "Input31", "Input32",
34];
35
36/// Screen-pixel handle sizes; two steps so they stay crisp while the node bars scale.
37#[derive(Clone, Copy)]
38pub(crate) struct Metrics {
39 pub tri_len: f32,
40 pub tri_half: f32,
41 pub out_half: f32,
42 out_gap: f32,
43}
44
45impl Metrics {
46 pub(crate) fn at(zoom: f32) -> Self {
47 if zoom >= 0.72 {
48 Self { tri_len: 6.5, tri_half: 3.6, out_half: 2.8, out_gap: 2.2 }
49 } else {
50 Self { tri_len: 4.5, tri_half: 2.6, out_half: 2.0, out_gap: 1.5 }
51 }
52 }
53
54 pub(crate) fn large(zoom: f32) -> bool {
55 zoom >= 0.72
56 }
57
58 pub(crate) fn output_center(self, r: [f32; 4]) -> [f32; 2] {
59 [r[2] + self.out_gap + self.out_half, (r[1] + r[3]) * 0.5]
60 }
61
62 /// Where a wire leaves the output square.
63 pub(crate) fn output_tip(self, r: [f32; 4]) -> [f32; 2] {
64 let c = self.output_center(r);
65 [c[0] + self.out_half, c[1]]
66 }
67}
68
69/// One input triangle of a node, in canvas-local pixels.
70#[derive(Clone, Copy, Debug)]
71pub(crate) struct Slot<'a> {
72 pub port: &'a str,
73 pub color: [f32; 4],
74 pub edge: Edge,
75 /// Triangle tip, flush on the node border.
76 pub tip: [f32; 2],
77 pub src: Option<NodeId>,
78}
79
80impl Slot<'_> {
81 /// Centre of the triangle's base, where the wire attaches.
82 pub(crate) fn base(&self, m: Metrics) -> [f32; 2] {
83 let n = self.edge.normal();
84 [self.tip[0] + n[0] * m.tri_len, self.tip[1] + n[1] * m.tri_len]
85 }
86
87 pub(crate) fn center(&self, m: Metrics) -> [f32; 2] {
88 let n = self.edge.normal();
89 let d = m.tri_len * 0.45;
90 [self.tip[0] + n[0] * d, self.tip[1] + n[1] * d]
91 }
92}
93
94#[derive(Clone, Copy, PartialEq, Eq)]
95enum Class {
96 Generator,
97 TwoInput,
98 Single,
99}
100
101#[derive(Clone, Copy)]
102enum Table {
103 Fixed(&'static [&'static str]),
104 /// Connected ports plus the first free one.
105 Grow(&'static [&'static str]),
106 /// One main input and an `EffectMask`.
107 Masked(&'static str),
108}
109
110fn zero_indexed(n: &Node) -> bool {
111 n.inputs.contains_key("Source") || n.inputs.contains_key("Input0") || !n.inputs.contains_key("Which")
112}
113
114fn table(n: &Node) -> (Table, Class) {
115 use Class::*;
116 match n.kind.as_str() {
117 "Merge" | "Dissolve" | "ChannelBoolean" => (Table::Fixed(&["Background", "Foreground", "EffectMask"]), TwoInput),
118 "Displace" => (Table::Fixed(&["Input", "Foreground", "EffectMask"]), TwoInput),
119 "Background" | "FastNoise" | "TextPlus" | "Loader" | "EllipseMask" | "RectangleMask" | "PolylineMask" => {
120 (Table::Fixed(&["EffectMask"]), Generator)
121 }
122 "Renderer3D" | "Transform3D" | "ReplaceMaterial3D" | "Override3D" | "ReplaceNormals3D" | "Displace3D" | "Duplicate3D" => {
123 (Table::Fixed(&["SceneInput"]), Single)
124 }
125 "Merge3D" => (Table::Grow(&SCENE_INPUTS), Single),
126 "sMerge" | "pMerge" | "Fuse.Switch" => (Table::Grow(&INPUTS[1..]), Single),
127 "sBoolean" => (Table::Grow(&INPUTS[1..=2]), Single),
128 "Switch" => (Table::Grow(if zero_indexed(n) { &INPUTS[..] } else { &INPUTS[1..] }), Single),
129 "BitmapMask" => (Table::Fixed(&["Image"]), Single),
130 "ImagePlane3D" | "TextureTransformOperator" => (Table::Fixed(&["MaterialInput"]), Single),
131 "Saver" | "PipeRouter" => (Table::Fixed(&["Input"]), Single),
132 "MacroOperator" | "GroupOperator" => (Table::Fixed(&["MainInput1"]), Single),
133 kind => (Table::Masked(default_main_input_port(kind)), Single),
134 }
135}
136
137/// Port a wire dropped on `n`'s body lands on: the first open main port.
138pub(crate) fn drop_port(n: &Node) -> &'static str {
139 let (table, class) = table(n);
140 let free = |p: &&'static str| n.inputs.get(*p).is_none_or(|b| b.source_op.is_none());
141 match table {
142 Table::Masked(main) => main,
143 Table::Fixed(l) if class == Class::TwoInput => l[..2].iter().find(|p| free(p)).copied().unwrap_or(l[0]),
144 Table::Fixed(l) => l[0],
145 Table::Grow(l) => l.iter().find(|p| free(p)).copied().unwrap_or(l[l.len() - 1]),
146 }
147}
148
149/// Calls `f` for every input port to show on `n`: the declared ports, then any other connected ones.
150fn each_port<'a>(n: &'a Node, table: Table, mut f: impl FnMut(&'a str)) {
151 let connected = |p: &str| n.inputs.get(p).is_some_and(|b| b.source_op.is_some());
152 match table {
153 Table::Fixed(l) => l.iter().for_each(|p| f(p)),
154 Table::Grow(l) => {
155 let mut free_shown = false;
156 for p in l {
157 if connected(p) {
158 f(p);
159 } else if !free_shown {
160 free_shown = true;
161 f(p);
162 }
163 }
164 }
165 Table::Masked(main) => {
166 f(main);
167 f("EffectMask");
168 }
169 }
170 let declared = |p: &str| match table {
171 Table::Fixed(l) | Table::Grow(l) => l.contains(&p),
172 Table::Masked(main) => p == main || p == "EffectMask",
173 };
174 let mut extras: Vec<&str> = n
175 .inputs
176 .iter()
177 .filter(|(p, b)| b.source_op.is_some() && !declared(p))
178 .map(|(p, _)| p.as_str())
179 .collect();
180 extras.sort_unstable();
181 extras.into_iter().for_each(f);
182}
183
184fn port_color(n: &Node, port: &str) -> [f32; 4] {
185 match port {
186 "Input0" | "MaterialInput" => YELLOW,
187 "Input1" if n.kind == "Switch" && zero_indexed(n) => GREEN,
188 "Input1" => YELLOW,
189 "Input2" | "SceneInput2" => GREEN,
190 "GarbageMatte" | "SolidMatte" => GRAY,
191 _ => match PortRole::from_input_name(port) {
192 PortRole::Background => YELLOW,
193 PortRole::Foreground => GREEN,
194 PortRole::Mask => BLUE,
195 PortRole::Scene3D if port == "SceneInput" || port == "SceneInput1" => YELLOW,
196 PortRole::Scene3D => PURPLE,
197 PortRole::Aux => GRAY,
198 },
199 }
200}
201
202/// Fusion's resting side for an input that has no upstream to face.
203fn default_edge(class: Class, role: PortRole) -> Edge {
204 match (class, role) {
205 (Class::TwoInput, PortRole::Foreground) | (Class::Single, PortRole::Mask) => Edge::Top,
206 (Class::TwoInput, PortRole::Mask) => Edge::Bottom,
207 _ => Edge::Left,
208 }
209}
210
211/// Picks the node edge facing vector `(dx, dy)`, biased for the bar's wide aspect.
212pub(crate) fn closest_edge(dx: f32, dy: f32) -> Edge {
213 if dx.abs() * 0.58 >= dy.abs() {
214 if dx >= 0.0 { Edge::Right } else { Edge::Left }
215 } else if dy >= 0.0 {
216 Edge::Bottom
217 } else {
218 Edge::Top
219 }
220}
221
222/// Polyline a wire follows from an output square to an input triangle.
223#[derive(Clone, Copy, Debug)]
224pub(crate) struct Route {
225 pts: [[f32; 2]; 6],
226 len: usize,
227}
228
229impl Route {
230 pub(crate) fn points(&self) -> &[[f32; 2]] {
231 &self.pts[..self.len]
232 }
233}
234
235fn within(p: [f32; 2], r: [f32; 4], margin: f32) -> bool {
236 p[0] >= r[0] - margin && p[0] <= r[2] + margin && p[1] >= r[1] - margin && p[1] <= r[3] + margin
237}
238
239fn dist2(a: [f32; 2], b: [f32; 2]) -> f32 {
240 (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)
241}
242
243/// Liang–Barsky segment/rect overlap.
244pub(crate) fn segment_hits_rect(a: [f32; 2], b: [f32; 2], r: [f32; 4]) -> bool {
245 let d = [b[0] - a[0], b[1] - a[1]];
246 let (mut t0, mut t1) = (0.0_f32, 1.0_f32);
247 for (p, q) in [(-d[0], a[0] - r[0]), (d[0], r[2] - a[0]), (-d[1], a[1] - r[1]), (d[1], r[3] - a[1])] {
248 if p == 0.0 {
249 if q < 0.0 {
250 return false;
251 }
252 } else {
253 let t = q / p;
254 if p < 0.0 { t0 = t0.max(t) } else { t1 = t1.min(t) }
255 if t0 > t1 {
256 return false;
257 }
258 }
259 }
260 true
261}
262
263impl FlowView {
264 pub(crate) fn upstream_of(&self, comp: &Comp, n: &Node, port: &str) -> Option<NodeId> {
265 let src = n.inputs.get(port)?.source_op.as_deref()?;
266 self.scope.resolve(comp, src)
267 }
268
269 /// Calls `f` for each input triangle of `n`, placed on the edge facing its upstream node
270 /// (or Fusion's default side when open) and spread along that edge so none overlap.
271 pub(crate) fn for_each_input<'a>(&self, comp: &Comp, n: &'a Node, mut f: impl FnMut(Slot<'a>)) {
272 let (table, class) = table(n);
273 let m = Metrics::at(self.zoom);
274 let r = self.node_rect_local(n.pos);
275 let (cx, cy) = ((r[0] + r[2]) * 0.5, (r[1] + r[3]) * 0.5);
276
277 // The two right-edge lanes flank the output square; a third crowds onto top/bottom instead.
278 let place = |port: &str, lanes: &mut [bool; 2]| -> (Option<NodeId>, Edge, usize) {
279 let Some(src) = self.upstream_of(comp, n, port) else {
280 return (None, default_edge(class, PortRole::from_input_name(port)), 0);
281 };
282 let sp = comp.node(src).pos;
283 let (dx, dy) = (sp[0] - n.pos[0], sp[1] - n.pos[1]);
284 match closest_edge(dx, dy) {
285 Edge::Right => {
286 let want = usize::from(dy >= 0.0);
287 match [want, 1 - want].into_iter().find(|&l| !lanes[l]) {
288 Some(lane) => {
289 lanes[lane] = true;
290 (Some(src), Edge::Right, lane)
291 }
292 None => (Some(src), if want == 1 { Edge::Bottom } else { Edge::Top }, 0),
293 }
294 }
295 edge => (Some(src), edge, 0),
296 }
297 };
298
299 let mut counts = [0_usize; 4];
300 let mut lanes = [false; 2];
301 each_port(n, table, |port| counts[place(port, &mut lanes).1 as usize] += 1);
302
303 let along = |center: f32, span: f32, i: usize, count: usize| {
304 let pitch = (span / count as f32).max(2.0 * m.tri_half + 1.0);
305 center + (i as f32 - (count as f32 - 1.0) * 0.5) * pitch
306 };
307 let lane_offset = m.out_half + m.tri_half + 1.0;
308 let mut seen = [0_usize; 4];
309 let mut lanes = [false; 2];
310 each_port(n, table, |port| {
311 let (src, edge, lane) = place(port, &mut lanes);
312 let (i, count) = (seen[edge as usize], counts[edge as usize]);
313 seen[edge as usize] += 1;
314 let tip = match edge {
315 Edge::Left => [r[0], along(cy, r[3] - r[1], i, count)],
316 Edge::Top => [along(cx, r[2] - r[0], i, count), r[1]],
317 Edge::Bottom => [along(cx, r[2] - r[0], i, count), r[3]],
318 Edge::Right => [r[2], cy + if lane == 1 { lane_offset } else { -lane_offset }],
319 };
320 f(Slot { port, color: port_color(n, port), edge, tip, src });
321 });
322 }
323
324 pub(crate) fn input_slot<'a>(&self, comp: &Comp, n: &'a Node, port: &str) -> Option<Slot<'a>> {
325 let mut found = None;
326 self.for_each_input(comp, n, |s| {
327 if s.port == port {
328 found = Some(s);
329 }
330 });
331 found
332 }
333
334 /// Straight from output square to input triangle; otherwise an elbow, otherwise a loop over or
335 /// under both nodes, so a wire never cuts through either body.
336 pub(crate) fn wire_route(&self, src_rect: [f32; 4], dst_rect: [f32; 4], slot: &Slot) -> Route {
337 let m = Metrics::at(self.zoom);
338 let p0 = m.output_tip(src_rect);
339 let q0 = slot.base(m);
340 let n = slot.edge.normal();
341 let p1 = [p0[0] + STUB, p0[1]];
342 let q1 = [q0[0] + n[0] * STUB, q0[1] + n[1] * STUB];
343 let inset = |r: [f32; 4]| [r[0] + 1.0, r[1] + 1.0, r[2] - 1.0, r[3] - 1.0];
344 let (sr, dr) = (inset(src_rect), inset(dst_rect));
345 let clear = |r: &Route| r.points().windows(2).all(|s| !segment_hits_rect(s[0], s[1], sr) && !segment_hits_rect(s[0], s[1], dr));
346
347 let straight = Route { pts: [p0, q0, q0, q0, q0, q0], len: 2 };
348 if clear(&straight) {
349 return straight;
350 }
351 let elbow = Route { pts: [p0, p1, [p1[0], q1[1]], q1, q0, q0], len: 5 };
352 if clear(&elbow) {
353 return elbow;
354 }
355 let dcy = (dst_rect[1] + dst_rect[3]) * 0.5;
356 let up = slot.edge == Edge::Top || (slot.edge != Edge::Bottom && slot.tip[1] <= dcy);
357 let margin = m.tri_len + STUB + 3.0;
358 let y = if up { src_rect[1].min(dst_rect[1]) - margin } else { src_rect[3].max(dst_rect[3]) + margin };
359 Route { pts: [p0, p1, [p1[0], y], [q1[0], y], q1, q0], len: 6 }
360 }
361
362 /// Extra pixels around a node's rect that its handles can reach.
363 fn handle_reach(&self, n: &Node) -> f32 {
364 let m = Metrics::at(self.zoom);
365 let grow = if matches!(table(n).0, Table::Grow(_)) { n.inputs.len() as f32 * 4.5 } else { 0.0 };
366 HIT_IN + m.tri_len + 4.0 + grow
367 }
368
369 /// Output square (`None` port) or input triangle under `local`. A node body always wins.
370 pub(crate) fn hit_handle<'a>(&self, comp: &'a Comp, local: [f32; 2]) -> Option<(NodeId, Option<&'a str>)> {
371 if self.zoom < HANDLE_MIN_ZOOM {
372 return None;
373 }
374 let m = Metrics::at(self.zoom);
375 for n in comp.nodes.iter().rev().filter(|n| self.scope.shows(n)) {
376 let r = self.node_rect_local(n.pos);
377 if !within(local, r, self.handle_reach(n).max(HIT_OUT)) {
378 continue;
379 }
380 if within(local, r, -BODY_INSET) {
381 return None;
382 }
383 let d = dist2(local, m.output_center(r));
384 let mut best = (d <= HIT_OUT * HIT_OUT).then_some((d, None));
385 self.for_each_input(comp, n, |s| {
386 let d = dist2(local, s.center(m));
387 if d <= HIT_IN * HIT_IN && best.is_none_or(|(b, _)| d < b) {
388 best = Some((d, Some(s.port)));
389 }
390 });
391 if let Some((_, port)) = best {
392 return Some((n.id, port));
393 }
394 }
395 None
396 }
397
398 /// Port a wire released at `local` lands on: an input triangle, else the auto-picked port of
399 /// the node body underneath.
400 pub(crate) fn hit_drop_target<'a>(&self, comp: &'a Comp, local: [f32; 2]) -> Option<(NodeId, &'a str)> {
401 let m = Metrics::at(self.zoom);
402 for n in comp.nodes.iter().rev().filter(|n| self.scope.shows(n)) {
403 let r = self.node_rect_local(n.pos);
404 if self.zoom >= HANDLE_MIN_ZOOM && within(local, r, self.handle_reach(n)) {
405 let mut best: Option<(f32, &str)> = None;
406 self.for_each_input(comp, n, |s| {
407 let d = dist2(local, s.center(m));
408 if d <= HIT_IN * HIT_IN && best.is_none_or(|(b, _)| d < b) {
409 best = Some((d, s.port));
410 }
411 });
412 if let Some((_, port)) = best {
413 return Some((n.id, port));
414 }
415 }
416 if within(local, r, DROP_MARGIN) {
417 return Some((n.id, drop_port(n)));
418 }
419 }
420 None
421 }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427
428 fn comp(src: &str) -> Comp {
429 Comp::from_fusion_str(&format!("Composition {{ Tools = ordered() {{ {src} }} }}")).expect("parse comp")
430 }
431
432 fn port(comp: &Comp, name: &str) -> &'static str {
433 drop_port(comp.node(comp.find_node(name).unwrap()))
434 }
435
436 fn view() -> FlowView {
437 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
438 flow.size = [800.0, 600.0];
439 flow
440 }
441
442 fn slots(flow: &FlowView, comp: &Comp, name: &str) -> Vec<(String, Edge, [f32; 2], Option<NodeId>)> {
443 let mut out = Vec::new();
444 flow.for_each_input(comp, comp.node(comp.find_node(name).unwrap()), |s| out.push((s.port.to_owned(), s.edge, s.tip, s.src)));
445 out
446 }
447
448 fn edge_of(slots: &[(String, Edge, [f32; 2], Option<NodeId>)], port: &str) -> Edge {
449 slots.iter().find(|s| s.0 == port).unwrap_or_else(|| panic!("no slot {port}")).1
450 }
451
452 /// Bounding box of the triangle on `edge` with its tip at `tip`.
453 fn tri_box(m: Metrics, edge: Edge, tip: [f32; 2]) -> [f32; 4] {
454 let b = Slot { port: "", color: YELLOW, edge, tip, src: None }.base(m);
455 let (lo, hi) = ([tip[0].min(b[0]), tip[1].min(b[1])], [tip[0].max(b[0]), tip[1].max(b[1])]);
456 if edge.normal()[0] == 0.0 {
457 [lo[0] - m.tri_half, lo[1], hi[0] + m.tri_half, hi[1]]
458 } else {
459 [lo[0], lo[1] - m.tri_half, hi[0], hi[1] + m.tri_half]
460 }
461 }
462
463 fn overlaps(a: [f32; 4], b: [f32; 4]) -> bool {
464 a[0] < b[2] && a[2] > b[0] && a[1] < b[3] && a[3] > b[1]
465 }
466
467 #[test]
468 fn single_input_kinds_use_engine_port_names() {
469 let c = comp(
470 "R = Renderer3D { }, D = Displace { }, CB = ChannelBoolean { }, Dis = Dissolve { },
471 BM = BitmapMask { }, T = Transform3D { }, Plane = ImagePlane3D { }, G = Background { }",
472 );
473 assert_eq!(port(&c, "R"), "SceneInput");
474 assert_eq!(port(&c, "D"), "Input");
475 assert_eq!(port(&c, "CB"), "Background");
476 assert_eq!(port(&c, "Dis"), "Background");
477 assert_eq!(port(&c, "BM"), "Image");
478 assert_eq!(port(&c, "T"), "SceneInput");
479 assert_eq!(port(&c, "Plane"), "MaterialInput");
480 assert_eq!(port(&c, "G"), "EffectMask");
481 }
482
483 #[test]
484 fn body_drops_take_the_first_open_main_port() {
485 let c = comp(
486 r#"A = Background { },
487 M = Merge { Inputs = { Background = Input { SourceOp = "A", Source = "Output" } } },
488 Full = Merge { Inputs = { Background = Input { SourceOp = "A", Source = "Output" },
489 Foreground = Input { SourceOp = "A", Source = "Output" } } },
490 D = Displace { Inputs = { Input = Input { SourceOp = "A", Source = "Output" } } }"#,
491 );
492 assert_eq!(port(&c, "M"), "Foreground");
493 assert_eq!(port(&c, "Full"), "Background");
494 assert_eq!(port(&c, "D"), "Foreground");
495 }
496
497 #[test]
498 fn multi_input_kinds_pick_next_free_port() {
499 let c = comp(
500 r#"A = Background { }, B = Background { },
501 M3 = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output" } } },
502 M3b = Merge3D { },
503 S = Switch { Inputs = { Input0 = Input { SourceOp = "A", Source = "Output" } } },
504 SW = Switch { Inputs = { Which = Input { Value = 1 } } },
505 SB = sBoolean { Inputs = { Input1 = Input { SourceOp = "A", Source = "Output" } } },
506 SB0 = sBoolean { },
507 FS = Fuse.Switch { }"#,
508 );
509 assert_eq!(port(&c, "M3b"), "SceneInput1");
510 assert_eq!(port(&c, "M3"), "SceneInput2");
511 assert_eq!(port(&c, "S"), "Input1");
512 assert_eq!(port(&c, "SW"), "Input1");
513 assert_eq!(port(&c, "SB"), "Input2");
514 assert_eq!(port(&c, "SB0"), "Input1");
515 assert_eq!(port(&c, "FS"), "Input1");
516 }
517
518 #[test]
519 fn native_switch_without_which_starts_at_input0() {
520 let c = comp("S = Switch { }");
521 assert_eq!(port(&c, "S"), "Input0");
522 }
523
524 #[test]
525 fn unconnected_inputs_rest_on_fusion_sides() {
526 let c = comp("Blur1 = Blur { }, Merge1 = Merge { }, Gen = FastNoise { }, Sv = Saver { }");
527 let flow = view();
528
529 let blur = slots(&flow, &c, "Blur1");
530 assert_eq!(blur.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["Input", "EffectMask"]);
531 assert_eq!((edge_of(&blur, "Input"), edge_of(&blur, "EffectMask")), (Edge::Left, Edge::Top));
532
533 let merge = slots(&flow, &c, "Merge1");
534 assert_eq!(edge_of(&merge, "Background"), Edge::Left);
535 assert_eq!(edge_of(&merge, "Foreground"), Edge::Top);
536 assert_eq!(edge_of(&merge, "EffectMask"), Edge::Bottom);
537
538 assert_eq!(slots(&flow, &c, "Gen").iter().map(|s| (s.0.as_str(), s.1)).collect::<Vec<_>>(), [("EffectMask", Edge::Left)]);
539 assert_eq!(slots(&flow, &c, "Sv").len(), 1);
540 }
541
542 #[test]
543 fn roles_map_to_fusion_colors() {
544 let c = comp(
545 r#"M = Merge { }, S = Switch { }, SB = sBoolean { }, M3 = Merge3D { },
546 B = Blur { Inputs = { GarbageMatte = Input { SourceOp = "M", Source = "Output" } } }"#,
547 );
548 let color = |name: &str, p: &str| port_color(c.node(c.find_node(name).unwrap()), p);
549 assert_eq!(color("M", "Background"), YELLOW);
550 assert_eq!(color("M", "Foreground"), GREEN);
551 assert_eq!(color("M", "EffectMask"), BLUE);
552 assert_eq!((color("S", "Input0"), color("S", "Input1")), (YELLOW, GREEN));
553 assert_eq!((color("SB", "Input1"), color("SB", "Input2")), (YELLOW, GREEN));
554 assert_eq!((color("M3", "SceneInput1"), color("M3", "SceneInput2"), color("M3", "SceneInput3")), (YELLOW, GREEN, PURPLE));
555 assert_eq!(color("B", "GarbageMatte"), GRAY);
556 }
557
558 #[test]
559 fn connected_inputs_face_their_upstream_across_all_quadrants() {
560 let flow = view();
561 // (upstream offset from the Blur, expected edge)
562 let cases: [([f32; 2], Edge); 8] = [
563 ([-110.0, 0.0], Edge::Left),
564 ([-110.0, -55.0], Edge::Left),
565 ([-40.0, -80.0], Edge::Top),
566 ([0.0, -60.0], Edge::Top),
567 ([40.0, 80.0], Edge::Bottom),
568 ([0.0, 60.0], Edge::Bottom),
569 ([110.0, -20.0], Edge::Right),
570 ([110.0, 20.0], Edge::Right),
571 ];
572 for (off, expected) in cases {
573 let c = comp(&format!(
574 r#"Up = Background {{ ViewInfo = OperatorInfo {{ Pos = {{ {}, {} }} }} }},
575 Blur1 = Blur {{ Inputs = {{ Input = Input {{ SourceOp = "Up", Source = "Output" }} }},
576 ViewInfo = OperatorInfo {{ Pos = {{ 0, 0 }} }} }}"#,
577 off[0], off[1]
578 ));
579 let s = slots(&flow, &c, "Blur1");
580 assert_eq!(edge_of(&s, "Input"), expected, "upstream at {off:?}");
581
582 let (up, blur) = (c.find_node("Up").unwrap(), c.find_node("Blur1").unwrap());
583 let (sr, dr) = (flow.node_rect_local(c.node(up).pos), flow.node_rect_local(c.node(blur).pos));
584 let m = Metrics::at(flow.zoom);
585 let slot = flow.input_slot(&c, c.node(blur), "Input").unwrap();
586 let route = flow.wire_route(sr, dr, &slot);
587 let shrink = |r: [f32; 4]| [r[0] + 1.5, r[1] + 1.5, r[2] - 1.5, r[3] - 1.5];
588 for seg in route.points().windows(2) {
589 assert!(!segment_hits_rect(seg[0], seg[1], shrink(sr)), "wire cuts the source body, upstream at {off:?}");
590 assert!(!segment_hits_rect(seg[0], seg[1], shrink(dr)), "wire cuts the consumer body, upstream at {off:?}");
591 }
592
593 let square = {
594 let c = m.output_center(dr);
595 [c[0] - m.out_half, c[1] - m.out_half, c[0] + m.out_half, c[1] + m.out_half]
596 };
597 for (_, edge, tip, _) in &s {
598 assert!(!overlaps(tri_box(m, *edge, *tip), square), "handle on {edge:?} hits the output square, upstream at {off:?}");
599 }
600 }
601 }
602
603 #[test]
604 fn crowded_edges_spread_without_overlap() {
605 let flow = view();
606 let c = comp(
607 r#"A = Background { ViewInfo = OperatorInfo { Pos = { -110, -30 } } },
608 B = Background { ViewInfo = OperatorInfo { Pos = { -110, 0 } } },
609 C = Background { ViewInfo = OperatorInfo { Pos = { -110, 30 } } },
610 R1 = Background { ViewInfo = OperatorInfo { Pos = { 110, 200 } } },
611 R2 = Background { ViewInfo = OperatorInfo { Pos = { 110, 210 } } },
612 R3 = Background { ViewInfo = OperatorInfo { Pos = { 110, 190 } } },
613 M3 = Merge3D {
614 Inputs = {
615 SceneInput1 = Input { SourceOp = "A", Source = "Output" },
616 SceneInput2 = Input { SourceOp = "B", Source = "Output" },
617 SceneInput3 = Input { SourceOp = "C", Source = "Output" },
618 },
619 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
620 },
621 Back = Merge {
622 Inputs = {
623 Background = Input { SourceOp = "R1", Source = "Output" },
624 Foreground = Input { SourceOp = "R2", Source = "Output" },
625 EffectMask = Input { SourceOp = "R3", Source = "Output" },
626 },
627 ViewInfo = OperatorInfo { Pos = { 0, 200 } },
628 }"#,
629 );
630 let m = Metrics::at(flow.zoom);
631 for name in ["M3", "Back"] {
632 let s = slots(&flow, &c, name);
633 for (i, a) in s.iter().enumerate() {
634 for b in &s[i + 1..] {
635 assert!(!overlaps(tri_box(m, a.1, a.2), tri_box(m, b.1, b.2)), "{name}: {} overlaps {}", a.0, b.0);
636 }
637 }
638 }
639 // Three upstreams plus the next free port all stack down the left edge.
640 let m3 = slots(&flow, &c, "M3");
641 assert_eq!(m3.iter().map(|s| s.0.as_str()).collect::<Vec<_>>(), ["SceneInput1", "SceneInput2", "SceneInput3", "SceneInput4"]);
642 assert!(m3.iter().all(|s| s.1 == Edge::Left));
643 assert!(m3.windows(2).all(|w| w[0].2[1] < w[1].2[1]));
644 // A third source on the right spills to top/bottom instead of crowding the output square.
645 let back = slots(&flow, &c, "Back");
646 assert_eq!(back.iter().filter(|s| s.1 == Edge::Right).count(), 2);
647 }
648
649 #[test]
650 fn hit_handle_finds_output_square_and_input_triangles() {
651 let flow = view();
652 let c = comp(
653 r#"Up = Background { ViewInfo = OperatorInfo { Pos = { -110, 0 } } },
654 M = Merge { Inputs = { Background = Input { SourceOp = "Up", Source = "Output" } },
655 ViewInfo = OperatorInfo { Pos = { 0, 0 } } }"#,
656 );
657 let (up, merge) = (c.find_node("Up").unwrap(), c.find_node("M").unwrap());
658 let m = Metrics::at(flow.zoom);
659 let ur = flow.node_rect_local(c.node(up).pos);
660 let mr = flow.node_rect_local(c.node(merge).pos);
661
662 assert_eq!(flow.hit_handle(&c, m.output_center(ur)), Some((up, None)));
663 for (p, want) in [("Background", Edge::Left), ("Foreground", Edge::Top), ("EffectMask", Edge::Bottom)] {
664 let s = flow.input_slot(&c, c.node(merge), p).unwrap();
665 assert_eq!(s.edge, want);
666 assert_eq!(flow.hit_handle(&c, s.center(m)), Some((merge, Some(p))), "{p}");
667 }
668 // A few pixels off the tip still grabs it; deep inside the body never does.
669 let bg = flow.input_slot(&c, c.node(merge), "Background").unwrap();
670 assert_eq!(flow.hit_handle(&c, [bg.tip[0] - 7.0, bg.tip[1] + 2.0]), Some((merge, Some("Background"))));
671 assert_eq!(flow.hit_handle(&c, [(mr[0] + mr[2]) * 0.5, (mr[1] + mr[3]) * 0.5]), None);
672 assert_eq!(flow.hit_handle(&c, [mr[0] + 6.0, (mr[1] + mr[3]) * 0.5]), None);
673 assert_eq!(flow.hit_handle(&c, [0.0, 0.0]), None);
674 }
675}