Merge branch 'master' of ssh://git.gag.com/scm/git/fw/altos
[fw/altos] / 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 import java.util.concurrent.*;
35 import org.altusmetrum.AltosLib.*;
36
37 public class AltosSiteMap extends JScrollPane implements AltosFlightDisplay {
38         // preferred vertical step in a tile in naut. miles
39         // will actually choose a step size between x and 2x, where this
40         // is 1.5x
41         static final double tile_size_nmi = 0.75;
42
43         static final int px_size = 512;
44
45         static final int MAX_TILE_DELTA = 100;
46
47         private static Point2D.Double translatePoint(Point2D.Double p,
48                         Point2D.Double d)
49         {
50                 return new Point2D.Double(p.x + d.x, p.y + d.y);
51         }
52
53         static class LatLng {
54                 public double lat, lng;
55                 public LatLng(double lat, double lng) {
56                         this.lat = lat;
57                         this.lng = lng;
58                 }
59         }
60
61         // based on google js
62         //  http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
63         // search for fromLatLngToPoint and fromPointToLatLng
64         private static Point2D.Double pt(LatLng latlng, int zoom) {
65                 double scale_x = 256/360.0 * Math.pow(2, zoom);
66                 double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
67                 return pt(latlng, scale_x, scale_y);
68         }
69
70         private static Point2D.Double pt(LatLng latlng,
71                                          double scale_x, double scale_y)
72         {
73                 Point2D.Double res = new Point2D.Double();
74                 double e;
75
76                 res.x = latlng.lng * scale_x;
77
78                 e = Math.sin(Math.toRadians(latlng.lat));
79                 e = Math.max(e,-(1-1.0E-15));
80                 e = Math.min(e,  1-1.0E-15 );
81
82                 res.y = 0.5*Math.log((1+e)/(1-e))*-scale_y;
83                 return res;
84         }
85
86         static private LatLng latlng(Point2D.Double pt,
87                                      double scale_x, double scale_y)
88         {
89                 double lat, lng;
90                 double rads;
91
92                 lng = pt.x/scale_x;
93                 rads = 2 * Math.atan(Math.exp(-pt.y/scale_y));
94                 lat = Math.toDegrees(rads - Math.PI/2);
95
96                 return new LatLng(lat,lng);
97         }
98
99         int zoom;
100         double scale_x, scale_y;
101
102         int radius;     /* half width/height of tiles to load */
103
104         private Point2D.Double pt(double lat, double lng) {
105                 return pt(new LatLng(lat, lng), scale_x, scale_y);
106         }
107
108         private LatLng latlng(double x, double y) {
109                 return latlng(new Point2D.Double(x,y), scale_x, scale_y);
110         }
111         private LatLng latlng(Point2D.Double pt) {
112                 return latlng(pt, scale_x, scale_y);
113         }
114
115         ConcurrentHashMap<Point,AltosSiteMapTile> mapTiles = new ConcurrentHashMap<Point,AltosSiteMapTile>();
116         Point2D.Double centre;
117
118         private Point2D.Double tileCoordOffset(Point p) {
119                 return new Point2D.Double(centre.x - p.x*px_size,
120                                           centre.y - p.y * px_size);
121         }
122
123         private Point tileOffset(Point2D.Double p) {
124                 return new Point((int)Math.floor((centre.x+p.x)/px_size),
125                                  (int)Math.floor((centre.y+p.y)/px_size));
126         }
127
128         private Point2D.Double getBaseLocation(double lat, double lng) {
129                 Point2D.Double locn, north_step;
130
131                 zoom = 2;
132                 // stupid loop structure to please Java's control flow analysis
133                 do {
134                         zoom++;
135                         scale_x = 256/360.0 * Math.pow(2, zoom);
136                         scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
137                         locn = pt(lat, lng);
138                         north_step = pt(lat+tile_size_nmi*4/3/60.0, lng);
139                         if (locn.y - north_step.y > px_size)
140                                 break;
141                 } while (zoom < 22);
142                 locn.x = -px_size * Math.floor(locn.x/px_size);
143                 locn.y = -px_size * Math.floor(locn.y/px_size);
144                 return locn;
145         }
146
147         public void reset() {
148                 // nothing
149         }
150
151         public void set_font() {
152                 // nothing
153         }
154
155         private void loadMap(final AltosSiteMapTile tile,
156                              File pngfile, String pngurl)
157         {
158                 final ImageIcon res = AltosSiteMapCache.fetchAndLoadMap(pngfile, pngurl);
159                 if (res != null) {
160                         SwingUtilities.invokeLater(new Runnable() {
161                                         public void run() {
162                                                 tile.loadMap(res);
163                                         }
164                                 });
165                 } else {
166                         System.out.printf("# Failed to fetch file %s\n", pngfile);
167                         System.out.printf(" wget -O '%s' '%s'\n", pngfile, pngurl);
168                 }
169         }
170
171         File pngfile;
172         String pngurl;
173
174         public int prefetchMap(int x, int y) {
175                 LatLng map_latlng = latlng(
176                         -centre.x + x*px_size + px_size/2,
177                         -centre.y + y*px_size + px_size/2);
178                 pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom);
179                 pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom);
180                 if (pngfile.exists()) {
181                         return 1;
182                 } else if (AltosSiteMapCache.fetchMap(pngfile, pngurl)) {
183                         return 0;
184                 } else {
185                         return -1;
186                 }
187         }
188
189         public static void prefetchMaps(double lat, double lng, int w, int h) {
190                 AltosSiteMap asm = new AltosSiteMap(true);
191                 asm.centre = asm.getBaseLocation(lat, lng);
192
193                 Point2D.Double p = new Point2D.Double();
194                 Point2D.Double p2;
195                 int dx = -w/2, dy = -h/2;
196                 for (int y = dy; y < h+dy; y++) {
197                         for (int x = dx; x < w+dx; x++) {
198                                 int r = asm.prefetchMap(x, y);
199                                 switch (r) {
200                                 case 1:
201                                         System.out.printf("Already have %s\n", asm.pngfile);
202                                         break;
203                                 case 0:
204                                         System.out.printf("Fetched map %s\n", asm.pngfile);
205                                         break;
206                                 case -1:
207                                         System.out.printf("# Failed to fetch file %s\n", asm.pngfile);
208                                         System.out.printf(" wget -O '%s' ''\n", asm.pngfile, asm.pngurl);
209                                         break;
210                                 }
211                         }
212                 }
213         }
214
215         public String initMap(Point offset) {
216                 AltosSiteMapTile tile = mapTiles.get(offset);
217                 Point2D.Double coord = tileCoordOffset(offset);
218
219                 LatLng map_latlng = latlng(px_size/2-coord.x, px_size/2-coord.y);
220
221                 File pngfile = MapFile(map_latlng.lat, map_latlng.lng, zoom);
222                 String pngurl = MapURL(map_latlng.lat, map_latlng.lng, zoom);
223                 loadMap(tile, pngfile, pngurl);
224                 return pngfile.toString();
225         }
226
227         public void setBaseLocation(double lat, double lng) {
228                 for (Point k : mapTiles.keySet()) {
229                         AltosSiteMapTile tile = mapTiles.get(k);
230                         tile.clearMap();
231                 }
232                         
233                 centre = getBaseLocation(lat, lng);
234                 scrollRocketToVisible(pt(lat,lng));
235         }
236
237         private void initMaps(double lat, double lng) {
238                 setBaseLocation(lat, lng);
239
240                 Thread thread = new Thread() {
241                                 public void run() {
242                                         for (Point k : mapTiles.keySet())
243                                                 initMap(k);
244                                 }
245                         };
246                 thread.start();
247         }
248
249         private static File MapFile(double lat, double lng, int zoom) {
250                 char chlat = lat < 0 ? 'S' : 'N';
251                 char chlng = lng < 0 ? 'W' : 'E';
252                 if (lat < 0) lat = -lat;
253                 if (lng < 0) lng = -lng;
254                 return new File(AltosUIPreferences.mapdir(),
255                                 String.format("map-%c%.6f,%c%.6f-%d.png",
256                                               chlat, lat, chlng, lng, zoom));
257         }
258
259         private static String MapURL(double lat, double lng, int zoom) {
260                 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);
261         }
262
263         boolean initialised = false;
264         Point2D.Double last_pt = null;
265         int last_state = -1;
266
267         public void show(double lat, double lon) {
268                 initMaps(lat, lon);
269                 scrollRocketToVisible(pt(lat, lon));
270         }
271         public void show(final AltosState state, final int crc_errors) {
272                 // if insufficient gps data, nothing to update
273                 if (!state.gps.locked && state.gps.nsat < 4)
274                         return;
275
276                 if (!initialised) {
277                         if (state.pad_lat != 0 || state.pad_lon != 0) {
278                                 initMaps(state.pad_lat, state.pad_lon);
279                                 initialised = true;
280                         } else if (state.gps.lat != 0 || state.gps.lon != 0) {
281                                 initMaps(state.gps.lat, state.gps.lon);
282                                 initialised = true;
283                         } else {
284                                 return;
285                         }
286                 }
287
288                 final Point2D.Double pt = pt(state.gps.lat, state.gps.lon);
289                 if (last_pt == pt && last_state == state.state)
290                         return;
291
292                 if (last_pt == null) {
293                         last_pt = pt;
294                 }
295                 boolean in_any = false;
296                 for (Point offset : mapTiles.keySet()) {
297                         AltosSiteMapTile tile = mapTiles.get(offset);
298                         Point2D.Double ref, lref;
299                         ref = translatePoint(pt, tileCoordOffset(offset));
300                         lref = translatePoint(last_pt, tileCoordOffset(offset));
301                         tile.show(state, crc_errors, lref, ref);
302                         if (0 <= ref.x && ref.x < px_size)
303                                 if (0 <= ref.y && ref.y < px_size)
304                                         in_any = true;
305                 }
306
307                 Point offset = tileOffset(pt);
308                 if (!in_any) {
309                         Point2D.Double ref, lref;
310                         ref = translatePoint(pt, tileCoordOffset(offset));
311                         lref = translatePoint(last_pt, tileCoordOffset(offset));
312
313                         AltosSiteMapTile tile = createTile(offset);
314                         tile.show(state, crc_errors, lref, ref);
315                         initMap(offset);
316                         finishTileLater(tile, offset);
317                 }
318
319                 scrollRocketToVisible(pt);
320
321                 if (offset != tileOffset(last_pt)) {
322                         ensureTilesAround(offset);
323                 }
324
325                 last_pt = pt;
326                 last_state = state.state;
327         }
328
329         public void draw_circle(double lat, double lon) {
330                 final Point2D.Double pt = pt(lat, lon);
331
332                 for (Point offset : mapTiles.keySet()) {
333                         AltosSiteMapTile tile = mapTiles.get(offset);
334                         Point2D.Double ref = translatePoint(pt, tileCoordOffset(offset));
335                         tile.draw_circle(ref);
336                 }
337         }
338
339         private AltosSiteMapTile createTile(Point offset) {
340                 AltosSiteMapTile tile = new AltosSiteMapTile(px_size);
341                 mapTiles.put(offset, tile);
342                 return tile;
343         }
344         private void finishTileLater(final AltosSiteMapTile tile,
345                                      final Point offset)
346         {
347                 SwingUtilities.invokeLater( new Runnable() {
348                         public void run() {
349                                 addTileAt(tile, offset);
350                         }
351                 } );
352         }
353
354         private void ensureTilesAround(Point base_offset) {
355                 for (int x = -radius; x <= radius; x++) {
356                         for (int y = -radius; y <= radius; y++) {
357                                 Point offset = new Point(base_offset.x + x, base_offset.y + y);
358                                 if (mapTiles.containsKey(offset))
359                                         continue;
360                                 AltosSiteMapTile tile = createTile(offset);
361                                 initMap(offset);
362                                 finishTileLater(tile, offset);
363                         }
364                 }
365         }
366
367         private Point topleft = new Point(0,0);
368         private void scrollRocketToVisible(Point2D.Double pt) {
369                 Rectangle r = comp.getVisibleRect();
370                 Point2D.Double copt = translatePoint(pt, tileCoordOffset(topleft));
371                 int dx = (int)copt.x - r.width/2 - r.x;
372                 int dy = (int)copt.y - r.height/2 - r.y;
373                 if (Math.abs(dx) > r.width/4 || Math.abs(dy) > r.height/4) {
374                         r.x += dx;
375                         r.y += dy;
376                         comp.scrollRectToVisible(r);
377                 }
378         }
379
380         private void addTileAt(AltosSiteMapTile tile, Point offset) {
381                 if (Math.abs(offset.x) >= MAX_TILE_DELTA ||
382                                 Math.abs(offset.y) >= MAX_TILE_DELTA)
383                 {
384                         System.out.printf("Rocket too far away from pad (tile %d,%d)\n",
385                                           offset.x, offset.y);
386                         return;
387                 }
388
389                 boolean review = false;
390                 Rectangle r = comp.getVisibleRect();
391                 if (offset.x < topleft.x) {
392                         r.x += (topleft.x - offset.x) * px_size;
393                         topleft.x = offset.x;
394                         review = true;
395                 }
396                 if (offset.y < topleft.y) {
397                         r.y += (topleft.y - offset.y) * px_size;
398                         topleft.y = offset.y;
399                         review = true;
400                 }
401                 GridBagConstraints c = new GridBagConstraints();
402                 c.anchor = GridBagConstraints.CENTER;
403                 c.fill = GridBagConstraints.BOTH;
404                 // put some space between the map tiles, debugging only
405                 // c.insets = new Insets(5, 5, 5, 5);
406
407                 c.gridx = offset.x + MAX_TILE_DELTA;
408                 c.gridy = offset.y + MAX_TILE_DELTA;
409                 layout.setConstraints(tile, c);
410
411                 comp.add(tile);
412                 if (review) {
413                         comp.scrollRectToVisible(r);
414                 }
415         }
416
417         private AltosSiteMap(boolean knowWhatYouAreDoing) {
418                 if (!knowWhatYouAreDoing) {
419                         throw new RuntimeException("Arggh.");
420                 }
421         }
422
423         JComponent comp = new JComponent() { };
424         private GridBagLayout layout = new GridBagLayout();
425
426         public AltosSiteMap(int in_radius) {
427                 radius = in_radius;
428
429                 GrabNDrag scroller = new GrabNDrag(comp);
430
431                 comp.setLayout(layout);
432
433                 for (int x = -radius; x <= radius; x++) {
434                         for (int y = -radius; y <= radius; y++) {
435                                 Point offset = new Point(x, y);
436                                 AltosSiteMapTile t = createTile(offset);
437                                 addTileAt(t, offset);
438                         }
439                 }
440                 setViewportView(comp);
441                 setPreferredSize(new Dimension(500,500));
442         }
443
444         public AltosSiteMap() {
445                 this(1);
446         }
447 }