Debian Codegraph @

src/uk/me/parabola/util/ShapeSplitter.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2014 Gerd Petermann
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 package uk.me.parabola.util;
14
15 import java.awt.Shape;
16 import java.awt.geom.Path2D;
17 import java.awt.geom.PathIterator;
18 import java.awt.geom.Rectangle2D;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Comparator;
22 import java.util.List;
23
24 import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
25 import uk.me.parabola.imgfmt.Utils;
26 import uk.me.parabola.imgfmt.app.Area;
27 import uk.me.parabola.imgfmt.app.Coord;
28 import uk.me.parabola.log.Logger;
29
30 public class ShapeSplitter {
31 private static final Logger log = Logger.getLogger(ShapeSplitter.class);
32 private static final int LEFT = 0;
33 private static final int TOP = 1;
34 private static final int RIGHT = 2;
35 private static final int BOTTOM= 3;
36
37
38 /**
39 * Clip a given shape with a given rectangle.
40 * @param shape the subject shape to clip
41 * @param clippingRect the clipping rectangle
42 * @return the intersection of the shape and the rectangle
43 * or null if they don't intersect.
44 * The intersection may contain dangling edges.
45 */
46 public static Path2D.Double clipShape (Shape shape, Rectangle2D clippingRect) {
47 double minX = Double.POSITIVE_INFINITY,minY = Double.POSITIVE_INFINITY,
48 maxX = Double.NEGATIVE_INFINITY,maxY = Double.NEGATIVE_INFINITY;
49 PathIterator pit = shape.getPathIterator(null);
50 double[] points = new double[512];
51 int num = 0;
52 Path2D.Double result = null;
53 double[] res = new double[6];
54 while (!pit.isDone()) {
55 int type = pit.currentSegment(res);
56 double x = res[0];
57 double y = res[1];
58 if (x < minX) minX = x;
59 if (x > maxX) maxX = x;
60 if (y < minY) minY = y;
61 if (y > maxY) maxY = y;
62 switch (type) {
63 case PathIterator.SEG_LINETO:
64 case PathIterator.SEG_MOVETO:
65 if (num + 2 >= points.length) {
66 points = Arrays.copyOf(points, points.length * 2);
67 }
68 points[num++] = x;
69 points[num++] = y;
70 break;
71 case PathIterator.SEG_CLOSE:
72 Path2D.Double segment = null;
73 if (!clippingRect.contains(minX, minY) || !clippingRect.contains(maxX,maxY)) {
74 Rectangle2D.Double bbox = new Rectangle2D.Double(minX,minY,maxX-minX,maxY-minY);
75 segment = clipSinglePathWithSutherlandHodgman (points, num, clippingRect, bbox);
76 } else
77 segment = pointsToPath2D(points, num);
78 if (segment != null){
79 if (result == null)
80 result = segment;
81 else
82 result.append(segment, false);
83 }
84 num = 0;
85 minX = minY = Double.POSITIVE_INFINITY;
86 maxX = maxY = Double.NEGATIVE_INFINITY;
87 break;
88 default:
89 log.error("Unsupported path iterator type " + type
90 + ". This is an mkgmap error.");
91 }
92
93 pit.next();
94 }
95 return result;
96 }
97
98 /**
99 * Convert a list of longitude+latitude values to a Path2D.Double
100 * @param points the pairs
101 * @return the path or null if the path describes a point or line.
102 */
103 public static Path2D.Double pointsToPath2D(double[] points, int num) {
104 if (num < 2)
105 return null;
106 if (points[0] == points[num-2] && points[1] == points[num-1])
107 num -= 2;
108 if (num < 6)
109 return null;
110 Path2D.Double path = new Path2D.Double(Path2D.WIND_NON_ZERO, num / 2 + 2);
111 double lastX = points[0], lastY = points[1];
112 path.moveTo(lastX, lastY);
113 int numOut = 1;
114 for (int i = 2; i < num; ){
115 double x = points[i++], y = points[i++];
116 if (x != lastX || y != lastY){
117 path.lineTo(x,y);
118 lastX = x; lastY = y;
119 ++numOut;
120 }
121 }
122 if (numOut < 3)
123 return null;
124 path.closePath();
125 return path;
126 }
127
128 // The Sutherland�Hodgman algorithm Pseudo-Code:
129 // List outputList = subjectPolygon;
130 // for (Edge clipEdge in clipPolygon) do
131 // List inputList = outputList;
132 // outputList.clear();
133 // Point S = inputList.last;
134 // for (Point E in inputList) do
135 // if (E inside clipEdge) then
136 // if (S not inside clipEdge) then
137 // outputList.add(ComputeIntersection(S,E,clipEdge));
138 // end if
139 // outputList.add(E);
140 // else if (S inside clipEdge) then
141 // outputList.add(ComputeIntersection(S,E,clipEdge));
142 // end if
143 // S = E;
144 // done
145 // done
146
147 /**
148 * Clip a single path with a given rectangle using the Sutherland-Hodgman algorithm. This is much faster compared to
149 * the area.intersect method, but may create dangling edges.
150 * @param points a list of longitude+latitude pairs
151 * @param num the nnumber of valid values in points
152 * @param clippingRect the clipping rectangle
153 * @param bbox the bounding box of the path
154 * @return the clipped path as a Path2D.Double or null if the result is empty
155 */
156 public static Path2D.Double clipSinglePathWithSutherlandHodgman (double[] points, int num, Rectangle2D clippingRect, Rectangle2D.Double bbox) {
157 if (num <= 2 || !bbox.intersects(clippingRect)) {
158 return null;
159 }
160
161 int countVals = num;
162 if (points[0] == points[num-2] && points[1] == points[num-1]){
163 countVals -= 2;
164 }
165 double[] outputList = points;
166 double[] input;
167
168 double leftX = clippingRect.getMinX();
169 double rightX = clippingRect.getMaxX();
170 double lowerY = clippingRect.getMinY();
171 double upperY = clippingRect.getMaxY();
172 boolean eIsIn = false, sIsIn = false;
173 for (int side = LEFT; side <= BOTTOM; side ++){
174 if (countVals < 6)
175 return null; // ignore point or line
176
177 boolean skipTestForThisSide;
178 switch(side){
179 case LEFT: skipTestForThisSide = (bbox.getMinX() >= leftX); break;
180 case TOP: skipTestForThisSide = (bbox.getMaxY() < upperY); break;
181 case RIGHT: skipTestForThisSide = (bbox.getMaxX() < rightX); break;
182 default: skipTestForThisSide = (bbox.getMinY() >= lowerY);
183 }
184 if (skipTestForThisSide)
185 continue;
186
187 input = outputList;
188 outputList = new double[countVals + 16];
189 double sLon = 0,sLat = 0;
190 double pLon = 0,pLat = 0; // intersection
191 int posIn = countVals - 2;
192 int posOut = 0;
193 for (int i = 0; i < countVals+2; i+=2){
194 if (posIn >= countVals)
195 posIn = 0;
196 double eLon = input[posIn++];
197 double eLat = input[posIn++];
198 switch (side){
199 case LEFT: eIsIn = (eLon >= leftX); break;
200 case TOP: eIsIn = (eLat < upperY); break;
201 case RIGHT: eIsIn = (eLon < rightX); break;
202 default: eIsIn = (eLat >= lowerY);
203 }
204 if (i > 0){
205 if (eIsIn != sIsIn){
206 // compute intersection
207 double slope;
208 if (eLon != sLon)
209 slope = (eLat - sLat) / (eLon-sLon);
210 else slope = 1;
211
212 switch (side){
213 case LEFT:
214 pLon = leftX;
215 pLat = slope *(leftX-sLon) + sLat;
216 break;
217 case RIGHT:
218 pLon = rightX;
219 pLat = slope *(rightX-sLon) + sLat;
220 break;
221
222 case TOP:
223 if (eLon != sLon)
224 pLon = sLon + (upperY - sLat) / slope;
225 else
226 pLon = sLon;
227 pLat = upperY;
228 break;
229 default: // BOTTOM
230 if (eLon != sLon)
231 pLon = sLon + (lowerY - sLat) / slope;
232 else
233 pLon = sLon;
234 pLat = lowerY;
235 break;
236
237 }
238 }
239 int toAdd = 0;
240 if (eIsIn){
241 if (!sIsIn){
242 toAdd += 2;
243 }
244 toAdd += 2;
245 }
246 else {
247 if (sIsIn){
248 toAdd += 2;
249 }
250 }
251 if (posOut + toAdd >= outputList.length) {
252 // unlikely
253 outputList = Arrays.copyOf(outputList, outputList.length * 2);
254 }
255 if (eIsIn){
256 if (!sIsIn){
257 outputList[posOut++] = pLon;
258 outputList[posOut++] = pLat;
259 }
260 outputList[posOut++] = eLon;
261 outputList[posOut++] = eLat;
262 }
263 else {
264 if (sIsIn){
265 outputList[posOut++] = pLon;
266 outputList[posOut++] = pLat;
267 }
268 }
269 }
270 // S = E
271 sLon = eLon; sLat = eLat;
272 sIsIn = eIsIn;
273 }
274 countVals = posOut;
275 }
276 return pointsToPath2D(outputList, countVals);
277 }
278
279 // Dec16/Jan17. Ticker Berkin. New implementation for splitting shapes and clipping
280
281 private boolean detectedProblems;
282 private List<MergeCloseHelper> newLess, newMore;
283 private String gpxDirectory;
284 private long fullArea;
285
286 private List<LoopEndPoint> endPoints; // for the side we are working on
287 private List<List<Coord>> origList; // ditto
288
289 private boolean multSamePoint; // .sort(comparator) might set this
290
291 // following are for processAwkward...
292 private LoopEndPoint forwardLine, backwardLine;
293 private int directionBalance;
294 private List<LoopEndPoint> dLoops, shapes, holes;
295 private boolean droppedEmpty;
296
297 private void logMsg(Object ... olist) {
298 detectedProblems = true;
299 log.warn(olist);
300 }
301
302 /**
303 * Service routine for processLineList. Processes a nested list of holes within a shape or
304 * list of shapes within a hole.
305 *
306 * Recurses to check for and handle the opposite of what has been called to process.
307 *
308 * @param startInx starting point in list.
309 * @param endInx index of highPoint of enclosing hole/shape.
310 * @param addHolesToThis if not null, then called from a shape and subtract holes from it
311 * otherwise new shapes within a hole.
312 */
313 private void doLines(int startInx, int endInx, MergeCloseHelper addHolesToThis) {
314 int inx = startInx;
315 final boolean calledFromHole = addHolesToThis == null;
316 while (inx < endInx) {
317 LoopEndPoint lowElem = endPoints.get(inx);
318 int otherEndInx = lowElem.otherEnd.ownIndex;
319 MergeCloseHelper thisLine = lowElem.theLoop;
320 if (lowElem.lowEnd != 1) {
321 logMsg("Wrong end of shape/hole encountered", inx, startInx, endInx, calledFromHole);
322 return;
323 }
324 doLines(inx+1, otherEndInx, calledFromHole ? thisLine : null);
325 inx = otherEndInx + 1;
326 if (calledFromHole) // handling list of shapes
327 thisLine.closeAppend(true);
328 else // handling list of holes
329 addHolesToThis.addHole(thisLine);
330 }
331 } // doLines
332
333 /**
334 * Service routine for splitShape. Takes list of lines and appends distinct shapes
335 * @param lineInfo list of lines that start and end on the dividing line (or orig startPoint)
336 * @param origList list of shapes to which we append new shapes formed from above
337 */
338 private void processLineList(List<MergeCloseHelper> lineInfo, List<List<Coord>> origList) {
339 this.origList = origList;
340 if (origList == null) // never wanted this side
341 return;
342 MergeCloseHelper firstLine = lineInfo.get(0);
343 if (lineInfo.size() == 1) { // single shape that never crossed line
344 if (!firstLine.points.isEmpty()) // all on this side
345 firstLine.closeAppend(false);
346 return;
347 }
348 // look at last item in list of lines
349 MergeCloseHelper lastLine = lineInfo.get(lineInfo.size()-1);
350 if (lastLine.points.isEmpty()) // will be empty if started on other side
351 lineInfo.remove(lineInfo.size()-1);
352 else { // ended up on this side and must have crossed the line
353 // so first element is really the end of the last
354 lastLine.combineFirstIntoLast(firstLine);
355 lineInfo.remove(0);
356 firstLine = lineInfo.get(0);
357 }
358 if (lineInfo.size() == 1) { // simple poly that crossed once and back
359 firstLine.setMoreInfo(0);
360 firstLine.closeAppend(true);
361 return;
362 }
363 // Above were the simple cases - probably 99% of calls.
364
365 // splitShape has generated a list of lines that start and end on the dividing line.
366 // These lines don't cross. Order their end-points by their lowest point on the divider and note which
367 // direction they go. The first (and last) point must define a shape. Starting with this
368 // shape; the next line up, if it is within this shape, must define a hole and
369 // so is added to the list of points for the shape. For the hole, recurse to
370 // handle any shapes enclosed. Repeat until we reach the end of the enclosing
371 // space.
372
373 final int fullAreaSign = Long.signum(fullArea);
374 // check and set any missing directions based on signs of full/area
375 boolean someDirectionsNotSet = false;
376 int areaDirection = 0;
377 // and build list of all endpoints
378 endPoints = new ArrayList<>(lineInfo.size()*2);
379 for (MergeCloseHelper thisLine : lineInfo) {
380 thisLine.setMoreInfo(fullAreaSign);
381 if (thisLine.direction == 0)
382 someDirectionsNotSet = true;
383 else if (thisLine.areaToLine != 0) {
384 int tmpAreaDirection = thisLine.direction * Long.signum(thisLine.areaToLine);
385 if (areaDirection == 0)
386 areaDirection = tmpAreaDirection;
387 else if (areaDirection != tmpAreaDirection)
388 logMsg("Direction/Area conflict", fullAreaSign, areaDirection, tmpAreaDirection);
389 }
390 // create endPoint elements
391 LoopEndPoint lep1 = new LoopEndPoint(thisLine.lowPoint, +1, thisLine);
392 LoopEndPoint lep2 = new LoopEndPoint(thisLine.highPoint, -1, thisLine);
393 lep1.otherEnd = lep2;
394 lep2.otherEnd = lep1;
395 endPoints.add(lep1);
396 endPoints.add(lep2);
397 }
398 if (someDirectionsNotSet) {
399 if (areaDirection == 0)
400 logMsg("Can't deduce direction/Area mapping", fullAreaSign);
401 else
402 for (MergeCloseHelper thisLine : lineInfo)
403 if (thisLine.direction == 0)
404 thisLine.direction = areaDirection * Long.signum(thisLine.areaToLine);
405 }
406
407 Comparator<LoopEndPoint> comparator = new EndPointComparator();
408 multSamePoint = false;
409 endPoints.sort(comparator);
410 if (multSamePoint)
411 processAwkward(comparator);
412 // if (log.isDebugEnabled()) { // can be useful to have raw loop data before shape/hole processing
413 // int fInx = 0;
414 // for (MergeCloseHelper thisLine : lineInfo) {
415 // ++fInx;
416 // uk.me.parabola.util.GpxCreator.createGpx(gpxDirectory + (lineInfo == newLess ? "N" : "P") + fInx, thisLine.points);
417 // }
418 // }
419
420 // set ownIndex in each element after sorting
421 int ownIndex = 0;
422 for (LoopEndPoint endPoint : endPoints) {
423 endPoint.ownIndex = ownIndex;
424 ++ownIndex;
425 }
426 doLines(0, endPoints.size(), null);
427 if (detectedProblems && log.isDebugEnabled())
428 for (LoopEndPoint endPoint : endPoints)
429 log.warn("ep", endPoint.ownIndex, endPoint.thePoint, endPoint.lowEnd, System.identityHashCode(endPoint),
430 System.identityHashCode(endPoint.otherEnd), endPoint.theLoop);
431 } // processLineList
432
433 private void processAwkward(Comparator<LoopEndPoint> comparator) {
434 // Where a loop has lowPoint==highPoint, let us call it a "balloon", otherwise call it a Dloop.
435 // Awkward cases are:
436 // Dloops with same low/high/area, For this to be true they must follow the same path (or intersect)
437 // Multiple hole balloons from the same point
438 // Balloon(s) that share the same point as dLoops
439 boolean haveBalloons = false;
440
441 // Duplicate dLoops in same direction can be removed / opposite direction cancel each other out.
442 // Do this before Balloon processing as dLoop removal can make some problems go away.
443 List<LoopEndPoint> newList = new ArrayList<>(endPoints.size());
444 LoopEndPoint prevElem = null;
445 boolean grouping = false;
446 for (LoopEndPoint thisElem : endPoints) {
447 if (prevElem != null) {
448 boolean sameAsPrev = comparator.compare(thisElem, prevElem) == 0;
449 // balloons won't break up the list because they will be inside the dLoops
450 // The two ends of the balloon don't compare equal
451 fixDups(newList, prevElem, sameAsPrev, grouping);
452 grouping = sameAsPrev;
453 }
454 prevElem = thisElem;
455 if (thisElem.theLoop.lowPoint == thisElem.theLoop.highPoint)
456 haveBalloons = true;
457 }
458 fixDups(newList, prevElem, false, grouping);
459
460 if (newList.size() < endPoints.size()) {
461 log.debug("Reduced dLoops from", endPoints.size(), "to", newList.size());
462 endPoints.clear();
463 endPoints.addAll(newList);
464 }
465
466 if (!haveBalloons)
467 return;
468
469 // Balloons will be sorted within the dLoops that share the same lowPoint or highPoint,
470 // but those that form a shape must be within a hole and those that form a hole must be within
471 // a shape and so might need moving.
472 // A single dLoop defines a transition and so we can get balloons on the correct side of it.
473 // Multiple dLoops might suggest more than 1 place where +ve or -ve balloons can go and
474 // this isn't possible to resolve without much more complex analysis of the geometry away from the cut-point.
475 // The ordering of multiple +ve balloons doesn't matter - they will become individual shapes.
476 // The ordering of multiple -ve balloons does matter - in the wrong order a crossing will be generated
477 // at the cut-point - again this isn't possible to solve without analysis of the geometry
478 newList = new ArrayList<>(endPoints.size());
479 dLoops = new ArrayList<>();
480 shapes = new ArrayList<>();
481 holes = new ArrayList<>();
482 droppedEmpty = false;
483 boolean reordered = false;
484 prevElem = null;
485 grouping = false;
486 for (LoopEndPoint thisElem : endPoints) {
487 if (prevElem != null) {
488 boolean sameAsPrev = thisElem.thePoint == prevElem.thePoint;
489 reordered |= fixOrder(newList, prevElem, sameAsPrev, grouping, comparator);
490 grouping = sameAsPrev;
491 }
492 prevElem = thisElem;
493 }
494 reordered |= fixOrder(newList, prevElem, false, grouping, comparator);
495
496 if (reordered || droppedEmpty) {
497 log.debug("Reordered endPoints or droppedEmpty", droppedEmpty);
498 endPoints.clear();
499 endPoints.addAll(newList);
500 }
501 } // processAwkward
502
503 private void fixDups(List<LoopEndPoint> newList, LoopEndPoint prevElem, boolean sameAsPrev, boolean grouping) {
504 if (grouping || sameAsPrev) {
505 if (prevElem.lowEnd == 1) {
506 if (!grouping) { // start of a group
507 forwardLine = null;
508 backwardLine = null;
509 directionBalance = 0;
510 }
511 if (prevElem.theLoop.direction > 0) {
512 forwardLine = prevElem;
513 ++directionBalance;
514 } else {
515 backwardLine = prevElem;
516 --directionBalance;
517 }
518 prevElem.theLoop.removedDloop = true; // mark removed so can remove other end
519 } else { // the high end, just keep the undelete ones
520 if (!prevElem.theLoop.removedDloop)
521 newList.add(prevElem);
522 }
523 }
524 if (sameAsPrev)
525 return;
526 // flush previous
527 if (!grouping) {
528 newList.add(prevElem);
529 return;
530 }
531 if (prevElem.lowEnd == 1) {
532 if (directionBalance > 0) {
533 newList.add(forwardLine);
534 forwardLine.theLoop.removedDloop = false; // undelete
535 } else if (directionBalance < 0) {
536 newList.add(backwardLine);
537 backwardLine.theLoop.removedDloop = false; // undelete
538 }
539 }
540 } // fixDups
541
542 private boolean fixOrder(List<LoopEndPoint> newList, LoopEndPoint prevElem, boolean sameAsPrev, boolean grouping,
543 Comparator<LoopEndPoint> comparator) {
544 if (grouping || sameAsPrev) {
545 if (prevElem.theLoop.lowPoint != prevElem.theLoop.highPoint)
546 dLoops.add(prevElem);
547 else if (prevElem.theLoop.areaOrHole == 1)
548 shapes.add(prevElem);
549 else if (prevElem.theLoop.areaOrHole == -1)
550 holes.add(prevElem);
551 else // zero area, can't tell if shape or hole and could end in wrong place if left
552 droppedEmpty = true;
553 }
554 if (sameAsPrev)
555 return false;
556 // flush previous
557 if (!grouping) {
558 newList.add(prevElem);
559 return false;
560 }
561
562 if (holes.size() > 2) // NB: each hole/shape has 2 ends at this point
563 log.warn("Cutting", holes.size()/2, "holes at same point might cause self-intersection",
564 holes.get(0).theLoop.points.get(0).toOSMURL());
565 if (dLoops.isEmpty()) {
566 if (shapes.isEmpty()) {
567 newList.addAll(holes);
568 holes.clear();
569 return false;
570 } else if (holes.isEmpty()) {
571 newList.addAll(shapes);
572 shapes.clear();
573 return false;
574 }
575 // single hole and single shape must be nested. Already warned for mult holes
576 if (shapes.size() > 2)
577 log.warn("Cutting hole and ", shapes.size()/2, "shapes at same point is problematic",
578 shapes.get(0).theLoop.points.get(0).toOSMURL());
579 // assume nested - have lost original sort which would have been good, so redo:
580 shapes.addAll(holes);
581 holes.clear();
582 shapes.sort(comparator);
583 newList.addAll(shapes);
584 shapes.clear();
585 return true;
586 } else {
587 if (shapes.isEmpty() && holes.isEmpty()) {
588 newList.addAll(dLoops);
589 dLoops.clear();
590 return false;
591 }
592 }
593
594 // might be able to do a few more limitations based on areas
595 if (dLoops.get(0).theLoop.areaOrHole == dLoops.get(0).lowEnd) { // lowEnd of area or highEnd of hole
596 newList.addAll(shapes);
597 newList.add(dLoops.get(0));
598 newList.addAll(holes);
599 } else {
600 newList.addAll(holes);
601 newList.add(dLoops.get(0));
602 newList.addAll(shapes);
603 }
604 dLoops.remove(0);
605 if (!dLoops.isEmpty()) {
606 // if 2 dividors hole>area | areae>hole then, as only place for holes is middle, can avoid this warning
607 log.warn("Possible ambiguous balloon allocation at", dLoops.get(0).theLoop.points.get(0).toOSMURL(),
608 "Dloops:", dLoops.size(), "shapes:", shapes.size()/2, "holes:", holes.size()/2);
609 newList.addAll(dLoops);
610 dLoops.clear();
611 }
612 shapes.clear();
613 holes.clear();
614 return true;
615 } // fixOrder
616
617 private List<Coord> startLine(List<MergeCloseHelper> lineInfo) {
618 MergeCloseHelper thisLine = new MergeCloseHelper();
619 lineInfo.add(thisLine);
620 return thisLine.points;
621 } // startLine
622
623 private void openLine(List<MergeCloseHelper> lineInfo, Coord lineCoord, int lineAlong, long currentArea) {
624 MergeCloseHelper thisLine = lineInfo.get(lineInfo.size()-1);
625 thisLine.points.add(lineCoord);
626 thisLine.firstPoint = lineAlong;
627 thisLine.startingArea = currentArea;
628 } // openLine
629
630 private List<Coord> closeLine(List<MergeCloseHelper> lineInfo, Coord lineCoord, int lineAlong, long currentArea) {
631 MergeCloseHelper thisLine = lineInfo.get(lineInfo.size()-1);
632 thisLine.points.add(lineCoord);
633 thisLine.lastPoint = lineAlong;
634 thisLine.endingArea = currentArea;
635 return startLine(lineInfo);
636 } // closeLine
637
638 /**
639 * Helper class for splitShape. Holds information about line.
640 * Sorts array/list of itself according to lowest point on dividing line.
641 */
642 private class MergeCloseHelper {
643
644 List<Coord> points;
645 int firstPoint, lastPoint;
646 long startingArea, endingArea; // from runningArea
647 int direction;
648 int lowPoint, highPoint;
649 long areaToLine;
650 int areaOrHole; // +1/-1
651 boolean removedDloop; // so can remove both ends of the same one
652
653 MergeCloseHelper() {
654 points = new ArrayList<>();
655 } // MergeCloseHelper
656
657 public String toString() {
658 return "fp=" + firstPoint + " lp=" + lastPoint + " area=" + areaToLine + " #=" + points.size() + " " +
659 points.get(1).toOSMURL() + " " + points.get(points.size()/2).toOSMURL();
660 } // toString
661
662 void setMoreInfo(int fullAreaSign) {
663 this.direction = Integer.signum(lastPoint - firstPoint);
664 if (this.direction > 0) {
665 this.lowPoint = firstPoint;
666 this.highPoint = lastPoint;
667 } else {
668 this.lowPoint = lastPoint;
669 this.highPoint = firstPoint;
670 }
671 this.areaToLine = this.endingArea - this.startingArea; // correct if closed
672 // !!! also correct when close along the line, because would do:
673 // this.areaToLine += (long)(lastPoint + firstPoint) * (dividingLine - dividingLine);
674 this.areaOrHole = fullAreaSign * Long.signum(this.areaToLine);
675 } // setMoreInfo
676
677 void combineFirstIntoLast(MergeCloseHelper other) {
678 this.points.addAll(other.points);
679 this.lastPoint = other.lastPoint;
680 this.endingArea = fullArea + other.endingArea;
681 } // combineFirstIntoLast
682
683 void addHole(MergeCloseHelper other) {
684 if (other.areaToLine == 0)
685 return; // spike into this area. cf. closeAppend()
686 // shapes must have opposite directions.
687 if (this.direction == 0 && other.direction == 0)
688 logMsg("Direction of shape and hole indeterminate.", "shape:", this, "hole:", other);
689 else if (this.direction != 0 && other.direction != 0 && this.direction == other.direction)
690 logMsg("Direction of shape and hole conflict.", "shape:", this, "hole:", other);
691 else if (this.direction < 0 || other.direction > 0) {
692 this.points.addAll(other.points);
693 if (this.direction == 0)
694 this.direction = -1;
695 } else { // add at start
696 other.points.addAll(this.points);
697 this.points = other.points;
698 if (this.direction == 0)
699 this.direction = +1;
700 }
701 this.areaToLine += other.areaToLine;
702 } // addHole
703
704 /**
705 * closes a shape and appends to list.
706 *
707 * If the shape starts and ends at the same point on the dividing line then
708 * there is no need to close it. Also check for and chuck a spike, which happens
709 * if there is a single point just across the dividing line and the two intersecting
710 * points ended up being the same or an edge runs back on itself exactly.
711 *
712 * @param onDividingLine if false, shape not cut so don't assume/care much about it
713 */
714 void closeAppend(boolean onDividingLine) {
715 final Coord firstCoord = points.get(0);
716 final int lastPointInx = points.size()-1;
717 if (lastPointInx >= 3 &&
718 firstCoord.highPrecEquals(points.get(lastPointInx))) { // by chance, ends up closed
719 // There is no need to close the shape along the line, but am finding, for shapes that never crossed the
720 // dividing line, quite a few that, after splitShapes has rotating the shape by 1, have first and last
721 // points highPrecEquals but they are different objects.
722 // This means that the original first and last were the same object, but the second and last were highPrecEquals!
723 // If left like this, it might be flagged by ShapeMergeFilter.
724 // NB: if no coordPool, likely to be different closing object anyway
725 if (firstCoord != points.get(lastPointInx))
726 points.set(lastPointInx, firstCoord); // quietly replace with first point
727 } else
728 points.add(firstCoord); // close it
729 if (onDividingLine) { // if not, just one shape untouched by chopping
730 if (this.areaToLine == 0)
731 return;
732 }
733 origList.add(points);
734 } // closeAppend
735
736 } // MergeCloseHelper
737
738 private class LoopEndPoint {
739
740 int thePoint;
741 int lowEnd; // +1 if thePoint is lowPoint, -1 otherwise
742 MergeCloseHelper theLoop;
743 LoopEndPoint otherEnd;
744 int ownIndex; // set after sort
745
746 LoopEndPoint(int thePoint, int lowEnd, MergeCloseHelper theLoop) {
747 this.thePoint = thePoint;
748 this.lowEnd = lowEnd;
749 this.theLoop = theLoop;
750 } // LoopEndPoint
751
752 } // LoopEndPoint
753
754 private class EndPointComparator implements Comparator<LoopEndPoint> {
755
756 @Override
757 public int compare(LoopEndPoint lep1, LoopEndPoint lep2) {
758 int cmp;
759 // sort in ascending thePoint order
760 cmp = lep1.thePoint - lep2.thePoint;
761 if (cmp != 0)
762 return cmp;
763 multSamePoint = true;
764
765 MergeCloseHelper mch1 = lep1.theLoop;
766 MergeCloseHelper mch2 = lep2.theLoop;
767 if (mch1 == mch2) // same object - get ends in correct order
768 return lep2.lowEnd;
769
770 if (lep1.lowEnd == 1)
771 if (lep2.lowEnd == 1)
772 cmp = mch2.highPoint - mch1.highPoint;
773 else // low == high
774 return +1;
775 else // high
776 if (lep2.lowEnd == 1) // high == low
777 return -1;
778 else
779 cmp = mch2.lowPoint - mch1.lowPoint;
780 if (cmp != 0)
781 return cmp;
782
783 // have same start & end (and orientation), widen by area (ie lowEnd down, highEnd up)
784 cmp = Long.compare(Math.abs(mch2.areaToLine), Math.abs(mch1.areaToLine));
785 if (cmp != 0)
786 return cmp * lep1.lowEnd;
787 // for same low/high/area must return equal/0 for duplicate detection and removal
788 return 0;
789 } // compare
790
791 } // EndPointComparator
792
793 /**
794 * split a shape with a line
795 * @param coords the shape. Must be closed.
796 * @param dividingLine the line in high precision.
797 * @param isLongitude true if above is line of longitude, false if latitude.
798 * @param lessList list of shapes to which we append new shapes on lower/left side of line.
799 * @param moreList list of shapes to which we append new shapes on upper/right side of line.
800 * @param coordPool if not null, hashmap for created coordinates. Will all be on the line.
801 */
802 public static void splitShape(List<Coord> coords, int dividingLine, boolean isLongitude,
803 List<List<Coord>> lessList, List<List<Coord>> moreList,
804 Long2ObjectOpenHashMap<Coord> coordPool) {
805 ShapeSplitter ss = new ShapeSplitter();
806 ss.split(coords, dividingLine, isLongitude, lessList, moreList, coordPool);
807 } // splitShape
808
809 private void split(List<Coord> coords, int dividingLine, boolean isLongitude,
810 List<List<Coord>> lessList, List<List<Coord>> moreList,
811 Long2ObjectOpenHashMap<Coord> coordPool) {
812 if (log.isDebugEnabled()) {
813 gpxDirectory = (isLongitude ? "V" : "H") + dividingLine + "_" +
814 (isLongitude ? coords.get(0).getLatitude() : coords.get(0).getLongitude()) + "/";
815 }
816 formLoops(coords, dividingLine, isLongitude, lessList != null, moreList != null, coordPool);
817 processLineList(newLess, lessList);
818 processLineList(newMore, moreList);
819 if (detectedProblems) {
820 logDiagInfo(coords, lessList, moreList);
821 log.warn(isLongitude ? "Vertical" : "Horizontal", "split", dividingLine, "failed on shape at", coords.get(0).toOSMURL(),
822 "Possibly a self-intersecting polygon");
823 }
824 } // split
825
826 private void formLoops(List<Coord> coords, int dividingLine, boolean isLongitude,
827 boolean wantLess, boolean wantMore, Long2ObjectOpenHashMap<Coord> coordPool) {
828 List<Coord> lessPoly = null, morePoly = null;
829 if (wantLess) {
830 newLess = new ArrayList<>();
831 lessPoly = startLine(newLess);
832 }
833 if (wantMore) {
834 newMore = new ArrayList<>();
835 morePoly = startLine(newMore);
836 }
837 /**
838 * trailXxx variables are the previous coordinate information.
839 * leadXxx are for the current coordinate
840 * lineXxx are the crossing point
841 * where Xxx is Coord : Coord
842 * Away : position in plane at right angles to dividing line
843 * Along : position in same plane as the dividing line
844 * Rel : -1/0/+1 depending on relationship of Away to dividing line
845 */
846 Coord trailCoord = null;
847 int trailAway = 0, trailAlong = 0, trailRel = 0;
848 long runningArea = 0;
849
850 for (Coord leadCoord : coords) {
851 final int leadAway = isLongitude ? leadCoord.getHighPrecLon() : leadCoord.getHighPrecLat();
852 final int leadAlong = isLongitude ? leadCoord.getHighPrecLat() : leadCoord.getHighPrecLon();
853 final int leadRel = Integer.signum(leadAway - dividingLine);
854 if (trailCoord != null) { // use first point as trailing (poly is closed)
855
856 Coord lineCoord = null;
857 int lineAlong = trailAlong; // initial assumption
858 if (trailRel == 0) // trailing point on line
859 lineCoord = trailCoord;
860 else if (leadRel == 0) { // leading point on line
861 lineCoord = leadCoord;
862 lineAlong = leadAlong;
863 } else if (trailRel != leadRel) { // crosses line; make intersecting coord
864 if (lineAlong != leadAlong)
865 lineAlong += Math.round((double)(dividingLine - trailAway) * (leadAlong - trailAlong)
866 / (leadAway - trailAway));
867 lineCoord = Coord.makeHighPrecCoord(isLongitude ? lineAlong : dividingLine, isLongitude ? dividingLine : lineAlong);
868 }
869 if (lineCoord != null && coordPool != null) {
870 // Add new coords to pool. Also add existing ones if on the dividing line because there is slight
871 // chance that the intersection will coincide with an existing point and ShapeMergeFilter expects
872 // the opening/closing point to be the same object. If we see the original point first,
873 // all is good, but if other way around, it will replace an original point with the created one.
874 final long hashVal = Utils.coord2Long(lineCoord);
875 final Coord replCoord = coordPool.get(hashVal);
876 if (replCoord == null)
877 coordPool.put(hashVal, lineCoord);
878 else
879 lineCoord = replCoord;
880 }
881
882 long extraArea; // add in later to get the area to leading point
883 if (leadRel * trailRel >= 0) // doesn't cross the line
884 extraArea = (long)(trailAlong + leadAlong) * (trailAway - leadAway);
885 else { // calc as 2 points
886 runningArea += (long)(trailAlong + lineAlong) * (trailAway - dividingLine);
887 extraArea = (long)(lineAlong + leadAlong) * (dividingLine - leadAway);
888 }
889
890 if (wantLess) {
891 if (leadRel < 0) { // this point required
892 if (trailRel >= 0) // previous not on this side, add line point
893 openLine(newLess, lineCoord, lineAlong, runningArea);
894 lessPoly.add(leadCoord);
895 } else if (trailRel < 0) // if this not reqd and prev was, add line point and start new shape
896 lessPoly = closeLine(newLess, lineCoord, lineAlong, runningArea + (leadRel == 0 ? extraArea : 0));
897 }
898
899 // identical to above except other way around
900 if (wantMore) {
901 if (leadRel > 0) { // this point required
902 if (trailRel <= 0) // previous not on this side, add line point
903 openLine(newMore, lineCoord, lineAlong, runningArea);
904 morePoly.add(leadCoord);
905 } else if (trailRel > 0) // if this not reqd and prev was, add line point and start new shape
906 morePoly = closeLine(newMore, lineCoord, lineAlong, runningArea + (leadRel == 0 ? extraArea : 0));
907 }
908
909 runningArea += extraArea;
910 } // if not first Coord
911 trailCoord = leadCoord;
912 trailAway = leadAway;
913 trailAlong = leadAlong;
914 trailRel = leadRel;
915 } // for leadCoord
916 fullArea = runningArea;
917 } // formLoops
918
919 void logDiagInfo(List<Coord> coords, List<List<Coord>> lessList, List<List<Coord>> moreList) {
920 int lowestPoint = newLess != null ? newLess.get(0).lowPoint : (newMore != null ? newMore.get(0).lowPoint : 0); // easier with small numbers
921 log.info("#points:", coords.size(), "fullArea:", fullArea, "lowest:", lowestPoint, "gpxDir:", gpxDirectory);
922 if (newLess != null)
923 for (MergeCloseHelper thisLine : newLess)
924 log.info("LessLoop", thisLine.lowPoint-lowestPoint, thisLine.highPoint-lowestPoint, thisLine.direction, thisLine.areaOrHole, thisLine.areaToLine, thisLine.points.size());
925 if (newMore != null)
926 for (MergeCloseHelper thisLine : newMore)
927 log.info("MoreLoop", thisLine.lowPoint-lowestPoint, thisLine.highPoint-lowestPoint, thisLine.direction, thisLine.areaOrHole, thisLine.areaToLine, thisLine.points.size());
928 if (log.isDebugEnabled()) {
929 uk.me.parabola.util.GpxCreator.createGpx(gpxDirectory + "S", coords); // original shape
930 int fInx = 0;
931 // NB: lessList/moreList could be non-existent, the same object or have already have contents
932 String filePrefix = lessList == moreList ? "B" : "L";
933 if (lessList != null)
934 for (List<Coord> fragment : lessList) {
935 ++fInx;
936 uk.me.parabola.util.GpxCreator.createGpx(gpxDirectory + filePrefix + fInx, fragment);
937 }
938 fInx = 0;
939 if (moreList != null && lessList != moreList)
940 for (List<Coord> fragment : moreList) {
941 ++fInx;
942 uk.me.parabola.util.GpxCreator.createGpx(gpxDirectory + "M" + fInx, fragment);
943 }
944 }
945 } // logDiagInfo
946
947 // end of splitShape components
948
949 /**
950 * clip a shape with a rectangle
951 *
952 * Use above splitShape for each side; just keeping the 1/2 we want each time.
953 *
954 * @param coords the shape.
955 * @param bounds the clipping area.
956 * @param coordPool if not null, hashmap for created coordinates. Will all be on the edge.
957 * @return list of shapes.
958 */
959 public static List<List<Coord>> clipToBounds(List<Coord> coords, Area bounds, Long2ObjectOpenHashMap<Coord> coordPool) {
960 List<List<Coord>> newListA = new ArrayList<>();
961 int dividingLine = bounds.getMinLat() << Coord.DELTA_SHIFT;
962 splitShape(coords, dividingLine, false, null, newListA, coordPool);
963 if (newListA.isEmpty())
964 return newListA;
965 List<List<Coord>> newListB = new ArrayList<>();
966 dividingLine = bounds.getMinLong() << Coord.DELTA_SHIFT;
967 for (List<Coord> aShape : newListA)
968 splitShape(aShape, dividingLine, true, null, newListB, coordPool);
969 if (newListB.isEmpty())
970 return newListB;
971 newListA.clear();
972 dividingLine = bounds.getMaxLat() << Coord.DELTA_SHIFT;
973 for (List<Coord> aShape : newListB)
974 splitShape(aShape, dividingLine, false, newListA, null, coordPool);
975 if (newListA.isEmpty())
976 return newListA;
977 newListB.clear();
978 dividingLine = bounds.getMaxLong() << Coord.DELTA_SHIFT;
979 for (List<Coord> aShape : newListA)
980 splitShape(aShape, dividingLine, true, newListB, null, coordPool);
981 return newListB;
982 } // clipToBounds
983
984 } // ShapeSplitter