2018-09-10 03:10:34 +03:00
|
|
|
use glutin_window::GlutinWindow;
|
|
|
|
use input::UserInput;
|
|
|
|
use opengl_graphics::{Filter, GlGraphics, GlyphCache, OpenGL, TextureSettings};
|
|
|
|
use piston::event_loop::{EventLoop, EventSettings, Events};
|
|
|
|
use piston::input::RenderEvent;
|
2018-10-06 21:50:55 +03:00
|
|
|
use piston::window::{Window, WindowSettings};
|
2018-12-04 20:58:34 +03:00
|
|
|
use {Canvas, GfxCtx};
|
2018-09-10 03:10:34 +03:00
|
|
|
|
2018-12-04 20:58:34 +03:00
|
|
|
pub trait GUI<T> {
|
|
|
|
fn event(&mut self, input: UserInput) -> (EventLoopMode, T);
|
2018-10-06 21:50:55 +03:00
|
|
|
fn get_mut_canvas(&mut self) -> &mut Canvas;
|
2018-12-04 20:58:34 +03:00
|
|
|
fn draw(&self, g: &mut GfxCtx, data: T);
|
2018-09-10 03:10:34 +03:00
|
|
|
}
|
|
|
|
|
2018-11-12 21:44:24 +03:00
|
|
|
#[derive(Clone, Copy, PartialEq)]
|
2018-09-10 03:10:34 +03:00
|
|
|
pub enum EventLoopMode {
|
|
|
|
Animation,
|
|
|
|
InputOnly,
|
|
|
|
}
|
|
|
|
|
2018-12-04 20:58:34 +03:00
|
|
|
pub fn run<T, G: GUI<T>>(mut gui: G, window_title: &str, initial_width: u32, initial_height: u32) {
|
2018-09-10 03:10:34 +03:00
|
|
|
let opengl = OpenGL::V3_2;
|
|
|
|
let settings = WindowSettings::new(window_title, [initial_width, initial_height])
|
|
|
|
.opengl(opengl)
|
|
|
|
.exit_on_esc(false)
|
|
|
|
// TODO it'd be cool to dynamically tweak antialiasing settings as we zoom in
|
|
|
|
.samples(2)
|
|
|
|
.srgb(false);
|
|
|
|
let mut window: GlutinWindow = settings.build().expect("Could not create window");
|
|
|
|
let mut events = Events::new(EventSettings::new().lazy(true));
|
|
|
|
let mut gl = GlGraphics::new(opengl);
|
|
|
|
|
|
|
|
let texture_settings = TextureSettings::new().filter(Filter::Nearest);
|
|
|
|
let mut glyphs = GlyphCache::new(
|
|
|
|
// TODO don't assume this exists!
|
|
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
|
|
(),
|
|
|
|
texture_settings,
|
|
|
|
).expect("Could not load font");
|
|
|
|
|
|
|
|
let mut last_event_mode = EventLoopMode::InputOnly;
|
|
|
|
while let Some(ev) = events.next(&mut window) {
|
2018-12-04 20:58:34 +03:00
|
|
|
let (new_event_mode, data) = gui.event(UserInput::new(ev.clone()));
|
2018-09-10 03:10:34 +03:00
|
|
|
// Don't constantly reset the events struct -- only when laziness changes.
|
|
|
|
if new_event_mode != last_event_mode {
|
|
|
|
events.set_lazy(new_event_mode == EventLoopMode::InputOnly);
|
|
|
|
last_event_mode = new_event_mode;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(args) = ev.render_args() {
|
|
|
|
gl.draw(args.viewport(), |c, g| {
|
2018-10-06 21:50:55 +03:00
|
|
|
let mut g = GfxCtx::new(&mut glyphs, g, c);
|
|
|
|
gui.get_mut_canvas()
|
|
|
|
.start_drawing(&mut g, window.draw_size());
|
2018-12-04 20:58:34 +03:00
|
|
|
gui.draw(&mut g, data);
|
2018-09-10 03:10:34 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|