abstreet/ezgui/src/runner.rs

380 lines
12 KiB
Rust
Raw Normal View History

2019-05-02 01:58:11 +03:00
use crate::input::ContextMenu;
2019-02-01 20:02:51 +03:00
use crate::{
widgets, Canvas, Color, Event, EventCtx, GfxCtx, HorizontalAlignment, Prerender, Text,
UserInput, VerticalAlignment,
2019-02-01 20:02:51 +03:00
};
use abstutil::{Timer, TimerSink};
use glium::glutin;
use glium_glyph::glyph_brush::rusttype::Font;
use glium_glyph::GlyphBrush;
use std::cell::Cell;
use std::time::{Duration, Instant};
2019-02-01 20:02:51 +03:00
use std::{env, panic, process, thread};
2018-09-10 03:10:34 +03:00
// 30fps is 1000 / 30
const SLEEP_BETWEEN_FRAMES: Duration = Duration::from_millis(33);
pub trait GUI {
fn event(&mut self, ctx: &mut EventCtx) -> EventLoopMode;
fn draw(&self, g: &mut GfxCtx);
// Will be called if event or draw panics.
fn dump_before_abort(&self, _canvas: &Canvas) {}
2018-12-17 22:32:52 +03:00
// Only before a normal exit, like window close
fn before_quit(&self, _canvas: &Canvas) {}
2019-02-15 00:01:26 +03:00
fn profiling_enabled(&self) -> bool {
false
}
2018-09-10 03:10:34 +03:00
}
#[derive(Clone, PartialEq)]
2018-09-10 03:10:34 +03:00
pub enum EventLoopMode {
Animation,
InputOnly,
ScreenCaptureEverything {
dir: String,
zoom: f64,
max_x: f64,
max_y: f64,
},
ScreenCaptureCurrentShot,
2018-09-10 03:10:34 +03:00
}
pub(crate) struct State<G: GUI> {
2019-02-01 20:02:51 +03:00
pub(crate) gui: G,
pub(crate) canvas: Canvas,
context_menu: ContextMenu,
}
impl<G: GUI> State<G> {
// The bool indicates if the input was actually used.
fn event(
mut self,
ev: Event,
prerender: &Prerender,
program: &glium::Program,
) -> (State<G>, EventLoopMode, bool) {
// Clear out the possible keys
match self.context_menu {
ContextMenu::Inactive(_) => {
self.context_menu = ContextMenu::new();
}
_ => {}
}
// It's impossible / very unlikey we'll grab the cursor in map space before the very first
// start_drawing call.
let mut input = UserInput::new(ev, self.context_menu, &mut self.canvas);
let mut gui = self.gui;
let mut canvas = self.canvas;
let event_mode = match panic::catch_unwind(panic::AssertUnwindSafe(|| {
gui.event(&mut EventCtx {
input: &mut input,
canvas: &mut canvas,
prerender,
program,
})
})) {
Ok(pair) => pair,
Err(err) => {
gui.dump_before_abort(&canvas);
panic::resume_unwind(err);
}
};
self.gui = gui;
self.canvas = canvas;
// TODO We should always do has_been_consumed, but various hacks prevent this from being
// true. For now, just avoid the specific annoying redraw case when a KeyRelease or Update
// event is unused.
let input_used = match ev {
Event::KeyRelease(_) | Event::Update => input.has_been_consumed(),
_ => true,
};
self.context_menu = input.context_menu.maybe_build(&self.canvas);
(self, event_mode, input_used)
}
// Returns naming hint. Logically consumes the number of uploads.
2019-02-01 20:10:39 +03:00
pub(crate) fn draw(
&mut self,
display: &glium::Display,
program: &glium::Program,
prerender: &Prerender,
2019-02-01 20:10:39 +03:00
screenshot: bool,
) -> Option<String> {
let mut target = display.draw();
let mut g = GfxCtx::new(
&self.canvas,
&prerender,
display,
&mut target,
program,
&self.context_menu,
screenshot,
);
self.canvas.start_drawing();
if let Err(err) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
self.gui.draw(&mut g);
})) {
self.gui.dump_before_abort(&self.canvas);
panic::resume_unwind(err);
}
let naming_hint = g.naming_hint.take();
// Always draw the menus last.
if let ContextMenu::Displaying(ref menu) = self.context_menu {
menu.draw(&mut g);
}
2019-01-14 21:24:11 +03:00
target.finish().unwrap();
2019-02-01 20:10:39 +03:00
naming_hint
2019-01-14 21:24:11 +03:00
}
}
pub fn run<G: GUI, F: FnOnce(&mut Canvas, &Prerender, &mut Timer) -> G>(
window_title: &str,
initial_width: f64,
initial_height: f64,
make_gui: F,
) {
// DPI is broken on my system; force the old behavior.
env::set_var("WINIT_HIDPI_FACTOR", "1.0");
let events_loop = glutin::EventsLoop::new();
let window = glutin::WindowBuilder::new()
.with_title(window_title)
.with_dimensions(glutin::dpi::LogicalSize::new(initial_width, initial_height));
// 2 looks bad, 4 looks fine
let context = glutin::ContextBuilder::new().with_multisampling(4);
let display = glium::Display::new(window, context, &events_loop).unwrap();
2019-03-19 00:57:46 +03:00
let (vertex_shader, fragment_shader) =
if display.is_glsl_version_supported(&glium::Version(glium::Api::Gl, 1, 4)) {
(
include_str!("assets/vertex_140.glsl"),
include_str!("assets/fragment_140.glsl"),
)
} else if display.is_glsl_version_supported(&glium::Version(glium::Api::Gl, 1, 1)) {
(
include_str!("assets/vertex_110.glsl"),
include_str!("assets/fragment_110.glsl"),
)
} else {
panic!(
"GLSL 140 and 110 not supported. Try {:?} or {:?}",
display.get_opengl_version(),
display.get_supported_glsl_version()
);
};
2019-01-24 09:27:32 +03:00
let program = glium::Program::new(
&display,
2019-01-24 09:27:32 +03:00
glium::program::ProgramCreationInput::SourceCode {
2019-03-19 00:57:46 +03:00
vertex_shader,
2019-01-24 09:27:32 +03:00
tessellation_control_shader: None,
tessellation_evaluation_shader: None,
geometry_shader: None,
2019-03-19 00:57:46 +03:00
fragment_shader,
2019-01-24 09:27:32 +03:00
transform_feedback_varyings: None,
// Without this, SRGB gets enabled and post-processes the color from the fragment
// shader.
outputs_srgb: true,
uses_point_size: false,
},
)
.unwrap();
2019-02-01 20:30:26 +03:00
let dejavu: &[u8] = include_bytes!("assets/DejaVuSans.ttf");
2019-04-23 05:01:55 +03:00
let glyphs = GlyphBrush::new(&display, vec![Font::from_bytes(dejavu).unwrap()]);
2019-04-23 05:01:55 +03:00
let mut canvas = Canvas::new(initial_width, initial_height, glyphs);
let prerender = Prerender {
display: &display,
num_uploads: Cell::new(0),
total_bytes_uploaded: Cell::new(0),
};
2019-04-03 02:18:12 +03:00
let gui = {
let mut timer = Timer::new_with_sink(
"Loading application...",
Box::new(LoadingScreen::new(
&prerender,
&program,
initial_width,
initial_height,
)),
);
make_gui(&mut canvas, &prerender, &mut timer)
};
let state = State {
canvas,
context_menu: ContextMenu::new(),
gui,
};
loop_forever(state, events_loop, program, prerender);
}
fn loop_forever<G: GUI>(
mut state: State<G>,
mut events_loop: glutin::EventsLoop,
program: glium::Program,
prerender: Prerender,
) {
2019-02-15 00:01:26 +03:00
if state.gui.profiling_enabled() {
2019-04-19 19:16:13 +03:00
#[cfg(target_os = "linux")]
{
cpuprofiler::PROFILER
.lock()
.unwrap()
.start("./profile")
.unwrap();
}
2019-02-15 00:01:26 +03:00
}
2019-01-24 22:47:46 +03:00
let mut wait_for_events = false;
loop {
let start_frame = Instant::now();
let mut new_events: Vec<Event> = Vec::new();
events_loop.poll_events(|event| {
if let glutin::Event::WindowEvent { event, .. } = event {
if event == glutin::WindowEvent::CloseRequested {
2019-02-15 00:01:26 +03:00
if state.gui.profiling_enabled() {
2019-04-19 19:16:13 +03:00
#[cfg(target_os = "linux")]
{
cpuprofiler::PROFILER.lock().unwrap().stop().unwrap();
}
2019-02-15 00:01:26 +03:00
}
state.gui.before_quit(&state.canvas);
process::exit(0);
}
if let Some(ev) = Event::from_glutin_event(event) {
new_events.push(ev);
}
}
});
if !wait_for_events {
new_events.push(Event::Update);
}
let mut any_input_used = false;
for event in new_events {
let (new_state, mode, input_used) = state.event(event, &prerender, &program);
if input_used {
any_input_used = true;
}
2019-01-24 22:47:46 +03:00
state = new_state;
wait_for_events = mode == EventLoopMode::InputOnly;
match mode {
EventLoopMode::ScreenCaptureEverything {
dir,
zoom,
max_x,
max_y,
} => {
state = widgets::screenshot_everything(
&dir,
state,
&prerender.display,
&program,
&prerender,
zoom,
max_x,
max_y,
);
}
EventLoopMode::ScreenCaptureCurrentShot => {
widgets::screenshot_current(
&mut state,
&prerender.display,
&program,
&prerender,
);
}
_ => {}
};
}
// Don't draw if an event was ignored. Every keypress also fires a release event, most of
// which are ignored.
if any_input_used {
state.draw(&prerender.display, &program, &prerender, false);
prerender.num_uploads.set(0);
}
// Primitive event loop.
// TODO Read http://gameprogrammingpatterns.com/game-loop.html carefully.
let this_frame = Instant::now().duration_since(start_frame);
if SLEEP_BETWEEN_FRAMES > this_frame {
thread::sleep(SLEEP_BETWEEN_FRAMES - this_frame);
2019-01-23 09:30:25 +03:00
}
}
}
pub struct LoadingScreen<'a> {
canvas: Canvas,
prerender: &'a Prerender<'a>,
program: &'a glium::Program,
lines: Vec<String>,
}
impl<'a> LoadingScreen<'a> {
pub fn new(
prerender: &'a Prerender<'a>,
program: &'a glium::Program,
initial_width: f64,
initial_height: f64,
) -> LoadingScreen<'a> {
// TODO Ew! Expensive and wacky. Fix by not storing GlyphBrush in Canvas at all.
let dejavu: &[u8] = include_bytes!("assets/DejaVuSans.ttf");
let glyphs = GlyphBrush::new(prerender.display, vec![Font::from_bytes(dejavu).unwrap()]);
let canvas = Canvas::new(initial_width, initial_height, glyphs);
LoadingScreen {
canvas,
prerender,
program,
lines: Vec::new(),
}
}
fn redraw(&self, text: Text) {
let mut target = self.prerender.display.draw();
let context_menu = ContextMenu::new();
let mut g = GfxCtx::new(
&self.canvas,
self.prerender,
self.prerender.display,
&mut target,
self.program,
&context_menu,
false,
);
g.clear(Color::BLACK);
g.draw_blocking_text(
&text,
(HorizontalAlignment::Center, VerticalAlignment::Center),
);
target.finish().unwrap();
}
}
impl<'a> TimerSink for LoadingScreen<'a> {
fn println(&mut self, line: String) {
self.lines.push(line);
let mut txt = Text::prompt("Loading...");
for l in &self.lines {
txt.add_line(l.to_string());
}
self.redraw(txt);
}
}