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
extern crate gfx;
extern crate gfx_device_gl;
extern crate glutin;
extern crate time;


use std::thread::sleep;
use std::time::{Duration, Instant};
use std::cmp;
const CLEAR_COLOR: [f32; 4] = [0.0, 0., 0., 1.0];
use self::glutin::ElementState;
use self::glutin::GlContext;
pub use self::glutin::VirtualKeyCode as Key;
use gfx::Device;
use graphics::camera::OrthoCamera;
use graphics::context::Context;
use graphics::pipeline::Transform;

#[derive(Copy, Clone, Debug)]
pub struct EventSettings {
    pub max_fps: u64,
    pub ups: u64,
    pub ups_reset: u64,
    pub swap_buffers: bool,
    pub bench_mode: bool,
    pub lazy: bool,
}

impl EventSettings {
    /// Creates new with default settings.
    pub fn new() -> EventSettings {
        EventSettings {
            max_fps: DEFAULT_MAX_FPS,
            ups: DEFAULT_UPS,
            swap_buffers: true,
            bench_mode: false,
            lazy: false,
            ups_reset: DEFAULT_UPS_RESET,
        }
    }
}

impl Default for EventSettings {
    fn default() -> EventSettings {
        EventSettings::new()
    }
}


/// The default updates per second.
pub const DEFAULT_UPS: u64 = 120;
/// The default delayed updates reset.
pub const DEFAULT_UPS_RESET: u64 = 2;
/// The default maximum frames per second.
pub const DEFAULT_MAX_FPS: u64 = 60;


static BILLION: u64 = 1_000_000_000;

fn ns_to_duration(ns: u64) -> Duration {
    let secs = ns / BILLION;
    let nanos = (ns % BILLION) as u32;
    Duration::new(secs, nanos)
}

fn duration_to_secs(dur: Duration) -> f32 {
    dur.as_secs() as f32 + dur.subsec_nanos() as f32 / 1_000_000_000.0
}




/// Do all operations with Window and GameLoop
pub fn run<State>(ctx: &mut Context, state: &mut State, ups: u64)
where
    State: MainLoop,
{
    let mut running = true;
    let mut transform = Transform {
        combined: ctx.camera.combined(),
    };

    let start = Instant::now();

    let mut last_update = start;
    let mut last_frame = start;
    let mut dt_update_in_ns = BILLION / ups;
    let mut dt_frame_in_ns = BILLION  / ups;
    let mut dt = 1.0 / ups as f32;
    let mut first_frame = true;




    while running {
            ctx.events.poll_events(|event| {
                if let glutin::Event::WindowEvent { event, .. } = event {
                    match event {
                        glutin::WindowEvent::CloseRequested
                        | glutin::WindowEvent::KeyboardInput {
                            input:
                                glutin::KeyboardInput {
                                    virtual_keycode: Some(Key::Escape),
                                    ..
                                },
                            ..
                        } => running = false,
                        glutin::WindowEvent::KeyboardInput {
                            input:
                                glutin::KeyboardInput {
                                    virtual_keycode: Some(keycode),
                                    state: ElementState::Pressed,
                                    ..
                                },
                            ..
                        } => {
                            state.button_down(keycode);
                        }
                        glutin::WindowEvent::KeyboardInput {
                            input:
                                glutin::KeyboardInput {
                                    virtual_keycode: Some(keycode),
                                    state: ElementState::Released,
                                    ..
                                },
                            ..
                        } => {
                            state.button_release(keycode);
                        }

                        _ => {}
                    }
                }
            });
            state.update(ctx, 1.0);


            match ctx.encoder
                .update_buffer(&ctx.data.transform, &[transform], 0)
            {
                Err(err) => {
                    println!("Error: {:?}", err);
                }
                _ => {}
            }
            transform.combined = ctx.camera.combined();

            ctx.encoder.clear(&ctx.data.out, CLEAR_COLOR);

            state.draw(ctx);
            ctx.encoder.flush(&mut ctx.device);
            ctx.window.swap_buffers().unwrap();
            ctx.device.cleanup();
            let cur_time = Instant::now();

            let next_frame = last_frame + ns_to_duration(dt_frame_in_ns);
            let next_update = last_update + ns_to_duration(dt_update_in_ns);
            let next_event = cmp::min(next_frame,next_update);

            if next_event > cur_time {
                sleep(next_event - cur_time);
            }
    }
}

///MainLoop
pub trait MainLoop {
    /// Update function, called every time
    fn update(&mut self, ctx: &mut Context, dt: f32);
    /// Draw function, called every time
    fn draw(&mut self, ctx: &mut Context);
    /// Called when keyboard button pressed
    fn button_down(&mut self, _button: Key) {}
    /// Called when keyboard button released
    fn button_release(&mut self, _button: Key) {}
}