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

Last change on this file since 2667 was 2626, checked in by jttt, 14 years ago

Fixed some of the warnings found by FindBugs

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