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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783

use crate::input::Input;
use crate::scene::Scene;
use crate::audio::{Audio, AlAudio, NullAudio, AudioError, Sound};
use crate::renderer::{Renderer, RendererError, RendererNewInfo, Sheet, Shader};
#[cfg(feature = "imgui_integration")] use crate::imgui_handler::ImGuiHandler;
#[cfg(feature = "default_logger")] use crate::doglog;

use sdl2::event::Event;
use sdl2::event::WindowEvent;
use sdl2::keyboard::Scancode;
use sdl2::keyboard::Mod as KeyboardMod;
#[cfg(feature = "graphical_panic")] use sdl2::messagebox;

#[cfg(feature = "graphical_panic")] use std::panic::PanicInfo;
#[cfg(feature = "graphical_panic")] use backtrace::Backtrace;

use keeshond_datapack::DataStore;
use keeshond_datapack::source::SourceManager;

#[cfg(feature = "imgui_integration")] use imgui;

use std::time::{Instant, Duration};
use std::rc::Rc;
use std::cell::RefCell;

const MILLISECONDS_PER_NANOSECOND : f64 = 0.000001;

#[derive(Debug)]
pub enum Sdl2Subsystem
{
    Main,
    Event,
    Video
}

#[derive(Debug, Fail)]
pub enum InitError
{
    #[fail(display = "Failed to initialize SDL {:?} subsystem: {}", _0, _1)]
    Sdl2InitError(Sdl2Subsystem, String),
    #[fail(display = "Failed to initialize renderer: {}", _0)]
    RendererInitError(RendererError),
    #[fail(display = "Failed to initialize audio: {}", _0)]
    AudioInitError(AudioError),
    #[fail(display = "Failed to initialize imgui: {}", _0)]
    ImguiInitError(String)
}

#[cfg(feature = "graphical_panic")]
fn panic_hook(info : &PanicInfo)
{
    // Get error message if that's what the payload happens to be
    let message : &str = match info.payload().downcast_ref::<String>()
    {
        Some(s) => s,
        None => match info.payload().downcast_ref::<&str>()
        {
            Some(s) => s,
            None => "No reason was given.",
        }
    };
    // Format with file/line info if available
    let mut message = match info.location()
    {
        Some(location) => format!("A panic error occurred on {}:{}: \n{}",
                                location.file(),
                                location.line(),
                                message),
        None => format!("A panic error occurred: \n{}", message),
    };
    
    let bt = Backtrace::new();
    
    message = format!("{}\n\n{:?}", message, bt);
    
    gui_cli_message(&message, "Panic Error");
    
    std::process::exit(1);
}

#[allow(unused_variables)]
pub fn gui_cli_message(message : &str, title : &str)
{
    // Print to console first in case something weird happens
    println!("{}", message);
    
    #[cfg(feature = "graphical_panic")]
    {
        // Show dialog box with panic
        match messagebox::show_simple_message_box(messagebox::MESSAGEBOX_ERROR, title, &message[..], None)
        {
            Ok(_) => (),
            Err(_) => println!("(Messagebox could not be displayed)"),
        };
    }
}

fn read_options() -> getopts::Matches
{
    let args : Vec<String> = std::env::args().collect();
    let options = getopts::Options::new();
    
    let match_result = options.parse(&args[1..]);
    
    match match_result
    {
        Ok(_) => (),
        Err(fail) =>
        {
            let message = format!("{:?}\n{}",
                                  fail,
                                  options.usage("Command parsing failed. Run without options to use defaults."));
            gui_cli_message(&message, "Commandline Help");
            std::process::exit(1);
        }
    }
    
    match_result.unwrap()
}

pub struct GameloopStopwatch
{
    jiffies : Instant,
    jiffies_this_frame : Duration,
    jiffies_this_second : Duration,
    tics_this_frame : u32,
    tics_this_second : u32,
    frames_this_second : u32,
    in_frame : bool
}

impl GameloopStopwatch
{
    pub fn new() -> GameloopStopwatch
    {
        GameloopStopwatch
        {
            jiffies : Instant::now(),
            jiffies_this_frame : Duration::new(0, 0),
            jiffies_this_second : Duration::new(0, 0),
            tics_this_frame : 0,
            tics_this_second : 0,
            frames_this_second : 0,
            in_frame : false
        }
    }
    
