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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//! [`network_debug_session_plugin`] may be installed to open network diagnostics egui window:
//! - Graphs player's predicted frames
//! - Highlights freezes waiting for remote input (when reached max prediction window)
//! - Displays [`ggrs::NetworkStats`]
//! - Displays last frame with skips and how many frames were skipped.
//!
//! To display window, use `egui_ctx.set_state::<NetworkDebugMenuState>();` ( after setting open = true ).
#![allow(missing_docs)]

use async_channel::{Receiver, Sender};
use bones_asset::HasSchema;
use egui::CollapsingHeader;
use egui_plot::{Bar, BarChart, GridMark, Plot};
use ggrs::{NetworkStats, PlayerHandle};
use once_cell::sync::Lazy;

use crate::prelude::*;

pub mod prelude {
    pub use super::NetworkDebugMenuState;
}

/// Session plugin for network debug window. Is not installed by default.
/// After installing plugin, [`NetworkDebugMenuState`] on [`EguiCtx`] state
/// may be modified to open menu.
pub fn network_debug_session_plugin(session: &mut Session) {
    session.add_system_to_stage(CoreStage::First, network_debug_window);
}

pub enum PlayerSyncState {
    SyncInProgress,
    Sychronized,
}

/// Messages used by network debug channel
pub enum NetworkDebugMessage {
    /// Reset network diag on new session.
    ResetData,

    /// Notifies that frames were skipped, and the frame at start of net
    /// update loop containing skips.
    SkipFrame { frame: i32, count: u32 },
    /// Update with current frame and the last confirmed frame.
    FrameUpdate { current: i32, last_confirmed: i32 },
    /// Update that network update loop starting at this frame froze waiting
    /// for inputs from other clients after reaching max prediction window.
    FrameFroze { frame: i32 },
    /// Network stats per remote player
    NetworkStats {
        network_stats: Vec<(PlayerHandle, NetworkStats)>,
    },
    /// Set the max prediction window for y axis of plot
    SetMaxPrediction(usize),
    /// List of players that are disconnected
    DisconnectedPlayers(Vec<usize>),
    /// Update ggrs synchronization state of player
    PlayerSync((PlayerSyncState, PlayerHandle)),
}

/// Sender and receiver for [`NetworkDebugMessage`] for network diagnostics debug tool.
pub struct NetworkDebugChannel {
    pub receiver: Receiver<NetworkDebugMessage>,
    pub sender: Sender<NetworkDebugMessage>,
}

impl Default for NetworkDebugChannel {
    fn default() -> Self {
        let (sender, receiver) = async_channel::unbounded();
        Self { sender, receiver }
    }
}

#[allow(missing_docs)]
pub struct NetworkFrameData {
    /// How many frames we are predicted ahead of last confirmed frame?
    pub predicted_frames: i32,
    pub current_frame: i32,
    /// Did frame freeze waiting for other inputs?
    pub froze: bool,
}

impl NetworkFrameData {
    pub fn new(confirmed: i32, current: i32) -> Self {
        Self {
            // confirmed may be -1 on start of match.
            predicted_frames: current - std::cmp::max(confirmed, 0),
            current_frame: current,
            froze: false,
        }
    }
}

/// Data captured from networking for debugging purposes.
#[derive(HasSchema)]
#[schema(no_clone)]
pub struct NetworkDebug {
    /// Last confirmed frame
    pub confirmed_frame: i32,

    /// Current frame
    pub current_frame: i32,

    /// Amount of frames skipped on last update that had skips.
    pub last_skipped_frame_count: u32,

    /// Last frame of net update loop that had skipped frames.
    pub last_frame_with_skips: i32,

    /// buffer of net data over time
    pub frame_buffer: Vec<NetworkFrameData>,

    /// How many frames to display in bar graph visualizer
    pub frame_buffer_display_size: usize,

    /// Is network debug tool paused.
    pub paused: bool,

    /// Network stats per connection to remote player
    pub network_stats: Vec<(PlayerHandle, NetworkStats)>,

    /// Max Prediction Window set in ggrs session runner.
    /// Cached here to determine max y on plot.
    pub max_prediction_window: usize,

    /// List of player handles that have been disconnected
    pub disconnected_players: Vec<usize>,

