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.GridBagLayout;
009import java.awt.event.ActionEvent;
010import java.awt.event.KeyEvent;
011import java.util.ArrayList;
012import java.util.Arrays;
013import java.util.Collection;
014import java.util.Collections;
015import java.util.HashSet;
016import java.util.LinkedList;
017import java.util.List;
018import java.util.Objects;
019import java.util.Set;
020import java.util.stream.Collectors;
021
022import javax.swing.BorderFactory;
023import javax.swing.JCheckBox;
024import javax.swing.JLabel;
025import javax.swing.JOptionPane;
026import javax.swing.JPanel;
027import javax.swing.JSpinner;
028import javax.swing.SpinnerNumberModel;
029import javax.swing.SwingUtilities;
030import javax.swing.event.ChangeEvent;
031import javax.swing.event.ChangeListener;
032
033import org.openstreetmap.josm.command.ChangeNodesCommand;
034import org.openstreetmap.josm.command.Command;
035import org.openstreetmap.josm.command.DeleteCommand;
036import org.openstreetmap.josm.command.SequenceCommand;
037import org.openstreetmap.josm.data.SystemOfMeasurement;
038import org.openstreetmap.josm.data.UndoRedoHandler;
039import org.openstreetmap.josm.data.coor.EastNorth;
040import org.openstreetmap.josm.data.osm.DataSet;
041import org.openstreetmap.josm.data.osm.Node;
042import org.openstreetmap.josm.data.osm.OsmPrimitive;
043import org.openstreetmap.josm.data.osm.Way;
044import org.openstreetmap.josm.data.projection.Ellipsoid;
045import org.openstreetmap.josm.gui.ExtendedDialog;
046import org.openstreetmap.josm.gui.HelpAwareOptionPane;
047import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
048import org.openstreetmap.josm.gui.MainApplication;
049import org.openstreetmap.josm.gui.Notification;
050import org.openstreetmap.josm.spi.preferences.Config;
051import org.openstreetmap.josm.spi.preferences.IPreferences;
052import org.openstreetmap.josm.tools.GBC;
053import org.openstreetmap.josm.tools.ImageProvider;
054import org.openstreetmap.josm.tools.Shortcut;
055import org.openstreetmap.josm.tools.StreamUtils;
056
057/**
058 * Delete unnecessary nodes from a way
059 * @since 2575
060 */
061public class SimplifyWayAction extends JosmAction {
062
063    /**
064     * Constructs a new {@code SimplifyWayAction}.
065     */
066    public SimplifyWayAction() {
067        super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."),
068                Shortcut.registerShortcut("tools:simplify", tr("Tools: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true);
069        setHelpId(ht("/Action/SimplifyWay"));
070    }
071
072    protected boolean confirmWayWithNodesOutsideBoundingBox(List<? extends OsmPrimitive> primitives) {
073        return DeleteAction.checkAndConfirmOutlyingDelete(primitives, null);
074    }
075
076    protected void alertSelectAtLeastOneWay() {
077        SwingUtilities.invokeLater(() ->
078            new Notification(
079                    tr("Please select at least one way to simplify."))
080                    .setIcon(JOptionPane.WARNING_MESSAGE)
081                    .setDuration(Notification.TIME_SHORT)
082                    .setHelpTopic(ht("/Action/SimplifyWay#SelectAWayToSimplify"))
083                    .show()
084        );
085    }
086
087    protected boolean confirmSimplifyManyWays(int numWays) {
088        ButtonSpec[] options = {
089                new ButtonSpec(
090                        tr("Yes"),
091                        new ImageProvider("ok"),
092                        tr("Simplify all selected ways"),
093                        null),
094                new ButtonSpec(
095                        tr("Cancel"),
096                        new ImageProvider("cancel"),
097                        tr("Cancel operation"),
098                        null)
099        };
100        return 0 == HelpAwareOptionPane.showOptionDialog(
101                MainApplication.getMainFrame(),
102                tr("The selection contains {0} ways. Are you sure you want to simplify them all?", numWays),
103                tr("Simplify ways?"),
104                JOptionPane.WARNING_MESSAGE,
105                null, // no special icon
106                options,
107                options[0],
108                ht("/Action/SimplifyWay#ConfirmSimplifyAll")
109                );
110    }
111
112    /**
113     * Asks the user for max-err value used to simplify ways, if not remembered before
114     * @param text the text being shown
115     * @param auto whether it's called automatically (conversion) or by the user
116     * @return the max-err value or -1 if canceled
117     * @since 15419
118     */
119    public static double askSimplifyWays(String text, boolean auto) {
120        return askSimplifyWays(Collections.emptyList(), text, auto);
121    }
122
123    /**
124     * Asks the user for max-err value used to simplify ways, if not remembered before
125     * @param ways the ways that are being simplified (to show estimated number of nodes to be removed)
126     * @param text the text being shown
127     * @param auto whether it's called automatically (conversion) or by the user
128     * @return the max-err value or -1 if canceled
129     * @since 16566
130     */
131    public static double askSimplifyWays(List<Way> ways, String text, boolean auto) {
132        IPreferences s = Config.getPref();
133        String key = "simplify-way." + (auto ? "auto." : "");
134        String keyRemember = key + "remember";
135        String keyError = key + "max-error";
136
137        String r = s.get(keyRemember, "ask");
138        if (auto && "no".equals(r)) {
139            return -1;
140        } else if ("yes".equals(r)) {
141            return s.getDouble(keyError, 3.0);
142        }
143
144        JPanel p = new JPanel(new GridBagLayout());
145        p.add(new JLabel("<html><body style=\"width: 375px;\">" + text + "<br><br>" +
146                tr("This reduces unnecessary nodes along the way and is especially recommended if GPS tracks were recorded by time "
147                 + "(e.g. one point per second) or when the accuracy was low (reduces \"zigzag\" tracks).")
148                + "</body></html>"), GBC.eol());
149        p.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
150        JPanel q = new JPanel(new GridBagLayout());
151        q.add(new JLabel(tr("Maximum error (meters): ")));
152        SpinnerNumberModel errorModel = new SpinnerNumberModel(
153                s.getDouble(keyError, 3.0), 0.01, null, 0.5);
154        JSpinner n = new JSpinner(errorModel);
155        ((JSpinner.DefaultEditor) n.getEditor()).getTextField().setColumns(4);
156        q.add(n);
157
158        JLabel nodesToRemove = new JLabel();
159        SimplifyChangeListener l = new SimplifyChangeListener(nodesToRemove, errorModel, ways);
160        if (!ways.isEmpty()) {
161            errorModel.addChangeListener(l);
162            l.stateChanged(null);
163            q.add(nodesToRemove, GBC.std().insets(5, 0, 0, 0));
164            errorModel.getChangeListeners();
165        }
166
167        q.setBorder(BorderFactory.createEmptyBorder(14, 0, 10, 0));
168        p.add(q, GBC.eol());
169        JCheckBox c = new JCheckBox(tr("Do not ask again"));
170        p.add(c, GBC.eol());
171
172        ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(),
173                tr("Simplify way"), tr("Simplify"),
174                auto ? tr("Proceed without simplifying") : tr("Cancel"))
175                .setContent(p)
176                .configureContextsensitiveHelp("Action/SimplifyWay", true);
177        if (auto) {
178            ed.setButtonIcons("simplify", "ok");
179        } else {
180            ed.setButtonIcons("ok", "cancel");
181        }
182
183        int ret = ed.showDialog().getValue();
184        double val = (double) n.getValue();
185        if (l.lastCommand != null && l.lastCommand.equals(UndoRedoHandler.getInstance().getLastCommand())) {
186            UndoRedoHandler.getInstance().undo();
187            l.lastCommand = null;
188        }
189        if (ret == 1) {
190            s.putDouble(keyError, val);
191            if (c.isSelected()) {
192                s.put(keyRemember, "yes");
193            }
194            return val;
195        } else {
196            if (auto && c.isSelected()) { //do not remember cancel for manual simplify, otherwise nothing would happen
197                s.put(keyRemember, "no");
198            }
199            return -1;
200        }
201    }
202
203    @Override
204    public void actionPerformed(ActionEvent e) {
205        DataSet ds = getLayerManager().getEditDataSet();
206        ds.update(() -> {
207            List<Way> ways = ds.getSelectedWays().stream()
208                    .filter(p -> !p.isIncomplete())
209                    .collect(Collectors.toList());
210            if (ways.isEmpty()) {
211                alertSelectAtLeastOneWay();
212                return;
213            } else if (!confirmWayWithNodesOutsideBoundingBox(ways) || (ways.size() > 10 && !confirmSimplifyManyWays(ways.size()))) {
214                return;
215            }
216
217            String lengthstr = SystemOfMeasurement.getSystemOfMeasurement().getDistText(
218                    ways.stream().mapToDouble(Way::getLength).sum());
219
220            double err = askSimplifyWays(ways, trn(
221                    "You are about to simplify {0} way with a total length of {1}.",
222                    "You are about to simplify {0} ways with a total length of {1}.",
223                    ways.size(), ways.size(), lengthstr), false);
224
225            if (err > 0) {
226                simplifyWays(ways, err);
227            }
228        });
229    }
230
231    /**
232     * Replies true if <code>node</code> is a required node which can't be removed
233     * in order to simplify the way.
234     *
235     * @param way the way to be simplified
236     * @param node the node to check
237     * @param multipleUseNodes set of nodes which is used more than once in the way
238     * @return true if <code>node</code> is a required node which can't be removed
239     * in order to simplify the way.
240     */
241    protected static boolean isRequiredNode(Way way, Node node, Set<Node> multipleUseNodes) {
242        boolean isRequired = node.isTagged();
243        if (!isRequired && multipleUseNodes.contains(node)) {
244            int frequency = Collections.frequency(way.getNodes(), node);
245            if ((way.getNode(0) == node) && (way.getNode(way.getNodesCount()-1) == node)) {
246                frequency = frequency - 1; // closed way closing node counted only once
247            }
248            isRequired = frequency > 1;
249        }
250        if (!isRequired) {
251            List<OsmPrimitive> parents = new LinkedList<>();
252            parents.addAll(node.getReferrers());
253            parents.remove(way);
254            isRequired = !parents.isEmpty();
255        }
256        return isRequired;
257    }
258
259    /**
260     * Calculate a set of nodes which occurs more than once in the way
261     * @param w the way
262     * @return a set of nodes which occurs more than once in the way
263     */
264    private static Set<Node> getMultiUseNodes(Way w) {
265        Set<Node> allNodes = new HashSet<>();
266        return w.getNodes().stream()
267                .filter(n -> !allNodes.add(n))
268                .collect(Collectors.toSet());
269    }
270
271    /**
272     * Runs the commands to simplify the ways with the given threshold
273     *
274     * @param ways the ways to simplify
275     * @param threshold the max error threshold
276     * @return The number of nodes removed from the ways (does not double-count)
277     * @since 16566
278     */
279    public static int simplifyWaysCountNodesRemoved(List<Way> ways, double threshold) {
280        Command command = buildSimplifyWaysCommand(ways, threshold);
281        if (command == null) {
282            return 0;
283        }
284        return (int) command.getParticipatingPrimitives().stream()
285                .filter(Node.class::isInstance)
286                .count();
287    }
288
289    /**
290     * Runs the commands to simplify the ways with the given threshold
291     *
292     * @param ways the ways to simplify
293     * @param threshold the max error threshold
294     * @since 15419
295     */
296    public static void simplifyWays(List<Way> ways, double threshold) {
297        Command command = buildSimplifyWaysCommand(ways, threshold);
298        if (command != null) {
299            UndoRedoHandler.getInstance().add(command);
300        }
301    }
302
303    /**
304     * Creates the commands to simplify the ways with the given threshold
305     *
306     * @param ways the ways to simplify
307     * @param threshold the max error threshold
308     * @return The command to simplify ways
309     * @since 16566 (private)
310     */
311    private static SequenceCommand buildSimplifyWaysCommand(List<Way> ways, double threshold) {
312        Collection<Command> allCommands = ways.stream()
313                .map(way -> createSimplifyCommand(way, threshold))
314                .filter(Objects::nonNull)
315                .collect(StreamUtils.toUnmodifiableList());
316        if (allCommands.isEmpty())
317            return null;
318        return new SequenceCommand(
319                trn("Simplify {0} way", "Simplify {0} ways", allCommands.size(), allCommands.size()),
320                allCommands);
321    }
322
323    /**
324     * Creates the SequenceCommand to simplify a way with default threshold.
325     *
326     * @param w the way to simplify
327     * @return The sequence of commands to run
328     * @since 15419
329     */
330    public static SequenceCommand createSimplifyCommand(Way w) {
331        return createSimplifyCommand(w, Config.getPref().getDouble("simplify-way.max-error", 3.0));
332    }
333
334    /**
335     * Creates the SequenceCommand to simplify a way with a given threshold.
336     *
337     * @param w the way to simplify
338     * @param threshold the max error threshold
339     * @return The sequence of commands to run
340     * @since 15419
341     */
342    public static SequenceCommand createSimplifyCommand(Way w, double threshold) {
343        int lower = 0;
344        int i = 0;
345
346        Set<Node> multipleUseNodes = getMultiUseNodes(w);
347        List<Node> newNodes = new ArrayList<>(w.getNodesCount());
348        while (i < w.getNodesCount()) {
349            if (isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
350                // copy a required node to the list of new nodes. Simplify not possible
351                newNodes.add(w.getNode(i));
352                i++;
353                lower++;
354                continue;
355            }
356            i++;
357            // find the longest sequence of not required nodes ...
358            while (i < w.getNodesCount() && !isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
359                i++;
360            }
361            // ... and simplify them
362            buildSimplifiedNodeList(w.getNodes(), lower, Math.min(w.getNodesCount()-1, i), threshold, newNodes);
363            lower = i;
364            i++;
365        }
366
367        // Closed way, check if the first node could also be simplified ...
368        if (newNodes.size() > 3 && newNodes.get(0) == newNodes.get(newNodes.size() - 1)
369                && !isRequiredNode(w, newNodes.get(0), multipleUseNodes)) {
370            final List<Node> l1 = Arrays.asList(newNodes.get(newNodes.size() - 2), newNodes.get(0), newNodes.get(1));
371            final List<Node> l2 = new ArrayList<>(3);
372            buildSimplifiedNodeList(l1, 0, 2, threshold, l2);
373            if (!l2.contains(newNodes.get(0))) {
374                newNodes.remove(0);
375                newNodes.set(newNodes.size() - 1, newNodes.get(0)); // close the way
376            }
377        }
378
379        if (newNodes.size() == w.getNodesCount()) return null;
380
381        Set<Node> delNodes = new HashSet<>(w.getNodes());
382        delNodes.removeAll(newNodes);
383
384        if (delNodes.isEmpty()) return null;
385
386        Collection<Command> cmds = new LinkedList<>();
387        cmds.add(new ChangeNodesCommand(w, newNodes));
388        cmds.add(new DeleteCommand(w.getDataSet(), delNodes));
389        w.getDataSet().clearSelection(delNodes);
390        return new SequenceCommand(
391                trn("Simplify Way (remove {0} node)", "Simplify Way (remove {0} nodes)", delNodes.size(), delNodes.size()), cmds);
392    }
393
394    /**
395     * Builds the simplified list of nodes for a way segment given by a lower index <code>from</code>
396     * and an upper index <code>to</code>
397     *
398     * @param wnew the way to simplify
399     * @param from the lower index
400     * @param to the upper index
401     * @param threshold the max error threshold
402     * @param simplifiedNodes list that will contain resulting nodes
403     */
404    protected static void buildSimplifiedNodeList(List<Node> wnew, int from, int to, double threshold, List<Node> simplifiedNodes) {
405
406        Node fromN = wnew.get(from);
407        Node toN = wnew.get(to);
408        EastNorth p1 = fromN.getEastNorth();
409        EastNorth p2 = toN.getEastNorth();
410        // Get max xte
411        int imax = -1;
412        double xtemax = 0;
413        for (int i = from + 1; i < to; i++) {
414            Node n = wnew.get(i);
415            EastNorth p = n.getEastNorth();
416            double ldx = p2.getX() - p1.getX();
417            double ldy = p2.getY() - p1.getY();
418            double offset;
419            //segment zero length
420            if (ldx == 0 && ldy == 0)
421                offset = 0;
422            else {
423                double pdx = p.getX() - p1.getX();
424                double pdy = p.getY() - p1.getY();
425                offset = (pdx * ldx + pdy * ldy) / (ldx * ldx + ldy * ldy);
426            }
427            final double distRad;
428            // CHECKSTYLE.OFF: SingleSpaceSeparator
429            if (offset <= 0) {
430                distRad = dist(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180,
431                                   n.lat() * Math.PI / 180,     n.lon() * Math.PI / 180);
432            } else if (offset >= 1) {
433                distRad = dist(toN.lat() * Math.PI / 180, toN.lon() * Math.PI / 180,
434                                 n.lat() * Math.PI / 180,   n.lon() * Math.PI / 180);
435            } else {
436                distRad = xtd(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180,
437                                toN.lat() * Math.PI / 180,   toN.lon() * Math.PI / 180,
438                                  n.lat() * Math.PI / 180,     n.lon() * Math.PI / 180);
439            }
440            // CHECKSTYLE.ON: SingleSpaceSeparator
441            double xte = Math.abs(distRad);
442            if (xte > xtemax) {
443                xtemax = xte;
444                imax = i;
445            }
446        }
447        if (imax != -1 && Ellipsoid.WGS84.a * xtemax >= threshold) {
448            // Segment cannot be simplified - try shorter segments
449            buildSimplifiedNodeList(wnew, from, imax, threshold, simplifiedNodes);
450            buildSimplifiedNodeList(wnew, imax, to, threshold, simplifiedNodes);
451        } else {
452            // Simplify segment
453            if (simplifiedNodes.isEmpty() || simplifiedNodes.get(simplifiedNodes.size()-1) != fromN) {
454                simplifiedNodes.add(fromN);
455            }
456            if (fromN != toN) {
457                simplifiedNodes.add(toN);
458            }
459        }
460    }
461
462    /* From Aviaton Formulary v1.3
463     * http://williams.best.vwh.net/avform.htm
464     */
465    private static double dist(double lat1, double lon1, double lat2, double lon2) {
466        return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
467                * Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
468    }
469
470    private static double course(double lat1, double lon1, double lat2, double lon2) {
471        return Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
472                * Math.cos(lat2) * Math.cos(lon1 - lon2))
473                % (2 * Math.PI);
474    }
475
476    private static double xtd(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3) {
477        double distAD = dist(lat1, lon1, lat3, lon3);
478        double crsAD = course(lat1, lon1, lat3, lon3);
479        double crsAB = course(lat1, lon1, lat2, lon2);
480        return Math.asin(Math.sin(distAD) * Math.sin(crsAD - crsAB));
481    }
482
483    @Override
484    protected void updateEnabledState() {
485        updateEnabledStateOnCurrentSelection();
486    }
487
488    @Override
489    protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
490        updateEnabledStateOnModifiableSelection(selection);
491    }
492
493    private static class SimplifyChangeListener implements ChangeListener {
494        Command lastCommand;
495        private final JLabel nodesToRemove;
496        private final SpinnerNumberModel errorModel;
497        private final List<Way> ways;
498
499        SimplifyChangeListener(JLabel nodesToRemove, SpinnerNumberModel errorModel, List<Way> ways) {
500            this.nodesToRemove = nodesToRemove;
501            this.errorModel = errorModel;
502            this.ways = ways;
503        }
504
505        @Override
506        public void stateChanged(ChangeEvent e) {
507            if (Objects.equals(UndoRedoHandler.getInstance().getLastCommand(), lastCommand)) {
508                UndoRedoHandler.getInstance().undo();
509            }
510            double threshold = errorModel.getNumber().doubleValue();
511            int removeNodes = simplifyWaysCountNodesRemoved(ways, threshold);
512            nodesToRemove.setText(trn(
513                    "(about {0} node to remove)",
514                    "(about {0} nodes to remove)", removeNodes, removeNodes));
515            lastCommand = SimplifyWayAction.buildSimplifyWaysCommand(ways, threshold);
516            if (lastCommand != null) {
517                UndoRedoHandler.getInstance().add(lastCommand);
518            }
519        }
520    }
521}