    pub fn begin_frame_timing(&mut self)
    {
        if self.in_frame
        {
            return;
        }
        
        self.in_frame = true;
        
        self.jiffies = Instant::now();
        self.jiffies_this_frame = Duration::new(0, 0);
        self.tics_this_frame = 0;
    }
    
    pub fn end_frame_timing(&mut self)
    {
        if !self.in_frame
        {
            return;
        }
        
        self.in_frame = false;
        
        self.jiffies_this_frame = Instant::now() - self.jiffies;
        self.tics_this_second += self.tics_this_frame;
        self.jiffies_this_second += self.jiffies_this_frame;
        self.frames_this_second += 1;
    }
    
    pub fn tic(&mut self)
    {
        self.tics_this_frame += 1;
    }
    
    pub fn new_second(&mut self)
    {
        self.jiffies_this_second = Duration::new(0, 0);
        self.tics_this_second = 0;
        self.frames_this_second = 0;
    }
    
    pub fn jiffies_this_frame(&self) -> Duration
    {
        if self.in_frame
        {
            return Instant::now() - self.jiffies;
        }
        
        self.jiffies_this_frame
    }
    
    pub fn jiffies_this_second(&self) -> Duration
    {
        self.jiffies_this_second
    }
    
    pub fn tics_this_frame(&self) -> u32
    {
        self.tics_this_frame
    }
    
    pub fn tics_this_second(&self) -> u32
    {
        self.tics_this_second
    }
    
    pub fn frames_this_second(&self) -> u32
    {
        self.frames_this_second
    }
    
    pub fn average_ms(&self) -> f64
    {
        self.jiffies_this_second.as_nanos() as f64 * MILLISECONDS_PER_NANOSECOND / self.frames_this_second as f64
    }
}

pub struct GameResources
{
    sheet_store : DataStore<Sheet>,
    shader_store : DataStore<Shader>,
    sound_store : DataStore<Sound>
}

impl GameResources
{
    pub fn sheets(&self) -> &DataStore<Sheet>
    {
        &self.sheet_store
    }
    
    pub fn sheets_mut(&mut self) -> &mut DataStore<Sheet>
    {
        &mut self.sheet_store
    }
    
    pub fn shaders(&self) -> &DataStore<Shader>
    {
        &self.shader_store
    }
    
    pub fn shaders_mut(&mut self) -> &mut DataStore<Shader>
    {
        &mut self.shader_store
    }
    
    pub fn sounds(&self) -> &DataStore<Sound>
    {
        &self.sound_store
    }
    
    pub fn sounds_mut(&mut self) -> &mut DataStore<Sound>
    {
        &mut self.sound_store
    }
}

pub struct GameControl
{
    target_framerate : f64,
    frame_interpolation : bool,
    input : Input,
    renderer : Renderer,
    audio : Box<Audio>,
    next_scene : Box<Scene>,
    next_scene_waiting : bool,
    source_manager : Rc<RefCell<SourceManager>>,
    resources : GameResources,
    #[cfg(feature = "imgui_integration")]
    imgui_handler : ImGuiHandler
}

impl GameControl
{
    pub fn new(sdl_context : Option<&sdl2::Sdl>) -> Result<GameControl, InitError>
    {   
        let source_manager = Rc::new(RefCell::new(SourceManager::new()));
        let sheet_store = DataStore::new(source_manager.clone());
        let shader_store = DataStore::new(source_manager.clone());
        let sound_store = DataStore::new(source_manager.clone());
        
        let mut resources = GameResources { sheet_store, shader_store, sound_store };
        
        let mut renderer_new_info = None;
        let audio : Box<Audio>;
        
        if let Some(sdl) = sdl_context
        {
            let video_subsystem = try_or_else!(sdl.video(),
                |error| Err(InitError::Sdl2InitError(Sdl2Subsystem::Video, error)));
            
            audio = Box::new(try_or_else!(AlAudio::new(&mut resources),
                |error| Err(InitError::AudioInitError(error))));
            
            renderer_new_info = Some(RendererNewInfo
            {
                video_subsystem,
                resources : &mut resources
            });
        }
        else
        {
            audio = Box::new(NullAudio::new());
        }
        
        #[cfg(feature = "imgui_integration")]
        let mut imgui_handler = try_or_else!(ImGuiHandler::new(),
            |error| Err(InitError::ImguiInitError(error)));
        
        #[allow(unused_mut)] // mut used only by imgui feature
        let mut renderer = try_or_else!(Renderer::new(renderer_new_info),
            |error| Err(InitError::RendererInitError(error)));
        
        #[cfg(feature = "imgui_integration")]
        try_or_else!(renderer.control().init_imgui_renderer(imgui_handler.imgui_mut()),
            |error| Err(InitError::RendererInitError(error)));
        
        Ok(GameControl
        {
            target_framerate : 60.0,
            frame_interpolation : false,
            input : Input::new(),
            renderer,
            audio,
            next_scene : Box::new(Scene::new()),
            next_scene_waiting : false,
            source_manager,
            resources,
            #[cfg(feature = "imgui_integration")]
            imgui_handler
        })
    }
    
