~lib2geom-hackers/lib2geom/trunk

« back to all changes in this revision

Viewing changes to centroid.cpp

  • Committer: njh
  • Date: 2006-05-22 11:50:24 UTC
  • Revision ID: svn-v4:4601daaa-0314-0410-9a8b-c964a3c23b6b:trunk/lib2geom:1
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include "path.h"
 
2
 
 
3
/*
 
4
 * ANSI C code from the article
 
5
 * "Centroid of a Polygon"
 
6
 * by Gerard Bashein and Paul R. Detmer,
 
7
 (gb@locke.hs.washington.edu, pdetmer@u.washington.edu)
 
8
 * in "Graphics Gems IV", Academic Press, 1994
 
9
 */
 
10
 
 
11
/**
 
12
 * polyCentroid: Calculates the centroid (xCentroid, yCentroid) and area of a polygon, given its
 
13
 * vertices (x[0], y[0]) ... (x[n-1], y[n-1]). It is assumed that the contour is closed, i.e., that
 
14
 * the vertex following (x[n-1], y[n-1]) is (x[0], y[0]).  The algebraic sign of the area is
 
15
 * positive for counterclockwise ordering of vertices in x-y plane; otherwise negative.
 
16
 
 
17
 * Returned values: 
 
18
    0 for normal execution; 
 
19
    1 if the polygon is degenerate (number of vertices < 3);
 
20
    2 if area = 0 (and the centroid is undefined).
 
21
 
 
22
    * for now we require the path to be a polyline and assume it is closed.
 
23
**/
 
24
int centroid(std::vector<Point> p, Point centroid, double &area) {
 
25
    if (n < 3)
 
26
        return 1;
 
27
    Point centroid_tmp(0,0);
 
28
    double atmp = 0;
 
29
    for (int i(n-1), j(0); j < n; i = j, j++) {
 
30
        const double ai = cross(p[j], p[i]);
 
31
        atmp += ai;
 
32
        centroid_tmp += (p[j] + p[i]) * ai; // first moment.
 
33
    }
 
34
    *area = atmp / 2;
 
35
    if (atmp != 0) {
 
36
        centroid = centroid / (3 * atmp);
 
37
        return 0;
 
38
    }
 
39
    return 2;
 
40
}
 
41
 
 
42
/*
 
43
  Local Variables:
 
44
  mode:c++
 
45
  c-file-style:"stroustrup"
 
46
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
 
47
  indent-tabs-mode:nil
 
48
  fill-column:99
 
49
  End:
 
50
*/
 
51
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :