001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
005import static org.openstreetmap.josm.tools.I18n.tr;
006import static org.openstreetmap.josm.tools.I18n.trn;
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.HashSet;
015import java.util.LinkedList;
016import java.util.List;
017import java.util.Set;
018import java.util.stream.Collectors;
019
020import javax.swing.JOptionPane;
021import javax.swing.SwingUtilities;
022
023import org.openstreetmap.josm.command.ChangeCommand;
024import org.openstreetmap.josm.command.Command;
025import org.openstreetmap.josm.command.DeleteCommand;
026import org.openstreetmap.josm.command.SequenceCommand;
027import org.openstreetmap.josm.data.UndoRedoHandler;
028import org.openstreetmap.josm.data.osm.DataSet;
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.data.projection.Ellipsoid;
033import org.openstreetmap.josm.gui.HelpAwareOptionPane;
034import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
035import org.openstreetmap.josm.gui.MainApplication;
036import org.openstreetmap.josm.gui.Notification;
037import org.openstreetmap.josm.spi.preferences.Config;
038import org.openstreetmap.josm.tools.ImageProvider;
039import org.openstreetmap.josm.tools.Shortcut;
040
041/**
042 * Delete unnecessary nodes from a way
043 * @since 2575
044 */
045public class SimplifyWayAction extends JosmAction {
046
047    /**
048     * Constructs a new {@code SimplifyWayAction}.
049     */
050    public SimplifyWayAction() {
051        super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."),
052                Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true);
053        setHelpId(ht("/Action/SimplifyWay"));
054    }
055
056    protected boolean confirmWayWithNodesOutsideBoundingBox(List<? extends OsmPrimitive> primitives) {
057        return DeleteAction.checkAndConfirmOutlyingDelete(primitives, null);
058    }
059
060    protected void alertSelectAtLeastOneWay() {
061        SwingUtilities.invokeLater(() ->
062            new Notification(
063                    tr("Please select at least one way to simplify."))
064                    .setIcon(JOptionPane.WARNING_MESSAGE)
065                    .setDuration(Notification.TIME_SHORT)
066                    .setHelpTopic(ht("/Action/SimplifyWay#SelectAWayToSimplify"))
067                    .show()
068        );
069    }
070
071    protected boolean confirmSimplifyManyWays(int numWays) {
072        ButtonSpec[] options = new ButtonSpec[] {
073                new ButtonSpec(
074                        tr("Yes"),
075                        new ImageProvider("ok"),
076                        tr("Simplify all selected ways"),
077                        null),
078                new ButtonSpec(
079                        tr("Cancel"),
080                        new ImageProvider("cancel"),
081                        tr("Cancel operation"),
082                        null)
083        };
084        return 0 == HelpAwareOptionPane.showOptionDialog(
085                MainApplication.getMainFrame(),
086                tr("The selection contains {0} ways. Are you sure you want to simplify them all?", numWays),
087                tr("Simplify ways?"),
088                JOptionPane.WARNING_MESSAGE,
089                null, // no special icon
090                options,
091                options[0],
092                ht("/Action/SimplifyWay#ConfirmSimplifyAll")
093                );
094    }
095
096    @Override
097    public void actionPerformed(ActionEvent e) {
098        DataSet ds = getLayerManager().getEditDataSet();
099        ds.beginUpdate();
100        try {
101            List<Way> ways = ds.getSelectedWays().stream()
102                    .filter(p -> !p.isIncomplete())
103                    .collect(Collectors.toList());
104            if (ways.isEmpty()) {
105                alertSelectAtLeastOneWay();
106                return;
107            } else if (!confirmWayWithNodesOutsideBoundingBox(ways) || (ways.size() > 10 && !confirmSimplifyManyWays(ways.size()))) {
108                return;
109            }
110
111            Collection<Command> allCommands = new LinkedList<>();
112            for (Way way: ways) {
113                SequenceCommand simplifyCommand = simplifyWay(way);
114                if (simplifyCommand == null) {
115                    continue;
116                }
117                allCommands.add(simplifyCommand);
118            }
119            if (allCommands.isEmpty()) return;
120            SequenceCommand rootCommand = new SequenceCommand(
121                    trn("Simplify {0} way", "Simplify {0} ways", allCommands.size(), allCommands.size()),
122                    allCommands
123                    );
124            UndoRedoHandler.getInstance().add(rootCommand);
125        } finally {
126            ds.endUpdate();
127        }
128    }
129
130    /**
131     * Replies true if <code>node</code> is a required node which can't be removed
132     * in order to simplify the way.
133     *
134     * @param way the way to be simplified
135     * @param node the node to check
136     * @param multipleUseNodes set of nodes which is used more than once in the way
137     * @return true if <code>node</code> is a required node which can't be removed
138     * in order to simplify the way.
139     */
140    protected static boolean isRequiredNode(Way way, Node node, Set<Node> multipleUseNodes) {
141        boolean isRequired = node.isTagged();
142        if (!isRequired && multipleUseNodes.contains(node)) {
143            int frequency = Collections.frequency(way.getNodes(), node);
144            if ((way.getNode(0) == node) && (way.getNode(way.getNodesCount()-1) == node)) {
145                frequency = frequency - 1; // closed way closing node counted only once
146            }
147            isRequired = frequency > 1;
148        }
149        if (!isRequired) {
150            List<OsmPrimitive> parents = new LinkedList<>();
151            parents.addAll(node.getReferrers());
152            parents.remove(way);
153            isRequired = !parents.isEmpty();
154        }
155        return isRequired;
156    }
157
158    /**
159     * Simplifies a way with default threshold (read from preferences).
160     *
161     * @param w the way to simplify
162     * @return The sequence of commands to run
163     * @since 6411
164     */
165    public final SequenceCommand simplifyWay(Way w) {
166        return simplifyWay(w, Config.getPref().getDouble("simplify-way.max-error", 3.0));
167    }
168
169    /**
170     * Calculate a set of nodes which occurs more than once in the way
171     * @param w the way
172     * @return a set of nodes which occurs more than once in the way
173     */
174    private static Set<Node> getMultiUseNodes(Way w) {
175        Set<Node> multipleUseNodes = new HashSet<>();
176        Set<Node> allNodes = new HashSet<>();
177        for (Node n : w.getNodes()) {
178            if (!allNodes.add(n))
179                multipleUseNodes.add(n);
180        }
181        return multipleUseNodes;
182    }
183
184    /**
185     * Simplifies a way with a given threshold.
186     *
187     * @param w the way to simplify
188     * @param threshold the max error threshold
189     * @return The sequence of commands to run
190     * @since 6411
191     */
192    public static SequenceCommand simplifyWay(Way w, double threshold) {
193        int lower = 0;
194        int i = 0;
195
196        Set<Node> multipleUseNodes = getMultiUseNodes(w);
197        List<Node> newNodes = new ArrayList<>(w.getNodesCount());
198        while (i < w.getNodesCount()) {
199            if (isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
200                // copy a required node to the list of new nodes. Simplify not possible
201                newNodes.add(w.getNode(i));
202                i++;
203                lower++;
204                continue;
205            }
206            i++;
207            // find the longest sequence of not required nodes ...
208            while (i < w.getNodesCount() && !isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
209                i++;
210            }
211            // ... and simplify them
212            buildSimplifiedNodeList(w.getNodes(), lower, Math.min(w.getNodesCount()-1, i), threshold, newNodes);
213            lower = i;
214            i++;
215        }
216
217        // Closed way, check if the first node could also be simplified ...
218        if (newNodes.size() > 3 && newNodes.get(0) == newNodes.get(newNodes.size() - 1)
219                && !isRequiredNode(w, newNodes.get(0), multipleUseNodes)) {
220            final List<Node> l1 = Arrays.asList(newNodes.get(newNodes.size() - 2), newNodes.get(0), newNodes.get(1));
221            final List<Node> l2 = new ArrayList<>(3);
222            buildSimplifiedNodeList(l1, 0, 2, threshold, l2);
223            if (!l2.contains(newNodes.get(0))) {
224                newNodes.remove(0);
225                newNodes.set(newNodes.size() - 1, newNodes.get(0)); // close the way
226            }
227        }
228
229        if (newNodes.size() == w.getNodesCount()) return null;
230
231        Set<Node> delNodes = new HashSet<>();
232        delNodes.addAll(w.getNodes());
233        delNodes.removeAll(newNodes);
234
235        if (delNodes.isEmpty()) return null;
236
237        Collection<Command> cmds = new LinkedList<>();
238        Way newWay = new Way(w);
239        newWay.setNodes(newNodes);
240        cmds.add(new ChangeCommand(w, newWay));
241        cmds.add(new DeleteCommand(w.getDataSet(), delNodes));
242        w.getDataSet().clearSelection(delNodes);
243        return new SequenceCommand(
244                trn("Simplify Way (remove {0} node)", "Simplify Way (remove {0} nodes)", delNodes.size(), delNodes.size()), cmds);
245    }
246
247    /**
248     * Builds the simplified list of nodes for a way segment given by a lower index <code>from</code>
249     * and an upper index <code>to</code>
250     *
251     * @param wnew the way to simplify
252     * @param from the lower index
253     * @param to the upper index
254     * @param threshold the max error threshold
255     * @param simplifiedNodes list that will contain resulting nodes
256     */
257    protected static void buildSimplifiedNodeList(List<Node> wnew, int from, int to, double threshold, List<Node> simplifiedNodes) {
258
259        Node fromN = wnew.get(from);
260        Node toN = wnew.get(to);
261
262        // Get max xte
263        int imax = -1;
264        double xtemax = 0;
265        for (int i = from + 1; i < to; i++) {
266            Node n = wnew.get(i);
267            // CHECKSTYLE.OFF: SingleSpaceSeparator
268            double xte = Math.abs(Ellipsoid.WGS84.a
269                    * xtd(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180, toN.lat() * Math.PI / 180,
270                            toN.lon() * Math.PI / 180,     n.lat() * Math.PI / 180,   n.lon() * Math.PI / 180));
271            // CHECKSTYLE.ON: SingleSpaceSeparator
272            if (xte > xtemax) {
273                xtemax = xte;
274                imax = i;
275            }
276        }
277
278        if (imax != -1 && xtemax >= threshold) {
279            // Segment cannot be simplified - try shorter segments
280            buildSimplifiedNodeList(wnew, from, imax, threshold, simplifiedNodes);
281            buildSimplifiedNodeList(wnew, imax, to, threshold, simplifiedNodes);
282        } else {
283            // Simplify segment
284            if (simplifiedNodes.isEmpty() || simplifiedNodes.get(simplifiedNodes.size()-1) != fromN) {
285                simplifiedNodes.add(fromN);
286            }
287            if (fromN != toN) {
288                simplifiedNodes.add(toN);
289            }
290        }
291    }
292
293    /* From Aviaton Formulary v1.3
294     * http://williams.best.vwh.net/avform.htm
295     */
296    private static double dist(double lat1, double lon1, double lat2, double lon2) {
297        return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
298                * Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
299    }
300
301    private static double course(double lat1, double lon1, double lat2, double lon2) {
302        return Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
303                * Math.cos(lat2) * Math.cos(lon1 - lon2))
304                % (2 * Math.PI);
305    }
306
307    private static double xtd(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3) {
308        double distAD = dist(lat1, lon1, lat3, lon3);
309        double crsAD = course(lat1, lon1, lat3, lon3);
310        double crsAB = course(lat1, lon1, lat2, lon2);
311        return Math.asin(Math.sin(distAD) * Math.sin(crsAD - crsAB));
312    }
313
314    @Override
315    protected void updateEnabledState() {
316        updateEnabledStateOnCurrentSelection();
317    }
318
319    @Override
320    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
321        updateEnabledStateOnModifiableSelection(selection);
322    }
323}