1 /*
2 * convex-cover.cpp
3 *
4 * Copyright 2006 Nathan Hurst <njh@mail.csse.monash.edu.au>
5 * Copyright 2006 Michael G. Sloan <mgsloan@gmail.com>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it either under the terms of the GNU Lesser General Public
9 * License version 2.1 as published by the Free Software Foundation
10 * (the "LGPL") or, at your option, under the terms of the Mozilla
11 * Public License Version 1.1 (the "MPL"). If you do not alter this
12 * notice, a recipient may use your version of this file under either
13 * the MPL or the LGPL.
14 *
15 * You should have received a copy of the LGPL along with this library
16 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 * You should have received a copy of the MPL along with this library
19 * in the file COPYING-MPL-1.1
20 *
21 * The contents of this file are subject to the Mozilla Public License
22 * Version 1.1 (the "License"); you may not use this file except in
23 * compliance with the License. You may obtain a copy of the License at
24 * http://www.mozilla.org/MPL/
25 *
26 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
27 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
28 * the specific language governing rights and limitations.
29 *
30 */
32 #include <2geom/convex-cover.h>
33 #include <algorithm>
34 #include <map>
35 /** Todo:
36 + modify graham scan to work top to bottom, rather than around angles
37 + intersection
38 + minimum distance between convex hulls
39 + maximum distance between convex hulls
40 + hausdorf metric?
41 + check all degenerate cases carefully
42 + check all algorithms meet all invariants
43 + generalise rotating caliper algorithm (iterator/circulator?)
44 */
46 using std::vector;
47 using std::map;
48 using std::pair;
50 namespace Geom{
52 /*** SignedTriangleArea
53 * returns the area of the triangle defined by p0, p1, p2. A clockwise triangle has positive area.
54 */
55 double
56 SignedTriangleArea(Point p0, Point p1, Point p2) {
57 return cross((p1 - p0), (p2 - p0));
58 }
60 class angle_cmp{
61 public:
62 Point o;
63 angle_cmp(Point o) : o(o) {}
65 bool
66 operator()(Point a, Point b) {
67 Point da = a - o;
68 Point db = b - o;
70 #if 1
71 double aa = da[0];
72 double ab = db[0];
73 if((da[1] == 0) && (db[1] == 0))
74 return da[0] < db[0];
75 if(da[1] == 0)
76 return true; // infinite tangent
77 if(db[1] == 0)
78 return false; // infinite tangent
79 aa = da[0] / da[1];
80 ab = db[0] / db[1];
81 if(aa > ab)
82 return true;
83 #else
84 //assert((ata > atb) == (aa < ab));
85 double aa = atan2(da);
86 double ab = atan2(db);
87 if(aa < ab)
88 return true;
89 #endif
90 if(aa == ab)
91 return L2sq(da) < L2sq(db);
92 return false;
93 }
94 };
96 void
97 ConvexHull::find_pivot() {
98 // Find pivot P;
99 unsigned pivot = 0;
100 for(unsigned i = 1; i < boundary.size(); i++)
101 if(boundary[i] <= boundary[pivot])
102 pivot = i;
104 std::swap(boundary[0], boundary[pivot]);
105 }
107 void
108 ConvexHull::angle_sort() {
109 // sort points by angle (resolve ties in favor of point farther from P);
110 // we leave the first one in place as our pivot
111 std::sort(boundary.begin()+1, boundary.end(), angle_cmp(boundary[0]));
112 }
114 void
115 ConvexHull::graham_scan() {
116 unsigned stac = 2;
117 for(unsigned int i = 2; i < boundary.size(); i++) {
118 double o = SignedTriangleArea(boundary[stac-2],
119 boundary[stac-1],
120 boundary[i]);
121 if(o == 0) { // colinear - dangerous...
122 stac--;
123 } else if(o < 0) { // anticlockwise
124 } else { // remove concavity
125 while(o >= 0 && stac > 2) {
126 stac--;
127 o = SignedTriangleArea(boundary[stac-2],
128 boundary[stac-1],
129 boundary[i]);
130 }
131 }
132 boundary[stac++] = boundary[i];
133 }
134 boundary.resize(stac);
135 }
137 void
138 ConvexHull::graham() {
139 if(is_degenerate()) // nothing to do
140 return;
141 find_pivot();
142 angle_sort();
143 graham_scan();
144 }
146 //Mathematically incorrect mod, but more useful.
147 int mod(int i, int l) {
148 return i >= 0 ?
149 i % l : (i % l) + l;
150 }
151 //OPT: usages can often be replaced by conditions
153 /*** ConvexHull::left
154 * Tests if a point is left (outside) of a particular segment, n. */
155 bool
156 ConvexHull::is_left(Point p, int n) {
157 return SignedTriangleArea((*this)[n], (*this)[n+1], p) > 0;
158 }
160 /*** ConvexHull::find_positive
161 * May return any number n where the segment n -> n + 1 (possibly looped around) in the hull such
162 * that the point is on the wrong side to be within the hull. Returns -1 if it is within the hull.*/
163 int
164 ConvexHull::find_left(Point p) {
165 int l = boundary.size(); //Who knows if C++ is smart enough to optimize this?
166 for(int i = 0; i < l; i++) {
167 if(is_left(p, i)) return i;
168 }
169 return -1;
170 }
171 //OPT: do a spread iteration - quasi-random with no repeats and full coverage.
173 /*** ConvexHull::contains_point
174 * In order to test whether a point is inside a convex hull we can travel once around the outside making
175 * sure that each triangle made from an edge and the point has positive area. */
176 bool
177 ConvexHull::contains_point(Point p) {
178 return find_left(p) == -1;
179 }
181 /*** ConvexHull::add_point
182 * to add a point we need to find whether the new point extends the boundary, and if so, what it
183 * obscures. Tarjan? Jarvis?*/
184 void
185 ConvexHull::merge(Point p) {
186 std::vector<Point> out;
188 int l = boundary.size();
190 if(l < 2) {
191 boundary.push_back(p);
192 return;
193 }
195 bool pushed = false;
197 bool pre = is_left(p, -1);
198 for(int i = 0; i < l; i++) {
199 bool cur = is_left(p, i);
200 if(pre) {
201 if(cur) {
202 if(!pushed) {
203 out.push_back(p);
204 pushed = true;
205 }
206 continue;
207 }
208 else if(!pushed) {
209 out.push_back(p);
210 pushed = true;
211 }
212 }
213 out.push_back(boundary[i]);
214 pre = cur;
215 }
217 boundary = out;
218 }
219 //OPT: quickly find an obscured point and find the bounds by extending from there. then push all points not within the bounds in order.
220 //OPT: use binary searches to find the actual starts/ends, use known rights as boundaries. may require cooperation of find_left algo.
222 /*** ConvexHull::is_clockwise
223 * We require that successive pairs of edges always turn right.
224 * proposed algorithm: walk successive edges and require triangle area is positive.
225 */
226 bool
227 ConvexHull::is_clockwise() const {
228 if(is_degenerate())
229 return true;
230 Point first = boundary[0];
231 Point second = boundary[1];
232 for(std::vector<Point>::const_iterator it(boundary.begin()+2), e(boundary.end());
233 it != e;) {
234 if(SignedTriangleArea(first, second, *it) > 0)
235 return false;
236 first = second;
237 second = *it;
238 ++it;
239 }
240 return true;
241 }
243 /*** ConvexHull::top_point_first
244 * We require that the first point in the convex hull has the least y coord, and that off all such points on the hull, it has the least x coord.
245 * proposed algorithm: track lexicographic minimum while walking the list.
246 */
247 bool
248 ConvexHull::top_point_first() const {
249 std::vector<Point>::const_iterator pivot = boundary.begin();
250 for(std::vector<Point>::const_iterator it(boundary.begin()+1),
251 e(boundary.end());
252 it != e; it++) {
253 if((*it)[1] < (*pivot)[1])
254 pivot = it;
255 else if(((*it)[1] == (*pivot)[1]) &&
256 ((*it)[0] < (*pivot)[0]))
257 pivot = it;
258 }
259 return pivot == boundary.begin();
260 }
261 //OPT: since the Y values are orderly there should be something like a binary search to do this.
263 /*** ConvexHull::no_colinear_points
264 * We require that no three vertices are colinear.
265 proposed algorithm: We must be very careful about rounding here.
266 */
267 bool
268 ConvexHull::no_colinear_points() const {
269 // XXX: implement me!
270 }
272 bool
273 ConvexHull::meets_invariants() const {
274 return is_clockwise() && top_point_first() && no_colinear_points();
275 }
277 /*** ConvexHull::is_degenerate
278 * We allow three degenerate cases: empty, 1 point and 2 points. In many cases these should be handled explicitly.
279 */
280 bool
281 ConvexHull::is_degenerate() const {
282 return boundary.size() < 3;
283 }
286 /* Here we really need a rotating calipers implementation. This implementation is slow and incorrect.
287 This incorrectness is a problem because it throws off the algorithms. Perhaps I will come up with
288 something better tomorrow. The incorrectness is in the order of the bridges - they must be in the
289 order of traversal around. Since the a->b and b->a bridges are seperated, they don't need to be merge
290 order, just the order of the traversal of the host hull. Currently some situations make a n->0 bridge
291 first.*/
292 pair< map<int, int>, map<int, int> >
293 bridges(ConvexHull a, ConvexHull b) {
294 map<int, int> abridges;
295 map<int, int> bbridges;
297 for(unsigned ia = 0; ia < a.boundary.size(); ia++) {
298 for(unsigned ib = 0; ib < b.boundary.size(); ib++) {
299 Point d = b[ib] - a[ia];
300 Geom::Coord e = cross(d, a[ia - 1] - a[ia]), f = cross(d, a[ia + 1] - a[ia]);
301 Geom::Coord g = cross(d, b[ib - 1] - a[ia]), h = cross(d, b[ib + 1] - a[ia]);
302 if (e > 0 && f > 0 && g > 0 && h > 0) abridges[ia] = ib;
303 else if(e < 0 && f < 0 && g < 0 && h < 0) bbridges[ib] = ia;
304 }
305 }
307 return make_pair(abridges, bbridges);
308 }
310 std::vector<Point> bridge_points(ConvexHull a, ConvexHull b) {
311 vector<Point> ret;
312 pair< map<int, int>, map<int, int> > indices = bridges(a, b);
313 for(map<int, int>::iterator it = indices.first.begin(); it != indices.first.end(); it++) {
314 ret.push_back(a[it->first]);
315 ret.push_back(b[it->second]);
316 }
317 for(map<int, int>::iterator it = indices.second.begin(); it != indices.second.end(); it++) {
318 ret.push_back(b[it->first]);
319 ret.push_back(a[it->second]);
320 }
321 return ret;
322 }
324 unsigned find_bottom_right(ConvexHull const &a) {
325 unsigned it = 1;
326 while(it < a.boundary.size() &&
327 a.boundary[it][Y] > a.boundary[it-1][Y])
328 it++;
329 return it-1;
330 }
332 /*** ConvexHull sweepline_intersection(ConvexHull a, ConvexHull b);
333 * find the intersection between two convex hulls. The intersection is also a convex hull.
334 * (Proof: take any two points both in a and in b. Any point between them is in a by convexity,
335 * and in b by convexity, thus in both. Need to prove still finite bounds.)
336 * This algorithm works by sweeping a line down both convex hulls in parallel, working out the left and right edges of the new hull.
337 */
338 ConvexHull sweepline_intersection(ConvexHull const &a, ConvexHull const &b) {
339 ConvexHull ret;
341 unsigned al = 0;
342 unsigned bl = 0;
344 while(al+1 < a.boundary.size() &&
345 (a.boundary[al+1][Y] > b.boundary[bl][Y])) {
346 al++;
347 }
348 while(bl+1 < b.boundary.size() &&
349 (b.boundary[bl+1][Y] > a.boundary[al][Y])) {
350 bl++;
351 }
352 // al and bl now point to the top of the first pair of edges that overlap in y value
353 //double sweep_y = std::min(a.boundary[al][Y],
354 // b.boundary[bl][Y]);
355 return ret;
356 }
358 /*** ConvexHull intersection(ConvexHull a, ConvexHull b);
359 * find the intersection between two convex hulls. The intersection is also a convex hull.
360 * (Proof: take any two points both in a and in b. Any point between them is in a by convexity,
361 * and in b by convexity, thus in both. Need to prove still finite bounds.)
362 */
363 ConvexHull intersection(ConvexHull /*a*/, ConvexHull /*b*/) {
364 ConvexHull ret;
365 /*
366 int ai = 0, bi = 0;
367 int aj = a.boundary.size() - 1;
368 int bj = b.boundary.size() - 1;
369 */
370 /*while (true) {
371 if(a[ai]
372 }*/
373 return ret;
374 }
376 /*** ConvexHull merge(ConvexHull a, ConvexHull b);
377 * find the smallest convex hull that surrounds a and b.
378 */
379 ConvexHull merge(ConvexHull a, ConvexHull b) {
380 ConvexHull ret;
382 pair< map<int, int>, map<int, int> > bpair = bridges(a, b);
383 map<int, int> ab = bpair.first;
384 map<int, int> bb = bpair.second;
386 ab[-1] = 0;
387 bb[-1] = 0;
389 int i = -1; // XXX: i is int but refers to vector indices
391 if(a.boundary[0][1] > b.boundary[0][1]) goto start_b;
392 while(true) {
393 for(; ab.count(i) == 0; i++) {
394 ret.boundary.push_back(a[i]);
395 if(i >= (int)a.boundary.size()) return ret;
396 }
397 if(ab[i] == 0 && i != -1) break;
398 i = ab[i];
399 start_b:
401 for(; bb.count(i) == 0; i++) {
402 ret.boundary.push_back(b[i]);
403 if(i >= (int)b.boundary.size()) return ret;
404 }
405 if(bb[i] == 0 && i != -1) break;
406 i = bb[i];
407 }
408 return ret;
409 }
411 ConvexHull graham_merge(ConvexHull a, ConvexHull b) {
412 ConvexHull result;
414 // we can avoid the find pivot step because of top_point_first
415 if(b.boundary[0] <= a.boundary[0])
416 std::swap(a, b);
418 result.boundary = a.boundary;
419 result.boundary.insert(result.boundary.end(),
420 b.boundary.begin(), b.boundary.end());
422 /** if we modified graham scan to work top to bottom as proposed in lect754.pdf we could replace the
423 angle sort with a simple merge sort type algorithm. furthermore, we could do the graham scan
424 online, avoiding a bunch of memory copies. That would probably be linear. -- njh*/
425 result.angle_sort();
426 result.graham_scan();
428 return result;
429 }
430 //TODO: reinstate
431 /*ConvexCover::ConvexCover(Path const &sp) : path(&sp) {
432 cc.reserve(sp.size());
433 for(Geom::Path::const_iterator it(sp.begin()), end(sp.end()); it != end; ++it) {
434 cc.push_back(ConvexHull((*it).begin(), (*it).end()));
435 }
436 }*/
438 double ConvexHull::centroid_and_area(Geom::Point& centroid) const {
439 const unsigned n = boundary.size();
440 if (n < 2)
441 return 0;
442 if(n < 3) {
443 centroid = (boundary[0] + boundary[1])/2;
444 return 0;
445 }
446 Geom::Point centroid_tmp(0,0);
447 double atmp = 0;
448 for (unsigned i = n-1, j = 0; j < n; i = j, j++) {
449 const double ai = -cross(boundary[j], boundary[i]);
450 atmp += ai;
451 centroid_tmp += (boundary[j] + boundary[i])*ai; // first moment.
452 }
453 if (atmp != 0) {
454 centroid = centroid_tmp / (3 * atmp);
455 }
456 return atmp / 2;
457 }
459 // TODO: This can be made lg(n) using golden section/fibonacci search three starting points, say 0,
460 // n/2, n-1 construct a new point, say (n/2 + n)/2 throw away the furthest boundary point iterate
461 // until interval is a single value
462 Point const * ConvexHull::furthest(Point direction) const {
463 Point const * p = &boundary[0];
464 double d = dot(*p, direction);
465 for(unsigned i = 1; i < boundary.size(); i++) {
466 double dd = dot(boundary[i], direction);
467 if(d < dd) {
468 p = &boundary[i];
469 d = dd;
470 }
471 }
472 return p;
473 }
476 // returns (a, (b,c)), three points which define the narrowest diameter of the hull as the pair of
477 // lines going through b,c, and through a, parallel to b,c TODO: This can be made linear time by
478 // moving point tc incrementally from the previous value (it can only move in one direction). It
479 // is currently n*O(furthest)
480 double ConvexHull::narrowest_diameter(Point &a, Point &b, Point &c) {
481 Point tb = boundary.back();
482 double d = INFINITY;
483 for(unsigned i = 0; i < boundary.size(); i++) {
484 Point tc = boundary[i];
485 Point n = -rot90(tb-tc);
486 Point ta = *furthest(n);
487 double td = dot(n, ta-tb)/dot(n,n);
488 if(td < d) {
489 a = ta;
490 b = tb;
491 c = tc;
492 d = td;
493 }
494 tb = tc;
495 }
496 return d;
497 }
499 };
501 /*
502 Local Variables:
503 mode:c++
504 c-file-style:"stroustrup"
505 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
506 indent-tabs-mode:nil
507 fill-column:99
508 End:
509 */
510 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :