rust_training_tool/
gui.rs

1//! Gui and main loop functionality.
2
3use eframe::{egui, egui::Key};
4use std::{
5    collections::HashSet,
6    time::{Duration, Instant},
7};
8
9/// The main function where your game logic is ran each frame.
10/// Takes in a `Context`.
11pub trait MainFunction: FnMut(Context, &mut egui::Ui) {}
12impl<T: FnMut(Context, &mut egui::Ui)> MainFunction for T {}
13
14/// The frame context the main logic is called with. Contains
15/// everything you need to update entities and render a frame.
16pub struct Context {
17    /// The time elapsed since last frame.
18    pub dt: Duration,
19    /// A set of all keys currently held down.
20    pub key_map: HashSet<Key>,
21    /// A painter which lets you draw shapes and text to the window.
22    pub painter: egui::Painter,
23    /// The size of the drawable region og the window in pixels.
24    pub drawable_area: egui::Rect,
25}
26
27struct Gui<F: MainFunction> {
28    main_function: F,
29    last_update: Instant,
30}
31
32impl<F: MainFunction> Gui<F> {
33    fn new(main_function: F) -> Self {
34        Self {
35            main_function,
36            last_update: Instant::now(),
37        }
38    }
39}
40
41/// The function which starts a window and calls the `main_function` each frame.
42/// `options` are passed to  `eframe::run_native`.
43///
44/// ### Example
45///
46/// ```
47/// # let _ = "
48/// use rust_training_tool::gui::run;
49/// # ";
50/// # use rust_training_tool::gui::__test_run as run;
51/// use rust_training_tool::{eframe, egui};
52///
53/// let options = eframe::NativeOptions {
54///     viewport: egui::ViewportBuilder::default()
55///         .with_inner_size([480.0, 360.0]),
56///     ..Default::default()
57/// };
58/// run(options, "test", |ctx, _ui| {
59///     ctx.painter.circle_filled(
60///         ctx.drawable_area.center(),
61///         ctx.drawable_area.width() * 0.1,
62///         egui::Color32::ORANGE,
63///     );
64/// })
65/// .expect("Gui should run");
66/// ```
67pub fn run<F>(options: eframe::NativeOptions, app_name: &str, main_function: F) -> eframe::Result
68where
69    F: MainFunction,
70{
71    eframe::run_native(
72        app_name,
73        options,
74        Box::new(|_cc| {
75            #[cfg(feature = "images")]
76            egui_extras::install_image_loaders(&_cc.egui_ctx);
77            Ok(Box::new(Gui::new(main_function)))
78        }),
79    )
80}
81
82/// Fake run function for use in doctests
83pub fn __test_run<F>(
84    _options: eframe::NativeOptions,
85    _app_name: &str,
86    _main_function: F,
87) -> eframe::Result
88where
89    F: MainFunction,
90{
91    Ok(())
92}
93
94impl<F: MainFunction> eframe::App for Gui<F> {
95    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
96        // update dt
97        let dt = self.last_update.elapsed();
98        self.last_update = Instant::now();
99
100        egui::CentralPanel::default()
101            .frame(egui::Frame::none())
102            .show(ctx, |ui| {
103                // create painter
104                let (response, painter) =
105                    ui.allocate_painter(ui.available_size(), egui::Sense::hover());
106
107                let key_map = ctx.input(|i| i.keys_down.clone());
108
109                (self.main_function)(
110                    Context {
111                        dt,
112                        key_map,
113                        drawable_area: response.rect,
114                        painter,
115                    },
116                    ui,
117                );
118            });
119
120        // update at 30 fps
121        ctx.request_repaint_after_secs(1.0 / 30.0);
122    }
123}