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
use na::{self, Real, Vector3};
use query::{Ray, RayCast, RayIntersection};
use shape::Triangle;
use math::{Isometry, Point};
impl<N: Real> RayCast<N> for Triangle<N> {
#[inline]
fn toi_and_normal_with_ray(
&self,
m: &Isometry<N>,
ray: &Ray<N>,
_: bool,
) -> Option<RayIntersection<N>> {
let ls_ray = ray.inverse_transform_by(m);
let res = triangle_ray_intersection(self.a(), self.b(), self.c(), &ls_ray);
res.map(|(mut r, _)| {
r.normal = m * r.normal;
r
})
}
}
pub fn triangle_ray_intersection<N: Real>(
a: &Point<N>,
b: &Point<N>,
c: &Point<N>,
ray: &Ray<N>,
) -> Option<(RayIntersection<N>, Vector3<N>)> {
let ab = *b - *a;
let ac = *c - *a;
let n = ab.cross(&ac);
let d = na::dot(&n, &ray.dir);
if d.is_zero() {
return None;
}
let ap = ray.origin - *a;
let t = na::dot(&ap, &n);
if (t < na::zero() && d < na::zero()) || (t > na::zero() && d > na::zero()) {
return None;
}
let d = d.abs();
let e = -ray.dir.cross(&ap);
let mut v;
let mut w;
let toi;
let normal;
if t < na::zero() {
v = -na::dot(&ac, &e);
if v < na::zero() || v > d {
return None;
}
w = na::dot(&ab, &e);
if w < na::zero() || v + w > d {
return None;
}
let invd = na::one::<N>() / d;
toi = -t * invd;
normal = -na::normalize(&n);
v = v * invd;
w = w * invd;
} else {
v = na::dot(&ac, &e);
if v < na::zero() || v > d {
return None;
}
w = -na::dot(&ab, &e);
if w < na::zero() || v + w > d {
return None;
}
let invd = na::one::<N>() / d;
toi = t * invd;
normal = na::normalize(&n);
v = v * invd;
w = w * invd;
}
Some((
RayIntersection::new(toi, normal),
Vector3::new(-v - w + na::one(), v, w),
))
}