A simple map viewer

main.rs 13KB

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