A simple map viewer

main.rs 17KB

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