-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriangle.cpp
More file actions
59 lines (44 loc) · 1.28 KB
/
triangle.cpp
File metadata and controls
59 lines (44 loc) · 1.28 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
#include "triangle.hpp"
#include <cmath>
#include <iostream>
Triangle::Triangle(const Point &p1, const Point &p2, const Point &p3,
const TextureMaterial &texture_)
: points{{p1, p2, p3}}
{
texture = &texture_;
}
// TODO: Improve speed with an other algorithm
std::optional<Point> Triangle::get_intersection(const Ray &r) const
{
auto v1 = points[1] - points[0];
auto v2 = points[2] - points[0];
auto n = cross_product(v1, v2);
auto det = -(r.dir * n);
if (det < epsilon && det > -epsilon)
return std::nullopt;
auto dist = r.origine - points[0];
auto DAO = cross_product(dist, r.dir);
auto u = v2 * DAO / det;
auto v = -(v1 * DAO) / det;
auto t = dist * n / det;
if (t < epsilon || u < epsilon || v < epsilon || (u + v) > 1)
return std::nullopt;
return r.origine + r.dir * t;
}
Vector Triangle::get_normal(const Point &p) const
{
auto v1 = points[0] - points[1];
auto v2 = points[0] - points[2];
return cross_product(v1, v2).as_unit();
}
Vector Triangle::get_facing_normal(const Point &p, const Ray &ray)
{
auto n = get_normal(p);
if (n * ray.dir < 0)
return -n;
return n;
}
Texture Triangle::get_texture(const Point &p) const
{
return texture->get_texture(p);
}