Skip to main content

egui_pop_viewport/graph/
wires.rs

1//! How wires are drawn: curves, straight segments, or orthogonal routes
2//! around the nodes (by the `ortho-router` crate), the latter cached
3//! by layout.
4
5use egui::{Pos2, Rect, pos2};
6use ortho_router::{Connector, Options, Port, Router, Side};
7
8/// How a graph's wires are drawn ([`GraphEditor::wires`](super::GraphEditor::wires)).
9#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
10pub enum WireStyle {
11    /// Curves out of each port (the default): they may cross nodes.
12    #[default]
13    Curves,
14    /// Horizontal and vertical segments around the nodes, with few
15    /// bends; wires through one channel are spread apart.
16    Orthogonal,
17    /// A straight segment from port to port.
18    Straight,
19}
20
21impl WireStyle {
22    /// Every style, in the order a menu lists them.
23    pub const ALL: [WireStyle; 3] = [
24        WireStyle::Curves,
25        WireStyle::Orthogonal,
26        WireStyle::Straight,
27    ];
28
29    /// Its name in snapshots and steps: `curves`, `orthogonal`,
30    /// `straight`.
31    pub fn name(self) -> &'static str {
32        match self {
33            WireStyle::Curves => "curves",
34            WireStyle::Orthogonal => "orthogonal",
35            WireStyle::Straight => "straight",
36        }
37    }
38
39    /// The style of a name ([`name`](Self::name)).
40    pub fn from_name(name: &str) -> Option<WireStyle> {
41        WireStyle::ALL.into_iter().find(|s| s.name() == name)
42    }
43}
44
45/// How far routes keep from nodes, in graph units.
46const MARGIN: f32 = 14.0;
47/// What a bend costs, as a length in graph units.
48const BEND: f32 = 40.0;
49/// How far apart wires sharing a channel are drawn.
50const SPACING: f32 = 5.0;
51
52/// Orthogonal routes, computed again only when the layout changes.
53#[derive(Clone, Debug)]
54pub(crate) struct RouteCache {
55    router: Router,
56    /// The layout the routes are for.
57    key: Option<u64>,
58    routes: Vec<Vec<Pos2>>,
59    /// How many times routes were computed (for tests).
60    pub(crate) computed: u64,
61}
62
63impl Default for RouteCache {
64    fn default() -> Self {
65        RouteCache {
66            router: Router::new(Options {
67                margin: MARGIN,
68                bend_penalty: BEND,
69                spacing: SPACING,
70            }),
71            key: None,
72            routes: Vec::new(),
73            computed: 0,
74        }
75    }
76}
77
78fn point(p: Pos2) -> ortho_router::Point {
79    ortho_router::Point::new(p.x, p.y)
80}
81
82impl RouteCache {
83    /// The routes of `wires` (an output's position, then an input's)
84    /// around `boxes`: one polyline per wire, in order.
85    pub(crate) fn routes(&mut self, boxes: &[Rect], wires: &[(Pos2, Pos2)]) -> &[Vec<Pos2>] {
86        self.router.set_obstacles(
87            boxes
88                .iter()
89                .map(|r| ortho_router::Rect::from_corners(point(r.min), point(r.max))),
90        );
91        let connectors: Vec<Connector> = wires
92            .iter()
93            .map(|&(a, b)| {
94                Connector::new(
95                    Port::new(point(a), Side::Right),
96                    Port::new(point(b), Side::Left),
97                )
98            })
99            .collect();
100        let key = self.router.fingerprint(&connectors);
101        if self.key != Some(key) {
102            self.routes = self
103                .router
104                .route_all(&connectors)
105                .into_iter()
106                .map(|r| r.points.iter().map(|p| pos2(p.x, p.y)).collect())
107                .collect();
108            self.key = Some(key);
109            self.computed += 1;
110        }
111        &self.routes
112    }
113
114    /// Forgets the routes (the style changed away from orthogonal).
115    pub(crate) fn clear(&mut self) {
116        self.key = None;
117        self.routes.clear();
118    }
119}
120
121/// A rough orthogonal wire from an output at `a` to an input at `b`,
122/// for the wire being drawn: out, one elbow halfway, in.
123pub(crate) fn elbow(a: Pos2, b: Pos2) -> [Pos2; 4] {
124    let x = (a.x + b.x) / 2.0;
125    [a, pos2(x, a.y), pos2(x, b.y), b]
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn routes_are_computed_again_only_when_the_layout_changes() {
134        let mut cache = RouteCache::default();
135        let boxes = [
136            Rect::from_min_size(pos2(0.0, 0.0), egui::vec2(100.0, 60.0)),
137            Rect::from_min_size(pos2(300.0, 100.0), egui::vec2(100.0, 60.0)),
138        ];
139        let wires = [(pos2(100.0, 30.0), pos2(300.0, 130.0))];
140        let first = cache.routes(&boxes, &wires).to_vec();
141        assert_eq!(cache.computed, 1);
142        assert_eq!(cache.routes(&boxes, &wires), first.as_slice());
143        assert_eq!(cache.computed, 1, "the same layout: from the cache");
144        let moved = [boxes[0], boxes[1].translate(egui::vec2(0.0, 10.0))];
145        let wires = [(pos2(100.0, 30.0), pos2(300.0, 140.0))];
146        let r = cache.routes(&moved, &wires)[0].clone();
147        assert_eq!(cache.computed, 2);
148        assert_eq!(r.first(), Some(&pos2(100.0, 30.0)));
149        assert_eq!(r.last(), Some(&pos2(300.0, 140.0)));
150        assert!(r.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y));
151    }
152
153    #[test]
154    fn styles_have_names() {
155        for s in WireStyle::ALL {
156            assert_eq!(WireStyle::from_name(s.name()), Some(s));
157        }
158        assert_eq!(WireStyle::default(), WireStyle::Curves);
159    }
160}