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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! A 'Game' in this context is a program that uses both wgpu and winit.
pub(crate) mod input;
pub(crate) mod window_size;

use std::sync::{atomic::AtomicBool, Arc, Mutex};

use async_trait::async_trait;
use thiserror::Error;
use winit::{
    dpi::PhysicalPosition,
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop, EventLoopWindowTarget},
    window::{Window, WindowBuilder},
};

use crate::LfLimitsExt;

use self::input::{InputMap, MouseInputType, VectorInputActivation, VectorInputType};

#[derive(Debug, Error)]
pub enum GameInitialisationFailure {
    #[error("failed to find an adapter (GPU) that supports the render surface")]
    AdapterError,
    #[error("failed to request a device from the adapter chosen: {0}")]
    DeviceError(wgpu::RequestDeviceError),
}

/// A cloneable and distributable flag that can be cheaply queried to see if the game has exited.
///
/// The idea is to clone this into in every thread you spawn so that they can gracefully exit when the game does.
#[derive(Clone)]
pub struct ExitFlag {
    inner: Arc<AtomicBool>,
}

impl ExitFlag {
    fn new() -> Self {
        Self {
            inner: Arc::new(AtomicBool::new(false)),
        }
    }

    pub fn get(&self) -> bool {
        self.inner.load(std::sync::atomic::Ordering::SeqCst)
    }

    fn set(&self) {
        self.inner.store(true, std::sync::atomic::Ordering::SeqCst)
    }
}

#[derive(Debug, Clone, Copy)]
pub enum InputMode {
    /// Indicates that any keyboard, mouse or gamepad input should be captured by the input management system,
    /// no raw input events should be passed to the game implementation, and the cursor should be hidden.
    Exclusive,
    /// Indicates that any keyboard, mouse or gamepad input should not be captured by the input management system,
    /// all raw input events should be passed to the game implementation, and the cursor should be shown.
    UI,
    /// Indicates that keyboard, mouse or gamepad input should be captured both by the input management system,
    /// and raw input events should be passed to the game implementation, and the cursor should be shown.
    Unified,
}
impl InputMode {
    fn should_hide_cursor(self) -> bool {
        match self {
            InputMode::Exclusive => true,
            InputMode::UI => false,
            InputMode::Unified => false,
        }
    }
    fn should_handle_input(self) -> bool {
        match self {
            InputMode::Exclusive => true,
            InputMode::UI => false,
            InputMode::Unified => true,
        }
    }
    fn should_propogate_raw_input(self) -> bool {
        match self {
            InputMode::Exclusive => false,
            InputMode::UI => true,
            InputMode::Unified => true,
        }
    }
    fn should_lock_cursor(self) -> bool {
        match self {
            InputMode::Exclusive => true,
            InputMode::UI => false,
            InputMode::Unified => false,
        }
    }
}

/// A command sent to the game to change the game state
pub enum GameCommand {
    Exit,
    SetInputMode(InputMode),
    SetMouseSensitivity(f32),
}

pub struct GameData {
    pub command_sender: flume::Sender<GameCommand>,
    pub surface_format: wgpu::TextureFormat,
    pub limits: wgpu::Limits,
    pub config: wgpu::SurfaceConfiguration,
    pub size: winit::dpi::PhysicalSize<u32>,
    pub window: Window,
    pub device: wgpu::Device,
    pub queue: wgpu::Queue,
    pub exit_flag: ExitFlag,
}

/// All of the callbacks required to implement a game. This API is built on top of a message passing
/// event system, and so calls to the below methods may be made concurrently, in any order, and on
/// different threads.
#[async_trait]
pub trait Game: Sized {
    /// Data processed before the window exists. This should be minimal and kept to `mpsc` message reception from initialiser threads.
    type InitData;

    type LinearInputType;
    type VectorInputType;

    fn target_limits() -> wgpu::Limits {
        wgpu::Limits::downlevel_webgl2_defaults()
    }
    fn default_inputs() -> InputMap<Self::LinearInputType, Self::VectorInputType>;

    async fn init(data: &GameData, init: Self::InitData) -> Self;

    fn on_init_failure(error: GameInitialisationFailure) -> ! {
        let error = format!("failed to initialise: {}", error);

        #[cfg(target_arch = "wasm32")]
        {
            alert(&error);
        }

        panic!("{}", error);
    }

