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
mod native_keycode;

use glutin;
use glutin::{ElementState, Event, MouseButton, WindowEvent};
use std::cell::RefCell;
use std::env;
use std::os::raw::c_void;
use std::process;
use std::rc::Rc;
use time;

use AppConfig;
use AppEvent;

use self::native_keycode::{translate_scan_code, translate_virtual_key};
use super::events;

enum WindowContext {
    Normal(glutin::GlWindow),
    Headless(glutin::HeadlessContext),
}

impl WindowContext {
    fn hidpi_factor(&self) -> f32 {
        match self {
            WindowContext::Normal(ref w) => w.get_hidpi_factor() as f32,
            _ => 1.0,
        }
    }

    fn window(&self) -> &glutin::GlWindow {
        match self {
            WindowContext::Normal(ref w) => w,
            _ => unimplemented!(),
        }
    }

    fn context(&self) -> &dyn glutin::GlContext {
        match self {
            WindowContext::Normal(ref w) => w,
            WindowContext::Headless(ref w) => w,
        }
    }

    fn swap_buffers(&self) -> Result<(), glutin::ContextError> {
        use glutin::GlContext;
        match self {
            WindowContext::Normal(ref w) => w.swap_buffers(),
            WindowContext::Headless(_) => Ok(()),
        }
    }
}

/// the main application struct
pub struct App {
    window: WindowContext,
    events_loop: glutin::EventsLoop,
    exiting: bool,
    intercept_close_request: bool,
    pub events: Rc<RefCell<Vec<AppEvent>>>,
}

fn get_virtual_key(input: glutin::KeyboardInput) -> String {
    match input.virtual_keycode {
        Some(k) => {
            let mut s = translate_virtual_key(k).into();
            if s == "" {
                s = format!("{:?}", k);
            }
            s
        }
        None => "".into(),
    }
}

fn get_scan_code(input: glutin::KeyboardInput) -> String {
    translate_scan_code(input.scancode).into()
}

fn translate_event(e: glutin::Event, dpi_factor: f32) -> Option<AppEvent> {
    if let Event::WindowEvent {
        event: winevent, ..
    } = e
    {
        match winevent {
            WindowEvent::MouseInput { state, button, .. } => {
                let button_num = match button {
                    MouseButton::Left => 0,
                    MouseButton::Middle => 1,
                    MouseButton::Right => 2,
                    MouseButton::Other(val) => val as usize,
                };
                let event = events::MouseButtonEvent { button: button_num };
                match state {
                    ElementState::Pressed => Some(AppEvent::MouseDown(event)),
                    ElementState::Released => Some(AppEvent::MouseUp(event)),
                }
            }
            WindowEvent::CursorMoved { position, .. } => {
                let phys =
                    glutin::dpi::PhysicalPosition::from_logical(position, f64::from(dpi_factor));
                Some(AppEvent::MousePos(phys.into()))
            }
            WindowEvent::KeyboardInput { input, .. } => match input.state {
                ElementState::Pressed => Some(AppEvent::KeyDown(events::KeyDownEvent {
                    key: get_virtual_key(input),
                    code: get_scan_code(input),
                    shift: input.modifiers.shift,
                    alt: input.modifiers.alt,
                    ctrl: input.modifiers.ctrl,
                })),
                ElementState::Released => Some(AppEvent::KeyUp(events::KeyUpEvent {
                    key: get_virtual_key(input),
                    code: get_scan_code(input),
                    shift: input.modifiers.shift,
                    alt: input.modifiers.alt,
                    ctrl: input.modifiers.ctrl,
                })),
            },
            WindowEvent::ReceivedCharacter(c) => Some(AppEvent::CharEvent(c)),
            WindowEvent::Resized(size) => {
                let phys = glutin::dpi::PhysicalSize::from_logical(size, f64::from(dpi_factor));
                Some(AppEvent::Resized(phys.into()))
            }
            WindowEvent::CloseRequested => Some(AppEvent::CloseRequested),
            _ => None,
        }
    } else {
        None
    }
}

