From 8785fda836fe3884bd51444fc55983fe135c6c9d Mon Sep 17 00:00:00 2001 From: Arne Dußin Date: Sat, 21 Nov 2020 01:08:06 +0100 Subject: Add unit tests for triangle --- src/math/triangle.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) (limited to 'src/math') diff --git a/src/math/triangle.rs b/src/math/triangle.rs index 53c7560..05e258d 100644 --- a/src/math/triangle.rs +++ b/src/math/triangle.rs @@ -30,6 +30,11 @@ impl Triangle { } } + /// Get the corners immutably + pub fn corners(&self) -> &[Vec2; 3] { + &self.corners + } + /// Create a new Triangle from a three-point slice, instead of the three points one after /// another. pub fn from_slice(corners: [Vec2; 3]) -> Self @@ -60,6 +65,21 @@ impl Triangle { } } +/// Convert a three-point-slice into a triangle +impl From<[Vec2; 3]> + for Triangle +{ + fn from(corners: [Vec2; 3]) -> Self { + Self::new(corners[0], corners[1], corners[2]) + } +} +/// Convert a triangle into a three-point-slice. The corners are in counterclockwise order. +impl Into<[Vec2; 3]> for Triangle { + fn into(self) -> [Vec2; 3] { + self.corners + } +} + #[derive(PartialEq, Eq)] pub(crate) enum TripletOrientation { Clockwise, @@ -131,6 +151,43 @@ mod test { use super::*; use std::f64::consts::PI; + #[test] + fn new() { + let a = Vec2::new(0., 0.); + let b = Vec2::new(0., 1.); + let c = Vec2::new(1., 1.); + + // Create with counterclockwise order. + let triangle = Triangle::new(a, b, c); + assert_eq!(triangle.corners(), &[a, b, c]); + + // Create with clockwise order. + let triangle = Triangle::new(a, c, b); + assert_eq!(triangle.corners(), &[a, b, c]); + + // Create with different starting corner + let triangle = Triangle::from([b, c, a]); + assert_eq!(triangle.corners(), &[b, c, a]); + + // Create with collinear corners + let triangle = Triangle::new(c, c, b); + assert_eq!(triangle.corners(), &[c, c, b]); + } + + #[test] + fn contains_point() { + let a = Vec2::new(0., 0.); + let b = Vec2::new(-1., -1.); + let c = Vec2::new(-2., 0.); + + let triangle = Triangle::new(a, b, c); + + assert!(triangle.contains_point(b)); + assert!(triangle.contains_point(Vec2::new(-0.5, -0.5))); + assert!(triangle.contains_point(Vec2::new(-1., -0.5))); + assert!(!triangle.contains_point(Vec2::new(-2., -2.))); + } + #[test] fn triplet_angle() { assert_eq!( -- cgit v1.2.3-70-g09d2