]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/function/srtm/LookupSrtmFunction.java
Always set point altitudes in LookipSRTM
[GpsPrune.git] / src / tim / prune / function / srtm / LookupSrtmFunction.java
1 package tim.prune.function.srtm;
2
3 import java.util.ArrayList;
4
5 import javax.swing.JOptionPane;
6
7 import tim.prune.App;
8 import tim.prune.DataSubscriber;
9 import tim.prune.GenericFunction;
10 import tim.prune.I18nManager;
11 import tim.prune.UpdateMessageBroker;
12 import tim.prune.data.Altitude;
13 import tim.prune.data.DataPoint;
14 import tim.prune.data.Field;
15 import tim.prune.data.Track;
16 import tim.prune.data.UnitSetLibrary;
17 import tim.prune.gui.ProgressDialog;
18 import tim.prune.undo.UndoLookupSrtm;
19
20 /**
21  * Class to provide a lookup function for point altitudes using the Space
22  * Shuttle's SRTM data files. HGT files are downloaded into memory via HTTP and
23  * point altitudes can then be interpolated from the 3m grid data.
24  */
25 public class LookupSrtmFunction extends GenericFunction implements Runnable
26 {
27         /** Progress dialog */
28         private ProgressDialog _progress = null;
29         /** Track to process */
30         private Track _track = null;
31         /** Flag for whether this is a real track or a terrain one */
32         private boolean _normalTrack = true;
33         /** Flag to check whether this function is currently running or not */
34         private boolean _running = false;
35
36         /** Altitude below which is considered void */
37         private static final int VOID_VAL = -32768;
38
39         /**
40          * Constructor
41          * @param inApp  App object
42          */
43         public LookupSrtmFunction(App inApp) {
44                 super(inApp);
45         }
46
47         /** @return name key */
48         public String getNameKey() {
49                 return "function.lookupsrtm";
50         }
51
52         /**
53          * Begin the lookup using the normal track
54          */
55         public void begin() {
56                 begin(_app.getTrackInfo().getTrack(), true);
57         }
58
59         /**
60          * Begin the lookup with an alternative track
61          * @param inAlternativeTrack
62          */
63         public void begin(Track inAlternativeTrack) {
64                 begin(inAlternativeTrack, false);
65         }
66
67         /**
68          * Begin the function with the given parameters
69          * @param inTrack track to process
70          * @param inNormalTrack true if this is a "normal" track, false for an artificially constructed one such as for terrain
71          */
72         private void begin(Track inTrack, boolean inNormalTrack)
73         {
74                 _running = true;
75                 if (! SrtmDiskCache.ensureCacheIsUsable())
76                 {
77                         _app.showErrorMessage(getNameKey(), "error.cache.notthere");
78                 }
79                 if (_progress == null) {
80                         _progress = new ProgressDialog(_parentFrame, getNameKey());
81                 }
82                 _progress.show();
83                 _track = inTrack;
84                 _normalTrack = inNormalTrack;
85                 // start new thread for time-consuming part
86                 new Thread(this).start();
87         }
88
89         /**
90          * Run method using separate thread
91          */
92         public void run()
93         {
94                 // Compile list of tiles to get
95                 ArrayList<SrtmTile> tileList = new ArrayList<SrtmTile>();
96
97                 // Now loop again to extract the required tiles
98                 for (int i = 0; i < _track.getNumPoints(); i++)
99                 {
100                         SrtmTile tile = new SrtmTile(_track.getPoint(i));
101                         boolean alreadyGot = false;
102                         for (int t = 0; t < tileList.size(); t++)
103                         {
104                                 if (tileList.get(t).equals(tile)) {
105                                         alreadyGot = true;
106                                 }
107                         }
108                         if (!alreadyGot) {tileList.add(tile);}
109                 }
110                 lookupValues(tileList);
111                 // Finished
112                 _running = false;
113         }
114
115         /**
116          * Lookup the values from SRTM data
117          * @param inTileList list of tiles to get
118          * @param inOverwriteZeros true to overwrite zero altitude values
119          */
120         private void lookupValues(ArrayList<SrtmTile> inTileList)
121         {
122                 UndoLookupSrtm undo = new UndoLookupSrtm(_app.getTrackInfo());
123                 int numAltitudesFound = 0;
124                 // Update progress bar
125                 if (_progress != null)
126                 {
127                         _progress.setMaximum(inTileList.size());
128                         _progress.setValue(0);
129                 }
130                 String errorMessage = "";
131                 for (int t=0; t<inTileList.size() && !_progress.isCancelled(); t++)
132                 {
133                         SrtmTile tile = inTileList.get(t);
134                         SrtmSource srtmSource = tile.findBestCachedSource();
135
136                         if (srtmSource == null)
137                         {
138                                 errorMessage += "Tile "+tile.getTileName()+" not in cache!\n";
139                                 continue;
140                         }
141
142                         // Set progress
143                         _progress.setValue(t);
144
145                         int[] heights;
146                         try {
147                                 heights = srtmSource.getTileHeights(tile);
148                         }
149                         catch (SrtmSourceException e)
150                         {
151                                 errorMessage += e.getMessage();
152                                 e.printStackTrace();
153                                 continue;
154                         }
155                         int rowSize = srtmSource.getRowSize(tile);
156                         if (rowSize <= 0)
157                         {
158                                 errorMessage += "Tile "+tile.getTileName()+" is corrupted";
159                         }
160
161                         numAltitudesFound += applySrtmTimeToWholeTrack(tile, heights, rowSize);
162                 }
163
164                 _progress.dispose();
165                 if (_progress.isCancelled()) {
166                         return;
167                 }
168
169                 if (! errorMessage.equals("")) {
170                         _app.showErrorMessageNoLookup(getNameKey(), errorMessage);
171                         return;
172                 }
173                 if (numAltitudesFound > 0)
174                 {
175                         // Inform app including undo information
176                         _track.requestRescale();
177                         UpdateMessageBroker.informSubscribers(DataSubscriber.DATA_ADDED_OR_REMOVED);
178                         // Don't update app if we're doing another track
179                         if (_normalTrack)
180                         {
181                                 _app.completeFunction(undo,
182                                         I18nManager.getTextWithNumber("confirm.lookupsrtm", numAltitudesFound));
183                         }
184                 }
185                 else if (inTileList.size() > 0) {
186                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonefound");
187                 }
188                 else {
189                         _app.showErrorMessage(getNameKey(), "error.lookupsrtm.nonerequired");
190                 }
191         }
192
193         /**
194          * Given the height data read in from file, apply the given tile to all points
195          * in the track with missing altitude
196          * @param inTile tile being applied
197          * @param inHeights height data read in from file
198          * @return number of altitudes found
199          */
200         private int applySrtmTimeToWholeTrack(SrtmTile inTile, int[] inHeights, int inRowSize)
201         {
202                 int numAltitudesFound = 0;
203                 // Loop over all points in track, try to apply altitude from array
204                 for (int p = 0; p < _track.getNumPoints(); p++)
205                 {
206                         DataPoint point = _track.getPoint(p);
207                         if (new SrtmTile(point).equals(inTile))
208                         {
209                                 double x = (point.getLongitude().getDouble() - inTile.getLongitude()) * (inRowSize - 1);
210                                 double y = inRowSize - (point.getLatitude().getDouble() - inTile.getLatitude()) * (inRowSize - 1);
211                                 int idx1 = ((int)y)*inRowSize + (int)x;
212                                 try
213                                 {
214                                         int[] fouralts = {inHeights[idx1], inHeights[idx1+1], inHeights[idx1-inRowSize], inHeights[idx1-inRowSize+1]};
215                                         int numVoids = (fouralts[0]==VOID_VAL?1:0) + (fouralts[1]==VOID_VAL?1:0)
216                                                 + (fouralts[2]==VOID_VAL?1:0) + (fouralts[3]==VOID_VAL?1:0);
217                                         // if (numVoids > 0) System.out.println(numVoids + " voids found");
218                                         double altitude = 0.0;
219                                         switch (numVoids)
220                                         {
221                                         case 0: altitude = bilinearInterpolate(fouralts, x, y); break;
222                                         case 1: altitude = bilinearInterpolate(fixVoid(fouralts), x, y); break;
223                                         case 2:
224                                         case 3: altitude = averageNonVoid(fouralts); break;
225                                         default: altitude = VOID_VAL;
226                                         }
227                                         // Special case for terrain tracks, don't interpolate voids yet
228                                         if (!_normalTrack && numVoids > 0) {
229                                                 altitude = VOID_VAL;
230                                         }
231                                         if (altitude != VOID_VAL)
232                                         {
233                                                 point.setFieldValue(Field.ALTITUDE, ""+altitude, false);
234                                                 // depending on settings, this value may have been added as feet, we need to force metres
235                                                 point.getAltitude().reset(new Altitude((int)altitude, UnitSetLibrary.UNITS_METRES));
236                                                 numAltitudesFound++;
237                                         }
238                                 }
239                                 catch (ArrayIndexOutOfBoundsException obe) {
240                                         System.err.println("Point not in tile? lat=" + point.getLatitude().getDouble() + ", x=" + x + ", y=" + y + ", idx=" + idx1+"\n");
241                                 }
242                         }
243                 }
244                 return numAltitudesFound;
245         }
246
247         /**
248          * Perform a bilinear interpolation on the given altitude array
249          * @param inAltitudes array of four altitude values on corners of square (bl, br, tl, tr)
250          * @param inX x coordinate
251          * @param inY y coordinate
252          * @return interpolated altitude
253          */
254         private static double bilinearInterpolate(int[] inAltitudes, double inX, double inY)
255         {
256                 double alpha = inX - (int) inX;
257                 double beta  = 1 - (inY - (int) inY);
258                 double alt = (1-alpha)*(1-beta)*inAltitudes[0] + alpha*(1-beta)*inAltitudes[1]
259                         + (1-alpha)*beta*inAltitudes[2] + alpha*beta*inAltitudes[3];
260                 return alt;
261         }
262
263         /**
264          * Fix a single void in the given array by replacing it with the average of the others
265          * @param inAltitudes array of altitudes containing one void
266          * @return fixed array without voids
267          */
268         private static int[] fixVoid(int[] inAltitudes)
269         {
270                 int[] fixed = new int[inAltitudes.length];
271                 for (int i = 0; i < inAltitudes.length; i++)
272                 {
273                         if (inAltitudes[i] == VOID_VAL) {
274                                 fixed[i] = (int) Math.round(averageNonVoid(inAltitudes));
275                         }
276                         else {
277                                 fixed[i] = inAltitudes[i];
278                         }
279                 }
280                 return fixed;
281         }
282
283         /**
284          * Calculate the average of the non-void altitudes in the given array
285          * @param inAltitudes array of altitudes with one or more voids
286          * @return average of non-void altitudes
287          */
288         private static final double averageNonVoid(int[] inAltitudes)
289         {
290                 double totalAltitude = 0.0;
291                 int numAlts = 0;
292                 for (int i = 0; i < inAltitudes.length; i++)
293                 {
294                         if (inAltitudes[i] != VOID_VAL)
295                         {
296                                 totalAltitude += inAltitudes[i];
297                                 numAlts++;
298                         }
299                 }
300                 if (numAlts < 1) {return VOID_VAL;}
301                 return totalAltitude / numAlts;
302         }
303
304         /**
305          * @return true if a thread is currently running
306          */
307         public boolean isRunning()
308         {
309                 return _running;
310         }
311 }