Skip to content

Commit

Permalink
Remove From implementations from the direction types (#10857)
Browse files Browse the repository at this point in the history
This removes the `From<Vec2/3>` implementations for the direction types.
It doesn't seem right to have when it only works if the vector is
nonzero and finite and produces NaN otherwise.

Added `Direction2d/3d::new` which uses `Vec2/3::try_normalize` to
guarantee it returns either a valid direction or `None`.

This should make it impossible to create an invalid direction, which I
think was the intention with these types.
  • Loading branch information
tim-blackbird authored Dec 5, 2023
1 parent 2c5639e commit 83ee6de
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
11 changes: 6 additions & 5 deletions crates/bevy_math/src/primitives/dim2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ use crate::Vec2;
#[derive(Clone, Copy, Debug)]
pub struct Direction2d(Vec2);

impl From<Vec2> for Direction2d {
fn from(value: Vec2) -> Self {
Self(value.normalize())
impl Direction2d {
/// Create a direction from a finite, nonzero [`Vec2`].
///
/// Returns `None` if the input is zero (or very close to zero), or non-finite.
pub fn new(value: Vec2) -> Option<Self> {
value.try_normalize().map(Self)
}
}

impl Direction2d {
/// Create a direction from a [`Vec2`] that is already normalized
pub fn from_normalized(value: Vec2) -> Self {
debug_assert!(value.is_normalized());
Expand Down
11 changes: 6 additions & 5 deletions crates/bevy_math/src/primitives/dim3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ use crate::Vec3;
#[derive(Clone, Copy, Debug)]
pub struct Direction3d(Vec3);

impl From<Vec3> for Direction3d {
fn from(value: Vec3) -> Self {
Self(value.normalize())
impl Direction3d {
/// Create a direction from a finite, nonzero [`Vec3`].
///
/// Returns `None` if the input is zero (or very close to zero), or non-finite.
pub fn new(value: Vec3) -> Option<Self> {
value.try_normalize().map(Self)
}
}

impl Direction3d {
/// Create a direction from a [`Vec3`] that is already normalized
pub fn from_normalized(value: Vec3) -> Self {
debug_assert!(value.is_normalized());
Expand Down

0 comments on commit 83ee6de

Please sign in to comment.