A simple map viewer

main.rs 12KB

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