From c7e0d83587ebd18e8b870669db8e17aa69a5b6ea Mon Sep 17 00:00:00 2001 From: Nathan Bowhay Date: Tue, 3 Feb 2015 12:13:06 -0800 Subject: [PATCH] Fixed possible divide by zero issues. Fixed several areas in the point class that could have a divide by zero issue. --- Engine/source/math/mPoint3.h | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/Engine/source/math/mPoint3.h b/Engine/source/math/mPoint3.h index 5a85c6cd0..8ba244767 100644 --- a/Engine/source/math/mPoint3.h +++ b/Engine/source/math/mPoint3.h @@ -233,11 +233,13 @@ class Point3D bool isZero() const; F64 len() const; F64 lenSquared() const; + F64 magnitudeSafe() const; //-------------------------------------- Mathematical mutators public: void neg(); void normalize(); + void normalizeSafe(); void normalize(F64 val); void convolve(const Point3D&); void convolveInverse(const Point3D&); @@ -728,11 +730,13 @@ inline Point3F& Point3F::operator*=(const Point3F &_vec) inline Point3F Point3F::operator/(const Point3F &_vec) const { + AssertFatal(_vec.x != 0.0f && _vec.y != 0.0f && _vec.z != 0.0f, "Error, div by zero attempted"); return Point3F(x / _vec.x, y / _vec.y, z / _vec.z); } inline Point3F& Point3F::operator/=(const Point3F &_vec) { + AssertFatal(_vec.x != 0.0f && _vec.y != 0.0f && _vec.z != 0.0f, "Error, div by zero attempted"); x /= _vec.x; y /= _vec.y; z /= _vec.z; @@ -855,7 +859,8 @@ inline F64 Point3D::lenSquared() const inline F64 Point3D::len() const { - return mSqrtD(x*x + y*y + z*z); + F64 temp = x*x + y*y + z*z; + return (temp > 0.0) ? mSqrtD(x*x + y*y + z*z) : 0.0; } inline void Point3D::normalize() @@ -863,6 +868,28 @@ inline void Point3D::normalize() m_point3D_normalize(*this); } +inline F64 Point3D::magnitudeSafe() const +{ + if( isZero() ) + { + return 0.0; + } + else + { + return len(); + } +} + +inline void Point3D::normalizeSafe() +{ + F64 vmag = magnitudeSafe(); + + if( vmag > POINT_EPSILON ) + { + *this *= F64(1.0 / vmag); + } +} + inline void Point3D::normalize(F64 val) { m_point3D_normalize_f(*this, val);