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