1 // pathfinder/geometry/src/unit_vector.rs 2 // 3 // Copyright © 2019 The Pathfinder Project Developers. 4 // 5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or 6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license 7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your 8 // option. This file may not be copied, modified, or distributed 9 // except according to those terms. 10 11 //! A utility module that allows unit vectors to be treated like angles. 12 13 use crate::vector::Vector2F; 14 use pathfinder_simd::default::F32x2; 15 16 #[derive(Clone, Copy, Debug)] 17 pub struct UnitVector(pub Vector2F); 18 19 impl UnitVector { 20 #[inline] from_angle(theta: f32) -> UnitVector21 pub fn from_angle(theta: f32) -> UnitVector { 22 UnitVector(Vector2F::new(theta.cos(), theta.sin())) 23 } 24 25 /// Angle addition formula. 26 #[inline] rotate_by(&self, other: UnitVector) -> UnitVector27 pub fn rotate_by(&self, other: UnitVector) -> UnitVector { 28 let products = (self.0).0.to_f32x4().xyyx() * (other.0).0.to_f32x4().xyxy(); 29 UnitVector(Vector2F::new(products[0] - products[1], products[2] + products[3])) 30 } 31 32 /// Angle subtraction formula. 33 #[inline] rev_rotate_by(&self, other: UnitVector) -> UnitVector34 pub fn rev_rotate_by(&self, other: UnitVector) -> UnitVector { 35 let products = (self.0).0.to_f32x4().xyyx() * (other.0).0.to_f32x4().xyxy(); 36 UnitVector(Vector2F::new(products[0] + products[1], products[2] - products[3])) 37 } 38 39 /// Half angle formula. 40 #[inline] halve_angle(&self) -> UnitVector41 pub fn halve_angle(&self) -> UnitVector { 42 let x = self.0.x(); 43 let term = F32x2::new(x, -x); 44 UnitVector(Vector2F((F32x2::splat(0.5) * (F32x2::splat(1.0) + term)).max(F32x2::default()) 45 .sqrt())) 46 } 47 } 48