    pub fn target_framerate(&self) -> f64
    {
        self.target_framerate
    }
    
    pub fn set_target_framerate(&mut self, new_framerate : f64)
    {
        if new_framerate < 1.0 || new_framerate >= 1000.0
        {
            panic!("Target framerate must be between 1 and 1000.");
        }
        
        self.target_framerate = new_framerate;
    }
    
    pub fn frame_interpolation(&self) -> bool
    {
        self.frame_interpolation
    }
    
    pub fn set_frame_interpolation(&mut self, enabled : bool)
    {
        self.frame_interpolation = enabled;
    }
    
    pub fn input(&self) -> &Input
    {
        &self.input
    }
    
    pub fn input_mut(&mut self) -> &mut Input
    {
        &mut self.input
    }
    
    pub fn renderer(&self) -> &Renderer
    {
        &self.renderer
    }
    
    pub fn renderer_mut(&mut self) -> &mut Renderer
    {
        &mut self.renderer
    }
    
    pub fn audio(&self) -> &Box<Audio>
    {
        &self.audio
    }
    
    pub fn audio_mut(&mut self) -> &mut Box<Audio>
    {
        &mut self.audio
    }
    
    fn sync_audio_store(&mut self)
    {
        self.audio.sync_sound_store(&mut self.resources.sound_store)
            .expect("Audio backend store sync failed");
    }
    
    pub fn source_manager(&self) -> Rc<RefCell<SourceManager>>
    {
        self.source_manager.clone()
    }
    
    pub fn res(&self) -> &GameResources
    {
        &self.resources
    }
    
    pub fn res_mut(&mut self) -> &mut GameResources
    {
        &mut self.resources
    }
    
    #[cfg(feature = "imgui_integration")]
    pub fn imgui(&self) -> &imgui::ImGui
    {
        self.imgui_handler.imgui()
    }
    
    #[cfg(feature = "imgui_integration")]
    pub fn imgui_mut(&mut self) -> &mut imgui::ImGui
    {
        self.imgui_handler.imgui_mut()
    }
    
    pub fn goto_constructed_scene(&mut self, next_scene : Box<Scene>)
    {
        self.next_scene = next_scene;
        self.next_scene_waiting = true;
    }
}

struct GameloopTimeState
{
    jiffies : Instant,
    last_jiffies : Instant,
    last_fps_jiffies : Instant,
    jiffy_queue : Duration,
    target_frametime : Duration,
    lag_this_second : u32,
    thought_yet : bool,
    think_timer : GameloopStopwatch,
    draw_timer : GameloopStopwatch,
    wait_timer : GameloopStopwatch,
    present_timer : GameloopStopwatch
}

impl GameloopTimeState
{
    fn new() -> GameloopTimeState
    {
        let jiffies = Instant::now();
        let last_jiffies = jiffies;
        let last_fps_jiffies = Instant::now();
        let jiffy_queue = Duration::new(0, 0);
        let target_frametime = Duration::new(0, 0);
        
        GameloopTimeState
        {
            jiffies,
            last_jiffies,
            last_fps_jiffies,
            jiffy_queue,
            target_frametime,
            lag_this_second : 0,
            thought_yet : false,
            think_timer : GameloopStopwatch::new(),
            draw_timer : GameloopStopwatch::new(),
            wait_timer : GameloopStopwatch::new(),
            present_timer : GameloopStopwatch::new()
        }
    }
    
    fn new_second(&mut self)
    {
        self.think_timer.new_second();
        self.draw_timer.new_second();
        self.wait_timer.new_second();
        self.present_timer.new_second();
        
        self.last_fps_jiffies += Duration::from_secs(1);
        self.lag_this_second = 0;
    }
    