    /// Track players that are synchronizing or synchronized. If player not listed,
    /// no sync has been attempted.
    pub player_sync_state: HashMap<PlayerHandle, PlayerSyncState>,
}

impl Default for NetworkDebug {
    fn default() -> Self {
        Self {
            confirmed_frame: 0,
            current_frame: 0,
            last_skipped_frame_count: 0,
            last_frame_with_skips: -1,
            frame_buffer: vec![],
            frame_buffer_display_size: 64,
            paused: false,
            network_stats: vec![],
            max_prediction_window: 0,
            disconnected_players: vec![],
            player_sync_state: default(),
        }
    }
}

impl NetworkDebug {
    /// Add frame data to [`NetworkDebug`]
    pub fn add_or_update_frame(&mut self, current: i32, confirmed: i32) {
        if let Some(last) = self.frame_buffer.last_mut() {
            if last.current_frame == current {
                // Frame already buffered.
                return;
            }
        }
        self.current_frame = current;
        self.confirmed_frame = confirmed;
        self.frame_buffer
            .push(NetworkFrameData::new(confirmed, current));
    }

    /// Set frame as having frozen
    pub fn set_frozen(&mut self, frame: i32) {
        let last = self.frame_buffer.last_mut().unwrap();
        if last.current_frame == frame {
            last.froze = true;
        }
    }
}

/// Used as state in [`EguiCtx`] such that a menu in bones
/// or game implementation may open the net debug window.
#[derive(Default, Clone)]
pub struct NetworkDebugMenuState {
    pub open: bool,
}

/// Async channel for sending debug messages from networking implementation
/// to debug tools.
pub static NETWORK_DEBUG_CHANNEL: Lazy<NetworkDebugChannel> =
    Lazy::new(NetworkDebugChannel::default);

