-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriangle.cpp
More file actions
125 lines (107 loc) · 2.39 KB
/
triangle.cpp
File metadata and controls
125 lines (107 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include "triangle.h"
triangle::triangle(const v3 &n, const v3 &p0, const v3 &p1, const v3 &p2)
{
this->normal = n;
p[0] = p0;
p[1] = p1;
p[2] = p2;
}
triangle::~triangle()
{
}
triangle &triangle::operator-=(const v3 &p)
{
this->p[0] -= p;
this->p[1] -= p;
this->p[2] -= p;
return *this;
}
void triangle::setNormal(const v3 &n)
{
this->normal = n;
}
v3 &triangle::getNormal()
{
return this->normal;
}
// void triangle::transform(const glm::mat4 & mat)
// {
// p[0].transform(mat);
// p[1].transform(mat);
// p[2].tranform(mat);
// }
int triangle::intersectPlane(const Plane &pl, lineSegment &seg) const
{
// 0 plane intersect the triangle
// 1 all triangle points on front side of the plane
//-1 all triangle points on the back of the plane
//-2 error
size_t cntFront = 0, cntBack = 0, onplane = 0;
for (size_t i = 0; i < 3; ++i)
{
double distance = pl.distanceToPoint(this->p[0]);
if (distance < 0)
++cntBack;
else if (distance > 0)
++cntFront;
else
++onplane;
}
if (cntFront == 3)
return 1;
if (cntBack == 3)
return -1;
size_t lines[] = {0, 1, 1, 2, 2, 0};
std::vector<v3> intersectPoints;
for (size_t i = 0; i < 3; ++i)
{
const v3 &a = this->p[lines[i * 2]];
const v3 &b = this->p[lines[i * 2 + 1]];
const float da = pl.distanceToPoint(a);
const float db = pl.distanceToPoint(b);
if (da * db < 0)
{
const float s = da / (da - db); //intersection factor
v3 bMinusa = b - a;
intersectPoints.push_back(a + bMinusa * s);
}
else if (da == 0) // plane falls exacalty on one of three Triangle
{
if (intersectPoints.size() < 2)
intersectPoints.push_back(a);
}
else if (db == 0)
{
if (intersectPoints.size() < 2)
intersectPoints.push_back(b);
}
}
if (intersectPoints.size() == 2) // output the intersecting line segment object
{
seg.setVertex(intersectPoints[0], 0);
seg.setVertex(intersectPoints[1], 1);
return 0;
}
return -2;
}
void triangle::getDerived()
{
v3 tp = p[1] - p[0];
tp = tp.cross(p[2] - p[1]);
U2 = tp / tp.length(); // U2
tp = p[1] - p[0];
U0 = tp / tp.length(); // U0
U1 = U2.cross(U0); // U1
Q0 = (0, 0, 0); //Q0
double L = tp.length();
Q1 = (L, 0, 0); //Q1
double A = U0.dot(p[2] - p[0]);
double B = U1.dot(p[2] - p[0]);
Q2 = (A, B, 0); //Q2
E0 = Q1 - Q0;
E1 = Q2 - Q1;
E2 = Q0 - Q2;
N0 = (0, -1, 0);
N1 = (B, L - A) / sqrt(B * B + (L - A) * (L - A));
N2 = (-B, A) / sqrt(B * B + A * A);
}