Skip to main content

rs_math3d/
primitives.rs

1// Copyright 2020-Present (c) Raja Lehtihet & Wael El Oraiby
2//
3// Redistribution and use in source and binary forms, with or without
4// modification, are permitted provided that the following conditions are met:
5//
6// 1. Redistributions of source code must retain the above copyright notice,
7// this list of conditions and the following disclaimer.
8//
9// 2. Redistributions in binary form must reproduce the above copyright notice,
10// this list of conditions and the following disclaimer in the documentation
11// and/or other materials provided with the distribution.
12//
13// 3. Neither the name of the copyright holder nor the names of its contributors
14// may be used to endorse or promote products derived from this software without
15// specific prior written permission.
16//
17// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27// POSSIBILITY OF SUCH DAMAGE.
28
29//! Geometric primitives for 3D graphics and collision detection.
30//!
31//! This module provides common geometric shapes and primitives used in
32//! 3D graphics, physics simulations, and collision detection systems.
33//!
34//! Discrete storage types such as rectangles and boxes work with integer scalars.
35//! Metric and analytic primitives such as lines, rays, planes, spheres, and
36//! triangles are intended for floating-point use.
37//!
38//! Constructors that normalize directions or normals provide checked `try_`
39//! variants. The unchecked variants assume non-degenerate input and panic when
40//! that precondition is violated.
41//!
42//! # Examples
43//!
44//! ```
45//! use rs_math3d::primitives::{Ray, Plane, Tri3};
46//! use rs_math3d::vector::Vector3;
47//! use rs_math3d::EPS_F32;
48//!
49//! // Create a ray from origin pointing along +X axis
50//! let ray = Ray::new(
51//!     &Vector3::new(0.0f32, 0.0, 0.0),
52//!     &Vector3::new(1.0, 0.0, 0.0),
53//!     EPS_F32,
54//! ).unwrap();
55//!
56//! // Create a plane at z=5 facing down
57//! let plane = Plane::new(
58//!     &Vector3::new(0.0f32, 0.0, -1.0),
59//!     &Vector3::new(0.0, 0.0, 5.0)
60//! );
61//!
62//! let checked = Plane::try_new(
63//!     &Vector3::new(0.0f32, 0.0, -1.0),
64//!     &Vector3::new(0.0, 0.0, 5.0),
65//!     EPS_F32,
66//! ).expect("plane normal should be valid");
67//! assert_eq!(plane.constant(), checked.constant());
68//! ```
69
70use crate::scalar::*;
71use crate::vector::*;
72use num_traits::{One, Zero};
73
74/// A 2D dimension with width and height.
75#[repr(C)]
76#[derive(Debug, Clone, Copy, Default)]
77pub struct Dimension<T: Scalar> {
78    /// Width component.
79    pub width: T,
80    /// Height component.
81    pub height: T,
82}
83
84impl<T: Scalar> Dimension<T> {
85    /// Creates a new dimension with the specified width and height.
86    pub fn new(width: T, height: T) -> Self {
87        Self { width, height }
88    }
89}
90
91/// A 2D axis-aligned rectangle.
92///
93/// Defined by its top-left corner position (x, y) and dimensions (width, height).
94#[repr(C)]
95#[derive(Debug, Clone, Copy, Default)]
96pub struct Rect<T: Scalar> {
97    /// X coordinate of the top-left corner.
98    pub x: T,
99    /// Y coordinate of the top-left corner.
100    pub y: T,
101    /// Rectangle width.
102    pub width: T,
103    /// Rectangle height.
104    pub height: T,
105}
106
107impl<T: Scalar> Rect<T> {
108    /// Creates a new rectangle from position and dimensions.
109    pub fn new(x: T, y: T, width: T, height: T) -> Self {
110        Self {
111            x,
112            y,
113            width,
114            height,
115        }
116    }
117    /// Creates a rectangle from two corner points.
118    ///
119    /// The points don't need to be min/max - they will be sorted.
120    pub fn from(min_vec: &Vector2<T>, max_vec: &Vector2<T>) -> Self {
121        let min_x = T::min(min_vec.x, max_vec.x);
122        let min_y = T::min(min_vec.y, max_vec.y);
123        let max_x = T::max(min_vec.x, max_vec.x);
124        let max_y = T::max(min_vec.y, max_vec.y);
125        Self {
126            x: min_x,
127            y: min_y,
128            width: max_x - min_x,
129            height: max_y - min_y,
130        }
131    }
132
133    /// Returns the minimum corner (top-left) of the rectangle.
134    pub fn min(&self) -> Vector2<T> {
135        Vector2::new(self.x, self.y)
136    }
137    /// Returns the maximum corner (bottom-right) of the rectangle.
138    pub fn max(&self) -> Vector2<T> {
139        Vector2::new(self.x + self.width, self.y + self.height)
140    }
141    /// Computes the intersection of two rectangles.
142    ///
143    /// Returns `None` if the rectangles don't overlap.
144    pub fn intersect(&self, other: &Self) -> Option<Self> {
145        let smx = self.max();
146        let smn = self.min();
147        let omx = other.max();
148        let omn = other.min();
149
150        if smx.x < omn.x || smx.y < omn.y || smn.x > omx.x || smn.y > omx.y {
151            return None;
152        }
153
154        let min_vec = Vector2::max(&self.min(), &other.min());
155        let max_vec = Vector2::min(&self.max(), &other.max());
156        Some(Self::from(&min_vec, &max_vec))
157    }
158
159    /// Checks if a point is inside the rectangle.
160    pub fn contains(&self, p: &Vector2<T>) -> bool {
161        p.x >= self.x && p.y >= self.y && p.x <= self.x + self.width && p.y <= self.y + self.height
162    }
163}
164
165/// A 3D axis-aligned bounding box (AABB).
166///
167/// Defined by its minimum and maximum corners.
168#[repr(C)]
169#[derive(Debug, Clone, Copy, Default)]
170pub struct Box3<T: Scalar> {
171    /// Minimum corner.
172    pub min: Vector3<T>,
173    /// Maximum corner.
174    pub max: Vector3<T>,
175}
176
177impl<T: Scalar> Box3<T> {
178    /// Creates a new box from two corner points.
179    ///
180    /// The points are automatically sorted to find min/max.
181    pub fn new(v0: &Vector3<T>, v1: &Vector3<T>) -> Self {
182        Self {
183            min: Vector3::min(v0, v1),
184            max: Vector3::max(v0, v1),
185        }
186    }
187    /// Checks if two boxes overlap.
188    pub fn overlap(&self, other: &Self) -> bool {
189        if self.max.x < other.min.x {
190            return false;
191        }
192        if self.max.y < other.min.y {
193            return false;
194        }
195        if self.max.z < other.min.z {
196            return false;
197        }
198
199        if self.min.x > other.max.x {
200            return false;
201        }
202        if self.min.y > other.max.y {
203            return false;
204        }
205        if self.min.z > other.max.z {
206            return false;
207        }
208        true
209    }
210
211    /// Expands the box to include a point.
212    pub fn add(&self, p: &Vector3<T>) -> Self {
213        Self {
214            min: Vector3::min(p, &self.min),
215            max: Vector3::max(p, &self.max),
216        }
217    }
218}
219
220impl<T: FloatScalar> Box3<T> {
221    /// Returns the center point of the box.
222    pub fn center(&self) -> Vector3<T> {
223        (self.max + self.min) * T::half()
224    }
225    /// Returns the half-extents of the box from center to max.
226    pub fn extent(&self) -> Vector3<T> {
227        self.max - self.center()
228    }
229
230    /// Subdivides the box into 8 octants.
231    ///
232    /// Returns an array of 8 boxes representing the octree subdivision.
233    pub fn subdivide(&self) -> [Self; 8] {
234        let cube_table: [Vector3<i32>; 8] = [
235            Vector3::new(0, 1, 0),
236            Vector3::new(1, 1, 0),
237            Vector3::new(1, 1, 1),
238            Vector3::new(0, 1, 1),
239            Vector3::new(0, 0, 0),
240            Vector3::new(1, 0, 0),
241            Vector3::new(1, 0, 1),
242            Vector3::new(0, 0, 1),
243        ];
244
245        let ps: [Vector3<T>; 2] = [self.min, self.max];
246        let mut vs = [Vector3::zero(); 8];
247        for i in 0..8 {
248            vs[i] = Vector3::new(
249                ps[cube_table[i].x as usize].x,
250                ps[cube_table[i].y as usize].y,
251                ps[cube_table[i].z as usize].z,
252            );
253        }
254
255        let c = self.center();
256        let mut out = [Box3 {
257            min: Vector3::zero(),
258            max: Vector3::zero(),
259        }; 8];
260        for i in 0..8 {
261            out[i] = Self::new(&Vector3::min(&c, &vs[i]), &Vector3::max(&c, &vs[i]));
262        }
263        out
264    }
265}
266
267/// An infinite line in 2D or 3D space.
268///
269/// Defined by a point on the line and a direction vector.
270#[repr(C)]
271#[derive(Debug, Clone, Copy, Default)]
272pub struct Line<T: Scalar, V: Vector<T>> {
273    /// Point on the line.
274    pub p: V,
275    /// Direction of the line.
276    pub d: V,
277    t: core::marker::PhantomData<T>,
278}
279
280impl<T: FloatScalar, V: FloatVector<T>> Line<T, V> {
281    /// Creates a new line from a point and direction.
282    ///
283    /// Returns `None` if the direction is too small.
284    pub fn new(p: &V, d: &V, epsilon: T) -> Option<Self> {
285        let d_ss = V::dot(d, d);
286        if d_ss <= epsilon * epsilon {
287            return None;
288        }
289        Some(Self {
290            p: *p,
291            d: *d,
292            t: core::marker::PhantomData,
293        })
294    }
295    /// Creates a line from two points.
296    ///
297    /// The line passes through both points, with direction from s to e.
298    ///
299    /// Returns `None` if the points are too close.
300    pub fn from_start_end(s: &V, e: &V, epsilon: T) -> Option<Self> {
301        let dir = *e - *s;
302        Self::new(s, &dir, epsilon)
303    }
304    /// Finds the closest point on the line to a given point.
305    ///
306    /// Returns:
307    /// - `t`: Parameter value where the closest point occurs
308    /// - Point: The closest point on the line
309    ///
310    /// Returns `None` if the line direction is too small.
311    pub fn closest_point_on_line(&self, p: &V, epsilon: T) -> Option<(T, V)> {
312        let p_dir = *p - self.p;
313
314        let d_sp = V::dot(&self.d, &p_dir);
315        let d_ss = V::dot(&self.d, &self.d);
316
317        if d_ss <= epsilon * epsilon {
318            return None;
319        }
320
321        let t = d_sp / d_ss;
322
323        Some((t, self.p + self.d * t))
324    }
325
326    /// Returns a line with normalized direction vector.
327    ///
328    /// Returns `None` if the direction is too small.
329    pub fn normalize(&self, epsilon: T) -> Option<Self> {
330        let d_ss = V::dot(&self.d, &self.d);
331        if d_ss <= epsilon * epsilon {
332            return None;
333        }
334        let inv_len = <T as One>::one() / d_ss.tsqrt();
335        Some(Self {
336            p: self.p,
337            d: self.d * inv_len,
338            t: core::marker::PhantomData,
339        })
340    }
341}
342
343/// Finds the shortest segment connecting two 3D lines.
344///
345/// Returns `None` if the lines are parallel (within epsilon tolerance).
346pub fn shortest_segment3d_between_lines3d<T: FloatScalar>(
347    line0: &Line<T, Vector3<T>>,
348    line1: &Line<T, Vector3<T>>,
349    epsilon: T,
350) -> Option<Segment<T, Vector3<T>>> {
351    let s0 = line0.p;
352    let s1 = line1.p;
353
354    let d1 = line1.d;
355    let d0 = line0.d;
356
357    let eps_sq = epsilon * epsilon;
358    let d0_len_sq = Vector3::dot(&d0, &d0);
359    let d1_len_sq = Vector3::dot(&d1, &d1);
360    if d0_len_sq <= eps_sq || d1_len_sq <= eps_sq {
361        return None;
362    }
363
364    let cross = Vector3::cross(&d1, &d0);
365    let cross_len_sq = Vector3::dot(&cross, &cross);
366    if cross_len_sq <= eps_sq {
367        return None;
368    }
369
370    let normal = Vector3::normalize(&cross);
371    let n0 = Vector3::normalize(&Vector3::cross(&normal, &d0));
372    let n1 = Vector3::normalize(&Vector3::cross(&normal, &d1));
373
374    let plane0 = Plane::try_new(&n0, &s0, epsilon)?;
375    let plane1 = Plane::try_new(&n1, &s1, epsilon)?;
376
377    let p1 = plane0.intersect_line(line1, epsilon);
378    let p0 = plane1.intersect_line(line0, epsilon);
379
380    match (p0, p1) {
381        (Some((_, s)), Some((_, e))) => Some(Segment::new(&s, &e)),
382        _ => None,
383    }
384}
385
386/// A line segment with defined start and end points.
387#[repr(C)]
388#[derive(Clone, Copy, Default)]
389pub struct Segment<T: Scalar, V: Vector<T>> {
390    /// Start point.
391    pub s: V,
392    /// End point.
393    pub e: V,
394    t: core::marker::PhantomData<T>,
395}
396
397impl<T: Scalar, V: Vector<T>> Segment<T, V> {
398    /// Creates a new segment from start to end point.
399    pub fn new(s: &V, e: &V) -> Self {
400        Self {
401            s: *s,
402            e: *e,
403            t: core::marker::PhantomData,
404        }
405    }
406}
407
408impl<T: FloatScalar, V: FloatVector<T>> Segment<T, V> {
409    /// Finds the closest point on the segment to a given point.
410    ///
411    /// Returns:
412    /// - `t`: Parameter value \[0,1\] where 0=start, 1=end
413    /// - Point: The closest point on the segment
414    ///
415    /// Returns `None` if the segment is too small.
416    pub fn closest_point_on_segment(&self, p: &V, epsilon: T) -> Option<(T, V)> {
417        let dir = self.e - self.s;
418        let p_dir = *p - self.s;
419
420        let d_sp = V::dot(&dir, &p_dir);
421        let d_ss = V::dot(&dir, &dir);
422
423        if d_ss <= epsilon * epsilon {
424            return None;
425        }
426
427        if d_sp < <T as Zero>::zero() {
428            return Some((<T as Zero>::zero(), self.s));
429        } else if d_sp > d_ss {
430            return Some((<T as One>::one(), self.e));
431        }
432
433        let t = d_sp / d_ss;
434
435        Some((t, self.s + dir * t))
436    }
437    /// Computes the distance from a point to the segment.
438    ///
439    /// Returns `None` if the segment is too small.
440    pub fn distance(&self, p: &V, epsilon: T) -> Option<T> {
441        self.closest_point_on_segment(p, epsilon)
442            .map(|(_, p_on_seg)| V::length(&(p_on_seg - *p)))
443    }
444}
445
446/// A ray with an origin and direction.
447///
448/// Commonly used for ray casting and intersection tests.
449#[repr(C)]
450#[derive(Clone, Copy, Default)]
451pub struct Ray<T: Scalar, V: Vector<T>> {
452    /// Ray origin.
453    pub start: V,
454    /// Ray direction (typically normalized).
455    pub direction: V,
456    t: core::marker::PhantomData<T>,
457}
458
459impl<T: FloatScalar, V: FloatVector<T>> Ray<T, V> {
460    /// Creates a new ray with normalized direction.
461    ///
462    /// Returns `None` if the direction is too small.
463    pub fn new(start: &V, direction: &V, epsilon: T) -> Option<Self> {
464        let d_ss = V::dot(direction, direction);
465        if d_ss <= epsilon * epsilon {
466            return None;
467        }
468        let inv_len = <T as One>::one() / d_ss.tsqrt();
469        Some(Self {
470            start: *start,
471            direction: *direction * inv_len,
472            t: core::marker::PhantomData,
473        })
474    }
475}
476
477impl<T: FloatScalar> Ray<T, Vector3<T>> {
478    /// Computes ray-plane intersection.
479    ///
480    /// Returns the intersection point, or `None` if the ray doesn't hit the plane
481    /// (parallel or pointing away).
482    ///
483    /// Returns `None` if the ray is parallel to the plane within `epsilon`.
484    pub fn intersect_plane(&self, p: &Plane<T>, epsilon: T) -> Option<Vector3<T>> {
485        let n = p.normal();
486        let denom = Vector3::dot(&n, &self.direction);
487        if denom.tabs() <= epsilon {
488            return None;
489        }
490        let t: T = -(p.d + Vector3::dot(&n, &self.start)) / denom;
491        if t < <T as Zero>::zero() {
492            None
493        } else {
494            Some(self.direction * t + self.start)
495        }
496    }
497}
498
499////////////////////////////////////////////////////////////////////////////////
500/// A sphere defined by center and radius.
501////////////////////////////////////////////////////////////////////////////////
502#[repr(C)]
503#[derive(Clone, Copy, Default)]
504pub struct Sphere3<T: FloatScalar> {
505    /// Sphere center.
506    pub center: Vector3<T>,
507    /// Sphere radius.
508    pub radius: T,
509}
510
511impl<T: FloatScalar> Sphere3<T> {
512    /// Creates a sphere from center and radius.
513    pub fn new(center: Vector3<T>, radius: T) -> Self {
514        Self { center, radius }
515    }
516}
517
518////////////////////////////////////////////////////////////////////////////////
519/// A triangle defined by three vertices.
520////////////////////////////////////////////////////////////////////////////////
521#[repr(C)]
522#[derive(Clone, Copy, Default)]
523pub struct Tri3<T: FloatScalar> {
524    vertices: [Vector3<T>; 3],
525}
526
527impl<T: FloatScalar> Tri3<T> {
528    /// Creates a triangle from three vertices.
529    pub fn new(vertices: [Vector3<T>; 3]) -> Self {
530        Self { vertices }
531    }
532    /// Returns the triangle vertices.
533    pub fn vertices(&self) -> &[Vector3<T>; 3] {
534        &self.vertices
535    }
536
537    /// Computes barycentric coordinates of a point in the triangle plane.
538    pub fn barycentric_coordinates(&self, pt: &Vector3<T>) -> Vector3<T> {
539        let v0 = self.vertices[0];
540        let v1 = self.vertices[1];
541        let v2 = self.vertices[2];
542        let e0 = v1 - v0;
543        let e1 = v2 - v0;
544        let vp = *pt - v0;
545
546        let d00 = Vector3::dot(&e0, &e0);
547        let d01 = Vector3::dot(&e0, &e1);
548        let d11 = Vector3::dot(&e1, &e1);
549        let d20 = Vector3::dot(&vp, &e0);
550        let d21 = Vector3::dot(&vp, &e1);
551        let denom = d00 * d11 - d01 * d01;
552        let v = (d11 * d20 - d01 * d21) / denom;
553        let w = (d00 * d21 - d01 * d20) / denom;
554        let u = <T as One>::one() - v - w;
555        Vector3::new(u, v, w)
556    }
557}
558
559////////////////////////////////////////////////////////////////////////////////
560/// A plane defined by ax + by + cz + d = 0.
561////////////////////////////////////////////////////////////////////////////////
562#[repr(C)]
563#[derive(Clone, Copy, Default)]
564pub struct Plane<T: Scalar> {
565    a: T,
566    b: T,
567    c: T,
568    d: T,
569}
570
571impl<T: Scalar> Plane<T> {
572    /// Returns the plane normal vector.
573    pub fn normal(&self) -> Vector3<T> {
574        Vector3::new(self.a, self.b, self.c)
575    }
576    /// Returns the plane constant term (d).
577    pub fn constant(&self) -> T {
578        self.d
579    }
580}
581
582impl<T: FloatScalar> Plane<T> {
583    /// Creates a plane from a normal and a point on the plane.
584    ///
585    /// # Panics
586    /// Panics if `n` is too small to normalize. Use [`Plane::try_new`] when the
587    /// input may be degenerate.
588    pub fn new(n: &Vector3<T>, p: &Vector3<T>) -> Self {
589        Self::try_new(n, p, T::epsilon()).expect("plane normal must be non-zero")
590    }
591
592    /// Creates a plane from a normal and a point on the plane.
593    ///
594    /// Returns `None` if `n` is too small to normalize.
595    pub fn try_new(n: &Vector3<T>, p: &Vector3<T>, epsilon: T) -> Option<Self> {
596        let norm = n.try_normalize(epsilon)?;
597        let d = Vector3::dot(&norm, p);
598        Some(Self {
599            a: norm.x,
600            b: norm.y,
601            c: norm.z,
602            d: -d,
603        })
604    }
605
606    /// Creates a plane from triangle vertices.
607    ///
608    /// # Panics
609    /// Panics if the triangle is degenerate. Use [`Plane::try_from_tri`] when
610    /// the input may be degenerate.
611    pub fn from_tri(v0: &Vector3<T>, v1: &Vector3<T>, v2: &Vector3<T>) -> Self {
612        Self::try_from_tri(v0, v1, v2, T::epsilon()).expect("triangle must define a plane")
613    }
614
615    /// Creates a plane from triangle vertices.
616    ///
617    /// Returns `None` if the triangle is degenerate.
618    pub fn try_from_tri(
619        v0: &Vector3<T>,
620        v1: &Vector3<T>,
621        v2: &Vector3<T>,
622        epsilon: T,
623    ) -> Option<Self> {
624        let n = try_tri_normal(v0, v1, v2, epsilon)?;
625        Self::try_new(&n, v0, epsilon)
626    }
627    /// Creates a plane from quad vertices.
628    ///
629    /// # Panics
630    /// Panics if the quad diagonals do not define a plane. Use
631    /// [`Plane::try_from_quad`] when the input may be degenerate.
632    pub fn from_quad(v0: &Vector3<T>, v1: &Vector3<T>, v2: &Vector3<T>, v3: &Vector3<T>) -> Self {
633        Self::try_from_quad(v0, v1, v2, v3, T::epsilon()).expect("quad must define a plane")
634    }
635
636    /// Creates a plane from quad vertices.
637    ///
638    /// Returns `None` if the quad diagonals do not define a plane.
639    pub fn try_from_quad(
640        v0: &Vector3<T>,
641        v1: &Vector3<T>,
642        v2: &Vector3<T>,
643        v3: &Vector3<T>,
644        epsilon: T,
645    ) -> Option<Self> {
646        let n = try_quad_normal(v0, v1, v2, v3, epsilon)?;
647        let c = (*v0 + *v1 + *v2 + *v3) * T::quarter();
648        Self::try_new(&n, &c, epsilon)
649    }
650
651    /// Intersects the plane with a ray.
652    pub fn intersect_ray(&self, r: &Ray<T, Vector3<T>>, epsilon: T) -> Option<Vector3<T>> {
653        r.intersect_plane(self, epsilon)
654    }
655
656    /// Computes line-plane intersection.
657    ///
658    /// Returns the parameter t and intersection point, or `None` if parallel.
659    pub fn intersect_line(
660        &self,
661        line: &Line<T, Vector3<T>>,
662        epsilon: T,
663    ) -> Option<(T, Vector3<T>)> {
664        let s = line.p;
665        let dir = line.d;
666        let n = self.normal();
667
668        let denom = Vector3::dot(&n, &dir);
669        if denom.tabs() < epsilon {
670            None
671        } else {
672            let t = -(self.constant() + Vector3::dot(&n, &s)) / denom;
673            Some((t, dir * t + s))
674        }
675    }
676}
677
678////////////////////////////////////////////////////////////////////////////////
679/// A parametric plane defined by center and axis vectors.
680////////////////////////////////////////////////////////////////////////////////
681#[repr(C)]
682#[derive(Clone, Copy, Default)]
683pub struct ParametricPlane<T: Scalar> {
684    /// Plane center point.
685    pub center: Vector3<T>,
686    /// Plane X axis direction.
687    pub x_axis: Vector3<T>,
688    /// Plane Y axis direction.
689    pub y_axis: Vector3<T>,
690}
691
692impl<T: FloatScalar> ParametricPlane<T> {
693    /// Creates a parametric plane from center and axes.
694    pub fn new(center: &Vector3<T>, x_axis: &Vector3<T>, y_axis: &Vector3<T>) -> Self {
695        Self {
696            center: *center,
697            x_axis: *x_axis,
698            y_axis: *y_axis,
699        }
700    }
701
702    /// Converts the parametric plane to an infinite plane.
703    pub fn plane(&self) -> Plane<T> {
704        self.try_plane(T::epsilon())
705            .expect("parametric plane axes must span a plane")
706    }
707
708    /// Converts the parametric plane to an infinite plane.
709    ///
710    /// Returns `None` if the axes are too small or parallel.
711    pub fn try_plane(&self, epsilon: T) -> Option<Plane<T>> {
712        let normal = self.try_normal(epsilon)?;
713        Plane::try_new(&normal, &self.center, epsilon)
714    }
715
716    /// Computes the normal vector (cross product of axes).
717    pub fn normal(&self) -> Vector3<T> {
718        self.try_normal(T::epsilon())
719            .expect("parametric plane axes must span a plane")
720    }
721
722    /// Computes the normal vector (cross product of axes).
723    ///
724    /// Returns `None` if the axes are too small or parallel.
725    pub fn try_normal(&self, epsilon: T) -> Option<Vector3<T>> {
726        Vector3::cross(&self.x_axis, &self.y_axis).try_normalize(epsilon)
727    }
728
729    /// Intersects the plane with a ray.
730    pub fn intersect_ray(&self, r: &Ray<T, Vector3<T>>, epsilon: T) -> Option<Vector3<T>> {
731        let plane = self.try_plane(epsilon)?;
732        r.intersect_plane(&plane, epsilon)
733    }
734
735    /// Intersects the plane with a line.
736    pub fn intersect_line(
737        &self,
738        line: &Line<T, Vector3<T>>,
739        epsilon: T,
740    ) -> Option<(T, Vector3<T>)> {
741        let plane = self.try_plane(epsilon)?;
742        plane.intersect_line(line, epsilon)
743    }
744
745    /// Projects a 3D point onto the plane's 2D coordinates.
746    pub fn project(&self, v: &Vector3<T>) -> Vector2<T> {
747        let p = *v - self.center;
748        let x_coord = Vector3::dot(&p, &self.x_axis) / Vector3::dot(&self.x_axis, &self.x_axis);
749        let y_coord = Vector3::dot(&p, &self.y_axis) / Vector3::dot(&self.y_axis, &self.y_axis);
750        Vector2::new(x_coord, y_coord)
751    }
752}
753
754////////////////////////////////////////////////////////////////////////////////
755/// Computes the normal vector of a triangle.
756////////////////////////////////////////////////////////////////////////////////
757pub fn tri_normal<T: FloatScalar>(v0: &Vector3<T>, v1: &Vector3<T>, v2: &Vector3<T>) -> Vector3<T> {
758    try_tri_normal(v0, v1, v2, T::epsilon()).expect("triangle must be non-degenerate")
759}
760
761/// Computes the normal vector of a triangle.
762///
763/// Returns `None` if the triangle is degenerate.
764pub fn try_tri_normal<T: FloatScalar>(
765    v0: &Vector3<T>,
766    v1: &Vector3<T>,
767    v2: &Vector3<T>,
768    epsilon: T,
769) -> Option<Vector3<T>> {
770    let v10 = *v1 - *v0;
771    let v20 = *v2 - *v0;
772    Vector3::cross(&v10, &v20).try_normalize(epsilon)
773}
774
775/// Computes the normal vector of a quadrilateral.
776///
777/// Uses the cross product of the two diagonals for a more stable result.
778pub fn quad_normal<T: FloatScalar>(
779    v0: &Vector3<T>,
780    v1: &Vector3<T>,
781    v2: &Vector3<T>,
782    v3: &Vector3<T>,
783) -> Vector3<T> {
784    try_quad_normal(v0, v1, v2, v3, T::epsilon()).expect("quad must be non-degenerate")
785}
786
787/// Computes the normal vector of a quadrilateral.
788///
789/// Returns `None` if the quad diagonals are too small or parallel.
790pub fn try_quad_normal<T: FloatScalar>(
791    v0: &Vector3<T>,
792    v1: &Vector3<T>,
793    v2: &Vector3<T>,
794    v3: &Vector3<T>,
795    epsilon: T,
796) -> Option<Vector3<T>> {
797    let v20 = *v2 - *v0;
798    let v31 = *v3 - *v1;
799    Vector3::cross(&v20, &v31).try_normalize(epsilon)
800}
801
802#[cfg(test)]
803mod tests {
804    use super::*;
805    #[test]
806    pub fn test_barycentric() {
807        let v0 = Vector3::new(0.0, 0.0, 0.0);
808        let v1 = Vector3::new(0.0, 1.0, 0.0);
809        let v2 = Vector3::new(0.0, 0.0, 1.0);
810
811        let tri = Tri3::new([v0, v1, v2]);
812        let pp0 = tri.barycentric_coordinates(&v0);
813        assert!(f32::abs(pp0.x - 1.0) < 0.01);
814        assert!(f32::abs(pp0.y) < 0.01);
815        assert!(f32::abs(pp0.z) < 0.01);
816
817        let pp1 = tri.barycentric_coordinates(&v1);
818        assert!(f32::abs(pp1.x) < 0.01);
819        assert!(f32::abs(pp1.y - 1.0) < 0.01);
820        assert!(f32::abs(pp1.z) < 0.01);
821
822        let pp2 = tri.barycentric_coordinates(&v2);
823        assert!(f32::abs(pp2.x) < 0.01);
824        assert!(f32::abs(pp2.y) < 0.01);
825        assert!(f32::abs(pp2.z - 1.0) < 0.01);
826    }
827
828    #[test]
829    pub fn test_barycentric_translated() {
830        // Test with a triangle not at the origin
831        let v0 = Vector3::new(1.0, 2.0, 3.0);
832        let v1 = Vector3::new(4.0, 2.0, 3.0);
833        let v2 = Vector3::new(1.0, 5.0, 3.0);
834
835        let tri = Tri3::new([v0, v1, v2]);
836
837        // Test vertices
838        let pp0 = tri.barycentric_coordinates(&v0);
839        assert!(f32::abs(pp0.x - 1.0) < 0.001);
840        assert!(f32::abs(pp0.y) < 0.001);
841        assert!(f32::abs(pp0.z) < 0.001);
842
843        let pp1 = tri.barycentric_coordinates(&v1);
844        assert!(f32::abs(pp1.x) < 0.001);
845        assert!(f32::abs(pp1.y - 1.0) < 0.001);
846        assert!(f32::abs(pp1.z) < 0.001);
847
848        let pp2 = tri.barycentric_coordinates(&v2);
849        assert!(f32::abs(pp2.x) < 0.001);
850        assert!(f32::abs(pp2.y) < 0.001);
851        assert!(f32::abs(pp2.z - 1.0) < 0.001);
852
853        // Test center point
854        let center = (v0 + v1 + v2) / 3.0;
855        let pp_center = tri.barycentric_coordinates(&center);
856        assert!(f32::abs(pp_center.x - 1.0 / 3.0) < 0.001);
857        assert!(f32::abs(pp_center.y - 1.0 / 3.0) < 0.001);
858        assert!(f32::abs(pp_center.z - 1.0 / 3.0) < 0.001);
859
860        // Verify barycentric coordinates sum to 1
861        assert!(f32::abs((pp_center.x + pp_center.y + pp_center.z) - 1.0) < 0.001);
862    }
863
864    #[test]
865    pub fn test_barycentric_edge_midpoints() {
866        let v0 = Vector3::new(0.0, 0.0, 0.0);
867        let v1 = Vector3::new(2.0, 0.0, 0.0);
868        let v2 = Vector3::new(0.0, 2.0, 0.0);
869
870        let tri = Tri3::new([v0, v1, v2]);
871
872        // Midpoint of edge v0-v1
873        let mid01 = (v0 + v1) / 2.0;
874        let pp_mid01 = tri.barycentric_coordinates(&mid01);
875        assert!(f32::abs(pp_mid01.x - 0.5) < 0.001);
876        assert!(f32::abs(pp_mid01.y - 0.5) < 0.001);
877        assert!(f32::abs(pp_mid01.z) < 0.001);
878
879        // Midpoint of edge v0-v2
880        let mid02 = (v0 + v2) / 2.0;
881        let pp_mid02 = tri.barycentric_coordinates(&mid02);
882        assert!(f32::abs(pp_mid02.x - 0.5) < 0.001);
883        assert!(f32::abs(pp_mid02.y) < 0.001);
884        assert!(f32::abs(pp_mid02.z - 0.5) < 0.001);
885
886        // Midpoint of edge v1-v2
887        let mid12 = (v1 + v2) / 2.0;
888        let pp_mid12 = tri.barycentric_coordinates(&mid12);
889        assert!(f32::abs(pp_mid12.x) < 0.001);
890        assert!(f32::abs(pp_mid12.y - 0.5) < 0.001);
891        assert!(f32::abs(pp_mid12.z - 0.5) < 0.001);
892    }
893
894    #[test]
895    pub fn test_barycentric_degenerate_triangle() {
896        let v0 = Vector3::new(0.0f32, 0.0, 0.0);
897        let v1 = Vector3::new(1.0f32, 0.0, 0.0);
898        let v2 = Vector3::new(2.0f32, 0.0, 0.0);
899
900        let tri = Tri3::new([v0, v1, v2]);
901        let test_point = Vector3::new(0.5f32, 0.0, 0.0);
902        let bary = tri.barycentric_coordinates(&test_point);
903        assert!(!bary.x.is_finite());
904        assert!(!bary.y.is_finite());
905        assert!(!bary.z.is_finite());
906    }
907
908    #[test]
909    pub fn test_barycentric_interpolation() {
910        // Test that we can reconstruct points using barycentric coordinates
911        let v0 = Vector3::new(1.0, 0.0, 0.0);
912        let v1 = Vector3::new(0.0, 1.0, 0.0);
913        let v2 = Vector3::new(0.0, 0.0, 1.0);
914
915        let tri = Tri3::new([v0, v1, v2]);
916
917        // Test arbitrary point inside triangle
918        let test_point = Vector3::new(0.2, 0.3, 0.5);
919        let bary = tri.barycentric_coordinates(&test_point);
920
921        // Reconstruct the point using barycentric coordinates
922        let reconstructed = v0 * bary.x + v1 * bary.y + v2 * bary.z;
923
924        assert!(f32::abs(reconstructed.x - test_point.x) < 0.001);
925        assert!(f32::abs(reconstructed.y - test_point.y) < 0.001);
926        assert!(f32::abs(reconstructed.z - test_point.z) < 0.001);
927    }
928
929    #[test]
930    pub fn test_box3_overlap() {
931        let a = Box3::new(&Vector3::new(0.0, 0.0, 0.0), &Vector3::new(1.0, 1.0, 1.0));
932        let b = Box3::new(&Vector3::new(0.5, 0.5, 0.5), &Vector3::new(1.5, 1.5, 1.5));
933        assert!(a.overlap(&b));
934
935        let c = Box3::new(&Vector3::new(2.0, 0.0, 0.0), &Vector3::new(3.0, 1.0, 1.0));
936        assert!(!a.overlap(&c));
937
938        let d = Box3::new(&Vector3::new(0.0, 2.0, 0.0), &Vector3::new(1.0, 3.0, 1.0));
939        assert!(!a.overlap(&d));
940
941        let e = Box3::new(&Vector3::new(0.0, 0.0, 2.0), &Vector3::new(1.0, 1.0, 3.0));
942        assert!(!a.overlap(&e));
943
944        let f = Box3::new(&Vector3::new(1.0, 0.0, 0.0), &Vector3::new(2.0, 1.0, 1.0));
945        assert!(a.overlap(&f));
946    }
947
948    #[test]
949    fn test_line_new_zero_direction() {
950        let p = Vector3::new(0.0f32, 0.0, 0.0);
951        let d = Vector3::new(0.0f32, 0.0, 0.0);
952        assert!(Line::new(&p, &d, EPS_F32).is_none());
953    }
954
955    #[test]
956    fn test_line_from_start_end_zero_direction() {
957        let p = Vector3::new(1.0f32, 2.0, 3.0);
958        assert!(Line::from_start_end(&p, &p, EPS_F32).is_none());
959    }
960
961    #[test]
962    fn test_line_closest_point_valid() {
963        let p = Vector3::new(0.0f32, 0.0, 0.0);
964        let d = Vector3::new(1.0f32, 0.0, 0.0);
965        let line = Line::new(&p, &d, EPS_F32).expect("line should be valid");
966        let target = Vector3::new(2.0f32, 1.0, 0.0);
967        let (t, closest) = line
968            .closest_point_on_line(&target, EPS_F32)
969            .expect("closest point should exist");
970        assert!((t - 2.0).abs() < 0.001);
971        assert!((closest.x - 2.0).abs() < 0.001);
972        assert!(closest.y.abs() < 0.001);
973        assert!(closest.z.abs() < 0.001);
974    }
975
976    #[test]
977    fn test_line_normalize_zero_direction() {
978        let line = Line {
979            p: Vector3::new(0.0f32, 0.0, 0.0),
980            d: Vector3::new(0.0f32, 0.0, 0.0),
981            t: core::marker::PhantomData,
982        };
983        assert!(line.normalize(EPS_F32).is_none());
984    }
985
986    #[test]
987    fn test_line_normalize_valid_direction() {
988        let p = Vector3::new(0.0f32, 0.0, 0.0);
989        let d = Vector3::new(2.0f32, 0.0, 0.0);
990        let line = Line::new(&p, &d, EPS_F32).expect("line should be valid");
991        let norm = line.normalize(EPS_F32).expect("normalize should succeed");
992        assert!((norm.d.length() - 1.0).abs() < 0.001);
993    }
994
995    #[test]
996    fn test_segment_distance_zero_length() {
997        let p = Vector3::new(0.0f32, 0.0, 0.0);
998        let seg = Segment::new(&p, &p);
999        let target = Vector3::new(1.0f32, 0.0, 0.0);
1000        assert!(seg.distance(&target, EPS_F32).is_none());
1001        assert!(seg.closest_point_on_segment(&target, EPS_F32).is_none());
1002    }
1003
1004    #[test]
1005    fn test_ray_new_zero_direction() {
1006        let p = Vector3::new(0.0f32, 0.0, 0.0);
1007        let d = Vector3::new(0.0f32, 0.0, 0.0);
1008        assert!(Ray::new(&p, &d, EPS_F32).is_none());
1009    }
1010
1011    #[test]
1012    fn test_shortest_segment_parallel_lines() {
1013        let p0 = Vector3::new(0.0f32, 0.0, 0.0);
1014        let p1 = Vector3::new(0.0f32, 1.0, 0.0);
1015        let d = Vector3::new(1.0f32, 0.0, 0.0);
1016        let l0 = Line::new(&p0, &d, EPS_F32).expect("line should be valid");
1017        let l1 = Line::new(&p1, &d, EPS_F32).expect("line should be valid");
1018        assert!(shortest_segment3d_between_lines3d(&l0, &l1, EPS_F32).is_none());
1019    }
1020
1021    #[test]
1022    fn test_ray_intersect_plane_parallel() {
1023        let ray = Ray::new(
1024            &Vector3::new(0.0f32, 0.0, 0.0),
1025            &Vector3::new(1.0, 0.0, 0.0),
1026            EPS_F32,
1027        )
1028        .expect("ray should be valid");
1029        let plane = Plane::new(
1030            &Vector3::new(0.0f32, 1.0, 0.0),
1031            &Vector3::new(0.0, 0.0, 0.0),
1032        );
1033        assert!(ray.intersect_plane(&plane, EPS_F32).is_none());
1034        assert!(plane.intersect_ray(&ray, EPS_F32).is_none());
1035    }
1036
1037    #[test]
1038    fn test_ray_intersect_plane_hit() {
1039        let ray = Ray::new(
1040            &Vector3::new(0.0f32, -1.0, 0.0),
1041            &Vector3::new(0.0, 1.0, 0.0),
1042            EPS_F32,
1043        )
1044        .expect("ray should be valid");
1045        let plane = Plane::new(
1046            &Vector3::new(0.0f32, 1.0, 0.0),
1047            &Vector3::new(0.0, 0.0, 0.0),
1048        );
1049        let hit = ray.intersect_plane(&plane, EPS_F32).expect("should hit");
1050        assert!(hit.y.abs() < 0.001);
1051    }
1052
1053    #[test]
1054    fn test_plane_try_new_zero_normal_none() {
1055        let plane = Plane::try_new(
1056            &Vector3::new(0.0f32, 0.0, 0.0),
1057            &Vector3::new(0.0, 0.0, 0.0),
1058            EPS_F32,
1059        );
1060        assert!(plane.is_none());
1061    }
1062
1063    #[test]
1064    fn test_box3_center_extent_subdivide() {
1065        let b = Box3::new(
1066            &Vector3::new(0.0f32, 0.0, 0.0),
1067            &Vector3::new(2.0, 2.0, 2.0),
1068        );
1069        let center = b.center();
1070        let extent = b.extent();
1071        assert!((center.x - 1.0).abs() < 0.001);
1072        assert!((center.y - 1.0).abs() < 0.001);
1073        assert!((center.z - 1.0).abs() < 0.001);
1074        assert!((extent.x - 1.0).abs() < 0.001);
1075        assert!((extent.y - 1.0).abs() < 0.001);
1076        assert!((extent.z - 1.0).abs() < 0.001);
1077
1078        let subs = b.subdivide();
1079        assert_eq!(subs.len(), 8);
1080        for sub in subs.iter() {
1081            assert!(sub.min.x >= 0.0 && sub.min.y >= 0.0 && sub.min.z >= 0.0);
1082            assert!(sub.max.x <= 2.0 && sub.max.y <= 2.0 && sub.max.z <= 2.0);
1083        }
1084    }
1085
1086    #[test]
1087    fn test_parametric_plane_project() {
1088        let plane = ParametricPlane::new(
1089            &Vector3::new(1.0f32, 2.0, 3.0),
1090            &Vector3::new(1.0, 0.0, 0.0),
1091            &Vector3::new(0.0, 1.0, 0.0),
1092        );
1093        let point = Vector3::new(3.0f32, 6.0, 3.0);
1094        let uv = plane.project(&point);
1095        assert!((uv.x - 2.0).abs() < 0.001);
1096        assert!((uv.y - 4.0).abs() < 0.001);
1097    }
1098
1099    #[test]
1100    fn test_parametric_plane_try_normal_parallel_axes_none() {
1101        let plane = ParametricPlane::new(
1102            &Vector3::new(0.0f32, 0.0, 0.0),
1103            &Vector3::new(1.0, 0.0, 0.0),
1104            &Vector3::new(2.0, 0.0, 0.0),
1105        );
1106        assert!(plane.try_normal(EPS_F32).is_none());
1107        assert!(plane.try_plane(EPS_F32).is_none());
1108    }
1109}