1 | #ifndef _Plane3_H__ |
---|
2 | #define _Plane3_H__ |
---|
3 | |
---|
4 | #include "Vector3.h" |
---|
5 | |
---|
6 | |
---|
7 | /** 3D Plane */ |
---|
8 | class Plane3 { |
---|
9 | public: |
---|
10 | |
---|
11 | Vector3 mNormal; |
---|
12 | float mD; |
---|
13 | |
---|
14 | Plane3() {} |
---|
15 | |
---|
16 | Plane3(const Vector3 &a, |
---|
17 | const Vector3 &b, |
---|
18 | const Vector3 &c |
---|
19 | ) { |
---|
20 | Vector3 v1=a-b, v2=c-b; |
---|
21 | mNormal = Normalize(CrossProd(v2,v1)); |
---|
22 | mD = -DotProd(b, mNormal); |
---|
23 | } |
---|
24 | |
---|
25 | Plane3(const Vector3 &normal, |
---|
26 | const Vector3 &point |
---|
27 | ):mNormal(normal) |
---|
28 | { |
---|
29 | mD = -DotProd(normal, point); |
---|
30 | } |
---|
31 | |
---|
32 | // relation of objects with the plane |
---|
33 | enum {BACK_SIDE, FRONT_SIDE, SPLIT, COINCIDENT}; |
---|
34 | |
---|
35 | float Distance(const Vector3 &v) const { |
---|
36 | return DotProd(v, mNormal) + mD; |
---|
37 | } |
---|
38 | |
---|
39 | int Side(const Vector3 &v, const float threshold = 1e-6) const { |
---|
40 | return signum(Distance(v), threshold); |
---|
41 | } |
---|
42 | |
---|
43 | Vector3 FindIntersection(const Vector3 &a, |
---|
44 | const Vector3 &b, |
---|
45 | float *t = NULL, |
---|
46 | bool *coplanar = NULL |
---|
47 | ) const |
---|
48 | { |
---|
49 | const Vector3 v = b - a; // line from A to B |
---|
50 | float dv = DotProd(v, mNormal); |
---|
51 | |
---|
52 | if (signum(dv) == 0) |
---|
53 | { |
---|
54 | if (coplanar) (*coplanar) = true; |
---|
55 | if (t) (*t) = 1; |
---|
56 | return a; |
---|
57 | } |
---|
58 | |
---|
59 | float u = - Distance(a) / dv; // TODO: could be done more efficiently |
---|
60 | |
---|
61 | if (coplanar) (*coplanar) = false; |
---|
62 | if (t) (*t) = u; |
---|
63 | |
---|
64 | //Debug << "t: " << u << ", b - a: " << v << ", norm: " << mNormal << ", dist(a): " << - Distance(a) << ", dv: " << dv << endl; |
---|
65 | //return a - Distance(a) * b / dv + Distance(a) * a / dv; // NOTE: gives better precision than calclulating a + u * v |
---|
66 | return a + u * v; |
---|
67 | } |
---|
68 | |
---|
69 | friend bool |
---|
70 | PlaneIntersection(const Plane3 &a, const Plane3 &b, const Plane3 &c, Vector3 &result); |
---|
71 | |
---|
72 | friend ostream &operator<<(ostream &s, const Plane3 p) { |
---|
73 | s<<p.mNormal<<" "<<p.mD; |
---|
74 | return s; |
---|
75 | } |
---|
76 | |
---|
77 | |
---|
78 | }; |
---|
79 | |
---|
80 | |
---|
81 | |
---|
82 | |
---|
83 | #endif |
---|