source: josm/trunk/src/org/openstreetmap/josm/actions/JoinAreasAction.java@ 7012

Last change on this file since 7012 was 7005, checked in by Don-vip, 10 years ago

see #8465 - use diamond operator where applicable

  • Property svn:eol-style set to native
File size: 50.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.HashSet;
15import java.util.LinkedHashSet;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.Set;
20import java.util.TreeMap;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.actions.ReverseWayAction.ReverseWayResult;
26import org.openstreetmap.josm.actions.SplitWayAction.SplitWayResult;
27import org.openstreetmap.josm.command.AddCommand;
28import org.openstreetmap.josm.command.ChangeCommand;
29import org.openstreetmap.josm.command.Command;
30import org.openstreetmap.josm.command.DeleteCommand;
31import org.openstreetmap.josm.command.SequenceCommand;
32import org.openstreetmap.josm.corrector.UserCancelException;
33import org.openstreetmap.josm.data.UndoRedoHandler;
34import org.openstreetmap.josm.data.coor.EastNorth;
35import org.openstreetmap.josm.data.osm.DataSet;
36import org.openstreetmap.josm.data.osm.Node;
37import org.openstreetmap.josm.data.osm.NodePositionComparator;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.osm.Relation;
40import org.openstreetmap.josm.data.osm.RelationMember;
41import org.openstreetmap.josm.data.osm.TagCollection;
42import org.openstreetmap.josm.data.osm.Way;
43import org.openstreetmap.josm.gui.Notification;
44import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
45import org.openstreetmap.josm.tools.Geometry;
46import org.openstreetmap.josm.tools.Pair;
47import org.openstreetmap.josm.tools.Shortcut;
48
49/**
50 * Join Areas (i.e. closed ways and multipolygons)
51 */
52public class JoinAreasAction extends JosmAction {
53 // This will be used to commit commands and unite them into one large command sequence at the end
54 private final LinkedList<Command> cmds = new LinkedList<>();
55 private int cmdsCount = 0;
56 private final List<Relation> addedRelations = new LinkedList<>();
57
58 /**
59 * This helper class describes join ares action result.
60 * @author viesturs
61 *
62 */
63 public static class JoinAreasResult {
64
65 public boolean hasChanges;
66
67 public List<Multipolygon> polygons;
68 }
69
70 public static class Multipolygon {
71 public Way outerWay;
72 public List<Way> innerWays;
73
74 public Multipolygon(Way way) {
75 outerWay = way;
76 innerWays = new ArrayList<>();
77 }
78 }
79
80 // HelperClass
81 // Saves a relation and a role an OsmPrimitve was part of until it was stripped from all relations
82 private static class RelationRole {
83 public final Relation rel;
84 public final String role;
85 public RelationRole(Relation rel, String role) {
86 this.rel = rel;
87 this.role = role;
88 }
89
90 @Override
91 public int hashCode() {
92 return rel.hashCode();
93 }
94
95 @Override
96 public boolean equals(Object other) {
97 if (!(other instanceof RelationRole)) return false;
98 RelationRole otherMember = (RelationRole) other;
99 return otherMember.role.equals(role) && otherMember.rel.equals(rel);
100 }
101 }
102
103
104 /**
105 * HelperClass - saves a way and the "inside" side.
106 *
107 * insideToTheLeft: if true left side is "in", false -right side is "in".
108 * Left and right are determined along the orientation of way.
109 */
110 public static class WayInPolygon {
111 public final Way way;
112 public boolean insideToTheRight;
113
114 public WayInPolygon(Way way, boolean insideRight) {
115 this.way = way;
116 this.insideToTheRight = insideRight;
117 }
118
119 @Override
120 public int hashCode() {
121 return way.hashCode();
122 }
123
124 @Override
125 public boolean equals(Object other) {
126 if (!(other instanceof WayInPolygon)) return false;
127 WayInPolygon otherMember = (WayInPolygon) other;
128 return otherMember.way.equals(this.way) && otherMember.insideToTheRight == this.insideToTheRight;
129 }
130 }
131
132 /**
133 * This helper class describes a polygon, assembled from several ways.
134 * @author viesturs
135 *
136 */
137 public static class AssembledPolygon {
138 public List<WayInPolygon> ways;
139
140 public AssembledPolygon(List<WayInPolygon> boundary) {
141 this.ways = boundary;
142 }
143
144 public List<Node> getNodes() {
145 List<Node> nodes = new ArrayList<>();
146 for (WayInPolygon way : this.ways) {
147 //do not add the last node as it will be repeated in the next way
148 if (way.insideToTheRight) {
149 for (int pos = 0; pos < way.way.getNodesCount() - 1; pos++) {
150 nodes.add(way.way.getNode(pos));
151 }
152 }
153 else {
154 for (int pos = way.way.getNodesCount() - 1; pos > 0; pos--) {
155 nodes.add(way.way.getNode(pos));
156 }
157 }
158 }
159
160 return nodes;
161 }
162
163 /**
164 * Inverse inside and outside
165 */
166 public void reverse() {
167 for(WayInPolygon way: ways)
168 way.insideToTheRight = !way.insideToTheRight;
169 Collections.reverse(ways);
170 }
171 }
172
173 public static class AssembledMultipolygon {
174 public AssembledPolygon outerWay;
175 public List<AssembledPolygon> innerWays;
176
177 public AssembledMultipolygon(AssembledPolygon way) {
178 outerWay = way;
179 innerWays = new ArrayList<>();
180 }
181 }
182
183 /**
184 * This hepler class implements algorithm traversing trough connected ways.
185 * Assumes you are going in clockwise orientation.
186 * @author viesturs
187 *
188 */
189 private static class WayTraverser {
190
191 private Set<WayInPolygon> availableWays;
192 private WayInPolygon lastWay;
193 private boolean lastWayReverse;
194
195 public WayTraverser(Collection<WayInPolygon> ways) {
196
197 availableWays = new HashSet<>(ways);
198 lastWay = null;
199 }
200
201 public void removeWays(Collection<WayInPolygon> ways) {
202 availableWays.removeAll(ways);
203 }
204
205 public void removeWay(WayInPolygon way) {
206 availableWays.remove(way);
207 }
208
209 public void setStartWay(WayInPolygon way) {
210 lastWay = way;
211 lastWayReverse = !way.insideToTheRight;
212 }
213
214 public WayInPolygon startNewWay() {
215 if (availableWays.isEmpty()) {
216 lastWay = null;
217 } else {
218 lastWay = availableWays.iterator().next();
219 lastWayReverse = !lastWay.insideToTheRight;
220 }
221
222 return lastWay;
223 }
224
225 /**
226 * Get the next way creating a clockwise path, ensure it is the most right way. #7959
227 * @return The next way.
228 */
229 public WayInPolygon walk() {
230 Node headNode = !lastWayReverse ? lastWay.way.lastNode() : lastWay.way.firstNode();
231 Node prevNode = !lastWayReverse ? lastWay.way.getNode(lastWay.way.getNodesCount() - 2) : lastWay.way.getNode(1);
232
233 double headAngle = Math.atan2(headNode.getEastNorth().east() - prevNode.getEastNorth().east(),
234 headNode.getEastNorth().north() - prevNode.getEastNorth().north());
235 double bestAngle = 0;
236
237 //find best next way
238 WayInPolygon bestWay = null;
239 boolean bestWayReverse = false;
240
241 for (WayInPolygon way : availableWays) {
242 Node nextNode;
243
244 // Check for a connected way
245 if (way.way.firstNode().equals(headNode) && way.insideToTheRight) {
246 nextNode = way.way.getNode(1);
247 } else if (way.way.lastNode().equals(headNode) && !way.insideToTheRight) {
248 nextNode = way.way.getNode(way.way.getNodesCount() - 2);
249 } else {
250 continue;
251 }
252
253 if(nextNode == prevNode) {
254 // go back
255 lastWay = way;
256 lastWayReverse = !way.insideToTheRight;
257 return lastWay;
258 }
259
260 double angle = Math.atan2(nextNode.getEastNorth().east() - headNode.getEastNorth().east(),
261 nextNode.getEastNorth().north() - headNode.getEastNorth().north()) - headAngle;
262 if(angle > Math.PI)
263 angle -= 2*Math.PI;
264 if(angle <= -Math.PI)
265 angle += 2*Math.PI;
266
267 // Now we have a valid candidate way, is it better than the previous one ?
268 if (bestWay == null || angle > bestAngle) {
269 //the new way is better
270 bestWay = way;
271 bestWayReverse = !way.insideToTheRight;
272 bestAngle = angle;
273 }
274 }
275
276 lastWay = bestWay;
277 lastWayReverse = bestWayReverse;
278
279 return lastWay;
280 }
281 }
282
283 /**
284 * Helper storage class for finding findOuterWays
285 * @author viesturs
286 */
287 static class PolygonLevel {
288 public final int level;
289 public final AssembledMultipolygon pol;
290
291 public PolygonLevel(AssembledMultipolygon pol, int level) {
292 this.pol = pol;
293 this.level = level;
294 }
295 }
296
297 /**
298 * Constructs a new {@code JoinAreasAction}.
299 */
300 public JoinAreasAction() {
301 super(tr("Join overlapping Areas"), "joinareas", tr("Joins areas that overlap each other"),
302 Shortcut.registerShortcut("tools:joinareas", tr("Tool: {0}", tr("Join overlapping Areas")),
303 KeyEvent.VK_J, Shortcut.SHIFT), true);
304 }
305
306 /**
307 * Gets called whenever the shortcut is pressed or the menu entry is selected
308 * Checks whether the selected objects are suitable to join and joins them if so
309 */
310 @Override
311 public void actionPerformed(ActionEvent e) {
312 LinkedList<Way> ways = new LinkedList<>(Main.main.getCurrentDataSet().getSelectedWays());
313 addedRelations.clear();
314
315 if (ways.isEmpty()) {
316 new Notification(
317 tr("Please select at least one closed way that should be joined."))
318 .setIcon(JOptionPane.INFORMATION_MESSAGE)
319 .show();
320 return;
321 }
322
323 List<Node> allNodes = new ArrayList<>();
324 for (Way way : ways) {
325 if (!way.isClosed()) {
326 new Notification(
327 tr("One of the selected ways is not closed and therefore cannot be joined."))
328 .setIcon(JOptionPane.INFORMATION_MESSAGE)
329 .show();
330 return;
331 }
332
333 allNodes.addAll(way.getNodes());
334 }
335
336 // TODO: Only display this warning when nodes outside dataSourceArea are deleted
337 boolean ok = Command.checkAndConfirmOutlyingOperation("joinarea", tr("Join area confirmation"),
338 trn("The selected way has nodes outside of the downloaded data region.",
339 "The selected ways have nodes outside of the downloaded data region.",
340 ways.size()) + "<br/>"
341 + tr("This can lead to nodes being deleted accidentally.") + "<br/>"
342 + tr("Are you really sure to continue?")
343 + tr("Please abort if you are not sure"),
344 tr("The selected area is incomplete. Continue?"),
345 allNodes, null);
346 if(!ok) return;
347
348 //analyze multipolygon relations and collect all areas
349 List<Multipolygon> areas = collectMultipolygons(ways);
350
351 if (areas == null)
352 //too complex multipolygon relations found
353 return;
354
355 if (!testJoin(areas)) {
356 new Notification(
357 tr("No intersection found. Nothing was changed."))
358 .setIcon(JOptionPane.INFORMATION_MESSAGE)
359 .show();
360 return;
361 }
362
363 if (!resolveTagConflicts(areas))
364 return;
365 //user canceled, do nothing.
366
367 try {
368 JoinAreasResult result = joinAreas(areas);
369
370 if (result.hasChanges) {
371 // move tags from ways to newly created relations
372 // TODO: do we need to also move tags for the modified relations?
373 for (Relation r: addedRelations) {
374 cmds.addAll(CreateMultipolygonAction.removeTagsFromWaysIfNeeded(r));
375 }
376 commitCommands(tr("Move tags from ways to relations"));
377
378 List<Way> allWays = new ArrayList<>();
379 for (Multipolygon pol : result.polygons) {
380 allWays.add(pol.outerWay);
381 allWays.addAll(pol.innerWays);
382 }
383 DataSet ds = Main.main.getCurrentDataSet();
384 ds.setSelected(allWays);
385 Main.map.mapView.repaint();
386 } else {
387 new Notification(
388 tr("No intersection found. Nothing was changed."))
389 .setIcon(JOptionPane.INFORMATION_MESSAGE)
390 .show();
391 }
392 }
393 catch (UserCancelException exception) {
394 //revert changes
395 //FIXME: this is dirty hack
396 makeCommitsOneAction(tr("Reverting changes"));
397 Main.main.undoRedo.undo();
398 Main.main.undoRedo.redoCommands.clear();
399 }
400 }
401
402 /**
403 * Tests if the areas have some intersections to join.
404 * @param areas Areas to test
405 * @return {@code true} if areas are joinable
406 */
407 private boolean testJoin(List<Multipolygon> areas) {
408 List<Way> allStartingWays = new ArrayList<>();
409
410 for (Multipolygon area : areas) {
411 allStartingWays.add(area.outerWay);
412 allStartingWays.addAll(area.innerWays);
413 }
414
415 //find intersection points
416 Set<Node> nodes = Geometry.addIntersections(allStartingWays, true, cmds);
417 return !nodes.isEmpty();
418 }
419
420 /**
421 * Will join two or more overlapping areas
422 * @param areas list of areas to join
423 * @return new area formed.
424 */
425 private JoinAreasResult joinAreas(List<Multipolygon> areas) throws UserCancelException {
426
427 JoinAreasResult result = new JoinAreasResult();
428 result.hasChanges = false;
429
430 List<Way> allStartingWays = new ArrayList<>();
431 List<Way> innerStartingWays = new ArrayList<>();
432 List<Way> outerStartingWays = new ArrayList<>();
433
434 for (Multipolygon area : areas) {
435 outerStartingWays.add(area.outerWay);
436 innerStartingWays.addAll(area.innerWays);
437 }
438
439 allStartingWays.addAll(innerStartingWays);
440 allStartingWays.addAll(outerStartingWays);
441
442 //first remove nodes in the same coordinate
443 boolean removedDuplicates = false;
444 removedDuplicates |= removeDuplicateNodes(allStartingWays);
445
446 if (removedDuplicates) {
447 result.hasChanges = true;
448 commitCommands(marktr("Removed duplicate nodes"));
449 }
450
451 //find intersection points
452 Set<Node> nodes = Geometry.addIntersections(allStartingWays, false, cmds);
453
454 //no intersections, return.
455 if (nodes.isEmpty())
456 return result;
457 commitCommands(marktr("Added node on all intersections"));
458
459 List<RelationRole> relations = new ArrayList<>();
460
461 // Remove ways from all relations so ways can be combined/split quietly
462 for (Way way : allStartingWays) {
463 relations.addAll(removeFromAllRelations(way));
464 }
465
466 // Don't warn now, because it will really look corrupted
467 boolean warnAboutRelations = !relations.isEmpty() && allStartingWays.size() > 1;
468
469 List<WayInPolygon> preparedWays = new ArrayList<>();
470
471 for (Way way : outerStartingWays) {
472 List<Way> splitWays = splitWayOnNodes(way, nodes);
473 preparedWays.addAll(markWayInsideSide(splitWays, false));
474 }
475
476 for (Way way : innerStartingWays) {
477 List<Way> splitWays = splitWayOnNodes(way, nodes);
478 preparedWays.addAll(markWayInsideSide(splitWays, true));
479 }
480
481 // Find boundary ways
482 List<Way> discardedWays = new ArrayList<>();
483 List<AssembledPolygon> bounadries = findBoundaryPolygons(preparedWays, discardedWays);
484
485 //find polygons
486 List<AssembledMultipolygon> preparedPolygons = findPolygons(bounadries);
487
488
489 //assemble final polygons
490 List<Multipolygon> polygons = new ArrayList<>();
491 Set<Relation> relationsToDelete = new LinkedHashSet<>();
492
493 for (AssembledMultipolygon pol : preparedPolygons) {
494
495 //create the new ways
496 Multipolygon resultPol = joinPolygon(pol);
497
498 //create multipolygon relation, if necessary.
499 RelationRole ownMultipolygonRelation = addOwnMultigonRelation(resultPol.innerWays, resultPol.outerWay);
500
501 //add back the original relations, merged with our new multipolygon relation
502 fixRelations(relations, resultPol.outerWay, ownMultipolygonRelation, relationsToDelete);
503
504 //strip tags from inner ways
505 //TODO: preserve tags on existing inner ways
506 stripTags(resultPol.innerWays);
507
508 polygons.add(resultPol);
509 }
510
511 commitCommands(marktr("Assemble new polygons"));
512
513 for(Relation rel: relationsToDelete) {
514 cmds.add(new DeleteCommand(rel));
515 }
516
517 commitCommands(marktr("Delete relations"));
518
519 // Delete the discarded inner ways
520 if (!discardedWays.isEmpty()) {
521 Command deleteCmd = DeleteCommand.delete(Main.main.getEditLayer(), discardedWays, true);
522 if (deleteCmd != null) {
523 cmds.add(deleteCmd);
524 commitCommands(marktr("Delete Ways that are not part of an inner multipolygon"));
525 }
526 }
527
528 makeCommitsOneAction(marktr("Joined overlapping areas"));
529
530 if (warnAboutRelations) {
531 new Notification(
532 tr("Some of the ways were part of relations that have been modified.<br>Please verify no errors have been introduced."))
533 .setIcon(JOptionPane.INFORMATION_MESSAGE)
534 .setDuration(Notification.TIME_LONG)
535 .show();
536 }
537
538 result.hasChanges = true;
539 result.polygons = polygons;
540 return result;
541 }
542
543 /**
544 * Checks if tags of two given ways differ, and presents the user a dialog to solve conflicts
545 * @param polygons ways to check
546 * @return {@code true} if all conflicts are resolved, {@code false} if conflicts remain.
547 */
548 private boolean resolveTagConflicts(List<Multipolygon> polygons) {
549
550 List<Way> ways = new ArrayList<>();
551
552 for (Multipolygon pol : polygons) {
553 ways.add(pol.outerWay);
554 ways.addAll(pol.innerWays);
555 }
556
557 if (ways.size() < 2) {
558 return true;
559 }
560
561 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
562 try {
563 cmds.addAll(CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, ways));
564 commitCommands(marktr("Fix tag conflicts"));
565 return true;
566 } catch (UserCancelException ex) {
567 return false;
568 }
569 }
570
571 /**
572 * This method removes duplicate points (if any) from the input way.
573 * @param ways the ways to process
574 * @return {@code true} if any changes where made
575 */
576 private boolean removeDuplicateNodes(List<Way> ways) {
577 //TODO: maybe join nodes with JoinNodesAction, rather than reconnect the ways.
578
579 Map<Node, Node> nodeMap = new TreeMap<>(new NodePositionComparator());
580 int totalNodesRemoved = 0;
581
582 for (Way way : ways) {
583 if (way.getNodes().size() < 2) {
584 continue;
585 }
586
587 int nodesRemoved = 0;
588 List<Node> newNodes = new ArrayList<>();
589 Node prevNode = null;
590
591 for (Node node : way.getNodes()) {
592 if (!nodeMap.containsKey(node)) {
593 //new node
594 nodeMap.put(node, node);
595
596 //avoid duplicate nodes
597 if (prevNode != node) {
598 newNodes.add(node);
599 } else {
600 nodesRemoved ++;
601 }
602 } else {
603 //node with same coordinates already exists, substitute with existing node
604 Node representator = nodeMap.get(node);
605
606 if (representator != node) {
607 nodesRemoved ++;
608 }
609
610 //avoid duplicate node
611 if (prevNode != representator) {
612 newNodes.add(representator);
613 }
614 }
615 prevNode = node;
616 }
617
618 if (nodesRemoved > 0) {
619
620 if (newNodes.size() == 1) { //all nodes in the same coordinate - add one more node, to have closed way.
621 newNodes.add(newNodes.get(0));
622 }
623
624 Way newWay=new Way(way);
625 newWay.setNodes(newNodes);
626 cmds.add(new ChangeCommand(way, newWay));
627 totalNodesRemoved += nodesRemoved;
628 }
629 }
630
631 return totalNodesRemoved > 0;
632 }
633
634 /**
635 * Commits the command list with a description
636 * @param description The description of what the commands do
637 */
638 private void commitCommands(String description) {
639 switch(cmds.size()) {
640 case 0:
641 return;
642 case 1:
643 Main.main.undoRedo.add(cmds.getFirst());
644 break;
645 default:
646 Command c = new SequenceCommand(tr(description), cmds);
647 Main.main.undoRedo.add(c);
648 break;
649 }
650
651 cmds.clear();
652 cmdsCount++;
653 }
654
655 /**
656 * This method analyzes the way and assigns each part what direction polygon "inside" is.
657 * @param parts the split parts of the way
658 * @param isInner - if true, reverts the direction (for multipolygon islands)
659 * @return list of parts, marked with the inside orientation.
660 */
661 private List<WayInPolygon> markWayInsideSide(List<Way> parts, boolean isInner) {
662
663 List<WayInPolygon> result = new ArrayList<>();
664
665 //prepare prev and next maps
666 Map<Way, Way> nextWayMap = new HashMap<>();
667 Map<Way, Way> prevWayMap = new HashMap<>();
668
669 for (int pos = 0; pos < parts.size(); pos ++) {
670
671 if (!parts.get(pos).lastNode().equals(parts.get((pos + 1) % parts.size()).firstNode()))
672 throw new RuntimeException("Way not circular");
673
674 nextWayMap.put(parts.get(pos), parts.get((pos + 1) % parts.size()));
675 prevWayMap.put(parts.get(pos), parts.get((pos + parts.size() - 1) % parts.size()));
676 }
677
678 //find the node with minimum y - it's guaranteed to be outer. (What about the south pole?)
679 Way topWay = null;
680 Node topNode = null;
681 int topIndex = 0;
682 double minY = Double.POSITIVE_INFINITY;
683
684 for (Way way : parts) {
685 for (int pos = 0; pos < way.getNodesCount(); pos ++) {
686 Node node = way.getNode(pos);
687
688 if (node.getEastNorth().getY() < minY) {
689 minY = node.getEastNorth().getY();
690 topWay = way;
691 topNode = node;
692 topIndex = pos;
693 }
694 }
695 }
696
697 //get the upper way and it's orientation.
698
699 boolean wayClockwise; // orientation of the top way.
700
701 if (topNode.equals(topWay.firstNode()) || topNode.equals(topWay.lastNode())) {
702 Node headNode = null; // the node at junction
703 Node prevNode = null; // last node from previous path
704 wayClockwise = false;
705
706 //node is in split point - find the outermost way from this point
707
708 headNode = topNode;
709 //make a fake node that is downwards from head node (smaller Y). It will be a division point between paths.
710 prevNode = new Node(new EastNorth(headNode.getEastNorth().getX(), headNode.getEastNorth().getY() - 1e5));
711
712 topWay = null;
713 wayClockwise = false;
714 Node bestWayNextNode = null;
715
716 for (Way way : parts) {
717 if (way.firstNode().equals(headNode)) {
718 Node nextNode = way.getNode(1);
719
720 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
721 //the new way is better
722 topWay = way;
723 wayClockwise = true;
724 bestWayNextNode = nextNode;
725 }
726 }
727
728 if (way.lastNode().equals(headNode)) {
729 //end adjacent to headNode
730 Node nextNode = way.getNode(way.getNodesCount() - 2);
731
732 if (topWay == null || !Geometry.isToTheRightSideOfLine(prevNode, headNode, bestWayNextNode, nextNode)) {
733 //the new way is better
734 topWay = way;
735 wayClockwise = false;
736 bestWayNextNode = nextNode;
737 }
738 }
739 }
740 } else {
741 //node is inside way - pick the clockwise going end.
742 Node prev = topWay.getNode(topIndex - 1);
743 Node next = topWay.getNode(topIndex + 1);
744
745 //there will be no parallel segments in the middle of way, so all fine.
746 wayClockwise = Geometry.angleIsClockwise(prev, topNode, next);
747 }
748
749 Way curWay = topWay;
750 boolean curWayInsideToTheRight = wayClockwise ^ isInner;
751
752 //iterate till full circle is reached
753 while (true) {
754
755 //add cur way
756 WayInPolygon resultWay = new WayInPolygon(curWay, curWayInsideToTheRight);
757 result.add(resultWay);
758
759 //process next way
760 Way nextWay = nextWayMap.get(curWay);
761 Node prevNode = curWay.getNode(curWay.getNodesCount() - 2);
762 Node headNode = curWay.lastNode();
763 Node nextNode = nextWay.getNode(1);
764
765 if (nextWay == topWay) {
766 //full loop traversed - all done.
767 break;
768 }
769
770 //find intersecting segments
771 // the intersections will look like this:
772 //
773 // ^
774 // |
775 // X wayBNode
776 // |
777 // wayB |
778 // |
779 // curWay | nextWay
780 //----X----------------->X----------------------X---->
781 // prevNode ^headNode nextNode
782 // |
783 // |
784 // wayA |
785 // |
786 // X wayANode
787 // |
788
789 int intersectionCount = 0;
790
791 for (Way wayA : parts) {
792
793 if (wayA == curWay) {
794 continue;
795 }
796
797 if (wayA.lastNode().equals(headNode)) {
798
799 Way wayB = nextWayMap.get(wayA);
800
801 //test if wayA is opposite wayB relative to curWay and nextWay
802
803 Node wayANode = wayA.getNode(wayA.getNodesCount() - 2);
804 Node wayBNode = wayB.getNode(1);
805
806 boolean wayAToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayANode);
807 boolean wayBToTheRight = Geometry.isToTheRightSideOfLine(prevNode, headNode, nextNode, wayBNode);
808
809 if (wayAToTheRight != wayBToTheRight) {
810 intersectionCount ++;
811 }
812 }
813 }
814
815 //if odd number of crossings, invert orientation
816 if (intersectionCount % 2 != 0) {
817 curWayInsideToTheRight = !curWayInsideToTheRight;
818 }
819
820 curWay = nextWay;
821 }
822
823 return result;
824 }
825
826 /**
827 * This is a method splits way into smaller parts, using the prepared nodes list as split points.
828 * Uses SplitWayAction.splitWay for the heavy lifting.
829 * @return list of split ways (or original ways if no splitting is done).
830 */
831 private List<Way> splitWayOnNodes(Way way, Set<Node> nodes) {
832
833 List<Way> result = new ArrayList<>();
834 List<List<Node>> chunks = buildNodeChunks(way, nodes);
835
836 if (chunks.size() > 1) {
837 SplitWayResult split = SplitWayAction.splitWay(Main.main.getEditLayer(), way, chunks, Collections.<OsmPrimitive>emptyList());
838
839 //execute the command, we need the results
840 cmds.add(split.getCommand());
841 commitCommands(marktr("Split ways into fragments"));
842
843 result.add(split.getOriginalWay());
844 result.addAll(split.getNewWays());
845 } else {
846 //nothing to split
847 result.add(way);
848 }
849
850 return result;
851 }
852
853 /**
854 * Simple chunking version. Does not care about circular ways and result being
855 * proper, we will glue it all back together later on.
856 * @param way the way to chunk
857 * @param splitNodes the places where to cut.
858 * @return list of node paths to produce.
859 */
860 private List<List<Node>> buildNodeChunks(Way way, Collection<Node> splitNodes) {
861 List<List<Node>> result = new ArrayList<>();
862 List<Node> curList = new ArrayList<>();
863
864 for (Node node : way.getNodes()) {
865 curList.add(node);
866 if (curList.size() > 1 && splitNodes.contains(node)) {
867 result.add(curList);
868 curList = new ArrayList<>();
869 curList.add(node);
870 }
871 }
872
873 if (curList.size() > 1) {
874 result.add(curList);
875 }
876
877 return result;
878 }
879
880 /**
881 * This method finds which ways are outer and which are inner.
882 * @param boundaries list of joined boundaries to search in
883 * @return outer ways
884 */
885 private List<AssembledMultipolygon> findPolygons(Collection<AssembledPolygon> boundaries) {
886
887 List<PolygonLevel> list = findOuterWaysImpl(0, boundaries);
888 List<AssembledMultipolygon> result = new ArrayList<>();
889
890 //take every other level
891 for (PolygonLevel pol : list) {
892 if (pol.level % 2 == 0) {
893 result.add(pol.pol);
894 }
895 }
896
897 return result;
898 }
899
900 /**
901 * Collects outer way and corresponding inner ways from all boundaries.
902 * @param level depth level
903 * @param boundaryWays
904 * @return the outermostWay.
905 */
906 private List<PolygonLevel> findOuterWaysImpl(int level, Collection<AssembledPolygon> boundaryWays) {
907
908 //TODO: bad performance for deep nestings...
909 List<PolygonLevel> result = new ArrayList<>();
910
911 for (AssembledPolygon outerWay : boundaryWays) {
912
913 boolean outerGood = true;
914 List<AssembledPolygon> innerCandidates = new ArrayList<>();
915
916 for (AssembledPolygon innerWay : boundaryWays) {
917 if (innerWay == outerWay) {
918 continue;
919 }
920
921 if (wayInsideWay(outerWay, innerWay)) {
922 outerGood = false;
923 break;
924 } else if (wayInsideWay(innerWay, outerWay)) {
925 innerCandidates.add(innerWay);
926 }
927 }
928
929 if (!outerGood) {
930 continue;
931 }
932
933 //add new outer polygon
934 AssembledMultipolygon pol = new AssembledMultipolygon(outerWay);
935 PolygonLevel polLev = new PolygonLevel(pol, level);
936
937 //process inner ways
938 if (!innerCandidates.isEmpty()) {
939 List<PolygonLevel> innerList = findOuterWaysImpl(level + 1, innerCandidates);
940 result.addAll(innerList);
941
942 for (PolygonLevel pl : innerList) {
943 if (pl.level == level + 1) {
944 pol.innerWays.add(pl.pol.outerWay);
945 }
946 }
947 }
948
949 result.add(polLev);
950 }
951
952 return result;
953 }
954
955 /**
956 * Finds all ways that form inner or outer boundaries.
957 * @param multigonWays A list of (splitted) ways that form a multigon and share common end nodes on intersections.
958 * @param discardedResult this list is filled with ways that are to be discarded
959 * @return A list of ways that form the outer and inner boundaries of the multigon.
960 */
961 public static List<AssembledPolygon> findBoundaryPolygons(Collection<WayInPolygon> multigonWays, List<Way> discardedResult) {
962 //first find all discardable ways, by getting outer shells.
963 //this will produce incorrect boundaries in some cases, but second pass will fix it.
964 List<WayInPolygon> discardedWays = new ArrayList<>();
965
966 // In multigonWays collection, some way are just a point (i.e. way like nodeA-nodeA)
967 // This seems to appear when is apply over invalid way like #9911 test-case
968 // Remove all of these way to make the next work.
969 ArrayList<WayInPolygon> cleanMultigonWays = new ArrayList<>();
970 for(WayInPolygon way: multigonWays)
971 if(way.way.getNodesCount() == 2 && way.way.firstNode() == way.way.lastNode())
972 discardedWays.add(way);
973 else
974 cleanMultigonWays.add(way);
975
976 WayTraverser traverser = new WayTraverser(cleanMultigonWays);
977 List<AssembledPolygon> result = new ArrayList<>();
978
979 WayInPolygon startWay;
980 while((startWay = traverser.startNewWay()) != null) {
981 ArrayList<WayInPolygon> path = new ArrayList<>();
982 path.add(startWay);
983 while(true) {
984 WayInPolygon nextWay = traverser.walk();
985 if(nextWay == null)
986 throw new RuntimeException("Join areas internal error.");
987 if(path.get(0) == nextWay) {
988 AssembledPolygon ring = new AssembledPolygon(path);
989 if(ring.getNodes().size() <= 2) {
990 // Invalid ring (2 nodes) -> remove
991 traverser.removeWays(path);
992 for(WayInPolygon way: path)
993 discardedResult.add(way.way);
994 } else {
995 // Close ring -> add
996 result.add(ring);
997 traverser.removeWays(path);
998 }
999 break;
1000 }
1001 if(path.contains(nextWay)) {
1002 // Inner loop -> remove
1003 int index = path.indexOf(nextWay);
1004 while(path.size() > index) {
1005 WayInPolygon currentWay = path.get(index);
1006 discardedResult.add(currentWay.way);
1007 traverser.removeWay(currentWay);
1008 path.remove(index);
1009 }
1010 traverser.setStartWay(path.get(index-1));
1011 } else {
1012 path.add(nextWay);
1013 }
1014 }
1015 }
1016
1017 return fixTouchingPolygons(result);
1018 }
1019
1020 /**
1021 * This method checks if polygons have several touching parts and splits them in several polygons.
1022 * @param polygons the polygons to process.
1023 */
1024 public static List<AssembledPolygon> fixTouchingPolygons(List<AssembledPolygon> polygons) {
1025 List<AssembledPolygon> newPolygons = new ArrayList<>();
1026
1027 for (AssembledPolygon ring : polygons) {
1028 ring.reverse();
1029 WayTraverser traverser = new WayTraverser(ring.ways);
1030 WayInPolygon startWay;
1031
1032 while((startWay = traverser.startNewWay()) != null) {
1033 List<WayInPolygon> simpleRingWays = new ArrayList<>();
1034 simpleRingWays.add(startWay);
1035 WayInPolygon nextWay;
1036 while((nextWay = traverser.walk()) != startWay) {
1037 if(nextWay == null)
1038 throw new RuntimeException("Join areas internal error.");
1039 simpleRingWays.add(nextWay);
1040 }
1041 traverser.removeWays(simpleRingWays);
1042 AssembledPolygon simpleRing = new AssembledPolygon(simpleRingWays);
1043 simpleRing.reverse();
1044 newPolygons.add(simpleRing);
1045 }
1046 }
1047
1048 return newPolygons;
1049 }
1050
1051 /**
1052 * Tests if way is inside other way
1053 * @param outside outer polygon description
1054 * @param inside inner polygon description
1055 * @return {@code true} if inner is inside outer
1056 */
1057 public static boolean wayInsideWay(AssembledPolygon inside, AssembledPolygon outside) {
1058 Set<Node> outsideNodes = new HashSet<>(outside.getNodes());
1059 List<Node> insideNodes = inside.getNodes();
1060
1061 for (Node insideNode : insideNodes) {
1062
1063 if (!outsideNodes.contains(insideNode))
1064 //simply test the one node
1065 return Geometry.nodeInsidePolygon(insideNode, outside.getNodes());
1066 }
1067
1068 //all nodes shared.
1069 return false;
1070 }
1071
1072 /**
1073 * Joins the lists of ways.
1074 * @param polygon The list of outer ways that belong to that multigon.
1075 * @return The newly created outer way
1076 */
1077 private Multipolygon joinPolygon(AssembledMultipolygon polygon) throws UserCancelException {
1078 Multipolygon result = new Multipolygon(joinWays(polygon.outerWay.ways));
1079
1080 for (AssembledPolygon pol : polygon.innerWays) {
1081 result.innerWays.add(joinWays(pol.ways));
1082 }
1083
1084 return result;
1085 }
1086
1087 /**
1088 * Joins the outer ways and deletes all short ways that can't be part of a multipolygon anyway.
1089 * @param ways The list of outer ways that belong to that multigon.
1090 * @return The newly created outer way
1091 */
1092 private Way joinWays(List<WayInPolygon> ways) throws UserCancelException {
1093
1094 //leave original orientation, if all paths are reverse.
1095 boolean allReverse = true;
1096 for (WayInPolygon way : ways) {
1097 allReverse &= !way.insideToTheRight;
1098 }
1099
1100 if (allReverse) {
1101 for (WayInPolygon way : ways) {
1102 way.insideToTheRight = !way.insideToTheRight;
1103 }
1104 }
1105
1106 Way joinedWay = joinOrientedWays(ways);
1107
1108 //should not happen
1109 if (joinedWay == null || !joinedWay.isClosed())
1110 throw new RuntimeException("Join areas internal error.");
1111
1112 return joinedWay;
1113 }
1114
1115 /**
1116 * Joins a list of ways (using CombineWayAction and ReverseWayAction as specified in WayInPath)
1117 * @param ways The list of ways to join and reverse
1118 * @return The newly created way
1119 */
1120 private Way joinOrientedWays(List<WayInPolygon> ways) throws UserCancelException{
1121 if (ways.size() < 2)
1122 return ways.get(0).way;
1123
1124 // This will turn ways so all of them point in the same direction and CombineAction won't bug
1125 // the user about this.
1126
1127 //TODO: ReverseWay and Combine way are really slow and we use them a lot here. This slows down large joins.
1128 List<Way> actionWays = new ArrayList<>(ways.size());
1129
1130 for (WayInPolygon way : ways) {
1131 actionWays.add(way.way);
1132
1133 if (!way.insideToTheRight) {
1134 ReverseWayResult res = ReverseWayAction.reverseWay(way.way);
1135 Main.main.undoRedo.add(res.getReverseCommand());
1136 cmdsCount++;
1137 }
1138 }
1139
1140 Pair<Way, Command> result = CombineWayAction.combineWaysWorker(actionWays);
1141
1142 Main.main.undoRedo.add(result.b);
1143 cmdsCount ++;
1144
1145 return result.a;
1146 }
1147
1148 /**
1149 * This method analyzes multipolygon relationships of given ways and collects addition inner ways to consider.
1150 * @param selectedWays the selected ways
1151 * @return list of polygons, or null if too complex relation encountered.
1152 */
1153 private List<Multipolygon> collectMultipolygons(List<Way> selectedWays) {
1154
1155 List<Multipolygon> result = new ArrayList<>();
1156
1157 //prepare the lists, to minimize memory allocation.
1158 List<Way> outerWays = new ArrayList<>();
1159 List<Way> innerWays = new ArrayList<>();
1160
1161 Set<Way> processedOuterWays = new LinkedHashSet<>();
1162 Set<Way> processedInnerWays = new LinkedHashSet<>();
1163
1164 for (Relation r : OsmPrimitive.getParentRelations(selectedWays)) {
1165 if (r.isDeleted() || !r.isMultipolygon()) {
1166 continue;
1167 }
1168
1169 boolean hasKnownOuter = false;
1170 outerWays.clear();
1171 innerWays.clear();
1172
1173 for (RelationMember rm : r.getMembers()) {
1174 if (rm.getRole().equalsIgnoreCase("outer")) {
1175 outerWays.add(rm.getWay());
1176 hasKnownOuter |= selectedWays.contains(rm.getWay());
1177 }
1178 else if (rm.getRole().equalsIgnoreCase("inner")) {
1179 innerWays.add(rm.getWay());
1180 }
1181 }
1182
1183 if (!hasKnownOuter) {
1184 continue;
1185 }
1186
1187 if (outerWays.size() > 1) {
1188 new Notification(
1189 tr("Sorry. Cannot handle multipolygon relations with multiple outer ways."))
1190 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1191 .show();
1192 return null;
1193 }
1194
1195 Way outerWay = outerWays.get(0);
1196
1197 //retain only selected inner ways
1198 innerWays.retainAll(selectedWays);
1199
1200 if (processedOuterWays.contains(outerWay)) {
1201 new Notification(
1202 tr("Sorry. Cannot handle way that is outer in multiple multipolygon relations."))
1203 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1204 .show();
1205 return null;
1206 }
1207
1208 if (processedInnerWays.contains(outerWay)) {
1209 new Notification(
1210 tr("Sorry. Cannot handle way that is both inner and outer in multipolygon relations."))
1211 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1212 .show();
1213 return null;
1214 }
1215
1216 for (Way way :innerWays)
1217 {
1218 if (processedOuterWays.contains(way)) {
1219 new Notification(
1220 tr("Sorry. Cannot handle way that is both inner and outer in multipolygon relations."))
1221 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1222 .show();
1223 return null;
1224 }
1225
1226 if (processedInnerWays.contains(way)) {
1227 new Notification(
1228 tr("Sorry. Cannot handle way that is inner in multiple multipolygon relations."))
1229 .setIcon(JOptionPane.INFORMATION_MESSAGE)
1230 .show();
1231 return null;
1232 }
1233 }
1234
1235 processedOuterWays.add(outerWay);
1236 processedInnerWays.addAll(innerWays);
1237
1238 Multipolygon pol = new Multipolygon(outerWay);
1239 pol.innerWays.addAll(innerWays);
1240
1241 result.add(pol);
1242 }
1243
1244 //add remaining ways, not in relations
1245 for (Way way : selectedWays) {
1246 if (processedOuterWays.contains(way) || processedInnerWays.contains(way)) {
1247 continue;
1248 }
1249
1250 result.add(new Multipolygon(way));
1251 }
1252
1253 return result;
1254 }
1255
1256 /**
1257 * Will add own multipolygon relation to the "previously existing" relations. Fixup is done by fixRelations
1258 * @param inner List of already closed inner ways
1259 * @param outer The outer way
1260 * @return The list of relation with roles to add own relation to
1261 */
1262 private RelationRole addOwnMultigonRelation(Collection<Way> inner, Way outer) {
1263 if (inner.isEmpty()) return null;
1264 // Create new multipolygon relation and add all inner ways to it
1265 Relation newRel = new Relation();
1266 newRel.put("type", "multipolygon");
1267 for (Way w : inner) {
1268 newRel.addMember(new RelationMember("inner", w));
1269 }
1270 cmds.add(new AddCommand(newRel));
1271 addedRelations.add(newRel);
1272
1273 // We don't add outer to the relation because it will be handed to fixRelations()
1274 // which will then do the remaining work.
1275 return new RelationRole(newRel, "outer");
1276 }
1277
1278 /**
1279 * Removes a given OsmPrimitive from all relations
1280 * @param osm Element to remove from all relations
1281 * @return List of relations with roles the primitives was part of
1282 */
1283 private List<RelationRole> removeFromAllRelations(OsmPrimitive osm) {
1284 List<RelationRole> result = new ArrayList<>();
1285
1286 for (Relation r : Main.main.getCurrentDataSet().getRelations()) {
1287 if (r.isDeleted()) {
1288 continue;
1289 }
1290 for (RelationMember rm : r.getMembers()) {
1291 if (rm.getMember() != osm) {
1292 continue;
1293 }
1294
1295 Relation newRel = new Relation(r);
1296 List<RelationMember> members = newRel.getMembers();
1297 members.remove(rm);
1298 newRel.setMembers(members);
1299
1300 cmds.add(new ChangeCommand(r, newRel));
1301 RelationRole saverel = new RelationRole(r, rm.getRole());
1302 if (!result.contains(saverel)) {
1303 result.add(saverel);
1304 }
1305 break;
1306 }
1307 }
1308
1309 commitCommands(marktr("Removed Element from Relations"));
1310 return result;
1311 }
1312
1313 /**
1314 * Adds the previously removed relations again to the outer way. If there are multiple multipolygon
1315 * relations where the joined areas were in "outer" role a new relation is created instead with all
1316 * members of both. This function depends on multigon relations to be valid already, it won't fix them.
1317 * @param rels List of relations with roles the (original) ways were part of
1318 * @param outer The newly created outer area/way
1319 * @param ownMultipol elements to directly add as outer
1320 * @param relationsToDelete set of relations to delete.
1321 */
1322 private void fixRelations(List<RelationRole> rels, Way outer, RelationRole ownMultipol, Set<Relation> relationsToDelete) {
1323 List<RelationRole> multiouters = new ArrayList<>();
1324
1325 if (ownMultipol != null) {
1326 multiouters.add(ownMultipol);
1327 }
1328
1329 for (RelationRole r : rels) {
1330 if (r.rel.isMultipolygon() && r.role.equalsIgnoreCase("outer")) {
1331 multiouters.add(r);
1332 continue;
1333 }
1334 // Add it back!
1335 Relation newRel = new Relation(r.rel);
1336 newRel.addMember(new RelationMember(r.role, outer));
1337 cmds.add(new ChangeCommand(r.rel, newRel));
1338 }
1339
1340 Relation newRel;
1341 switch (multiouters.size()) {
1342 case 0:
1343 return;
1344 case 1:
1345 // Found only one to be part of a multipolygon relation, so just add it back as well
1346 newRel = new Relation(multiouters.get(0).rel);
1347 newRel.addMember(new RelationMember(multiouters.get(0).role, outer));
1348 cmds.add(new ChangeCommand(multiouters.get(0).rel, newRel));
1349 return;
1350 default:
1351 // Create a new relation with all previous members and (Way)outer as outer.
1352 newRel = new Relation();
1353 for (RelationRole r : multiouters) {
1354 // Add members
1355 for (RelationMember rm : r.rel.getMembers())
1356 if (!newRel.getMembers().contains(rm)) {
1357 newRel.addMember(rm);
1358 }
1359 // Add tags
1360 for (String key : r.rel.keySet()) {
1361 newRel.put(key, r.rel.get(key));
1362 }
1363 // Delete old relation
1364 relationsToDelete.add(r.rel);
1365 }
1366 newRel.addMember(new RelationMember("outer", outer));
1367 cmds.add(new AddCommand(newRel));
1368 }
1369 }
1370
1371 /**
1372 * Remove all tags from the all the way
1373 * @param ways The List of Ways to remove all tags from
1374 */
1375 private void stripTags(Collection<Way> ways) {
1376 for (Way w : ways) {
1377 stripTags(w);
1378 }
1379 /* I18N: current action printed in status display */
1380 commitCommands(marktr("Remove tags from inner ways"));
1381 }
1382
1383 /**
1384 * Remove all tags from the way
1385 * @param x The Way to remove all tags from
1386 */
1387 private void stripTags(Way x) {
1388 Way y = new Way(x);
1389 for (String key : x.keySet()) {
1390 y.remove(key);
1391 }
1392 cmds.add(new ChangeCommand(x, y));
1393 }
1394
1395 /**
1396 * Takes the last cmdsCount actions back and combines them into a single action
1397 * (for when the user wants to undo the join action)
1398 * @param message The commit message to display
1399 */
1400 private void makeCommitsOneAction(String message) {
1401 UndoRedoHandler ur = Main.main.undoRedo;
1402 cmds.clear();
1403 int i = Math.max(ur.commands.size() - cmdsCount, 0);
1404 for (; i < ur.commands.size(); i++) {
1405 cmds.add(ur.commands.get(i));
1406 }
1407
1408 for (i = 0; i < cmds.size(); i++) {
1409 ur.undo();
1410 }
1411
1412 commitCommands(message == null ? marktr("Join Areas Function") : message);
1413 cmdsCount = 0;
1414 }
1415
1416 @Override
1417 protected void updateEnabledState() {
1418 if (getCurrentDataSet() == null) {
1419 setEnabled(false);
1420 } else {
1421 updateEnabledState(getCurrentDataSet().getSelected());
1422 }
1423 }
1424
1425 @Override
1426 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
1427 setEnabled(selection != null && !selection.isEmpty());
1428 }
1429}
Note: See TracBrowser for help on using the repository browser.