impl App {
    /// create a new game window
    pub fn new(config: AppConfig) -> App {
        use glutin::*;
        let events_loop = glutin::EventsLoop::new();
        let gl_req = GlRequest::GlThenGles {
            opengl_version: (3, 2),
            opengles_version: (2, 0),
        };

        let window = if config.headless {
            let context = glutin::HeadlessRendererBuilder::new(config.size.0, config.size.1)
                .with_gl(gl_req)
                .with_gl_profile(GlProfile::Core)
                .build()
                .unwrap();

            WindowContext::Headless(context)
        } else {
            let monitor = if config.fullscreen {
                events_loop.get_available_monitors().nth(0)
            } else {
                None
            };

            let window = glutin::WindowBuilder::new()
                .with_title(config.title)
                .with_fullscreen(monitor)
                .with_resizable(config.resizable)
                .with_dimensions((config.size.0, config.size.1).into());

            let context = glutin::ContextBuilder::new()
                .with_vsync(config.vsync)
                .with_gl(gl_req)
                .with_gl_profile(GlProfile::Core);

            let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap();

            if !config.show_cursor {
                gl_window.hide_cursor(true);
            }

            WindowContext::Normal(gl_window)
        };

        unsafe {
            window.context().make_current().unwrap();
        }

        App {
            window,
            events_loop,
            exiting: false,
            intercept_close_request: config.intercept_close_request,
            events: Rc::new(RefCell::new(Vec::new())),
        }
    }

    /// return the screen resolution in physical pixels
    pub fn get_screen_resolution(&self) -> (u32, u32) {
        if let WindowContext::Normal(ref glwindow) = self.window {
            glwindow
                .window()
                .get_current_monitor()
                .get_dimensions()
                .into()
        } else {
            (0, 0)
        }
    }

    /// return the command line / URL parameters
    pub fn get_params() -> Vec<String> {
        let mut params: Vec<String> = env::args().collect();
        params.remove(0);
        params
    }

    /// activate or deactivate fullscreen. only works on native target
    pub fn set_fullscreen(&self, b: bool) {
        if let WindowContext::Normal(ref glwindow) = self.window {
            if b {
                glwindow.set_fullscreen(Some(glwindow.window().get_current_monitor()));
            } else {
                glwindow.set_fullscreen(None);
            }
        }
    }

    /// print a message on standard output (native) or js console (web)
    pub fn print<T: Into<String>>(msg: T) {
        print!("{}", msg.into());
    }

    /// exit current process (close the game window). On web target, this does nothing.
    pub fn exit() {
        process::exit(0);
    }

    /// returns the HiDPI factor for current screen
    pub fn hidpi_factor(&self) -> f32 {
        self.window.hidpi_factor()
    }

    fn get_proc_address(&self, name: &str) -> *const c_void {
        self.window.context().get_proc_address(name) as *const c_void
    }

    /// return the opengl context for this window
    pub fn canvas<'p>(&'p self) -> Box<dyn 'p + FnMut(&str) -> *const c_void> {
        Box::new(move |name| self.get_proc_address(name))
    }

    fn handle_events(&mut self) -> bool {
        use glutin::*;
        let mut running = true;

        let dpi_factor = self.hidpi_factor();
        let (window, events_loop, events) = (&self.window, &mut self.events_loop, &mut self.events);
        let intercept_close_request = self.intercept_close_request;
        events_loop.poll_events(|event| {
            match event {
                glutin::Event::WindowEvent { ref event, .. } => match event {
                    &glutin::WindowEvent::CloseRequested => {
                        if !intercept_close_request {
                            running = false;
                        }
                    }
                    &glutin::WindowEvent::Resized(size) => {
                        // Fixed for Windows which minimized to emit a Resized(0,0) event
                        if size.width != 0.0 && size.height != 0.0 {
                            window.window().resize(size.to_physical(dpi_factor as f64));
                        }
                    }
                    &glutin::WindowEvent::KeyboardInput { input, .. } => {
                        // issue tracked in https://github.com/tomaka/winit/issues/41
                        // Right now we handle it manually.
                        if cfg!(target_os = "macos") {
                            if let Some(keycode) = input.virtual_keycode {
                                if keycode == VirtualKeyCode::Q && input.modifiers.logo {
                                    running = false;
                                }
                            }
                        }
                    }
                    _ => (),
                },
                _ => (),
            };

            translate_event(event, dpi_factor).map(|evt| events.borrow_mut().push(evt));
        });

        return running;
    }

    pub fn poll_events<F>(&mut self, callback: F) -> bool
    where
        F: FnOnce(&mut Self) -> (),
    {
        if !self.handle_events() {
            return false;
        }

        callback(self);
        self.events.borrow_mut().clear();
        self.window.swap_buffers().unwrap();

        !self.exiting
    }

    /// start the game loop, calling provided callback every frame
    pub fn run<'a, F>(mut self, mut callback: F)
    where
        F: FnMut(&mut Self) -> (),
    {
        let mut running = true;

        while running {
            running = self.handle_events();

            if !running {
                break;
            }

            callback(&mut self);
            self.events.borrow_mut().clear();
            self.window.swap_buffers().unwrap();

            if self.exiting {
                break;
            }
        }
    }
}

/// return the time since the start of the program in seconds
pub fn now() -> f64 {
    // precise_time_s() is in second
    // https://doc.rust-lang.org/time/time/fn.precise_time_s.html
    time::precise_time_s()
}