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

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

Most of it works, except one small bug

File size: 18.3 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 // todo: когда два кольца меняют одно и то же отношение, в список команд добавляется
313 // изменение базового отношения на новое, а не предыдущего
314 // поэтому сохраняется только первое изменение
315
316 List<Command> commands = new ArrayList<Command>();
317 boolean foundOwnWay = false;
318 for( RingSegment seg : segments ) {
319 boolean needAdding = !seg.isWayConstructed();
320 Way w = seg.constructWay(seg.isReference() ? null : sourceCopy);
321 if( needAdding )
322 commands.add(new AddCommand(w));
323 if( w.equals(source) ) {
324 if( createMultipolygon || !seg.getWayNodes().equals(source.getNodes()) ) {
325 sourceCopy.setNodes(seg.getWayNodes());
326 commands.add(new ChangeCommand(source, sourceCopy));
327 }
328 foundOwnWay = true;
329 } else {
330 for( Relation rel : referencingRelations.keySet() ) {
331 int relIndex = referencingRelations.get(rel);
332 rel.addMember(new RelationMember(rel.getMember(relIndex).getRole(), w));
333 }
334 }
335 if( createMultipolygon )
336 relation.addMember(new RelationMember("outer", w));
337 }
338 if( !foundOwnWay )
339 commands.add(new DeleteCommand(source));
340 commands.addAll(relationCommands);
341 if( createMultipolygon )
342 commands.add(new AddCommand(relation));
343 return commands;
344 }
345
346 /**
347 * Returns the relation created in {@link #getCommands()}.
348 */
349 public Relation getRelation() {
350 return relation;
351 }
352
353 @Override
354 public String toString() {
355 StringBuilder sb = new StringBuilder("TheRing@");
356 sb.append(this.hashCode()).append('[').append("wayId: ").append(source == null ? "null" : source.getUniqueId()).append("; segments: ");
357 if( segments.isEmpty() )
358 sb.append("empty");
359 else {
360 sb.append(segments.get(0));
361 for( int i = 1; i < segments.size(); i++ )
362 sb.append(", ").append(segments.get(i));
363 }
364 return sb.append(']').toString();
365 }
366
367 /**
368 * Appends "append" to "base" so the closed polygon forms.
369 */
370 private static void closePolygon( List<Node> base, List<Node> append ) {
371 if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
372 List<Node> ap2 = new ArrayList<Node>(append);
373 Collections.reverse(ap2);
374 append = ap2;
375 }
376 base.remove(base.size() - 1);
377 base.addAll(append);
378 }
379
380 /**
381 * Checks if a middle point between two nodes is inside a polygon. Useful to check if the way is inside.
382 */
383 private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) {
384 EastNorth en1 = n1.getEastNorth();
385 EastNorth en2 = n2.getEastNorth();
386 Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
387 return Geometry.nodeInsidePolygon(testNode, polygon);
388 }
389
390 private static class RingSegment {
391 private List<Node> nodes;
392 private RingSegment references;
393 private Way resultingWay = null;
394 private boolean wasTemplateApplied = false;
395 private boolean isRing;
396
397 private RingSegment() {
398 }
399
400 public RingSegment( Way w ) {
401 this(w.getNodes());
402 }
403
404 public RingSegment( List<Node> nodes ) {
405 this.nodes = nodes;
406 isRing = nodes.size() > 1 && nodes.get(0).equals(nodes.get(nodes.size() - 1));
407 if( isRing )
408 nodes.remove(nodes.size() - 1);
409 references = null;
410 }
411
412 public RingSegment( RingSegment ref ) {
413 this.nodes = null;
414 this.references = ref;
415 }
416
417 /**
418 * Splits this segment at node n. Retains nodes 0..n and moves
419 * nodes n..N to a separate segment that is returned.
420 * @param n node at which to split.
421 * @return new segment, {@code null} if splitting is unnecessary.
422 */
423 public RingSegment split( Node n ) {
424 if( nodes == null )
425 throw new IllegalArgumentException("Cannot split segment: it is a reference");
426 int pos = nodes.indexOf(n);
427 if( pos <= 0 || pos >= nodes.size() - 1 )
428 return null;
429 List<Node> newNodes = new ArrayList<Node>(nodes.subList(pos, nodes.size()));
430 nodes.subList(pos + 1, nodes.size()).clear();
431 return new RingSegment(newNodes);
432 }
433
434 /**
435 * Split this segment as a way at two nodes. If one of them is null or at the end,
436 * split as an arc. Note: order of nodes is important.
437 * @return A new segment from n2 to n1.
438 */
439 public RingSegment split( Node n1, Node n2 ) {
440 if( nodes == null )
441 throw new IllegalArgumentException("Cannot split segment: it is a reference");
442 if( !isRing ) {
443 if( n1 == null || nodes.get(0).equals(n1) || nodes.get(nodes.size() - 1).equals(n1) )
444 return split(n2);
445 if( n2 == null || nodes.get(0).equals(n2) || nodes.get(nodes.size() - 1).equals(n2) )
446 return split(n1);
447 throw new IllegalArgumentException("Split for two nodes is called for not-ring: " + this);
448 }
449 int pos1 = nodes.indexOf(n1);
450 int pos2 = nodes.indexOf(n2);
451 if( pos1 == pos2 )
452 return null;
453
454 List<Node> newNodes = new ArrayList<Node>();
455 if( pos2 > pos1 ) {
456 newNodes.addAll(nodes.subList(pos2, nodes.size()));
457 newNodes.addAll(nodes.subList(0, pos1 + 1));
458 if( pos2 + 1 < nodes.size() )
459 nodes.subList(pos2 + 1, nodes.size()).clear();
460 if( pos1 > 0 )
461 nodes.subList(0, pos1).clear();
462 } else {
463 newNodes.addAll(nodes.subList(pos2, pos1 + 1));
464 nodes.addAll(new ArrayList<Node>(nodes.subList(0, pos2 + 1)));
465 nodes.subList(0, pos1).clear();
466 }
467 isRing = false;
468 return new RingSegment(newNodes);
469 }
470
471 public List<Node> getNodes() {
472 return nodes == null ? references.nodes : nodes;
473 }
474
475 public List<Node> getWayNodes() {
476 if( nodes == null )
477 throw new IllegalArgumentException("Won't give you wayNodes: it is a reference");
478 List<Node> wayNodes = new ArrayList<Node>(nodes);
479 if( isRing )
480 wayNodes.add(wayNodes.get(0));
481 return wayNodes;
482 }
483
484 public boolean isReference() {
485 return nodes == null;
486 }
487
488 public boolean isRing() {
489 return isRing;
490 }
491
492 public void makeReference( RingSegment segment ) {
493 System.out.println(this + " was made a reference to " + segment);
494 this.nodes = null;
495 this.references = segment;
496 }
497
498 public void swapReference() {
499 this.nodes = references.nodes;
500 references.nodes = null;
501 references.references = this;
502 this.references = null;
503 }
504
505 public boolean isWayConstructed() {
506 return isReference() ? references.isWayConstructed() : resultingWay != null;
507 }
508
509 public Way constructWay( Way template ) {
510 if( isReference() )
511 return references.constructWay(template);
512 if( resultingWay == null ) {
513 resultingWay = new Way();
514 resultingWay.setNodes(getWayNodes());
515 }
516 if( template != null && !wasTemplateApplied ) {
517 resultingWay.setKeys(template.getKeys());
518 wasTemplateApplied = true;
519 }
520 return resultingWay;
521 }
522
523 public void overrideWay( Way source ) {
524 if( isReference() )
525 references.overrideWay(source);
526 else {
527 resultingWay = source;
528 wasTemplateApplied = true;
529 }
530 }
531
532 /**
533 * Compares two segments with respect to referencing.
534 * @return true if ways are equals, or one references another.
535 */
536 public boolean isReferencingEqual( RingSegment other ) {
537 return this.equals(other) || (other.isReference() && other.references == this) || (isReference() && references == other);
538 }
539
540 @Override
541 public String toString() {
542 StringBuilder sb = new StringBuilder("RingSegment@");
543 sb.append(this.hashCode()).append('[');
544 if( isReference() )
545 sb.append("references ").append(references.hashCode());
546 else if( nodes.isEmpty() )
547 sb.append("empty");
548 else {
549 if( isRing )
550 sb.append("ring:");
551 sb.append(nodes.get(0).getUniqueId());
552 for( int i = 1; i < nodes.size(); i++ )
553 sb.append(',').append(nodes.get(i).getUniqueId());
554 }
555 return sb.append(']').toString();
556 }
557 }
558}
Note: See TracBrowser for help on using the repository browser.