source: josm/trunk/src/org/openstreetmap/josm/actions/OrthogonalizeAction.java@ 8449

Last change on this file since 8449 was 8443, checked in by Don-vip, 9 years ago

remove extra whitespaces

  • Property svn:eol-style set to native
File size: 25.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.event.ActionEvent;
8import java.awt.event.KeyEvent;
9import java.util.ArrayList;
10import java.util.Arrays;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.HashMap;
14import java.util.HashSet;
15import java.util.Iterator;
16import java.util.LinkedList;
17import java.util.List;
18import java.util.Map;
19import java.util.Set;
20
21import javax.swing.JOptionPane;
22
23import org.openstreetmap.josm.Main;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.MoveCommand;
26import org.openstreetmap.josm.command.SequenceCommand;
27import org.openstreetmap.josm.data.coor.EastNorth;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.Way;
31import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
32import org.openstreetmap.josm.gui.Notification;
33import org.openstreetmap.josm.tools.Shortcut;
34
35/**
36 * Tools / Orthogonalize
37 *
38 * Align edges of a way so all angles are angles of 90 or 180 degrees.
39 * See USAGE String below.
40 */
41public final class OrthogonalizeAction extends JosmAction {
42 private static final String USAGE = tr(
43 "<h3>When one or more ways are selected, the shape is adjusted such, that all angles are 90 or 180 degrees.</h3>"+
44 "You can add two nodes to the selection. Then, the direction is fixed by these two reference nodes. "+
45 "(Afterwards, you can undo the movement for certain nodes:<br>"+
46 "Select them and press the shortcut for Orthogonalize / Undo. The default is Shift-Q.)");
47
48 /**
49 * Constructs a new {@code OrthogonalizeAction}.
50 */
51 public OrthogonalizeAction() {
52 super(tr("Orthogonalize Shape"),
53 "ortho",
54 tr("Move nodes so all angles are 90 or 180 degrees"),
55 Shortcut.registerShortcut("tools:orthogonalize", tr("Tool: {0}", tr("Orthogonalize Shape")),
56 KeyEvent.VK_Q,
57 Shortcut.DIRECT), true);
58 putValue("help", ht("/Action/OrthogonalizeShape"));
59 }
60
61 /**
62 * excepted deviation from an angle of 0, 90, 180, 360 degrees
63 * maximum value: 45 degrees
64 *
65 * Current policy is to except just everything, no matter how strange the result would be.
66 */
67 private static final double TOLERANCE1 = Math.toRadians(45.); // within a way
68 private static final double TOLERANCE2 = Math.toRadians(45.); // ways relative to each other
69
70 /**
71 * Remember movements, so the user can later undo it for certain nodes
72 */
73 private static final Map<Node, EastNorth> rememberMovements = new HashMap<>();
74
75 /**
76 * Undo the previous orthogonalization for certain nodes.
77 *
78 * This is useful, if the way shares nodes that you don't like to change, e.g. imports or
79 * work of another user.
80 *
81 * This action can be triggered by shortcut only.
82 */
83 public static class Undo extends JosmAction {
84 /**
85 * Constructor
86 */
87 public Undo() {
88 super(tr("Orthogonalize Shape / Undo"), "ortho",
89 tr("Undo orthogonalization for certain nodes"),
90 Shortcut.registerShortcut("tools:orthogonalizeUndo", tr("Tool: {0}", tr("Orthogonalize Shape / Undo")),
91 KeyEvent.VK_Q,
92 Shortcut.SHIFT),
93 true, "action/orthogonalize/undo", true);
94 }
95 @Override
96 public void actionPerformed(ActionEvent e) {
97 if (!isEnabled())
98 return;
99 final Collection<Command> commands = new LinkedList<>();
100 final Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
101 try {
102 for (OsmPrimitive p : sel) {
103 if (!(p instanceof Node)) throw new InvalidUserInputException();
104 Node n = (Node) p;
105 if (rememberMovements.containsKey(n)) {
106 EastNorth tmp = rememberMovements.get(n);
107 commands.add(new MoveCommand(n, -tmp.east(), -tmp.north()));
108 rememberMovements.remove(n);
109 }
110 }
111 if (!commands.isEmpty()) {
112 Main.main.undoRedo.add(new SequenceCommand(tr("Orthogonalize / Undo"), commands));
113 Main.map.repaint();
114 } else throw new InvalidUserInputException();
115 } catch (InvalidUserInputException ex) {
116 new Notification(
117 tr("Orthogonalize Shape / Undo<br>"+
118 "Please select nodes that were moved by the previous Orthogonalize Shape action!"))
119 .setIcon(JOptionPane.INFORMATION_MESSAGE)
120 .show();
121 }
122 }
123 }
124
125 @Override
126 public void actionPerformed(ActionEvent e) {
127 if (!isEnabled())
128 return;
129 if ("EPSG:4326".equals(Main.getProjection().toString())) {
130 String msg = tr("<html>You are using the EPSG:4326 projection which might lead<br>" +
131 "to undesirable results when doing rectangular alignments.<br>" +
132 "Change your projection to get rid of this warning.<br>" +
133 "Do you want to continue?</html>");
134 if (!ConditionalOptionPaneUtil.showConfirmationDialog(
135 "align_rectangular_4326",
136 Main.parent,
137 msg,
138 tr("Warning"),
139 JOptionPane.YES_NO_OPTION,
140 JOptionPane.QUESTION_MESSAGE,
141 JOptionPane.YES_OPTION))
142 return;
143 }
144
145 final List<Node> nodeList = new ArrayList<>();
146 final List<WayData> wayDataList = new ArrayList<>();
147 final Collection<OsmPrimitive> sel = getCurrentDataSet().getSelected();
148
149 try {
150 // collect nodes and ways from the selection
151 for (OsmPrimitive p : sel) {
152 if (p instanceof Node) {
153 nodeList.add((Node) p);
154 } else if (p instanceof Way) {
155 wayDataList.add(new WayData((Way) p));
156 } else
157 throw new InvalidUserInputException(tr("Selection must consist only of ways and nodes."));
158 }
159 if (wayDataList.isEmpty())
160 throw new InvalidUserInputException("usage");
161 else {
162 if (nodeList.size() == 2 || nodeList.isEmpty()) {
163 OrthogonalizeAction.rememberMovements.clear();
164 final Collection<Command> commands = new LinkedList<>();
165
166 if (nodeList.size() == 2) { // fixed direction
167 commands.addAll(orthogonalize(wayDataList, nodeList));
168 } else if (nodeList.isEmpty()) {
169 List<List<WayData>> groups = buildGroups(wayDataList);
170 for (List<WayData> g: groups) {
171 commands.addAll(orthogonalize(g, nodeList));
172 }
173 } else
174 throw new IllegalStateException();
175
176 Main.main.undoRedo.add(new SequenceCommand(tr("Orthogonalize"), commands));
177 Main.map.repaint();
178
179 } else
180 throw new InvalidUserInputException("usage");
181 }
182 } catch (InvalidUserInputException ex) {
183 String msg;
184 if ("usage".equals(ex.getMessage())) {
185 msg = "<h2>" + tr("Usage") + "</h2>" + USAGE;
186 } else {
187 msg = ex.getMessage() + "<br><hr><h2>" + tr("Usage") + "</h2>" + USAGE;
188 }
189 new Notification(msg)
190 .setIcon(JOptionPane.INFORMATION_MESSAGE)
191 .setDuration(Notification.TIME_VERY_LONG)
192 .show();
193 }
194 }
195
196 /**
197 * Collect groups of ways with common nodes in order to orthogonalize each group separately.
198 */
199 private static List<List<WayData>> buildGroups(List<WayData> wayDataList) {
200 List<List<WayData>> groups = new ArrayList<>();
201 Set<WayData> remaining = new HashSet<>(wayDataList);
202 while (!remaining.isEmpty()) {
203 List<WayData> group = new ArrayList<>();
204 groups.add(group);
205 Iterator<WayData> it = remaining.iterator();
206 WayData next = it.next();
207 it.remove();
208 extendGroupRec(group, next, new ArrayList<>(remaining));
209 remaining.removeAll(group);
210 }
211 return groups;
212 }
213
214 private static void extendGroupRec(List<WayData> group, WayData newGroupMember, List<WayData> remaining) {
215 group.add(newGroupMember);
216 for (int i = 0; i < remaining.size(); ++i) {
217 WayData candidate = remaining.get(i);
218 if (candidate == null) continue;
219 if (!Collections.disjoint(candidate.way.getNodes(), newGroupMember.way.getNodes())) {
220 remaining.set(i, null);
221 extendGroupRec(group, candidate, remaining);
222 }
223 }
224 }
225
226 /**
227 *
228 * Outline:
229 * 1. Find direction of all segments
230 * - direction = 0..3 (right,up,left,down)
231 * - right is not really right, you may have to turn your screen
232 * 2. Find average heading of all segments
233 * - heading = angle of a vector in polar coordinates
234 * - sum up horizontal segments (those with direction 0 or 2)
235 * - sum up vertical segments
236 * - turn the vertical sum by 90 degrees and add it to the horizontal sum
237 * - get the average heading from this total sum
238 * 3. Rotate all nodes by the average heading so that right is really right
239 * and all segments are approximately NS or EW.
240 * 4. If nodes are connected by a horizontal segment: Replace their y-Coordinate by
241 * the mean value of their y-Coordinates.
242 * - The same for vertical segments.
243 * 5. Rotate back.
244 *
245 **/
246 private static Collection<Command> orthogonalize(List<WayData> wayDataList, List<Node> headingNodes) throws InvalidUserInputException {
247 // find average heading
248 double headingAll;
249 try {
250 if (headingNodes.isEmpty()) {
251 // find directions of the segments and make them consistent between different ways
252 wayDataList.get(0).calcDirections(Direction.RIGHT);
253 double refHeading = wayDataList.get(0).heading;
254 for (WayData w : wayDataList) {
255 w.calcDirections(Direction.RIGHT);
256 int directionOffset = angleToDirectionChange(w.heading - refHeading, TOLERANCE2);
257 w.calcDirections(Direction.RIGHT.changeBy(directionOffset));
258 if (angleToDirectionChange(refHeading - w.heading, TOLERANCE2) != 0) throw new RuntimeException();
259 }
260 EastNorth totSum = new EastNorth(0., 0.);
261 for (WayData w : wayDataList) {
262 totSum = EN.sum(totSum, w.segSum);
263 }
264 headingAll = EN.polar(new EastNorth(0., 0.), totSum);
265 } else {
266 headingAll = EN.polar(headingNodes.get(0).getEastNorth(), headingNodes.get(1).getEastNorth());
267 for (WayData w : wayDataList) {
268 w.calcDirections(Direction.RIGHT);
269 int directionOffset = angleToDirectionChange(w.heading - headingAll, TOLERANCE2);
270 w.calcDirections(Direction.RIGHT.changeBy(directionOffset));
271 }
272 }
273 } catch (RejectedAngleException ex) {
274 throw new InvalidUserInputException(
275 tr("<html>Please make sure all selected ways head in a similar direction<br>"+
276 "or orthogonalize them one by one.</html>"), ex);
277 }
278
279 // put the nodes of all ways in a set
280 final Set<Node> allNodes = new HashSet<>();
281 for (WayData w : wayDataList) {
282 for (Node n : w.way.getNodes()) {
283 allNodes.add(n);
284 }
285 }
286
287 // the new x and y value for each node
288 final Map<Node, Double> nX = new HashMap<>();
289 final Map<Node, Double> nY = new HashMap<>();
290
291 // calculate the centroid of all nodes
292 // it is used as rotation center
293 EastNorth pivot = new EastNorth(0., 0.);
294 for (Node n : allNodes) {
295 pivot = EN.sum(pivot, n.getEastNorth());
296 }
297 pivot = new EastNorth(pivot.east() / allNodes.size(), pivot.north() / allNodes.size());
298
299 // rotate
300 for (Node n: allNodes) {
301 EastNorth tmp = EN.rotateCC(pivot, n.getEastNorth(), -headingAll);
302 nX.put(n, tmp.east());
303 nY.put(n, tmp.north());
304 }
305
306 // orthogonalize
307 final Direction[] HORIZONTAL = {Direction.RIGHT, Direction.LEFT};
308 final Direction[] VERTICAL = {Direction.UP, Direction.DOWN};
309 final Direction[][] ORIENTATIONS = {HORIZONTAL, VERTICAL};
310 for (Direction[] orientation : ORIENTATIONS){
311 final Set<Node> s = new HashSet<>(allNodes);
312 int s_size = s.size();
313 for (int dummy = 0; dummy < s_size; ++dummy) {
314 if (s.isEmpty()) {
315 break;
316 }
317 final Node dummy_n = s.iterator().next(); // pick arbitrary element of s
318
319 final Set<Node> cs = new HashSet<>(); // will contain each node that can be reached from dummy_n
320 cs.add(dummy_n); // walking only on horizontal / vertical segments
321
322 boolean somethingHappened = true;
323 while (somethingHappened) {
324 somethingHappened = false;
325 for (WayData w : wayDataList) {
326 for (int i=0; i < w.nSeg; ++i) {
327 Node n1 = w.way.getNodes().get(i);
328 Node n2 = w.way.getNodes().get(i+1);
329 if (Arrays.asList(orientation).contains(w.segDirections[i])) {
330 if (cs.contains(n1) && !cs.contains(n2)) {
331 cs.add(n2);
332 somethingHappened = true;
333 }
334 if (cs.contains(n2) && !cs.contains(n1)) {
335 cs.add(n1);
336 somethingHappened = true;
337 }
338 }
339 }
340 }
341 }
342 for (Node n : cs) {
343 s.remove(n);
344 }
345
346 final Map<Node, Double> nC = (orientation == HORIZONTAL) ? nY : nX;
347
348 double average = 0;
349 for (Node n : cs) {
350 average += nC.get(n).doubleValue();
351 }
352 average = average / cs.size();
353
354 // if one of the nodes is a heading node, forget about the average and use its value
355 for (Node fn : headingNodes) {
356 if (cs.contains(fn)) {
357 average = nC.get(fn);
358 }
359 }
360
361 // At this point, the two heading nodes (if any) are horizontally aligned, i.e. they
362 // have the same y coordinate. So in general we shouldn't find them in a vertical string
363 // of segments. This can still happen in some pathological cases (see #7889). To avoid
364 // both heading nodes collapsing to one point, we simply skip this segment string and
365 // don't touch the node coordinates.
366 if (orientation == VERTICAL && headingNodes.size() == 2 && cs.containsAll(headingNodes)) {
367 continue;
368 }
369
370 for (Node n : cs) {
371 nC.put(n, average);
372 }
373 }
374 if (!s.isEmpty()) throw new RuntimeException();
375 }
376
377 // rotate back and log the change
378 final Collection<Command> commands = new LinkedList<>();
379 for (Node n: allNodes) {
380 EastNorth tmp = new EastNorth(nX.get(n), nY.get(n));
381 tmp = EN.rotateCC(pivot, tmp, headingAll);
382 final double dx = tmp.east() - n.getEastNorth().east();
383 final double dy = tmp.north() - n.getEastNorth().north();
384 if (headingNodes.contains(n)) { // The heading nodes should not have changed
385 final double EPSILON = 1E-6;
386 if (Math.abs(dx) > Math.abs(EPSILON * tmp.east()) ||
387 Math.abs(dy) > Math.abs(EPSILON * tmp.east()))
388 throw new AssertionError();
389 } else {
390 OrthogonalizeAction.rememberMovements.put(n, new EastNorth(dx, dy));
391 commands.add(new MoveCommand(n, dx, dy));
392 }
393 }
394 return commands;
395 }
396
397 /**
398 * Class contains everything we need to know about a singe way.
399 */
400 private static class WayData {
401 public final Way way; // The assigned way
402 public final int nSeg; // Number of Segments of the Way
403 public final int nNode; // Number of Nodes of the Way
404 public Direction[] segDirections; // Direction of the segments
405 // segment i goes from node i to node (i+1)
406 public EastNorth segSum; // (Vector-)sum of all horizontal segments plus the sum of all vertical
407 // segments turned by 90 degrees
408 public double heading; // heading of segSum == approximate heading of the way
409 public WayData(Way pWay) {
410 way = pWay;
411 nNode = way.getNodes().size();
412 nSeg = nNode - 1;
413 }
414
415 /**
416 * Estimate the direction of the segments, given the first segment points in the
417 * direction <code>pInitialDirection</code>.
418 * Then sum up all horizontal / vertical segments to have a good guess for the
419 * heading of the entire way.
420 * @param pInitialDirection initial direction
421 * @throws InvalidUserInputException
422 */
423 public void calcDirections(Direction pInitialDirection) throws InvalidUserInputException {
424 final EastNorth[] en = new EastNorth[nNode]; // alias: way.getNodes().get(i).getEastNorth() ---> en[i]
425 for (int i=0; i < nNode; i++) {
426 en[i] = new EastNorth(way.getNodes().get(i).getEastNorth().east(), way.getNodes().get(i).getEastNorth().north());
427 }
428 segDirections = new Direction[nSeg];
429 Direction direction = pInitialDirection;
430 segDirections[0] = direction;
431 for (int i=0; i < nSeg - 1; i++) {
432 double h1 = EN.polar(en[i],en[i+1]);
433 double h2 = EN.polar(en[i+1],en[i+2]);
434 try {
435 direction = direction.changeBy(angleToDirectionChange(h2 - h1, TOLERANCE1));
436 } catch (RejectedAngleException ex) {
437 throw new InvalidUserInputException(tr("Please select ways with angles of approximately 90 or 180 degrees."), ex);
438 }
439 segDirections[i+1] = direction;
440 }
441
442 // sum up segments
443 EastNorth h = new EastNorth(0.,0.);
444 EastNorth v = new EastNorth(0.,0.);
445 for (int i = 0; i < nSeg; ++i) {
446 EastNorth segment = EN.diff(en[i+1], en[i]);
447 if (segDirections[i] == Direction.RIGHT) {
448 h = EN.sum(h,segment);
449 } else if (segDirections[i] == Direction.UP) {
450 v = EN.sum(v,segment);
451 } else if (segDirections[i] == Direction.LEFT) {
452 h = EN.diff(h,segment);
453 } else if (segDirections[i] == Direction.DOWN) {
454 v = EN.diff(v,segment);
455 } else throw new IllegalStateException();
456 /**
457 * When summing up the length of the sum vector should increase.
458 * However, it is possible to construct ways, such that this assertion fails.
459 * So only uncomment this for testing
460 **/
461 // if (segDirections[i].ordinal() % 2 == 0) {
462 // if (EN.abs(h) < lh) throw new AssertionError();
463 // lh = EN.abs(h);
464 // } else {
465 // if (EN.abs(v) < lv) throw new AssertionError();
466 // lv = EN.abs(v);
467 // }
468 }
469 // rotate the vertical vector by 90 degrees (clockwise) and add it to the horizontal vector
470 segSum = EN.sum(h, new EastNorth(v.north(), -v.east()));
471 // if (EN.abs(segSum) < lh) throw new AssertionError();
472 this.heading = EN.polar(new EastNorth(0.,0.), segSum);
473 }
474 }
475
476 private enum Direction {
477 RIGHT, UP, LEFT, DOWN;
478 public Direction changeBy(int directionChange) {
479 int tmp = (this.ordinal() + directionChange) % 4;
480 if (tmp < 0) {
481 tmp += 4; // the % operator can return negative value
482 }
483 return Direction.values()[tmp];
484 }
485 }
486
487 /**
488 * Make sure angle (up to 2*Pi) is in interval [ 0, 2*Pi ).
489 */
490 private static double standard_angle_0_to_2PI(double a) {
491 while (a >= 2 * Math.PI) {
492 a -= 2 * Math.PI;
493 }
494 while (a < 0) {
495 a += 2 * Math.PI;
496 }
497 return a;
498 }
499
500 /**
501 * Make sure angle (up to 2*Pi) is in interval ( -Pi, Pi ].
502 */
503 private static double standard_angle_mPI_to_PI(double a) {
504 while (a > Math.PI) {
505 a -= 2 * Math.PI;
506 }
507 while (a <= -Math.PI) {
508 a += 2 * Math.PI;
509 }
510 return a;
511 }
512
513 /**
514 * Class contains some auxiliary functions
515 */
516 private static final class EN {
517 private EN() {
518 // Hide implicit public constructor for utility class
519 }
520 /**
521 * Rotate counter-clock-wise.
522 */
523 public static EastNorth rotateCC(EastNorth pivot, EastNorth en, double angle) {
524 double cosPhi = Math.cos(angle);
525 double sinPhi = Math.sin(angle);
526 double x = en.east() - pivot.east();
527 double y = en.north() - pivot.north();
528 double nx = cosPhi * x - sinPhi * y + pivot.east();
529 double ny = sinPhi * x + cosPhi * y + pivot.north();
530 return new EastNorth(nx, ny);
531 }
532 public static EastNorth sum(EastNorth en1, EastNorth en2) {
533 return new EastNorth(en1.east() + en2.east(), en1.north() + en2.north());
534 }
535 public static EastNorth diff(EastNorth en1, EastNorth en2) {
536 return new EastNorth(en1.east() - en2.east(), en1.north() - en2.north());
537 }
538 public static double polar(EastNorth en1, EastNorth en2) {
539 return Math.atan2(en2.north() - en1.north(), en2.east() - en1.east());
540 }
541 }
542
543 /**
544 * Recognize angle to be approximately 0, 90, 180 or 270 degrees.
545 * returns an integral value, corresponding to a counter clockwise turn:
546 */
547 private static int angleToDirectionChange(double a, double deltaMax) throws RejectedAngleException {
548 a = standard_angle_mPI_to_PI(a);
549 double d0 = Math.abs(a);
550 double d90 = Math.abs(a - Math.PI / 2);
551 double d_m90 = Math.abs(a + Math.PI / 2);
552 int dirChange;
553 if (d0 < deltaMax) {
554 dirChange = 0;
555 } else if (d90 < deltaMax) {
556 dirChange = 1;
557 } else if (d_m90 < deltaMax) {
558 dirChange = -1;
559 } else {
560 a = standard_angle_0_to_2PI(a);
561 double d180 = Math.abs(a - Math.PI);
562 if (d180 < deltaMax) {
563 dirChange = 2;
564 } else
565 throw new RejectedAngleException();
566 }
567 return dirChange;
568 }
569
570 /**
571 * Exception: unsuited user input
572 */
573 private static class InvalidUserInputException extends Exception {
574 InvalidUserInputException(String message) {
575 super(message);
576 }
577 InvalidUserInputException(String message, Throwable cause) {
578 super(message, cause);
579 }
580 InvalidUserInputException() {
581 super();
582 }
583 }
584 /**
585 * Exception: angle cannot be recognized as 0, 90, 180 or 270 degrees
586 */
587 private static class RejectedAngleException extends Exception {
588 RejectedAngleException() {
589 super();
590 }
591 }
592
593 /**
594 * Don't check, if the current selection is suited for orthogonalization.
595 * Instead, show a usage dialog, that explains, why it cannot be done.
596 */
597 @Override
598 protected void updateEnabledState() {
599 setEnabled(getCurrentDataSet() != null);
600 }
601}
Note: See TracBrowser for help on using the repository browser.