source: josm/trunk/src/org/openstreetmap/josm/gui/NavigatableComponent.java@ 3642

Last change on this file since 3642 was 3642, checked in by bastiK, 13 years ago

fixed #5561 (patch by cmuelle8) - wrong node selected after "unglue way"

  • Property svn:eol-style set to native
File size: 43.0 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5
6import java.awt.Point;
7import java.awt.Rectangle;
8import java.awt.geom.Point2D;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.Date;
13import java.util.HashSet;
14import java.util.LinkedHashMap;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Locale;
18import java.util.Map;
19import java.util.Set;
20import java.util.Stack;
21import java.util.TreeMap;
22import java.util.concurrent.CopyOnWriteArrayList;
23
24import javax.swing.JComponent;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.data.Bounds;
28import org.openstreetmap.josm.data.ProjectionBounds;
29import org.openstreetmap.josm.data.coor.CachedLatLon;
30import org.openstreetmap.josm.data.coor.EastNorth;
31import org.openstreetmap.josm.data.coor.LatLon;
32import org.openstreetmap.josm.data.osm.BBox;
33import org.openstreetmap.josm.data.osm.DataSet;
34import org.openstreetmap.josm.data.osm.Node;
35import org.openstreetmap.josm.data.osm.OsmPrimitive;
36import org.openstreetmap.josm.data.osm.Way;
37import org.openstreetmap.josm.data.osm.WaySegment;
38import org.openstreetmap.josm.data.preferences.IntegerProperty;
39import org.openstreetmap.josm.data.projection.Projection;
40import org.openstreetmap.josm.gui.help.Helpful;
41import org.openstreetmap.josm.gui.preferences.ProjectionPreference;
42import org.openstreetmap.josm.tools.Predicate;
43
44/**
45 * An component that can be navigated by a mapmover. Used as map view and for the
46 * zoomer in the download dialog.
47 *
48 * @author imi
49 */
50public class NavigatableComponent extends JComponent implements Helpful {
51
52 /**
53 * Interface to notify listeners of the change of the zoom area.
54 */
55 public interface ZoomChangeListener {
56 void zoomChanged();
57 }
58
59 public static final IntegerProperty PROP_SNAP_DISTANCE = new IntegerProperty("mappaint.node.snap-distance", 10);
60
61 /**
62 * the zoom listeners
63 */
64 private static final CopyOnWriteArrayList<ZoomChangeListener> zoomChangeListeners = new CopyOnWriteArrayList<ZoomChangeListener>();
65
66 /**
67 * Removes a zoom change listener
68 *
69 * @param listener the listener. Ignored if null or already absent
70 */
71 public static void removeZoomChangeListener(NavigatableComponent.ZoomChangeListener listener) {
72 zoomChangeListeners.remove(listener);
73 }
74
75 /**
76 * Adds a zoom change listener
77 *
78 * @param listener the listener. Ignored if null or already registered.
79 */
80 public static void addZoomChangeListener(NavigatableComponent.ZoomChangeListener listener) {
81 if (listener != null) {
82 zoomChangeListeners.addIfAbsent(listener);
83 }
84 }
85
86 protected static void fireZoomChanged() {
87 for (ZoomChangeListener l : zoomChangeListeners) {
88 l.zoomChanged();
89 }
90 }
91
92 /**
93 * The scale factor in x or y-units per pixel. This means, if scale = 10,
94 * every physical pixel on screen are 10 x or 10 y units in the
95 * northing/easting space of the projection.
96 */
97 private double scale = Main.proj.getDefaultZoomInPPD();
98 /**
99 * Center n/e coordinate of the desired screen center.
100 */
101 protected EastNorth center = calculateDefaultCenter();
102
103 public NavigatableComponent() {
104 setLayout(null);
105 }
106
107 protected DataSet getCurrentDataSet() {
108 return Main.main.getCurrentDataSet();
109 }
110
111 private EastNorth calculateDefaultCenter() {
112 Bounds b = Main.proj.getWorldBoundsLatLon();
113 double lat = (b.getMax().lat() + b.getMin().lat())/2;
114 double lon = (b.getMax().lon() + b.getMin().lon())/2;
115
116 return Main.proj.latlon2eastNorth(new LatLon(lat, lon));
117 }
118
119 public static String getDistText(double dist) {
120 return getSystemOfMeasurement().getDistText(dist);
121 }
122
123 public String getDist100PixelText()
124 {
125 return getDistText(getDist100Pixel());
126 }
127
128 public double getDist100Pixel()
129 {
130 int w = getWidth()/2;
131 int h = getHeight()/2;
132 LatLon ll1 = getLatLon(w-50,h);
133 LatLon ll2 = getLatLon(w+50,h);
134 return ll1.greatCircleDistance(ll2);
135 }
136
137 /**
138 * @return Returns the center point. A copy is returned, so users cannot
139 * change the center by accessing the return value. Use zoomTo instead.
140 */
141 public EastNorth getCenter() {
142 return center;
143 }
144
145 /**
146 * @param x X-Pixelposition to get coordinate from
147 * @param y Y-Pixelposition to get coordinate from
148 *
149 * @return Geographic coordinates from a specific pixel coordination
150 * on the screen.
151 */
152 public EastNorth getEastNorth(int x, int y) {
153 return new EastNorth(
154 center.east() + (x - getWidth()/2.0)*scale,
155 center.north() - (y - getHeight()/2.0)*scale);
156 }
157
158 public ProjectionBounds getProjectionBounds() {
159 return new ProjectionBounds(
160 new EastNorth(
161 center.east() - getWidth()/2.0*scale,
162 center.north() - getHeight()/2.0*scale),
163 new EastNorth(
164 center.east() + getWidth()/2.0*scale,
165 center.north() + getHeight()/2.0*scale));
166 }
167
168 /* FIXME: replace with better method - used by MapSlider */
169 public ProjectionBounds getMaxProjectionBounds() {
170 Bounds b = getProjection().getWorldBoundsLatLon();
171 return new ProjectionBounds(getProjection().latlon2eastNorth(b.getMin()),
172 getProjection().latlon2eastNorth(b.getMax()));
173 }
174
175 /* FIXME: replace with better method - used by Main to reset Bounds when projection changes, don't use otherwise */
176 public Bounds getRealBounds() {
177 return new Bounds(
178 getProjection().eastNorth2latlon(new EastNorth(
179 center.east() - getWidth()/2.0*scale,
180 center.north() - getHeight()/2.0*scale)),
181 getProjection().eastNorth2latlon(new EastNorth(
182 center.east() + getWidth()/2.0*scale,
183 center.north() + getHeight()/2.0*scale)));
184 }
185
186 /**
187 * @param x X-Pixelposition to get coordinate from
188 * @param y Y-Pixelposition to get coordinate from
189 *
190 * @return Geographic unprojected coordinates from a specific pixel coordination
191 * on the screen.
192 */
193 public LatLon getLatLon(int x, int y) {
194 return getProjection().eastNorth2latlon(getEastNorth(x, y));
195 }
196
197 public LatLon getLatLon(double x, double y) {
198 return getLatLon((int)x, (int)y);
199 }
200
201 /**
202 * @param r
203 * @return Minimum bounds that will cover rectangle
204 */
205 public Bounds getLatLonBounds(Rectangle r) {
206 // TODO Maybe this should be (optional) method of Projection implementation
207 EastNorth p1 = getEastNorth(r.x, r.y);
208 EastNorth p2 = getEastNorth(r.x + r.width, r.y + r.height);
209
210 Bounds result = new Bounds(Main.proj.eastNorth2latlon(p1));
211
212 double eastMin = Math.min(p1.east(), p2.east());
213 double eastMax = Math.max(p1.east(), p2.east());
214 double northMin = Math.min(p1.north(), p2.north());
215 double northMax = Math.max(p1.north(), p2.north());
216 double deltaEast = (eastMax - eastMin) / 10;
217 double deltaNorth = (northMax - northMin) / 10;
218
219 for (int i=0; i < 10; i++) {
220 result.extend(Main.proj.eastNorth2latlon(new EastNorth(eastMin + i * deltaEast, northMin)));
221 result.extend(Main.proj.eastNorth2latlon(new EastNorth(eastMin + i * deltaEast, northMax)));
222 result.extend(Main.proj.eastNorth2latlon(new EastNorth(eastMin, northMin + i * deltaNorth)));
223 result.extend(Main.proj.eastNorth2latlon(new EastNorth(eastMax, northMin + i * deltaNorth)));
224 }
225
226 return result;
227 }
228
229 /**
230 * Return the point on the screen where this Coordinate would be.
231 * @param p The point, where this geopoint would be drawn.
232 * @return The point on screen where "point" would be drawn, relative
233 * to the own top/left.
234 */
235 public Point2D getPoint2D(EastNorth p) {
236 if (null == p)
237 return new Point();
238 double x = (p.east()-center.east())/scale + getWidth()/2;
239 double y = (center.north()-p.north())/scale + getHeight()/2;
240 return new Point2D.Double(x, y);
241 }
242
243 public Point2D getPoint2D(LatLon latlon) {
244 if (latlon == null)
245 return new Point();
246 else if (latlon instanceof CachedLatLon)
247 return getPoint2D(((CachedLatLon)latlon).getEastNorth());
248 else
249 return getPoint2D(getProjection().latlon2eastNorth(latlon));
250 }
251 public Point2D getPoint2D(Node n) {
252 return getPoint2D(n.getEastNorth());
253 }
254
255 // looses precision, may overflow (depends on p and current scale)
256 //@Deprecated
257 public Point getPoint(EastNorth p) {
258 Point2D d = getPoint2D(p);
259 return new Point((int) d.getX(), (int) d.getY());
260 }
261
262 // looses precision, may overflow (depends on p and current scale)
263 //@Deprecated
264 public Point getPoint(LatLon latlon) {
265 Point2D d = getPoint2D(latlon);
266 return new Point((int) d.getX(), (int) d.getY());
267 }
268
269 // looses precision, may overflow (depends on p and current scale)
270 //@Deprecated
271 public Point getPoint(Node n) {
272 Point2D d = getPoint2D(n);
273 return new Point((int) d.getX(), (int) d.getY());
274 }
275
276 /**
277 * Zoom to the given coordinate.
278 * @param newCenter The center x-value (easting) to zoom to.
279 * @param scale The scale to use.
280 */
281 private void zoomTo(EastNorth newCenter, double newScale) {
282 Bounds b = getProjection().getWorldBoundsLatLon();
283 CachedLatLon cl = new CachedLatLon(newCenter);
284 boolean changed = false;
285 double lat = cl.lat();
286 double lon = cl.lon();
287 if(lat < b.getMin().lat()) {changed = true; lat = b.getMin().lat(); }
288 else if(lat > b.getMax().lat()) {changed = true; lat = b.getMax().lat(); }
289 if(lon < b.getMin().lon()) {changed = true; lon = b.getMin().lon(); }
290 else if(lon > b.getMax().lon()) {changed = true; lon = b.getMax().lon(); }
291 if(changed) {
292 newCenter = new CachedLatLon(lat, lon).getEastNorth();
293 }
294 int width = getWidth()/2;
295 int height = getHeight()/2;
296 LatLon l1 = new LatLon(b.getMin().lat(), lon);
297 LatLon l2 = new LatLon(b.getMax().lat(), lon);
298 EastNorth e1 = getProjection().latlon2eastNorth(l1);
299 EastNorth e2 = getProjection().latlon2eastNorth(l2);
300 double d = e2.north() - e1.north();
301 if(d < height*newScale)
302 {
303 double newScaleH = d/height;
304 e1 = getProjection().latlon2eastNorth(new LatLon(lat, b.getMin().lon()));
305 e2 = getProjection().latlon2eastNorth(new LatLon(lat, b.getMax().lon()));
306 d = e2.east() - e1.east();
307 if(d < width*newScale) {
308 newScale = Math.max(newScaleH, d/width);
309 }
310 }
311 else
312 {
313 d = d/(l1.greatCircleDistance(l2)*height*10);
314 if(newScale < d) {
315 newScale = d;
316 }
317 }
318
319 if (!newCenter.equals(center) || (scale != newScale)) {
320 pushZoomUndo(center, scale);
321 zoomNoUndoTo(newCenter, newScale);
322 }
323 }
324
325 /**
326 * Zoom to the given coordinate without adding to the zoom undo buffer.
327 * @param newCenter The center x-value (easting) to zoom to.
328 * @param scale The scale to use.
329 */
330 private void zoomNoUndoTo(EastNorth newCenter, double newScale) {
331 if (!newCenter.equals(center)) {
332 EastNorth oldCenter = center;
333 center = newCenter;
334 firePropertyChange("center", oldCenter, newCenter);
335 }
336 if (scale != newScale) {
337 double oldScale = scale;
338 scale = newScale;
339 firePropertyChange("scale", oldScale, newScale);
340 }
341
342 repaint();
343 fireZoomChanged();
344 }
345
346 public void zoomTo(EastNorth newCenter) {
347 zoomTo(newCenter, scale);
348 }
349
350 public void zoomTo(LatLon newCenter) {
351 if(newCenter instanceof CachedLatLon) {
352 zoomTo(((CachedLatLon)newCenter).getEastNorth(), scale);
353 } else {
354 zoomTo(getProjection().latlon2eastNorth(newCenter), scale);
355 }
356 }
357
358 public void zoomToFactor(double x, double y, double factor) {
359 double newScale = scale*factor;
360 // New center position so that point under the mouse pointer stays the same place as it was before zooming
361 // You will get the formula by simplifying this expression: newCenter = oldCenter + mouseCoordinatesInNewZoom - mouseCoordinatesInOldZoom
362 zoomTo(new EastNorth(
363 center.east() - (x - getWidth()/2.0) * (newScale - scale),
364 center.north() + (y - getHeight()/2.0) * (newScale - scale)),
365 newScale);
366 }
367
368 public void zoomToFactor(EastNorth newCenter, double factor) {
369 zoomTo(newCenter, scale*factor);
370 }
371
372 public void zoomToFactor(double factor) {
373 zoomTo(center, scale*factor);
374 }
375
376 public void zoomTo(ProjectionBounds box) {
377 // -20 to leave some border
378 int w = getWidth()-20;
379 if (w < 20) {
380 w = 20;
381 }
382 int h = getHeight()-20;
383 if (h < 20) {
384 h = 20;
385 }
386
387 double scaleX = (box.max.east()-box.min.east())/w;
388 double scaleY = (box.max.north()-box.min.north())/h;
389 double newScale = Math.max(scaleX, scaleY);
390
391 zoomTo(box.getCenter(), newScale);
392 }
393
394 public void zoomTo(Bounds box) {
395 zoomTo(new ProjectionBounds(getProjection().latlon2eastNorth(box.getMin()),
396 getProjection().latlon2eastNorth(box.getMax())));
397 }
398
399 private class ZoomData {
400 LatLon center;
401 double scale;
402
403 public ZoomData(EastNorth center, double scale) {
404 this.center = new CachedLatLon(center);
405 this.scale = scale;
406 }
407
408 public EastNorth getCenterEastNorth() {
409 return getProjection().latlon2eastNorth(center);
410 }
411
412 public double getScale() {
413 return scale;
414 }
415 }
416
417 private Stack<ZoomData> zoomUndoBuffer = new Stack<ZoomData>();
418 private Stack<ZoomData> zoomRedoBuffer = new Stack<ZoomData>();
419 private Date zoomTimestamp = new Date();
420
421 private void pushZoomUndo(EastNorth center, double scale) {
422 Date now = new Date();
423 if ((now.getTime() - zoomTimestamp.getTime()) > (Main.pref.getDouble("zoom.undo.delay", 1.0) * 1000)) {
424 zoomUndoBuffer.push(new ZoomData(center, scale));
425 if (zoomUndoBuffer.size() > Main.pref.getInteger("zoom.undo.max", 50)) {
426 zoomUndoBuffer.remove(0);
427 }
428 zoomRedoBuffer.clear();
429 }
430 zoomTimestamp = now;
431 }
432
433 public void zoomPrevious() {
434 if (!zoomUndoBuffer.isEmpty()) {
435 ZoomData zoom = zoomUndoBuffer.pop();
436 zoomRedoBuffer.push(new ZoomData(center, scale));
437 zoomNoUndoTo(zoom.getCenterEastNorth(), zoom.getScale());
438 }
439 }
440
441 public void zoomNext() {
442 if (!zoomRedoBuffer.isEmpty()) {
443 ZoomData zoom = zoomRedoBuffer.pop();
444 zoomUndoBuffer.push(new ZoomData(center, scale));
445 zoomNoUndoTo(zoom.getCenterEastNorth(), zoom.getScale());
446 }
447 }
448
449 public boolean hasZoomUndoEntries() {
450 return !zoomUndoBuffer.isEmpty();
451 }
452
453 public boolean hasZoomRedoEntries() {
454 return !zoomRedoBuffer.isEmpty();
455 }
456
457 private BBox getBBox(Point p, int snapDistance) {
458 return new BBox(getLatLon(p.x - snapDistance, p.y - snapDistance),
459 getLatLon(p.x + snapDistance, p.y + snapDistance));
460 }
461
462 /**
463 * The *result* does not depend on the current map selection state,
464 * neither does the result *order*.
465 * It solely depends on the distance to point p.
466 *
467 * @return a sorted map with the keys representing the distance of
468 * their associated nodes to point p.
469 */
470 private Map<Double, List<Node>> getNearestNodesImpl(Point p,
471 Predicate<OsmPrimitive> predicate) {
472 TreeMap<Double, List<Node>> nearestMap = new TreeMap<Double, List<Node>>();
473 DataSet ds = getCurrentDataSet();
474
475 if (ds != null) {
476 double dist, snapDistanceSq = PROP_SNAP_DISTANCE.get();
477 snapDistanceSq *= snapDistanceSq;
478
479 for (Node n : ds.searchNodes(getBBox(p, PROP_SNAP_DISTANCE.get()))) {
480 if (predicate.evaluate(n)
481 && (dist = getPoint2D(n).distanceSq(p)) < snapDistanceSq)
482 {
483 List<Node> nlist;
484 if (nearestMap.containsKey(dist)) {
485 nlist = nearestMap.get(dist);
486 } else {
487 nlist = new LinkedList<Node>();
488 nearestMap.put(dist, nlist);
489 }
490 nlist.add(n);
491 }
492 }
493 }
494
495 return nearestMap;
496 }
497
498 /**
499 * The *result* does not depend on the current map selection state,
500 * neither does the result *order*.
501 * It solely depends on the distance to point p.
502 *
503 * @return All nodes nearest to point p that are in a belt from
504 * dist(nearest) to dist(nearest)+4px around p and
505 * that are not in ignore.
506 *
507 * @param p the point for which to search the nearest segment.
508 * @param ignore a collection of nodes which are not to be returned.
509 * @param predicate the returned objects have to fulfill certain properties.
510 */
511 public final List<Node> getNearestNodes(Point p,
512 Collection<Node> ignore, Predicate<OsmPrimitive> predicate) {
513 List<Node> nearestList = Collections.emptyList();
514
515 if (ignore == null) {
516 ignore = Collections.emptySet();
517 }
518
519 Map<Double, List<Node>> nlists = getNearestNodesImpl(p, predicate);
520 if (!nlists.isEmpty()) {
521 Double minDistSq = null;
522 List<Node> nlist;
523 for (Double distSq : nlists.keySet()) {
524 nlist = nlists.get(distSq);
525
526 // filter nodes to be ignored before determining minDistSq..
527 nlist.removeAll(ignore);
528 if (minDistSq == null) {
529 if (!nlist.isEmpty()) {
530 minDistSq = distSq;
531 nearestList = new ArrayList<Node>();
532 nearestList.addAll(nlist);
533 }
534 } else {
535 if (distSq-minDistSq < (4)*(4)) {
536 nearestList.addAll(nlist);
537 }
538 }
539 }
540 }
541
542 return nearestList;
543 }
544
545 /**
546 * The *result* does not depend on the current map selection state,
547 * neither does the result *order*.
548 * It solely depends on the distance to point p.
549 *
550 * @return All nodes nearest to point p that are in a belt from
551 * dist(nearest) to dist(nearest)+4px around p.
552 * @see #getNearestNodes(Point, Collection, Predicate)
553 *
554 * @param p the point for which to search the nearest segment.
555 * @param predicate the returned objects have to fulfill certain properties.
556 */
557 public final List<Node> getNearestNodes(Point p, Predicate<OsmPrimitive> predicate) {
558 return getNearestNodes(p, null, predicate);
559 }
560
561 /**
562 * The *result* depends on the current map selection state IF use_selected is true.
563 *
564 * If more than one node within node.snap-distance pixels is found,
565 * the nearest node selected is returned IF use_selected is true.
566 *
567 * Else the nearest new/id=0 node within about the same distance
568 * as the true nearest node is returned.
569 *
570 * If no such node is found either, the true nearest
571 * node to p is returned.
572 *
573 * Finally, if a node is not found at all, null is returned.
574 *
575 * @return A node within snap-distance to point p,
576 * that is chosen by the algorithm described.
577 *
578 * @param p the screen point
579 * @param predicate this parameter imposes a condition on the returned object, e.g.
580 * give the nearest node that is tagged.
581 */
582 public final Node getNearestNode(Point p, Predicate<OsmPrimitive> predicate, boolean use_selected) {
583 Node n = null;
584
585 Map<Double, List<Node>> nlists = getNearestNodesImpl(p, predicate);
586 if (!nlists.isEmpty()) {
587 Node ntsel = null, ntnew = null;
588 double minDistSq = nlists.keySet().iterator().next();
589
590 for (Double distSq : nlists.keySet()) {
591 for (Node nd : nlists.get(distSq)) {
592 // find the nearest selected node
593 if (ntsel == null && nd.isSelected()) {
594 ntsel = nd;
595 }
596 // find the nearest newest node that is within about the same
597 // distance as the true nearest node
598 if (ntnew == null && nd.isNew() && (distSq-minDistSq < 1)) {
599 ntnew = nd;
600 }
601 }
602 }
603
604 // take nearest selected, nearest new or true nearest node to p, in that order
605 n = (ntsel != null && use_selected) ? ntsel
606 : ((ntnew != null) ? ntnew
607 : nlists.values().iterator().next().get(0));
608 }
609
610 return n;
611 }
612
613 /**
614 * Convenience method to {@link #getNearestNode(Point, Predicate, boolean)}.
615 *
616 * @return The nearest node to point p.
617 */
618 public final Node getNearestNode(Point p, Predicate<OsmPrimitive> predicate) {
619 return getNearestNode(p, predicate, true);
620 }
621
622 @Deprecated
623 public final Node getNearestNode(Point p) {
624 return getNearestNode(p, OsmPrimitive.isUsablePredicate);
625 }
626
627 /**
628 * The *result* does not depend on the current map selection state,
629 * neither does the result *order*.
630 * It solely depends on the distance to point p.
631 *
632 * @return a sorted map with the keys representing the perpendicular
633 * distance of their associated way segments to point p.
634 */
635 private Map<Double, List<WaySegment>> getNearestWaySegmentsImpl(Point p,
636 Predicate<OsmPrimitive> predicate) {
637 Map<Double, List<WaySegment>> nearestMap = new TreeMap<Double, List<WaySegment>>();
638 DataSet ds = getCurrentDataSet();
639
640 if (ds != null) {
641 double snapDistanceSq = Main.pref.getInteger("mappaint.segment.snap-distance", 10);
642 snapDistanceSq *= snapDistanceSq;
643
644 for (Way w : ds.searchWays(getBBox(p, Main.pref.getInteger("mappaint.segment.snap-distance", 10)))) {
645 if (!predicate.evaluate(w)) {
646 continue;
647 }
648 Node lastN = null;
649 int i = -2;
650 for (Node n : w.getNodes()) {
651 i++;
652 if (n.isDeleted() || n.isIncomplete()) { //FIXME: This shouldn't happen, raise exception?
653 continue;
654 }
655 if (lastN == null) {
656 lastN = n;
657 continue;
658 }
659
660 Point2D A = getPoint2D(lastN);
661 Point2D B = getPoint2D(n);
662 double c = A.distanceSq(B);
663 double a = p.distanceSq(B);
664 double b = p.distanceSq(A);
665
666 /* perpendicular distance squared
667 * loose some precision to account for possible deviations in the calculation above
668 * e.g. if identical (A and B) come about reversed in another way, values may differ
669 * -- zero out least significant 32 dual digits of mantissa..
670 */
671 double perDistSq = Double.longBitsToDouble(
672 Double.doubleToLongBits( a - (a - b + c) * (a - b + c) / 4 / c )
673 >> 32 << 32); // resolution in numbers with large exponent not needed here..
674
675 if (perDistSq < snapDistanceSq && a < c + snapDistanceSq && b < c + snapDistanceSq) {
676 //System.err.println(Double.toHexString(perDistSq));
677
678 List<WaySegment> wslist;
679 if (nearestMap.containsKey(perDistSq)) {
680 wslist = nearestMap.get(perDistSq);
681 } else {
682 wslist = new LinkedList<WaySegment>();
683 nearestMap.put(perDistSq, wslist);
684 }
685 wslist.add(new WaySegment(w, i));
686 }
687
688 lastN = n;
689 }
690 }
691 }
692
693 return nearestMap;
694 }
695
696 /**
697 * The result *order* depends on the current map selection state.
698 * Segments within 10px of p are searched and sorted by their distance to @param p,
699 * then, within groups of equally distant segments, prefer those that are selected.
700 *
701 * @return all segments within 10px of p that are not in ignore,
702 * sorted by their perpendicular distance.
703 *
704 * @param p the point for which to search the nearest segments.
705 * @param ignore a collection of segments which are not to be returned.
706 * @param predicate the returned objects have to fulfill certain properties.
707 */
708 public final List<WaySegment> getNearestWaySegments(Point p,
709 Collection<WaySegment> ignore, Predicate<OsmPrimitive> predicate) {
710 List<WaySegment> nearestList = new ArrayList<WaySegment>();
711 List<WaySegment> unselected = new LinkedList<WaySegment>();
712
713 for (List<WaySegment> wss : getNearestWaySegmentsImpl(p, predicate).values()) {
714 // put selected waysegs within each distance group first
715 // makes the order of nearestList dependent on current selection state
716 for (WaySegment ws : wss) {
717 (ws.way.isSelected() ? nearestList : unselected).add(ws);
718 }
719 nearestList.addAll(unselected);
720 unselected.clear();
721 }
722 if (ignore != null) {
723 nearestList.removeAll(ignore);
724 }
725
726 return nearestList;
727 }
728
729 /**
730 * The result *order* depends on the current map selection state.
731 *
732 * @return all segments within 10px of p, sorted by their perpendicular distance.
733 * @see #getNearestWaySegments(Point, Collection, Predicate)
734 *
735 * @param p the point for which to search the nearest segments.
736 * @param predicate the returned objects have to fulfill certain properties.
737 */
738 public final List<WaySegment> getNearestWaySegments(Point p, Predicate<OsmPrimitive> predicate) {
739 return getNearestWaySegments(p, null, predicate);
740 }
741
742 /**
743 * The *result* depends on the current map selection state IF use_selected is true.
744 *
745 * @return The nearest way segment to point p,
746 * and, depending on use_selected, prefers a selected way segment, if found.
747 * @see #getNearestWaySegments(Point, Collection, Predicate)
748 *
749 * @param p the point for which to search the nearest segment.
750 * @param predicate the returned object has to fulfill certain properties.
751 * @param use_selected whether selected way segments should be preferred.
752 */
753 public final WaySegment getNearestWaySegment(Point p, Predicate<OsmPrimitive> predicate, boolean use_selected) {
754 WaySegment wayseg = null, ntsel = null;
755
756 for (List<WaySegment> wslist : getNearestWaySegmentsImpl(p, predicate).values()) {
757 if (wayseg != null && ntsel != null) {
758 break;
759 }
760 for (WaySegment ws : wslist) {
761 if (wayseg == null) {
762 wayseg = ws;
763 }
764 if (ntsel == null && ws.way.isSelected()) {
765 ntsel = ws;
766 }
767 }
768 }
769
770 return (ntsel != null && use_selected) ? ntsel : wayseg;
771 }
772
773 /**
774 * Convenience method to {@link #getNearestWaySegment(Point, Predicate, boolean)}.
775 *
776 * @return The nearest way segment to point p.
777 */
778 public final WaySegment getNearestWaySegment(Point p, Predicate<OsmPrimitive> predicate) {
779 return getNearestWaySegment(p, predicate, true);
780 }
781
782 /**
783 * The *result* does not depend on the current map selection state,
784 * neither does the result *order*.
785 * It solely depends on the perpendicular distance to point p.
786 *
787 * @return all nearest ways to the screen point given that are not in ignore.
788 * @see #getNearestWaySegments(Point, Collection, Predicate)
789 *
790 * @param p the point for which to search the nearest ways.
791 * @param ignore a collection of ways which are not to be returned.
792 * @param predicate the returned object has to fulfill certain properties.
793 */
794 public final List<Way> getNearestWays(Point p,
795 Collection<Way> ignore, Predicate<OsmPrimitive> predicate) {
796 List<Way> nearestList = new ArrayList<Way>();
797 Set<Way> wset = new HashSet<Way>();
798
799 for (List<WaySegment> wss : getNearestWaySegmentsImpl(p, predicate).values()) {
800 for (WaySegment ws : wss) {
801 if (wset.add(ws.way)) {
802 nearestList.add(ws.way);
803 }
804 }
805 }
806 if (ignore != null) {
807 nearestList.removeAll(ignore);
808 }
809
810 return nearestList;
811 }
812
813 /**
814 * The *result* does not depend on the current map selection state,
815 * neither does the result *order*.
816 * It solely depends on the perpendicular distance to point p.
817 *
818 * @return all nearest ways to the screen point given.
819 * @see #getNearestWays(Point, Collection, Predicate)
820 *
821 * @param p the point for which to search the nearest ways.
822 * @param predicate the returned object has to fulfill certain properties.
823 */
824 public final List<Way> getNearestWays(Point p, Predicate<OsmPrimitive> predicate) {
825 return getNearestWays(p, null, predicate);
826 }
827
828 /**
829 * The *result* depends on the current map selection state.
830 *
831 * @return The nearest way to point p,
832 * prefer a selected way if there are multiple nearest.
833 * @see #getNearestWaySegment(Point, Collection, Predicate)
834 *
835 * @param p the point for which to search the nearest segment.
836 * @param predicate the returned object has to fulfill certain properties.
837 */
838 public final Way getNearestWay(Point p, Predicate<OsmPrimitive> predicate) {
839 WaySegment nearestWaySeg = getNearestWaySegment(p, predicate);
840 return (nearestWaySeg == null) ? null : nearestWaySeg.way;
841 }
842
843 @Deprecated
844 public final Way getNearestWay(Point p) {
845 return getNearestWay(p, OsmPrimitive.isUsablePredicate);
846 }
847
848 /**
849 * The *result* does not depend on the current map selection state,
850 * neither does the result *order*.
851 * It solely depends on the distance to point p.
852 *
853 * First, nodes will be searched. If there are nodes within BBox found,
854 * return a collection of those nodes only.
855 *
856 * If no nodes are found, search for nearest ways. If there are ways
857 * within BBox found, return a collection of those ways only.
858 *
859 * If nothing is found, return an empty collection.
860 *
861 * @return Primitives nearest to the given screen point that are not in ignore.
862 * @see #getNearestNodes(Point, Collection, Predicate)
863 * @see #getNearestWays(Point, Collection, Predicate)
864 *
865 * @param p The point on screen.
866 * @param ignore a collection of ways which are not to be returned.
867 * @param predicate the returned object has to fulfill certain properties.
868 */
869 public final List<OsmPrimitive> getNearestNodesOrWays(Point p,
870 Collection<OsmPrimitive> ignore, Predicate<OsmPrimitive> predicate) {
871 List<OsmPrimitive> nearestList = Collections.emptyList();
872 OsmPrimitive osm = getNearestNodeOrWay(p, predicate, false);
873
874 if (osm != null) {
875 if (osm instanceof Node) {
876 nearestList = new ArrayList<OsmPrimitive>(getNearestNodes(p, predicate));
877 } else if (osm instanceof Way) {
878 nearestList = new ArrayList<OsmPrimitive>(getNearestWays(p, predicate));
879 }
880 if (ignore != null) {
881 nearestList.removeAll(ignore);
882 }
883 }
884
885 return nearestList;
886 }
887
888 /**
889 * The *result* does not depend on the current map selection state,
890 * neither does the result *order*.
891 * It solely depends on the distance to point p.
892 *
893 * @return Primitives nearest to the given screen point.
894 * @see #getNearests(Point, Collection, Predicate)
895 *
896 * @param p The point on screen.
897 * @param predicate the returned object has to fulfill certain properties.
898 */
899 public final List<OsmPrimitive> getNearestNodesOrWays(Point p, Predicate<OsmPrimitive> predicate) {
900 return getNearestNodesOrWays(p, null, predicate);
901 }
902
903 /**
904 * This is used as a helper routine to {@link #getNearestNodeOrWay(Point, Predicate, boolean)}
905 * It decides, whether to yield the node to be tested or look for further (way) candidates.
906 *
907 * @return true, if the node fulfills the properties of the function body
908 *
909 * @param osm node to check
910 * @param p point clicked
911 * @param use_selected whether to prefer selected nodes
912 */
913 private boolean isPrecedenceNode(Node osm, Point p, boolean use_selected) {
914 boolean ret = false;
915
916 if (osm != null) {
917 ret |= !(p.distanceSq(getPoint2D(osm)) > (4)*(4));
918 ret |= osm.isTagged();
919 if (use_selected) {
920 ret |= osm.isSelected();
921 }
922 }
923
924 return ret;
925 }
926
927 /**
928 * The *result* depends on the current map selection state IF use_selected is true.
929 *
930 * IF use_selected is true, use {@link #getNearestNode(Point, Predicate)} to find
931 * the nearest, selected node. If not found, try {@link #getNearestWaySegment(Point, Predicate)}
932 * to find the nearest selected way.
933 *
934 * IF use_selected is false, or if no selected primitive was found, do the following.
935 *
936 * If the nearest node found is within 4px of p, simply take it.
937 * Else, find the nearest way segment. Then, if p is closer to its
938 * middle than to the node, take the way segment, else take the node.
939 *
940 * Finally, if no nearest primitive is found at all, return null.
941 *
942 * @return A primitive within snap-distance to point p,
943 * that is chosen by the algorithm described.
944 * @see getNearestNode(Point, Predicate)
945 * @see getNearestNodesImpl(Point, Predicate)
946 * @see getNearestWay(Point, Predicate)
947 *
948 * @param p The point on screen.
949 * @param predicate the returned object has to fulfill certain properties.
950 * @param use_selected whether to prefer primitives that are currently selected.
951 */
952 public final OsmPrimitive getNearestNodeOrWay(Point p, Predicate<OsmPrimitive> predicate, boolean use_selected) {
953 OsmPrimitive osm = getNearestNode(p, predicate, use_selected);
954 WaySegment ws = null;
955
956 if (!isPrecedenceNode((Node)osm, p, use_selected)) {
957 ws = getNearestWaySegment(p, predicate, use_selected);
958
959 if (ws != null) {
960 if ((ws.way.isSelected() && use_selected) || osm == null) {
961 // either (no _selected_ nearest node found, if desired) or no nearest node was found
962 osm = ws.way;
963 } else {
964 int maxWaySegLenSq = 3*PROP_SNAP_DISTANCE.get();
965 maxWaySegLenSq *= maxWaySegLenSq;
966
967 Point2D wp1 = getPoint2D(ws.way.getNode(ws.lowerIndex));
968 Point2D wp2 = getPoint2D(ws.way.getNode(ws.lowerIndex+1));
969
970 // is wayseg shorter than maxWaySegLenSq and
971 // is p closer to the middle of wayseg than to the nearest node?
972 if (wp1.distanceSq(wp2) < maxWaySegLenSq &&
973 p.distanceSq(project(0.5, wp1, wp2)) < p.distanceSq(getPoint2D((Node)osm))) {
974 osm = ws.way;
975 }
976 }
977 }
978 }
979
980 return osm;
981 }
982
983 @Deprecated
984 public final OsmPrimitive getNearest(Point p, Predicate<OsmPrimitive> predicate) {
985 return getNearestNodeOrWay(p, predicate, false);
986 }
987
988 @Deprecated
989 public final Collection<OsmPrimitive> getNearestCollection(Point p, Predicate<OsmPrimitive> predicate) {
990 return asColl(getNearest(p, predicate));
991 }
992
993 /**
994 * @return o as collection of o's type.
995 */
996 public final static <T> Collection<T> asColl(T o) {
997 if (o == null)
998 return Collections.emptySet();
999 return Collections.singleton(o);
1000 }
1001
1002 public final static double perDist(Point2D pt, Point2D a, Point2D b) {
1003 if (pt != null && a != null && b != null) {
1004 double pd = (
1005 (a.getX()-pt.getX())*(b.getX()-a.getX()) -
1006 (a.getY()-pt.getY())*(b.getY()-a.getY()) );
1007 return Math.abs(pd) / a.distance(b);
1008 }
1009 return 0d;
1010 }
1011
1012 /**
1013 *
1014 * @param pt point to project onto (ab)
1015 * @param a root of vector
1016 * @param b vector
1017 * @return point of intersection of line given by (ab)
1018 * with its orthogonal line running through pt
1019 */
1020 public final static Point2D project(Point2D pt, Point2D a, Point2D b) {
1021 if (pt != null && a != null && b != null) {
1022 double r = ((
1023 (pt.getX()-a.getX())*(b.getX()-a.getX()) +
1024 (pt.getY()-a.getY())*(b.getY()-a.getY()) )
1025 / a.distanceSq(b));
1026 return project(r, a, b);
1027 }
1028 return null;
1029 }
1030
1031 /**
1032 * if r = 0 returns a, if r=1 returns b,
1033 * if r = 0.5 returns center between a and b, etc..
1034 *
1035 * @param r scale value
1036 * @param a root of vector
1037 * @param b vector
1038 * @return new point at a + r*(ab)
1039 */
1040 public final static Point2D project(double r, Point2D a, Point2D b) {
1041 Point2D ret = null;
1042
1043 if (a != null && b != null) {
1044 ret = new Point2D.Double(a.getX() + r*(b.getX()-a.getX()),
1045 a.getY() + r*(b.getY()-a.getY()));
1046 }
1047 return ret;
1048 }
1049
1050 /**
1051 * The *result* does not depend on the current map selection state,
1052 * neither does the result *order*.
1053 * It solely depends on the distance to point p.
1054 *
1055 * @return a list of all objects that are nearest to point p and
1056 * not in ignore or an empty list if nothing was found.
1057 *
1058 * @param p The point on screen.
1059 * @param ignore a collection of ways which are not to be returned.
1060 * @param predicate the returned object has to fulfill certain properties.
1061 */
1062 public final List<OsmPrimitive> getAllNearest(Point p,
1063 Collection<OsmPrimitive> ignore, Predicate<OsmPrimitive> predicate) {
1064 List<OsmPrimitive> nearestList = new ArrayList<OsmPrimitive>();
1065 Set<Way> wset = new HashSet<Way>();
1066
1067 for (List<WaySegment> wss : getNearestWaySegmentsImpl(p, predicate).values()) {
1068 for (WaySegment ws : wss) {
1069 if (wset.add(ws.way)) {
1070 nearestList.add(ws.way);
1071 }
1072 }
1073 }
1074 for (List<Node> nlist : getNearestNodesImpl(p, predicate).values()) {
1075 nearestList.addAll(nlist);
1076 }
1077 if (ignore != null) {
1078 nearestList.removeAll(ignore);
1079 }
1080
1081 return nearestList;
1082 }
1083
1084 /**
1085 * The *result* does not depend on the current map selection state,
1086 * neither does the result *order*.
1087 * It solely depends on the distance to point p.
1088 *
1089 * @return a list of all objects that are nearest to point p
1090 * or an empty list if nothing was found.
1091 * @see #getAllNearest(Point, Collection, Predicate)
1092 *
1093 * @param p The point on screen.
1094 * @param predicate the returned object has to fulfill certain properties.
1095 */
1096 public final List<OsmPrimitive> getAllNearest(Point p, Predicate<OsmPrimitive> predicate) {
1097 return getAllNearest(p, null, predicate);
1098 }
1099
1100 /**
1101 * @return The projection to be used in calculating stuff.
1102 */
1103 public Projection getProjection() {
1104 return Main.proj;
1105 }
1106
1107 public String helpTopic() {
1108 String n = getClass().getName();
1109 return n.substring(n.lastIndexOf('.')+1);
1110 }
1111
1112 /**
1113 * Return a ID which is unique as long as viewport dimensions are the same
1114 */
1115 public int getViewID() {
1116 String x = center.east() + "_" + center.north() + "_" + scale + "_" +
1117 getWidth() + "_" + getHeight() + "_" + getProjection().toString();
1118 java.util.zip.CRC32 id = new java.util.zip.CRC32();
1119 id.update(x.getBytes());
1120 return (int)id.getValue();
1121 }
1122
1123 public static SystemOfMeasurement getSystemOfMeasurement() {
1124 SystemOfMeasurement som = SYSTEMS_OF_MEASUREMENT.get(ProjectionPreference.PROP_SYSTEM_OF_MEASUREMENT.get());
1125 if (som == null)
1126 return METRIC_SOM;
1127 return som;
1128 }
1129
1130 public static class SystemOfMeasurement {
1131 public final double aValue;
1132 public final double bValue;
1133 public final String aName;
1134 public final String bName;
1135
1136 /**
1137 * System of measurement. Currently covers only length units.
1138 *
1139 * If a quantity x is given in m (x_m) and in unit a (x_a) then it translates as
1140 * x_a == x_m / aValue
1141 */
1142 public SystemOfMeasurement(double aValue, String aName, double bValue, String bName) {
1143 this.aValue = aValue;
1144 this.aName = aName;
1145 this.bValue = bValue;
1146 this.bName = bName;
1147 }
1148
1149 public String getDistText(double dist) {
1150 double a = dist / aValue;
1151 if (!Main.pref.getBoolean("system_of_measurement.use_only_lower_unit", false) && a > bValue / aValue) {
1152 double b = dist / bValue;
1153 return String.format(Locale.US, "%." + (b<10 ? 2 : 1) + "f %s", b, bName);
1154 } else if (a < 0.01)
1155 return "< 0.01 " + aName;
1156 else
1157 return String.format(Locale.US, "%." + (a<10 ? 2 : 1) + "f %s", a, aName);
1158 }
1159 }
1160
1161 public static final SystemOfMeasurement METRIC_SOM = new SystemOfMeasurement(1, "m", 1000, "km");
1162 public static final SystemOfMeasurement CHINESE_SOM = new SystemOfMeasurement(1.0/3.0, "\u5e02\u5c3a" /* chi */, 500, "\u5e02\u91cc" /* li */);
1163 public static final SystemOfMeasurement IMPERIAL_SOM = new SystemOfMeasurement(0.3048, "ft", 1609.344, "mi");
1164
1165 public static Map<String, SystemOfMeasurement> SYSTEMS_OF_MEASUREMENT;
1166 static {
1167 SYSTEMS_OF_MEASUREMENT = new LinkedHashMap<String, SystemOfMeasurement>();
1168 SYSTEMS_OF_MEASUREMENT.put(marktr("Metric"), METRIC_SOM);
1169 SYSTEMS_OF_MEASUREMENT.put(marktr("Chinese"), CHINESE_SOM);
1170 SYSTEMS_OF_MEASUREMENT.put(marktr("Imperial"), IMPERIAL_SOM);
1171 }
1172}
Note: See TracBrowser for help on using the repository browser.