/// System displaying network debug window
pub fn network_debug_window(
    // localization: Res<Localization<GameMeta>>,
    mut diagnostics: ResMutInit<NetworkDebug>,
    egui_ctx: ResMut<EguiCtx>,
) {
    let mut state = egui_ctx.get_state::<NetworkDebugMenuState>();
    let show = &mut state.open;

    if *show {
        while let Ok(message) = NETWORK_DEBUG_CHANNEL.receiver.try_recv() {
            if diagnostics.paused {
                continue;
            }
            match message {
                NetworkDebugMessage::ResetData => *diagnostics = NetworkDebug::default(),
                NetworkDebugMessage::SkipFrame { frame, count } => {
                    diagnostics.last_frame_with_skips = frame;
                    diagnostics.last_skipped_frame_count = count;
                }
                NetworkDebugMessage::FrameUpdate {
                    current,
                    last_confirmed: confirmed,
                } => {
                    diagnostics.add_or_update_frame(current, confirmed);
                }
                NetworkDebugMessage::FrameFroze { frame } => {
                    diagnostics.set_frozen(frame);
                }
                NetworkDebugMessage::NetworkStats { network_stats } => {
                    diagnostics.network_stats = network_stats;
                }
                NetworkDebugMessage::SetMaxPrediction(max_preiction_window) => {
                    diagnostics.max_prediction_window = max_preiction_window;
                }
                NetworkDebugMessage::DisconnectedPlayers(disconnected_players) => {
                    diagnostics.disconnected_players = disconnected_players;
                }
                NetworkDebugMessage::PlayerSync((sync_state, player)) => {
                    diagnostics.player_sync_state.insert(player, sync_state);
                }
            }
        }

        if *show {
            // let frame_localized = localization.get("frame");
            let frame_localized = "frame";
            // let predicted_localized = localization.get("predicted");
            let predicted_localized = "predicted";
            // egui::Window::new(&localization.get("network-diagnostics"))
            egui::Window::new("Network Diagnostics")
                .id(egui::Id::new("network-diagnostics"))
                .open(show)
                .show(&egui_ctx, |ui| {
                    ui.monospace(&format!(
                        "{label}: {current_frame}",
                        // label = localization.get("current-frame"),
                        label = "Current Frame",
                        current_frame = diagnostics.current_frame
                    ));
                    ui.monospace(&format!(
                        "{label}: {confirmed_frame}",
                        // label = localization.get("confirmed-frame"),
                        label = "Confirmed Frame",
                        confirmed_frame = diagnostics.confirmed_frame
                    ));

                    if diagnostics.last_frame_with_skips != -1 {
                        ui.monospace(&format!(
                            "{label}: {last_skip_frame}",
                            // label = localization.get("last-frame-with-skips"),
                            label = "Last Frame With Skips",
                            last_skip_frame = diagnostics.last_frame_with_skips
                        ));
                        ui.monospace(&format!(
                            "{label}: {skip_count}",
                            // label = localization.get("last-skipped-frame-count"),
                            label = "Last Skipped Frame Count",
                            skip_count = diagnostics.last_skipped_frame_count
                        ));
                    } else {
                        // ui.monospace(localization.get("no-frame-skips-detected"));
                        ui.monospace("No Frame Skips Detected");
                    }

                    let pause_label = if diagnostics.paused {
                        // localization.get("resume")
                        "resume"
                    } else {
                        // localization.get("pause")
                        "pause"
                    };
                    if ui.button(pause_label).clicked() {
                        diagnostics.paused = !diagnostics.paused;
                    }

                    let max_display_frame;
                    if let Some(last) = diagnostics.frame_buffer.last() {
                        max_display_frame = last.current_frame;
                    } else {
                        max_display_frame = diagnostics.frame_buffer_display_size as i32;
                    }
                    let min_display_frame =
                        max_display_frame - diagnostics.frame_buffer_display_size as i32;

                    let max_prediction_window = diagnostics.max_prediction_window;

                    // Plot::new(localization.get("predicted-frames"))
                    Plot::new("Predicted Frames")
                        .allow_zoom(false)
                        .allow_scroll(false)
                        .allow_boxed_zoom(false)
                        .include_x(min_display_frame)
                        .include_x(max_display_frame)
                        .auto_bounds_y()
                        .include_y(max_prediction_window as f64)
                        .show_axes([false, true])
                        .y_grid_spacer(move |_grid_input| {
                            (0..(max_prediction_window + 1))
                                .map(|y| GridMark {
                                    step_size: 1.0,
                                    value: y as f64,
                                })
                                .collect()
                        })
                        .label_formatter({
                            move |_name, value| {
                                let frame_floor = value.x as i32;
                                format!("{frame_localized}: {frame_floor}")
                            }
                        })
                        .height(128.0)
                        .show(ui, |plot_ui| {
                            plot_ui.bar_chart(
                                BarChart::new(
                                    diagnostics
                                        .frame_buffer
                                        .iter()
                                        .map(|frame| {
                                            let color = if frame.froze {
                                                egui::Color32::YELLOW
                                            } else {
                                                egui::Color32::LIGHT_BLUE
                                            };
                                            Bar::new(
                                                frame.current_frame as f64,
                                                frame.predicted_frames as f64,
                                            )
                                            .fill(color)
                                        })
                                        .collect(),
                                )
                                .width(1.0)
                                .element_formatter(Box::new(move |bar, _chart| {
                                    format!(
                                        "{frame_localized}: {} {predicted_localized}: {}",
                                        bar.argument as i32, bar.value as i32
                                    )
                                })),
                            );
                        });

                    for (player_handle, stats) in diagnostics.network_stats.iter() {
                        // let label = format!("{} {}", localization.get("player"), player_handle);
                        let label = format!("{} {}", "player", player_handle);
                        CollapsingHeader::new(label)
                            .default_open(true)
                            .show(ui, |ui| {
                                if diagnostics.disconnected_players.contains(player_handle) {
                                    ui.colored_label(Color::RED, "Disconnected!");
                                } else {
                                    match diagnostics.player_sync_state.get(player_handle) {
                                        Some(sync_state) => match sync_state {
                                            PlayerSyncState::SyncInProgress => {
                                                ui.colored_label(
                                                Color::ORANGE,
                                                "GGRS synchronization with player in progress...",
                                            );
                                            }
                                            PlayerSyncState::Sychronized => {
                                                ui.label("Synchronized with player.");
                                            }
                                        },
                                        None => {
                                            ui.colored_label(
                                                Color::RED,
                                                "Not synchronized with player.",
                                            );
                                        }
                                    }
                                }
                                ui.monospace(&format!("{stats:?}"));
                            });
                    }
                });
        }
    }

    egui_ctx.set_state(state);
}