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

Last change on this file since 12785 was 12749, checked in by Don-vip, 7 years ago

see #15229 - see #15182 - see #13036 - remove GUI stuff from Command and DeleteCommand

  • Property svn:eol-style set to native
File size: 11.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Arrays;
12import java.util.Collection;
13import java.util.Collections;
14import java.util.HashSet;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Set;
18
19import javax.swing.JOptionPane;
20import javax.swing.SwingUtilities;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.command.ChangeCommand;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.DeleteCommand;
26import org.openstreetmap.josm.command.SequenceCommand;
27import org.openstreetmap.josm.data.osm.DataSet;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.Way;
31import org.openstreetmap.josm.data.projection.Ellipsoid;
32import org.openstreetmap.josm.gui.HelpAwareOptionPane;
33import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
34import org.openstreetmap.josm.gui.MainApplication;
35import org.openstreetmap.josm.gui.Notification;
36import org.openstreetmap.josm.tools.ImageProvider;
37import org.openstreetmap.josm.tools.Shortcut;
38
39/**
40 * Delete unnecessary nodes from a way
41 * @since 2575
42 */
43public class SimplifyWayAction extends JosmAction {
44
45 /**
46 * Constructs a new {@code SimplifyWayAction}.
47 */
48 public SimplifyWayAction() {
49 super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."),
50 Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true);
51 putValue("help", ht("/Action/SimplifyWay"));
52 }
53
54 protected boolean confirmWayWithNodesOutsideBoundingBox(List<? extends OsmPrimitive> primitives) {
55 return DeleteAction.checkAndConfirmOutlyingDelete(primitives, null);
56 }
57
58 protected void alertSelectAtLeastOneWay() {
59 SwingUtilities.invokeLater(() ->
60 new Notification(
61 tr("Please select at least one way to simplify."))
62 .setIcon(JOptionPane.WARNING_MESSAGE)
63 .setDuration(Notification.TIME_SHORT)
64 .setHelpTopic(ht("/Action/SimplifyWay#SelectAWayToSimplify"))
65 .show()
66 );
67 }
68
69 protected boolean confirmSimplifyManyWays(int numWays) {
70 ButtonSpec[] options = new ButtonSpec[] {
71 new ButtonSpec(
72 tr("Yes"),
73 ImageProvider.get("ok"),
74 tr("Simplify all selected ways"),
75 null
76 ),
77 new ButtonSpec(
78 tr("Cancel"),
79 ImageProvider.get("cancel"),
80 tr("Cancel operation"),
81 null
82 )
83 };
84 return 0 == HelpAwareOptionPane.showOptionDialog(
85 Main.parent,
86 tr(
87 "The selection contains {0} ways. Are you sure you want to simplify them all?",
88 numWays
89 ),
90 tr("Simplify ways?"),
91 JOptionPane.WARNING_MESSAGE,
92 null, // no special icon
93 options,
94 options[0],
95 ht("/Action/SimplifyWay#ConfirmSimplifyAll")
96 );
97 }
98
99 @Override
100 public void actionPerformed(ActionEvent e) {
101 DataSet ds = getLayerManager().getEditDataSet();
102 ds.beginUpdate();
103 try {
104 List<Way> ways = OsmPrimitive.getFilteredList(ds.getSelected(), Way.class);
105 ways.removeIf(OsmPrimitive::isIncomplete);
106 if (ways.isEmpty()) {
107 alertSelectAtLeastOneWay();
108 return;
109 } else if (!confirmWayWithNodesOutsideBoundingBox(ways) || (ways.size() > 10 && !confirmSimplifyManyWays(ways.size()))) {
110 return;
111 }
112
113 Collection<Command> allCommands = new LinkedList<>();
114 for (Way way: ways) {
115 SequenceCommand simplifyCommand = simplifyWay(way);
116 if (simplifyCommand == null) {
117 continue;
118 }
119 allCommands.add(simplifyCommand);
120 }
121 if (allCommands.isEmpty()) return;
122 SequenceCommand rootCommand = new SequenceCommand(
123 trn("Simplify {0} way", "Simplify {0} ways", allCommands.size(), allCommands.size()),
124 allCommands
125 );
126 MainApplication.undoRedo.add(rootCommand);
127 } finally {
128 ds.endUpdate();
129 }
130 }
131
132 /**
133 * Replies true if <code>node</code> is a required node which can't be removed
134 * in order to simplify the way.
135 *
136 * @param way the way to be simplified
137 * @param node the node to check
138 * @return true if <code>node</code> is a required node which can't be removed
139 * in order to simplify the way.
140 */
141 protected static boolean isRequiredNode(Way way, Node node) {
142 int frequency = Collections.frequency(way.getNodes(), node);
143 if ((way.getNode(0) == node) && (way.getNode(way.getNodesCount()-1) == node)) {
144 frequency = frequency - 1; // closed way closing node counted only once
145 }
146 boolean isRequired = frequency > 1;
147 if (!isRequired) {
148 List<OsmPrimitive> parents = new LinkedList<>();
149 parents.addAll(node.getReferrers());
150 parents.remove(way);
151 isRequired = !parents.isEmpty();
152 }
153 if (!isRequired) {
154 isRequired = node.isTagged();
155 }
156 return isRequired;
157 }
158
159 /**
160 * Simplifies a way with default threshold (read from preferences).
161 *
162 * @param w the way to simplify
163 * @return The sequence of commands to run
164 * @since 6411
165 */
166 public final SequenceCommand simplifyWay(Way w) {
167 return simplifyWay(w, Main.pref.getDouble("simplify-way.max-error", 3.0));
168 }
169
170 /**
171 * Simplifies a way with a given threshold.
172 *
173 * @param w the way to simplify
174 * @param threshold the max error threshold
175 * @return The sequence of commands to run
176 * @since 6411
177 */
178 public static SequenceCommand simplifyWay(Way w, double threshold) {
179 int lower = 0;
180 int i = 0;
181 List<Node> newNodes = new ArrayList<>(w.getNodesCount());
182 while (i < w.getNodesCount()) {
183 if (isRequiredNode(w, w.getNode(i))) {
184 // copy a required node to the list of new nodes. Simplify not possible
185 newNodes.add(w.getNode(i));
186 i++;
187 lower++;
188 continue;
189 }
190 i++;
191 // find the longest sequence of not required nodes ...
192 while (i < w.getNodesCount() && !isRequiredNode(w, w.getNode(i))) {
193 i++;
194 }
195 // ... and simplify them
196 buildSimplifiedNodeList(w.getNodes(), lower, Math.min(w.getNodesCount()-1, i), threshold, newNodes);
197 lower = i;
198 i++;
199 }
200
201 // Closed way, check if the first node could also be simplified ...
202 if (newNodes.size() > 3 && newNodes.get(0) == newNodes.get(newNodes.size() - 1) && !isRequiredNode(w, newNodes.get(0))) {
203 final List<Node> l1 = Arrays.asList(newNodes.get(newNodes.size() - 2), newNodes.get(0), newNodes.get(1));
204 final List<Node> l2 = new ArrayList<>(3);
205 buildSimplifiedNodeList(l1, 0, 2, threshold, l2);
206 if (!l2.contains(newNodes.get(0))) {
207 newNodes.remove(0);
208 newNodes.set(newNodes.size() - 1, newNodes.get(0)); // close the way
209 }
210 }
211
212 Set<Node> delNodes = new HashSet<>();
213 delNodes.addAll(w.getNodes());
214 delNodes.removeAll(newNodes);
215
216 if (delNodes.isEmpty()) return null;
217
218 Collection<Command> cmds = new LinkedList<>();
219 Way newWay = new Way(w);
220 newWay.setNodes(newNodes);
221 cmds.add(new ChangeCommand(w, newWay));
222 cmds.add(new DeleteCommand(w.getDataSet(), delNodes));
223 w.getDataSet().clearSelection(delNodes);
224 return new SequenceCommand(
225 trn("Simplify Way (remove {0} node)", "Simplify Way (remove {0} nodes)", delNodes.size(), delNodes.size()), cmds);
226 }
227
228 /**
229 * Builds the simplified list of nodes for a way segment given by a lower index <code>from</code>
230 * and an upper index <code>to</code>
231 *
232 * @param wnew the way to simplify
233 * @param from the lower index
234 * @param to the upper index
235 * @param threshold the max error threshold
236 * @param simplifiedNodes list that will contain resulting nodes
237 */
238 protected static void buildSimplifiedNodeList(List<Node> wnew, int from, int to, double threshold, List<Node> simplifiedNodes) {
239
240 Node fromN = wnew.get(from);
241 Node toN = wnew.get(to);
242
243 // Get max xte
244 int imax = -1;
245 double xtemax = 0;
246 for (int i = from + 1; i < to; i++) {
247 Node n = wnew.get(i);
248 // CHECKSTYLE.OFF: SingleSpaceSeparator
249 double xte = Math.abs(Ellipsoid.WGS84.a
250 * xtd(fromN.lat() * Math.PI / 180, fromN.lon() * Math.PI / 180, toN.lat() * Math.PI / 180,
251 toN.lon() * Math.PI / 180, n.lat() * Math.PI / 180, n.lon() * Math.PI / 180));
252 // CHECKSTYLE.ON: SingleSpaceSeparator
253 if (xte > xtemax) {
254 xtemax = xte;
255 imax = i;
256 }
257 }
258
259 if (imax != -1 && xtemax >= threshold) {
260 // Segment cannot be simplified - try shorter segments
261 buildSimplifiedNodeList(wnew, from, imax, threshold, simplifiedNodes);
262 buildSimplifiedNodeList(wnew, imax, to, threshold, simplifiedNodes);
263 } else {
264 // Simplify segment
265 if (simplifiedNodes.isEmpty() || simplifiedNodes.get(simplifiedNodes.size()-1) != fromN) {
266 simplifiedNodes.add(fromN);
267 }
268 if (fromN != toN) {
269 simplifiedNodes.add(toN);
270 }
271 }
272 }
273
274 /* From Aviaton Formulary v1.3
275 * http://williams.best.vwh.net/avform.htm
276 */
277 private static double dist(double lat1, double lon1, double lat2, double lon2) {
278 return 2 * Math.asin(Math.sqrt(Math.pow(Math.sin((lat1 - lat2) / 2), 2) + Math.cos(lat1) * Math.cos(lat2)
279 * Math.pow(Math.sin((lon1 - lon2) / 2), 2)));
280 }
281
282 private static double course(double lat1, double lon1, double lat2, double lon2) {
283 return Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
284 * Math.cos(lat2) * Math.cos(lon1 - lon2))
285 % (2 * Math.PI);
286 }
287
288 private static double xtd(double lat1, double lon1, double lat2, double lon2, double lat3, double lon3) {
289 double distAD = dist(lat1, lon1, lat3, lon3);
290 double crsAD = course(lat1, lon1, lat3, lon3);
291 double crsAB = course(lat1, lon1, lat2, lon2);
292 return Math.asin(Math.sin(distAD) * Math.sin(crsAD - crsAB));
293 }
294
295 @Override
296 protected void updateEnabledState() {
297 updateEnabledStateOnCurrentSelection();
298 }
299
300 @Override
301 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
302 setEnabled(selection != null && !selection.isEmpty());
303 }
304}
Note: See TracBrowser for help on using the repository browser.