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
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
#![warn(missing_docs)]

/*
Possible TODO:
* add PixelsBuilder customization
*/

use cfg_if::cfg_if;
use pixels::SurfaceTexture;
use std::rc::Rc;
use winit::{
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
    window::Window,
};

use web_time::Instant;

mod error;
pub use error::{Error, Result};

mod input;
pub use input::{Input, InputState};

#[doc(no_inline)]
pub use pixels;
#[doc(no_inline)]
pub use winit;

#[doc(no_inline)]
pub use pixels::Pixels;
#[doc(no_inline)]
pub use web_time::Duration;
#[doc(no_inline)]
pub use winit::dpi::PhysicalSize;
#[doc(no_inline)]
pub use winit::keyboard::{KeyCode, NamedKey};
#[doc(no_inline)]
pub use winit::window::WindowBuilder;

/// Update context.
#[derive(Debug)]
pub struct Context {
    target_frame_time: Duration,
    max_frame_time: Duration,
    exit: bool,
    delta_time: Duration,
    /// Input handler.
    pub input: Input,
}

impl Context {
    #[inline]
    fn new(window: Rc<Window>, target_frame_time: Duration, max_frame_time: Duration) -> Self {
        Self {
            target_frame_time,
            max_frame_time,
            delta_time: Duration::ZERO,
            exit: false,
            input: Input::new(window),
        }
    }

    /// `winit` window.
    #[inline]
    pub fn window(&self) -> &Window {
        &self.input.window
    }

    /// Time between previous and current update.
    #[inline]
    pub fn frame_time(&self) -> Duration {
        self.delta_time
    }

    /// Set the desired (minimum) time between application updates.
    /// Implemented based on <https://gafferongames.com/post/fix_your_timestep>.
    #[inline]
    pub fn set_target_frame_time(&mut self, time: Duration) {
        self.target_frame_time = time;
    }

    /// Set the maximum time between application updates.
    /// The real frame time can be loger, but [`Context::frame_time()`] will not exceed this value.
    /// Implemented based on <https://gafferongames.com/post/fix_your_timestep>.
    #[inline]
    pub fn set_max_frame_time(&mut self, time: Duration) {
        self.max_frame_time = time;
    }

    /// Exit the application.
    #[inline]
    pub fn exit(&mut self) {
        self.exit = true;
    }
}

/// Application trait
pub trait App {
    /// Application update.
    /// Rate of updates can be set using [`Context`].
    fn update(&mut self, ctx: &mut Context) -> Result<()>;

    /// Application render.
    /// Will be called once every frame.
    fn render(&mut self, pix: &mut Pixels) -> Result<()>;

    /// Custom event handler if needed.
    #[inline]
    fn handle(&mut self, _event: &Event<()>) -> Result<()> {
        Ok(())
    }
}

/// Start the application. Not available on web target.
#[cfg(not(target_arch = "wasm32"))]
#[inline]
pub fn start(
    window_builder: WindowBuilder,
    app: impl App + 'static,
    pixel_buffer_size: PhysicalSize<u32>,
    target_frame_time: Duration,
    max_frame_time: Duration,
) -> Result<()> {
    use pollster::FutureExt;

    start_async(
        window_builder,
        app,
        pixel_buffer_size,
        target_frame_time,
        max_frame_time,
    )
    .block_on()
}

/// Start the application asynchronously.
pub async fn start_async(
    #[allow(unused_mut)] mut window_builder: WindowBuilder,
    mut app: impl App + 'static,
    pixel_buffer_size: PhysicalSize<u32>,
    target_frame_time: Duration,
    max_frame_time: Duration,
) -> Result<()> {
    let event_loop = EventLoop::new()?;

    #[cfg(target_arch = "wasm32")]
    {
        use winit::platform::web::WindowBuilderExtWebSys;

        window_builder = window_builder.with_append(true);
    }

    let window = Rc::new(window_builder.build(&event_loop)?);
    let window_size = window.inner_size();

    let mut context = Context::new(window.clone(), target_frame_time, max_frame_time);
    let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &*window);
    let mut pixels = Pixels::new_async(
        pixel_buffer_size.width,
        pixel_buffer_size.height,
        surface_texture,
    )
    .await?;

    let mut instant = Instant::now();
    let mut accumulated_time = Duration::ZERO;

    event_loop.set_control_flow(ControlFlow::Poll);

    let event_handler = move |event: Event<()>, elwt: &EventLoopWindowTarget<()>| {
        elwt.set_control_flow(ControlFlow::Poll);

        if handle_error(app.handle(&event), elwt).is_err() {
            return;
        }

        context.input.process_event(&event);

        match event {
            Event::WindowEvent { window_id, event } if window_id == window.id() => {
                match event {
                    WindowEvent::CloseRequested => {
                        elwt.exit();
                    }
                    WindowEvent::Resized(new_size) => {
                        if handle_error(
                            pixels
                                .resize_surface(new_size.width, new_size.height)
                                .map_err(Into::into),
                            elwt,
                        )
                        .is_err()
                        {
                            #[allow(clippy::needless_return)]
                            // keep 'return' in case I add code after this
                            return;
                        }
                    }
                    WindowEvent::RedrawRequested => {
                        let mut elapsed = instant.elapsed();
                        instant = Instant::now();

                        if elapsed > context.max_frame_time {
                            elapsed = context.max_frame_time;
                        }

                        accumulated_time += elapsed;

                        let mut keys_updated = false;

                        while accumulated_time > context.target_frame_time {
                            context.delta_time = context.target_frame_time;

                            if handle_error(app.update(&mut context), elwt).is_err() {
                                return;
                            }

                            if context.exit {
                                elwt.exit();
                                return;
                            }

                            if !keys_updated {
                                context.input.update_keys();
                                keys_updated = true;
                            }

                            accumulated_time =
                                accumulated_time.saturating_sub(context.target_frame_time);
                        }

                        // blending_factor = accumulated_time.as_secs_f32() / context.target_frame_time.as_secs_f32();

                        if handle_error(app.render(&mut pixels), elwt).is_err() {
                            #[allow(clippy::needless_return)]
                            // keep 'return' in case I add code after this and don't notice
                            return;
                        }
                    }
                    _ => {}
                }
            }
            Event::AboutToWait => {
                window.request_redraw();
            }
            _ => {}
        }
    };

    cfg_if! {
        if #[cfg(target_arch = "wasm32")] {
            use winit::platform::web::EventLoopExtWebSys;

            event_loop.spawn(event_handler);
        } else {
            event_loop.run(event_handler)?;
        }
    }

    Ok(())
}

#[inline]
fn handle_error(
    result: Result<()>,
    elwt: &EventLoopWindowTarget<()>,
) -> std::result::Result<(), ()> {
    if let Err(error) = result {
        log::error!("{}", error);
        elwt.exit();

        Err(())
    } else {
        Ok(())
    }
}