a241cbd073e6e481a5c7aa897d8bb12a9987f88a
[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     // max vertical step in a tile in naut. miles
37     static final double tile_size_nmi = 1.0; 
38
39     static final int px_size = 512;
40
41     private static Point2D.Double translatePoint(Point2D.Double p, 
42             Point2D.Double d) 
43     {
44         return new Point2D.Double(p.x + d.x, p.y + d.y);
45     }
46
47     static class LatLng {
48         public double lat, lng;
49         public LatLng(double lat, double lng) {
50             this.lat = lat;
51             this.lng = lng;
52         }
53     }
54
55     // based on google js
56     //  http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/10/main.js
57     // search for fromLatLngToPoint and fromPointToLatLng
58     private static Point2D.Double pt(LatLng latlng, int zoom) {
59         double scale_x = 256/360.0 * Math.pow(2, zoom);
60         double scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
61         return pt(latlng, scale_x, scale_y);
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     private Point2D.Double pt(double lat, double lng) {
97         return pt(new LatLng(lat, lng), scale_x, scale_y);
98     }
99
100     private LatLng latlng(double x, double y) {
101         return latlng(new Point2D.Double(x,y), scale_x, scale_y);
102     }
103     private LatLng latlng(Point2D.Double pt) {
104         return latlng(pt, scale_x, scale_y);
105     }
106
107     AltosSiteMapTile [] mapTiles = new AltosSiteMapTile[9];
108     Point2D.Double [] tileOffset = new Point2D.Double[9];
109
110     private Point2D.Double getBaseLocation(double lat, double lng) {
111         Point2D.Double locn, north_step;
112
113         zoom = 2;
114         // stupid loop structure to please Java's control flow analysis
115         do {
116             zoom++;
117             scale_x = 256/360.0 * Math.pow(2, zoom);
118             scale_y = 256/(2.0*Math.PI) * Math.pow(2, zoom);
119             locn = pt(lat, lng);
120             north_step = pt(lat+tile_size_nmi/60.0, lng);
121             if (locn.y - north_step.y > px_size)
122                 break;
123         } while (zoom < 22);
124         locn.x = -px_size * Math.floor(locn.x/px_size);
125         locn.y = -px_size * Math.floor(locn.y/px_size);
126         return locn;
127     }
128
129     public void reset() {
130         // nothing
131     }
132
133     private void bgLoadMap(final int i, 
134             final File pngfile, final String pngurl) 
135     {
136         Thread thread = new Thread() {
137             public void run() {
138                 ImageIcon res;
139                 res = AltosSiteMapCache.fetchAndLoadMap(pngfile, pngurl);
140                 if (res != null) {
141                     mapTiles[i].loadMap(res);
142                 } else {
143                     System.out.printf("# Failed to fetch file %s\n", pngfile);
144                     System.out.printf(" wget -O '%s' ''\n", pngfile, pngurl);
145                 }
146             }
147         };
148         thread.start();
149     }
150  
151     public static void prefetchMaps(double lat, double lng, int w, int h) {
152         AltosPreferences.init(null);
153
154         AltosSiteMap asm = new AltosSiteMap(true);
155         Point2D.Double c = asm.getBaseLocation(lat, lng);
156         Point2D.Double p = new Point2D.Double();
157         Point2D.Double p2;
158         int dx = -w/2, dy = -h/2;
159         for (int y = dy; y < h+dy; y++) {
160             for (int x = dx; x < w+dx; x++) {
161                 LatLng map_latlng = asm.latlng(
162                         -c.x + x*px_size + px_size/2, 
163                         -c.y + y*px_size + px_size/2);
164                 File pngfile = asm.MapFile(map_latlng.lat, map_latlng.lng);
165                 String pngurl = asm.MapURL(map_latlng.lat, map_latlng.lng);
166                 if (pngfile.exists()) {
167                     System.out.printf("Already have %s\n", pngfile);
168                 } else if (AltosSiteMapCache.fetchMap(pngfile, pngurl)) {
169                     System.out.printf("Fetched map %s\n", pngfile);
170                 } else {
171                     System.out.printf("# Failed to fetch file %s\n", pngfile);
172                     System.out.printf(" wget -O '%s' ''\n", pngfile, pngurl);
173                 }
174             }
175         }
176     }
177
178     private void initMaps(double lat, double lng) {
179         Point2D.Double c = getBaseLocation(lat, lng);
180         Point2D.Double p = new Point2D.Double();
181
182         for (int i = 0; i < 9; i++) {
183             int x = i%3 - 1, y = i/3 - 1;
184
185             tileOffset[i] = new Point2D.Double(
186                     c.x - x*px_size, p.y = c.y - y*px_size);
187             LatLng map_latlng = latlng(
188                     -tileOffset[i].x+px_size/2, 
189                     -tileOffset[i].y+px_size/2);
190
191             File pngfile = MapFile(map_latlng.lat, map_latlng.lng);
192             String pngurl = MapURL(map_latlng.lat, map_latlng.lng);
193             bgLoadMap(i, pngfile, pngurl);
194         }
195     } 
196     
197     private File MapFile(double lat, double lng) {
198         char chlat = lat < 0 ? 'S' : 'N';
199         char chlng = lng < 0 ? 'E' : 'W';
200         if (lat < 0) lat = -lat;
201         if (lng < 0) lng = -lng;
202         return new File(AltosPreferences.logdir(), 
203                 String.format("map-%c%.6f,%c%.6f-%d.png",
204                     chlat, lat, chlng, lng, zoom));
205     }
206
207     private String MapURL(double lat, double lng) {
208         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);
209     }
210
211     boolean initialised = false;
212     public void show(AltosState state, int crc_errors) {
213         // if insufficient gps data, nothing to update
214         if (!state.gps_ready) {
215             if (state.pad_lat == 0 && state.pad_lon == 0)
216                 return;
217             if (state.ngps < 3)
218                 return;
219         }
220
221         if (!initialised) {
222             initMaps(state.pad_lat, state.pad_lon);
223             initialised = true;
224         }
225
226         Point2D.Double pt = pt(state.gps.lat, state.gps.lon);
227         for (int x = 0; x < mapTiles.length; x++) {
228             mapTiles[x].show(state, crc_errors, 
229                     translatePoint(pt, tileOffset[x]));
230         }
231     }
232
233     private AltosSiteMap(boolean knowWhatYouAreDoing) {
234         if (!knowWhatYouAreDoing) {
235             throw new RuntimeException("Arggh.");
236         }
237     }
238
239     public AltosSiteMap() {
240         JComponent comp = new JComponent() {
241             GrabNDrag scroller = new GrabNDrag(this);
242             {
243                 addMouseMotionListener(scroller);
244                 addMouseListener(scroller);
245                 setAutoscrolls(true);
246             }
247         };
248
249         GridBagLayout layout = new GridBagLayout();
250         comp.setLayout(layout);
251
252         GridBagConstraints c = new GridBagConstraints();
253         c.anchor = GridBagConstraints.CENTER;
254         c.fill = GridBagConstraints.BOTH;
255
256         // put some space between the map tiles, debugging only
257         // c.insets = new Insets(5, 5, 5, 5);
258         for (int x = 0; x < 9; x++) {
259             c.gridx = x % 3; c.gridy = x / 3;
260             mapTiles[x] = new AltosSiteMapTile(px_size);
261             layout.setConstraints(mapTiles[x], c);
262             comp.add(mapTiles[x]);
263         }
264         setViewportView(comp);
265         setPreferredSize(new Dimension(500,200));
266     }
267 }
268