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

Last change on this file since 3779 was 3757, checked in by stoecker, 13 years ago

fix help topics

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