1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
use egui::Rect;
use re_format::format_f32;
use re_types::blueprint::components::VisualBounds2D;
use re_ui::UiExt;
use re_viewer_context::ViewState;

use crate::layout::{ForceLayoutParams, ForceLayoutProvider, Layout, LayoutRequest};

/// View state for the custom view.
///
/// This state is preserved between frames, but not across Viewer sessions.
#[derive(Default)]
pub struct GraphViewState {
    pub layout_state: LayoutState,
    pub visual_bounds: Option<VisualBounds2D>,
    pub rect_in_ui: Option<Rect>,
}

impl GraphViewState {
    pub fn layout_ui(&self, ui: &mut egui::Ui) {
        let Some(rect) = self.layout_state.bounding_rect() else {
            return;
        };
        ui.grid_left_hand_label("Bounding box")
            .on_hover_text("The bounding box encompassing all entities in the view right now");
        ui.vertical(|ui| {
            ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
            let egui::Rect { min, max } = rect;
            ui.label(format!("x [{} - {}]", format_f32(min.x), format_f32(max.x),));
            ui.label(format!("y [{} - {}]", format_f32(min.y), format_f32(max.y),));
        });
        ui.end_row();
    }

    pub fn simulation_ui(&mut self, ui: &mut egui::Ui) {
        if ui.button("Reset simulation").clicked() {
            self.layout_state.reset();
        }
    }
}

impl ViewState for GraphViewState {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }
}

/// The following is a simple state machine that keeps track of the different
/// layouts and if they need to be recomputed. It also holds the state of the
/// force-based simulation.
#[derive(Default)]
pub enum LayoutState {
    #[default]
    None,
    InProgress {
        layout: Layout,
        provider: ForceLayoutProvider,
        params: ForceLayoutParams,
    },
    Finished {
        layout: Layout,
        provider: ForceLayoutProvider,
        params: ForceLayoutParams,
    },
}

impl LayoutState {
    pub fn bounding_rect(&self) -> Option<Rect> {
        match self {
            Self::None => None,
            Self::Finished { layout, .. } | Self::InProgress { layout, .. } => {
                Some(layout.bounding_rect())
            }
        }
    }

    pub fn reset(&mut self) {
        *self = Self::None;
    }

    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    pub fn is_in_progress(&self) -> bool {
        matches!(self, Self::InProgress { .. })
    }

    /// A simple state machine that keeps track of the different stages and if the layout needs to be recomputed.
    fn update(self, new_request: LayoutRequest, new_params: ForceLayoutParams) -> Self {
        match self {
            // Layout is up to date, nothing to do here.
            Self::Finished {
                ref provider,
                ref params,
                ..
            } if (provider.request == new_request) && (params == &new_params) => {
                self // no op
            }
            // We need to recompute the layout.
            Self::None => {
                let mut provider = ForceLayoutProvider::new(new_request, &new_params);
                let layout = provider.tick();
                Self::InProgress {
                    layout,
                    provider,
                    params: new_params,
                }
            }
            Self::Finished { layout, .. } => {
                let mut provider =
                    ForceLayoutProvider::new_with_previous(new_request, &layout, &new_params);
                let layout = provider.tick();
                Self::InProgress {
                    layout,
                    provider,
                    params: new_params,
                }
            }
            Self::InProgress {
                layout, provider, ..
            } if provider.request != new_request => {
                let mut provider =
                    ForceLayoutProvider::new_with_previous(new_request, &layout, &new_params);
                let layout = provider.tick();

                Self::InProgress {
                    layout,
                    provider,
                    params: new_params,
                }
            }
            // We keep iterating on the layout until it is stable.
            Self::InProgress {
                mut provider,
                layout,
                params: old_params,
            } => match (provider.is_finished(), new_params == old_params) {
                (true, true) => Self::Finished {
                    layout,
                    provider,
                    params: new_params,
                },
                (false, true) => Self::InProgress {
                    layout: provider.tick(),
                    provider,
                    params: new_params,
                },
                _ => {
                    let mut provider =
                        ForceLayoutProvider::new_with_previous(new_request, &layout, &new_params);
                    let layout = provider.tick();

                    Self::InProgress {
                        layout,
                        provider,
                        params: new_params,
                    }
                }
            },
        }
    }

    /// This method is lazy. A new layout is only computed if the current timestamp requires it.
    pub fn get(&mut self, request: LayoutRequest, params: ForceLayoutParams) -> &mut Layout {
        *self = std::mem::take(self).update(request, params);

        match self {
            Self::Finished { layout, .. } | Self::InProgress { layout, .. } => layout,
            Self::None => unreachable!(), // We just set the state to `Self::Current` above.
        }
    }
}