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

Last change on this file since 16175 was 16175, checked in by Don-vip, 4 years ago

fix #18953 - OrthogonalizeAction: don't produce empty commands sequence

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