From cfb15613b19a1b5109a5d9668d784909519b0a18 Mon Sep 17 00:00:00 2001 From: Danny McGee Date: Wed, 18 Oct 2023 00:59:37 -0400 Subject: [PATCH] Allow specified tolerance for `NearlyEq` checks --- studio/src/interaction/gizmos/controller.rs | 2 +- studio/src/math/util.rs | 30 ++++++++++++++++----- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/studio/src/interaction/gizmos/controller.rs b/studio/src/interaction/gizmos/controller.rs index 15cd881..5657574 100644 --- a/studio/src/interaction/gizmos/controller.rs +++ b/studio/src/interaction/gizmos/controller.rs @@ -161,7 +161,7 @@ impl From for SphericalCoords { } let pitch = f32::asin(-y / radius); - let heading = if (pitch - 90_f32.to_radians()).abs() < 1e-3_f32 { + let heading = if pitch.nearly_eq_within(90_f32.to_radians(), 1e-3) { 0. } else { f32::atan2(x, z) diff --git a/studio/src/math/util.rs b/studio/src/math/util.rs index c7dafe2..c7a5e19 100644 --- a/studio/src/math/util.rs +++ b/studio/src/math/util.rs @@ -1,17 +1,33 @@ use bevy::prelude::Vec3; -pub trait NearlyEq { - fn nearly_eq(self, rhs: Rhs) -> bool; +pub trait NearlyEq { + const DEFAULT_TOLERANCE: Tolerance; + + #[inline] + fn nearly_eq(self, rhs: Rhs) -> bool + where + Self: Sized, + { + self.nearly_eq_within(rhs, Self::DEFAULT_TOLERANCE) + } + + fn nearly_eq_within(self, rhs: Rhs, tolerance: Tolerance) -> bool; } impl NearlyEq for f32 { - fn nearly_eq(self, rhs: f32) -> bool { - (self - rhs).abs() < Self::EPSILON + const DEFAULT_TOLERANCE: f32 = f32::EPSILON; + + fn nearly_eq_within(self, rhs: f32, tolerance: f32) -> bool { + (self - rhs).abs() < tolerance } } -impl NearlyEq for Vec3 { - fn nearly_eq(self, rhs: Vec3) -> bool { - self.x.nearly_eq(rhs.x) && self.y.nearly_eq(rhs.y) && self.z.nearly_eq(rhs.z) +impl NearlyEq for Vec3 { + const DEFAULT_TOLERANCE: f32 = >::DEFAULT_TOLERANCE; + + fn nearly_eq_within(self, rhs: Vec3, tolerance: f32) -> bool { + self.x.nearly_eq_within(rhs.x, tolerance) + && self.y.nearly_eq_within(rhs.y, tolerance) + && self.z.nearly_eq_within(rhs.z, tolerance) } }