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