diff --git a/src/Math/Test/VectorTest.cpp b/src/Math/Test/VectorTest.cpp index 38f13c919..0726925ea 100644 --- a/src/Math/Test/VectorTest.cpp +++ b/src/Math/Test/VectorTest.cpp @@ -93,6 +93,10 @@ void VectorTest::length() { QCOMPARE(Vector4(1.0f, 2.0f, 3.0f, 4.0f).length(), 5.4772256f); } +void VectorTest::lengthSquared() { + QCOMPARE(Vector4(1.0f, 2.0f, 3.0f, 4.0f).lengthSquared(), 30.0f); +} + void VectorTest::normalized() { QVERIFY(Vector4(1.0f, 1.0f, 1.0f, 1.0f).normalized() == Vector4(0.5f, 0.5f, 0.5f, 0.5f)); } diff --git a/src/Math/Test/VectorTest.h b/src/Math/Test/VectorTest.h index 70c7222e3..143ea01a3 100644 --- a/src/Math/Test/VectorTest.h +++ b/src/Math/Test/VectorTest.h @@ -30,6 +30,7 @@ class VectorTest: public QObject { void multiplyDivide(); void addSubstract(); void length(); + void lengthSquared(); void normalized(); void product(); void angle(); diff --git a/src/Math/Vector.h b/src/Math/Vector.h index 66a88f8f7..11fa9da49 100644 --- a/src/Math/Vector.h +++ b/src/Math/Vector.h @@ -218,11 +218,27 @@ template class Vector { return out; } - /** @brief %Vector length */ + /** + * @brief %Vector length + * + * @see lengthSquared() + */ inline T length() const { return sqrt(dot(*this, *this)); } + /** + * @brief %Vector length squared + * + * More efficient than length() for comparing vector length with + * other values, because it doesn't compute the square root, just the + * dot product: @f$ a \cdot a < length \cdot length @f$ is faster + * than @f$ \sqrt{a \cdot a} < length @f$. + */ + inline T lengthSquared() const { + return dot(*this, *this); + } + /** @brief Normalized vector (of length 1) */ inline Vector normalized() const { return *this/length();