Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright (C) 2019.
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
16 import java.awt.geom.Path2D;
17 import java.util.ArrayList;
18 import java.util.BitSet;
19 import java.util.List;
20 import java.util.Set;
21 import java.util.TreeMap;
22
23 import uk.me.parabola.imgfmt.Utils;
24 import uk.me.parabola.imgfmt.app.Area;
25 import uk.me.parabola.imgfmt.app.Coord;
26 import uk.me.parabola.log.Logger;
27 import uk.me.parabola.mkgmap.reader.osm.Way;
28
29 /**
30 * Implements insideness tests for points, polyline and polygon. We distinguish
31 * 3 cases for points: <br>
32 * 1: the point is outside the polygon <br>
33 * 2: the point is on the boundary of the polygon (or very close to it) <br>
34 * 3: the point in inside the polygon
35 *
36 * We distinguish 6 cases for lines: <br>
37 * 1: all of the line is outside the polygon <br>
38 * 2: some of the line is outside and the rest touches or runs along the polygon
39 * edge <br>
40 * 3: all of the line runs along the polygon edge <br>
41 * 4: some of the line is inside and the rest touches or runs along. <br>
42 * 5: all of the line is inside the polygon <br>
43 * 6: some is inside and some outside the polygon. Obviously some point is on
44 * the polygon edge but we don't care if runs along the edge.
45 *
46 * @author Gerd Petermann
47 *
48 */
49 public class IsInUtil {
50 private static final Logger log = Logger.getLogger(IsInUtil.class);
51 public static final int IN = 0x01;
52 public static final int ON = 0x02;
53 public static final int OUT = 0x04;
54
55 public static final int IN_ON_OUT = IN | ON | OUT;
56
57 private IsInUtil() {
58 // hide public constructor
59 }
60
61 public static void mergePolygons(Set<Way> polygons, List<List<Coord>> outers, List<List<Coord>> holes) {
62 // combine all polygons which intersect the bbox of the element if possible
63 Path2D.Double path = new Path2D.Double();
64 for (Way polygon : polygons) {
65 path.append(Java2DConverter.createPath2D(polygon.getPoints()), false);
66 }
67 java.awt.geom.Area polygonsArea = new java.awt.geom.Area(path);
68 List<List<Coord>> mergedShapes = Java2DConverter.areaToShapes(polygonsArea);
69
70 // combination of polygons may contain holes. They are counter clockwise.
71 for (List<Coord> shape : mergedShapes) {
72 (Way.clockwise(shape) ? outers : holes).add(shape);
73 }
74 }
75
76 private enum IntersectionStatus {
77 TOUCHING, CROSSING, SPLITTING, JOINING,SIMILAR, DOUBLE_SPIKE
78 }
79
80 private static final int EPS_HP = 4; // ~0.15 meters at equator
81 private static final int EPS_HP_SQRD = EPS_HP * EPS_HP;
82 private static final double EPS = 0.15; // meters. needed for distToLineSegment()
83 private static final double EPS_OFF = EPS * 2;
84
85 public static int isLineInShape(List<Coord> lineToTest, List<Coord> shape, Area elementBbox) {
86 final int n = lineToTest.size();
87 int status = isPointInShape(lineToTest.get(0), shape);
88 BitSet onBoundary = new BitSet();
89
90 for (int i = 0; i < shape.size() - 1; i++) {
91 Coord p11 = shape.get(i);
92 Coord p12 = shape.get(i + 1);
93 if (p11.distanceInHighPrecSquared(p12) < EPS_HP_SQRD) { // skip very short segments
94 continue;
95 }
96 // check if shape segment is clearly below, above, right or left of bbox
97 if ((Math.min(p11.getLatitude(), p12.getLatitude()) > elementBbox.getMaxLat() + 1)
98 || (Math.max(p11.getLatitude(), p12.getLatitude()) < elementBbox.getMinLat() - 1)
99 || (Math.min(p11.getLongitude(), p12.getLongitude()) > elementBbox.getMaxLong() + 1)
100 || (Math.max(p11.getLongitude(), p12.getLongitude()) < elementBbox.getMinLong() - 1))
101 continue;
102 for (int k = 0; k < n - 1; k++) {
103 Coord p21 = lineToTest.get(k);
104 Coord p22 = lineToTest.get(k + 1);
105 if (p21.distanceInHighPrecSquared(p22) < EPS_HP_SQRD) { // skip very short segments
106 continue;
107 }
108 Coord inter = Utils.getSegmentSegmentIntersection(p11, p12, p21, p22);
109 if (inter != null) {
110 // segments have at least one common point
111 boolean isCrossing = false;
112 if (inter.distanceInHighPrecSquared(p21) < EPS_HP_SQRD) {
113 onBoundary.set(k);
114 if (k == 0) {
115 status |= ON;
116 } else {
117 if (p21.distanceInHighPrecSquared(p11) < EPS_HP_SQRD) {
118 Coord p20 = lineToTest.get(k - 1);
119 Coord p10 = shape.get(i - 1 >= 0 ? i - 1 : shape.size() - 2);
120 IntersectionStatus x = analyseCrossingInPoint(p11, p20, p22, p10, p12);
121 Coord pTest = null;
122 if (x == IntersectionStatus.CROSSING) {
123 isCrossing = true;
124 } else if (x == IntersectionStatus.JOINING) {
125 if (!isOnOrCloseToEdgeOfShape(shape, p21, p20)) {
126 pTest = p21.destOnRhumbLine(EPS_OFF, p21.bearingTo(p20));
127 }
128 } else if (x == IntersectionStatus.SPLITTING) {
129 if (!isOnOrCloseToEdgeOfShape(shape, p21, p22)) {
130 pTest = p21.destOnRhumbLine(EPS_OFF, p21.bearingTo(p22));
131 }
132 }
133 if (pTest != null) {
134 int testStat = isPointInShape(pTest, shape);
135 status |= testStat;
136 if ((status | ON) == IN_ON_OUT)
137 return IN_ON_OUT;
138 }
139 } else if (p21.distanceInHighPrecSquared(p12) < EPS_HP_SQRD) {
140 // handled in next iteration (k+1) or (i+1)b
141 } else {
142 // way segment starts on a shape segment
143 // somewhere between p11 and p12
144 // it may cross the shape or just touch it,
145 // check if previous way segment is on the same
146 // side or not
147 long isLeftPrev = lineToTest.get(k-1).isLeft(p11, p12);
148 long isLeftNext = p22.isLeft(p11, p12);
149 if (isLeftPrev< 0 && isLeftNext > 0 || isLeftPrev > 0 && isLeftNext < 0) {
150 // both way segments are not on the shape
151 // segment and they are on different sides
152 isCrossing = true;
153 }
154 }
155 }
156 } else if (inter.distanceInHighPrecSquared(p22) < EPS_HP_SQRD) {
157 onBoundary.set(k + 1);
158 // handle intersection on next iteration
159 } else if (inter.distanceInHighPrecSquared(p11) < EPS_HP_SQRD || inter.distanceInHighPrecSquared(p12) < EPS_HP_SQRD) {
160 // intersection is very close to end of shape segment
161 if (inter.distToLineSegment(p21, p22) > EPS)
162 isCrossing = true;
163 } else {
164 isCrossing = true;
165 }
166 if (isCrossing) {
167 // real intersection found
168 return IN_ON_OUT;
169 }
170 }
171 }
172 }
173
174 if (!onBoundary.isEmpty())
175 status |= ON;
176 if (status == ON) {
177 // found no intersection and first point is on boundary
178 while (onBoundary.cardinality() != n) {
179 int pos = onBoundary.nextClearBit(0);
180 // return result for first point which is not on boundary
181 Coord pTest = lineToTest.get(pos);
182 status |= isPointInShape(pTest, shape);
183 if (status == ON) {
184 onBoundary.set(pos);
185 continue;
186 }
187 return status;
188 }
189 status |= checkAllOn(lineToTest, shape);
190 }
191 return status;
192 }
193
194
195 /**
196 * Handle special case that all points of {@code lineToTest} are on the edge of shape
197 * @param lineToTest
198 * @param shape
199 * @return
200 */
201 private static int checkAllOn(List<Coord> lineToTest, List<Coord> shape) {
202 int n = lineToTest.size();
203 // all points are on boundary
204 for (int i = 0; i < n-1; i++) {
205 Coord p1 = lineToTest.get(i);
206 Coord p2 = lineToTest.get(i + 1);
207 if (!isOnOrCloseToEdgeOfShape(shape, p1, p2)) {
208 Coord pTest = p1.destOnRhumbLine(EPS_OFF, p1.bearingTo(p2));
209 int resMidPoint = isPointInShape(pTest, shape);
210 if (resMidPoint != ON)
211 return resMidPoint;
212 }
213 }
214 return ON;
215 }
216
217 /**
218 * two line-strings a-s-c and x-s-y the same mid point. Check if they are crossing. This is the case
219 * if a-s-c is between x-s-y or if x-s-y is between a-s-c.
220 * @param s the share point
221 * @param a 1st point 1st line-string
222 * @param b 2nd point 1st line-string
223 * @param x 1st point 2nd line-string
224 * @param y 2nd point 2nd line-string
225 * @return kind of crossing or touching
226 */
227 private static IntersectionStatus analyseCrossingInPoint(Coord s, Coord a, Coord b, Coord x, Coord y) {
228 TreeMap<Long, Character> map = new TreeMap<>();
229 long ba = Math.round(s.bearingTo(a) * 1000);
230 long bb = Math.round(s.bearingTo(b) * 1000);
231 long bx = Math.round(s.bearingTo(x) * 1000);
232 long by = Math.round(s.bearingTo(y) * 1000);
233 map.put(ba, 'a');
234 map.put(bb, 'b');
235 map.put(bx, 'x');
236 map.put(by, 'y');
237 List<Character> sortedByBearing = new ArrayList<>(map.values());
238 int apos = sortedByBearing.indexOf('a');
239 int bpos = sortedByBearing.indexOf('b');
240 int xpos = sortedByBearing.indexOf('x');
241 int ypos = sortedByBearing.indexOf('y');
242
243 if (map.size() == 4) {
244 if (Math.abs(xpos-ypos) == 2) {
245 // pair xy is either on 0 and 2 or 1 and 3, so only one of a and b is between them
246 // shape segments x-s-y is nether between nor outside of way segments a-s-b
247 return IntersectionStatus.CROSSING;
248 }
249 return IntersectionStatus.TOUCHING;
250 }
251
252 if (map.size() == 3) {
253 if (xpos < 0) {
254 // x-s-y is a spike that touches a-s-b
255 return IntersectionStatus.TOUCHING;
256 }
257 if (bpos < 0) {
258 // either s-x or s-y is overlaps s-b
259 return IntersectionStatus.JOINING;
260 }
261 if (ba == bx || ba == by) {
262 return IntersectionStatus.SPLITTING;
263 }
264 return IntersectionStatus.TOUCHING;
265 }
266 if (map.size() == 2) {
267 if (apos > 0 || bpos > 0) {
268 // two spikes meeting
269 return IntersectionStatus.TOUCHING;
270 }
271 // a-s-b and x-s-y are overlapping (maybe have different directions)
272 return IntersectionStatus.SIMILAR;
273 }
274 // both a-s-b and x-s-y come from and go to the same direction
275 return IntersectionStatus.DOUBLE_SPIKE;
276 }
277
278 /**
279 * Check if the sequence p1-p2 or p2-p1 appears in the shape or if there is only one point c between and the sequence p1-c-p2
280 * is nearly straight.
281 * @param shape list of points describing the shape
282 * @param p1 first point
283 * @param p2 second point
284 * @return true if the sequence p1-p2 or p2-p1 appears in the shape or if there is only one point c between and the sequence p1-c-p2
285 * is nearly straight, else false.
286 */
287 private static boolean isOnOrCloseToEdgeOfShape(List<Coord> shape, Coord p1, Coord p2) {
288 for (int i = 0; i < shape.size(); i++) {
289 Coord p = shape.get(i);
290 if (p.distanceInHighPrecSquared(p1) >= EPS_HP_SQRD)
291 continue;
292
293 int posPrev = i > 0 ? i - 1 : shape.size() - 2;
294 int posNext = i < shape.size() - 1 ? i + 1 : 1;
295 if (shape.get(posPrev).distanceInHighPrecSquared(p2) < EPS_HP_SQRD || shape.get(posNext).distanceInHighPrecSquared(p2) < EPS_HP_SQRD)
296 return true;
297
298 int posPrev2 = posPrev > 0 ? posPrev - 1 : shape.size() - 2;
299 int posNext2 = posNext < shape.size() - 1 ? posNext + 1 : 1;
300 if (shape.get(posPrev2).distanceInHighPrecSquared(p2) < EPS_HP_SQRD && Math.abs(Utils.getAngle(p1, shape.get(posPrev), p2)) < 0.1) {
301 // shape segments between p1 and p2 are almost straight
302 return true;
303 }
304 if (shape.get(posNext2).distanceInHighPrecSquared(p2) < EPS_HP_SQRD && Math.abs(Utils.getAngle(p1, shape.get(posNext), p2)) < 0.1) {
305 // shape segments between p1 and p2 are almost straight
306 return true;
307 }
308 }
309
310 return false;
311 }
312
313 /**
314 * Check if node is in polygon using crossing number counter, with some some tolerance
315 * @param node the point to test
316 * @param shape list of points describing the polygon
317 * @return IN/ON/OUT
318 */
319 public static int isPointInShape(Coord node, List<Coord> shape) {
320 final int nodeLat = node.getHighPrecLat();
321 final int nodeLon = node.getHighPrecLon();
322 if (log.isDebugEnabled()) {
323 log.debug("node", node, nodeLon, nodeLat, shape.size(), shape);
324 }
325 int trailLat = 0, trailLon = 0;
326 int lhsCount = 0, rhsCount = 0; // count both, to be sure
327 int minLat, maxLat, minLon, maxLon;
328 double lonDif, latDif, distSqrd;
329 boolean subsequent = false;
330 for (Coord leadCoord : shape) {
331 final int leadLat = leadCoord.getHighPrecLat();
332 final int leadLon = leadCoord.getHighPrecLon();
333 if (subsequent) { // use first point as trailing (poly is closed)
334 if (leadCoord.distanceInHighPrecSquared(node) < EPS_HP_SQRD)
335 return ON;
336 if (leadLat < trailLat) {
337 minLat = leadLat;
338 maxLat = trailLat;
339 } else {
340 minLat = trailLat;
341 maxLat = leadLat;
342 }
343 if (leadLon < trailLon) {
344 minLon = leadLon;
345 maxLon = trailLon;
346 } else {
347 minLon = trailLon;
348 maxLon = leadLon;
349 }
350 if (minLat - EPS_HP > nodeLat) {
351 // line segment is all slightly above, ignore
352 } else if (maxLat + EPS_HP < nodeLat) {
353 // line segment is all slightly below, ignore
354 } else if (minLon - EPS_HP > nodeLon && minLat < nodeLat && maxLat > nodeLat) {
355 ++rhsCount; // definite line segment all slightly to the right
356 } else if (maxLon + EPS_HP < nodeLon && minLat < nodeLat && maxLat > nodeLat) {
357 ++lhsCount; // definite line segment all slightly to the left
358 } else { // need to consider this segment more carefully.
359 if (leadLat == trailLat)
360 lonDif = Double.POSITIVE_INFINITY; // horizontal lines ignored in crossing calc, infinity handled in distToLine calc
361 else
362 lonDif = nodeLon - trailLon - (double)(nodeLat - trailLat) / (leadLat - trailLat) * (leadLon - trailLon);
363 if ((minLon - EPS_HP <= nodeLon) && (maxLon + EPS_HP >= nodeLon)) { // check if the point is ON the line
364 if (leadLon == trailLon)
365 latDif = Double.POSITIVE_INFINITY; // handled in distToLine calc
366 else
367 latDif = nodeLat - trailLat - (double)(nodeLon - trailLon) / (leadLon - trailLon) * (leadLat - trailLat);
368 // calculate distance to segment using right-angle attitude theorem
369 log.debug("inBox", leadLon-nodeLon, leadLat-nodeLat, trailLon-nodeLon, trailLat-nodeLat, lonDif, latDif, lhsCount, rhsCount);
370 // There can be a small area, within the square EPS_HP*2 around the node, but is not in the circle radius EPS_HP where a polygon
371 // vertix meets this square, that will be incorrectly calculated as ON
372 if (Double.isInfinite(lonDif))
373 distSqrd = latDif*latDif;
374 else if (Double.isInfinite(latDif))
375 distSqrd = lonDif*lonDif;
376 else if (Math.abs(lonDif) < EPS_HP || Math.abs(latDif) < EPS_HP)
377 return ON;
378 else
379 distSqrd = lonDif*lonDif * latDif*latDif / (lonDif*lonDif + latDif*latDif);
380 if (distSqrd < EPS_HP_SQRD)
381 return ON;
382 } else
383 log.debug("inSlice", leadLon-nodeLon, leadLat-nodeLat, trailLon-nodeLon, trailLat-nodeLat, lonDif, "N/A", lhsCount, rhsCount);
384 if ((trailLat <= nodeLat && leadLat > nodeLat) || // an upward crossing
385 (trailLat > nodeLat && leadLat <= nodeLat)) { // a downward crossing
386 if (lonDif < 0)
387 ++rhsCount; // a valid crossing right of nodeLon
388 else
389 ++lhsCount;
390 }
391 }
392 } // if not first Coord
393 subsequent = true;
394 trailLat = leadLat;
395 trailLon = leadLon;
396 } // for leadCoord
397 log.debug("lhs | rhs", lhsCount, rhsCount);
398 assert (lhsCount & 1) == (rhsCount & 1) : "LHS: " + lhsCount + " RHS: " + rhsCount;
399 return (rhsCount & 1) == 1 ? IN : OUT;
400 }
401
402 }