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
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.
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).
22
* for now we require the path to be a polyline and assume it is closed.
24
int centroid(std::vector<Point> p, Point centroid, double &area) {
27
Point centroid_tmp(0,0);
29
for (int i(n-1), j(0); j < n; i = j, j++) {
30
const double ai = cross(p[j], p[i]);
32
centroid_tmp += (p[j] + p[i]) * ai; // first moment.
36
centroid = centroid / (3 * atmp);
45
c-file-style:"stroustrup"
46
c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
51
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :