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

Last change on this file since 2268 was 2268, checked in by stoecker, 15 years ago

fix #3571 - patch by bastiK - improve orthogonalization action

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