source: josm/trunk/src/org/openstreetmap/josm/data/gpx/GpxData.java@ 14338

Last change on this file since 14338 was 14338, checked in by Don-vip, 6 years ago

fix #16755 - Cut overlapping GPX layers when merging (patch by Bjoeni, modified)

  • Property svn:eol-style set to native
File size: 38.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.gpx;
3
4import java.io.File;
5import java.text.MessageFormat;
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.Collection;
9import java.util.Collections;
10import java.util.Date;
11import java.util.DoubleSummaryStatistics;
12import java.util.HashMap;
13import java.util.HashSet;
14import java.util.Iterator;
15import java.util.List;
16import java.util.Map;
17import java.util.NoSuchElementException;
18import java.util.Set;
19import java.util.stream.Collectors;
20import java.util.stream.Stream;
21
22import org.openstreetmap.josm.data.Bounds;
23import org.openstreetmap.josm.data.Data;
24import org.openstreetmap.josm.data.DataSource;
25import org.openstreetmap.josm.data.coor.EastNorth;
26import org.openstreetmap.josm.data.gpx.GpxTrack.GpxTrackChangeListener;
27import org.openstreetmap.josm.data.projection.ProjectionRegistry;
28import org.openstreetmap.josm.gui.MainApplication;
29import org.openstreetmap.josm.gui.layer.GpxLayer;
30import org.openstreetmap.josm.tools.ListenerList;
31import org.openstreetmap.josm.tools.ListeningCollection;
32
33/**
34 * Objects of this class represent a gpx file with tracks, waypoints and routes.
35 * It uses GPX v1.1, see <a href="http://www.topografix.com/GPX/1/1/">the spec</a>
36 * for details.
37 *
38 * @author Raphael Mack &lt;ramack@raphael-mack.de&gt;
39 */
40public class GpxData extends WithAttributes implements Data {
41
42 /**
43 * The disk file this layer is stored in, if it is a local layer. May be <code>null</code>.
44 */
45 public File storageFile;
46 /**
47 * A boolean flag indicating if the data was read from the OSM server.
48 */
49 public boolean fromServer;
50
51 /**
52 * Creator metadata for this file (usually software)
53 */
54 public String creator;
55
56 /**
57 * A list of tracks this file consists of
58 */
59 private final ArrayList<GpxTrack> privateTracks = new ArrayList<>();
60 /**
61 * GPX routes in this file
62 */
63 private final ArrayList<GpxRoute> privateRoutes = new ArrayList<>();
64 /**
65 * Addidionaly waypoints for this file.
66 */
67 private final ArrayList<WayPoint> privateWaypoints = new ArrayList<>();
68 private final GpxTrackChangeListener proxy = e -> fireInvalidate();
69
70 /**
71 * Tracks. Access is discouraged, use {@link #getTracks()} to read.
72 * @see #getTracks()
73 */
74 public final Collection<GpxTrack> tracks = new ListeningCollection<GpxTrack>(privateTracks, this::fireInvalidate) {
75
76 @Override
77 protected void removed(GpxTrack cursor) {
78 cursor.removeListener(proxy);
79 super.removed(cursor);
80 }
81
82 @Override
83 protected void added(GpxTrack cursor) {
84 super.added(cursor);
85 cursor.addListener(proxy);
86 }
87 };
88
89 /**
90 * Routes. Access is discouraged, use {@link #getTracks()} to read.
91 * @see #getRoutes()
92 */
93 public final Collection<GpxRoute> routes = new ListeningCollection<>(privateRoutes, this::fireInvalidate);
94
95 /**
96 * Waypoints. Access is discouraged, use {@link #getTracks()} to read.
97 * @see #getWaypoints()
98 */
99 public final Collection<WayPoint> waypoints = new ListeningCollection<>(privateWaypoints, this::fireInvalidate);
100
101 /**
102 * All data sources (bounds of downloaded bounds) of this GpxData.<br>
103 * Not part of GPX standard but rather a JOSM extension, needed by the fact that
104 * OSM API does not provide {@code <bounds>} element in its GPX reply.
105 * @since 7575
106 */
107 public final Set<DataSource> dataSources = new HashSet<>();
108
109 private final ListenerList<GpxDataChangeListener> listeners = ListenerList.create();
110
111 static class TimestampConfictException extends Exception {}
112
113 private List<GpxTrackSegmentSpan> segSpans;
114
115 /**
116 * Merges data from another object.
117 * @param other existing GPX data
118 */
119 public synchronized void mergeFrom(GpxData other) {
120 mergeFrom(other, false, false);
121 }
122
123 /**
124 * Merges data from another object.
125 * @param other existing GPX data
126 * @param cutOverlapping whether overlapping parts of the given track should be removed
127 * @param connect whether the tracks should be connected on cuts
128 * @since 14338
129 */
130 public synchronized void mergeFrom(GpxData other, boolean cutOverlapping, boolean connect) {
131 if (storageFile == null && other.storageFile != null) {
132 storageFile = other.storageFile;
133 }
134 fromServer = fromServer && other.fromServer;
135
136 for (Map.Entry<String, Object> ent : other.attr.entrySet()) {
137 // TODO: Detect conflicts.
138 String k = ent.getKey();
139 if (META_LINKS.equals(k) && attr.containsKey(META_LINKS)) {
140 Collection<GpxLink> my = super.<GpxLink>getCollection(META_LINKS);
141 @SuppressWarnings("unchecked")
142 Collection<GpxLink> their = (Collection<GpxLink>) ent.getValue();
143 my.addAll(their);
144 } else {
145 put(k, ent.getValue());
146 }
147 }
148
149 if (cutOverlapping) {
150 for (GpxTrack trk : other.privateTracks) {
151 cutOverlapping(trk, connect);
152 }
153 } else {
154 other.privateTracks.forEach(this::addTrack);
155 }
156 other.privateRoutes.forEach(this::addRoute);
157 other.privateWaypoints.forEach(this::addWaypoint);
158 dataSources.addAll(other.dataSources);
159 fireInvalidate();
160 }
161
162 private void cutOverlapping(GpxTrack trk, boolean connect) {
163 List<GpxTrackSegment> segsOld = new ArrayList<>(trk.getSegments());
164 List<GpxTrackSegment> segsNew = new ArrayList<>();
165 for (GpxTrackSegment seg : segsOld) {
166 GpxTrackSegmentSpan s = GpxTrackSegmentSpan.tryGetFromSegment(seg);
167 if (s != null && anySegmentOverlapsWith(s)) {
168 List<WayPoint> wpsNew = new ArrayList<>();
169 List<WayPoint> wpsOld = new ArrayList<>(seg.getWayPoints());
170 if (s.isInverted()) {
171 Collections.reverse(wpsOld);
172 }
173 boolean split = false;
174 WayPoint prevLastOwnWp = null;
175 Date prevWpTime = null;
176 for (WayPoint wp : wpsOld) {
177 Date wpTime = wp.setTimeFromAttribute();
178 boolean overlap = false;
179 if (wpTime != null) {
180 for (GpxTrackSegmentSpan ownspan : getSegmentSpans()) {
181 if (wpTime.after(ownspan.firstTime) && wpTime.before(ownspan.lastTime)) {
182 overlap = true;
183 if (connect) {
184 if (!split) {
185 wpsNew.add(ownspan.getFirstWp());
186 } else {
187 connectTracks(prevLastOwnWp, ownspan, trk.getAttributes());
188 }
189 prevLastOwnWp = ownspan.getLastWp();
190 }
191 split = true;
192 break;
193 } else if (connect && prevWpTime != null
194 && prevWpTime.before(ownspan.firstTime)
195 && wpTime.after(ownspan.lastTime)) {
196 // the overlapping high priority track is shorter than the distance
197 // between two waypoints of the low priority track
198 if (split) {
199 connectTracks(prevLastOwnWp, ownspan, trk.getAttributes());
200 prevLastOwnWp = ownspan.getLastWp();
201 } else {
202 wpsNew.add(ownspan.getFirstWp());
203 // splitting needs to be handled here,
204 // because other high priority tracks between the same waypoints could follow
205 if (!wpsNew.isEmpty()) {
206 segsNew.add(new ImmutableGpxTrackSegment(wpsNew));
207 }
208 if (!segsNew.isEmpty()) {
209 privateTracks.add(new ImmutableGpxTrack(segsNew, trk.getAttributes()));
210 }
211 segsNew = new ArrayList<>();
212 wpsNew = new ArrayList<>();
213 wpsNew.add(ownspan.getLastWp());
214 // therefore no break, because another segment could overlap, see above
215 }
216 }
217 }
218 prevWpTime = wpTime;
219 }
220 if (!overlap) {
221 if (split) {
222 //track has to be split, because we have an overlapping short track in the middle
223 if (!wpsNew.isEmpty()) {
224 segsNew.add(new ImmutableGpxTrackSegment(wpsNew));
225 }
226 if (!segsNew.isEmpty()) {
227 privateTracks.add(new ImmutableGpxTrack(segsNew, trk.getAttributes()));
228 }
229 segsNew = new ArrayList<>();
230 wpsNew = new ArrayList<>();
231 if (connect && prevLastOwnWp != null) {
232 wpsNew.add(new WayPoint(prevLastOwnWp));
233 }
234 prevLastOwnWp = null;
235 split = false;
236 }
237 wpsNew.add(new WayPoint(wp));
238 }
239 }
240 if (!wpsNew.isEmpty()) {
241 segsNew.add(new ImmutableGpxTrackSegment(wpsNew));
242 }
243 } else {
244 segsNew.add(seg);
245 }
246 }
247 if (segsNew.equals(segsOld)) {
248 privateTracks.add(trk);
249 } else if (!segsNew.isEmpty()) {
250 privateTracks.add(new ImmutableGpxTrack(segsNew, trk.getAttributes()));
251 }
252 }
253
254 private void connectTracks(WayPoint prevWp, GpxTrackSegmentSpan span, Map<String, Object> attr) {
255 if (prevWp != null && !span.lastEquals(prevWp)) {
256 privateTracks.add(new ImmutableGpxTrack(Arrays.asList(Arrays.asList(new WayPoint(prevWp), span.getFirstWp())), attr));
257 }
258 }
259
260 static class GpxTrackSegmentSpan {
261
262 public final Date firstTime;
263 public final Date lastTime;
264 private final boolean inv;
265 private final WayPoint firstWp;
266 private final WayPoint lastWp;
267
268 GpxTrackSegmentSpan(WayPoint a, WayPoint b) {
269 Date at = a.getTime();
270 Date bt = b.getTime();
271 inv = bt.before(at);
272 if (inv) {
273 firstWp = b;
274 firstTime = bt;
275 lastWp = a;
276 lastTime = at;
277 } else {
278 firstWp = a;
279 firstTime = at;
280 lastWp = b;
281 lastTime = bt;
282 }
283 }
284
285 public WayPoint getFirstWp() {
286 return new WayPoint(firstWp);
287 }
288
289 public WayPoint getLastWp() {
290 return new WayPoint(lastWp);
291 }
292
293 // no new instances needed, therefore own methods for that
294
295 public boolean firstEquals(Object other) {
296 return firstWp.equals(other);
297 }
298
299 public boolean lastEquals(Object other) {
300 return lastWp.equals(other);
301 }
302
303 public boolean isInverted() {
304 return inv;
305 }
306
307 public boolean overlapsWith(GpxTrackSegmentSpan other) {
308 return (firstTime.before(other.lastTime) && other.firstTime.before(lastTime))
309 || (other.firstTime.before(lastTime) && firstTime.before(other.lastTime));
310 }
311
312 public static GpxTrackSegmentSpan tryGetFromSegment(GpxTrackSegment seg) {
313 WayPoint b = getNextWpWithTime(seg, true);
314 if (b != null) {
315 WayPoint e = getNextWpWithTime(seg, false);
316 if (e != null) {
317 return new GpxTrackSegmentSpan(b, e);
318 }
319 }
320 return null;
321 }
322
323 private static WayPoint getNextWpWithTime(GpxTrackSegment seg, boolean forward) {
324 List<WayPoint> wps = new ArrayList<>(seg.getWayPoints());
325 for (int i = forward ? 0 : wps.size() - 1; i >= 0 && i < wps.size(); i += forward ? 1 : -1) {
326 if (wps.get(i).setTimeFromAttribute() != null) {
327 return wps.get(i);
328 }
329 }
330 return null;
331 }
332 }
333
334 /**
335 * Get a list of SegmentSpans containing the beginning and end of each segment
336 * @return the list of SegmentSpans
337 * @since 14338
338 */
339 public synchronized List<GpxTrackSegmentSpan> getSegmentSpans() {
340 if (segSpans == null) {
341 segSpans = new ArrayList<>();
342 for (GpxTrack trk : privateTracks) {
343 for (GpxTrackSegment seg : trk.getSegments()) {
344 GpxTrackSegmentSpan s = GpxTrackSegmentSpan.tryGetFromSegment(seg);
345 if (s != null) {
346 segSpans.add(s);
347 }
348 }
349 }
350 segSpans.sort((o1, o2) -> {
351 return o1.firstTime.compareTo(o2.firstTime);
352 });
353 }
354 return segSpans;
355 }
356
357 private boolean anySegmentOverlapsWith(GpxTrackSegmentSpan other) {
358 for (GpxTrackSegmentSpan s : getSegmentSpans()) {
359 if (s.overlapsWith(other)) {
360 return true;
361 }
362 }
363 return false;
364 }
365
366 /**
367 * Get all tracks contained in this data set.
368 * @return The tracks.
369 */
370 public synchronized Collection<GpxTrack> getTracks() {
371 return Collections.unmodifiableCollection(privateTracks);
372 }
373
374 /**
375 * Get stream of track segments.
376 * @return {@code Stream<GPXTrack>}
377 */
378 private synchronized Stream<GpxTrackSegment> getTrackSegmentsStream() {
379 return getTracks().stream().flatMap(trk -> trk.getSegments().stream());
380 }
381
382 /**
383 * Clear all tracks, empties the current privateTracks container,
384 * helper method for some gpx manipulations.
385 */
386 private synchronized void clearTracks() {
387 privateTracks.forEach(t -> t.removeListener(proxy));
388 privateTracks.clear();
389 }
390
391 /**
392 * Add a new track
393 * @param track The new track
394 * @since 12156
395 */
396 public synchronized void addTrack(GpxTrack track) {
397 if (privateTracks.stream().anyMatch(t -> t == track)) {
398 throw new IllegalArgumentException(MessageFormat.format("The track was already added to this data: {0}", track));
399 }
400 privateTracks.add(track);
401 track.addListener(proxy);
402 fireInvalidate();
403 }
404
405 /**
406 * Remove a track
407 * @param track The old track
408 * @since 12156
409 */
410 public synchronized void removeTrack(GpxTrack track) {
411 if (!privateTracks.removeIf(t -> t == track)) {
412 throw new IllegalArgumentException(MessageFormat.format("The track was not in this data: {0}", track));
413 }
414 track.removeListener(proxy);
415 fireInvalidate();
416 }
417
418 /**
419 * Combine tracks into a single, segmented track.
420 * The attributes of the first track are used, the rest discarded.
421 *
422 * @since 13210
423 */
424 public synchronized void combineTracksToSegmentedTrack() {
425 List<GpxTrackSegment> segs = getTrackSegmentsStream()
426 .collect(Collectors.toCollection(ArrayList<GpxTrackSegment>::new));
427 Map<String, Object> attrs = new HashMap<>(privateTracks.get(0).getAttributes());
428
429 // do not let the name grow if split / combine operations are called iteratively
430 attrs.put("name", attrs.get("name").toString().replaceFirst(" #\\d+$", ""));
431
432 clearTracks();
433 addTrack(new ImmutableGpxTrack(segs, attrs));
434 }
435
436 /**
437 * @param attrs attributes of/for an gpx track, written to if the name appeared previously in {@code counts}.
438 * @param counts a {@code HashMap} of previously seen names, associated with their count.
439 * @return the unique name for the gpx track.
440 *
441 * @since 13210
442 */
443 public static String ensureUniqueName(Map<String, Object> attrs, Map<String, Integer> counts) {
444 String name = attrs.getOrDefault("name", "GPX split result").toString();
445 Integer count = counts.getOrDefault(name, 0) + 1;
446 counts.put(name, count);
447
448 attrs.put("name", MessageFormat.format("{0}{1}", name, (count > 1) ? " #"+count : ""));
449 return attrs.get("name").toString();
450 }
451
452 /**
453 * Split tracks so that only single-segment tracks remain.
454 * Each segment will make up one individual track after this operation.
455 *
456 * @since 13210
457 */
458 public synchronized void splitTrackSegmentsToTracks() {
459 final HashMap<String, Integer> counts = new HashMap<>();
460
461 List<GpxTrack> trks = getTracks().stream()
462 .flatMap(trk -> {
463 return trk.getSegments().stream().map(seg -> {
464 HashMap<String, Object> attrs = new HashMap<>(trk.getAttributes());
465 ensureUniqueName(attrs, counts);
466 return new ImmutableGpxTrack(Arrays.asList(seg), attrs);
467 });
468 })
469 .collect(Collectors.toCollection(ArrayList<GpxTrack>::new));
470
471 clearTracks();
472 trks.stream().forEachOrdered(this::addTrack);
473 }
474
475 /**
476 * Split tracks into layers, the result is one layer for each track.
477 * If this layer currently has only one GpxTrack this is a no-operation.
478 *
479 * The new GpxLayers are added to the LayerManager, the original GpxLayer
480 * is untouched as to preserve potential route or wpt parts.
481 *
482 * @since 13210
483 */
484 public synchronized void splitTracksToLayers() {
485 final HashMap<String, Integer> counts = new HashMap<>();
486
487 getTracks().stream()
488 .filter(trk -> privateTracks.size() > 1)
489 .map(trk -> {
490 HashMap<String, Object> attrs = new HashMap<>(trk.getAttributes());
491 GpxData d = new GpxData();
492 d.addTrack(trk);
493 return new GpxLayer(d, ensureUniqueName(attrs, counts)); })
494 .forEachOrdered(layer -> MainApplication.getLayerManager().addLayer(layer));
495 }
496
497 /**
498 * Replies the current number of tracks in this GpxData
499 * @return track count
500 * @since 13210
501 */
502 public synchronized int getTrackCount() {
503 return privateTracks.size();
504 }
505
506 /**
507 * Replies the accumulated total of all track segments,
508 * the sum of segment counts for each track present.
509 * @return track segments count
510 * @since 13210
511 */
512 public synchronized int getTrackSegsCount() {
513 return privateTracks.stream().collect(Collectors.summingInt(t -> t.getSegments().size()));
514 }
515
516 /**
517 * Gets the list of all routes defined in this data set.
518 * @return The routes
519 * @since 12156
520 */
521 public synchronized Collection<GpxRoute> getRoutes() {
522 return Collections.unmodifiableCollection(privateRoutes);
523 }
524
525 /**
526 * Add a new route
527 * @param route The new route
528 * @since 12156
529 */
530 public synchronized void addRoute(GpxRoute route) {
531 if (privateRoutes.stream().anyMatch(r -> r == route)) {
532 throw new IllegalArgumentException(MessageFormat.format("The route was already added to this data: {0}", route));
533 }
534 privateRoutes.add(route);
535 fireInvalidate();
536 }
537
538 /**
539 * Remove a route
540 * @param route The old route
541 * @since 12156
542 */
543 public synchronized void removeRoute(GpxRoute route) {
544 if (!privateRoutes.removeIf(r -> r == route)) {
545 throw new IllegalArgumentException(MessageFormat.format("The route was not in this data: {0}", route));
546 }
547 fireInvalidate();
548 }
549
550 /**
551 * Gets a list of all way points in this data set.
552 * @return The way points.
553 * @since 12156
554 */
555 public synchronized Collection<WayPoint> getWaypoints() {
556 return Collections.unmodifiableCollection(privateWaypoints);
557 }
558
559 /**
560 * Add a new waypoint
561 * @param waypoint The new waypoint
562 * @since 12156
563 */
564 public synchronized void addWaypoint(WayPoint waypoint) {
565 if (privateWaypoints.stream().anyMatch(w -> w == waypoint)) {
566 throw new IllegalArgumentException(MessageFormat.format("The route was already added to this data: {0}", waypoint));
567 }
568 privateWaypoints.add(waypoint);
569 fireInvalidate();
570 }
571
572 /**
573 * Remove a waypoint
574 * @param waypoint The old waypoint
575 * @since 12156
576 */
577 public synchronized void removeWaypoint(WayPoint waypoint) {
578 if (!privateWaypoints.removeIf(w -> w == waypoint)) {
579 throw new IllegalArgumentException(MessageFormat.format("The route was not in this data: {0}", waypoint));
580 }
581 fireInvalidate();
582 }
583
584 /**
585 * Determines if this GPX data has one or more track points
586 * @return {@code true} if this GPX data has track points, {@code false} otherwise
587 */
588 public synchronized boolean hasTrackPoints() {
589 return getTrackPoints().findAny().isPresent();
590 }
591
592 /**
593 * Gets a stream of all track points in the segments of the tracks of this data.
594 * @return The stream
595 * @see #getTracks()
596 * @see GpxTrack#getSegments()
597 * @see GpxTrackSegment#getWayPoints()
598 * @since 12156
599 */
600 public synchronized Stream<WayPoint> getTrackPoints() {
601 return getTracks().stream().flatMap(trk -> trk.getSegments().stream()).flatMap(trkseg -> trkseg.getWayPoints().stream());
602 }
603
604 /**
605 * Determines if this GPX data has one or more route points
606 * @return {@code true} if this GPX data has route points, {@code false} otherwise
607 */
608 public synchronized boolean hasRoutePoints() {
609 return privateRoutes.stream().anyMatch(rte -> !rte.routePoints.isEmpty());
610 }
611
612 /**
613 * Determines if this GPX data is empty (i.e. does not contain any point)
614 * @return {@code true} if this GPX data is empty, {@code false} otherwise
615 */
616 public synchronized boolean isEmpty() {
617 return !hasRoutePoints() && !hasTrackPoints() && waypoints.isEmpty();
618 }
619
620 /**
621 * Returns the bounds defining the extend of this data, as read in metadata, if any.
622 * If no bounds is defined in metadata, {@code null} is returned. There is no guarantee
623 * that data entirely fit in this bounds, as it is not recalculated. To get recalculated bounds,
624 * see {@link #recalculateBounds()}. To get downloaded areas, see {@link #dataSources}.
625 * @return the bounds defining the extend of this data, or {@code null}.
626 * @see #recalculateBounds()
627 * @see #dataSources
628 * @since 7575
629 */
630 public Bounds getMetaBounds() {
631 Object value = get(META_BOUNDS);
632 if (value instanceof Bounds) {
633 return (Bounds) value;
634 }
635 return null;
636 }
637
638 /**
639 * Calculates the bounding box of available data and returns it.
640 * The bounds are not stored internally, but recalculated every time
641 * this function is called.<br>
642 * To get bounds as read from metadata, see {@link #getMetaBounds()}.<br>
643 * To get downloaded areas, see {@link #dataSources}.<br>
644 *
645 * FIXME might perhaps use visitor pattern?
646 * @return the bounds
647 * @see #getMetaBounds()
648 * @see #dataSources
649 */
650 public synchronized Bounds recalculateBounds() {
651 Bounds bounds = null;
652 for (WayPoint wpt : privateWaypoints) {
653 if (bounds == null) {
654 bounds = new Bounds(wpt.getCoor());
655 } else {
656 bounds.extend(wpt.getCoor());
657 }
658 }
659 for (GpxRoute rte : privateRoutes) {
660 for (WayPoint wpt : rte.routePoints) {
661 if (bounds == null) {
662 bounds = new Bounds(wpt.getCoor());
663 } else {
664 bounds.extend(wpt.getCoor());
665 }
666 }
667 }
668 for (GpxTrack trk : privateTracks) {
669 Bounds trkBounds = trk.getBounds();
670 if (trkBounds != null) {
671 if (bounds == null) {
672 bounds = new Bounds(trkBounds);
673 } else {
674 bounds.extend(trkBounds);
675 }
676 }
677 }
678 return bounds;
679 }
680
681 /**
682 * calculates the sum of the lengths of all track segments
683 * @return the length in meters
684 */
685 public synchronized double length() {
686 return privateTracks.stream().mapToDouble(GpxTrack::length).sum();
687 }
688
689 /**
690 * returns minimum and maximum timestamps in the track
691 * @param trk track to analyze
692 * @return minimum and maximum dates in array of 2 elements
693 */
694 public static Date[] getMinMaxTimeForTrack(GpxTrack trk) {
695 final DoubleSummaryStatistics statistics = trk.getSegments().stream()
696 .flatMap(seg -> seg.getWayPoints().stream())
697 .mapToDouble(pnt -> pnt.time)
698 .summaryStatistics();
699 return statistics.getCount() == 0
700 ? null
701 : new Date[]{new Date((long) (statistics.getMin() * 1000)), new Date((long) (statistics.getMax() * 1000))};
702 }
703
704 /**
705 * Returns minimum and maximum timestamps for all tracks
706 * Warning: there are lot of track with broken timestamps,
707 * so we just ingore points from future and from year before 1970 in this method
708 * works correctly @since 5815
709 * @return minimum and maximum dates in array of 2 elements
710 */
711 public synchronized Date[] getMinMaxTimeForAllTracks() {
712 double now = System.currentTimeMillis() / 1000.0;
713 final DoubleSummaryStatistics statistics = tracks.stream()
714 .flatMap(trk -> trk.getSegments().stream())
715 .flatMap(seg -> seg.getWayPoints().stream())
716 .mapToDouble(pnt -> pnt.time)
717 .filter(t -> t > 0 && t <= now)
718 .summaryStatistics();
719 return statistics.getCount() == 0
720 ? new Date[0]
721 : new Date[]{new Date((long) (statistics.getMin() * 1000)), new Date((long) (statistics.getMax() * 1000))};
722 }
723
724 /**
725 * Makes a WayPoint at the projection of point p onto the track providing p is less than
726 * tolerance away from the track
727 *
728 * @param p : the point to determine the projection for
729 * @param tolerance : must be no further than this from the track
730 * @return the closest point on the track to p, which may be the first or last point if off the
731 * end of a segment, or may be null if nothing close enough
732 */
733 public synchronized WayPoint nearestPointOnTrack(EastNorth p, double tolerance) {
734 /*
735 * assume the coordinates of P are xp,yp, and those of a section of track between two
736 * trackpoints are R=xr,yr and S=xs,ys. Let N be the projected point.
737 *
738 * The equation of RS is Ax + By + C = 0 where A = ys - yr B = xr - xs C = - Axr - Byr
739 *
740 * Also, note that the distance RS^2 is A^2 + B^2
741 *
742 * If RS^2 == 0.0 ignore the degenerate section of track
743 *
744 * PN^2 = (Axp + Byp + C)^2 / RS^2 that is the distance from P to the line
745 *
746 * so if PN^2 is less than PNmin^2 (initialized to tolerance) we can reject the line
747 * otherwise... determine if the projected poijnt lies within the bounds of the line: PR^2 -
748 * PN^2 <= RS^2 and PS^2 - PN^2 <= RS^2
749 *
750 * where PR^2 = (xp - xr)^2 + (yp-yr)^2 and PS^2 = (xp - xs)^2 + (yp-ys)^2
751 *
752 * If so, calculate N as xn = xr + (RN/RS) B yn = y1 + (RN/RS) A
753 *
754 * where RN = sqrt(PR^2 - PN^2)
755 */
756
757 double pnminsq = tolerance * tolerance;
758 EastNorth bestEN = null;
759 double bestTime = 0.0;
760 double px = p.east();
761 double py = p.north();
762 double rx = 0.0, ry = 0.0, sx, sy, x, y;
763 for (GpxTrack track : privateTracks) {
764 for (GpxTrackSegment seg : track.getSegments()) {
765 WayPoint r = null;
766 for (WayPoint wpSeg : seg.getWayPoints()) {
767 EastNorth en = wpSeg.getEastNorth(ProjectionRegistry.getProjection());
768 if (r == null) {
769 r = wpSeg;
770 rx = en.east();
771 ry = en.north();
772 x = px - rx;
773 y = py - ry;
774 double pRsq = x * x + y * y;
775 if (pRsq < pnminsq) {
776 pnminsq = pRsq;
777 bestEN = en;
778 bestTime = r.time;
779 }
780 } else {
781 sx = en.east();
782 sy = en.north();
783 double a = sy - ry;
784 double b = rx - sx;
785 double c = -a * rx - b * ry;
786 double rssq = a * a + b * b;
787 if (rssq == 0) {
788 continue;
789 }
790 double pnsq = a * px + b * py + c;
791 pnsq = pnsq * pnsq / rssq;
792 if (pnsq < pnminsq) {
793 x = px - rx;
794 y = py - ry;
795 double prsq = x * x + y * y;
796 x = px - sx;
797 y = py - sy;
798 double pssq = x * x + y * y;
799 if (prsq - pnsq <= rssq && pssq - pnsq <= rssq) {
800 double rnoverRS = Math.sqrt((prsq - pnsq) / rssq);
801 double nx = rx - rnoverRS * b;
802 double ny = ry + rnoverRS * a;
803 bestEN = new EastNorth(nx, ny);
804 bestTime = r.time + rnoverRS * (wpSeg.time - r.time);
805 pnminsq = pnsq;
806 }
807 }
808 r = wpSeg;
809 rx = sx;
810 ry = sy;
811 }
812 }
813 if (r != null) {
814 EastNorth c = r.getEastNorth(ProjectionRegistry.getProjection());
815 /* if there is only one point in the seg, it will do this twice, but no matter */
816 rx = c.east();
817 ry = c.north();
818 x = px - rx;
819 y = py - ry;
820 double prsq = x * x + y * y;
821 if (prsq < pnminsq) {
822 pnminsq = prsq;
823 bestEN = c;
824 bestTime = r.time;
825 }
826 }
827 }
828 }
829 if (bestEN == null)
830 return null;
831 WayPoint best = new WayPoint(ProjectionRegistry.getProjection().eastNorth2latlon(bestEN));
832 best.time = bestTime;
833 return best;
834 }
835
836 /**
837 * Iterate over all track segments and over all routes.
838 *
839 * @param trackVisibility An array indicating which tracks should be
840 * included in the iteration. Can be null, then all tracks are included.
841 * @return an Iterable object, which iterates over all track segments and
842 * over all routes
843 */
844 public Iterable<Collection<WayPoint>> getLinesIterable(final boolean... trackVisibility) {
845 return () -> new LinesIterator(this, trackVisibility);
846 }
847
848 /**
849 * Resets the internal caches of east/north coordinates.
850 */
851 public synchronized void resetEastNorthCache() {
852 privateWaypoints.forEach(WayPoint::invalidateEastNorthCache);
853 getTrackPoints().forEach(WayPoint::invalidateEastNorthCache);
854 for (GpxRoute route: getRoutes()) {
855 if (route.routePoints == null) {
856 continue;
857 }
858 for (WayPoint wp: route.routePoints) {
859 wp.invalidateEastNorthCache();
860 }
861 }
862 }
863
864 /**
865 * Iterates over all track segments and then over all routes.
866 */
867 public static class LinesIterator implements Iterator<Collection<WayPoint>> {
868
869 private Iterator<GpxTrack> itTracks;
870 private int idxTracks;
871 private Iterator<GpxTrackSegment> itTrackSegments;
872 private final Iterator<GpxRoute> itRoutes;
873
874 private Collection<WayPoint> next;
875 private final boolean[] trackVisibility;
876
877 /**
878 * Constructs a new {@code LinesIterator}.
879 * @param data GPX data
880 * @param trackVisibility An array indicating which tracks should be
881 * included in the iteration. Can be null, then all tracks are included.
882 */
883 public LinesIterator(GpxData data, boolean... trackVisibility) {
884 itTracks = data.tracks.iterator();
885 idxTracks = -1;
886 itRoutes = data.routes.iterator();
887 this.trackVisibility = trackVisibility;
888 next = getNext();
889 }
890
891 @Override
892 public boolean hasNext() {
893 return next != null;
894 }
895
896 @Override
897 public Collection<WayPoint> next() {
898 if (!hasNext()) {
899 throw new NoSuchElementException();
900 }
901 Collection<WayPoint> current = next;
902 next = getNext();
903 return current;
904 }
905
906 private Collection<WayPoint> getNext() {
907 if (itTracks != null) {
908 if (itTrackSegments != null && itTrackSegments.hasNext()) {
909 return itTrackSegments.next().getWayPoints();
910 } else {
911 while (itTracks.hasNext()) {
912 GpxTrack nxtTrack = itTracks.next();
913 idxTracks++;
914 if (trackVisibility != null && !trackVisibility[idxTracks])
915 continue;
916 itTrackSegments = nxtTrack.getSegments().iterator();
917 if (itTrackSegments.hasNext()) {
918 return itTrackSegments.next().getWayPoints();
919 }
920 }
921 // if we get here, all the Tracks are finished; Continue with Routes
922 itTracks = null;
923 }
924 }
925 if (itRoutes.hasNext()) {
926 return itRoutes.next().routePoints;
927 }
928 return null;
929 }
930
931 @Override
932 public void remove() {
933 throw new UnsupportedOperationException();
934 }
935 }
936
937 @Override
938 public Collection<DataSource> getDataSources() {
939 return Collections.unmodifiableCollection(dataSources);
940 }
941
942 @Override
943 public synchronized int hashCode() {
944 final int prime = 31;
945 int result = 1;
946 result = prime * result + ((dataSources == null) ? 0 : dataSources.hashCode());
947 result = prime * result + ((privateRoutes == null) ? 0 : privateRoutes.hashCode());
948 result = prime * result + ((privateTracks == null) ? 0 : privateTracks.hashCode());
949 result = prime * result + ((privateWaypoints == null) ? 0 : privateWaypoints.hashCode());
950 return result;
951 }
952
953 @Override
954 public synchronized boolean equals(Object obj) {
955 if (this == obj)
956 return true;
957 if (obj == null)
958 return false;
959 if (getClass() != obj.getClass())
960 return false;
961 GpxData other = (GpxData) obj;
962 if (dataSources == null) {
963 if (other.dataSources != null)
964 return false;
965 } else if (!dataSources.equals(other.dataSources))
966 return false;
967 if (privateRoutes == null) {
968 if (other.privateRoutes != null)
969 return false;
970 } else if (!privateRoutes.equals(other.privateRoutes))
971 return false;
972 if (privateTracks == null) {
973 if (other.privateTracks != null)
974 return false;
975 } else if (!privateTracks.equals(other.privateTracks))
976 return false;
977 if (privateWaypoints == null) {
978 if (other.privateWaypoints != null)
979 return false;
980 } else if (!privateWaypoints.equals(other.privateWaypoints))
981 return false;
982 return true;
983 }
984
985 /**
986 * Adds a listener that gets called whenever the data changed.
987 * @param listener The listener
988 * @since 12156
989 */
990 public void addChangeListener(GpxDataChangeListener listener) {
991 listeners.addListener(listener);
992 }
993
994 /**
995 * Adds a listener that gets called whenever the data changed. It is added with a weak link
996 * @param listener The listener
997 */
998 public void addWeakChangeListener(GpxDataChangeListener listener) {
999 listeners.addWeakListener(listener);
1000 }
1001
1002 /**
1003 * Removes a listener that gets called whenever the data changed.
1004 * @param listener The listener
1005 * @since 12156
1006 */
1007 public void removeChangeListener(GpxDataChangeListener listener) {
1008 listeners.removeListener(listener);
1009 }
1010
1011 private void fireInvalidate() {
1012 if (listeners.hasListeners()) {
1013 GpxDataChangeEvent e = new GpxDataChangeEvent(this);
1014 listeners.fireEvent(l -> l.gpxDataChanged(e));
1015 }
1016 }
1017
1018 /**
1019 * A listener that listens to GPX data changes.
1020 * @author Michael Zangl
1021 * @since 12156
1022 */
1023 @FunctionalInterface
1024 public interface GpxDataChangeListener {
1025 /**
1026 * Called when the gpx data changed.
1027 * @param e The event
1028 */
1029 void gpxDataChanged(GpxDataChangeEvent e);
1030 }
1031
1032 /**
1033 * A data change event in any of the gpx data.
1034 * @author Michael Zangl
1035 * @since 12156
1036 */
1037 public static class GpxDataChangeEvent {
1038 private final GpxData source;
1039
1040 GpxDataChangeEvent(GpxData source) {
1041 super();
1042 this.source = source;
1043 }
1044
1045 /**
1046 * Get the data that was changed.
1047 * @return The data.
1048 */
1049 public GpxData getSource() {
1050 return source;
1051 }
1052 }
1053}
Note: See TracBrowser for help on using the repository browser.