    fn update_jiffies(&mut self)
    {
        self.jiffies = Instant::now();
        self.jiffy_queue += self.jiffies - self.last_jiffies;
        self.last_jiffies = self.jiffies;
    }
    
    fn sleep(&mut self, wait_duration : Duration)
    {
        while self.jiffy_queue <= wait_duration
        {
            self.update_jiffies();
            
            if self.jiffy_queue <= wait_duration - Duration::from_millis(1)
            {
                std::thread::sleep(Duration::from_millis(1));
            }
        }
    }
}

pub struct Gameloop
{
    #[allow(dead_code)] // Only used by the imgui integration feature
    sdl_context : sdl2::Sdl,
    event_pump : sdl2::EventPump,
    control : GameControl,
    current_scene : Box<Scene>,
    time : GameloopTimeState
}

impl Gameloop
{
    pub fn new(package_name : &str, friendly_name : &str) -> Result<Gameloop, InitError>
    {
        #[cfg(feature = "default_logger")]
        {
            let mut logger = doglog::DogLog::new();
            logger.add_package_filter(String::from(package_name));
            
            if let Err(_) = doglog::DogLog::init(logger, log::LevelFilter::Debug)
            {
                eprintln!("Could not initialize default logger.");
            }
        }
        
        info!("🐶 KEESHOND Game Engine 🐶");
        
        // Messagebox panic handler
        #[cfg(feature = "graphical_panic")]
        std::panic::set_hook(Box::new(panic_hook));
        
        // Get commandline options
        let _matches = read_options();
        
        let version = sdl2::version::version();
        info!("Starting SDL version {}", version);
        
        // Subsystems init
        let sdl_context = try_or_else!(sdl2::init(),
            |error| Err(InitError::Sdl2InitError(Sdl2Subsystem::Main, error)));
        let event_pump = try_or_else!(sdl_context.event_pump(),
            |error| Err(InitError::Sdl2InitError(Sdl2Subsystem::Event, error)));
        
        #[allow(unused_mut)] // mut used only by imgui feature
        let mut control = try_or_else!(GameControl::new(Some(&sdl_context)), |error| Err(error));
        
        control.renderer_mut().set_window_title(friendly_name);
        
        Ok(Gameloop
        {
            sdl_context,
            event_pump,
            control,
            current_scene : Box::new(Scene::new()),
            time : GameloopTimeState::new()
        })
    }
    
    pub fn control(&self) -> &GameControl
    {
        &self.control
    }
    
    pub fn control_mut(&mut self) -> &mut GameControl
    {
        &mut self.control
    }
    
    fn update_input(&mut self)
    {
        let event_pump = &self.event_pump;
        
        let mut callback = | key : &str |
        {
            let scancode = try_opt_or_else!(Scancode::from_name(key), || false);
            
            event_pump.keyboard_state().is_scancode_pressed(scancode)
        };
        
        self.control.input_mut().check_and_update_state(&mut callback);
    }
    
    fn think(&mut self)
    {
        self.time.think_timer.begin_frame_timing();
        
        let target_ms = 1000.0 / self.control.target_framerate();
        self.time.target_frametime = Duration::from_nanos((target_ms * 1_000_000.0) as u64);
        
        self.control.sync_audio_store();
        
        while self.time.jiffy_queue > self.time.target_frametime
        {
            // Prevent overflow if CPU cannot process all the frames
            if (self.time.think_timer.jiffies_this_frame()) > self.time.target_frametime
            {
                while self.time.jiffy_queue > self.time.target_frametime
                {
                    self.time.jiffy_queue -= self.time.target_frametime;
                    self.time.lag_this_second += 1;
                }
                break;
            }
            
            self.update_input();
            self.current_scene.think(&mut self.control);
            
            self.time.think_timer.tic();
            
            self.time.jiffy_queue -= self.time.target_frametime;
            self.time.thought_yet = true;
        }
        
        self.time.think_timer.end_frame_timing();
    }
    