    /// Allows you to intercept and cancel events, before passing them off to the standard event handler,
    /// to allow for egui integration, among others.
    ///
    /// This method only receives input events if the cursor is not captured, to avoid UI glitches.
    fn process_raw_event<'a, T>(&mut self, event: Event<'a, T>) -> Option<Event<'a, T>> {
        Some(event)
    }

    fn window_resize(&mut self, data: &GameData, new_size: winit::dpi::PhysicalSize<u32>);

    fn handle_linear_input(
        &mut self,
        data: &GameData,
        input: &Self::LinearInputType,
        activation: input::LinearInputActivation,
    );

    fn handle_vector_input(
        &mut self,
        data: &GameData,
        input: &Self::VectorInputType,
        activation: input::VectorInputActivation,
    );

    /// Requests that the next frame is drawn into the view, pretty please :)
    fn render_to(&mut self, data: &GameData, view: wgpu::TextureView);

    /// Invoked when the window is told to close (i.e. x pressed, sigint, etc.) but not when
    /// a synthetic exit is triggered by enqueuing `GameCommand::Exit`. To actually do something with the
    /// user's request to quit, this method must enqueue `GameCommand::Exit`
    fn user_exit_requested(&mut self, data: &GameData) {
        let _ = data.command_sender.send(GameCommand::Exit);
    }

    /// Invoked right at the end of the program life, after the final frame is rendered.
    fn finished(self, _: GameData) {}
}

/// All the data held by a program/game while running. `T` gives the top-level state for the game
/// implementation
pub(crate) struct GameState<T: Game> {
    data: GameData,
    current_modifiers: input::ModifiersState,
    game: T,
    input_map: input::InputMap<T::LinearInputType, T::VectorInputType>,
    command_receiver: flume::Receiver<GameCommand>,

    surface: Mutex<wgpu::Surface>,

    // While true, disallows cursor movement
    input_mode: InputMode,
    // The last position we saw the cursor at
    last_cursor_position: PhysicalPosition<f64>,
    // A multiplier, from pixels moved to intensity, clamped at 1.0
    mouse_sensitivity: f32,
}

