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