    fn draw(&mut self)
    {
        self.time.draw_timer.begin_frame_timing();
        
        if self.time.thought_yet
        {
            let mut interpolation_amount = 0.0;
        
            if self.control.frame_interpolation
            {
                interpolation_amount = (self.time.jiffy_queue.as_nanos() as f64
                    / self.time.target_frametime.as_nanos() as f64) - 1.0;
            }
            
            self.control.renderer.control().sync_sheet_store(&mut self.control.resources.sheet_store)
                .expect("GPU sheet store sync failed");
            self.control.renderer.control().sync_shader_store(&mut self.control.resources.shader_store)
                .expect("GPU shader store sync failed");
            
            self.control.renderer.draw(&mut self.current_scene, interpolation_amount as f32);
        }
        
        #[cfg(feature = "imgui_integration")]
        {
            self.update_imgui();
        }
        
        self.control.renderer.control().flush_drawing();
        
        self.time.draw_timer.end_frame_timing();
    }
    
    #[cfg(feature = "imgui_integration")]
    fn update_imgui(&mut self)
    {
        let frametime = self.time.target_frametime * self.time.think_timer.tics_this_frame();
        self.control.imgui_handler.update_cursor(&mut self.sdl_context.mouse());
        
        let frame_delta = frametime.as_nanos() as f64 * MILLISECONDS_PER_NANOSECOND / 1000.0;
        let (width, height) = self.control.renderer.window_size();
        let mut ui = self.control.imgui_handler.imgui_mut()
            .frame(imgui::FrameSize::new(width as f64, height as f64, 1.0), frame_delta as f32);
        
        self.current_scene.imgui_think(&mut ui);
        
        self.control.renderer.control().draw_imgui(ui);
    }
    
    fn wait(&mut self)
    {
        self.time.wait_timer.begin_frame_timing();
        
        if !self.control.frame_interpolation
        {
            // Spin until it's time for the next frame
            self.time.sleep(self.time.target_frametime);
        }
        else
        {
            self.time.update_jiffies();
        }
        
        self.time.wait_timer.end_frame_timing();
    }
    
    fn present(&mut self)
    {
        self.time.present_timer.begin_frame_timing();
        
        self.control.renderer.present();
        
        self.time.present_timer.end_frame_timing();
    }
    
    fn update_fps(&mut self)
    {
        if self.time.jiffies < self.time.last_fps_jiffies + Duration::from_secs(1)
        {
            return;
        }
        
        debug!("{} ents  |  FPS: {} / {}  |  avg ms:  think {:.2}  draw {:.2}  present {:.2}  wait {:.2}",
        self.current_scene.entity_count(),
            self.time.draw_timer.frames_this_second(),
            self.time.think_timer.tics_this_second(),
            self.time.think_timer.average_ms(),
            self.time.draw_timer.average_ms(),
            self.time.present_timer.average_ms(),
            self.time.wait_timer.average_ms());
        
        if self.time.lag_this_second > 0
        {
            warn!("Too much CPU work, game is slowing down!");
        }
        
        self.time.new_second();
    }

    pub fn run(&mut self)
    {
        self.time = GameloopTimeState::new();
        
        'runloop: loop
        {
            // Consume events
            for event in self.event_pump.poll_iter()
            {
                match event
                {
                    Event::Quit {..} =>
                    {
                        break 'runloop;
                    },
                    Event::Window { win_event, .. } => match win_event
                    {
                        WindowEvent::SizeChanged {..} =>
                        {
                            self.control.renderer.recalculate_viewport();
                        }
                        _ => ()
                    },
                    Event::KeyDown { scancode, keymod, repeat, .. } =>
                    {
                        // For some reason I can't access LALTMOD and RALTMOD
                        //  so I have to use the bitmasks manually...
                        if !repeat && (keymod.contains(KeyboardMod::from_bits_truncate(0x0100))
                            || keymod.contains(KeyboardMod::from_bits_truncate(0x0200)))
                            && scancode == Some(sdl2::keyboard::Scancode::Return)
                        {
                            self.control.renderer.toggle_fullscreen();
                        }
                    },
                    _ => ()
                }
                
                #[cfg(feature = "imgui_integration")]
                self.control.imgui_handler.handle_event(event);
            }
            
            self.think();
            self.draw();
            self.wait();
            self.present();
            
            self.update_fps();
            
            // Go to next scene if one is requested
            if self.control.next_scene_waiting
            {
                std::mem::swap(&mut self.current_scene, &mut self.control.next_scene);
                
                // Reset jiffy queue
                self.time = GameloopTimeState::new();
                self.control.next_scene_waiting = false;
            }
        }
    }
}