AltosSiteMap: extend map if rocket goes far away
[fw/altos] / ao-tools / altosui / AltosSiteMap.java
1 /*
2  * Copyright © 2010 Anthony Towns <aj@erisian.com.au>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 package altosui;
19
20 import java.awt.*;
21 import java.awt.image.*;
22 import java.awt.event.*;
23 import javax.swing.*;
24 import javax.swing.event.MouseInputAdapter;
25 import javax.imageio.ImageIO;
26 import javax.swing.table.*;
27 import java.io.*;
28 import java.util.*;
29 import java.text.*;
30 import java.util.prefs.*;
31 import java.lang.Math;
32 import java.awt.geom.Point2D;
33 import java.awt.geom.Line2D;
34
35 public class AltosSiteMap extends JScrollPane implements AltosFlightDisplay {
36         // preferred vertical step in a tile in naut. miles
37         // will actually choose a step size between x and 2x, where this
38         // is 1.5x
39         static final double tile_size_nmi = 0.75;
40
41         static final int px_size = 512;
42
43         private static Point2D.Double translatePoint(Point2D.Double p,
44                         Point2D.Double d)
45         {
46                 return new Point2D.Double(p.x + d.x, p.y + d.y);
47         }
48
49         static class LatLng {
50                 public double lat, lng;
51                 public LatLng(double lat, double lng) {
52                         this.lat = lat;
53                         this.lng = lng;
54                 }
55         }
56
57         // based on google js
58         //  http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
59         // search for fromLatLngToPoint and fromPointToLatLng
60         private static Point2D.Double pt(LatLng latlng, int zoom) {
61                 double scale_x = 256/360.0 * Math.pow(2, zoom);
62                 double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
63                 return pt(latlng, scale_x, scale_y);
64         }
65
66         private static Point2D.Double pt(LatLng latlng,
67                                          double scale_x, double scale_y)
68         {
69                 Point2D.Double res = new Point2D.Double();
70                 double e;
71
72                 res.x = latlng.lng * scale_x;
73
74                 e = Math.sin(Math.toRadians(latlng.lat));
75                 e = Math.max(e,-(1-1.0E-15));
76                 e = Math.min(e,  1-1.0E-15 );
77
78                 res.y = 0.5*Math.log((1+e)/(1-e))*-scale_y;
79                 return res;
80         }
81
82         static private LatLng latlng(Point2D.Double pt,
83                                      double scale_x, double scale_y)
84         {
85                 double lat, lng;
86                 double rads;
87
88                 lng = pt.x/scale_x;
89                 rads = 2 * Math.atan(Math.exp(-pt.y/scale_y));
90                 lat = Math.toDegrees(rads - Math.PI/2);
91
92                 return new LatLng(lat,lng);
93         }
94
95         int zoom;
96         double scale_x, scale_y;
97
98         private Point2D.Double pt(double lat, double lng) {
99                 return pt(new LatLng(lat, lng), scale_x, scale_y);
100         }
101
102         private LatLng latlng(double x, double y) {
103                 return latlng(new Point2D.Double(x,y), scale_x, scale_y);
104         }
105         private LatLng latlng(Point2D.Double pt) {
106                 return latlng(pt, scale_x, scale_y);
107         }
108
109         Vector<AltosSiteMapTile> mapTiles = new Vector<AltosSiteMapTile>();
110         Point2D.Double centre;
111
112         private Point tileOffset(AltosSiteMapTile tile) {
113                 GridBagConstraints c = layout.getConstraints(tile);
114                 return new Point(c.gridx - 100, c.gridy - 100);
115         }
116         private Point2D.Double tileCoordOffset(AltosSiteMapTile tile) {
117                 Point p = tileOffset(tile);
118                 return new Point2D.Double(centre.x - p.x*px_size,
119                                           centre.y - p.y * px_size);
120         }
121
122         private Point tileOffset(Point2D.Double p) {
123                 return new Point((int)Math.floor((centre.x+p.x)/px_size),
124                                  (int)Math.floor((centre.y+p.y)/px_size));
125         }
126
127         private Point2D.Double getBaseLocation(double lat, double lng) {
128                 Point2D.Double locn, north_step;
129
130                 zoom = 2;
131                 // stupid loop structure to please Java's control flow analysis
132                 do {
133                         zoom++;
134                         scale_x = 256/360.0 * Math.pow(2, zoom);
135                         scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
136                         locn = pt(lat, lng);
137                         north_step = pt(lat+tile_size_nmi*4/3/60.0, lng);
138                         if (locn.y - north_step.y > px_size)
139                                 break;
140                 } while (zoom < 22);
141                 locn.x = -px_size * Math.floor(locn.x/px_size);
142                 locn.y = -px_size * Math.floor(locn.y/px_size);
143                 return locn;
144         }
145
146         public void reset() {
147                 // nothing
148         }
149
150         private void bgLoadMap(final AltosSiteMapTile tile,
151                                final File pngfile, final String pngurl)
152         {
153                 //System.out.printf("Loading/fetching map %s\n", pngfile);
154                 Thread thread = new Thread() {
155                         public void run() {
156                                 ImageIcon res;
157                                 res = AltosSiteMapCache.fetchAndLoadMap(pngfile, pngurl);
158                                 if (res != null) {
159                                         tile.loadMap(res);
160                                 } else {
161                                         System.out.printf("# Failed to fetch file %s\n", pngfile);
162                                         System.out.printf(" wget -O '%s' ''\n", pngfile, pngurl);
163                                 }
164                         }
165                 };
166                 thread.start();
167         }
168
169         public static void prefetchMaps(double lat, double lng, int w, int h) {
170                 AltosPreferences.init(null);
171
172                 AltosSiteMap asm = new AltosSiteMap(true);
173                 asm.centre = asm.getBaseLocation(lat, lng);
174
175                 Point2D.Double p = new Point2D.Double();
176                 Point2D.Double p2;
177                 int dx = -w/2, dy = -h/2;
178                 for (int y = dy; y < h+dy; y++) {
179                         for (int x = dx; x < w+dx; x++) {
180                                 LatLng map_latlng = asm.latlng(
181                                                             -asm.centre.x + x*px_size + px_size/2,
182                                                             -asm.centre.y + y*px_size + px_size/2);
183                                 File pngfile = asm.MapFile(map_latlng.lat, map_latlng.lng);
184                                 String pngurl = asm.MapURL(map_latlng.lat, map_latlng.lng);
185                                 if (pngfile.exists()) {
186                                         System.out.printf("Already have %s\n", pngfile);
187                                 } else if (AltosSiteMapCache.fetchMap(pngfile, pngurl)) {
188                                         System.out.printf("Fetched map %s\n", pngfile);
189                                 } else {
190                                         System.out.printf("# Failed to fetch file %s\n", pngfile);
191                                         System.out.printf(" wget -O '%s' ''\n", pngfile, pngurl);
192                                 }
193                         }
194                 }
195         }
196
197         private void initMap(AltosSiteMapTile tile) {
198                 Point2D.Double offset = tileCoordOffset(tile);
199
200                 LatLng map_latlng = latlng(px_size/2-offset.x, px_size/2-offset.y);
201
202                 File pngfile = MapFile(map_latlng.lat, map_latlng.lng);
203                 String pngurl = MapURL(map_latlng.lat, map_latlng.lng);
204                 bgLoadMap(tile, pngfile, pngurl);
205         }
206
207         private void initMaps(double lat, double lng) {
208                 centre = getBaseLocation(lat, lng);
209
210                 for (AltosSiteMapTile tile : mapTiles) {
211                         initMap(tile);
212                 }
213         }
214
215         private File MapFile(double lat, double lng) {
216                 char chlat = lat < 0 ? 'S' : 'N';
217                 char chlng = lng < 0 ? 'E' : 'W';
218                 if (lat < 0) lat = -lat;
219                 if (lng < 0) lng = -lng;
220                 return new File(AltosPreferences.logdir(),
221                                 String.format("map-%c%.6f,%c%.6f-%d.png",
222                                               chlat, lat, chlng, lng, zoom));
223         }
224
225         private String MapURL(double lat, double lng) {
226                 return String.format("http://maps.google.com/maps/api/staticmap?center=%.6f,%.6f&zoom=%d&size=%dx%d&sensor=false&maptype=hybrid&format=png32", lat, lng, zoom, px_size, px_size);
227         }
228
229         boolean initialised = false;
230         Point2D.Double last_pt = null;
231         int last_state = -1;
232         public void show(AltosState state, int crc_errors) {
233                 // if insufficient gps data, nothing to update
234                 if (state.gps == null)
235                         return;
236                 if (!state.gps.locked) {
237                         if (state.pad_lat == 0 && state.pad_lon == 0)
238                                 return;
239                         if (state.gps.nsat < 4)
240                                 return;
241                 }
242
243                 if (!initialised) {
244                         initMaps(state.pad_lat, state.pad_lon);
245                         initialised = true;
246                 }
247
248                 Point2D.Double pt = pt(state.gps.lat, state.gps.lon);
249                 if (last_pt == pt && last_state == state.state)
250                         return;
251
252                 if (last_pt == null) {
253                         last_pt = pt;
254                 }
255                 boolean in_any = false;
256                 for (AltosSiteMapTile tile : mapTiles) {
257                         Point2D.Double ref, lref;
258                         ref = translatePoint(pt, tileCoordOffset(tile));
259                         lref = translatePoint(last_pt, tileCoordOffset(tile));
260                         tile.show(state, crc_errors, lref, ref);
261                         if (0 <= ref.x && ref.x < px_size)
262                                 if (0 <= ref.y && ref.y < px_size)
263                                         in_any = true;
264                 }
265                 if (!in_any) {
266                         AltosSiteMapTile tile = addTileAt(tileOffset(pt));
267                         Point2D.Double ref, lref;
268                         ref = translatePoint(pt, tileCoordOffset(tile));
269                         lref = translatePoint(last_pt, tileCoordOffset(tile));
270                         initMap(tile);
271                         setViewportView(comp);
272                         tile.show(state, crc_errors, lref, ref);
273                 }
274                 last_pt = pt;
275                 last_state = state.state;
276         }
277
278         private AltosSiteMapTile addTileAt(Point offset) {
279                 GridBagConstraints c = new GridBagConstraints();
280                 c.anchor = GridBagConstraints.CENTER;
281                 c.fill = GridBagConstraints.BOTH;
282
283                 // put some space between the map tiles, debugging only
284                 // c.insets = new Insets(5, 5, 5, 5);
285                 //
286                 AltosSiteMapTile t = new AltosSiteMapTile(px_size);
287                 mapTiles.add(t);
288                 c.gridx = offset.x + 100;
289                 c.gridy = offset.y + 100;
290                 layout.setConstraints(t, c);
291                 comp.add(t);
292
293                 return t;
294         }
295
296         private AltosSiteMap(boolean knowWhatYouAreDoing) {
297                 if (!knowWhatYouAreDoing) {
298                         throw new RuntimeException("Arggh.");
299                 }
300         }
301
302         JComponent comp;
303         private GridBagLayout layout;
304
305         public AltosSiteMap() {
306                 comp = new JComponent() {
307                         GrabNDrag scroller = new GrabNDrag(this);
308                         {
309                                 addMouseMotionListener(scroller);
310                                 addMouseListener(scroller);
311                                 setAutoscrolls(true);
312                         }
313                 };
314
315                 layout = new GridBagLayout();
316                 comp.setLayout(layout);
317
318                 for (int x = -1; x <= 1; x++) {
319                         for (int y = -1; y <= 1; y++) {
320                                 addTileAt(new Point(x, y));
321                         }
322                 }
323                 setViewportView(comp);
324                 setPreferredSize(new Dimension(500,200));
325         }
326 }