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

Last change on this file since 12188 was 12131, checked in by Don-vip, 7 years ago

see #11889, see #11924, see #13387 - use backported versions of Math.toDegrees/toRadians (more accurate and faster) - to revert when migrating to Java 9

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