A simple map viewer

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