Add Triangle::from_points

This commit is contained in:
Hanno Braun 2022-03-17 15:17:29 +01:00
parent a3249d3510
commit 3ea35f18d6

View File

@ -11,6 +11,28 @@ pub struct Triangle<const D: usize> {
} }
impl<const D: usize> Triangle<D> { impl<const D: usize> Triangle<D> {
/// Construct a triangle from three points
///
/// # Panics
///
/// Panics, if the points don't form a triangle.
pub fn from_points(points: [Point<D>; 3]) -> Self {
let area = {
let [a, b, c] = points.map(Point::to_xyz);
(b - a).cross(&(c - a)).magnitude()
};
// A triangle is not valid if it doesn't span any area
if area != Scalar::from(0.0) {
Self {
points,
color: [255, 0, 0, 255],
}
} else {
panic!("Invalid Triangle specified");
}
}
/// Access the triangle's points /// Access the triangle's points
pub fn points(&self) -> [Point<D>; 3] { pub fn points(&self) -> [Point<D>; 3] {
self.points self.points
@ -36,20 +58,7 @@ impl Triangle<3> {
impl<const D: usize> From<[Point<D>; 3]> for Triangle<D> { impl<const D: usize> From<[Point<D>; 3]> for Triangle<D> {
fn from(points: [Point<D>; 3]) -> Self { fn from(points: [Point<D>; 3]) -> Self {
let area = { Self::from_points(points)
let [a, b, c] = points.map(Point::to_xyz);
(b - a).cross(&(c - a)).magnitude()
};
// A triangle is not valid if it doesn't span any area
if area != Scalar::from(0.0) {
Self {
points,
color: [255, 0, 0, 255],
}
} else {
panic!("Invalid Triangle specified");
}
} }
} }