meshellaneous/triangle/
mod.rs

1mod intersect;
2mod modifiers;
3
4use std::ops::{Index, IndexMut};
5
6use glam::{Vec2, Vec3};
7
8#[derive(Clone, Copy, Debug)]
9pub struct Triangle {
10    pub points: [Vec3; 3],
11    pub uvs: [Vec2; 3],
12    pub normal: Vec3,
13}
14
15impl Triangle {
16    pub fn new(points: [Vec3; 3], uvs: [Vec2; 3], normal: Vec3) -> Self {
17        Self {
18            points,
19            uvs,
20            normal,
21        }
22    }
23
24    /// Gets the normal from points
25    /// and create a Triangle
26    pub fn from_points_uvs(points: [Vec3; 3], uvs: [Vec2; 3]) -> Self {
27        let normal = (points[1] - points[0]).cross(points[2] - points[0]);
28        Self::new(points, uvs, normal)
29    }
30
31    /// Gets the normal from points  
32    /// uses ZERO for uvs
33    /// and creates a Triangle
34    pub fn from_points(points: [Vec3; 3]) -> Self {
35        Self::from_points_uvs(points, [Vec2::ZERO; 3])
36    }
37
38    /// returns a point with the maximum x, y and z values
39    pub fn max(&self) -> Vec3 {
40        self[0].max(self[1]).max(self[2])
41    }
42
43    /// returns a point with the minimum x, y, and z values
44    pub fn min(&self) -> Vec3 {
45        self[0].min(self[1]).min(self[2])
46    }
47
48    /// Calculates the area of this triangle
49    pub fn area(&self) -> f32 {
50        // https://math.stackexchange.com/a/128995
51        let ab = self[1] - self[0];
52        let ac = self[2] - self[0];
53        ab.dot(ac) * 0.5
54    }
55}
56
57impl Index<usize> for Triangle {
58    type Output = Vec3;
59
60    /// returns a reference to the nth point
61    ///
62    /// ### Panic
63    /// panics if the index is above 2
64    fn index(&self, index: usize) -> &Self::Output {
65        &self.points[index]
66    }
67}
68
69impl IndexMut<usize> for Triangle {
70    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
71        &mut self.points[index]
72    }
73}