-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriangle.cpp
More file actions
57 lines (40 loc) · 1.54 KB
/
Copy pathtriangle.cpp
File metadata and controls
57 lines (40 loc) · 1.54 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
#include "header/triangle.h"
triangle::triangle(const point3& a, const point3& b, const point3& c, const rayTracingMaterial& mat)
: object(mat){
vertices[0] = a;
vertices[1] = b;
vertices[2] = c;
normal = (b - a).cross(c - a).unit_vector();
}
// In this function we assume that the triangle coordinate are stored as ABC, and the hit point is D
hitInfo triangle::hit(const ray& r) const {
hitInfo hit;
double divisor = normal.unit_vector().dot(r.direction.unit_vector());
if (divisor != 0) {
double d = normal.dot(vertices[0]);
double dividend = d - normal.dot(r.origin);
double distance = dividend/divisor;
if (distance > 0) {
point3 hitPlan = r.at(distance);
if (isPointInTriangle(hitPlan)) {
hit.didHit = true;
hit.distance = distance;
hit.hitPoint = hitPlan;
hit.normal = normal.unit_vector();
}
}
}
return hit;
}
double triangle::triangleArea(const point3& a, const point3& b, const point3& c) {
point3 AB = b - a;
point3 AC = c - a;
return AB.cross(AC).length() / 2;
}
bool triangle::isPointInTriangle(const point3& point) const {
double totalArea = triangleArea(vertices[0], vertices[1], vertices[2]);
double area1 = triangleArea(point, vertices[0], vertices[1]);
double area2 = triangleArea(point, vertices[1], vertices[2]);
double area3 = triangleArea(point, vertices[2], vertices[0]);
return fabs(totalArea - (area1 + area2 + area3)) < 1e-6;
}