# Untitled

By: a guest on Aug 19th, 2012  |  syntax: C++  |  size: 1.69 KB  |  hits: 8  |  expires: Never
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
1. /* homogeneous coordinates point */
2. namespace POINT2D
3. {
4.     template<class T> T _sqr(T x){ return x*x; }
5.
6.     struct point
7.     {
8.         point(double _x = 0, double _y = 0, double _w = 1): x(_x), y(_y), w(_w) { normalize(); }
9.         double x, y, w;
10.         void normalize() { if (w != 0){ x /= w; y /= w; w = 1; } }
11.     };
12.
13.     const point O(0, 0, 1);
14.
15.     inline istream& operator >> (istream& istr, point& p){ p.w = 1.0; return istr >> p.x >> p.y; }
16.
17.     inline ostream& operator << (ostream& ostr, const point& p){ return ostr << p.x << " " << p.y; }
18.
19.     inline point operator + (const point& a, const point& b){ return point(a.x+b.x, a.y+b.y, a.w+b.w); }
20.
21.     inline point operator - (const point& a, const point& b){ return point(a.x-b.x, a.y-b.y, a.w-b.w); }
22.
23.     inline point operator * (double b, const point& a){ return point(b*a.x, b*a.y, b*a.w); }
24.
25.     inline point operator / (const point& a, double b){ return point(a.x/b, a.y/b, a.w/b); }
26.
27.     inline double operator * (const point& a, const point& b){ return a.x*b.x+a.y*b.y+a.w*b.w; }
28.
29.     /* cross product operator:
30.        if a and b two points then c = a / b is a line crossing this points
31.        if a and b two lines then c = a / b is a point of intersection
32.        if a and b two 3d vectors then c = a / b is a vector a x b
33.     */
34.     inline point operator / (const point& a, const point& b){ return point(a.y*b.w-a.w*b.y, a.w*b.x-a.x*b.w, a.x*b.y-a.y*b.x); }
35.
36.     /* square of length */
37.     inline double length2(const point& a){ return _sqr(a.x) + _sqr(a.y); }
38.
39.     inline double length(const point& a){ return sqrt(length2(a)); }
40.
41.     inline double cross_product_2d(const point& a, const point& b){ return (a/b).w; }
42. }