From 39a7665bf6ae2eb7a26b5a6cf993048daafa5cf9 Mon Sep 17 00:00:00 2001 From: kyle-cochran Date: Thu, 1 Feb 2024 15:51:20 -0800 Subject: [PATCH] fix: normalize the output vector of Polygon::getNormalVector (#106) * fix: normalize the output vector of Polygon::getNormalVector * test: add unit test --- .../Geometry/3D/Objects/Polygon.cpp | 2 +- .../Geometry/3D/Objects/Polygon.test.cpp | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.cpp b/src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.cpp index d48af94d..f1c88756 100644 --- a/src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.cpp +++ b/src/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.cpp @@ -145,7 +145,7 @@ Vector3d Polygon::getNormalVector() const throw ostk::core::error::runtime::Undefined("Polygon"); } - return xAxis_.cross(yAxis_); + return xAxis_.cross(yAxis_).normalized(); } Size Polygon::getEdgeCount() const diff --git a/test/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.test.cpp b/test/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.test.cpp index c6a37d79..2b9c617e 100644 --- a/test/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.test.cpp +++ b/test/OpenSpaceToolkit/Mathematics/Geometry/3D/Objects/Polygon.test.cpp @@ -301,6 +301,8 @@ TEST(OpenSpaceToolkit_Mathematics_Geometry_3D_Objects_Polygon, GetYAxis) TEST(OpenSpaceToolkit_Mathematics_Geometry_3D_Objects_Polygon, GetNormalVector) { + using ostk::core::types::Real; + using ostk::math::object::Vector3d; using Polygon2d = ostk::math::geometry::d2::objects::Polygon; using ostk::math::geometry::d3::objects::Point; @@ -315,6 +317,23 @@ TEST(OpenSpaceToolkit_Mathematics_Geometry_3D_Objects_Polygon, GetNormalVector) EXPECT_EQ(Vector3d(0.0, 0.0, +1.0), Polygon(polygon2d, origin, xAxis, yAxis).getNormalVector()); } + { + const Polygon2d polygon2d = {{{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}, {0.0, 1.0}}}; + const Point origin = {1.0, 2.0, 3.0}; + const Vector3d xAxis = {1.0000000000000006, 0.0, 0.0}; + + const Vector3d yAxis = {0.0, 1.0000000000000006, 0.0}; + + // X and Y axes can be considered unitary while their cross product is not + EXPECT_TRUE( + (xAxis.norm() - 1.0) < Real::Epsilon() && (yAxis.norm() - 1.0) < Real::Epsilon() && + (xAxis.cross(yAxis).norm() - 1.0) > Real::Epsilon() + ); + + // The `getNormalVector` function normalizes the output + EXPECT_TRUE((Polygon(polygon2d, origin, xAxis, yAxis).getNormalVector().norm() - 1.0) < Real::Epsilon()); + } + { EXPECT_ANY_THROW(Polygon::Undefined().getNormalVector()); }