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