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

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

fix #6474 - fix toolbar action entries for some actions and fix fullscreen mode start

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