A simple map viewer

main.rs 15KB

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