A simple map viewer

main.rs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #[macro_use]
  2. extern crate clap;
  3. extern crate env_logger;
  4. extern crate glutin;
  5. extern crate image;
  6. extern crate linked_hash_map;
  7. #[macro_use]
  8. extern crate log;
  9. extern crate reqwest;
  10. extern crate toml;
  11. extern crate xdg;
  12. pub mod args;
  13. #[macro_use]
  14. pub mod context;
  15. pub mod buffer;
  16. pub mod config;
  17. pub mod coord;
  18. pub mod map_view;
  19. pub mod map_view_gl;
  20. pub mod program;
  21. pub mod texture;
  22. pub mod tile;
  23. pub mod tile_cache;
  24. pub mod tile_atlas;
  25. pub mod tile_loader;
  26. pub mod tile_source;
  27. use coord::ScreenCoord;
  28. use glutin::{ControlFlow, ElementState, Event, GlContext, MouseButton, MouseScrollDelta, VirtualKeyCode, WindowEvent};
  29. use map_view_gl::MapViewGl;
  30. use std::time::{Duration, Instant};
  31. use tile_source::TileSource;
  32. #[derive(Copy, Clone, Debug, PartialEq, Eq)]
  33. enum Action {
  34. Nothing,
  35. Redraw,
  36. Close,
  37. }
  38. #[derive(Copy, Clone, Debug, PartialEq)]
  39. struct InputState {
  40. mouse_position: (f64, f64),
  41. mouse_pressed: bool,
  42. }
  43. fn handle_event(event: &Event, map: &mut MapViewGl, input_state: &mut InputState, sources: &mut TileSources) -> Action {
  44. match *event {
  45. Event::Awakened => Action::Redraw,
  46. Event::WindowEvent{ref event, ..} => match *event {
  47. WindowEvent::CloseRequested => Action::Close,
  48. WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => {
  49. input_state.mouse_pressed = true;
  50. Action::Nothing
  51. },
  52. WindowEvent::MouseInput { state: ElementState::Released, button: MouseButton::Left, .. } => {
  53. input_state.mouse_pressed = false;
  54. Action::Nothing
  55. },
  56. WindowEvent::CursorMoved { position: (x, y), .. } => {
  57. if input_state.mouse_pressed {
  58. map.move_pixel(
  59. input_state.mouse_position.0 - x,
  60. input_state.mouse_position.1 - y,
  61. );
  62. input_state.mouse_position = (x, y);
  63. Action::Redraw
  64. } else {
  65. input_state.mouse_position = (x, y);
  66. Action::Nothing
  67. }
  68. },
  69. WindowEvent::MouseWheel { delta, modifiers, .. } => {
  70. let (dx, dy) = match delta {
  71. MouseScrollDelta::LineDelta(dx, dy) => {
  72. // filter strange wheel events with huge values.
  73. // (maybe this is just a personal touchpad driver issue)
  74. if dx.abs() < 16.0 && dy.abs() < 16.0 {
  75. //TODO find a sensible line height value (servo (the glutin port) uses 38)
  76. (dx, dy * 38.0)
  77. } else {
  78. (0.0, 0.0)
  79. }
  80. },
  81. MouseScrollDelta::PixelDelta(dx, dy) => (dx, dy),
  82. };
  83. //TODO add option for default mouse wheel behavior (scroll or zoom?)
  84. //TODO add option to reverse scroll/zoom direction
  85. if modifiers.ctrl {
  86. map.move_pixel(f64::from(-dx), f64::from(-dy));
  87. } else {
  88. map.zoom_at(
  89. ScreenCoord::new(
  90. input_state.mouse_position.0,
  91. input_state.mouse_position.1,
  92. ),
  93. f64::from(dy) * (1.0 / 320.0),
  94. );
  95. }
  96. Action::Redraw
  97. },
  98. WindowEvent::KeyboardInput {
  99. input: glutin::KeyboardInput {
  100. state: glutin::ElementState::Pressed,
  101. virtual_keycode: Some(keycode),
  102. modifiers,
  103. .. },
  104. .. } => {
  105. match keycode {
  106. VirtualKeyCode::Escape => {
  107. Action::Close
  108. },
  109. VirtualKeyCode::PageUp => {
  110. sources.switch_to_prev();
  111. Action::Redraw
  112. },
  113. VirtualKeyCode::PageDown => {
  114. sources.switch_to_next();
  115. Action::Redraw
  116. },
  117. VirtualKeyCode::Left => {
  118. map.move_pixel(-50.0, 0.0);
  119. Action::Redraw
  120. },
  121. VirtualKeyCode::Right => {
  122. map.move_pixel(50.0, 0.0);
  123. Action::Redraw
  124. },
  125. VirtualKeyCode::Up => {
  126. map.move_pixel(0.0, -50.0);
  127. Action::Redraw
  128. },
  129. VirtualKeyCode::Down => {
  130. map.move_pixel(0.0, 50.0);
  131. Action::Redraw
  132. },
  133. VirtualKeyCode::Add => {
  134. if modifiers.ctrl {
  135. map.change_tile_zoom_offset(1.0);
  136. } else {
  137. map.step_zoom(1, 1.0);
  138. }
  139. Action::Redraw
  140. },
  141. VirtualKeyCode::Subtract => {
  142. if modifiers.ctrl {
  143. map.change_tile_zoom_offset(-1.0);
  144. } else {
  145. map.step_zoom(-1, 1.0);
  146. }
  147. Action::Redraw
  148. },
  149. _ => Action::Nothing,
  150. }
  151. },
  152. WindowEvent::Refresh => {
  153. Action::Redraw
  154. },
  155. WindowEvent::Resized(w, h) => {
  156. map.set_viewport_size(w, h);
  157. Action::Redraw
  158. },
  159. _ => Action::Nothing,
  160. },
  161. _ => Action::Nothing,
  162. }
  163. }
  164. fn dur_to_sec(dur: Duration) -> f64 {
  165. dur.as_secs() as f64 + f64::from(dur.subsec_nanos()) * 1e-9
  166. }
  167. fn main() {
  168. env_logger::init();
  169. let config = config::Config::from_arg_matches(&args::parse()).unwrap();
  170. let mut sources = TileSources::new(config.tile_sources()).unwrap();
  171. let mut events_loop = glutin::EventsLoop::new();
  172. let builder = glutin::WindowBuilder::new()
  173. .with_title(format!("DeltaMap - {}", sources.current_name()));
  174. let gl_context = glutin::ContextBuilder::new();
  175. let gl_window = glutin::GlWindow::new(builder, gl_context, &events_loop).unwrap();
  176. let window = gl_window.window();
  177. let _ = unsafe { gl_window.make_current() };
  178. let cx = context::Context::from_gl_window(&gl_window);
  179. let mut map = {
  180. let proxy = events_loop.create_proxy();
  181. map_view_gl::MapViewGl::new(
  182. &cx,
  183. window.get_inner_size().unwrap(),
  184. move || { proxy.wakeup().unwrap(); },
  185. config.use_network(),
  186. config.async(),
  187. )
  188. };
  189. let mut input_state = InputState {
  190. mouse_position: (0.0, 0.0),
  191. mouse_pressed: false,
  192. };
  193. let duration_per_frame = Duration::from_millis((1000.0 / config.fps() - 0.5).max(0.0).floor() as u64);
  194. info!("milliseconds per frame: {}", dur_to_sec(duration_per_frame) * 1000.0);
  195. // estimated draw duration
  196. let mut est_draw_dur = duration_per_frame;
  197. let mut last_draw = Instant::now();
  198. let mut increase_atlas_size = true;
  199. loop {
  200. let start_source_id = sources.current().id();
  201. let mut redraw = false;
  202. let mut close = false;
  203. events_loop.run_forever(|event| {
  204. match handle_event(&event, &mut map, &mut input_state, &mut sources) {
  205. Action::Close => close = true,
  206. Action::Redraw => redraw = true,
  207. Action::Nothing => {},
  208. }
  209. ControlFlow::Break
  210. });
  211. if close {
  212. break;
  213. }
  214. events_loop.poll_events(|event| {
  215. match handle_event(&event, &mut map, &mut input_state, &mut sources) {
  216. Action::Close => {
  217. close = true;
  218. return;
  219. },
  220. Action::Redraw => {
  221. redraw = true;
  222. },
  223. Action::Nothing => {},
  224. }
  225. });
  226. if close {
  227. break;
  228. }
  229. {
  230. let diff = last_draw.elapsed();
  231. if diff + est_draw_dur * 2 < duration_per_frame {
  232. if let Some(dur) = duration_per_frame.checked_sub(est_draw_dur * 2) {
  233. std::thread::sleep(dur);
  234. events_loop.poll_events(|event| {
  235. match handle_event(&event, &mut map, &mut input_state, &mut sources) {
  236. Action::Close => {
  237. close = true;
  238. return;
  239. },
  240. Action::Redraw => {
  241. redraw = true;
  242. },
  243. Action::Nothing => {},
  244. }
  245. });
  246. if close {
  247. break;
  248. }
  249. }
  250. }
  251. }
  252. if redraw {
  253. let draw_start = Instant::now();
  254. let draw_result = map.draw(sources.current());
  255. let draw_dur = draw_start.elapsed();
  256. let _ = gl_window.swap_buffers();
  257. // Move glClear call out of the critical path.
  258. //TODO do not call glClear when drawing fills the whole screen anyway
  259. cx.clear_color((0.2, 0.2, 0.2, 1.0));
  260. //TODO increase atlas size earlier to avoid excessive copying to the GPU
  261. //TODO increase max tile cache size?
  262. increase_atlas_size = {
  263. match (draw_result, increase_atlas_size) {
  264. (Err(draws), true) if draws > 1 => {
  265. map.increase_atlas_size().is_ok()
  266. },
  267. (Ok(draws), true) if draws > 1 => {
  268. map.increase_atlas_size().is_ok()
  269. },
  270. _ => increase_atlas_size,
  271. }
  272. };
  273. last_draw = Instant::now();
  274. debug!("draw: {} sec (est {} sec)", dur_to_sec(draw_dur), dur_to_sec(est_draw_dur));
  275. est_draw_dur = if draw_dur > est_draw_dur {
  276. draw_dur
  277. } else {
  278. (draw_dur / 4) + ((est_draw_dur / 4) * 3)
  279. };
  280. }
  281. // set window title
  282. if sources.current().id() != start_source_id {
  283. window.set_title(&format!("DeltaMap - {}", sources.current_name()));
  284. }
  285. }
  286. }
  287. struct TileSources<'a> {
  288. current_index: usize,
  289. sources: &'a [(String, TileSource)],
  290. }
  291. impl<'a> TileSources<'a> {
  292. pub fn new(sources: &'a [(String, TileSource)]) -> Option<TileSources> {
  293. if sources.is_empty() {
  294. None
  295. } else {
  296. Some(TileSources {
  297. current_index: 0,
  298. sources,
  299. })
  300. }
  301. }
  302. pub fn current(&self) -> &TileSource {
  303. &self.sources[self.current_index].1
  304. }
  305. pub fn current_name(&self) -> &str {
  306. &self.sources[self.current_index].0
  307. }
  308. pub fn switch_to_next(&mut self) {
  309. self.current_index = (self.current_index + 1) % self.sources.len();
  310. }
  311. pub fn switch_to_prev(&mut self) {
  312. self.current_index = (self.current_index + self.sources.len().saturating_sub(1)) % self.sources.len();
  313. }
  314. }