Skip to main content

use_simplex/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use use_dimension::Dimension;
5use use_vector::Vector3;
6
7/// A general simplex descriptor.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct Simplex {
10    dimension: Dimension,
11}
12
13impl Simplex {
14    /// Creates a simplex descriptor for a positive dimension.
15    #[must_use]
16    pub const fn new(dimension: usize) -> Option<Self> {
17        match Dimension::new(dimension) {
18            Some(dimension) => Some(Self { dimension }),
19            None => None,
20        }
21    }
22
23    /// Returns the simplex dimension.
24    #[must_use]
25    pub const fn dimension(self) -> Dimension {
26        self.dimension
27    }
28
29    /// Returns the number of vertices in this simplex family.
30    #[must_use]
31    pub const fn vertex_count(self) -> usize {
32        self.dimension.value() + 1
33    }
34}
35
36/// A 3-simplex in 3D space.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct Tetrahedron {
39    vertices: [Vector3; 4],
40}
41
42impl Tetrahedron {
43    /// Creates a tetrahedron from four vertices.
44    #[must_use]
45    pub const fn new(vertices: [Vector3; 4]) -> Self {
46        Self { vertices }
47    }
48
49    /// Returns the vertices.
50    #[must_use]
51    pub const fn vertices(self) -> [Vector3; 4] {
52        self.vertices
53    }
54
55    /// Returns the vertex count.
56    #[must_use]
57    pub const fn vertex_count(self) -> usize {
58        4
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::{Simplex, Tetrahedron};
65    use use_vector::Vector3;
66
67    #[test]
68    fn counts_simplex_vertices() {
69        let simplex = Simplex::new(3).expect("valid simplex");
70        let tetrahedron = Tetrahedron::new([
71            Vector3::ZERO,
72            Vector3::new(1.0, 0.0, 0.0),
73            Vector3::new(0.0, 1.0, 0.0),
74            Vector3::new(0.0, 0.0, 1.0),
75        ]);
76
77        assert_eq!(simplex.vertex_count(), 4);
78        assert_eq!(tetrahedron.vertex_count(), 4);
79        assert_eq!(Simplex::new(0), None);
80    }
81}