| 1 | #define USING_R 1 |
| 2 | /* Modified 24 May 2005 Roger S. Bivand for maptools |
| 3 | Written by Joseph O'Rourke |
| 4 | [email protected] |
| 5 | October 27, 1995 |
| 6 | |
| 7 | Computes the centroid (center of gravity) of an arbitrary |
| 8 | simple polygon via a weighted sum of signed triangle areas, |
| 9 | weighted by the centroid of each triangle. |
| 10 | Reads x,y coordinates from stdin. |
| 11 | NB: Assumes points are entered in ccw order! |
| 12 | E.g., input for square: |
| 13 | 0 0 |
| 14 | 10 0 |
| 15 | 10 10 |
| 16 | 0 10 |
| 17 | This solves Exercise 12, p.47, of my text, |
| 18 | Computational Geometry in C. See the book for an explanation |
| 19 | of why this works. Follow links from |
| 20 | http://cs.smith.edu/~orourke/ |
| 21 | |
| 22 | */ |
| 23 | |
| 24 | #ifndef USING_R |
| 25 | # define R_alloc(n,size) S_alloc(n,size,S_evaluator) |
| 26 | #endif |
| 27 | |
| 28 | #include "sp.h" |
| 29 | |
| 30 | |
| 31 | /*#define PMAX 1000 Max # of pts in polygon */ |
| 32 | /* typedef tPointd *tPolygond; */ /* type double polygon */ |
| 33 | |
| 34 | |
| 35 | void spRFindCG( int *n, double *x, double *y, double *xc, double *yc, |
| 36 | double *area ) { |
| 37 | |
| 38 | int i, nn; |
| 39 | tPointd *P; |
| 40 | tPointd CG; |
| 41 | double Areasum2; |
| 42 | nn = n[0]; |
| 43 | P = (tPointd *) R_alloc((size_t) nn, sizeof(tPointd)); |
| 44 | for (i=0; i<nn; i++) { |
| 45 | P[i][0] = x[i]; |
| 46 | P[i][1] = y[i]; |
| 47 | } |
| 48 | FindCG(nn, P, CG, &Areasum2); |
| 49 | xc[0] = CG[0]; |
| 50 | yc[0] = CG[1]; |
| 51 | area[0] = Areasum2/2; |
| 52 | return; |
| 53 | } |
| 54 | |
| 55 | /* |
| 56 | Returns the cg in CG. Computes the weighted sum of |
| 57 | each triangle's area times its centroid. Twice area |
| 58 | and three times centroid is used to avoid division |
| 59 | until the last moment. |
| 60 | */ |
| 61 |