source: osm/applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/TheRing.java@ 26844

Last change on this file since 26844 was 26844, checked in by zverik, 14 years ago

Almost works

File size: 17.9 KB
Line 
1package relcontext.actions;
2
3import java.util.*;
4import javax.swing.JOptionPane;
5import org.openstreetmap.josm.Main;
6import org.openstreetmap.josm.command.*;
7import org.openstreetmap.josm.data.coor.EastNorth;
8import org.openstreetmap.josm.data.osm.*;
9import org.openstreetmap.josm.tools.Geometry;
10import org.openstreetmap.josm.tools.Geometry.PolygonIntersection;
11
12/**
13 * One ring that contains segments forming an outer way of multipolygon.
14 * This class is used in {@link CreateMultipolygonAction#makeManySimpleMultipolygons(java.util.Collection)}.
15 *
16 * @author Zverik
17 */
18public class TheRing {
19 private static final String PREF_MULTIPOLY = "reltoolbox.multipolygon.";
20
21 private Way source;
22 private List<RingSegment> segments;
23 private Relation relation = null;
24
25 public TheRing( Way source ) {
26 this.source = source;
27 segments = new ArrayList<RingSegment>(1);
28 segments.add(new RingSegment(source));
29 }
30
31 public static boolean areAllOfThoseRings( Collection<Way> ways ) {
32 List<Way> rings = new ArrayList<Way>();
33 for( Way way : ways ) {
34 if( way.isClosed() )
35 rings.add(way);
36 else
37 return false;
38 }
39 if( rings.isEmpty() || ways.size() == 1 )
40 return false;
41
42 // check for non-containment of rings
43 for( int i = 0; i < rings.size() - 1; i++ ) {
44 for( int j = i + 1; j < rings.size(); j++ ) {
45 PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
46 if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
47 return false;
48 }
49 }
50
51 return true;
52 }
53
54 /**
55 * Creates ALOT of Multipolygons and pets him gently.
56 * @return list of new relations.
57 */
58 public static List<Relation> makeManySimpleMultipolygons( Collection<Way> selection, List<Command> commands ) {
59 System.out.println("---------------------------------------");
60 List<TheRing> rings = new ArrayList<TheRing>(selection.size());
61 for( Way w : selection )
62 rings.add(new TheRing(w));
63 for( int i = 0; i < rings.size() - 1; i++ )
64 for( int j = i + 1; j < rings.size(); j++ )
65 rings.get(i).collide(rings.get(j));
66 redistributeSegments(rings);
67 List<Relation> relations = new ArrayList<Relation>();
68 for( TheRing r : rings ) {
69 commands.addAll(r.getCommands());
70 relations.add(r.getRelation());
71 }
72 return relations;
73 }
74
75 public void collide( TheRing other ) {
76 boolean collideNoted = false;
77 for( int i = 0; i < segments.size(); i++ ) {
78 RingSegment segment1 = segments.get(i);
79 if( !segment1.isReference() ) {
80 for( int j = 0; j < other.segments.size(); j++ ) {
81 RingSegment segment2 = other.segments.get(j);
82 if( !segment2.isReference() ) {
83 System.out.println("Comparing " + segment1 + " and " + segment2);
84 Node[] split = getSplitNodes(segment1.getNodes(), segment2.getNodes(), segment1.isRing(), segment2.isRing());
85 if( split != null ) {
86 if( !collideNoted ) {
87 System.out.println("Rings for ways " + source.getUniqueId() + " and " + other.source.getUniqueId() + " collide.");
88 collideNoted = true;
89 }
90 RingSegment segment = splitRingAt(i, split[0], split[1]);
91 RingSegment otherSegment = other.splitRingAt(j, split[2], split[3]);
92 if( !areSegmentsEqual(segment, otherSegment) )
93 throw new IllegalArgumentException("Error: algorithm gave incorrect segments: " + segment + " and " + otherSegment);
94 segment.makeReference(otherSegment);
95 }
96 }
97 if( segment1.isReference() )
98 break;
99 }
100 }
101 }
102 }
103
104 /**
105 * Returns array of {start1, last1, start2, last2} or null if there is no common nodes.
106 */
107 public static Node[] getSplitNodes( List<Node> nodes1, List<Node> nodes2, boolean isRing1, boolean isRing2 ) {
108 int pos = 0;
109 while( pos < nodes1.size() && !nodes2.contains(nodes1.get(pos)) )
110 pos++;
111 boolean collideFound = pos == nodes1.size();
112 if( pos == 0 && isRing1 ) {
113 // rewind a bit
114 pos = nodes1.size() - 1;
115 while( pos > 0 && nodes2.contains(nodes1.get(pos)) )
116 pos--;
117 if( pos == 0 ) {
118 JOptionPane.showMessageDialog(Main.parent, "Two rings are equal, and this must not be.", "Multipolygon from rings", JOptionPane.ERROR_MESSAGE);
119 return null;
120 }
121 pos = pos == nodes1.size() - 1 ? 0 : pos + 1;
122 }
123 int firstPos = isRing1 ? pos : nodes1.size();
124 while( !collideFound ) {
125 System.out.println("pos=" + pos);
126 int start1 = pos;
127 int start2 = nodes2.indexOf(nodes1.get(start1));
128 int last1 = incrementBy(start1, 1, nodes1.size(), isRing1);
129 int last2 = start2;
130 int increment2 = 0;
131 if( last1 >= 0 ) {
132 last2 = incrementBy(start2, -1, nodes2.size(), isRing2);
133 if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
134 increment2 = -1;
135 else {
136 last2 = incrementBy(start2, 1, nodes2.size(), isRing2);
137 if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
138 increment2 = 1;
139 }
140 }
141 System.out.println("last1=" + last1 + " last2=" + last2 + " increment2=" + increment2);
142 if( increment2 != 0 ) {
143 // find the first nodes
144 boolean reachedEnd = false;
145 while( !reachedEnd ) {
146 int newLast1 = incrementBy(last1, 1, nodes1.size(), isRing1);
147 int newLast2 = incrementBy(last2, increment2, nodes2.size(), isRing2);
148 if( newLast1 < 0 || newLast2 < 0 || !nodes1.get(newLast1).equals(nodes2.get(newLast2)) )
149 reachedEnd = true;
150 else {
151 last1 = newLast1;
152 last2 = newLast2;
153 }
154 }
155 System.out.println("last1=" + last1 + " last2=" + last2);
156 if( increment2 < 0 ) {
157 int tmp = start2;
158 start2 = last2;
159 last2 = tmp;
160 }
161 return new Node[] {nodes1.get(start1), nodes1.get(last1), nodes2.get(start2), nodes2.get(last2)};
162 } else {
163 pos = last1;
164 while( pos != firstPos && pos >= 0 && !nodes2.contains(nodes1.get(pos)) )
165 pos = incrementBy(pos, 1, nodes1.size(), isRing1);
166 if( pos < 0 || pos == firstPos || !nodes2.contains(nodes1.get(pos)) )
167 collideFound = true;
168 }
169 }
170 return null;
171 }
172
173 private static int incrementBy( int value, int increment, int limit1, boolean isRing ) {
174 int result = value + increment;
175 if( result < 0 )
176 return isRing ? result + limit1 : -1;
177 else if( result >= limit1 )
178 return isRing ? result - limit1 : -1;
179 else
180 return result;
181 }
182
183 private boolean areSegmentsEqual( RingSegment seg1, RingSegment seg2 ) {
184 List<Node> nodes1 = seg1.getNodes();
185 List<Node> nodes2 = seg2.getNodes();
186 int size = nodes1.size();
187 if( size != nodes2.size() )
188 return false;
189 boolean reverse = size > 1 && !nodes1.get(0).equals(nodes2.get(0));
190 for( int i = 0; i < size; i++ )
191 if( !nodes1.get(i).equals(nodes2.get(reverse ? size-1-i : i)) )
192 return false;
193 return true;
194 }
195
196 /**
197 * Split the segment in this ring at those nodes.
198 * @return The segment between nodes.
199 */
200 private RingSegment splitRingAt( int segmentIndex, Node n1, Node n2 ) {
201 if( n1.equals(n2) )
202 throw new IllegalArgumentException("Both nodes are equal, id=" + n1.getUniqueId());
203 RingSegment segment = segments.get(segmentIndex);
204 boolean isRing = segment.isRing();
205 System.out.println("Split segment " + segment + " at nodes " + n1.getUniqueId() + " and " + n2.getUniqueId());
206 boolean reversed = segment.getNodes().indexOf(n2) < segment.getNodes().indexOf(n1);
207 if( reversed && !isRing ) {
208 // order nodes
209 Node tmp = n1;
210 n1 = n2;
211 n2 = tmp;
212 }
213 RingSegment secondPart = isRing ? segment.split(n1, n2) : segment.split(n1);
214 // if secondPart == null, then n1 == firstNode
215 RingSegment thirdPart = isRing ? null : secondPart == null ? segment.split(n2) : secondPart.split(n2);
216 // if secondPart == null, then thirdPart is between n1 and n2
217 // otherwise, thirdPart is between n2 and lastNode
218 // if thirdPart == null, then n2 == lastNode
219 int pos = segmentIndex + 1;
220 if( secondPart != null )
221 segments.add(pos++, secondPart);
222 if( thirdPart != null )
223 segments.add(pos++, thirdPart);
224 return isRing || secondPart == null ? segment : secondPart;
225 }
226
227 /**
228 * Tries to arrange segments in order for each ring to have at least one.
229 * Also, sets source way for all rings.
230 *
231 * If this method is not called, do not forget to call {@link #putSourceWayFirst()} for all rings.
232 */
233 public static void redistributeSegments( List<TheRing> rings ) {
234 // build segments map
235 Map<RingSegment, TheRing> segmentMap = new HashMap<RingSegment, TheRing>();
236 for( TheRing ring : rings )
237 for( RingSegment seg : ring.segments )
238 if( !seg.isReference() )
239 segmentMap.put(seg, ring);
240
241 // rearrange references
242 for( int i = 0; i < rings.size(); i++ ) {
243 TheRing ring = rings.get(i);
244 if( ring.countNonReferenceSegments() == 0 ) {
245 // need to find one non-reference segment
246 for( RingSegment seg : ring.segments ) {
247 TheRing otherRing = segmentMap.get(seg.references);
248 if( otherRing.countNonReferenceSegments() > 1 ) {
249 // we could check for >0, but it is prone to deadlocking
250 seg.swapReference();
251 }
252 }
253 }
254 }
255
256 // initializing source way for each ring
257 for( TheRing ring : rings )
258 ring.putSourceWayFirst();
259 }
260
261 private int countNonReferenceSegments() {
262 int count = 0;
263 for( RingSegment seg : segments )
264 if( !seg.isReference() )
265 count++;
266 return count;
267 }
268
269 public void putSourceWayFirst() {
270 for( RingSegment seg : segments ) {
271 if( !seg.isReference() ) {
272 seg.overrideWay(source);
273 return;
274 }
275 }
276 }
277
278 public List<Command> getCommands() {
279 return getCommands(true);
280 }
281
282 /**
283 * Returns a list of commands to make a new relation and all newly created ways.
284 * The first way is copied from the source one, ChangeCommand is issued in this case.
285 */
286 public List<Command> getCommands( boolean createMultipolygon ) {
287 Way sourceCopy = new Way(source);
288 if( createMultipolygon ) {
289 Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
290 relation = new Relation();
291 relation.put("type", "multipolygon");
292 for( String key : sourceCopy.keySet() ) {
293 if( !linearTags.contains(key) ) {
294 relation.put(key, sourceCopy.get(key));
295 sourceCopy.remove(key);
296 }
297 }
298 }
299
300 // build a map of referencing relations
301 Map<Relation, Integer> referencingRelations = new HashMap<Relation, Integer>();
302 List<Command> relationCommands = new ArrayList<Command>();
303 for( OsmPrimitive p : source.getReferrers() ) {
304 if( p instanceof Relation ) {
305 Relation rel = new Relation((Relation)p);
306 relationCommands.add(new ChangeCommand((Relation)p, rel));
307 for( int i = 0; i < rel.getMembersCount(); i++ )
308 if( rel.getMember(i).getMember().equals(source) )
309 referencingRelations.put(rel, Integer.valueOf(i));
310 }
311 }
312
313 List<Command> commands = new ArrayList<Command>();
314 boolean foundOwnWay = false;
315 for( RingSegment seg : segments ) {
316 boolean needAdding = !seg.isWayConstructed();
317 Way w = seg.constructWay(seg.isReference() ? null : sourceCopy);
318 if( needAdding )
319 commands.add(new AddCommand(w));
320 if( w.equals(source) ) {
321 if( createMultipolygon || !seg.getWayNodes().equals(source.getNodes()) ) {
322 sourceCopy.setNodes(seg.getWayNodes());
323 commands.add(new ChangeCommand(source, sourceCopy));
324 }
325 foundOwnWay = true;
326 } else {
327 for( Relation rel : referencingRelations.keySet() ) {
328 int relIndex = referencingRelations.get(rel);
329 rel.addMember(new RelationMember(rel.getMember(relIndex).getRole(), w));
330 }
331 }
332 if( createMultipolygon )
333 relation.addMember(new RelationMember("outer", w));
334 }
335 if( !foundOwnWay )
336 commands.add(new DeleteCommand(source));
337 commands.addAll(relationCommands);
338 if( createMultipolygon )
339 commands.add(new AddCommand(relation));
340 return commands;
341 }
342
343 /**
344 * Returns the relation created in {@link #getCommands()}.
345 */
346 public Relation getRelation() {
347 return relation;
348 }
349
350 @Override
351 public String toString() {
352 StringBuilder sb = new StringBuilder("TheRing@");
353 sb.append(this.hashCode()).append('[').append("wayId: ").append(source == null ? "null" : source.getUniqueId()).append("; segments: ");
354 if( segments.isEmpty() )
355 sb.append("empty");
356 else {
357 sb.append(segments.get(0));
358 for( int i = 1; i < segments.size(); i++ )
359 sb.append(", ").append(segments.get(i));
360 }
361 return sb.append(']').toString();
362 }
363
364 /**
365 * Appends "append" to "base" so the closed polygon forms.
366 */
367 private static void closePolygon( List<Node> base, List<Node> append ) {
368 if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
369 List<Node> ap2 = new ArrayList<Node>(append);
370 Collections.reverse(ap2);
371 append = ap2;
372 }
373 base.remove(base.size() - 1);
374 base.addAll(append);
375 }
376
377 /**
378 * Checks if a middle point between two nodes is inside a polygon. Useful to check if the way is inside.
379 */
380 private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) {
381 EastNorth en1 = n1.getEastNorth();
382 EastNorth en2 = n2.getEastNorth();
383 Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
384 return Geometry.nodeInsidePolygon(testNode, polygon);
385 }
386
387 private static class RingSegment {
388 private List<Node> nodes;
389 private RingSegment references;
390 private Way resultingWay = null;
391 private boolean wasTemplateApplied = false;
392 private boolean isRing;
393
394 private RingSegment() {
395 }
396
397 public RingSegment( Way w ) {
398 this(w.getNodes());
399 }
400
401 public RingSegment( List<Node> nodes ) {
402 this.nodes = nodes;
403 isRing = nodes.size() > 1 && nodes.get(0).equals(nodes.get(nodes.size() - 1));
404 if( isRing )
405 nodes.remove(nodes.size() - 1);
406 references = null;
407 }
408
409 public RingSegment( RingSegment ref ) {
410 this.nodes = null;
411 this.references = ref;
412 }
413
414 /**
415 * Splits this segment at node n. Retains nodes 0..n and moves
416 * nodes n..N to a separate segment that is returned.
417 * @param n node at which to split.
418 * @return new segment, {@code null} if splitting is unnecessary.
419 */
420 public RingSegment split( Node n ) {
421 if( nodes == null )
422 throw new IllegalArgumentException("Cannot split segment: it is a reference");
423 int pos = nodes.indexOf(n);
424 if( pos <= 0 || pos >= nodes.size() - 1 )
425 return null;
426 List<Node> newNodes = new ArrayList<Node>(nodes.subList(pos, nodes.size()));
427 nodes.subList(pos + 1, nodes.size()).clear();
428 return new RingSegment(newNodes);
429 }
430
431 /**
432 * Split this segment as a way at two nodes. If one of them is null or at the end,
433 * split as an arc. Note: order of nodes is important.
434 * @return A new segment from n2 to n1.
435 */
436 public RingSegment split( Node n1, Node n2 ) {
437 if( nodes == null )
438 throw new IllegalArgumentException("Cannot split segment: it is a reference");
439 if( !isRing ) {
440 if( n1 == null || nodes.get(0).equals(n1) || nodes.get(nodes.size() - 1).equals(n1) )
441 return split(n2);
442 if( n2 == null || nodes.get(0).equals(n2) || nodes.get(nodes.size() - 1).equals(n2) )
443 return split(n1);
444 throw new IllegalArgumentException("Split for two nodes is called for not-ring: " + this);
445 }
446 int pos1 = nodes.indexOf(n1);
447 int pos2 = nodes.indexOf(n2);
448 if( pos1 == pos2 )
449 return null;
450
451 List<Node> newNodes = new ArrayList<Node>();
452 if( pos2 > pos1 ) {
453 newNodes.addAll(nodes.subList(pos2, nodes.size()));
454 newNodes.addAll(nodes.subList(0, pos1 + 1));
455 if( pos2 + 1 < nodes.size() )
456 nodes.subList(pos2 + 1, nodes.size()).clear();
457 if( pos1 > 0 )
458 nodes.subList(0, pos1).clear();
459 } else {
460 newNodes.addAll(nodes.subList(pos2, pos1 + 1));
461 nodes.addAll(new ArrayList<Node>(nodes.subList(0, pos2 + 1)));
462 nodes.subList(0, pos1).clear();
463 }
464 isRing = false;
465 return new RingSegment(newNodes);
466 }
467
468 public List<Node> getNodes() {
469 return nodes == null ? references.nodes : nodes;
470 }
471
472 public List<Node> getWayNodes() {
473 if( nodes == null )
474 throw new IllegalArgumentException("Won't give you wayNodes: it is a reference");
475 List<Node> wayNodes = new ArrayList<Node>(nodes);
476 if( isRing )
477 wayNodes.add(wayNodes.get(0));
478 return wayNodes;
479 }
480
481 public boolean isReference() {
482 return nodes == null;
483 }
484
485 public boolean isRing() {
486 return isRing;
487 }
488
489 public void makeReference( RingSegment segment ) {
490 System.out.println(this + " was made a reference to " + segment);
491 this.nodes = null;
492 this.references = segment;
493 }
494
495 public void swapReference() {
496 this.nodes = references.nodes;
497 references.nodes = null;
498 references.references = this;
499 this.references = null;
500 }
501
502 public boolean isWayConstructed() {
503 return isReference() ? references.isWayConstructed() : resultingWay != null;
504 }
505
506 public Way constructWay( Way template ) {
507 if( isReference() )
508 return references.constructWay(template);
509 if( resultingWay == null ) {
510 resultingWay = new Way();
511 resultingWay.setNodes(getWayNodes());
512 }
513 if( template != null && !wasTemplateApplied ) {
514 resultingWay.setKeys(template.getKeys());
515 wasTemplateApplied = true;
516 }
517 return resultingWay;
518 }
519
520 public void overrideWay( Way source ) {
521 if( isReference() )
522 references.overrideWay(source);
523 else {
524 resultingWay = source;
525 wasTemplateApplied = true;
526 }
527 }
528
529 /**
530 * Compares two segments with respect to referencing.
531 * @return true if ways are equals, or one references another.
532 */
533 public boolean isReferencingEqual( RingSegment other ) {
534 return this.equals(other) || (other.isReference() && other.references == this) || (isReference() && references == other);
535 }
536
537 @Override
538 public String toString() {
539 StringBuilder sb = new StringBuilder("RingSegment@");
540 sb.append(this.hashCode()).append('[');
541 if( isReference() )
542 sb.append("references ").append(references.hashCode());
543 else if( nodes.isEmpty() )
544 sb.append("empty");
545 else {
546 if( isRing )
547 sb.append("ring:");
548 sb.append(nodes.get(0).getUniqueId());
549 for( int i = 1; i < nodes.size(); i++ )
550 sb.append(',').append(nodes.get(i).getUniqueId());
551 }
552 return sb.append(']').toString();
553 }
554 }
555}
Note: See TracBrowser for help on using the repository browser.