impl<T: Game + 'static> GameState<T> {
    // Creating some of the wgpu types requires async code
    async fn new(init: T::InitData, window_target: &EventLoopWindowTarget<()>) -> Self {
        let window = WindowBuilder::new().build(window_target).unwrap();

        let size = window.inner_size();

        // The instance is a handle to our GPU
        // Backends::all => Vulkan + Metal + DX12 + Browser WebGPU
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::util::backend_bits_from_env().unwrap_or(wgpu::Backends::all()),
            dx12_shader_compiler: wgpu::util::dx12_shader_compiler_from_env().unwrap_or_default(),
        });

        // # Safety
        //
        // The surface needs to live as long as the window that created it.
        // State owns the window so this should be safe.
        let surface = unsafe { instance.create_surface(&window) }.unwrap();

        let adapter = match instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                force_fallback_adapter: false,
                compatible_surface: Some(&surface),
            })
            .await
        {
            Some(adapter) => adapter,
            None => T::on_init_failure(GameInitialisationFailure::AdapterError),
        };

        let available_limits = if cfg!(target_arch = "wasm32") {
            wgpu::Limits::downlevel_defaults()
        } else {
            adapter.limits()
        };

        let target_limits = T::target_limits();
        let limits = available_limits.intersection(&target_limits);

        let mut features = wgpu::Features::empty();
        // Assume integrated and virtual GPUs, and CPUs, are UMA
        if adapter
            .features()
            .contains(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)
            && matches!(
                adapter.get_info().device_type,
                wgpu::DeviceType::IntegratedGpu
                    | wgpu::DeviceType::Cpu
                    | wgpu::DeviceType::VirtualGpu
            )
        {
            features |= wgpu::Features::MAPPABLE_PRIMARY_BUFFERS;
        }
        // Things that are always helpful
        features |= adapter.features().intersection(
            wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_PASSES,
        );

        let (device, queue) = match adapter
            .request_device(
                &wgpu::DeviceDescriptor {
                    features,
                    limits: limits.clone(),
                    label: None,
                },
                None,
            )
            .await
        {
            Ok(vs) => vs,
            Err(e) => T::on_init_failure(GameInitialisationFailure::DeviceError(e)),
        };

        // Configure surface
        let mut surface_config = surface
            .get_default_config(&adapter, size.width, size.height)
            .expect("got an adapter based on the surface");
        surface_config.present_mode = wgpu::PresentMode::AutoVsync;
        surface.configure(&device, &surface_config);

        let surface_caps = surface.get_capabilities(&adapter);

        let surface_format = surface_caps
            .formats
            .iter()
            .copied()
            .filter(|f| f.is_srgb())
            .next()
            .unwrap_or(surface_caps.formats[0]);

        let config = wgpu::SurfaceConfiguration {
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            format: surface_format,
            width: size.width,
            height: size.height,
            present_mode: surface_caps.present_modes[0],
            alpha_mode: surface_caps.alpha_modes[0],
            view_formats: vec![],
        };
        surface.configure(&device, &config);

        let (command_sender, command_receiver) = flume::unbounded();

        // Some state can be set by commands to ensure valid initial state.
        command_sender
            .try_send(GameCommand::SetInputMode(InputMode::Unified))
            .expect("unbounded queue helf by this thread should send immediately");

        let data = GameData {
            command_sender,
            surface_format,
            limits,
            config,
            size,
            window,
            device,
            queue,
            exit_flag: ExitFlag::new(),
        };
        let game = T::init(&data, init).await;

        let input_map = T::default_inputs();

        Self {
            data,
            current_modifiers: input::ModifiersState::default(),
            game,
            surface: Mutex::new(surface),
            command_receiver,
            input_map,
            input_mode: InputMode::Unified,
            last_cursor_position: PhysicalPosition { x: 0.0, y: 0.0 },
            mouse_sensitivity: 0.01,
        }
    }

    pub(crate) fn run(init: T::InitData) {
        let event_loop = EventLoop::new();

        // Built on first `Event::Resumed`
        // Taken out on `Event::LoopDestroyed`
        let mut state: Option<Self> = None;
        let mut init = Some(init);

        event_loop.run(move |event, window_target, control_flow| {
            if event == Event::LoopDestroyed {
                state.take().expect("loop is destroyed once").finished();
                return;
            }

            // Resume always emmitted to begin with
            if state.is_none() && event == Event::Resumed {
                state = Some(pollster::block_on(Self::new(
                    init.take().expect("should only initialise once"),
                    window_target,
                )));
            }

            let state = match state.as_mut() {
                None => return,
                Some(state) => state,
            };

            state.receive_event(event, window_target, control_flow);
        });
    }

    fn is_input_event(event: &Event<'_, ()>) -> bool {
        match event {
            winit::event::Event::WindowEvent { event, .. } => match event {
                winit::event::WindowEvent::CursorMoved { .. }
                | winit::event::WindowEvent::CursorEntered { .. }
                | winit::event::WindowEvent::CursorLeft { .. }
                | winit::event::WindowEvent::MouseWheel { .. }
                | winit::event::WindowEvent::MouseInput { .. }
                | winit::event::WindowEvent::TouchpadRotate { .. }
                | winit::event::WindowEvent::TouchpadPressure { .. }
                | winit::event::WindowEvent::AxisMotion { .. }
                | winit::event::WindowEvent::Touch(_)
                | winit::event::WindowEvent::ReceivedCharacter(_)
                | winit::event::WindowEvent::KeyboardInput { .. }
                | winit::event::WindowEvent::ModifiersChanged(_)
                | winit::event::WindowEvent::Ime(_)
                | winit::event::WindowEvent::TouchpadMagnify { .. }
                | winit::event::WindowEvent::SmartMagnify { .. } => true,
                _ => false,
            },
            winit::event::Event::DeviceEvent { event, .. } => match event {
                winit::event::DeviceEvent::MouseMotion { .. }
                | winit::event::DeviceEvent::MouseWheel { .. }
                | winit::event::DeviceEvent::Motion { .. }
                | winit::event::DeviceEvent::Button { .. }
                | winit::event::DeviceEvent::Key(_)
                | winit::event::DeviceEvent::Text { .. } => true,
                _ => false,
            },
            _ => false,
        }
    }

    fn receive_event(
        &mut self,
        mut event: Event<'_, ()>,
        window_target: &EventLoopWindowTarget<()>,
        control_flow: &mut ControlFlow,
    ) {
        // Discard events that aren't for us
        event = match event {
            Event::WindowEvent { window_id, .. } if window_id != self.window().id() => return,
            event => event,
        };

        // We filter all window events through the game to allow it to integrate with other libraries, such as egui.
        // But only send keyboard and mouse input events to UI if the mouse isn't captured.
        let should_send_input = self.input_mode.should_propogate_raw_input();
        if should_send_input || !Self::is_input_event(&event) {
            event = match self.game.process_raw_event(event) {
                None => return,
                Some(event) => event,
            };
        }

        self.process_event(event, window_target, control_flow)
    }

    fn process_event(
        &mut self,
        event: Event<'_, ()>,
        _window_target: &EventLoopWindowTarget<()>,
        control_flow: &mut ControlFlow,
    ) {
        match event {
            Event::WindowEvent { event, .. } => match event {
                WindowEvent::CloseRequested | WindowEvent::Destroyed => self.request_exit(),
                // (0, 0) means minimized on Windows.
                WindowEvent::Resized(winit::dpi::PhysicalSize {
                    width: 0,
                    height: 0,
                }) => {}
                WindowEvent::Resized(physical_size) => {
                    self.resize(physical_size);
                }
                WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
                    self.resize(*new_inner_size);
                }
                WindowEvent::ModifiersChanged(modifiers) => {
                    let changed = self.set_current_input_modifiers(modifiers);

                    for (key, activation) in changed {
                        self.linear_input(input::LinearInputType::KnownKeyboard(key), activation);
                    }
                }
                WindowEvent::KeyboardInput {
                    device_id: _device_id,
                    input,
                    is_synthetic,
                } if !is_synthetic => {
                    if let Some(key) = input.virtual_keycode {
                        let activation = match input.state {
                            winit::event::ElementState::Pressed => 1.0,
                            winit::event::ElementState::Released => 0.0,
                        };
                        let activation =
                            input::LinearInputActivation::try_from(activation).expect("from const");
                        self.linear_input(
                            input::LinearInputType::KnownKeyboard(key.into()),
                            activation,
                        );
                    } else {
                        eprintln!("unknown key code, scan code: {:?}", input.scancode)
                    }
                }
                WindowEvent::CursorMoved {
                    device_id: _device_id,
                    position,
                    ..
                } => {
                    let delta_x = position.x - self.last_cursor_position.x;
                    let delta_y = position.y - self.last_cursor_position.y;

                    // Only trigger a single linear event, depending on the largest movement
                    if delta_x.abs() > 2.0 || delta_y.abs() > 2.0 {
                        self.process_linear_mouse_movement(delta_x, delta_y);
                    }

                    // Also trigger a vector input
                    self.vector_input(
                        VectorInputType::MouseMove,
                        VectorInputActivation::clamp(
                            delta_x as f32 * self.mouse_sensitivity,
                            delta_y as f32 * self.mouse_sensitivity,
                        ),
                    );

                    self.last_cursor_position = position.cast();

                    // Winit doesn't support cursor locking on a lot of platforms, so do it manually.
                    let should_lock_cursor = self.input_mode.should_lock_cursor();
                    if should_lock_cursor {
                        let mut center = self.data.window.inner_size();
                        center.width /= 2;
                        center.height /= 2;

                        let old_pos = position.cast::<u32>();
                        let new_pos = PhysicalPosition::new(center.width, center.height);

                        if old_pos != new_pos {
                            // Ignore result - if it doesn't work then there's not much we can do.
                            let _ = self.data.window.set_cursor_position(new_pos);
                        }

                        self.last_cursor_position = new_pos.cast();
                    }
                }
                _ => {}
            },
            Event::RedrawRequested(window_id) if window_id == self.window().id() => {
                self.data.device.poll(wgpu::MaintainBase::Poll);

                self.pre_frame_update();

                // Check everything the game implementation can send 'upstream'
                if self.data.exit_flag.get() {
                    *control_flow = ControlFlow::Exit;
                }

                match self.render() {
                    Ok(_) => {}
                    Err(wgpu::SurfaceError::Lost) => self.resize(self.data.size),
                    Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
                    // All other errors (Outdated, Timeout) should be resolved by the next frame
                    Err(e) => eprintln!("{:?}", e),
                }
            }
            Event::MainEventsCleared => {
                self.window().request_redraw();
            }
            _ => {}
        }
    }

    pub fn window(&self) -> &Window {
        &self.data.window
    }

    fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
        if new_size.width > 0 && new_size.height > 0 {
            self.data.size = new_size;
            self.data.config.width = new_size.width;
            self.data.config.height = new_size.height;

            let lock = self.surface.lock().unwrap();

            // Block until existing work is done.
            let (s, r) = flume::bounded(1);
            self.data
                .queue
                .on_submitted_work_done(move || s.send(()).unwrap());
            self.data.device.poll(wgpu::Maintain::Wait);
            let _ = r.recv().unwrap();

            lock.configure(&self.data.device, &self.data.config);

            self.game.window_resize(&self.data, new_size)
        }
    }

    fn set_current_input_modifiers(
        &mut self,
        modifiers: winit::event::ModifiersState,
    ) -> Vec<(input::KeyCode, input::LinearInputActivation)> {
        let mut changed = Vec::new();
        let mut check = |old, new, key| {
            if old != new {
                let activation = if old {
                    input::LinearInputActivation::try_from(0.0).unwrap()
                } else {
                    input::LinearInputActivation::try_from(1.0).unwrap()
                };
                changed.push((key, activation))
            }
        };

        check(
            self.current_modifiers.shift,
            modifiers.shift(),
            input::KeyCode::Shift,
        );
        check(
            self.current_modifiers.ctrl,
            modifiers.ctrl(),
            input::KeyCode::Ctrl,
        );
        check(
            self.current_modifiers.alt,
            modifiers.alt(),
            input::KeyCode::Alt,
        );
        check(
            self.current_modifiers.logo,
            modifiers.logo(),
            input::KeyCode::Logo,
        );

        self.current_modifiers = input::ModifiersState {
            shift: modifiers.shift(),
            ctrl: modifiers.ctrl(),
            alt: modifiers.alt(),
            logo: modifiers.logo(),
        };

        return changed;
    }

    fn process_linear_mouse_movement(&mut self, delta_x: f64, delta_y: f64) {
        if delta_x.abs() > delta_y.abs() {
            if delta_x > 0.0 {
                self.linear_input(
                    input::LinearInputType::Mouse(MouseInputType::MoveRight),
                    input::LinearInputActivation::clamp(delta_x as f32 * self.mouse_sensitivity),
                );
            } else {
                self.linear_input(
                    input::LinearInputType::Mouse(MouseInputType::MoveLeft),
                    input::LinearInputActivation::clamp(-delta_x as f32 * self.mouse_sensitivity),
                );
            }
        } else {
            if delta_y > 0.0 {
                self.linear_input(
                    input::LinearInputType::Mouse(MouseInputType::MoveUp),
                    input::LinearInputActivation::clamp(delta_y as f32 * self.mouse_sensitivity),
                );
            } else {
                self.linear_input(
                    input::LinearInputType::Mouse(MouseInputType::MoveDown),
                    input::LinearInputActivation::clamp(-delta_y as f32 * self.mouse_sensitivity),
                );
            }
        }
    }

    fn linear_input(
        &mut self,
        inputted: input::LinearInputType,
        activation: input::LinearInputActivation,
    ) {
        if !self.input_mode.should_handle_input() {
            return;
        }
        let input_value = self.input_map.get_linear(&inputted);
        if let Some(input_value) = input_value {
            self.game
                .handle_linear_input(&self.data, input_value, activation)
        }
    }

    fn vector_input(
        &mut self,
        inputted: input::VectorInputType,
        activation: input::VectorInputActivation,
    ) {
        if !self.input_mode.should_handle_input() {
            return;
        }
        let input_value = self.input_map.get_vector(&inputted);
        if let Some(input_value) = input_value {
            self.game
                .handle_vector_input(&self.data, input_value, activation)
        }
    }

    fn request_exit(&mut self) {
        self.data.exit_flag.set();
        self.game.user_exit_requested(&self.data);
    }

    fn pre_frame_update(&mut self) {
        // Get all the things the game wants to do before the next frame
        while let Ok(cmd) = self.command_receiver.try_recv() {
            match cmd {
                GameCommand::Exit => self.data.exit_flag.set(),
                GameCommand::SetInputMode(input_mode) => {
                    self.input_mode = input_mode;

                    let should_show_cursor = !input_mode.should_hide_cursor();
                    self.data.window.set_cursor_visible(should_show_cursor);
                }
                GameCommand::SetMouseSensitivity(new_sensitivity) => {
                    self.mouse_sensitivity = new_sensitivity;
                }
            }
        }
    }

    fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
        let lock = self.surface.lock().unwrap();

        let was_suboptimal = {
            let output = lock.get_current_texture()?;
            let view = output
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default());

            self.game.render_to(&self.data, view);

            let was_suboptimal = output.suboptimal;

            output.present();

            was_suboptimal
        };

        if was_suboptimal {
            // Force recreation
            return Err(wgpu::SurfaceError::Lost);
        }
        Ok(())
    }

    fn finished(self) {
        self.game.finished(self.data)
    }
}