]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/function/srtm/LookupSrtmFunction.java
Version 13, August 2011
[GpsPrune.git] / tim / prune / function / srtm / LookupSrtmFunction.java
1 package tim.prune.function.srtm;
2
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.Dimension;
6 import java.awt.FlowLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
9 import java.io.IOException;
10 import java.net.URL;
11 import java.util.ArrayList;
12 import java.util.zip.ZipEntry;
13 import java.util.zip.ZipInputStream;
14
15 import javax.swing.JButton;
16 import javax.swing.JDialog;
17 import javax.swing.JLabel;
18 import javax.swing.JOptionPane;
19 import javax.swing.JPanel;
20 import javax.swing.JProgressBar;
21
22 import tim.prune.App;
23 import tim.prune.DataSubscriber;
24 import tim.prune.GenericFunction;
25 import tim.prune.I18nManager;
26 import tim.prune.UpdateMessageBroker;
27 import tim.prune.data.DataPoint;
28 import tim.prune.data.Field;
29 import tim.prune.data.Track;
30 import tim.prune.undo.UndoLookupSrtm;
31
32 /**
33  * Class to provide a lookup function for point altitudes
34  * using the Space Shuttle's SRTM data files.
35  * HGT files are downloaded into memory via HTTP and point altitudes
36  * can then be interpolated from the 3m grid data.
37  */
38 public class LookupSrtmFunction extends GenericFunction implements Runnable
39 {
40         /** function dialog */
41         private JDialog _dialog = null;
42         /** Progress bar for function */
43         private JProgressBar _progressBar = null;
44         /** Cancel flag */
45         private boolean _cancelled = false;
46
47         /** Expected size of hgt file in bytes */
48         private static final long HGT_SIZE = 2884802L;
49         /** Altitude below which is considered void */
50         private static final int VOID_VAL = -32768;
51
52
53         /**
54          * Constructor
55          * @param inApp App object
56          */
57         public LookupSrtmFunction(App inApp)
58         {
59                 super(inApp);
60         }
61
62         /** @return name key */
63         public String getNameKey() {
64                 return "function.lookupsrtm";
65         }
66
67         /**
68          * Begin the lookup
69          */
70         public void begin()
71         {
72                 if (_dialog == null)
73                 {
74                         _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), false);
75                         _dialog.setLocationRelativeTo(_parentFrame);
76                         _dialog.getContentPane().add(makeDialogComponents());
77                         _dialog.pack();
78                 }
79                 _progressBar.setMinimum(0);
80                 _progressBar.setMaximum(100);
81                 _progressBar.setValue(20);
82                 _cancelled = false;
83                 // start new thread for time-consuming part
84                 new Thread(this).start();
85         }
86
87
88         /**
89          * Make the dialog components
90          * @return the GUI components for the dialog
91          */
92         private Component makeDialogComponents()
93         {
94                 JPanel dialogPanel = new JPanel();
95                 dialogPanel.setLayout(new BorderLayout());
96                 dialogPanel.add(new JLabel(I18nManager.getText("confirm.running")), BorderLayout.NORTH);
97                 _progressBar = new JProgressBar();
98                 _progressBar.setPreferredSize(new Dimension(250, 30));
99                 dialogPanel.add(_progressBar, BorderLayout.CENTER);
100                 // Cancel button at the bottom
101                 JPanel buttonPanel = new JPanel();
102                 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
103                 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
104                 cancelButton.addActionListener(new ActionListener() {
105                         public void actionPerformed(ActionEvent e) {
106                                 _cancelled = true;
107                                 _dialog.dispose();
108                         }
109                 });
110                 buttonPanel.add(cancelButton);
111                 dialogPanel.add(buttonPanel, BorderLayout.SOUTH);
112                 return dialogPanel;
113         }
114
115         /**
116          * Run method using separate thread
117          */
118         public void run()
119         {
120                 // Compile list of tiles to get
121                 Track track = _app.getTrackInfo().getTrack();
122                 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
123                 boolean hasZeroAltitudePoints = false;
124                 boolean hasNonZeroAltitudePoints = false;
125                 // First, loop to see what kind of points we have
126                 for (int i=0; i<track.getNumPoints(); i++)
127                 {
128                         if (track.getPoint(i).hasAltitude())
129                         {
130                                 if (track.getPoint(i).getAltitude().getValue() == 0) {
131                                         hasZeroAltitudePoints = true;
132                                 }
133                                 else {
134                                         hasNonZeroAltitudePoints = true;
135                                 }
136                         }
137                 }
138                 // Should we overwrite the zero altitude values?
139                 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
140                 // If non-zero values present as well, ask user whether to overwrite the zeros or not
141                 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
142                         I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
143                         JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
144                 {
145                         overwriteZeros = true;
146                 }
147
148                 _dialog.setVisible(true);
149                 // Now loop again to extract the required tiles
150                 for (int i=0; i<track.getNumPoints(); i++)
151                 {
152                         // Consider points which don't have altitudes or have zero values
153                         if (!track.getPoint(i).hasAltitude() || (overwriteZeros && track.getPoint(i).getAltitude().getValue() == 0))
154                         {
155                                 SrtmTile tile = new SrtmTile(track.getPoint(i));
156                                 boolean alreadyGot = false;
157                                 for (int t=0; t<tileList.size(); t++) {
158                                         if (tileList.get(t).equals(tile)) {
159                                                 alreadyGot = true;
160                                         }
161                                 }
162                                 if (!alreadyGot) {tileList.add(tile);}
163                         }
164                 }
165                 lookupValues(tileList, overwriteZeros);
166         }
167
168         /**
169          * Lookup the values from SRTM data
170          * @param inTileList list of tiles to get
171          * @param inOverwriteZeros true to overwrite zero altitude values
172          */
173         private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
174         {
175                 Track track = _app.getTrackInfo().getTrack();
176                 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
177                 int numAltitudesFound = 0;
178                 // Update progress bar
179                 _progressBar.setMaximum(inTileList.size());
180                 _progressBar.setIndeterminate(inTileList.size() <= 1);
181                 _progressBar.setValue(0);
182                 String errorMessage = null;
183                 // Get urls for each tile
184                 URL[] urls = TileFinder.getUrls(inTileList);
185                 for (int t=0; t<inTileList.size() && !_cancelled; t++)
186                 {
187                         if (urls[t] != null)
188                         {
189                                 SrtmTile tile = inTileList.get(t);
190                                 try
191                                 {
192                                         _progressBar.setValue(t);
193                                         final int ARRLENGTH = 1201*1201;
194                                         int[] heights = new int[ARRLENGTH];
195                                         // Open zipinputstream on url and check size
196                                         ZipInputStream inStream = new ZipInputStream(urls[t].openStream());
197                                         ZipEntry entry = inStream.getNextEntry();
198                                         boolean entryOk = (entry.getSize() == HGT_SIZE);
199                                         if (entryOk)
200                                         {
201                                                 // Read entire file contents into one byte array
202                                                 for (int i=0; i<ARRLENGTH; i++) {
203                                                         heights[i] = inStream.read()*256 + inStream.read();
204                                                         if (heights[i] >= 32768) {heights[i] -= 65536;}
205                                                 }
206                                         }
207                                         //else {
208                                         //      System.out.println("length not ok: " + entry.getSize());
209                                         //}
210                                         // Close stream from url
211                                         inStream.close();
212
213                                         if (entryOk)
214                                         {
215                                                 // Loop over all points in track, try to apply altitude from array
216                                                 for (int p=0; p<track.getNumPoints(); p++)
217                                                 {
218                                                         DataPoint point = track.getPoint(p);
219                                                         if (!point.hasAltitude() || (inOverwriteZeros && point.getAltitude().getValue() == 0)) {
220                                                                 if (new SrtmTile(point).equals(tile))
221                                                                 {
222                                                                         double x = (point.getLongitude().getDouble() - tile.getLongitude()) * 1200;
223                                                                         double y = 1201 - (point.getLatitude().getDouble() - tile.getLatitude()) * 1200;
224                                                                         int idx1 = ((int)y)*1201 + (int)x;
225                                                                         try {
226                                                                                 int[] fouralts = {heights[idx1], heights[idx1+1], heights[idx1-1201], heights[idx1-1200]};
227                                                                                 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
228                                                                                         + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
229                                                                                 // if (numVoids > 0) System.out.println(numVoids + " voids found");
230                                                                                 double altitude = 0.0;
231                                                                                 switch (numVoids) {
232                                                                                         case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
233                                                                                         case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
234                                                                                         case 2:
235                                                                                         case 3: altitude = averageNonVoid(fouralts); break;
236                                                                                         default: altitude = VOID_VAL;
237                                                                                 }
238                                                                                 if (altitude != VOID_VAL) {
239                                                                                         point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
240                                                                                         numAltitudesFound++;
241                                                                                 }
242                                                                         }
243                                                                         catch (ArrayIndexOutOfBoundsException obe) {
244                                                                                 //System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
245                                                                         }
246                                                                 }
247                                                         }
248                                                 }
249                                         }
250                                 }
251                                 catch (IOException ioe) {
252                                         errorMessage = ioe.getClass().getName() + " - " + ioe.getMessage();
253                                 }
254                         }
255                 }
256                 _dialog.dispose();
257                 if (_cancelled) {return;}
258                 if (numAltitudesFound > 0)
259                 {
260                         // Inform app including undo information
261                         track.requestRescale();
262                         UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
263                         _app.completeFunction(undo, I18nManager.getText("confirm.lookupsrtm1") + " " + numAltitudesFound
264                                 + " " + I18nManager.getText("confirm.lookupsrtm2"));
265                 }
266                 else if (errorMessage != null) {
267                         _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
268                 }
269                 else if (inTileList.size() > 0) {
270                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
271                 }
272                 else {
273                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
274                 }
275         }
276
277         /**
278          * Perform a bilinear interpolation on the given altitude array
279          * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
280          * @param inX x coordinate
281          * @param inY y coordinate
282          * @return interpolated altitude
283          */
284         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
285         {
286                 double alpha = inX - (int) inX;
287                 double beta  = 1 - (inY - (int) inY);
288                 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
289                         + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
290                 return alt;
291         }
292
293         /**
294          * Fix a single void in the given array by replacing it with the average of the others
295          * @param inAltitudes array of altitudes containing one void
296          * @return fixed array without voids
297          */
298         private static int[] fixVoid(int[] inAltitudes)
299         {
300                 int[] fixed = new int[inAltitudes.length];
301                 for (int i=0; i<inAltitudes.length; i++) {
302                         if (inAltitudes[i] == VOID_VAL) {
303                                 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
304                         }
305                         else {
306                                 fixed[i] = inAltitudes[i];
307                         }
308                 }
309                 return fixed;
310         }
311
312         /**
313          * Calculate the average of the non-void altitudes in the given array
314          * @param inAltitudes array of altitudes with one or more voids
315          * @return average of non-void altitudes
316          */
317         private static final double averageNonVoid(int[] inAltitudes)
318         {
319                 double totalAltitude = 0.0;
320                 int numAlts = 0;
321                 for (int i=0; i<inAltitudes.length; i++) {
322                         if (inAltitudes[i] != VOID_VAL) {
323                                 totalAltitude += inAltitudes[i];
324                                 numAlts++;
325                         }
326                 }
327                 if (numAlts < 1) {return VOID_VAL;}
328                 return totalAltitude / numAlts;
329         }
330 }