]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/data/Track.java
Version 14, October 2012
[GpsPrune.git] / tim / prune / data / Track.java
1 package tim.prune.data;
2
3 import java.util.List;
4
5 import tim.prune.UpdateMessageBroker;
6 import tim.prune.function.edit.FieldEdit;
7 import tim.prune.function.edit.FieldEditList;
8 import tim.prune.gui.map.MapUtils;
9
10
11 /**
12  * Class to hold all track information,
13  * including track points and waypoints
14  */
15 public class Track
16 {
17         // Data points
18         private DataPoint[] _dataPoints = null;
19         // Scaled x, y values
20         private double[] _xValues = null;
21         private double[] _yValues = null;
22         private boolean _scaled = false;
23         private int _numPoints = 0;
24         private boolean _hasTrackpoint = false;
25         private boolean _hasWaypoint = false;
26         // Master field list
27         private FieldList _masterFieldList = null;
28         // variable ranges
29         private DoubleRange _latRange = null, _longRange = null;
30         private DoubleRange _xRange = null, _yRange = null;
31
32
33         /**
34          * Constructor for empty track
35          */
36         public Track()
37         {
38                 // create field list
39                 _masterFieldList = new FieldList(null);
40                 // make empty DataPoint array
41                 _dataPoints = new DataPoint[0];
42                 _numPoints = 0;
43                 // needs to be scaled
44                 _scaled = false;
45         }
46
47         /**
48          * Constructor using fields and points from another Track
49          * @param inFieldList Field list from another Track object
50          * @param inPoints (edited) point array
51          */
52         public Track(FieldList inFieldList, DataPoint[] inPoints)
53         {
54                 _masterFieldList = inFieldList;
55                 _dataPoints = inPoints;
56                 if (_dataPoints == null) _dataPoints = new DataPoint[0];
57                 _numPoints = _dataPoints.length;
58                 _scaled = false;
59         }
60
61         /**
62          * Load method, for initialising and reinitialising data
63          * @param inFieldArray array of Field objects describing fields
64          * @param inPointArray 2d object array containing data
65          * @param inAltFormat altitude format
66          */
67         public void load(Field[] inFieldArray, Object[][] inPointArray, Altitude.Format inAltFormat)
68         {
69                 if (inFieldArray == null || inPointArray == null)
70                 {
71                         _numPoints = 0;
72                         return;
73                 }
74                 // copy field list
75                 _masterFieldList = new FieldList(inFieldArray);
76                 // make DataPoint object from each point in inPointList
77                 _dataPoints = new DataPoint[inPointArray.length];
78                 String[] dataArray = null;
79                 int pointIndex = 0;
80                 for (int p=0; p < inPointArray.length; p++)
81                 {
82                         dataArray = (String[]) inPointArray[p];
83                         // Convert to DataPoint objects
84                         DataPoint point = new DataPoint(dataArray, _masterFieldList, inAltFormat);
85                         if (point.isValid())
86                         {
87                                 _dataPoints[pointIndex] = point;
88                                 pointIndex++;
89                         }
90                 }
91                 _numPoints = pointIndex;
92                 // Set first track point to be start of segment
93                 DataPoint firstTrackPoint = getNextTrackPoint(0);
94                 if (firstTrackPoint != null) {
95                         firstTrackPoint.setSegmentStart(true);
96                 }
97                 // needs to be scaled
98                 _scaled = false;
99         }
100
101
102         /**
103          * Load the track by transferring the contents from a loaded Track object
104          * @param inOther Track object containing loaded data
105          */
106         public void load(Track inOther)
107         {
108                 _numPoints = inOther._numPoints;
109                 _masterFieldList = inOther._masterFieldList;
110                 _dataPoints = inOther._dataPoints;
111                 // needs to be scaled
112                 _scaled = false;
113         }
114
115         /**
116          * Request that a rescale be done to recalculate derived values
117          */
118         public void requestRescale()
119         {
120                 _scaled = false;
121         }
122
123         /**
124          * Extend the track's field list with the given additional fields
125          * @param inFieldList list of fields to be added
126          */
127         public void extendFieldList(FieldList inFieldList)
128         {
129                 _masterFieldList = _masterFieldList.merge(inFieldList);
130         }
131
132         ////////////////// Modification methods //////////////////////
133
134
135         /**
136          * Combine this Track with new data
137          * @param inOtherTrack other track to combine
138          */
139         public void combine(Track inOtherTrack)
140         {
141                 // merge field list
142                 _masterFieldList = _masterFieldList.merge(inOtherTrack._masterFieldList);
143                 // expand data array and add other track's data points
144                 int totalPoints = getNumPoints() + inOtherTrack.getNumPoints();
145                 DataPoint[] mergedPoints = new DataPoint[totalPoints];
146                 System.arraycopy(_dataPoints, 0, mergedPoints, 0, getNumPoints());
147                 System.arraycopy(inOtherTrack._dataPoints, 0, mergedPoints, getNumPoints(), inOtherTrack.getNumPoints());
148                 _dataPoints = mergedPoints;
149                 // combine point count
150                 _numPoints = totalPoints;
151                 // needs to be scaled again
152                 _scaled = false;
153                 // inform listeners
154                 UpdateMessageBroker.informSubscribers();
155         }
156
157
158         /**
159          * Crop the track to the given size - subsequent points are not (yet) deleted
160          * @param inNewSize new number of points in track
161          */
162         public void cropTo(int inNewSize)
163         {
164                 if (inNewSize >= 0 && inNewSize < getNumPoints())
165                 {
166                         _numPoints = inNewSize;
167                         // needs to be scaled again
168                         _scaled = false;
169                         UpdateMessageBroker.informSubscribers();
170                 }
171         }
172
173
174         /**
175          * Delete the points marked for deletion
176          * @return number of points deleted
177          */
178         public int deleteMarkedPoints()
179         {
180                 int numCopied = 0;
181                 // Copy selected points
182                 DataPoint[] newPointArray = new DataPoint[_numPoints];
183                 for (int i=0; i<_numPoints; i++)
184                 {
185                         DataPoint point = _dataPoints[i];
186                         // Don't delete photo points
187                         if (point.hasMedia() || !point.getDeleteFlag())
188                         {
189                                 newPointArray[numCopied] = point;
190                                 numCopied++;
191                         }
192                 }
193
194                 // Copy array references
195                 int numDeleted = _numPoints - numCopied;
196                 if (numDeleted > 0)
197                 {
198                         _dataPoints = new DataPoint[numCopied];
199                         System.arraycopy(newPointArray, 0, _dataPoints, 0, numCopied);
200                         _numPoints = _dataPoints.length;
201                         _scaled = false;
202                 }
203                 return numDeleted;
204         }
205
206
207         /**
208          * Delete the specified point
209          * @param inIndex point index
210          * @return true if successful
211          */
212         public boolean deletePoint(int inIndex)
213         {
214                 boolean answer = deleteRange(inIndex, inIndex);
215                 return answer;
216         }
217
218
219         /**
220          * Delete the specified range of points from the Track
221          * @param inStart start of range (inclusive)
222          * @param inEnd end of range (inclusive)
223          * @return true if successful
224          */
225         public boolean deleteRange(int inStart, int inEnd)
226         {
227                 if (inStart < 0 || inEnd < 0 || inEnd < inStart)
228                 {
229                         // no valid range selected so can't delete
230                         return false;
231                 }
232                 // check through range to be deleted, and see if any new segment flags present
233                 boolean hasSegmentStart = false;
234                 DataPoint nextTrackPoint = getNextTrackPoint(inEnd+1);
235                 if (nextTrackPoint != null) {
236                         for (int i=inStart; i<=inEnd && !hasSegmentStart; i++) {
237                                 hasSegmentStart |= _dataPoints[i].getSegmentStart();
238                         }
239                         // If segment break found, make sure next trackpoint also has break
240                         if (hasSegmentStart) {nextTrackPoint.setSegmentStart(true);}
241                 }
242                 // valid range, let's delete it
243                 int numToDelete = inEnd - inStart + 1;
244                 DataPoint[] newPointArray = new DataPoint[_numPoints - numToDelete];
245                 // Copy points before the selected range
246                 if (inStart > 0)
247                 {
248                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inStart);
249                 }
250                 // Copy points after the deleted one(s)
251                 if (inEnd < (_numPoints - 1))
252                 {
253                         System.arraycopy(_dataPoints, inEnd + 1, newPointArray, inStart,
254                                 _numPoints - inEnd - 1);
255                 }
256                 // Copy points over original array
257                 _dataPoints = newPointArray;
258                 _numPoints -= numToDelete;
259                 // needs to be scaled again
260                 _scaled = false;
261                 return true;
262         }
263
264
265         /**
266          * Reverse the specified range of points
267          * @param inStart start index
268          * @param inEnd end index
269          * @return true if successful, false otherwise
270          */
271         public boolean reverseRange(int inStart, int inEnd)
272         {
273                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints)
274                 {
275                         return false;
276                 }
277                 // calculate how many point swaps are required
278                 int numPointsToReverse = (inEnd - inStart + 1) / 2;
279                 DataPoint p = null;
280                 for (int i=0; i<numPointsToReverse; i++)
281                 {
282                         // swap pairs of points
283                         p = _dataPoints[inStart + i];
284                         _dataPoints[inStart + i] = _dataPoints[inEnd - i];
285                         _dataPoints[inEnd - i] = p;
286                 }
287                 // adjust segment starts
288                 shiftSegmentStarts(inStart, inEnd);
289                 // Find first track point and following track point, and set segment starts to true
290                 DataPoint firstTrackPoint = getNextTrackPoint(inStart);
291                 if (firstTrackPoint != null) {firstTrackPoint.setSegmentStart(true);}
292                 DataPoint nextTrackPoint = getNextTrackPoint(inEnd+1);
293                 if (nextTrackPoint != null) {nextTrackPoint.setSegmentStart(true);}
294                 // needs to be scaled again
295                 _scaled = false;
296                 UpdateMessageBroker.informSubscribers();
297                 return true;
298         }
299
300
301         /**
302          * Add the given time offset to the specified range
303          * @param inStart start of range
304          * @param inEnd end of range
305          * @param inOffset offset to add (-ve to subtract)
306          * @param inUndo true for undo operation
307          * @return true on success
308          */
309         public boolean addTimeOffset(int inStart, int inEnd, long inOffset, boolean inUndo)
310         {
311                 // sanity check
312                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints) {
313                         return false;
314                 }
315                 boolean foundTimestamp = false;
316                 // Loop over all points within range
317                 for (int i=inStart; i<=inEnd; i++)
318                 {
319                         Timestamp timestamp = _dataPoints[i].getTimestamp();
320                         if (timestamp != null)
321                         {
322                                 // This point has a timestamp so add the offset to it
323                                 foundTimestamp = true;
324                                 timestamp.addOffset(inOffset);
325                                 _dataPoints[i].setModified(inUndo);
326                         }
327                 }
328                 return foundTimestamp;
329         }
330
331         /**
332          * Add the given altitude offset to the specified range
333          * @param inStart start of range
334          * @param inEnd end of range
335          * @param inOffset offset to add (-ve to subtract)
336          * @param inFormat altitude format of offset
337          * @param inDecimals number of decimal places in offset
338          * @return true on success
339          */
340         public boolean addAltitudeOffset(int inStart, int inEnd, double inOffset,
341          Altitude.Format inFormat, int inDecimals)
342         {
343                 // sanity check
344                 if (inStart < 0 || inEnd < 0 || inStart >= inEnd || inEnd >= _numPoints) {
345                         return false;
346                 }
347                 boolean foundAlt = false;
348                 // Loop over all points within range
349                 for (int i=inStart; i<=inEnd; i++)
350                 {
351                         Altitude alt = _dataPoints[i].getAltitude();
352                         if (alt != null && alt.isValid())
353                         {
354                                 // This point has an altitude so add the offset to it
355                                 foundAlt = true;
356                                 alt.addOffset(inOffset, inFormat, inDecimals);
357                                 _dataPoints[i].setModified(false);
358                         }
359                 }
360                 // needs to be scaled again
361                 _scaled = false;
362                 return foundAlt;
363         }
364
365
366         /**
367          * Collect all waypoints to the start or end of the track
368          * @param inAtStart true to collect at start, false for end
369          * @return true if successful, false if no change
370          */
371         public boolean collectWaypoints(boolean inAtStart)
372         {
373                 // Check for mixed data, numbers of waypoints & nons
374                 int numWaypoints = 0, numNonWaypoints = 0;
375                 boolean wayAfterNon = false, nonAfterWay = false;
376                 DataPoint[] waypoints = new DataPoint[_numPoints];
377                 DataPoint[] nonWaypoints = new DataPoint[_numPoints];
378                 DataPoint point = null;
379                 for (int i=0; i<_numPoints; i++)
380                 {
381                         point = _dataPoints[i];
382                         if (point.isWaypoint())
383                         {
384                                 waypoints[numWaypoints] = point;
385                                 numWaypoints++;
386                                 wayAfterNon |= (numNonWaypoints > 0);
387                         }
388                         else
389                         {
390                                 nonWaypoints[numNonWaypoints] = point;
391                                 numNonWaypoints++;
392                                 nonAfterWay |= (numWaypoints > 0);
393                         }
394                 }
395                 // Exit if the data is already in the specified order
396                 if (numWaypoints == 0 || numNonWaypoints == 0
397                         || (inAtStart && !wayAfterNon && nonAfterWay)
398                         || (!inAtStart && wayAfterNon && !nonAfterWay))
399                 {
400                         return false;
401                 }
402
403                 // Copy the arrays back into _dataPoints in the specified order
404                 if (inAtStart)
405                 {
406                         System.arraycopy(waypoints, 0, _dataPoints, 0, numWaypoints);
407                         System.arraycopy(nonWaypoints, 0, _dataPoints, numWaypoints, numNonWaypoints);
408                 }
409                 else
410                 {
411                         System.arraycopy(nonWaypoints, 0, _dataPoints, 0, numNonWaypoints);
412                         System.arraycopy(waypoints, 0, _dataPoints, numNonWaypoints, numWaypoints);
413                 }
414                 // needs to be scaled again
415                 _scaled = false;
416                 UpdateMessageBroker.informSubscribers();
417                 return true;
418         }
419
420
421         /**
422          * Interleave all waypoints by each nearest track point
423          * @return true if successful, false if no change
424          */
425         public boolean interleaveWaypoints()
426         {
427                 // Separate waypoints and find nearest track point
428                 int numWaypoints = 0;
429                 DataPoint[] waypoints = new DataPoint[_numPoints];
430                 int[] pointIndices = new int[_numPoints];
431                 DataPoint point = null;
432                 int i = 0;
433                 for (i=0; i<_numPoints; i++)
434                 {
435                         point = _dataPoints[i];
436                         if (point.isWaypoint())
437                         {
438                                 waypoints[numWaypoints] = point;
439                                 pointIndices[numWaypoints] = getNearestPointIndex(
440                                         _xValues[i], _yValues[i], -1.0, true);
441                                 numWaypoints++;
442                         }
443                 }
444                 // Exit if data not mixed
445                 if (numWaypoints == 0 || numWaypoints == _numPoints)
446                         return false;
447
448                 // Loop round points copying to correct order
449                 DataPoint[] dataCopy = new DataPoint[_numPoints];
450                 int copyIndex = 0;
451                 for (i=0; i<_numPoints; i++)
452                 {
453                         point = _dataPoints[i];
454                         // if it's a track point, copy it
455                         if (!point.isWaypoint())
456                         {
457                                 dataCopy[copyIndex] = point;
458                                 copyIndex++;
459                         }
460                         // check for waypoints with this index
461                         for (int j=0; j<numWaypoints; j++)
462                         {
463                                 if (pointIndices[j] == i)
464                                 {
465                                         dataCopy[copyIndex] = waypoints[j];
466                                         copyIndex++;
467                                 }
468                         }
469                 }
470                 // Copy data back to track
471                 _dataPoints = dataCopy;
472                 // needs to be scaled again to recalc x, y
473                 _scaled = false;
474                 UpdateMessageBroker.informSubscribers();
475                 return true;
476         }
477
478
479         /**
480          * Cut and move the specified section
481          * @param inSectionStart start index of section
482          * @param inSectionEnd end index of section
483          * @param inMoveTo index of move to point
484          * @return true if move successful
485          */
486         public boolean cutAndMoveSection(int inSectionStart, int inSectionEnd, int inMoveTo)
487         {
488                 // TODO: Move cut/move into separate function?
489                 // Check that indices make sense
490                 if (inSectionStart >= 0 && inSectionEnd > inSectionStart && inMoveTo >= 0
491                         && (inMoveTo < inSectionStart || inMoveTo > (inSectionEnd+1)))
492                 {
493                         // do the cut and move
494                         DataPoint[] newPointArray = new DataPoint[_numPoints];
495                         // System.out.println("Cut/move section (" + inSectionStart + " - " + inSectionEnd + ") to before point " + inMoveTo);
496                         // Is it a forward copy or a backward copy?
497                         if (inSectionStart > inMoveTo)
498                         {
499                                 int sectionLength = inSectionEnd - inSectionStart + 1;
500                                 // move section to earlier point
501                                 if (inMoveTo > 0) {
502                                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inMoveTo); // unchanged points before
503                                 }
504                                 System.arraycopy(_dataPoints, inSectionStart, newPointArray, inMoveTo, sectionLength); // moved bit
505                                 // after insertion point, before moved bit
506                                 System.arraycopy(_dataPoints, inMoveTo, newPointArray, inMoveTo + sectionLength, inSectionStart - inMoveTo);
507                                 // after moved bit
508                                 if (inSectionEnd < (_numPoints - 1)) {
509                                         System.arraycopy(_dataPoints, inSectionEnd+1, newPointArray, inSectionEnd+1, _numPoints - inSectionEnd - 1);
510                                 }
511                         }
512                         else
513                         {
514                                 // Move section to later point
515                                 if (inSectionStart > 0) {
516                                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inSectionStart); // unchanged points before
517                                 }
518                                 // from end of section to move to point
519                                 if (inMoveTo > (inSectionEnd + 1)) {
520                                         System.arraycopy(_dataPoints, inSectionEnd+1, newPointArray, inSectionStart, inMoveTo - inSectionEnd - 1);
521                                 }
522                                 // moved bit
523                                 System.arraycopy(_dataPoints, inSectionStart, newPointArray, inSectionStart + inMoveTo - inSectionEnd - 1,
524                                         inSectionEnd - inSectionStart + 1);
525                                 // unchanged bit after
526                                 if (inSectionEnd < (_numPoints - 1)) {
527                                         System.arraycopy(_dataPoints, inMoveTo, newPointArray, inMoveTo, _numPoints - inMoveTo);
528                                 }
529                         }
530                         // Copy array references
531                         _dataPoints = newPointArray;
532                         _scaled = false;
533                         return true;
534                 }
535                 return false;
536         }
537
538
539         /**
540          * Interpolate extra points between two selected ones
541          * @param inStartIndex start index of interpolation
542          * @param inNumPoints num points to insert
543          * @return true if successful
544          */
545         public boolean interpolate(int inStartIndex, int inNumPoints)
546         {
547                 // check parameters
548                 if (inStartIndex < 0 || inStartIndex >= _numPoints || inNumPoints <= 0)
549                         return false;
550
551                 // get start and end points
552                 DataPoint startPoint = getPoint(inStartIndex);
553                 DataPoint endPoint = getPoint(inStartIndex + 1);
554
555                 // Make array of points to insert
556                 DataPoint[] insertedPoints = startPoint.interpolate(endPoint, inNumPoints);
557
558                 // Insert points into track
559                 return insertRange(insertedPoints, inStartIndex + 1);
560         }
561
562
563         /**
564          * Average selected points
565          * @param inStartIndex start index of selection
566          * @param inEndIndex end index of selection
567          * @return true if successful
568          */
569         public boolean average(int inStartIndex, int inEndIndex)
570         {
571                 // check parameters
572                 if (inStartIndex < 0 || inStartIndex >= _numPoints || inEndIndex <= inStartIndex)
573                         return false;
574
575                 DataPoint startPoint = getPoint(inStartIndex);
576                 double firstLatitude = startPoint.getLatitude().getDouble();
577                 double firstLongitude = startPoint.getLongitude().getDouble();
578                 double latitudeDiff = 0.0, longitudeDiff = 0.0;
579                 double totalAltitude = 0;
580                 int numAltitudes = 0;
581                 Altitude.Format altFormat = Altitude.Format.NO_FORMAT;
582                 // loop between start and end points
583                 for (int i=inStartIndex; i<= inEndIndex; i++)
584                 {
585                         DataPoint currPoint = getPoint(i);
586                         latitudeDiff += (currPoint.getLatitude().getDouble() - firstLatitude);
587                         longitudeDiff += (currPoint.getLongitude().getDouble() - firstLongitude);
588                         if (currPoint.hasAltitude()) {
589                                 totalAltitude += currPoint.getAltitude().getValue(altFormat);
590                                 // Use altitude format of first valid altitude
591                                 if (altFormat == Altitude.Format.NO_FORMAT)
592                                         altFormat = currPoint.getAltitude().getFormat();
593                                 numAltitudes++;
594                         }
595                 }
596                 int numPoints = inEndIndex - inStartIndex + 1;
597                 double meanLatitude = firstLatitude + (latitudeDiff / numPoints);
598                 double meanLongitude = firstLongitude + (longitudeDiff / numPoints);
599                 Altitude meanAltitude = null;
600                 if (numAltitudes > 0) {meanAltitude = new Altitude((int) (totalAltitude / numAltitudes), altFormat);}
601
602                 DataPoint insertedPoint = new DataPoint(new Latitude(meanLatitude, Coordinate.FORMAT_NONE),
603                         new Longitude(meanLongitude, Coordinate.FORMAT_NONE), meanAltitude);
604                 // Make into singleton
605                 insertedPoint.setSegmentStart(true);
606                 DataPoint nextPoint = getNextTrackPoint(inEndIndex+1);
607                 if (nextPoint != null) {nextPoint.setSegmentStart(true);}
608                 // Insert points into track
609                 return insertRange(new DataPoint[] {insertedPoint}, inEndIndex + 1);
610         }
611
612
613         /**
614          * Append the specified points to the end of the track
615          * @param inPoints DataPoint objects to add
616          */
617         public void appendPoints(DataPoint[] inPoints)
618         {
619                 // Insert points into track
620                 if (inPoints != null && inPoints.length > 0)
621                 {
622                         insertRange(inPoints, _numPoints);
623                 }
624                 // needs to be scaled again to recalc x, y
625                 _scaled = false;
626                 UpdateMessageBroker.informSubscribers();
627         }
628
629
630         //////// information methods /////////////
631
632
633         /**
634          * Get the point at the given index
635          * @param inPointNum index number, starting at 0
636          * @return DataPoint object, or null if out of range
637          */
638         public DataPoint getPoint(int inPointNum)
639         {
640                 if (inPointNum > -1 && inPointNum < getNumPoints())
641                 {
642                         return _dataPoints[inPointNum];
643                 }
644                 return null;
645         }
646
647         /**
648          * @return the number of (valid) points in the track
649          */
650         public int getNumPoints()
651         {
652                 return _numPoints;
653         }
654
655         /**
656          * @return The range of x values as a DoubleRange object
657          */
658         public DoubleRange getXRange()
659         {
660                 if (!_scaled) scalePoints();
661                 return _xRange;
662         }
663
664         /**
665          * @return The range of y values as a DoubleRange object
666          */
667         public DoubleRange getYRange()
668         {
669                 if (!_scaled) scalePoints();
670                 return _yRange;
671         }
672
673         /**
674          * @return The range of lat values as a DoubleRange object
675          */
676         public DoubleRange getLatRange()
677         {
678                 if (!_scaled) scalePoints();
679                 return _latRange;
680         }
681         /**
682          * @return The range of lon values as a DoubleRange object
683          */
684         public DoubleRange getLonRange()
685         {
686                 if (!_scaled) scalePoints();
687                 return _longRange;
688         }
689
690         /**
691          * @param inPointNum point index, starting at 0
692          * @return scaled x value of specified point
693          */
694         public double getX(int inPointNum)
695         {
696                 if (!_scaled) scalePoints();
697                 return _xValues[inPointNum];
698         }
699
700         /**
701          * @param inPointNum point index, starting at 0
702          * @return scaled y value of specified point
703          */
704         public double getY(int inPointNum)
705         {
706                 if (!_scaled) scalePoints();
707                 return _yValues[inPointNum];
708         }
709
710         /**
711          * @return the master field list
712          */
713         public FieldList getFieldList()
714         {
715                 return _masterFieldList;
716         }
717
718
719         /**
720          * Checks if any data exists for the specified field
721          * @param inField Field to examine
722          * @return true if data exists for this field
723          */
724         public boolean hasData(Field inField)
725         {
726                 // Don't use this method for altitudes
727                 if (inField.equals(Field.ALTITUDE)) {return hasAltitudeData();}
728                 return hasData(inField, 0, _numPoints-1);
729         }
730
731
732         /**
733          * Checks if any data exists for the specified field in the specified range
734          * @param inField Field to examine
735          * @param inStart start of range to check
736          * @param inEnd end of range to check (inclusive)
737          * @return true if data exists for this field
738          */
739         public boolean hasData(Field inField, int inStart, int inEnd)
740         {
741                 // Loop over selected point range
742                 for (int i=inStart; i<=inEnd; i++)
743                 {
744                         if (_dataPoints[i].getFieldValue(inField) != null)
745                         {
746                                 // Check altitudes and timestamps
747                                 if ((inField != Field.ALTITUDE || _dataPoints[i].getAltitude().isValid())
748                                         && (inField != Field.TIMESTAMP || _dataPoints[i].getTimestamp().isValid()))
749                                 {
750                                         return true;
751                                 }
752                         }
753                 }
754                 return false;
755         }
756
757         /**
758          * @return true if track has altitude data
759          */
760         public boolean hasAltitudeData()
761         {
762                 for (int i=0; i<_numPoints; i++) {
763                         if (_dataPoints[i].hasAltitude()) {return true;}
764                 }
765                 return false;
766         }
767
768         /**
769          * @return true if track contains at least one trackpoint
770          */
771         public boolean hasTrackPoints()
772         {
773                 if (!_scaled) scalePoints();
774                 return _hasTrackpoint;
775         }
776
777         /**
778          * @return true if track contains waypoints
779          */
780         public boolean hasWaypoints()
781         {
782                 if (!_scaled) scalePoints();
783                 return _hasWaypoint;
784         }
785
786         /**
787          * @return true if track contains any points marked for deletion
788          */
789         public boolean hasMarkedPoints()
790         {
791                 if (_numPoints < 1) {
792                         return false;
793                 }
794                 // Loop over points looking for any marked for deletion
795                 for (int i=0; i<=_numPoints-1; i++)
796                 {
797                         if (_dataPoints[i] != null && _dataPoints[i].getDeleteFlag()) {
798                                 return true;
799                         }
800                 }
801                 // None found
802                 return false;
803         }
804
805         /**
806          * Clear all the deletion markers
807          */
808         public void clearDeletionMarkers()
809         {
810                 for (int i=0; i<_numPoints; i++)
811                 {
812                         _dataPoints[i].setMarkedForDeletion(false);
813                 }
814         }
815
816         /**
817          * Collect all the waypoints into the given List
818          * @param inList List to fill with waypoints
819          */
820         public void getWaypoints(List<DataPoint> inList)
821         {
822                 // clear list
823                 inList.clear();
824                 // loop over points and copy all waypoints into list
825                 for (int i=0; i<=_numPoints-1; i++)
826                 {
827                         if (_dataPoints[i] != null && _dataPoints[i].isWaypoint())
828                         {
829                                 inList.add(_dataPoints[i]);
830                         }
831                 }
832         }
833
834
835         /**
836          * Search for the given Point in the track and return the index
837          * @param inPoint Point to look for
838          * @return index of Point, if any or -1 if not found
839          */
840         public int getPointIndex(DataPoint inPoint)
841         {
842                 if (inPoint != null)
843                 {
844                         // Loop over points in track
845                         for (int i=0; i<=_numPoints-1; i++)
846                         {
847                                 if (_dataPoints[i] == inPoint)
848                                 {
849                                         return i;
850                                 }
851                         }
852                 }
853                 // not found
854                 return -1;
855         }
856
857
858         ///////// Internal processing methods ////////////////
859
860
861         /**
862          * Scale all the points in the track to gain x and y values
863          * ready for plotting
864          */
865         private void scalePoints()
866         {
867                 // Loop through all points in track, to see limits of lat, long
868                 _longRange = new DoubleRange();
869                 _latRange = new DoubleRange();
870                 int p;
871                 _hasWaypoint = false; _hasTrackpoint = false;
872                 for (p=0; p < getNumPoints(); p++)
873                 {
874                         DataPoint point = getPoint(p);
875                         if (point != null && point.isValid())
876                         {
877                                 _longRange.addValue(point.getLongitude().getDouble());
878                                 _latRange.addValue(point.getLatitude().getDouble());
879                                 if (point.isWaypoint())
880                                         _hasWaypoint = true;
881                                 else
882                                         _hasTrackpoint = true;
883                         }
884                 }
885
886                 // Loop over points and calculate scales
887                 _xValues = new double[getNumPoints()];
888                 _yValues = new double[getNumPoints()];
889                 _xRange = new DoubleRange();
890                 _yRange = new DoubleRange();
891                 for (p=0; p < getNumPoints(); p++)
892                 {
893                         DataPoint point = getPoint(p);
894                         if (point != null)
895                         {
896                                 _xValues[p] = MapUtils.getXFromLongitude(point.getLongitude().getDouble());
897                                 _xRange.addValue(_xValues[p]);
898                                 _yValues[p] = MapUtils.getYFromLatitude(point.getLatitude().getDouble());
899                                 _yRange.addValue(_yValues[p]);
900                         }
901                 }
902                 _scaled = true;
903         }
904
905
906         /**
907          * Find the nearest point to the specified x and y coordinates
908          * or -1 if no point is within the specified max distance
909          * @param inX x coordinate
910          * @param inY y coordinate
911          * @param inMaxDist maximum distance from selected coordinates
912          * @param inJustTrackPoints true if waypoints should be ignored
913          * @return index of nearest point or -1 if not found
914          */
915         public int getNearestPointIndex(double inX, double inY, double inMaxDist, boolean inJustTrackPoints)
916         {
917                 int nearestPoint = 0;
918                 double nearestDist = -1.0;
919                 double mDist, yDist;
920                 for (int i=0; i < getNumPoints(); i++)
921                 {
922                         if (!inJustTrackPoints || !_dataPoints[i].isWaypoint())
923                         {
924                                 yDist = Math.abs(_yValues[i] - inY);
925                                 if (yDist < nearestDist || nearestDist < 0.0)
926                                 {
927                                         // y dist is within range, so check x too
928                                         mDist = yDist + getMinXDist(_xValues[i] - inX);
929                                         if (mDist < nearestDist || nearestDist < 0.0)
930                                         {
931                                                 nearestPoint = i;
932                                                 nearestDist = mDist;
933                                         }
934                                 }
935                         }
936                 }
937                 // Check whether it's within required distance
938                 if (nearestDist > inMaxDist && inMaxDist > 0.0)
939                 {
940                         return -1;
941                 }
942                 return nearestPoint;
943         }
944
945         /**
946          * @param inX x value of point
947          * @return minimum wrapped value
948          */
949         private static final double getMinXDist(double inX)
950         {
951                 // TODO: Can use some kind of floor here?
952                 return Math.min(Math.min(Math.abs(inX), Math.abs(inX-1.0)), Math.abs(inX+1.0));
953         }
954
955         /**
956          * Get the next track point starting from the given index
957          * @param inStartIndex index to start looking from
958          * @return next track point, or null if end of data reached
959          */
960         public DataPoint getNextTrackPoint(int inStartIndex)
961         {
962                 return getNextTrackPoint(inStartIndex, _numPoints, true);
963         }
964
965         /**
966          * Get the next track point in the given range
967          * @param inStartIndex index to start looking from
968          * @param inEndIndex index to stop looking
969          * @return next track point, or null if end of data reached
970          */
971         public DataPoint getNextTrackPoint(int inStartIndex, int inEndIndex)
972         {
973                 return getNextTrackPoint(inStartIndex, inEndIndex, true);
974         }
975
976         /**
977          * Get the previous track point starting from the given index
978          * @param inStartIndex index to start looking from
979          * @return next track point, or null if end of data reached
980          */
981         public DataPoint getPreviousTrackPoint(int inStartIndex)
982         {
983                 // end index is given as _numPoints but actually it just counts down to -1
984                 return getNextTrackPoint(inStartIndex, _numPoints, false);
985         }
986
987         /**
988          * Get the next track point starting from the given index
989          * @param inStartIndex index to start looking from
990          * @param inEndIndex index to stop looking (inclusive)
991          * @param inCountUp true for next, false for previous
992          * @return next track point, or null if end of data reached
993          */
994         private DataPoint getNextTrackPoint(int inStartIndex, int inEndIndex, boolean inCountUp)
995         {
996                 // Loop forever over points
997                 int increment = inCountUp?1:-1;
998                 for (int i=inStartIndex; i<=inEndIndex; i+=increment)
999                 {
1000                         DataPoint point = getPoint(i);
1001                         // Exit if end of data reached - there wasn't a track point
1002                         if (point == null) {return null;}
1003                         if (point.isValid() && !point.isWaypoint()) {
1004                                 // next track point found
1005                                 return point;
1006                         }
1007                 }
1008                 return null;
1009         }
1010
1011         /**
1012          * Shift all the segment start flags in the given range by 1
1013          * Method used by reverse range and its undo
1014          * @param inStartIndex start of range, inclusive
1015          * @param inEndIndex end of range, inclusive
1016          */
1017         public void shiftSegmentStarts(int inStartIndex, int inEndIndex)
1018         {
1019                 boolean prevFlag = true;
1020                 boolean currFlag = true;
1021                 for (int i=inStartIndex; i<= inEndIndex; i++)
1022                 {
1023                         DataPoint point = getPoint(i);
1024                         if (point != null && !point.isWaypoint())
1025                         {
1026                                 // remember flag
1027                                 currFlag = point.getSegmentStart();
1028                                 // shift flag by 1
1029                                 point.setSegmentStart(prevFlag);
1030                                 prevFlag = currFlag;
1031                         }
1032                 }
1033         }
1034
1035         ////////////////// Cloning and replacing ///////////////////
1036
1037         /**
1038          * Clone the array of DataPoints
1039          * @return shallow copy of DataPoint objects
1040          */
1041         public DataPoint[] cloneContents()
1042         {
1043                 DataPoint[] clone = new DataPoint[getNumPoints()];
1044                 System.arraycopy(_dataPoints, 0, clone, 0, getNumPoints());
1045                 return clone;
1046         }
1047
1048
1049         /**
1050          * Clone the specified range of data points
1051          * @param inStart start index (inclusive)
1052          * @param inEnd end index (inclusive)
1053          * @return shallow copy of DataPoint objects
1054          */
1055         public DataPoint[] cloneRange(int inStart, int inEnd)
1056         {
1057                 int numSelected = 0;
1058                 if (inEnd >= 0 && inEnd >= inStart)
1059                 {
1060                         numSelected = inEnd - inStart + 1;
1061                 }
1062                 DataPoint[] result = new DataPoint[numSelected>0?numSelected:0];
1063                 if (numSelected > 0)
1064                 {
1065                         System.arraycopy(_dataPoints, inStart, result, 0, numSelected);
1066                 }
1067                 return result;
1068         }
1069
1070
1071         /**
1072          * Re-insert the specified point at the given index
1073          * @param inPoint point to insert
1074          * @param inIndex index at which to insert the point
1075          * @return true if it worked, false otherwise
1076          */
1077         public boolean insertPoint(DataPoint inPoint, int inIndex)
1078         {
1079                 if (inIndex > _numPoints || inPoint == null)
1080                 {
1081                         return false;
1082                 }
1083                 // Make new array to copy points over to
1084                 DataPoint[] newPointArray = new DataPoint[_numPoints + 1];
1085                 if (inIndex > 0)
1086                 {
1087                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inIndex);
1088                 }
1089                 newPointArray[inIndex] = inPoint;
1090                 if (inIndex < _numPoints)
1091                 {
1092                         System.arraycopy(_dataPoints, inIndex, newPointArray, inIndex+1, _numPoints - inIndex);
1093                 }
1094                 // Change over to new array
1095                 _dataPoints = newPointArray;
1096                 _numPoints++;
1097                 // needs to be scaled again
1098                 _scaled = false;
1099                 UpdateMessageBroker.informSubscribers();
1100                 return true;
1101         }
1102
1103
1104         /**
1105          * Re-insert the specified point range at the given index
1106          * @param inPoints point array to insert
1107          * @param inIndex index at which to insert the points
1108          * @return true if it worked, false otherwise
1109          */
1110         public boolean insertRange(DataPoint[] inPoints, int inIndex)
1111         {
1112                 if (inIndex > _numPoints || inPoints == null)
1113                 {
1114                         return false;
1115                 }
1116                 // Make new array to copy points over to
1117                 DataPoint[] newPointArray = new DataPoint[_numPoints + inPoints.length];
1118                 if (inIndex > 0)
1119                 {
1120                         System.arraycopy(_dataPoints, 0, newPointArray, 0, inIndex);
1121                 }
1122                 System.arraycopy(inPoints, 0, newPointArray, inIndex, inPoints.length);
1123                 if (inIndex < _numPoints)
1124                 {
1125                         System.arraycopy(_dataPoints, inIndex, newPointArray, inIndex+inPoints.length, _numPoints - inIndex);
1126                 }
1127                 // Change over to new array
1128                 _dataPoints = newPointArray;
1129                 _numPoints += inPoints.length;
1130                 // needs to be scaled again
1131                 _scaled = false;
1132                 UpdateMessageBroker.informSubscribers();
1133                 return true;
1134         }
1135
1136
1137         /**
1138          * Replace the track contents with the given point array
1139          * @param inContents array of DataPoint objects
1140          * @return true on success
1141          */
1142         public boolean replaceContents(DataPoint[] inContents)
1143         {
1144                 // master field array stays the same
1145                 // (would need to store field array too if we wanted to redo a load)
1146                 // replace data array
1147                 _dataPoints = inContents;
1148                 _numPoints = _dataPoints.length;
1149                 _scaled = false;
1150                 UpdateMessageBroker.informSubscribers();
1151                 return true;
1152         }
1153
1154
1155         /**
1156          * Edit the specified point
1157          * @param inPoint point to edit
1158          * @param inEditList list of edits to make
1159          * @param inUndo true if undo operation, false otherwise
1160          * @return true if successful
1161          */
1162         public boolean editPoint(DataPoint inPoint, FieldEditList inEditList, boolean inUndo)
1163         {
1164                 if (inPoint != null && inEditList != null && inEditList.getNumEdits() > 0)
1165                 {
1166                         // remember if coordinates have changed
1167                         boolean coordsChanged = false;
1168                         // go through edits one by one
1169                         int numEdits = inEditList.getNumEdits();
1170                         for (int i=0; i<numEdits; i++)
1171                         {
1172                                 FieldEdit edit = inEditList.getEdit(i);
1173                                 Field editField = edit.getField();
1174                                 inPoint.setFieldValue(editField, edit.getValue(), inUndo);
1175                                 // Check that master field list has this field already (maybe point name has been added)
1176                                 if (!_masterFieldList.contains(editField)) {
1177                                         _masterFieldList.extendList(editField);
1178                                 }
1179                                 // check coordinates
1180                                 coordsChanged |= (editField.equals(Field.LATITUDE)
1181                                         || editField.equals(Field.LONGITUDE) || editField.equals(Field.ALTITUDE));
1182                         }
1183                         // set photo status if coordinates have changed
1184                         if (inPoint.getPhoto() != null && coordsChanged)
1185                         {
1186                                 inPoint.getPhoto().setCurrentStatus(Photo.Status.CONNECTED);
1187                         }
1188                         // point possibly needs to be scaled again
1189                         _scaled = false;
1190                         // trigger listeners
1191                         UpdateMessageBroker.informSubscribers();
1192                         return true;
1193                 }
1194                 return false;
1195         }
1196
1197         /**
1198          * @param inPoint point to check
1199          * @return true if this track contains the given point
1200          */
1201         public boolean containsPoint(DataPoint inPoint)
1202         {
1203                 if (inPoint == null) return false;
1204                 for (int i=0; i < getNumPoints(); i++)
1205                 {
1206                         if (getPoint(i) == inPoint) return true;
1207                 }
1208                 return false; // not found
1209         }
1210 }