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