A simple map viewer

main.rs 14KB

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