]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/function/srtm/LookupSrtmFunction.java
Version 20.4, May 2021
[GpsPrune.git] / src / tim / prune / function / srtm / LookupSrtmFunction.java
1 package tim.prune.function.srtm;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.net.URL;
7 import java.util.ArrayList;
8 import java.util.zip.ZipEntry;
9 import java.util.zip.ZipInputStream;
10
11 import javax.swing.JOptionPane;
12
13 import tim.prune.App;
14 import tim.prune.DataSubscriber;
15 import tim.prune.GenericFunction;
16 import tim.prune.I18nManager;
17 import tim.prune.UpdateMessageBroker;
18 import tim.prune.config.Config;
19 import tim.prune.data.Altitude;
20 import tim.prune.data.DataPoint;
21 import tim.prune.data.Field;
22 import tim.prune.data.Track;
23 import tim.prune.data.UnitSetLibrary;
24 import tim.prune.gui.ProgressDialog;
25 import tim.prune.tips.TipManager;
26 import tim.prune.undo.UndoLookupSrtm;
27
28 /**
29  * Class to provide a lookup function for point altitudes using the Space
30  * Shuttle's SRTM data files. HGT files are downloaded into memory via HTTP and
31  * point altitudes can then be interpolated from the 3m grid data.
32  */
33 public class LookupSrtmFunction extends GenericFunction implements Runnable
34 {
35         /** Progress dialog */
36         private ProgressDialog _progress = null;
37         /** Track to process */
38         private Track _track = null;
39         /** Flag for whether this is a real track or a terrain one */
40         private boolean _normalTrack = true;
41         /** Flag set when any tiles had to be downloaded (rather than just loaded locally) */
42         private boolean _hadToDownload = false;
43         /** Flag to check whether this function is currently running or not */
44         private boolean _running = false;
45
46         /** Expected size of hgt file in bytes */
47         private static final long HGT_SIZE = 2884802L;
48         /** Altitude below which is considered void */
49         private static final int VOID_VAL = -32768;
50
51         /**
52          * Constructor
53          * @param inApp  App object
54          */
55         public LookupSrtmFunction(App inApp) {
56                 super(inApp);
57         }
58
59         /** @return name key */
60         public String getNameKey() {
61                 return "function.lookupsrtm";
62         }
63
64         /**
65          * Begin the lookup using the normal track
66          */
67         public void begin() {
68                 begin(_app.getTrackInfo().getTrack(), true);
69         }
70
71         /**
72          * Begin the lookup with an alternative track
73          * @param inAlternativeTrack
74          */
75         public void begin(Track inAlternativeTrack) {
76                 begin(inAlternativeTrack, false);
77         }
78
79         /**
80          * Begin the function with the given parameters
81          * @param inTrack track to process
82          * @param inNormalTrack true if this is a "normal" track, false for an artificially constructed one such as for terrain
83          */
84         private void begin(Track inTrack, boolean inNormalTrack)
85         {
86                 _running = true;
87                 _hadToDownload = false;
88                 if (_progress == null) {
89                         _progress = new ProgressDialog(_parentFrame, getNameKey());
90                 }
91                 _progress.show();
92                 _track = inTrack;
93                 _normalTrack = inNormalTrack;
94                 // start new thread for time-consuming part
95                 new Thread(this).start();
96         }
97
98         /**
99          * Run method using separate thread
100          */
101         public void run()
102         {
103                 // Compile list of tiles to get
104                 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
105                 boolean hasZeroAltitudePoints = false;
106                 boolean hasNonZeroAltitudePoints = false;
107                 // First, loop to see what kind of points we have
108                 for (int i = 0; i < _track.getNumPoints(); i++)
109                 {
110                         if (_track.getPoint(i).hasAltitude())
111                         {
112                                 if (_track.getPoint(i).getAltitude().getValue() == 0) {
113                                         hasZeroAltitudePoints = true;
114                                 }
115                                 else {
116                                         hasNonZeroAltitudePoints = true;
117                                 }
118                         }
119                 }
120                 // Should we overwrite the zero altitude values?
121                 boolean overwriteZeros = hasZeroAltitudePoints && !hasNonZeroAltitudePoints;
122                 // If non-zero values present as well, ask user whether to overwrite the zeros or not
123                 if (hasNonZeroAltitudePoints && hasZeroAltitudePoints && JOptionPane.showConfirmDialog(_parentFrame,
124                         I18nManager.getText("dialog.lookupsrtm.overwritezeros"), I18nManager.getText(getNameKey()),
125                         JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
126                 {
127                         overwriteZeros = true;
128                 }
129
130                 // Now loop again to extract the required tiles
131                 for (int i = 0; i < _track.getNumPoints(); i++)
132                 {
133                         // Consider points which don't have altitudes or have zero values
134                         if (!_track.getPoint(i).hasAltitude()
135                                 || (overwriteZeros && _track.getPoint(i).getAltitude().getValue() == 0))
136                         {
137                                 SrtmTile tile = new SrtmTile(_track.getPoint(i));
138                                 boolean alreadyGot = false;
139                                 for (int t = 0; t < tileList.size(); t++)
140                                 {
141                                         if (tileList.get(t).equals(tile)) {
142                                                 alreadyGot = true;
143                                         }
144                                 }
145                                 if (!alreadyGot) {tileList.add(tile);}
146                         }
147                 }
148                 lookupValues(tileList, overwriteZeros);
149                 // Finished
150                 _running = false;
151                 // Show tip if lots of online lookups were necessary
152                 if (_hadToDownload) {
153                         _app.showTip(TipManager.Tip_DownloadSrtm);
154                 }
155         }
156
157
158         /**
159          * Lookup the values from SRTM data
160          * @param inTileList list of tiles to get
161          * @param inOverwriteZeros true to overwrite zero altitude values
162          */
163         private void lookupValues(ArrayList<SrtmTile> inTileList, boolean inOverwriteZeros)
164         {
165                 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
166                 int numAltitudesFound = 0;
167                 // Update progress bar
168                 if (_progress != null)
169                 {
170                         _progress.setMaximum(inTileList.size());
171                         _progress.setValue(0);
172                 }
173                 String errorMessage = null;
174                 // Get urls for each tile
175                 URL[] urls = TileFinder.getUrls(inTileList);
176                 for (int t=0; t<inTileList.size() && !_progress.isCancelled() && urls != null; t++)
177                 {
178                         if (urls[t] != null)
179                         {
180                                 SrtmTile tile = inTileList.get(t);
181                                 try
182                                 {
183                                         // Set progress
184                                         _progress.setValue(t);
185                                         final int ARRLENGTH = 1201 * 1201;
186                                         int[] heights = new int[ARRLENGTH];
187                                         // Open zipinputstream on url and check size
188                                         ZipInputStream inStream = getStreamToHgtFile(urls[t]);
189                                         boolean entryOk = false;
190                                         if (inStream != null)
191                                         {
192                                                 ZipEntry entry = inStream.getNextEntry();
193                                                 entryOk = (entry != null && entry.getSize() == HGT_SIZE);
194                                                 if (entryOk)
195                                                 {
196                                                         // Read entire file contents into one byte array
197                                                         for (int i = 0; i < ARRLENGTH; i++)
198                                                         {
199                                                                 heights[i] = inStream.read() * 256 + inStream.read();
200                                                                 if (heights[i] >= 32768) {heights[i] -= 65536;}
201                                                         }
202                                                 }
203                                                 // else {
204                                                 //      System.out.println("length not ok: " + entry.getSize());
205                                                 // }
206                                                 // Close stream from url
207                                                 inStream.close();
208                                         }
209
210                                         if (entryOk)
211                                         {
212                                                 numAltitudesFound += applySrtmTileToWholeTrack(tile, heights, inOverwriteZeros);
213                                         }
214                                 }
215                                 catch (IOException ioe) {
216                                         errorMessage = ioe.getClass().getName() + " - " + ioe.getMessage();
217                                 }
218                         }
219                 }
220
221                 _progress.dispose();
222                 if (_progress.isCancelled()) {
223                         return;
224                 }
225
226                 if (numAltitudesFound > 0)
227                 {
228                         // Inform app including undo information
229                         _track.requestRescale();
230                         UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
231                         // Don't update app if we're doing another track
232                         if (_normalTrack)
233                         {
234                                 _app.completeFunction(undo,
235                                         I18nManager.getTextWithNumber("confirm.lookupsrtm", numAltitudesFound));
236                         }
237                 }
238                 else if (errorMessage != null) {
239                         _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
240                 }
241                 else if (inTileList.size() > 0) {
242                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
243                 }
244                 else {
245                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
246                 }
247         }
248
249         /**
250          * See whether the SRTM file is already available locally first, then try online
251          * @param inUrl URL for online resource
252          * @return ZipInputStream either on the local file or on the downloaded zip file
253          */
254         private ZipInputStream getStreamToHgtFile(URL inUrl)
255         throws IOException
256         {
257                 String diskCachePath = Config.getConfigString(Config.KEY_DISK_CACHE);
258                 if (diskCachePath != null)
259                 {
260                         File srtmDir = new File(diskCachePath, "srtm");
261                         if (srtmDir.exists() && srtmDir.isDirectory() && srtmDir.canRead())
262                         {
263                                 File srtmFile = new File(srtmDir, new File(inUrl.getFile()).getName());
264                                 if (srtmFile.exists() && srtmFile.isFile() && srtmFile.canRead()
265                                         && srtmFile.length() > 400)
266                                 {
267                                         // System.out.println("Lookup: Using file " + srtmFile.getAbsolutePath());
268                                         // File found, use this one
269                                         return new ZipInputStream(new FileInputStream(srtmFile));
270                                 }
271                         }
272                 }
273                 // System.out.println("Lookup: Trying online: " + inUrl.toString());
274                 _hadToDownload = true;
275                 // MAYBE: Only download if we're in online mode?
276                 return new ZipInputStream(inUrl.openStream());
277         }
278
279         /**
280          * Given the height data read in from file, apply the given tile to all points
281          * in the track with missing altitude
282          * @param inTile tile being applied
283          * @param inHeights height data read in from file
284          * @param inOverwriteZeros true to overwrite zero altitude values
285          * @return number of altitudes found
286          */
287         private int applySrtmTileToWholeTrack(SrtmTile inTile, int[] inHeights, boolean inOverwriteZeros)
288         {
289                 int numAltitudesFound = 0;
290                 // Loop over all points in track, try to apply altitude from array
291                 for (int p = 0; p < _track.getNumPoints(); p++)
292                 {
293                         DataPoint point = _track.getPoint(p);
294                         if (!point.hasAltitude()
295                                 || (inOverwriteZeros && point.getAltitude().getValue() == 0))
296                         {
297                                 if (new SrtmTile(point).equals(inTile))
298                                 {
299                                         double x = (point.getLongitude().getDouble() - inTile.getLongitude()) * 1200;
300                                         double y = 1201 - (point.getLatitude().getDouble() - inTile.getLatitude()) * 1200;
301                                         int idx1 = ((int)y)*1201 + (int)x;
302                                         try
303                                         {
304                                                 int[] fouralts = {inHeights[idx1], inHeights[idx1+1], inHeights[idx1-1201], inHeights[idx1-1200]};
305                                                 int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
306                                                         + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
307                                                 // if (numVoids > 0) System.out.println(numVoids + " voids found");
308                                                 double altitude = 0.0;
309                                                 switch (numVoids)
310                                                 {
311                                                         case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
312                                                         case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
313                                                         case 2:
314                                                         case 3: altitude = averageNonVoid(fouralts); break;
315                                                         default: altitude = VOID_VAL;
316                                                 }
317                                                 // Special case for terrain tracks, don't interpolate voids yet
318                                                 if (!_normalTrack && numVoids > 0) {
319                                                         altitude = VOID_VAL;
320                                                 }
321                                                 if (altitude != VOID_VAL)
322                                                 {
323                                                         point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
324                                                         // depending on settings, this value may have been added as feet, we need to force metres
325                                                         point.getAltitude().reset(new Altitude((int)altitude, UnitSetLibrary.UNITS_METRES));
326                                                         numAltitudesFound++;
327                                                 }
328                                         }
329                                         catch (ArrayIndexOutOfBoundsException obe) {
330                                                 // System.err.println("lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1);
331                                         }
332                                 }
333                         }
334                 }
335                 return numAltitudesFound;
336         }
337
338         /**
339          * Perform a bilinear interpolation on the given altitude array
340          * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
341          * @param inX x coordinate
342          * @param inY y coordinate
343          * @return interpolated altitude
344          */
345         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
346         {
347                 double alpha = inX - (int) inX;
348                 double beta  = 1 - (inY - (int) inY);
349                 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
350                         + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
351                 return alt;
352         }
353
354         /**
355          * Fix a single void in the given array by replacing it with the average of the others
356          * @param inAltitudes array of altitudes containing one void
357          * @return fixed array without voids
358          */
359         private static int[] fixVoid(int[] inAltitudes)
360         {
361                 int[] fixed = new int[inAltitudes.length];
362                 for (int i = 0; i < inAltitudes.length; i++)
363                 {
364                         if (inAltitudes[i] == VOID_VAL) {
365                                 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
366                         }
367                         else {
368                                 fixed[i] = inAltitudes[i];
369                         }
370                 }
371                 return fixed;
372         }
373
374         /**
375          * Calculate the average of the non-void altitudes in the given array
376          * @param inAltitudes array of altitudes with one or more voids
377          * @return average of non-void altitudes
378          */
379         private static final double averageNonVoid(int[] inAltitudes)
380         {
381                 double totalAltitude = 0.0;
382                 int numAlts = 0;
383                 for (int i = 0; i < inAltitudes.length; i++)
384                 {
385                         if (inAltitudes[i] != VOID_VAL)
386                         {
387                                 totalAltitude += inAltitudes[i];
388                                 numAlts++;
389                         }
390                 }
391                 if (numAlts < 1) {return VOID_VAL;}
392                 return totalAltitude / numAlts;
393         }
394
395         /**
396          * @return true if a thread is currently running
397          */
398         public boolean isRunning()
399         {
400                 return _running;
401         }
402 }