source: josm/trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/relations/Multipolygon.java@ 4667

Last change on this file since 4667 was 4667, checked in by Don-vip, 12 years ago

fix #7162 - undoing multipolygon changes causes exception (NPE)

  • Property svn:eol-style set to native
File size: 21.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm.visitor.paint.relations;
3
4import java.awt.geom.Path2D;
5import java.awt.geom.Path2D.Double;
6import java.awt.geom.PathIterator;
7import java.awt.geom.Point2D;
8import java.awt.geom.Rectangle2D;
9import java.util.ArrayList;
10import java.util.Collection;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.Iterator;
14import java.util.List;
15import java.util.Set;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
19import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
20import org.openstreetmap.josm.data.osm.DataSet;
21import org.openstreetmap.josm.data.osm.Node;
22import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
23import org.openstreetmap.josm.data.osm.Relation;
24import org.openstreetmap.josm.data.osm.RelationMember;
25import org.openstreetmap.josm.data.osm.Way;
26import org.openstreetmap.josm.data.osm.event.NodeMovedEvent;
27import org.openstreetmap.josm.data.osm.event.WayNodesChangedEvent;
28import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.PolyData.Intersection;
29
30public class Multipolygon {
31 /** preference key for a collection of roles which indicate that the respective member belongs to an
32 * <em>outer</em> polygon. Default is <tt>outer</tt>.
33 */
34 static public final String PREF_KEY_OUTER_ROLES = "mappaint.multipolygon.outer.roles";
35 /** preference key for collection of role prefixes which indicate that the respective
36 * member belongs to an <em>outer</em> polygon. Default is empty.
37 */
38 static public final String PREF_KEY_OUTER_ROLE_PREFIXES = "mappaint.multipolygon.outer.role-prefixes";
39 /** preference key for a collection of roles which indicate that the respective member belongs to an
40 * <em>inner</em> polygon. Default is <tt>inner</tt>.
41 */
42 static public final String PREF_KEY_INNER_ROLES = "mappaint.multipolygon.inner.roles";
43 /** preference key for collection of role prefixes which indicate that the respective
44 * member belongs to an <em>inner</em> polygon. Default is empty.
45 */
46 static public final String PREF_KEY_INNER_ROLE_PREFIXES = "mappaint.multipolygon.inner.role-prefixes";
47
48 /**
49 * <p>Kind of strategy object which is responsible for deciding whether a given
50 * member role indicates that the member belongs to an <em>outer</em> or an
51 * <em>inner</em> polygon.</p>
52 *
53 * <p>The decision is taken based on preference settings, see the four preference keys
54 * above.</p>
55 *
56 */
57 private static class MultipolygonRoleMatcher implements PreferenceChangedListener{
58 private final List<String> outerExactRoles = new ArrayList<String>();
59 private final List<String> outerRolePrefixes = new ArrayList<String>();
60 private final List<String> innerExactRoles = new ArrayList<String>();
61 private final List<String> innerRolePrefixes = new ArrayList<String>();
62
63 private void initDefaults() {
64 outerExactRoles.clear();
65 outerRolePrefixes.clear();
66 innerExactRoles.clear();
67 innerRolePrefixes.clear();
68 outerExactRoles.add("outer");
69 innerExactRoles.add("inner");
70 }
71
72 private void setNormalized(Collection<String> literals, List<String> target){
73 target.clear();
74 for(String l: literals) {
75 if (l == null) {
76 continue;
77 }
78 l = l.trim();
79 if (!target.contains(l)) {
80 target.add(l);
81 }
82 }
83 }
84
85 private void initFromPreferences() {
86 initDefaults();
87 if (Main.pref == null) return;
88 Collection<String> literals;
89 literals = Main.pref.getCollection(PREF_KEY_OUTER_ROLES);
90 if (literals != null && !literals.isEmpty()){
91 setNormalized(literals, outerExactRoles);
92 }
93 literals = Main.pref.getCollection(PREF_KEY_OUTER_ROLE_PREFIXES);
94 if (literals != null && !literals.isEmpty()){
95 setNormalized(literals, outerRolePrefixes);
96 }
97 literals = Main.pref.getCollection(PREF_KEY_INNER_ROLES);
98 if (literals != null && !literals.isEmpty()){
99 setNormalized(literals, innerExactRoles);
100 }
101 literals = Main.pref.getCollection(PREF_KEY_INNER_ROLE_PREFIXES);
102 if (literals != null && !literals.isEmpty()){
103 setNormalized(literals, innerRolePrefixes);
104 }
105 }
106
107 @Override
108 public void preferenceChanged(PreferenceChangeEvent evt) {
109 if (PREF_KEY_INNER_ROLE_PREFIXES.equals(evt.getKey()) ||
110 PREF_KEY_INNER_ROLES.equals(evt.getKey()) ||
111 PREF_KEY_OUTER_ROLE_PREFIXES.equals(evt.getKey()) ||
112 PREF_KEY_OUTER_ROLES.equals(evt.getKey())){
113 initFromPreferences();
114 }
115 }
116
117 public boolean isOuterRole(String role){
118 if (role == null) return false;
119 for (String candidate: outerExactRoles) {
120 if (role.equals(candidate)) return true;
121 }
122 for (String candidate: outerRolePrefixes) {
123 if (role.startsWith(candidate)) return true;
124 }
125 return false;
126 }
127
128 public boolean isInnerRole(String role){
129 if (role == null) return false;
130 for (String candidate: innerExactRoles) {
131 if (role.equals(candidate)) return true;
132 }
133 for (String candidate: innerRolePrefixes) {
134 if (role.startsWith(candidate)) return true;
135 }
136 return false;
137 }
138 }
139
140 /*
141 * Init a private global matcher object which will listen to preference
142 * changes.
143 */
144 private static MultipolygonRoleMatcher roleMatcher;
145 private static MultipolygonRoleMatcher getMultipolygonRoleMatcher() {
146 if (roleMatcher == null) {
147 roleMatcher = new MultipolygonRoleMatcher();
148 if (Main.pref != null){
149 roleMatcher.initFromPreferences();
150 Main.pref.addPreferenceChangeListener(roleMatcher);
151 }
152 }
153 return roleMatcher;
154 }
155
156 public static class JoinedWay {
157 private final List<Node> nodes;
158 private final Collection<Long> wayIds;
159 private final boolean selected;
160
161 public JoinedWay(List<Node> nodes, Collection<Long> wayIds, boolean selected) {
162 this.nodes = nodes;
163 this.wayIds = wayIds;
164 this.selected = selected;
165 }
166
167 public List<Node> getNodes() {
168 return nodes;
169 }
170
171 public Collection<Long> getWayIds() {
172 return wayIds;
173 }
174
175 public boolean isSelected() {
176 return selected;
177 }
178
179 public boolean isClosed() {
180 return nodes.isEmpty() || nodes.get(nodes.size() - 1).equals(nodes.get(0));
181 }
182 }
183
184 public static class PolyData {
185 public enum Intersection {INSIDE, OUTSIDE, CROSSING}
186
187 private final Path2D.Double poly;
188 public boolean selected;
189 private Rectangle2D bounds;
190 private final Collection<Long> wayIds;
191 private final List<Node> nodes;
192 private final List<PolyData> inners;
193
194 public PolyData(Way closedWay) {
195 this(closedWay.getNodes(), closedWay.isSelected(), Collections.singleton(closedWay.getUniqueId()));
196 }
197
198 public PolyData(JoinedWay joinedWay) {
199 this(joinedWay.getNodes(), joinedWay.isSelected(), joinedWay.getWayIds());
200 }
201
202 private PolyData(List<Node> nodes, boolean selected, Collection<Long> wayIds) {
203 this.wayIds = Collections.unmodifiableCollection(wayIds);
204 this.nodes = new ArrayList<Node>(nodes);
205 this.selected = selected;
206 this.inners = new ArrayList<Multipolygon.PolyData>();
207 this.poly = new Path2D.Double();
208 this.poly.setWindingRule(Path2D.WIND_EVEN_ODD);
209 buildPoly();
210 }
211
212 private void buildPoly() {
213 boolean initial = true;
214 for (Node n : nodes) {
215 Point2D p = n.getEastNorth();
216 if (initial) {
217 poly.moveTo(p.getX(), p.getY());
218 initial = false;
219 } else {
220 poly.lineTo(p.getX(), p.getY());
221 }
222 }
223 poly.closePath();
224 for (PolyData inner : inners) {
225 appendInner(inner.poly);
226 }
227 }
228
229 public PolyData(PolyData copy) {
230 this.selected = copy.selected;
231 this.poly = (Double) copy.poly.clone();
232 this.wayIds = Collections.unmodifiableCollection(copy.wayIds);
233 this.nodes = new ArrayList<Node>(copy.nodes);
234 this.inners = new ArrayList<Multipolygon.PolyData>(copy.inners);
235 }
236
237 public Intersection contains(Path2D.Double p) {
238 int contains = 0;
239 int total = 0;
240 double[] coords = new double[6];
241 for (PathIterator it = p.getPathIterator(null); !it.isDone(); it.next()) {
242 switch (it.currentSegment(coords)) {
243 case PathIterator.SEG_MOVETO:
244 case PathIterator.SEG_LINETO:
245 if (poly.contains(coords[0], coords[1])) {
246 contains++;
247 }
248 total++;
249 }
250 }
251 if (contains == total) return Intersection.INSIDE;
252 if (contains == 0) return Intersection.OUTSIDE;
253 return Intersection.CROSSING;
254 }
255
256 public void addInner(PolyData inner) {
257 inners.add(inner);
258 appendInner(inner.poly);
259 }
260
261 private void appendInner(Path2D.Double inner) {
262 poly.append(inner.getPathIterator(null), false);
263 }
264
265 public Path2D.Double get() {
266 return poly;
267 }
268
269 public Rectangle2D getBounds() {
270 if (bounds == null) {
271 bounds = poly.getBounds2D();
272 }
273 return bounds;
274 }
275
276 public Collection<Long> getWayIds() {
277 return wayIds;
278 }
279
280 private void resetNodes() {
281 if (!nodes.isEmpty()) {
282 DataSet ds = null;
283 // Find DataSet (can be null for several nodes when undoing nodes creation, see #7162)
284 for (Iterator<Node> it = nodes.iterator(); it.hasNext() && ds == null; ) {
285 ds = it.next().getDataSet();
286 }
287 nodes.clear();
288 if (ds == null) {
289 // DataSet still not found. This should not happen, but a warning does no harm
290 System.err.println("Warning: DataSet not found while resetting nodes in Multipolygon. This should not happen, you may report it to JOSM developers.");
291 } else if (wayIds.size() == 1) {
292 Way w = (Way) ds.getPrimitiveById(wayIds.iterator().next(), OsmPrimitiveType.WAY);
293 nodes.addAll(w.getNodes());
294 } else {
295 List<Way> waysToJoin = new ArrayList<Way>();
296 for (Iterator<Long> it = wayIds.iterator(); it.hasNext(); ) {
297 waysToJoin.add((Way) ds.getPrimitiveById(it.next(), OsmPrimitiveType.WAY));
298 }
299 nodes.addAll(joinWays(waysToJoin).iterator().next().getNodes());
300 }
301 resetPoly();
302 }
303 }
304
305 private void resetPoly() {
306 poly.reset();
307 buildPoly();
308 bounds = null;
309 }
310
311 public void nodeMoved(NodeMovedEvent event) {
312 final Node n = event.getNode();
313 boolean innerChanged = false;
314 for (PolyData inner : inners) {
315 if (inner.nodes.contains(n)) {
316 inner.resetPoly();
317 innerChanged = true;
318 }
319 }
320 if (nodes.contains(n) || innerChanged) {
321 resetPoly();
322 }
323 }
324
325 public void wayNodesChanged(WayNodesChangedEvent event) {
326 final Long wayId = event.getChangedWay().getUniqueId();
327 boolean innerChanged = false;
328 for (PolyData inner : inners) {
329 if (inner.wayIds.contains(wayId)) {
330 inner.resetNodes();
331 innerChanged = true;
332 }
333 }
334 if (wayIds.contains(wayId) || innerChanged) {
335 resetNodes();
336 }
337 }
338 }
339
340 private final List<Way> innerWays = new ArrayList<Way>();
341 private final List<Way> outerWays = new ArrayList<Way>();
342 private final List<PolyData> innerPolygons = new ArrayList<PolyData>();
343 private final List<PolyData> outerPolygons = new ArrayList<PolyData>();
344 private final List<PolyData> combinedPolygons = new ArrayList<PolyData>();
345
346 private boolean incomplete;
347
348 public Multipolygon(Relation r) {
349 load(r);
350 }
351
352 private void load(Relation r) {
353 MultipolygonRoleMatcher matcher = getMultipolygonRoleMatcher();
354
355 // Fill inner and outer list with valid ways
356 for (RelationMember m : r.getMembers()) {
357 if (m.getMember().isIncomplete()) {
358 this.incomplete = true;
359 } else if (m.getMember().isDrawable()) {
360 if (m.isWay()) {
361 Way w = m.getWay();
362
363 if (w.getNodesCount() < 2) {
364 continue;
365 }
366
367 if (matcher.isInnerRole(m.getRole())) {
368 innerWays.add(w);
369 } else if (matcher.isOuterRole(m.getRole())) {
370 outerWays.add(w);
371 } else if (!m.hasRole()) {
372 outerWays.add(w);
373 } // Remaining roles ignored
374 } // Non ways ignored
375 }
376 }
377
378 createPolygons(innerWays, innerPolygons);
379 createPolygons(outerWays, outerPolygons);
380 if (!outerPolygons.isEmpty()) {
381 addInnerToOuters();
382 }
383 }
384
385 public final boolean isIncomplete() {
386 return incomplete;
387 }
388
389 private void createPolygons(List<Way> ways, List<PolyData> result) {
390 List<Way> waysToJoin = new ArrayList<Way>();
391 for (Way way: ways) {
392 if (way.isClosed()) {
393 result.add(new PolyData(way));
394 } else {
395 waysToJoin.add(way);
396 }
397 }
398
399 for (JoinedWay jw: joinWays(waysToJoin)) {
400 result.add(new PolyData(jw));
401 }
402 }
403
404 public static Collection<JoinedWay> joinWays(Collection<Way> waysToJoin)
405 {
406 final Collection<JoinedWay> result = new ArrayList<JoinedWay>();
407 final Way[] joinArray = waysToJoin.toArray(new Way[waysToJoin.size()]);
408 int left = waysToJoin.size();
409 while (left > 0) {
410 Way w = null;
411 boolean selected = false;
412 List<Node> nodes = null;
413 Set<Long> wayIds = new HashSet<Long>();
414 boolean joined = true;
415 while (joined && left > 0) {
416 joined = false;
417 for (int i = 0; i < joinArray.length && left != 0; ++i) {
418 if (joinArray[i] != null) {
419 Way c = joinArray[i];
420 if (w == null) {
421 w = c;
422 selected = w.isSelected();
423 joinArray[i] = null;
424 --left;
425 } else {
426 int mode = 0;
427 int cl = c.getNodesCount()-1;
428 int nl;
429 if (nodes == null) {
430 nl = w.getNodesCount()-1;
431 if (w.getNode(nl) == c.getNode(0)) {
432 mode = 21;
433 } else if (w.getNode(nl) == c.getNode(cl)) {
434 mode = 22;
435 } else if (w.getNode(0) == c.getNode(0)) {
436 mode = 11;
437 } else if (w.getNode(0) == c.getNode(cl)) {
438 mode = 12;
439 }
440 } else {
441 nl = nodes.size()-1;
442 if (nodes.get(nl) == c.getNode(0)) {
443 mode = 21;
444 } else if (nodes.get(0) == c.getNode(cl)) {
445 mode = 12;
446 } else if (nodes.get(0) == c.getNode(0)) {
447 mode = 11;
448 } else if (nodes.get(nl) == c.getNode(cl)) {
449 mode = 22;
450 }
451 }
452 if (mode != 0) {
453 joinArray[i] = null;
454 joined = true;
455 if (c.isSelected()) {
456 selected = true;
457 }
458 --left;
459 if (nodes == null) {
460 nodes = w.getNodes();
461 wayIds.add(w.getUniqueId());
462 }
463 nodes.remove((mode == 21 || mode == 22) ? nl : 0);
464 if (mode == 21) {
465 nodes.addAll(c.getNodes());
466 } else if (mode == 12) {
467 nodes.addAll(0, c.getNodes());
468 } else if (mode == 22) {
469 for (Node node : c.getNodes()) {
470 nodes.add(nl, node);
471 }
472 } else /* mode == 11 */ {
473 for (Node node : c.getNodes()) {
474 nodes.add(0, node);
475 }
476 }
477 wayIds.add(c.getUniqueId());
478 }
479 }
480 }
481 } /* for(i = ... */
482 } /* while(joined) */
483
484 if (nodes == null) {
485 nodes = w.getNodes();
486 wayIds.add(w.getUniqueId());
487 }
488
489 result.add(new JoinedWay(nodes, wayIds, selected));
490 } /* while(left != 0) */
491
492 return result;
493 }
494
495 public PolyData findOuterPolygon(PolyData inner, List<PolyData> outerPolygons) {
496
497 // First try to test only bbox, use precise testing only if we don't get unique result
498 Rectangle2D innerBox = inner.getBounds();
499 PolyData insidePolygon = null;
500 PolyData intersectingPolygon = null;
501 int insideCount = 0;
502 int intersectingCount = 0;
503
504 for (PolyData outer: outerPolygons) {
505 if (outer.getBounds().contains(innerBox)) {
506 insidePolygon = outer;
507 insideCount++;
508 } else if (outer.getBounds().intersects(innerBox)) {
509 intersectingPolygon = outer;
510 intersectingCount++;
511 }
512 }
513
514 if (insideCount == 1)
515 return insidePolygon;
516 else if (intersectingCount == 1)
517 return intersectingPolygon;
518
519 PolyData result = null;
520 for (PolyData combined : outerPolygons) {
521 Intersection c = combined.contains(inner.poly);
522 if (c != Intersection.OUTSIDE)
523 {
524 if (result == null || result.contains(combined.poly) != Intersection.INSIDE) {
525 result = combined;
526 }
527 }
528 }
529 return result;
530 }
531
532 private void addInnerToOuters() {
533
534 if (innerPolygons.isEmpty()) {
535 combinedPolygons.addAll(outerPolygons);
536 } else if (outerPolygons.size() == 1) {
537 PolyData combinedOuter = new PolyData(outerPolygons.get(0));
538 for (PolyData inner: innerPolygons) {
539 combinedOuter.addInner(inner);
540 }
541 combinedPolygons.add(combinedOuter);
542 } else {
543 for (PolyData outer: outerPolygons) {
544 combinedPolygons.add(new PolyData(outer));
545 }
546
547 for (PolyData pdInner: innerPolygons) {
548 PolyData o = findOuterPolygon(pdInner, combinedPolygons);
549 if (o == null) {
550 o = outerPolygons.get(0);
551 }
552 o.addInner(pdInner);
553 }
554 }
555
556 // Clear inner and outer polygons to reduce memory footprint
557 innerPolygons.clear();
558 outerPolygons.clear();
559 }
560
561 public List<Way> getOuterWays() {
562 return outerWays;
563 }
564
565 public List<Way> getInnerWays() {
566 return innerWays;
567 }
568/*
569 public List<PolyData> getInnerPolygons() {
570 return innerPolygons;
571 }
572
573 public List<PolyData> getOuterPolygons() {
574 return outerPolygons;
575 }
576*/
577 public List<PolyData> getCombinedPolygons() {
578 return combinedPolygons;
579 }
580}
Note: See TracBrowser for help on using the repository browser.