source: josm/trunk/src/org/openstreetmap/josm/data/osm/Way.java@ 12867

Last change on this file since 12867 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

  • Property svn:eol-style set to native
File size: 24.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.HashSet;
9import java.util.List;
10import java.util.Map;
11import java.util.Set;
12
13import org.openstreetmap.josm.data.coor.LatLon;
14import org.openstreetmap.josm.data.osm.visitor.OsmPrimitiveVisitor;
15import org.openstreetmap.josm.data.osm.visitor.PrimitiveVisitor;
16import org.openstreetmap.josm.spi.preferences.Config;
17import org.openstreetmap.josm.tools.CopyList;
18import org.openstreetmap.josm.tools.Pair;
19import org.openstreetmap.josm.tools.Utils;
20
21/**
22 * One full way, consisting of a list of way {@link Node nodes}.
23 *
24 * @author imi
25 * @since 64
26 */
27public final class Way extends OsmPrimitive implements IWay {
28
29 /**
30 * All way nodes in this way
31 *
32 */
33 private Node[] nodes = new Node[0];
34 private BBox bbox;
35
36 /**
37 *
38 * You can modify returned list but changes will not be propagated back
39 * to the Way. Use {@link #setNodes(List)} to update this way
40 * @return Nodes composing the way
41 * @since 1862
42 */
43 public List<Node> getNodes() {
44 return new CopyList<>(nodes);
45 }
46
47 /**
48 * Set new list of nodes to way. This method is preferred to multiple calls to addNode/removeNode
49 * and similar methods because nodes are internally saved as array which means lower memory overhead
50 * but also slower modifying operations.
51 * @param nodes New way nodes. Can be null, in that case all way nodes are removed
52 * @since 1862
53 */
54 public void setNodes(List<Node> nodes) {
55 boolean locked = writeLock();
56 try {
57 for (Node node:this.nodes) {
58 node.removeReferrer(this);
59 node.clearCachedStyle();
60 }
61
62 if (nodes == null) {
63 this.nodes = new Node[0];
64 } else {
65 this.nodes = nodes.toArray(new Node[nodes.size()]);
66 }
67 for (Node node: this.nodes) {
68 node.addReferrer(this);
69 node.clearCachedStyle();
70 }
71
72 clearCachedStyle();
73 fireNodesChanged();
74 } finally {
75 writeUnlock(locked);
76 }
77 }
78
79 /**
80 * Prevent directly following identical nodes in ways.
81 * @param nodes list of nodes
82 * @return {@code nodes} with consecutive identical nodes removed
83 */
84 private static List<Node> removeDouble(List<Node> nodes) {
85 Node last = null;
86 int count = nodes.size();
87 for (int i = 0; i < count && count > 2;) {
88 Node n = nodes.get(i);
89 if (last == n) {
90 nodes.remove(i);
91 --count;
92 } else {
93 last = n;
94 ++i;
95 }
96 }
97 return nodes;
98 }
99
100 @Override
101 public int getNodesCount() {
102 return nodes.length;
103 }
104
105 /**
106 * Replies the real number of nodes in this way (full number of nodes minus one if this way is closed)
107 *
108 * @return the real number of nodes in this way.
109 *
110 * @see #getNodesCount()
111 * @see #isClosed()
112 * @since 5847
113 */
114 public int getRealNodesCount() {
115 int count = getNodesCount();
116 return isClosed() ? count-1 : count;
117 }
118
119 /**
120 * Replies the node at position <code>index</code>.
121 *
122 * @param index the position
123 * @return the node at position <code>index</code>
124 * @throws IndexOutOfBoundsException if <code>index</code> &lt; 0
125 * or <code>index</code> &gt;= {@link #getNodesCount()}
126 * @since 1862
127 */
128 public Node getNode(int index) {
129 return nodes[index];
130 }
131
132 @Override
133 public long getNodeId(int idx) {
134 return nodes[idx].getUniqueId();
135 }
136
137 /**
138 * Replies true if this way contains the node <code>node</code>, false
139 * otherwise. Replies false if <code>node</code> is null.
140 *
141 * @param node the node. May be null.
142 * @return true if this way contains the node <code>node</code>, false
143 * otherwise
144 * @since 1911
145 */
146 public boolean containsNode(Node node) {
147 if (node == null) return false;
148
149 Node[] nodes = this.nodes;
150 for (Node n : nodes) {
151 if (n.equals(node))
152 return true;
153 }
154 return false;
155 }
156
157 /**
158 * Return nodes adjacent to <code>node</code>
159 *
160 * @param node the node. May be null.
161 * @return Set of nodes adjacent to <code>node</code>
162 * @since 4671
163 */
164 public Set<Node> getNeighbours(Node node) {
165 Set<Node> neigh = new HashSet<>();
166
167 if (node == null) return neigh;
168
169 Node[] nodes = this.nodes;
170 for (int i = 0; i < nodes.length; i++) {
171 if (nodes[i].equals(node)) {
172 if (i > 0)
173 neigh.add(nodes[i-1]);
174 if (i < nodes.length-1)
175 neigh.add(nodes[i+1]);
176 }
177 }
178 return neigh;
179 }
180
181 /**
182 * Replies the ordered {@link List} of chunks of this way. Each chunk is replied as a {@link Pair} of {@link Node nodes}.
183 * @param sort If true, the nodes of each pair are sorted as defined by {@link Pair#sort}.
184 * If false, Pair.a and Pair.b are in the way order
185 * (i.e for a given Pair(n), Pair(n-1).b == Pair(n).a, Pair(n).b == Pair(n+1).a, etc.)
186 * @return The ordered list of chunks of this way.
187 * @since 3348
188 */
189 public List<Pair<Node, Node>> getNodePairs(boolean sort) {
190 List<Pair<Node, Node>> chunkSet = new ArrayList<>();
191 if (isIncomplete()) return chunkSet;
192 Node lastN = null;
193 Node[] nodes = this.nodes;
194 for (Node n : nodes) {
195 if (lastN == null) {
196 lastN = n;
197 continue;
198 }
199 Pair<Node, Node> np = new Pair<>(lastN, n);
200 if (sort) {
201 Pair.sort(np);
202 }
203 chunkSet.add(np);
204 lastN = n;
205 }
206 return chunkSet;
207 }
208
209 /**
210 * @deprecated no longer supported
211 */
212 @Deprecated
213 @Override public void accept(org.openstreetmap.josm.data.osm.visitor.Visitor visitor) {
214 visitor.visit(this);
215 }
216
217 @Override public void accept(OsmPrimitiveVisitor visitor) {
218 visitor.visit(this);
219 }
220
221 @Override public void accept(PrimitiveVisitor visitor) {
222 visitor.visit(this);
223 }
224
225 protected Way(long id, boolean allowNegative) {
226 super(id, allowNegative);
227 }
228
229 /**
230 * Contructs a new {@code Way} with id 0.
231 * @since 86
232 */
233 public Way() {
234 super(0, false);
235 }
236
237 /**
238 * Contructs a new {@code Way} from an existing {@code Way}.
239 * @param original The original {@code Way} to be identically cloned. Must not be null
240 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}.
241 * If {@code false}, does nothing
242 * @since 2410
243 */
244 public Way(Way original, boolean clearMetadata) {
245 super(original.getUniqueId(), true);
246 cloneFrom(original);
247 if (clearMetadata) {
248 clearOsmMetadata();
249 }
250 }
251
252 /**
253 * Contructs a new {@code Way} from an existing {@code Way} (including its id).
254 * @param original The original {@code Way} to be identically cloned. Must not be null
255 * @since 86
256 */
257 public Way(Way original) {
258 this(original, false);
259 }
260
261 /**
262 * Contructs a new {@code Way} for the given id. If the id &gt; 0, the way is marked
263 * as incomplete. If id == 0 then way is marked as new
264 *
265 * @param id the id. &gt;= 0 required
266 * @throws IllegalArgumentException if id &lt; 0
267 * @since 343
268 */
269 public Way(long id) {
270 super(id, false);
271 }
272
273 /**
274 * Contructs a new {@code Way} with given id and version.
275 * @param id the id. &gt;= 0 required
276 * @param version the version
277 * @throws IllegalArgumentException if id &lt; 0
278 * @since 2620
279 */
280 public Way(long id, int version) {
281 super(id, version, false);
282 }
283
284 @Override
285 public void load(PrimitiveData data) {
286 if (!(data instanceof WayData))
287 throw new IllegalArgumentException("Not a way data: " + data);
288 boolean locked = writeLock();
289 try {
290 super.load(data);
291
292 WayData wayData = (WayData) data;
293
294 if (!wayData.getNodes().isEmpty() && getDataSet() == null) {
295 throw new AssertionError("Data consistency problem - way without dataset detected");
296 }
297
298 List<Node> newNodes = new ArrayList<>(wayData.getNodes().size());
299 for (Long nodeId : wayData.getNodes()) {
300 Node node = (Node) getDataSet().getPrimitiveById(nodeId, OsmPrimitiveType.NODE);
301 if (node != null) {
302 newNodes.add(node);
303 } else {
304 throw new AssertionError("Data consistency problem - way with missing node detected");
305 }
306 }
307 setNodes(newNodes);
308 } finally {
309 writeUnlock(locked);
310 }
311 }
312
313 @Override
314 public WayData save() {
315 WayData data = new WayData();
316 saveCommonAttributes(data);
317 for (Node node:nodes) {
318 data.getNodes().add(node.getUniqueId());
319 }
320 return data;
321 }
322
323 @Override
324 public void cloneFrom(OsmPrimitive osm) {
325 if (!(osm instanceof Way))
326 throw new IllegalArgumentException("Not a way: " + osm);
327 boolean locked = writeLock();
328 try {
329 super.cloneFrom(osm);
330 Way otherWay = (Way) osm;
331 setNodes(otherWay.getNodes());
332 } finally {
333 writeUnlock(locked);
334 }
335 }
336
337 @Override
338 public String toString() {
339 String nodesDesc = isIncomplete() ? "(incomplete)" : ("nodes=" + Arrays.toString(nodes));
340 return "{Way id=" + getUniqueId() + " version=" + getVersion()+ ' ' + getFlagsAsString() + ' ' + nodesDesc + '}';
341 }
342
343 @Override
344 public boolean hasEqualSemanticAttributes(OsmPrimitive other, boolean testInterestingTagsOnly) {
345 if (!(other instanceof Way))
346 return false;
347 Way w = (Way) other;
348 if (getNodesCount() != w.getNodesCount()) return false;
349 if (!super.hasEqualSemanticAttributes(other, testInterestingTagsOnly))
350 return false;
351 for (int i = 0; i < getNodesCount(); i++) {
352 if (!getNode(i).hasEqualSemanticAttributes(w.getNode(i)))
353 return false;
354 }
355 return true;
356 }
357
358 @Override
359 public int compareTo(OsmPrimitive o) {
360 if (o instanceof Relation)
361 return 1;
362 return o instanceof Way ? Long.compare(getUniqueId(), o.getUniqueId()) : -1;
363 }
364
365 /**
366 * Removes the given {@link Node} from this way. Ignored, if n is null.
367 * @param n The node to remove. Ignored, if null
368 * @since 1463
369 */
370 public void removeNode(Node n) {
371 if (n == null || isIncomplete()) return;
372 boolean locked = writeLock();
373 try {
374 boolean closed = lastNode() == n && firstNode() == n;
375 int i;
376 List<Node> copy = getNodes();
377 while ((i = copy.indexOf(n)) >= 0) {
378 copy.remove(i);
379 }
380 i = copy.size();
381 if (closed && i > 2) {
382 copy.add(copy.get(0));
383 } else if (i >= 2 && i <= 3 && copy.get(0) == copy.get(i-1)) {
384 copy.remove(i-1);
385 }
386 setNodes(removeDouble(copy));
387 n.clearCachedStyle();
388 } finally {
389 writeUnlock(locked);
390 }
391 }
392
393 /**
394 * Removes the given set of {@link Node nodes} from this way. Ignored, if selection is null.
395 * @param selection The selection of nodes to remove. Ignored, if null
396 * @since 5408
397 */
398 public void removeNodes(Set<? extends Node> selection) {
399 if (selection == null || isIncomplete()) return;
400 boolean locked = writeLock();
401 try {
402 boolean closed = isClosed() && selection.contains(lastNode());
403 List<Node> copy = new ArrayList<>();
404
405 for (Node n: nodes) {
406 if (!selection.contains(n)) {
407 copy.add(n);
408 }
409 }
410
411 int i = copy.size();
412 if (closed && i > 2) {
413 copy.add(copy.get(0));
414 } else if (i >= 2 && i <= 3 && copy.get(0) == copy.get(i-1)) {
415 copy.remove(i-1);
416 }
417 setNodes(removeDouble(copy));
418 for (Node n : selection) {
419 n.clearCachedStyle();
420 }
421 } finally {
422 writeUnlock(locked);
423 }
424 }
425
426 /**
427 * Adds a node to the end of the list of nodes. Ignored, if n is null.
428 *
429 * @param n the node. Ignored, if null
430 * @throws IllegalStateException if this way is marked as incomplete. We can't add a node
431 * to an incomplete way
432 * @since 1313
433 */
434 public void addNode(Node n) {
435 if (n == null) return;
436
437 boolean locked = writeLock();
438 try {
439 if (isIncomplete())
440 throw new IllegalStateException(tr("Cannot add node {0} to incomplete way {1}.", n.getId(), getId()));
441 clearCachedStyle();
442 n.addReferrer(this);
443 nodes = Utils.addInArrayCopy(nodes, n);
444 n.clearCachedStyle();
445 fireNodesChanged();
446 } finally {
447 writeUnlock(locked);
448 }
449 }
450
451 /**
452 * Adds a node at position offs.
453 *
454 * @param offs the offset
455 * @param n the node. Ignored, if null.
456 * @throws IllegalStateException if this way is marked as incomplete. We can't add a node
457 * to an incomplete way
458 * @throws IndexOutOfBoundsException if offs is out of bounds
459 * @since 1313
460 */
461 public void addNode(int offs, Node n) {
462 if (n == null) return;
463
464 boolean locked = writeLock();
465 try {
466 if (isIncomplete())
467 throw new IllegalStateException(tr("Cannot add node {0} to incomplete way {1}.", n.getId(), getId()));
468
469 clearCachedStyle();
470 n.addReferrer(this);
471 Node[] newNodes = new Node[nodes.length + 1];
472 System.arraycopy(nodes, 0, newNodes, 0, offs);
473 System.arraycopy(nodes, offs, newNodes, offs + 1, nodes.length - offs);
474 newNodes[offs] = n;
475 nodes = newNodes;
476 n.clearCachedStyle();
477 fireNodesChanged();
478 } finally {
479 writeUnlock(locked);
480 }
481 }
482
483 @Override
484 public void setDeleted(boolean deleted) {
485 boolean locked = writeLock();
486 try {
487 for (Node n:nodes) {
488 if (deleted) {
489 n.removeReferrer(this);
490 } else {
491 n.addReferrer(this);
492 }
493 n.clearCachedStyle();
494 }
495 fireNodesChanged();
496 super.setDeleted(deleted);
497 } finally {
498 writeUnlock(locked);
499 }
500 }
501
502 @Override
503 public boolean isClosed() {
504 if (isIncomplete()) return false;
505
506 Node[] nodes = this.nodes;
507 return nodes.length >= 3 && nodes[nodes.length-1] == nodes[0];
508 }
509
510 /**
511 * Determines if this way denotes an area (closed way with at least three distinct nodes).
512 * @return {@code true} if this way is closed and contains at least three distinct nodes
513 * @see #isClosed
514 * @since 5490
515 */
516 public boolean isArea() {
517 if (this.nodes.length >= 4 && isClosed()) {
518 Node distinctNode = null;
519 for (int i = 1; i < nodes.length-1; i++) {
520 if (distinctNode == null && nodes[i] != nodes[0]) {
521 distinctNode = nodes[i];
522 } else if (distinctNode != null && nodes[i] != nodes[0] && nodes[i] != distinctNode) {
523 return true;
524 }
525 }
526 }
527 return false;
528 }
529
530 /**
531 * Returns the last node of this way.
532 * The result equals <tt>{@link #getNode getNode}({@link #getNodesCount getNodesCount} - 1)</tt>.
533 * @return the last node of this way
534 * @since 1400
535 */
536 public Node lastNode() {
537 Node[] nodes = this.nodes;
538 if (isIncomplete() || nodes.length == 0) return null;
539 return nodes[nodes.length-1];
540 }
541
542 /**
543 * Returns the first node of this way.
544 * The result equals {@link #getNode getNode}{@code (0)}.
545 * @return the first node of this way
546 * @since 1400
547 */
548 public Node firstNode() {
549 Node[] nodes = this.nodes;
550 if (isIncomplete() || nodes.length == 0) return null;
551 return nodes[0];
552 }
553
554 /**
555 * Replies true if the given node is the first or the last one of this way, false otherwise.
556 * @param n The node to test
557 * @return true if the {@code n} is the first or the last node, false otherwise.
558 * @since 1400
559 */
560 public boolean isFirstLastNode(Node n) {
561 Node[] nodes = this.nodes;
562 if (isIncomplete() || nodes.length == 0) return false;
563 return n == nodes[0] || n == nodes[nodes.length -1];
564 }
565
566 /**
567 * Replies true if the given node is an inner node of this way, false otherwise.
568 * @param n The node to test
569 * @return true if the {@code n} is an inner node, false otherwise.
570 * @since 3515
571 */
572 public boolean isInnerNode(Node n) {
573 Node[] nodes = this.nodes;
574 if (isIncomplete() || nodes.length <= 2) return false;
575 /* circular ways have only inner nodes, so return true for them! */
576 if (n == nodes[0] && n == nodes[nodes.length-1]) return true;
577 for (int i = 1; i < nodes.length - 1; ++i) {
578 if (nodes[i] == n) return true;
579 }
580 return false;
581 }
582
583 @Override
584 public String getDisplayName(NameFormatter formatter) {
585 return formatter.format(this);
586 }
587
588 @Override
589 public OsmPrimitiveType getType() {
590 return OsmPrimitiveType.WAY;
591 }
592
593 @Override
594 public OsmPrimitiveType getDisplayType() {
595 return isClosed() ? OsmPrimitiveType.CLOSEDWAY : OsmPrimitiveType.WAY;
596 }
597
598 private void checkNodes() {
599 DataSet dataSet = getDataSet();
600 if (dataSet != null) {
601 Node[] nodes = this.nodes;
602 for (Node n: nodes) {
603 if (n.getDataSet() != dataSet)
604 throw new DataIntegrityProblemException("Nodes in way must be in the same dataset",
605 tr("Nodes in way must be in the same dataset"));
606 if (n.isDeleted())
607 throw new DataIntegrityProblemException("Deleted node referenced: " + toString(),
608 "<html>" + tr("Deleted node referenced by {0}",
609 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(this)) + "</html>");
610 }
611 if (Config.getPref().getBoolean("debug.checkNullCoor", true)) {
612 for (Node n: nodes) {
613 if (n.isVisible() && !n.isIncomplete() && !n.isLatLonKnown())
614 throw new DataIntegrityProblemException("Complete visible node with null coordinates: " + toString(),
615 "<html>" + tr("Complete node {0} with null coordinates in way {1}",
616 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(n),
617 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(this)) + "</html>");
618 }
619 }
620 }
621 }
622
623 private void fireNodesChanged() {
624 checkNodes();
625 if (getDataSet() != null) {
626 getDataSet().fireWayNodesChanged(this);
627 }
628 }
629
630 @Override
631 void setDataset(DataSet dataSet) {
632 super.setDataset(dataSet);
633 checkNodes();
634 }
635
636 @Override
637 public BBox getBBox() {
638 if (getDataSet() == null)
639 return new BBox(this);
640 if (bbox == null) {
641 bbox = new BBox(this);
642 }
643 return new BBox(bbox);
644 }
645
646 @Override
647 protected void addToBBox(BBox box, Set<PrimitiveId> visited) {
648 box.add(getBBox());
649 }
650
651 @Override
652 public void updatePosition() {
653 bbox = new BBox(this);
654 }
655
656 /**
657 * Replies true if this way has incomplete nodes, false otherwise.
658 * @return true if this way has incomplete nodes, false otherwise.
659 * @since 2587
660 */
661 public boolean hasIncompleteNodes() {
662 Node[] nodes = this.nodes;
663 for (Node node : nodes) {
664 if (node.isIncomplete())
665 return true;
666 }
667 return false;
668 }
669
670 @Override
671 public boolean isUsable() {
672 return super.isUsable() && !hasIncompleteNodes();
673 }
674
675 @Override
676 public boolean isDrawable() {
677 return super.isDrawable() && !hasIncompleteNodes();
678 }
679
680 /**
681 * Replies the length of the way, in metres, as computed by {@link LatLon#greatCircleDistance}.
682 * @return The length of the way, in metres
683 * @since 4138
684 */
685 public double getLength() {
686 double length = 0;
687 Node lastN = null;
688 for (Node n:nodes) {
689 if (lastN != null) {
690 LatLon lastNcoor = lastN.getCoor();
691 LatLon coor = n.getCoor();
692 if (lastNcoor != null && coor != null) {
693 length += coor.greatCircleDistance(lastNcoor);
694 }
695 }
696 lastN = n;
697 }
698 return length;
699 }
700
701 /**
702 * Replies the length of the longest segment of the way, in metres, as computed by {@link LatLon#greatCircleDistance}.
703 * @return The length of the segment, in metres
704 * @since 8320
705 */
706 public double getLongestSegmentLength() {
707 double length = 0;
708 Node lastN = null;
709 for (Node n:nodes) {
710 if (lastN != null) {
711 LatLon lastNcoor = lastN.getCoor();
712 LatLon coor = n.getCoor();
713 if (lastNcoor != null && coor != null) {
714 double l = coor.greatCircleDistance(lastNcoor);
715 if (l > length) {
716 length = l;
717 }
718 }
719 }
720 lastN = n;
721 }
722 return length;
723 }
724
725 /**
726 * Tests if this way is a oneway.
727 * @return {@code 1} if the way is a oneway,
728 * {@code -1} if the way is a reversed oneway,
729 * {@code 0} otherwise.
730 * @since 5199
731 */
732 public int isOneway() {
733 String oneway = get("oneway");
734 if (oneway != null) {
735 if ("-1".equals(oneway)) {
736 return -1;
737 } else {
738 Boolean isOneway = OsmUtils.getOsmBoolean(oneway);
739 if (isOneway != null && isOneway) {
740 return 1;
741 }
742 }
743 }
744 return 0;
745 }
746
747 /**
748 * Replies the first node of this way, respecting or not its oneway state.
749 * @param respectOneway If true and if this way is a reversed oneway, replies the last node. Otherwise, replies the first node.
750 * @return the first node of this way, according to {@code respectOneway} and its oneway state.
751 * @since 5199
752 */
753 public Node firstNode(boolean respectOneway) {
754 return !respectOneway || isOneway() != -1 ? firstNode() : lastNode();
755 }
756
757 /**
758 * Replies the last node of this way, respecting or not its oneway state.
759 * @param respectOneway If true and if this way is a reversed oneway, replies the first node. Otherwise, replies the last node.
760 * @return the last node of this way, according to {@code respectOneway} and its oneway state.
761 * @since 5199
762 */
763 public Node lastNode(boolean respectOneway) {
764 return !respectOneway || isOneway() != -1 ? lastNode() : firstNode();
765 }
766
767 @Override
768 public boolean concernsArea() {
769 return hasAreaTags();
770 }
771
772 @Override
773 public boolean isOutsideDownloadArea() {
774 for (final Node n : nodes) {
775 if (n.isOutsideDownloadArea()) {
776 return true;
777 }
778 }
779 return false;
780 }
781
782 @Override
783 protected void keysChangedImpl(Map<String, String> originalKeys) {
784 super.keysChangedImpl(originalKeys);
785 clearCachedNodeStyles();
786 }
787
788 /**
789 * Clears all cached styles for all nodes of this way. This should not be called from outside.
790 * @see Node#clearCachedStyle()
791 */
792 public void clearCachedNodeStyles() {
793 for (final Node n : nodes) {
794 n.clearCachedStyle();
795 }
796 }
797}
Note: See TracBrowser for help on using the repository browser.