source: josm/trunk/src/org/openstreetmap/josm/actions/SimplifyWayAction.java@ 15652

Last change on this file since 15652 was 15586, checked in by Don-vip, 4 years ago

code cleanup

  • Property svn:eol-style set to native
File size: 17.2 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[2575]2package org.openstreetmap.josm.actions;
3
[2976]4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
[2575]5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
[15419]8import java.awt.GridBagLayout;
[2575]9import java.awt.event.ActionEvent;
10import java.awt.event.KeyEvent;
[2999]11import java.util.ArrayList;
[11118]12import java.util.Arrays;
[2575]13import java.util.Collection;
14import java.util.Collections;
15import java.util.HashSet;
16import java.util.LinkedList;
17import java.util.List;
[8338]18import java.util.Set;
[14654]19import java.util.stream.Collectors;
[2575]20
[15419]21import javax.swing.BorderFactory;
22import javax.swing.JCheckBox;
23import javax.swing.JLabel;
[2575]24import javax.swing.JOptionPane;
[15419]25import javax.swing.JPanel;
26import javax.swing.JSpinner;
27import javax.swing.SpinnerNumberModel;
[11488]28import javax.swing.SwingUtilities;
[2575]29
30import org.openstreetmap.josm.command.ChangeCommand;
31import org.openstreetmap.josm.command.Command;
32import org.openstreetmap.josm.command.DeleteCommand;
33import org.openstreetmap.josm.command.SequenceCommand;
[15419]34import org.openstreetmap.josm.data.SystemOfMeasurement;
[14134]35import org.openstreetmap.josm.data.UndoRedoHandler;
[3952]36import org.openstreetmap.josm.data.osm.DataSet;
[2575]37import org.openstreetmap.josm.data.osm.Node;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.osm.Way;
[9230]40import org.openstreetmap.josm.data.projection.Ellipsoid;
[15419]41import org.openstreetmap.josm.gui.ExtendedDialog;
[2976]42import org.openstreetmap.josm.gui.HelpAwareOptionPane;
43import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
[14153]44import org.openstreetmap.josm.gui.MainApplication;
[6131]45import org.openstreetmap.josm.gui.Notification;
[12846]46import org.openstreetmap.josm.spi.preferences.Config;
[15419]47import org.openstreetmap.josm.spi.preferences.IPreferences;
48import org.openstreetmap.josm.tools.GBC;
[2976]49import org.openstreetmap.josm.tools.ImageProvider;
[2575]50import org.openstreetmap.josm.tools.Shortcut;
51
[6248]52/**
53 * Delete unnecessary nodes from a way
[6411]54 * @since 2575
[6248]55 */
[2575]56public class SimplifyWayAction extends JosmAction {
[7509]57
[6248]58 /**
59 * Constructs a new {@code SimplifyWayAction}.
60 */
[2575]61 public SimplifyWayAction() {
[8509]62 super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."),
63 Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true);
[14397]64 setHelpId(ht("/Action/SimplifyWay"));
[2575]65 }
66
[4461]67 protected boolean confirmWayWithNodesOutsideBoundingBox(List<? extends OsmPrimitive> primitives) {
[12749]68 return DeleteAction.checkAndConfirmOutlyingDelete(primitives, null);
[2976]69 }
70
71 protected void alertSelectAtLeastOneWay() {
[11488]72 SwingUtilities.invokeLater(() ->
73 new Notification(
74 tr("Please select at least one way to simplify."))
75 .setIcon(JOptionPane.WARNING_MESSAGE)
76 .setDuration(Notification.TIME_SHORT)
77 .setHelpTopic(ht("/Action/SimplifyWay#SelectAWayToSimplify"))
78 .show()
79 );
[2976]80 }
81
82 protected boolean confirmSimplifyManyWays(int numWays) {
[15586]83 ButtonSpec[] options = {
[2976]84 new ButtonSpec(
85 tr("Yes"),
[13842]86 new ImageProvider("ok"),
[2976]87 tr("Simplify all selected ways"),
[13842]88 null),
89 new ButtonSpec(
90 tr("Cancel"),
91 new ImageProvider("cancel"),
92 tr("Cancel operation"),
93 null)
[2976]94 };
[9917]95 return 0 == HelpAwareOptionPane.showOptionDialog(
[14153]96 MainApplication.getMainFrame(),
[13842]97 tr("The selection contains {0} ways. Are you sure you want to simplify them all?", numWays),
98 tr("Simplify ways?"),
99 JOptionPane.WARNING_MESSAGE,
100 null, // no special icon
101 options,
102 options[0],
103 ht("/Action/SimplifyWay#ConfirmSimplifyAll")
[4869]104 );
[2976]105 }
106
[15419]107 /**
108 * Asks the user for max-err value used to simplify ways, if not remembered before
109 * @param text the text being shown
110 * @param auto whether it's called automatically (conversion) or by the user
111 * @return the max-err value or -1 if canceled
112 * @since 15419
113 */
114 public static double askSimplifyWays(String text, boolean auto) {
115 IPreferences s = Config.getPref();
116 String key = "simplify-way." + (auto ? "auto." : "");
117 String keyRemember = key + "remember";
118 String keyError = key + "max-error";
119
120 String r = s.get(keyRemember, "ask");
121 if (auto && "no".equals(r)) {
122 return -1;
123 } else if ("yes".equals(r)) {
124 return s.getDouble(keyError, 3.0);
125 }
126
127 JPanel p = new JPanel(new GridBagLayout());
128 p.add(new JLabel("<html><body style=\"width: 375px;\">" + text + "<br><br>" +
129 tr("This reduces unnecessary nodes along the way and is especially recommended if GPS tracks were recorded by time "
130 + "(e.g. one point per second) or when the accuracy was low (reduces \"zigzag\" tracks).")
131 + "</body></html>"), GBC.eol());
132 p.setBorder(BorderFactory.createEmptyBorder(5, 10, 10, 5));
133 JPanel q = new JPanel(new GridBagLayout());
134 q.add(new JLabel(tr("Maximum error (meters): ")));
135 JSpinner n = new JSpinner(new SpinnerNumberModel(
[15471]136 s.getDouble(keyError, 3.0), 0.01, null, 0.5));
137 ((JSpinner.DefaultEditor) n.getEditor()).getTextField().setColumns(4);
[15419]138 q.add(n);
139 q.setBorder(BorderFactory.createEmptyBorder(14, 0, 10, 0));
140 p.add(q, GBC.eol());
141 JCheckBox c = new JCheckBox(tr("Do not ask again"));
142 p.add(c, GBC.eol());
143
144 ExtendedDialog ed = new ExtendedDialog(MainApplication.getMainFrame(),
145 tr("Simplify way"), tr("Simplify"),
146 auto ? tr("Proceed without simplifying") : tr("Cancel"))
147 .setContent(p)
148 .configureContextsensitiveHelp(("Action/SimplifyWay"), true);
149 if (auto) {
150 ed.setButtonIcons("simplify", "ok");
151 } else {
152 ed.setButtonIcons("ok", "cancel");
153 }
154
155 int ret = ed.showDialog().getValue();
156 double val = (double) n.getValue();
157 if (ret == 1) {
158 s.putDouble(keyError, val);
159 if (c.isSelected()) {
160 s.put(keyRemember, "yes");
161 }
162 return val;
163 } else {
164 if (auto && c.isSelected()) { //do not remember cancel for manual simplify, otherwise nothing would happen
165 s.put(keyRemember, "no");
166 }
167 return -1;
168 }
169 }
170
[6084]171 @Override
[2976]172 public void actionPerformed(ActionEvent e) {
[10382]173 DataSet ds = getLayerManager().getEditDataSet();
[3952]174 ds.beginUpdate();
[6981]175 try {
[14654]176 List<Way> ways = ds.getSelectedWays().stream()
177 .filter(p -> !p.isIncomplete())
178 .collect(Collectors.toList());
[3952]179 if (ways.isEmpty()) {
180 alertSelectAtLeastOneWay();
[2575]181 return;
[11109]182 } else if (!confirmWayWithNodesOutsideBoundingBox(ways) || (ways.size() > 10 && !confirmSimplifyManyWays(ways.size()))) {
[4461]183 return;
[3952]184 }
[2575]185
[15419]186 String lengthstr = SystemOfMeasurement.getSystemOfMeasurement().getDistText(
[15427]187 ways.stream().mapToDouble(Way::getLength).sum());
[15419]188
189 double err = askSimplifyWays(trn(
190 "You are about to simplify {0} way with a total length of {1}.",
191 "You are about to simplify {0} ways with a total length of {1}.",
192 ways.size(), ways.size(), lengthstr), false);
193
194 if (err > 0) {
195 simplifyWays(ways, err);
[2575]196 }
[3952]197 } finally {
198 ds.endUpdate();
[2575]199 }
200 }
201
[2976]202 /**
203 * Replies true if <code>node</code> is a required node which can't be removed
204 * in order to simplify the way.
[3530]205 *
[2976]206 * @param way the way to be simplified
207 * @param node the node to check
[14970]208 * @param multipleUseNodes set of nodes which is used more than once in the way
[2976]209 * @return true if <code>node</code> is a required node which can't be removed
210 * in order to simplify the way.
211 */
[14970]212 protected static boolean isRequiredNode(Way way, Node node, Set<Node> multipleUseNodes) {
[13540]213 boolean isRequired = node.isTagged();
[14970]214 if (!isRequired && multipleUseNodes.contains(node)) {
[13540]215 int frequency = Collections.frequency(way.getNodes(), node);
216 if ((way.getNode(0) == node) && (way.getNode(way.getNodesCount()-1) == node)) {
217 frequency = frequency - 1; // closed way closing node counted only once
218 }
219 isRequired = frequency > 1;
[11118]220 }
[8443]221 if (!isRequired) {
[7005]222 List<OsmPrimitive> parents = new LinkedList<>();
[2976]223 parents.addAll(node.getReferrers());
224 parents.remove(way);
225 isRequired = !parents.isEmpty();
226 }
227 return isRequired;
228 }
229
230 /**
[14970]231 * Calculate a set of nodes which occurs more than once in the way
232 * @param w the way
233 * @return a set of nodes which occurs more than once in the way
234 */
235 private static Set<Node> getMultiUseNodes(Way w) {
236 Set<Node> multipleUseNodes = new HashSet<>();
237 Set<Node> allNodes = new HashSet<>();
238 for (Node n : w.getNodes()) {
239 if (!allNodes.add(n))
240 multipleUseNodes.add(n);
241 }
242 return multipleUseNodes;
243 }
244
245 /**
[15419]246 * Runs the commands to simplify the ways with the given threshold
[6411]247 *
[15419]248 * @param ways the ways to simplify
249 * @param threshold the max error threshold
250 * @since 15419
251 */
252 public static void simplifyWays(List<Way> ways, double threshold) {
253 Collection<Command> allCommands = new LinkedList<>();
254 for (Way way : ways) {
255 SequenceCommand simplifyCommand = createSimplifyCommand(way, threshold);
256 if (simplifyCommand == null) {
257 continue;
258 }
259 allCommands.add(simplifyCommand);
260 }
261 if (allCommands.isEmpty())
262 return;
263 SequenceCommand rootCommand = new SequenceCommand(
264 trn("Simplify {0} way", "Simplify {0} ways", allCommands.size(), allCommands.size()),
265 allCommands);
266 UndoRedoHandler.getInstance().add(rootCommand);
267 }
268
269 /**
270 * Creates the SequenceCommand to simplify a way with default threshold.
271 *
[6411]272 * @param w the way to simplify
[15419]273 * @return The sequence of commands to run
274 * @since 6411
275 * @deprecated Replaced by {@link #createSimplifyCommand(Way)}. You can also use {@link #simplifyWays(List, double)} directly.
276 */
277 @Deprecated
278 public final SequenceCommand simplifyWay(Way w) {
279 return createSimplifyCommand(w);
280 }
281
282 /**
283 * Creates the SequenceCommand to simplify a way with a given threshold.
284 *
285 * @param w the way to simplify
[8459]286 * @param threshold the max error threshold
[6411]287 * @return The sequence of commands to run
288 * @since 6411
[15419]289 * @deprecated Replaced by {@link #createSimplifyCommand(Way, double)}. You can also use {@link #simplifyWays(List, double)} directly.
[6411]290 */
[15419]291 @Deprecated
[12287]292 public static SequenceCommand simplifyWay(Way w, double threshold) {
[15419]293 return createSimplifyCommand(w, threshold);
294 }
295
296 /**
297 * Creates the SequenceCommand to simplify a way with default threshold.
298 *
299 * @param w the way to simplify
300 * @return The sequence of commands to run
301 * @since 15419
302 */
[15431]303 public static SequenceCommand createSimplifyCommand(Way w) {
[15419]304 return createSimplifyCommand(w, Config.getPref().getDouble("simplify-way.max-error", 3.0));
305 }
306
307 /**
308 * Creates the SequenceCommand to simplify a way with a given threshold.
309 *
310 * @param w the way to simplify
311 * @param threshold the max error threshold
312 * @return The sequence of commands to run
313 * @since 15419
314 */
315 public static SequenceCommand createSimplifyCommand(Way w, double threshold) {
[2976]316 int lower = 0;
317 int i = 0;
[14970]318
319 Set<Node> multipleUseNodes = getMultiUseNodes(w);
[7005]320 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
[8510]321 while (i < w.getNodesCount()) {
[14970]322 if (isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
[6411]323 // copy a required node to the list of new nodes. Simplify not possible
[2976]324 newNodes.add(w.getNode(i));
325 i++;
326 lower++;
327 continue;
[2575]328 }
[2976]329 i++;
330 // find the longest sequence of not required nodes ...
[14970]331 while (i < w.getNodesCount() && !isRequiredNode(w, w.getNode(i), multipleUseNodes)) {
[2976]332 i++;
[2575]333 }
[2976]334 // ... and simplify them
[8459]335 buildSimplifiedNodeList(w.getNodes(), lower, Math.min(w.getNodesCount()-1, i), threshold, newNodes);
[8510]336 lower = i;
[2976]337 i++;
[2575]338 }
339
[11385]340 // Closed way, check if the first node could also be simplified ...
[14971]341 if (newNodes.size() > 3 && newNodes.get(0) == newNodes.get(newNodes.size() - 1)
342 && !isRequiredNode(w, newNodes.get(0), multipleUseNodes)) {
[11385]343 final List<Node> l1 = Arrays.asList(newNodes.get(newNodes.size() - 2), newNodes.get(0), newNodes.get(1));
344 final List<Node> l2 = new ArrayList<>(3);
345 buildSimplifiedNodeList(l1, 0, 2, threshold, l2);
346 if (!l2.contains(newNodes.get(0))) {
347 newNodes.remove(0);
348 newNodes.set(newNodes.size() - 1, newNodes.get(0)); // close the way
[11118]349 }
350 }
351
[13540]352 if (newNodes.size() == w.getNodesCount()) return null;
353
[15152]354 Set<Node> delNodes = new HashSet<>(w.getNodes());
[2976]355 delNodes.removeAll(newNodes);
[2575]356
[2976]357 if (delNodes.isEmpty()) return null;
[2575]358
[7005]359 Collection<Command> cmds = new LinkedList<>();
[2976]360 Way newWay = new Way(w);
361 newWay.setNodes(newNodes);
362 cmds.add(new ChangeCommand(w, newWay));
[12386]363 cmds.add(new DeleteCommand(w.getDataSet(), delNodes));
[6411]364 w.getDataSet().clearSelection(delNodes);
[8540]365 return new SequenceCommand(
366 trn("Simplify Way (remove {0} node)", "Simplify Way (remove {0} nodes)", delNodes.size(), delNodes.size()), cmds);
[2575]367 }
368
[2976]369 /**
370 * Builds the simplified list of nodes for a way segment given by a lower index <code>from</code>
371 * and an upper index <code>to</code>
[3530]372 *
[2976]373 * @param wnew the way to simplify
374 * @param from the lower index
375 * @param to the upper index
[8459]376 * @param threshold the max error threshold
[9230]377 * @param simplifiedNodes list that will contain resulting nodes
[2575]378 */
[12287]379 protected static void buildSimplifiedNodeList(List<Node> wnew, int from, int to, double threshold, List<Node> simplifiedNodes) {
[2575]380
[2999]381 Node fromN = wnew.get(from);
382 Node toN = wnew.get(to);
[2976]383
[2999]384 // Get max xte
[2575]385 int imax = -1;
386 double xtemax = 0;
387 for (int i = from + 1; i < to; i++) {
[2999]388 Node n = wnew.get(i);
[12171]389 // CHECKSTYLE.OFF: SingleSpaceSeparator
[9230]390 double xte = Math.abs(Ellipsoid.WGS84.a
[12161]391 * xtd(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180, toN.lat() * Math.PI / 180,
392 toN.lon() * Math.PI / 180, n.lat() * Math.PI / 180, n.lon() * Math.PI / 180));
[12171]393 // CHECKSTYLE.ON: SingleSpaceSeparator
[2575]394 if (xte > xtemax) {
395 xtemax = xte;
396 imax = i;
397 }
398 }
399
[2976]400 if (imax != -1 && xtemax >= threshold) {
[2999]401 // Segment cannot be simplified - try shorter segments
[8510]402 buildSimplifiedNodeList(wnew, from, imax, threshold, simplifiedNodes);
403 buildSimplifiedNodeList(wnew, imax, to, threshold, simplifiedNodes);
[2976]404 } else {
[2999]405 // Simplify segment
[10662]406 if (simplifiedNodes.isEmpty() || simplifiedNodes.get(simplifiedNodes.size()-1) != fromN) {
[2976]407 simplifiedNodes.add(fromN);
408 }
[10662]409 if (fromN != toN) {
[2976]410 simplifiedNodes.add(toN);
411 }
[2575]412 }
413 }
414
415 /* From Aviaton Formulary v1.3
416 * http://williams.best.vwh.net/avform.htm
417 */
[11118]418 private static double dist(double lat1, double lon1, double lat2, double lon2) {
[2575]419 return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
420 * Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
421 }
422
[11118]423 private static double course(double lat1, double lon1, double lat2, double lon2) {
[2575]424 return Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
425 * Math.cos(lat2) * Math.cos(lon1 - lon2))
426 % (2 * Math.PI);
427 }
428
[11118]429 private static double xtd(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3) {
[6981]430 double distAD = dist(lat1, lon1, lat3, lon3);
431 double crsAD = course(lat1, lon1, lat3, lon3);
432 double crsAB = course(lat1, lon1, lat2, lon2);
433 return Math.asin(Math.sin(distAD) * Math.sin(crsAD - crsAB));
[2575]434 }
435
436 @Override
437 protected void updateEnabledState() {
[10409]438 updateEnabledStateOnCurrentSelection();
[2575]439 }
440
441 @Override
442 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
[13434]443 updateEnabledStateOnModifiableSelection(selection);
[2575]444 }
445}
Note: See TracBrowser for help on using the repository browser.