You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.5 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "math.h"
  2. #include "map_view.h"
  3. MapView::MapView(SDL_Window *window, int width, int height, int zoom): window(window), offsetx(0), offsety(0), zoom(zoom){
  4. resize(width, height);
  5. update_bounds();
  6. }
  7. void MapView::center_coords(double lat, double lng){
  8. double x = (lng + 180.0f) / 360.0f;
  9. double y = (1.0f - log(tan(lat * M_PI / 180.0f) + 1.0f / cos(lat * M_PI / 180.0f)) / M_PI) / 2.0f;
  10. offsetx = x * (TILESIZE << zoom) - width / 2;
  11. offsety = y * (TILESIZE << zoom) - height / 2;
  12. }
  13. void MapView::render(){
  14. SDL_Surface *screen = SDL_GetWindowSurface(window);
  15. tiles.render(screen, offsetx, offsety);
  16. SDL_UpdateWindowSurface(window);
  17. }
  18. void MapView::move_by(int dx, int dy){
  19. offsetx += dx;
  20. offsety += dy;
  21. }
  22. void MapView::zoom_at(int x, int y){
  23. if(zoom < 22){
  24. zoom++;
  25. offsetx = offsetx * 2 + x;
  26. offsety = offsety * 2 + y;
  27. }
  28. }
  29. void MapView::zoom_in(){
  30. zoom_at(width / 2, height / 2);
  31. }
  32. void MapView::zoom_out(){
  33. if(zoom > 3){
  34. zoom--;
  35. offsetx = (offsetx - width / 2) / 2;
  36. offsety = (offsety - height / 2) / 2;
  37. }
  38. }
  39. void MapView::resize(int w, int h){
  40. /* keep the same center*/
  41. offsetx += (width - w) / 2;
  42. offsety += (height - h) / 2;
  43. width = w;
  44. height = h;
  45. }
  46. void MapView::update_bounds(){
  47. int maxy = (1 << zoom) * TILESIZE - height;
  48. if(offsety < 0)
  49. offsety = 0;
  50. else if(offsety > maxy)
  51. offsety = maxy;
  52. /* Make our x offset loop back around*/
  53. offsetx = mod(offsetx, TILESIZE * (1 << zoom));
  54. tiles.set_bounds(offsetx / TILESIZE, offsety / TILESIZE, (offsetx + width) / TILESIZE, (offsety + height) / TILESIZE, zoom);
  55. }