Skip to content

Commit

Permalink
Test (and slight refactor) of Vector3 normalisation
Browse files Browse the repository at this point in the history
getNormalised() now implemented in terms of normalise(), rather than separate
code. normalise() now returns the underlying BasicVector3 Element type rather
than coercing everything to float (this would break if we had any
BasicVector3<int> classes and wanted to normalise them, but we don't).
  • Loading branch information
Matthew Mott committed Apr 2, 2021
1 parent 2f7ebf6 commit ac918cb
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
26 changes: 14 additions & 12 deletions libs/math/Vector3.h
Expand Up @@ -260,21 +260,15 @@ class BasicVector3
}

/**
* Return a new BasicVector3 equivalent to the normalised version of this
* BasicVector3 (scaled by the inverse of its size)
*/
BasicVector3<Element> getNormalised() const {
return (*this)/getLength();
}
* \brief Normalise this vector in-place by scaling by the inverse of its
* size.
/**
* Normalise this vector in-place by scaling by the inverse of its size.
* Returns the length it had before normalisation.
* \return The length of the vector before normalisation.
*/
float normalise()
Element normalise()
{
float length = getLength();
float inverseLength = 1/length;
Element length = getLength();
Element inverseLength = 1/length;

_v[0] *= inverseLength;
_v[1] *= inverseLength;
Expand All @@ -283,6 +277,14 @@ class BasicVector3
return length;
}

/// Return the result of normalising this vector
BasicVector3<Element> getNormalised() const
{
BasicVector3<Element> copy = *this;
copy.normalise();
return copy;
}

// Returns a vector with the reciprocal values of each component
BasicVector3<Element> getInversed() {
return BasicVector3<Element>(
Expand Down
14 changes: 14 additions & 0 deletions test/math/Vector3.cpp
Expand Up @@ -38,6 +38,20 @@ TEST(MathTest, VectorLength)
EXPECT_NEAR(v3.getLength(), sqrt(3*3 + 4*4 + 5*5), 1E-6);
}

TEST(MathTest, NormaliseVector3)
{
Vector3 v(10, 5, 4);
Vector3 vN = v.getNormalised();

// getNormalised should return correct result and not change the original
EXPECT_EQ(vN, v * 1.0/v.getLength());
EXPECT_NE(vN, v);

// Normalise in place gives same result
v.normalise();
EXPECT_EQ(v, vN);
}

TEST(MathTest, Vector3IsPacked)
{
Vector3 vec(256, -10, 10000);
Expand Down

0 comments on commit ac918cb

Please sign in to comment.