Skip to main content

three_rs/math/
ray.rs

1//! Port of `three.js/src/math/Ray.js`.
2
3use super::{Box3, Matrix4, Plane, Sphere, Vector3};
4
5/// Port of three.js' `Ray`: an infinite ray from an `origin` along a
6/// `direction`, used by [`Raycaster`](crate::core::Raycaster) for picking.
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub struct Ray {
9    /// The origin of the ray.
10    pub origin: Vector3,
11    /// The (normalized) direction of the ray.
12    pub direction: Vector3,
13}
14
15impl Default for Ray {
16    /// `new Ray()` — origin `(0,0,0)`, direction `(0,0,-1)`.
17    fn default() -> Self {
18        Self {
19            origin: Vector3::new(0.0, 0.0, 0.0),
20            direction: Vector3::new(0.0, 0.0, -1.0),
21        }
22    }
23}
24
25impl Ray {
26    /// `new Ray()`.
27    pub const fn new(origin: Vector3, direction: Vector3) -> Self {
28        Self { origin, direction }
29    }
30
31    /// `Ray.set()`.
32    pub fn set(&mut self, origin: &Vector3, direction: &Vector3) -> &mut Self {
33        self.origin.copy(origin);
34        self.direction.copy(direction);
35        self
36    }
37
38    /// `Ray.copy()`.
39    pub fn copy(&mut self, ray: &Self) -> &mut Self {
40        self.origin.copy(&ray.origin);
41        self.direction.copy(&ray.direction);
42        self
43    }
44
45    /// `Ray.at()`.
46    pub fn at(&self, t: f64) -> Vector3 {
47        let mut target = Vector3::default();
48        target
49            .copy(&self.origin)
50            .add_scaled_vector(&self.direction, t);
51        target
52    }
53
54    /// `Ray.lookAt()`.
55    pub fn look_at(&mut self, v: &Vector3) -> &mut Self {
56        let origin = self.origin;
57        self.direction.copy(v).sub(&origin).normalize();
58        self
59    }
60
61    /// `Ray.recast()`.
62    pub fn recast(&mut self, t: f64) -> &mut Self {
63        let vector = self.at(t);
64        self.origin.copy(&vector);
65        self
66    }
67
68    /// `Ray.closestPointToPoint()`.
69    pub fn closest_point_to_point(&self, point: &Vector3) -> Vector3 {
70        let mut target = Vector3::default();
71        target.sub_vectors(point, &self.origin);
72
73        let direction_distance = target.dot(&self.direction);
74
75        if direction_distance < 0.0 {
76            target.copy(&self.origin);
77            return target;
78        }
79
80        target
81            .copy(&self.origin)
82            .add_scaled_vector(&self.direction, direction_distance);
83        target
84    }
85
86    /// `Ray.distanceToPoint()`.
87    pub fn distance_to_point(&self, point: &Vector3) -> f64 {
88        self.distance_sq_to_point(point).sqrt()
89    }
90
91    /// `Ray.distanceSqToPoint()`.
92    pub fn distance_sq_to_point(&self, point: &Vector3) -> f64 {
93        let mut vector = Vector3::default();
94        let direction_distance = vector.sub_vectors(point, &self.origin).dot(&self.direction);
95
96        // point behind the ray
97
98        if direction_distance < 0.0 {
99            return self.origin.distance_to_squared(point);
100        }
101
102        vector
103            .copy(&self.origin)
104            .add_scaled_vector(&self.direction, direction_distance);
105
106        vector.distance_to_squared(point)
107    }
108
109    /// `Ray.distanceSqToSegment()`.
110    ///
111    /// `optional_point_on_ray` / `optional_point_on_segment` are three.js'
112    /// out-params: when given they receive the closest point on the ray and on
113    /// the segment respectively.
114    pub fn distance_sq_to_segment(
115        &self,
116        v0: &Vector3,
117        v1: &Vector3,
118        optional_point_on_ray: Option<&mut Vector3>,
119        optional_point_on_segment: Option<&mut Vector3>,
120    ) -> f64 {
121        // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
122        // It returns the min distance between the ray and the segment
123        // defined by v0 and v1
124        // It can also set two optional targets :
125        // - The closest point on the ray
126        // - The closest point on the segment
127
128        let mut seg_center = Vector3::default();
129        let mut seg_dir = Vector3::default();
130        let mut diff = Vector3::default();
131
132        seg_center.copy(v0).add(v1).multiply_scalar(0.5);
133        seg_dir.copy(v1).sub(v0).normalize();
134        diff.copy(&self.origin).sub(&seg_center);
135
136        let seg_extent = v0.distance_to(v1) * 0.5;
137        let a01 = -self.direction.dot(&seg_dir);
138        let b0 = diff.dot(&self.direction);
139        let b1 = -diff.dot(&seg_dir);
140        let c = diff.length_sq();
141        let det = (1.0 - a01 * a01).abs();
142        let mut s0;
143        let mut s1;
144        let sqr_dist;
145
146        if det > 0.0 {
147            // The ray and segment are not parallel.
148
149            s0 = a01 * b1 - b0;
150            s1 = a01 * b0 - b1;
151            let ext_det = seg_extent * det;
152
153            if s0 >= 0.0 {
154                if s1 >= -ext_det {
155                    if s1 <= ext_det {
156                        // region 0
157                        // Minimum at interior points of ray and segment.
158
159                        let inv_det = 1.0 / det;
160                        s0 *= inv_det;
161                        s1 *= inv_det;
162                        sqr_dist =
163                            s0 * (s0 + a01 * s1 + 2.0 * b0) + s1 * (a01 * s0 + s1 + 2.0 * b1) + c;
164                    } else {
165                        // region 1
166
167                        s1 = seg_extent;
168                        s0 = (-(a01 * s1 + b0)).max(0.0);
169                        sqr_dist = -s0 * s0 + s1 * (s1 + 2.0 * b1) + c;
170                    }
171                } else {
172                    // region 5
173
174                    s1 = -seg_extent;
175                    s0 = (-(a01 * s1 + b0)).max(0.0);
176                    sqr_dist = -s0 * s0 + s1 * (s1 + 2.0 * b1) + c;
177                }
178            } else if s1 <= -ext_det {
179                // region 4
180
181                s0 = (-(-a01 * seg_extent + b0)).max(0.0);
182                s1 = if s0 > 0.0 {
183                    -seg_extent
184                } else {
185                    (-b1).max(-seg_extent).min(seg_extent)
186                };
187                sqr_dist = -s0 * s0 + s1 * (s1 + 2.0 * b1) + c;
188            } else if s1 <= ext_det {
189                // region 3
190
191                s0 = 0.0;
192                s1 = (-b1).max(-seg_extent).min(seg_extent);
193                sqr_dist = s1 * (s1 + 2.0 * b1) + c;
194            } else {
195                // region 2
196
197                s0 = (-(a01 * seg_extent + b0)).max(0.0);
198                s1 = if s0 > 0.0 {
199                    seg_extent
200                } else {
201                    (-b1).max(-seg_extent).min(seg_extent)
202                };
203                sqr_dist = -s0 * s0 + s1 * (s1 + 2.0 * b1) + c;
204            }
205        } else {
206            // Ray and segment are parallel.
207
208            s1 = if a01 > 0.0 { -seg_extent } else { seg_extent };
209            s0 = (-(a01 * s1 + b0)).max(0.0);
210            sqr_dist = -s0 * s0 + s1 * (s1 + 2.0 * b1) + c;
211        }
212
213        if let Some(point_on_ray) = optional_point_on_ray {
214            point_on_ray
215                .copy(&self.origin)
216                .add_scaled_vector(&self.direction, s0);
217        }
218
219        if let Some(point_on_segment) = optional_point_on_segment {
220            point_on_segment
221                .copy(&seg_center)
222                .add_scaled_vector(&seg_dir, s1);
223        }
224
225        sqr_dist
226    }
227
228    /// `Ray.intersectSphere()`.
229    pub fn intersect_sphere(&self, sphere: &Sphere) -> Option<Vector3> {
230        if sphere.radius < 0.0 {
231            return None; // handle empty spheres, see #31187
232        }
233
234        let mut vector = Vector3::default();
235        vector.sub_vectors(&sphere.center, &self.origin);
236        let tca = vector.dot(&self.direction);
237        let d2 = vector.dot(&vector) - tca * tca;
238        let radius2 = sphere.radius * sphere.radius;
239
240        if d2 > radius2 {
241            return None;
242        }
243
244        let thc = (radius2 - d2).sqrt();
245
246        // t0 = first intersect point - entrance on front of sphere
247        let t0 = tca - thc;
248
249        // t1 = second intersect point - exit point on back of sphere
250        let t1 = tca + thc;
251
252        // test to see if t1 is behind the ray - if so, return null
253        if t1 < 0.0 {
254            return None;
255        }
256
257        // test to see if t0 is behind the ray:
258        // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
259        // in order to always return an intersect point that is in front of the ray.
260        if t0 < 0.0 {
261            return Some(self.at(t1));
262        }
263
264        // else t0 is in front of the ray, so return the first collision point scaled by t0
265        Some(self.at(t0))
266    }
267
268    /// `Ray.intersectsSphere()`.
269    pub fn intersects_sphere(&self, sphere: &Sphere) -> bool {
270        if sphere.radius < 0.0 {
271            return false; // handle empty spheres, see #31187
272        }
273
274        self.distance_sq_to_point(&sphere.center) <= (sphere.radius * sphere.radius)
275    }
276
277    /// `Ray.distanceToPlane()`.
278    pub fn distance_to_plane(&self, plane: &Plane) -> Option<f64> {
279        let denominator = plane.normal.dot(&self.direction);
280
281        if denominator == 0.0 {
282            // line is coplanar, return origin
283            if plane.distance_to_point(&self.origin) == 0.0 {
284                return Some(0.0);
285            }
286
287            // Null is preferable to undefined since undefined means.... it is undefined
288
289            return None;
290        }
291
292        let t = -(self.origin.dot(&plane.normal) + plane.constant) / denominator;
293
294        // Return if the ray never intersects the plane
295
296        if t >= 0.0 {
297            Some(t)
298        } else {
299            None
300        }
301    }
302
303    /// `Ray.intersectPlane()`.
304    pub fn intersect_plane(&self, plane: &Plane) -> Option<Vector3> {
305        let t = self.distance_to_plane(plane)?;
306
307        Some(self.at(t))
308    }
309
310    /// `Ray.intersectsPlane()`.
311    pub fn intersects_plane(&self, plane: &Plane) -> bool {
312        // check if the ray lies on the plane first
313
314        let dist_to_point = plane.distance_to_point(&self.origin);
315
316        if dist_to_point == 0.0 {
317            return true;
318        }
319
320        let denominator = plane.normal.dot(&self.direction);
321
322        if denominator * dist_to_point < 0.0 {
323            return true;
324        }
325
326        // ray origin is behind the plane (and is pointing behind it)
327
328        false
329    }
330
331    /// `Ray.intersectBox()`.
332    pub fn intersect_box(&self, box3: &Box3) -> Option<Vector3> {
333        let mut tmin;
334        let mut tmax;
335
336        let invdirx = 1.0 / self.direction.x;
337        let invdiry = 1.0 / self.direction.y;
338        let invdirz = 1.0 / self.direction.z;
339
340        let origin = &self.origin;
341
342        if invdirx >= 0.0 {
343            tmin = (box3.min.x - origin.x) * invdirx;
344            tmax = (box3.max.x - origin.x) * invdirx;
345        } else {
346            tmin = (box3.max.x - origin.x) * invdirx;
347            tmax = (box3.min.x - origin.x) * invdirx;
348        }
349
350        let (tymin, tymax) = if invdiry >= 0.0 {
351            (
352                (box3.min.y - origin.y) * invdiry,
353                (box3.max.y - origin.y) * invdiry,
354            )
355        } else {
356            (
357                (box3.max.y - origin.y) * invdiry,
358                (box3.min.y - origin.y) * invdiry,
359            )
360        };
361
362        if (tmin > tymax) || (tymin > tmax) {
363            return None;
364        }
365
366        if tymin > tmin || tmin.is_nan() {
367            tmin = tymin;
368        }
369
370        if tymax < tmax || tmax.is_nan() {
371            tmax = tymax;
372        }
373
374        let (tzmin, tzmax) = if invdirz >= 0.0 {
375            (
376                (box3.min.z - origin.z) * invdirz,
377                (box3.max.z - origin.z) * invdirz,
378            )
379        } else {
380            (
381                (box3.max.z - origin.z) * invdirz,
382                (box3.min.z - origin.z) * invdirz,
383            )
384        };
385
386        if (tmin > tzmax) || (tzmin > tmax) {
387            return None;
388        }
389
390        if tzmin > tmin || tmin.is_nan() {
391            tmin = tzmin;
392        }
393
394        if tzmax < tmax || tmax.is_nan() {
395            tmax = tzmax;
396        }
397
398        //return point closest to the ray (positive side)
399
400        if tmax < 0.0 {
401            return None;
402        }
403
404        Some(self.at(if tmin >= 0.0 { tmin } else { tmax }))
405    }
406
407    /// `Ray.intersectsBox()`.
408    pub fn intersects_box(&self, box3: &Box3) -> bool {
409        self.intersect_box(box3).is_some()
410    }
411
412    /// `Ray.intersectTriangle()`.
413    pub fn intersect_triangle(
414        &self,
415        a: &Vector3,
416        b: &Vector3,
417        c: &Vector3,
418        backface_culling: bool,
419    ) -> Option<Vector3> {
420        // Watertight ray/triangle intersection. Reference: Woop, Benthin, Wald,
421        // "Watertight Ray/Triangle Intersection", JCGT vol. 2 no. 1 (2013), Appendix A.
422        // https://jcgt.org/published/0002/01/05/
423
424        let origin = &self.origin;
425        let direction = &self.direction;
426
427        let dx = direction.x;
428        let dy = direction.y;
429        let dz = direction.z;
430
431        // triangle vertices relative to the ray origin
432
433        let (aox, aoy, aoz) = (a.x - origin.x, a.y - origin.y, a.z - origin.z);
434        // `box` is a reserved word in Rust; three.js' `box`/`boy`/`boz` become `box_`/`boy`/`boz`.
435        let (box_, boy, boz) = (b.x - origin.x, b.y - origin.y, b.z - origin.z);
436        let (cox, coy, coz) = (c.x - origin.x, c.y - origin.y, c.z - origin.z);
437
438        // Use the dimension where the ray direction is maximal as the projection
439        // axis (kz) and read every component already permuted into (kx, ky, kz).
440        // kx and ky are swapped when the direction's kz component is negative, to
441        // preserve the winding order of triangles.
442
443        let (adx, ady, adz) = (dx.abs(), dy.abs(), dz.abs());
444
445        let dkx;
446        let dky;
447        let dkz;
448        let akx;
449        let aky;
450        let akz;
451        let bkx;
452        let bky;
453        let bkz;
454        let ckx;
455        let cky;
456        let ckz;
457
458        if adx >= ady && adx >= adz {
459            dkz = dx;
460            akz = aox;
461            bkz = box_;
462            ckz = cox;
463
464            if dx >= 0.0 {
465                dkx = dy;
466                dky = dz;
467                akx = aoy;
468                aky = aoz;
469                bkx = boy;
470                bky = boz;
471                ckx = coy;
472                cky = coz;
473            } else {
474                dkx = dz;
475                dky = dy;
476                akx = aoz;
477                aky = aoy;
478                bkx = boz;
479                bky = boy;
480                ckx = coz;
481                cky = coy;
482            }
483        } else if ady >= adz {
484            dkz = dy;
485            akz = aoy;
486            bkz = boy;
487            ckz = coy;
488
489            if dy >= 0.0 {
490                dkx = dz;
491                dky = dx;
492                akx = aoz;
493                aky = aox;
494                bkx = boz;
495                bky = box_;
496                ckx = coz;
497                cky = cox;
498            } else {
499                dkx = dx;
500                dky = dz;
501                akx = aox;
502                aky = aoz;
503                bkx = box_;
504                bky = boz;
505                ckx = cox;
506                cky = coz;
507            }
508        } else {
509            dkz = dz;
510            akz = aoz;
511            bkz = boz;
512            ckz = coz;
513
514            if dz >= 0.0 {
515                dkx = dx;
516                dky = dy;
517                akx = aox;
518                aky = aoy;
519                bkx = box_;
520                bky = boy;
521                ckx = cox;
522                cky = coy;
523            } else {
524                dkx = dy;
525                dky = dx;
526                akx = aoy;
527                aky = aox;
528                bkx = boy;
529                bky = box_;
530                ckx = coy;
531                cky = cox;
532            }
533        }
534
535        // a zero direction has no maximal axis and cannot intersect
536
537        if dkz == 0.0 {
538            return None;
539        }
540
541        // shear constants that align the ray with the +kz axis
542
543        let sx = dkx / dkz;
544        let sy = dky / dkz;
545        let sz = 1.0 / dkz;
546
547        // sheared and scaled vertices
548
549        let (ax, ay) = (akx - sx * akz, aky - sy * akz);
550        let (bx, by) = (bkx - sx * bkz, bky - sy * bkz);
551        let (cx, cy) = (ckx - sx * ckz, cky - sy * ckz);
552
553        // scaled barycentric coordinates (signed edge functions); the shear makes a
554        // shared edge evaluate identically for both adjacent triangles, so the ray
555        // can never fall between them
556
557        let u = cx * by - cy * bx;
558        let v = ax * cy - ay * cx;
559        let w = bx * ay - by * ax;
560
561        if backface_culling {
562            if u < 0.0 || v < 0.0 || w < 0.0 {
563                return None;
564            }
565        } else if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
566            return None;
567        }
568
569        let det = u + v + w;
570
571        // ray is co-planar with the triangle
572
573        if det == 0.0 {
574            return None;
575        }
576
577        // scaled hit distance; t = tScaled / det must lie in front of the origin
578
579        let t_scaled = sz * (u * akz + v * bkz + w * ckz);
580
581        if if det > 0.0 {
582            t_scaled < 0.0
583        } else {
584            t_scaled > 0.0
585        } {
586            return None;
587        }
588
589        Some(self.at(t_scaled / det))
590    }
591
592    /// `Ray.applyMatrix4()`.
593    pub fn apply_matrix4(&mut self, matrix4: &Matrix4) -> &mut Self {
594        self.origin.apply_matrix4(matrix4);
595        self.direction.transform_direction(matrix4);
596        self
597    }
598
599    /// `Ray.equals()`.
600    pub fn equals(&self, ray: &Self) -> bool {
601        ray.origin.equals(&self.origin) && ray.direction.equals(&self.direction)
602    }
603}