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

Revision 4385, 24.6 KB checked in by bastiK, 6 months ago (diff)

fixed #6190 - orthogonalize produces strange shapes

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