// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
usesuper::UnknownUnit; usecrate::approxeq::ApproxEq; usecrate::approxord::{max, min}; usecrate::length::Length; usecrate::num::*; usecrate::point::{point2, point3, Point2D, Point3D}; usecrate::scale::Scale; usecrate::size::{size2, size3, Size2D, Size3D}; usecrate::transform2d::Transform2D; usecrate::transform3d::Transform3D; usecrate::trig::Trig; usecrate::Angle; use core::cmp::{Eq, PartialEq}; use core::fmt; use core::hash::Hash; use core::iter::Sum; use core::marker::PhantomData; use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}; #[cfg(feature = "mint")] use mint; use num_traits::real::Real; use num_traits::{Float, NumCast, Signed}; #[cfg(feature = "serde")] use serde;
#[cfg(feature = "bytemuck")] use bytemuck::{Pod, Zeroable};
/// A 2d Vector tagged with a unit. #[repr(C)] pubstruct Vector2D<T, U> { /// The `x` (traditionally, horizontal) coordinate. pub x: T, /// The `y` (traditionally, vertical) coordinate. pub y: T, #[doc(hidden)] pub _unit: PhantomData<U>,
}
/// Tag a unit-less value with units. #[inline] pubfn from_untyped(p: Vector2D<T, UnknownUnit>) -> Self {
vec2(p.x, p.y)
}
/// Apply the function `f` to each component of this vector. /// /// # Example /// /// This may be used to perform unusual arithmetic which is not already offered as methods. /// /// ``` /// use euclid::default::Vector2D; /// /// let p = Vector2D::<u32>::new(5, 11); /// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Vector2D::new(0, 1)); /// ``` #[inline] pubfn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Vector2D<V, U> {
vec2(f(self.x), f(self.y))
}
/// Apply the function `f` to each pair of components of this point and `rhs`. /// /// # Example /// /// This may be used to perform unusual arithmetic which is not already offered as methods. /// /// ``` /// use euclid::default::Vector2D; /// /// let a: Vector2D<u8> = Vector2D::new(50, 200); /// let b: Vector2D<u8> = Vector2D::new(100, 100); /// assert_eq!(a.zip(b, u8::saturating_add), Vector2D::new(150, 255)); /// ``` #[inline] pubfn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector2D<V, U> {
vec2(f(self.x, rhs.x), f(self.y, rhs.y))
}
/// Computes the vector with absolute values of each component. /// /// # Example /// /// ```rust /// # use std::{i32, f32}; /// # use euclid::vec2; /// enum U {} /// /// assert_eq!(vec2::<_, U>(-1, 2).abs(), vec2(1, 2)); /// /// let vec = vec2::<_, U>(f32::NAN, -f32::MAX).abs(); /// assert!(vec.x.is_nan()); /// assert_eq!(vec.y, f32::MAX); /// ``` /// /// # Panics /// /// The behavior for each component follows the scalar type's implementation of /// `num_traits::Signed::abs`. pubfn abs(self) -> Self where
T: Signed,
{
vec2(self.x.abs(), self.y.abs())
}
/// Returns the norm of the cross product [self.x, self.y, 0] x [other.x, other.y, 0]. #[inline] pubfn cross(self, other: Self) -> T where
T: Sub<Output = T> + Mul<Output = T>,
{ self.x * other.y - self.y * other.x
}
/// Returns the component-wise multiplication of the two vectors. #[inline] pubfn component_mul(self, other: Self) -> Self where
T: Mul<Output = T>,
{
vec2(self.x * other.x, self.y * other.y)
}
/// Returns the component-wise division of the two vectors. #[inline] pubfn component_div(self, other: Self) -> Self where
T: Div<Output = T>,
{
vec2(self.x / other.x, self.y / other.y)
}
}
impl<T: Copy, U> Vector2D<T, U> { /// Create a 3d vector from this one, using the specified z value. #[inline] pubfn extend(self, z: T) -> Vector3D<T, U> {
vec3(self.x, self.y, z)
}
/// Cast this vector into a point. /// /// Equivalent to adding this vector to the origin. #[inline] pubfn to_point(self) -> Point2D<T, U> {
Point2D {
x: self.x,
y: self.y,
_unit: PhantomData,
}
}
/// Swap x and y. #[inline] pubfn yx(self) -> Self {
vec2(self.y, self.x)
}
/// Cast this vector into a size. #[inline] pubfn to_size(self) -> Size2D<T, U> {
size2(self.x, self.y)
}
/// Drop the units, preserving only the numeric value. #[inline] pubfn to_untyped(self) -> Vector2D<T, UnknownUnit> {
vec2(self.x, self.y)
}
/// Cast the unit. #[inline] pubfn cast_unit<V>(self) -> Vector2D<T, V> {
vec2(self.x, self.y)
}
/// Cast into an array with x and y. #[inline] pubfn to_array(self) -> [T; 2] {
[self.x, self.y]
}
/// Cast into a tuple with x and y. #[inline] pubfn to_tuple(self) -> (T, T) {
(self.x, self.y)
}
/// Convert into a 3d vector with `z` coordinate equals to `T::zero()`. #[inline] pubfn to_3d(self) -> Vector3D<T, U> where
T: Zero,
{
vec3(self.x, self.y, Zero::zero())
}
/// Rounds each component to the nearest integer value. /// /// This behavior is preserved for negative values (unlike the basic cast). /// /// ```rust /// # use euclid::vec2; /// enum Mm {} /// /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).round(), vec2::<_, Mm>(0.0, -1.0)) /// ``` #[inline] #[must_use] pubfn round(self) -> Self where
T: Round,
{
vec2(self.x.round(), self.y.round())
}
/// Rounds each component to the smallest integer equal or greater than the original value. /// /// This behavior is preserved for negative values (unlike the basic cast). /// /// ```rust /// # use euclid::vec2; /// enum Mm {} /// /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).ceil(), vec2::<_, Mm>(0.0, 0.0)) /// ``` #[inline] #[must_use] pubfn ceil(self) -> Self where
T: Ceil,
{
vec2(self.x.ceil(), self.y.ceil())
}
/// Rounds each component to the biggest integer equal or lower than the original value. /// /// This behavior is preserved for negative values (unlike the basic cast). /// /// ```rust /// # use euclid::vec2; /// enum Mm {} /// /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).floor(), vec2::<_, Mm>(-1.0, -1.0)) /// ``` #[inline] #[must_use] pubfn floor(self) -> Self where
T: Floor,
{
vec2(self.x.floor(), self.y.floor())
}
/// Returns the signed angle between this vector and the x axis. /// Positive values counted counterclockwise, where 0 is `+x` axis, `PI/2` /// is `+y` axis. /// /// The returned angle is between -PI and PI. pubfn angle_from_x_axis(self) -> Angle<T> where
T: Trig,
{
Angle::radians(Trig::fast_atan2(self.y, self.x))
}
/// Creates translation by this vector in vector units. #[inline] pubfn to_transform(self) -> Transform2D<T, U, U> where
T: Zero + One,
{
Transform2D::translation(self.x, self.y)
}
}
/// Returns this vector projected onto another one. /// /// Projecting onto a nil vector will cause a division by zero. #[inline] pubfn project_onto_vector(self, onto: Self) -> Self where
T: Sub<T, Output = T> + Div<T, Output = T>,
{
onto * (self.dot(onto) / onto.square_length())
}
/// Returns the signed angle between this vector and another vector. /// /// The returned angle is between -PI and PI. pubfn angle_to(self, other: Self) -> Angle<T> where
T: Sub<Output = T> + Trig,
{
Angle::radians(Trig::fast_atan2(self.cross(other), self.dot(other)))
}
}
impl<T: Float, U> Vector2D<T, U> { /// Return the normalized vector even if the length is larger than the max value of Float. #[inline] #[must_use] pubfn robust_normalize(self) -> Self { let length = self.length(); if length.is_infinite() { let scaled = self / T::max_value();
scaled / scaled.length()
} else { self / length
}
}
/// Returns true if all members are finite. #[inline] pubfn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite()
}
}
impl<T: Real, U> Vector2D<T, U> { /// Returns the vector length. #[inline] pubfn length(self) -> T { self.square_length().sqrt()
}
/// Returns the vector with length of one unit. #[inline] #[must_use] pubfn normalize(self) -> Self { self / self.length()
}
/// Returns the vector with length of one unit. /// /// Unlike [`Vector2D::normalize`](#method.normalize), this returns None in the case that the /// length of the vector is zero. #[inline] #[must_use] pubfn try_normalize(self) -> Option<Self> { let len = self.length(); if len == T::zero() {
None
} else {
Some(self / len)
}
}
/// Return this vector scaled to fit the provided length. #[inline] pubfn with_length(self, length: T) -> Self { self.normalize() * length
}
/// Return this vector capped to a maximum length. #[inline] pubfn with_max_length(self, max_length: T) -> Self { let square_length = self.square_length(); if square_length > max_length * max_length { returnself * (max_length / square_length.sqrt());
}
self
}
/// Return this vector with a minimum length applied. #[inline] pubfn with_min_length(self, min_length: T) -> Self { let square_length = self.square_length(); if square_length < min_length * min_length { returnself * (min_length / square_length.sqrt());
}
self
}
/// Return this vector with minimum and maximum lengths applied. #[inline] pubfn clamp_length(self, min: T, max: T) -> Self {
debug_assert!(min <= max); self.with_min_length(min).with_max_length(max)
}
}
impl<T, U> Vector2D<T, U> where
T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
{ /// Linearly interpolate each component between this vector and another vector. /// /// # Example /// /// ```rust /// use euclid::vec2; /// use euclid::default::Vector2D; /// /// let from: Vector2D<_> = vec2(0.0, 10.0); /// let to: Vector2D<_> = vec2(8.0, -4.0); /// /// assert_eq!(from.lerp(to, -1.0), vec2(-8.0, 24.0)); /// assert_eq!(from.lerp(to, 0.0), vec2( 0.0, 10.0)); /// assert_eq!(from.lerp(to, 0.5), vec2( 4.0, 3.0)); /// assert_eq!(from.lerp(to, 1.0), vec2( 8.0, -4.0)); /// assert_eq!(from.lerp(to, 2.0), vec2(16.0, -18.0)); /// ``` #[inline] pubfn lerp(self, other: Self, t: T) -> Self { let one_t = T::one() - t; self * one_t + other * t
}
/// Returns a reflection vector using an incident ray and a surface normal. #[inline] pubfn reflect(self, normal: Self) -> Self { let two = T::one() + T::one(); self - normal * two * self.dot(normal)
}
}
impl<T: PartialOrd, U> Vector2D<T, U> { /// Returns the vector each component of which are minimum of this vector and another. #[inline] pubfn min(self, other: Self) -> Self {
vec2(min(self.x, other.x), min(self.y, other.y))
}
/// Returns the vector each component of which are maximum of this vector and another. #[inline] pubfn max(self, other: Self) -> Self {
vec2(max(self.x, other.x), max(self.y, other.y))
}
/// Returns the vector each component of which is clamped by corresponding /// components of `start` and `end`. /// /// Shortcut for `self.max(start).min(end)`. #[inline] pubfn clamp(self, start: Self, end: Self) -> Self where
T: Copy,
{ self.max(start).min(end)
}
/// Returns vector with results of "greater than" operation on each component. #[inline] pubfn greater_than(self, other: Self) -> BoolVector2D {
BoolVector2D {
x: self.x > other.x,
y: self.y > other.y,
}
}
/// Returns vector with results of "lower than" operation on each component. #[inline] pubfn lower_than(self, other: Self) -> BoolVector2D {
BoolVector2D {
x: self.x < other.x,
y: self.y < other.y,
}
}
}
impl<T: PartialEq, U> Vector2D<T, U> { /// Returns vector with results of "equal" operation on each component. #[inline] pubfn equal(self, other: Self) -> BoolVector2D {
BoolVector2D {
x: self.x == other.x,
y: self.y == other.y,
}
}
/// Returns vector with results of "not equal" operation on each component. #[inline] pubfn not_equal(self, other: Self) -> BoolVector2D {
BoolVector2D {
x: self.x != other.x,
y: self.y != other.y,
}
}
}
impl<T: NumCast + Copy, U> Vector2D<T, U> { /// Cast from one numeric representation to another, preserving the units. /// /// When casting from floating vector to integer coordinates, the decimals are truncated /// as one would expect from a simple cast, but this behavior does not always make sense /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting. #[inline] pubfn cast<NewT: NumCast>(self) -> Vector2D<NewT, U> { self.try_cast().unwrap()
}
/// Fallible cast from one numeric representation to another, preserving the units. /// /// When casting from floating vector to integer coordinates, the decimals are truncated /// as one would expect from a simple cast, but this behavior does not always make sense /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting. pubfn try_cast<NewT: NumCast>(self) -> Option<Vector2D<NewT, U>> { match (NumCast::from(self.x), NumCast::from(self.y)) {
(Some(x), Some(y)) => Some(Vector2D::new(x, y)),
_ => None,
}
}
// Convenience functions for common casts.
/// Cast into an `f32` vector. #[inline] pubfn to_f32(self) -> Vector2D<f32, U> { self.cast()
}
/// Cast into an `f64` vector. #[inline] pubfn to_f64(self) -> Vector2D<f64, U> { self.cast()
}
/// Cast into an `usize` vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_usize(self) -> Vector2D<usize, U> { self.cast()
}
/// Cast into an `u32` vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_u32(self) -> Vector2D<u32, U> { self.cast()
}
/// Cast into an i32 vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_i32(self) -> Vector2D<i32, U> { self.cast()
}
/// Cast into an i64 vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_i64(self) -> Vector2D<i64, U> { self.cast()
}
}
impl<T: Neg, U> Neg for Vector2D<T, U> { type Output = Vector2D<T::Output, U>;
/// Tag a unitless value with units. #[inline] pubfn from_untyped(p: Vector3D<T, UnknownUnit>) -> Self {
vec3(p.x, p.y, p.z)
}
/// Apply the function `f` to each component of this vector. /// /// # Example /// /// This may be used to perform unusual arithmetic which is not already offered as methods. /// /// ``` /// use euclid::default::Vector3D; /// /// let p = Vector3D::<u32>::new(5, 11, 15); /// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Vector3D::new(0, 1, 5)); /// ``` #[inline] pubfn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Vector3D<V, U> {
vec3(f(self.x), f(self.y), f(self.z))
}
/// Apply the function `f` to each pair of components of this point and `rhs`. /// /// # Example /// /// This may be used to perform unusual arithmetic which is not already offered as methods. /// /// ``` /// use euclid::default::Vector3D; /// /// let a: Vector3D<u8> = Vector3D::new(50, 200, 10); /// let b: Vector3D<u8> = Vector3D::new(100, 100, 0); /// assert_eq!(a.zip(b, u8::saturating_add), Vector3D::new(150, 255, 10)); /// ``` #[inline] pubfn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector3D<V, U> {
vec3(f(self.x, rhs.x), f(self.y, rhs.y), f(self.z, rhs.z))
}
/// Computes the vector with absolute values of each component. /// /// # Example /// /// ```rust /// # use std::{i32, f32}; /// # use euclid::vec3; /// enum U {} /// /// assert_eq!(vec3::<_, U>(-1, 0, 2).abs(), vec3(1, 0, 2)); /// /// let vec = vec3::<_, U>(f32::NAN, 0.0, -f32::MAX).abs(); /// assert!(vec.x.is_nan()); /// assert_eq!(vec.y, 0.0); /// assert_eq!(vec.z, f32::MAX); /// ``` /// /// # Panics /// /// The behavior for each component follows the scalar type's implementation of /// `num_traits::Signed::abs`. pubfn abs(self) -> Self where
T: Signed,
{
vec3(self.x.abs(), self.y.abs(), self.z.abs())
}
/// Returns the component-wise multiplication of the two vectors. #[inline] pubfn component_mul(self, other: Self) -> Self where
T: Mul<Output = T>,
{
vec3(self.x * other.x, self.y * other.y, self.z * other.z)
}
/// Returns the component-wise division of the two vectors. #[inline] pubfn component_div(self, other: Self) -> Self where
T: Div<Output = T>,
{
vec3(self.x / other.x, self.y / other.y, self.z / other.z)
}
/// Cast this vector into a point. /// /// Equivalent to adding this vector to the origin. #[inline] pubfn to_point(self) -> Point3D<T, U> {
point3(self.x, self.y, self.z)
}
/// Returns a 2d vector using this vector's x and y coordinates #[inline] pubfn xy(self) -> Vector2D<T, U> {
vec2(self.x, self.y)
}
/// Returns a 2d vector using this vector's x and z coordinates #[inline] pubfn xz(self) -> Vector2D<T, U> {
vec2(self.x, self.z)
}
/// Returns a 2d vector using this vector's x and z coordinates #[inline] pubfn yz(self) -> Vector2D<T, U> {
vec2(self.y, self.z)
}
/// Cast into an array with x, y and z. #[inline] pubfn to_array(self) -> [T; 3] {
[self.x, self.y, self.z]
}
/// Cast into an array with x, y, z and 0. #[inline] pubfn to_array_4d(self) -> [T; 4] where
T: Zero,
{
[self.x, self.y, self.z, Zero::zero()]
}
/// Cast into a tuple with x, y and z. #[inline] pubfn to_tuple(self) -> (T, T, T) {
(self.x, self.y, self.z)
}
/// Cast into a tuple with x, y, z and 0. #[inline] pubfn to_tuple_4d(self) -> (T, T, T, T) where
T: Zero,
{
(self.x, self.y, self.z, Zero::zero())
}
/// Drop the units, preserving only the numeric value. #[inline] pubfn to_untyped(self) -> Vector3D<T, UnknownUnit> {
vec3(self.x, self.y, self.z)
}
/// Cast the unit. #[inline] pubfn cast_unit<V>(self) -> Vector3D<T, V> {
vec3(self.x, self.y, self.z)
}
/// Convert into a 2d vector. #[inline] pubfn to_2d(self) -> Vector2D<T, U> { self.xy()
}
/// Rounds each component to the nearest integer value. /// /// This behavior is preserved for negative values (unlike the basic cast). /// /// ```rust /// # use euclid::vec3; /// enum Mm {} /// /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).round(), vec3::<_, Mm>(0.0, -1.0, 0.0)) /// ``` #[inline] #[must_use] pubfn round(self) -> Self where
T: Round,
{
vec3(self.x.round(), self.y.round(), self.z.round())
}
/// Rounds each component to the smallest integer equal or greater than the original value. /// /// This behavior is preserved for negative values (unlike the basic cast). /// /// ```rust /// # use euclid::vec3; /// enum Mm {} /// /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).ceil(), vec3::<_, Mm>(0.0, 0.0, 1.0)) /// ``` #[inline] #[must_use] pubfn ceil(self) -> Self where
T: Ceil,
{
vec3(self.x.ceil(), self.y.ceil(), self.z.ceil())
}
/// Rounds each component to the biggest integer equal or lower than the original value. /// /// This behavior is preserved for negative values (unlike the basic cast). /// /// ```rust /// # use euclid::vec3; /// enum Mm {} /// /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).floor(), vec3::<_, Mm>(-1.0, -1.0, 0.0)) /// ``` #[inline] #[must_use] pubfn floor(self) -> Self where
T: Floor,
{
vec3(self.x.floor(), self.y.floor(), self.z.floor())
}
/// Creates translation by this vector in vector units #[inline] pubfn to_transform(self) -> Transform3D<T, U, U> where
T: Zero + One,
{
Transform3D::translation(self.x, self.y, self.z)
}
}
/// Returns this vector projected onto another one. /// /// Projecting onto a nil vector will cause a division by zero. #[inline] pubfn project_onto_vector(self, onto: Self) -> Self where
T: Sub<T, Output = T> + Div<T, Output = T>,
{
onto * (self.dot(onto) / onto.square_length())
}
}
impl<T: Float, U> Vector3D<T, U> { /// Return the normalized vector even if the length is larger than the max value of Float. #[inline] #[must_use] pubfn robust_normalize(self) -> Self { let length = self.length(); if length.is_infinite() { let scaled = self / T::max_value();
scaled / scaled.length()
} else { self / length
}
}
/// Returns true if all members are finite. #[inline] pubfn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
}
}
impl<T: Real, U> Vector3D<T, U> { /// Returns the positive angle between this vector and another vector. /// /// The returned angle is between 0 and PI. pubfn angle_to(self, other: Self) -> Angle<T> where
T: Trig,
{
Angle::radians(Trig::fast_atan2( self.cross(other).length(), self.dot(other),
))
}
/// Returns the vector length. #[inline] pubfn length(self) -> T { self.square_length().sqrt()
}
/// Returns the vector with length of one unit #[inline] #[must_use] pubfn normalize(self) -> Self { self / self.length()
}
/// Returns the vector with length of one unit. /// /// Unlike [`Vector2D::normalize`](#method.normalize), this returns None in the case that the /// length of the vector is zero. #[inline] #[must_use] pubfn try_normalize(self) -> Option<Self> { let len = self.length(); if len == T::zero() {
None
} else {
Some(self / len)
}
}
/// Return this vector capped to a maximum length. #[inline] pubfn with_max_length(self, max_length: T) -> Self { let square_length = self.square_length(); if square_length > max_length * max_length { returnself * (max_length / square_length.sqrt());
}
self
}
/// Return this vector with a minimum length applied. #[inline] pubfn with_min_length(self, min_length: T) -> Self { let square_length = self.square_length(); if square_length < min_length * min_length { returnself * (min_length / square_length.sqrt());
}
self
}
/// Return this vector with minimum and maximum lengths applied. #[inline] pubfn clamp_length(self, min: T, max: T) -> Self {
debug_assert!(min <= max); self.with_min_length(min).with_max_length(max)
}
}
impl<T, U> Vector3D<T, U> where
T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
{ /// Linearly interpolate each component between this vector and another vector. /// /// # Example /// /// ```rust /// use euclid::vec3; /// use euclid::default::Vector3D; /// /// let from: Vector3D<_> = vec3(0.0, 10.0, -1.0); /// let to: Vector3D<_> = vec3(8.0, -4.0, 0.0); /// /// assert_eq!(from.lerp(to, -1.0), vec3(-8.0, 24.0, -2.0)); /// assert_eq!(from.lerp(to, 0.0), vec3( 0.0, 10.0, -1.0)); /// assert_eq!(from.lerp(to, 0.5), vec3( 4.0, 3.0, -0.5)); /// assert_eq!(from.lerp(to, 1.0), vec3( 8.0, -4.0, 0.0)); /// assert_eq!(from.lerp(to, 2.0), vec3(16.0, -18.0, 1.0)); /// ``` #[inline] pubfn lerp(self, other: Self, t: T) -> Self { let one_t = T::one() - t; self * one_t + other * t
}
/// Returns a reflection vector using an incident ray and a surface normal. #[inline] pubfn reflect(self, normal: Self) -> Self { let two = T::one() + T::one(); self - normal * two * self.dot(normal)
}
}
impl<T: PartialOrd, U> Vector3D<T, U> { /// Returns the vector each component of which are minimum of this vector and another. #[inline] pubfn min(self, other: Self) -> Self {
vec3(
min(self.x, other.x),
min(self.y, other.y),
min(self.z, other.z),
)
}
/// Returns the vector each component of which are maximum of this vector and another. #[inline] pubfn max(self, other: Self) -> Self {
vec3(
max(self.x, other.x),
max(self.y, other.y),
max(self.z, other.z),
)
}
/// Returns the vector each component of which is clamped by corresponding /// components of `start` and `end`. /// /// Shortcut for `self.max(start).min(end)`. #[inline] pubfn clamp(self, start: Self, end: Self) -> Self where
T: Copy,
{ self.max(start).min(end)
}
/// Returns vector with results of "greater than" operation on each component. #[inline] pubfn greater_than(self, other: Self) -> BoolVector3D {
BoolVector3D {
x: self.x > other.x,
y: self.y > other.y,
z: self.z > other.z,
}
}
/// Returns vector with results of "lower than" operation on each component. #[inline] pubfn lower_than(self, other: Self) -> BoolVector3D {
BoolVector3D {
x: self.x < other.x,
y: self.y < other.y,
z: self.z < other.z,
}
}
}
/// Returns vector with results of "not equal" operation on each component. #[inline] pubfn not_equal(self, other: Self) -> BoolVector3D {
BoolVector3D {
x: self.x != other.x,
y: self.y != other.y,
z: self.z != other.z,
}
}
}
impl<T: NumCast + Copy, U> Vector3D<T, U> { /// Cast from one numeric representation to another, preserving the units. /// /// When casting from floating vector to integer coordinates, the decimals are truncated /// as one would expect from a simple cast, but this behavior does not always make sense /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting. #[inline] pubfn cast<NewT: NumCast>(self) -> Vector3D<NewT, U> { self.try_cast().unwrap()
}
/// Fallible cast from one numeric representation to another, preserving the units. /// /// When casting from floating vector to integer coordinates, the decimals are truncated /// as one would expect from a simple cast, but this behavior does not always make sense /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting. pubfn try_cast<NewT: NumCast>(self) -> Option<Vector3D<NewT, U>> { match (
NumCast::from(self.x),
NumCast::from(self.y),
NumCast::from(self.z),
) {
(Some(x), Some(y), Some(z)) => Some(vec3(x, y, z)),
_ => None,
}
}
// Convenience functions for common casts.
/// Cast into an `f32` vector. #[inline] pubfn to_f32(self) -> Vector3D<f32, U> { self.cast()
}
/// Cast into an `f64` vector. #[inline] pubfn to_f64(self) -> Vector3D<f64, U> { self.cast()
}
/// Cast into an `usize` vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_usize(self) -> Vector3D<usize, U> { self.cast()
}
/// Cast into an `u32` vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_u32(self) -> Vector3D<u32, U> { self.cast()
}
/// Cast into an `i32` vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_i32(self) -> Vector3D<i32, U> { self.cast()
}
/// Cast into an `i64` vector, truncating decimals if any. /// /// When casting from floating vector vectors, it is worth considering whether /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain /// the desired conversion behavior. #[inline] pubfn to_i64(self) -> Vector3D<i64, U> { self.cast()
}
}
impl<T: Neg, U> Neg for Vector3D<T, U> { type Output = Vector3D<T::Output, U>;
/// A 2d vector of booleans, useful for component-wise logic operations. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pubstruct BoolVector2D { pub x: bool, pub y: bool,
}
/// A 3d vector of booleans, useful for component-wise logic operations. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pubstruct BoolVector3D { pub x: bool, pub y: bool, pub z: bool,
}
impl BoolVector2D { /// Returns `true` if all components are `true` and `false` otherwise. #[inline] pubfn all(self) -> bool { self.x && self.y
}
/// Returns `true` if any component are `true` and `false` otherwise. #[inline] pubfn any(self) -> bool { self.x || self.y
}
/// Returns `true` if all components are `false` and `false` otherwise. Negation of `any()`. #[inline] pubfn none(self) -> bool {
!self.any()
}
/// Returns new vector with by-component AND operation applied. #[inline] pubfn and(self, other: Self) -> Self {
BoolVector2D {
x: self.x && other.x,
y: self.y && other.y,
}
}
/// Returns new vector with by-component OR operation applied. #[inline] pubfn or(self, other: Self) -> Self {
BoolVector2D {
x: self.x || other.x,
y: self.y || other.y,
}
}
/// Returns new vector with results of negation operation on each component. #[inline] pubfn not(self) -> Self {
BoolVector2D {
x: !self.x,
y: !self.y,
}
}
/// Returns point, each component of which or from `a`, or from `b` depending on truly value /// of corresponding vector component. `true` selects value from `a` and `false` from `b`. #[inline] pubfn select_point<T, U>(self, a: Point2D<T, U>, b: Point2D<T, U>) -> Point2D<T, U> {
point2( ifself.x { a.x } else { b.x }, ifself.y { a.y } else { b.y },
)
}
/// Returns vector, each component of which or from `a`, or from `b` depending on truly value /// of corresponding vector component. `true` selects value from `a` and `false` from `b`. #[inline] pubfn select_vector<T, U>(self, a: Vector2D<T, U>, b: Vector2D<T, U>) -> Vector2D<T, U> {
vec2( ifself.x { a.x } else { b.x }, ifself.y { a.y } else { b.y },
)
}
/// Returns size, each component of which or from `a`, or from `b` depending on truly value /// of corresponding vector component. `true` selects value from `a` and `false` from `b`. #[inline] pubfn select_size<T, U>(self, a: Size2D<T, U>, b: Size2D<T, U>) -> Size2D<T, U> {
size2( ifself.x { a.width } else { b.width }, ifself.y { a.height } else { b.height },
)
}
}
impl BoolVector3D { /// Returns `true` if all components are `true` and `false` otherwise. #[inline] pubfn all(self) -> bool { self.x && self.y && self.z
}
/// Returns `true` if any component are `true` and `false` otherwise. #[inline] pubfn any(self) -> bool { self.x || self.y || self.z
}
/// Returns `true` if all components are `false` and `false` otherwise. Negation of `any()`. #[inline] pubfn none(self) -> bool {
!self.any()
}
/// Returns new vector with results of negation operation on each component. #[inline] pubfn not(self) -> Self {
BoolVector3D {
x: !self.x,
y: !self.y,
z: !self.z,
}
}
/// Returns point, each component of which or from `a`, or from `b` depending on truly value /// of corresponding vector component. `true` selects value from `a` and `false` from `b`. #[inline] pubfn select_point<T, U>(self, a: Point3D<T, U>, b: Point3D<T, U>) -> Point3D<T, U> {
point3( ifself.x { a.x } else { b.x }, ifself.y { a.y } else { b.y }, ifself.z { a.z } else { b.z },
)
}
/// Returns vector, each component of which or from `a`, or from `b` depending on truly value /// of corresponding vector component. `true` selects value from `a` and `false` from `b`. #[inline] pubfn select_vector<T, U>(self, a: Vector3D<T, U>, b: Vector3D<T, U>) -> Vector3D<T, U> {
vec3( ifself.x { a.x } else { b.x }, ifself.y { a.y } else { b.y }, ifself.z { a.z } else { b.z },
)
}
/// Returns size, each component of which or from `a`, or from `b` depending on truly value /// of corresponding vector component. `true` selects value from `a` and `false` from `b`. #[inline] #[must_use] pubfn select_size<T, U>(self, a: Size3D<T, U>, b: Size3D<T, U>) -> Size3D<T, U> {
size3( ifself.x { a.width } else { b.width }, ifself.y { a.height } else { b.height }, ifself.z { a.depth } else { b.depth },
)
}
/// Returns a 2d vector using this vector's x and y coordinates. #[inline] pubfn xy(self) -> BoolVector2D {
BoolVector2D {
x: self.x,
y: self.y,
}
}
/// Returns a 2d vector using this vector's x and z coordinates. #[inline] pubfn xz(self) -> BoolVector2D {
BoolVector2D {
x: self.x,
y: self.z,
}
}
/// Returns a 2d vector using this vector's y and z coordinates. #[inline] pubfn yz(self) -> BoolVector2D {
BoolVector2D {
x: self.y,
y: self.z,
}
}
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.