keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NURBSCircle.h
.h
5,350
144
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/NURBSCurve.h> // The algorithm for representing a circle as a NURBS curve or a sphere as a // NURBS surface is described in // https://www.geometrictools.com/Documentation/NURBSCircleSphere.pdf // The implementations are related to the documents as shown next. // NURBSQuarterCircleDegree2 implements equation (9) // NURBSQuarterCircleDegree4 implements equation (10) // NURBSHalfCircleDegree3 implements equation (12) // NURBSFullCircleDegree3 implements Section 2.3 namespace gte { template <typename Real> class NURBSQuarterCircleDegree2 : public NURBSCurve<2, Real> { public: // Construction. The quarter circle is x^2 + y^2 = 1 for x >= 0 // and y >= 0. The direction of traversal is counterclockwise as // u increase from 0 to 1. NURBSQuarterCircleDegree2() : NURBSCurve<2, Real>(BasisFunctionInput<Real>(3, 2), nullptr, nullptr) { Real const sqrt2 = std::sqrt((Real)2); this->mWeights[0] = sqrt2; this->mWeights[1] = (Real)1; this->mWeights[2] = sqrt2; this->mControls[0] = { (Real)1, (Real)0 }; this->mControls[1] = { (Real)1, (Real)1 }; this->mControls[2] = { (Real)0, (Real)1 }; } }; template <typename Real> class NURBSQuarterCircleDegree4 : public NURBSCurve<2, Real> { public: // Construction. The quarter circle is x^2 + y^2 = 1 for x >= 0 // and y >= 0. The direction of traversal is counterclockwise as // u increases from 0 to 1. NURBSQuarterCircleDegree4() : NURBSCurve<2, Real>(BasisFunctionInput<Real>(5, 4), nullptr, nullptr) { Real const sqrt2 = std::sqrt((Real)2); this->mWeights[0] = (Real)1; this->mWeights[1] = (Real)1; this->mWeights[2] = (Real)2 * sqrt2 / (Real)3; this->mWeights[3] = (Real)1; this->mWeights[4] = (Real)1; Real const x1 = (Real)1; Real const y1 = (Real)0.5 / sqrt2; Real const x2 = (Real)1 - sqrt2 / (Real)8; this->mControls[0] = { (Real)1, (Real)0 }; this->mControls[1] = { x1, y1 }; this->mControls[2] = { x2, x2 }; this->mControls[3] = { y1, x1 }; this->mControls[4] = { (Real)0, (Real)1 }; } }; template <typename Real> class NURBSHalfCircleDegree3 : public NURBSCurve<2, Real> { public: // Construction. The half circle is x^2 + y^2 = 1 for x >= 0. The // direction of traversal is counterclockwise as u increases from // 0 to 1. NURBSHalfCircleDegree3() : NURBSCurve<2, Real>(BasisFunctionInput<Real>(4, 3), nullptr, nullptr) { Real const oneThird = (Real)1 / (Real)3; this->mWeights[0] = (Real)1; this->mWeights[1] = oneThird; this->mWeights[2] = oneThird; this->mWeights[3] = (Real)1; this->mControls[0] = { (Real)1, (Real)0 }; this->mControls[1] = { (Real)1, (Real)2 }; this->mControls[2] = { (Real)-1, (Real)2 }; this->mControls[3] = { (Real)-1, (Real)0 }; } }; template <typename Real> class NURBSFullCircleDegree3 : public NURBSCurve<2, Real> { public: // Construction. The full circle is x^2 + y^2 = 1. The direction of // traversal is counterclockwise as u increases from 0 to 1. NURBSFullCircleDegree3() : NURBSCurve<2, Real>(CreateBasisFunctionInput(), nullptr, nullptr) { Real const oneThird = (Real)1 / (Real)3; this->mWeights[0] = (Real)1; this->mWeights[1] = oneThird; this->mWeights[2] = oneThird; this->mWeights[3] = (Real)1; this->mWeights[4] = oneThird; this->mWeights[5] = oneThird; this->mWeights[6] = (Real)1; this->mControls[0] = { (Real)1, (Real)0 }; this->mControls[1] = { (Real)1, (Real)2 }; this->mControls[2] = { (Real)-1, (Real)2 }; this->mControls[3] = { (Real)-1, (Real)0 }; this->mControls[4] = { (Real)-1, (Real)-2 }; this->mControls[5] = { (Real)1, (Real)-2 }; this->mControls[6] = { (Real)1, (Real)0 }; } private: static BasisFunctionInput<Real> CreateBasisFunctionInput() { // We need knots (0,0,0,0,1/2,1/2,1/2,1,1,1,1). BasisFunctionInput<Real> input; input.numControls = 7; input.degree = 3; input.uniform = true; input.periodic = false; input.numUniqueKnots = 3; input.uniqueKnots.resize(input.numUniqueKnots); input.uniqueKnots[0] = { (Real)0, 4 }; input.uniqueKnots[1] = { (Real)0.5, 3 }; input.uniqueKnots[2] = { (Real)1, 4 }; return input; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay2Ray2.h
.h
9,336
243
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.25 #pragma once #include <Mathematics/IntrLine2Line2.h> #include <Mathematics/Ray.h> namespace gte { template <typename T> class TIQuery<T, Ray2<T>, Ray2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0) { } // The number is 0 (no intersection), 1 (rays intersect in a // single point), 2 (rays are collinear and intersect in a // segment; ray directions are opposite of each other), or // std::numeric_limits<int32_t>::max() (intersection is a ray; ray // directions are the same). bool intersect; int32_t numIntersections; }; Result operator()(Ray2<T> const& ray0, Ray2<T> const& ray1) { Result result{}; T const zero = static_cast<T>(0); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> line0(ray0.origin, ray0.direction); Line2<T> line1(ray1.origin, ray1.direction); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the rays. if (llResult.line0Parameter[0] >= zero && llResult.line1Parameter[0] >= zero) { result.intersect = true; result.numIntersections = 1; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { if (Dot(ray0.direction, ray1.direction) > zero) { // The rays are collinear and in the same direction, so // they must overlap. result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); } else { // The rays are collinear but in opposite directions. // Test whether they overlap. Ray0 has interval // [0,+infinity) and ray1 has interval (-infinity,t] // relative to ray0.direction. Vector2<T> diff = ray1.origin - ray0.origin; T t = Dot(ray0.direction, diff); if (t > zero) { result.intersect = true; result.numIntersections = 2; } else if (t < zero) { result.intersect = false; result.numIntersections = 0; } else // t == 0 { result.intersect = true; result.numIntersections = 1; } } } else { result.intersect = false; result.numIntersections = 0; } return result; } }; template <typename T> class FIQuery<T, Ray2<T>, Ray2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), ray0Parameter{ static_cast<T>(0), static_cast<T>(0) }, ray1Parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector2<T>::Zero(), Vector2<T>::Zero() } { } // The number is 0 (no intersection), 1 (rays intersect in a // single point), 2 (rays are collinear and intersect in a // segment; ray directions are opposite of each other), or // std::numeric_limits<int32_t>::max() (intersection is a ray; ray // directions are the same). bool intersect; int32_t numIntersections; // If numIntersections is 1, the intersection is // point[0] = ray0.origin + ray0Parameter[0] * ray0.direction // = ray1.origin + ray1Parameter[0] * ray1.direction // If numIntersections is 2, the segment of intersection is formed // by the ray origins, // ray0Parameter[0] = ray1Parameter[0] = 0 // point[0] = ray0.origin // = ray1.origin + ray1Parameter[1] * ray1.direction // point[1] = ray1.origin // = ray0.origin + ray0Parameter[1] * ray0.direction // where ray0Parameter[1] >= 0 and ray1Parameter[1] >= 0. // If numIntersections is maxInt, let // ray1.origin = ray0.origin + t * ray0.direction // then // ray0Parameter[] = { max(t,0), +maxReal } // ray1Parameter[] = { -min(t,0), +maxReal } // point[0] = ray0.origin + ray0Parameter[0] * ray0.direction std::array<T, 2> ray0Parameter, ray1Parameter; std::array<Vector2<T>, 2> point; }; Result operator()(Ray2<T> const& ray0, Ray2<T> const& ray1) { Result result{}; T const zero = static_cast<T>(0); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> line0(ray0.origin, ray0.direction); Line2<T> line1(ray1.origin, ray1.direction); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the rays. if (llResult.line0Parameter[0] >= zero && llResult.line1Parameter[0] >= zero) { result.intersect = true; result.numIntersections = 1; result.ray0Parameter[0] = llResult.line0Parameter[0]; result.ray1Parameter[0] = llResult.line1Parameter[0]; result.point[0] = llResult.point; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { // Compute t for which ray1.origin = // ray0.origin + t*ray0.direction. T maxReal = std::numeric_limits<T>::max(); Vector2<T> diff = ray1.origin - ray0.origin; T t = Dot(ray0.direction, diff); if (Dot(ray0.direction, ray1.direction) > zero) { // The rays are collinear and in the same direction, so // they must overlap. result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); if (t >= zero) { result.ray0Parameter[0] = t; result.ray0Parameter[1] = maxReal; result.ray1Parameter[0] = zero; result.ray1Parameter[1] = maxReal; result.point[0] = ray1.origin; } else { result.ray0Parameter[0] = zero; result.ray0Parameter[1] = maxReal; result.ray1Parameter[0] = -t; result.ray1Parameter[1] = maxReal; result.point[0] = ray0.origin; } } else { // The rays are collinear but in opposite directions. // Test whether they overlap. Ray0 has interval // [0,+infinity) and ray1 has interval (-infinity,t1] // relative to ray0.direction. if (t >= zero) { result.intersect = true; result.numIntersections = 2; result.ray0Parameter[0] = zero; result.ray0Parameter[1] = t; result.ray1Parameter[0] = zero; result.ray1Parameter[1] = t; result.point[0] = ray0.origin; result.point[1] = ray1.origin; } else { result.intersect = false; result.numIntersections = 0; } } } else { result.intersect = false; result.numIntersections = 0; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment2Segment2.h
.h
17,311
412
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.25 #pragma once #include <Mathematics/Segment.h> #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine2Line2.h> namespace gte { template <typename T> class TIQuery<T, Segment2<T>, Segment2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0) { } // The number is 0 (no intersection), 1 (segments intersect in a // single point), or 2 (segments are collinear and intersect in a // segment). bool intersect; int32_t numIntersections; }; // This version of the query uses Segment3<T>::GetCenteredForm, which // has a Normalize call. This generates rounding errors, so the query // should be used only with float or double. Result operator()(Segment2<T> const& segment0, Segment2<T> const& segment1) { Result result{}; Vector2<T> seg0Origin{}, seg0Direction{}, seg1Origin{}, seg1Direction{}; T seg0Extent{}, seg1Extent{}; segment0.GetCenteredForm(seg0Origin, seg0Direction, seg0Extent); segment1.GetCenteredForm(seg1Origin, seg1Direction, seg1Extent); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> line0(seg0Origin, seg0Direction); Line2<T> line1(seg1Origin, seg1Direction); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the segments. if (std::fabs(llResult.line0Parameter[0]) <= seg0Extent && std::fabs(llResult.line1Parameter[0]) <= seg1Extent) { result.intersect = true; result.numIntersections = 1; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { // Compute the location of segment1 endpoints relative to // segment0. Vector2<T> diff = seg1Origin - seg0Origin; T t = Dot(seg0Direction, diff); // Get the parameter intervals of the segments relative to // segment0. std::array<T, 2> interval0 = { -seg0Extent, seg0Extent }; std::array<T, 2> interval1 = { t - seg1Extent, t + seg1Extent }; // Compute the intersection of the intervals. FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery; auto iiResult = iiQuery(interval0, interval1); result.intersect = iiResult.intersect; result.numIntersections = iiResult.numIntersections; } else { result.intersect = false; result.numIntersections = 0; } return result; } // This version of the query supports rational arithmetic. Result Exact(Segment2<T> const& segment0, Segment2<T> const& segment1) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Vector2<T> seg0Direction = segment0.p[1] - segment0.p[0]; Vector2<T> seg1Direction = segment1.p[1] - segment1.p[0]; Line2<T> line0(segment0.p[0], seg0Direction); Line2<T> line1(segment1.p[0], seg1Direction); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // The lines are not parallel, so they intersect in a single // point. Test whether the line-line intersection is on the // segments. if (zero <= llResult.line0Parameter[0] && llResult.line0Parameter[1] <= one && zero <= llResult.line1Parameter[0] && llResult.line1Parameter[1] <= one) { result.intersect = true; result.numIntersections = 1; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { // The lines are the same. Compute the location of segment1 // endpoints relative to segment0. T dotD0D0 = Dot(seg0Direction, seg0Direction); Vector2<T> diff = segment1.p[0] - segment0.p[0]; T t0 = Dot(seg0Direction, diff) / dotD0D0; diff = segment1.p[1] - segment0.p[0]; T t1 = Dot(seg0Direction, diff) / dotD0D0; // Get the parameter intervals of the segments relative to // segment0. std::array<T, 2> interval0 = { zero, one }; std::array<T, 2> interval1{}; if (t1 >= t0) { interval1[0] = t0; interval1[1] = t1; } else { interval1[0] = t1; interval1[1] = t0; } // Compute the intersection of the intervals. FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; auto iiResult = iiQuery(interval0, interval1); result.intersect = iiResult.intersect; result.numIntersections = iiResult.numIntersections; } else { // The lines are parallel but not the same, so the segments // cannot intersect. result.intersect = false; result.numIntersections = 0; } return result; } }; template <typename T> class FIQuery<T, Segment2<T>, Segment2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), segment0Parameter{ static_cast<T>(0), static_cast<T>(0) }, segment1Parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector2<T>::Zero(), Vector2<T>::Zero() } { } // The number is 0 (no intersection), 1 (segments intersect in a // a single point), or 2 (segments are collinear and intersect // in a segment). bool intersect; int32_t numIntersections; // If numIntersections is 1, the intersection is // point[0] // = segment0.origin + segment0Parameter[0] * segment0.direction // = segment1.origin + segment1Parameter[0] * segment1.direction // If numIntersections is 2, the endpoints of the segment of // intersection are // point[i] // = segment0.origin + segment0Parameter[i] * segment0.direction // = segment1.origin + segment1Parameter[i] * segment1.direction // with segment0Parameter[0] <= segment0Parameter[1] and // segment1Parameter[0] <= segment1Parameter[1]. std::array<T, 2> segment0Parameter, segment1Parameter; std::array<Vector2<T>, 2> point; }; // This version of the query uses Segment3<T>::GetCenteredForm, which // has a Normalize call. This generates rounding errors, so the query // should be used only with float or double. NOTE: The parameters are // are relative to the centered form of the segment. Each segment has // a center C, a unit-length direction D and an extent e > 0. A // segment point is C+t*D where |t| <= e. Result operator()(Segment2<T> const& segment0, Segment2<T> const& segment1) { Result result{}; Vector2<T> seg0Origin{}, seg0Direction{}, seg1Origin{}, seg1Direction{}; T seg0Extent{}, seg1Extent{}; segment0.GetCenteredForm(seg0Origin, seg0Direction, seg0Extent); segment1.GetCenteredForm(seg1Origin, seg1Direction, seg1Extent); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> line0(seg0Origin, seg0Direction); Line2<T> line1(seg1Origin, seg1Direction); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the segments. if (std::fabs(llResult.line0Parameter[0]) <= seg0Extent && std::fabs(llResult.line1Parameter[0]) <= seg1Extent) { result.intersect = true; result.numIntersections = 1; result.segment0Parameter[0] = llResult.line0Parameter[0]; result.segment0Parameter[1] = result.segment0Parameter[0]; result.segment1Parameter[0] = llResult.line1Parameter[0]; result.segment1Parameter[1] = result.segment1Parameter[0]; result.point[0] = llResult.point; result.point[1] = result.point[0]; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { // Compute the location of segment1 endpoints relative to // segment0. Vector2<T> diff = seg1Origin - seg0Origin; T t = Dot(seg0Direction, diff); // Get the parameter intervals of the segments relative to // segment0. std::array<T, 2> interval0 = { -seg0Extent, seg0Extent }; std::array<T, 2> interval1 = { t - seg1Extent, t + seg1Extent }; // Compute the intersection of the intervals. FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery; auto iiResult = iiQuery(interval0, interval1); if (iiResult.intersect) { result.intersect = true; result.numIntersections = iiResult.numIntersections; for (int32_t i = 0; i < iiResult.numIntersections; ++i) { result.segment0Parameter[i] = iiResult.overlap[i]; result.segment1Parameter[i] = iiResult.overlap[i] - t; result.point[i] = seg0Origin + result.segment0Parameter[i] * seg0Direction; } if (iiResult.numIntersections == 1) { result.segment0Parameter[1] = result.segment0Parameter[0]; result.segment1Parameter[1] = result.segment1Parameter[0]; result.point[1] = result.point[0]; } } else { result.intersect = false; result.numIntersections = 0; } } else { result.intersect = false; result.numIntersections = 0; } return result; } // This version of the query supports rational arithmetic. NOTE: The // parameters are relative to the endpoint form of the segment. Each // segment has endpoints P0 and P1. A segment point is P0+t*(P1-P0) // where 0 <= t <= 1. Result Exact(Segment2<T> const& segment0, Segment2<T> const& segment1) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Vector2<T> seg0Direction = segment0.p[1] - segment0.p[0]; Vector2<T> seg1Direction = segment1.p[1] - segment1.p[0]; Line2<T> line0(segment0.p[0], seg0Direction); Line2<T> line1(segment1.p[0], seg1Direction); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // The lines are not parallel, so they intersect in a single // point. Test whether the line-line intersection is on the // segments. if (zero <= llResult.line0Parameter[0] && llResult.line0Parameter[1] <= one && zero <= llResult.line1Parameter[0] && llResult.line1Parameter[1] <= one) { result.intersect = true; result.numIntersections = 1; result.segment0Parameter[0] = llResult.line0Parameter[0]; result.segment0Parameter[1] = result.segment0Parameter[0]; result.segment1Parameter[0] = llResult.line1Parameter[0]; result.segment1Parameter[1] = result.segment1Parameter[0]; result.point[0] = llResult.point; result.point[1] = result.point[0]; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { // The lines are the same. Compute the location of segment1 // endpoints relative to segment0. T dotD0D0 = Dot(seg0Direction, seg0Direction); Vector2<T> diff = segment1.p[0] - segment0.p[0]; T t0 = Dot(seg0Direction, diff) / dotD0D0; diff = segment1.p[1] - segment0.p[0]; T t1 = Dot(seg0Direction, diff) / dotD0D0; // Get the parameter intervals of the segments relative to // segment0. std::array<T, 2> interval0 = { zero, one }; std::array<T, 2> interval1{}; if (t1 >= t0) { interval1[0] = t0; interval1[1] = t1; } else { interval1[0] = t1; interval1[1] = t0; } // Compute the intersection of the intervals. FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; auto iiResult = iiQuery(interval0, interval1); if (iiResult.intersect) { result.intersect = true; result.numIntersections = iiResult.numIntersections; // Compute the results for segment0. for (int32_t i = 0; i < iiResult.numIntersections; ++i) { result.segment0Parameter[i] = iiResult.overlap[i]; result.point[i] = segment0.p[0] + result.segment0Parameter[i] * seg0Direction; } // Compute the results for segment1. The interval1 was // computed relative to segment0, so we have to reverse // the process to obtain the parameters. T dotD1D1 = Dot(seg1Direction, seg1Direction); for (int32_t i = 0; i < iiResult.numIntersections; ++i) { diff = result.point[i] - segment1.p[0]; result.segment1Parameter[i] = Dot(seg1Direction, diff) / dotD1D1; } if (iiResult.numIntersections == 1) { result.segment0Parameter[1] = result.segment0Parameter[0]; result.segment1Parameter[1] = result.segment1Parameter[0]; result.point[1] = result.point[0]; } else { if (t1 < t0) { std::swap( result.segment1Parameter[0], result.segment1Parameter[1]); } } } else { result.intersect = false; result.numIntersections = 0; } } else { result.intersect = false; result.numIntersections = 0; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprEllipsoid3.h
.h
13,145
327
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once // An ellipsoid is defined implicitly by (X-C)^T * M * (X-C) = 1, where C is // the center, M is a positive definite matrix and X is any point on the // ellipsoid. The code implements a nonlinear least-squares fitting algorithm // for the error function // F(C,M) = sum_{i=0}^{n-1} ((X[i] - C)^T * M * (X[i] - C) - 1)^2 // for n data points X[0] through X[n-1]. An Ellipsoid3<Real> object has // member 'center' that corresponds to C. It also has axes with unit-length // directions 'axis[]' and corresponding axis half-lengths 'extent[]'. The // matrix is M = sum_{i=0}^2 axis[i] * axis[i]^T / extent[i]^2, where axis[i] // is a 3x1 vector and axis[i]^T is a 1x3 vector. // // The minimizer uses a 2-step gradient descent algorithm. // // Given the current (C,M), locate a minimum of // G(t) = F(C - t * dF(C,M)/dC, M) // for t > 0. The function G(t) >= 0 is a polynomial of degree 4 with // derivative G'(t) that is a polynomial of degree 3. G'(t) must have a // positive root because G(0) > 0 and G'(0) < 0 and the G-coefficient of t^4 // is positive. The positive root that T produces the smallest G-value is used // to update the center C' = C - T * dF/dC(C,M). // // Given the current (C,M), locate a minimum of // H(t) = F(C, M - t * dF(C,M)/dM) // for t > 0. The function H(t) >= 0 is a polynomial of degree 2 with // derivative H'(t) that is a polynomial of degree 1. H'(t) must have a // positive root because H(0) > 0 and H'(0) < 0 and the H-coefficient of t^2 // is positive. The positive root T that produces the smallest G-value is used // to update the matrix M' = M - T * dF/dC(C,M) as long as M' is positive // definite. If M' is not positive definite, the root is halved for a finite // number of steps until M' is positive definite. #include <Mathematics/ContOrientedBox3.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/RootsPolynomial.h> namespace gte { template <typename Real> class ApprEllipsoid3 { public: // If you want this function to compute the initial guess for the // ellipsoid, set 'useEllipsoidForInitialGuess' to true. An oriented // bounding box containing the points is used to start the minimizer. // Set 'useEllipsoidForInitialGuess' to true if you want the initial // guess to be the input ellipsoid. This is useful if you want to // repeat the query. The returned 'Real' value is the error function // value for the output 'ellisoid'. Real operator()(std::vector<Vector3<Real>> const& points, size_t numIterations, bool useEllipsoidForInitialGuess, Ellipsoid3<Real>& ellipsoid) { Vector3<Real> C; Matrix3x3<Real> M; // the zero matrix if (useEllipsoidForInitialGuess) { C = ellipsoid.center; for (int32_t i = 0; i < 3; ++i) { auto product = OuterProduct(ellipsoid.axis[i], ellipsoid.axis[i]); M += product / (ellipsoid.extent[i] * ellipsoid.extent[i]); } } else { OrientedBox3<Real> box; GetContainer(static_cast<int32_t>(points.size()), points.data(), box); C = box.center; for (int32_t i = 0; i < 3; ++i) { auto product = OuterProduct(box.axis[i], box.axis[i]); M += product / (box.extent[i] * box.extent[i]); } } Real error = ErrorFunction(points, C, M); for (size_t i = 0; i < numIterations; ++i) { error = UpdateMatrix(points, C, M); error = UpdateCenter(points, M, C); } // Extract the ellipsoid axes and extents. SymmetricEigensolver3x3<Real> solver; std::array<Real, 3> eval; std::array<std::array<Real, 3>, 3> evec; solver(M(0, 0), M(0, 1), M(0, 2), M(1, 1), M(1, 2), M(2, 2), true, +1, eval, evec); Real const one = static_cast<Real>(1); ellipsoid.center = C; for (int32_t i = 0; i < 3; ++i) { ellipsoid.axis[i] = { evec[i][0], evec[i][1], evec[i][2] }; ellipsoid.extent[i] = one / std::sqrt(eval[i]); } return error; } private: Real UpdateCenter(std::vector<Vector3<Real>> const& points, Matrix3x3<Real> const& M, Vector3<Real>& C) { Real const zero = static_cast<Real>(0); Real const one = static_cast<Real>(1); Real const two = static_cast<Real>(2); Real const three = static_cast<Real>(3); Real const four = static_cast<Real>(4); Real const epsilon = static_cast<Real>(1e-06); std::vector<Vector3<Real>> MDelta(points.size()); std::vector<Real> a(points.size()); Real invQuantity = one / static_cast<Real>(points.size()); Vector3<Real> negDFDC = Vector3<Real>::Zero(); Real aMean = zero, aaMean = zero; for (size_t i = 0; i < points.size(); ++i) { Vector3<Real> Delta = points[i] - C; MDelta[i] = M * Delta; a[i] = Dot(Delta, MDelta[i]) - one; aMean += a[i]; aaMean += a[i] * a[i]; negDFDC += a[i] * MDelta[i]; } aMean *= invQuantity; aaMean *= invQuantity; if (Normalize(negDFDC) < epsilon) { return aaMean; } Real bMean = zero, abMean = zero, bbMean = zero; Real c = Dot(negDFDC, M * negDFDC); for (size_t i = 0; i < points.size(); ++i) { Real b = Dot(negDFDC, MDelta[i]); bMean += b; abMean += a[i] * b; bbMean += b * b; } bMean *= invQuantity; abMean *= invQuantity; bbMean *= invQuantity; // Compute the coefficients of the quartic polynomial q(t) that // represents the error function on the given line in the gradient // descent minimization. std::array<Real, 5> q; q[0] = aaMean; q[1] = -four * abMean; q[2] = four * bbMean + two * c * aMean; q[3] = -four * c * bMean; q[4] = c * c; // Compute the coefficients of q'(t). std::array<Real, 4> dq; dq[0] = q[1]; dq[1] = two * q[2]; dq[2] = three * q[3]; dq[3] = four * q[4]; // Compute the roots of q'(t). std::map<Real, int32_t> rmMap; RootsPolynomial<Real>::SolveCubic(dq[0], dq[1], dq[2], dq[3], rmMap); // Choose the root that leads to the minimum along the gradient // descent line and update the center to that point. Real minError = aaMean; Real minRoot = zero; for (auto const& rm : rmMap) { Real root = rm.first; if (root > zero) { Real error = q[0] + root * (q[1] + root * (q[2] + root * (q[3] + root * q[4]))); if (error < minError) { minError = error; minRoot = root; } } } if (minRoot > zero) { C += minRoot * negDFDC; return minError; } return aaMean; } Real UpdateMatrix(std::vector<Vector3<Real>> const& points, Vector3<Real> const& C, Matrix3x3<Real>& M) { Real const zero = static_cast<Real>(0); Real const one = static_cast<Real>(1); Real const two = static_cast<Real>(2); Real const half = static_cast<Real>(0.5); Real const epsilon = static_cast<Real>(1e-06); std::vector<Vector3<Real>> Delta(points.size()); std::vector<Real> a(points.size()); Real invQuantity = one / static_cast<Real>(points.size()); Matrix3x3<Real> negDFDM; // zero matrix, symmetric Real aaMean = zero; for (size_t i = 0; i < points.size(); ++i) { Delta[i] = points[i] - C; a[i] = Dot(Delta[i], M * Delta[i]) - one; Real twoA = two * a[i]; negDFDM(0, 0) -= a[i] * Delta[i][0] * Delta[i][0]; negDFDM(0, 1) -= twoA * Delta[i][0] * Delta[i][1]; negDFDM(0, 2) -= twoA * Delta[i][0] * Delta[i][2]; negDFDM(1, 1) -= a[i] * Delta[i][1] * Delta[i][1]; negDFDM(1, 2) -= twoA * Delta[i][1] * Delta[i][2]; negDFDM(2, 2) -= a[i] * Delta[i][2] * Delta[i][2]; aaMean += a[i] * a[i]; } aaMean *= invQuantity; // Normalize the matrix as if it were a vector of numbers. Real length = std::sqrt( negDFDM(0, 0) * negDFDM(0, 0) + negDFDM(0, 1) * negDFDM(0, 1) + negDFDM(0, 2) * negDFDM(0, 2) + negDFDM(1, 1) * negDFDM(1, 1) + negDFDM(1, 2) * negDFDM(1, 2) + negDFDM(2, 2) * negDFDM(2, 2)); if (length < epsilon) { return aaMean; } Real invLength = one / length; negDFDM(0, 0) *= invLength; negDFDM(0, 1) *= invLength; negDFDM(0, 2) *= invLength; negDFDM(1, 1) *= invLength; negDFDM(1, 2) *= invLength; negDFDM(2, 2) *= invLength; // Fill in the lower triangular portion because negGradM is a // symmetric matrix. negDFDM(1, 0) = negDFDM(0, 1); negDFDM(2, 0) = negDFDM(0, 2); negDFDM(2, 1) = negDFDM(1, 2); Real abMean = zero, bbMean = zero; for (size_t i = 0; i < points.size(); ++i) { Real b = Dot(Delta[i], negDFDM * Delta[i]); abMean += a[i] * b; bbMean += b * b; } abMean *= invQuantity; bbMean *= invQuantity; // Compute the coefficients of the quadratic polynomial q(t) that // represents the error function on the given line in the gradient // descent minimization. std::array<Real, 3> q; q[0] = aaMean; q[1] = two * abMean; q[2] = bbMean; // Compute the coefficients of q'(t). std::array<Real, 2> dq; dq[0] = q[1]; dq[1] = two * q[2]; // Compute the root as long as it is positive and // M + root * negGradM is a positive definite matrix. Real root = -dq[0] / dq[1]; if (root > zero) { // Use Sylvester's criterion for testing positive definitess. // A for(;;) loop terminates for floating-point arithmetic but // not for rational (BSRational<UInteger>) arithmetic. Limit // the number of iterations so that the loop terminates for // rational arithmetic but 'return' occurs for floating-point // arithmetic. for (size_t k = 0; k < 2048; ++k) { Matrix3x3<Real> nextM = M + root * negDFDM; if (nextM(0, 0) > zero) { Real det = nextM(0, 0) * nextM(1, 1) - nextM(0, 1) * nextM(1, 0); if (det > zero) { det = Determinant(nextM); if (det > zero) { M = nextM; Real minError = q[0] + root * (q[1] + root * q[2]); return minError; } } } root *= half; } } return aaMean; } Real ErrorFunction(std::vector<Vector3<Real>> const& points, Vector3<Real> const& C, Matrix3x3<Real> const& M) const { Real error = static_cast<Real>(0); for (auto const& P : points) { Vector3<Real> Delta = P - C; Real a = Dot(Delta, M * Delta) - static_cast<Real>(1); error += a * a; } error /= static_cast<Real>(points.size()); return error; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MarchingCubes.h
.h
80,668
1,255
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <array> #include <string> // Create the lookup table for the Marching Cubes algorithm that is used to // extract a triangular mesh that represents a level surface of a 3D image // sampled on a regular lattice. The assumption is that no data sample is // zero, which allows us to have a table with 256 entries: 2 signs per // sample, 8 samples per volume element (voxel). Each entry corresponds to // the pattern of 8 signs at the corners of a voxel. The signs are stored as // bits (b7,b6,b5,b4,b3,b2,b1,b0). The bit assignments to voxel corners is // b0 = (x,y,z), b1 = (x+1,y,z), b2 = (x,y+1,z), b3 = (x+1,y+1,z) // b4 = (x,y,z+1), b5 = (x+1,y,z+1), b6 = (x,y+1,z+1), b7 = (x+1,y+1,z+1) // If a bit is zero, then the voxel value at the corresponding corner is // positive; otherwise, the bit is one and the value is negative. The // triangles are counterclockwise ordered according to an observer viewing // the triangle from the negative side of the level surface. // INTERNAL USE ONLY. This is used for convenience in creating the // Configuration table. TODO: Expand the macro manually for the table // creation. #define GTE_MC_ENTRY(name) CT_##name, &MarchingCubes::name namespace gte { class MarchingCubes { public: // Construction and destruction. virtual ~MarchingCubes() = default; MarchingCubes() { // Create the lookup table. for (mEntry = 0; mEntry < 256; ++mEntry) { (this->*ConfigurationTable()[mEntry].F)(ConfigurationTable()[mEntry].index); } } enum { MAX_VERTICES = 12, MAX_TRIANGLES = 5, }; struct Topology { // All members are set to zeros. Topology() : numVertices(0), numTriangles(0) { std::fill(vpair.begin(), vpair.end(), std::array<int32_t, 2>{ 0, 0 }); std::fill(itriple.begin(), itriple.end(), std::array<int32_t, 3>{ 0, 0, 0 }); } int32_t numVertices; int32_t numTriangles; std::array<std::array<int32_t, 2>, MAX_VERTICES> vpair; std::array<std::array<int32_t, 3>, MAX_TRIANGLES> itriple; }; // The entry must be in {0..255}. inline Topology const& GetTable(int32_t entry) const { return TopologyTable()[entry]; } // The table has 256 entries, each 41 integers, stored as // table[256][41]. The return value is a pointer to the table via // &table[0][0]. inline int32_t const* GetTable() const { return reinterpret_cast<int32_t const*>(TopologyTable().data()); } // The pre-built topology table that is generated by the constructor. // This is for reference in case you want to have a GPU-based // implementation where you load the table as a GPU resource. static std::array<std::array<int32_t, 41>, 256> const& GetPrebuiltTable() { static std::array<std::array<int32_t, 41>, 256> topologyTable = { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 4, 0, 2, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 2, 6, 2, 3, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 1, 3, 1, 5, 0, 1, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 0, 4, 2, 6, 2, 3, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 3, 1, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 1, 0, 4, 0, 2, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 1, 5, 0, 1, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 1, 5, 0, 4, 0, 2, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 4, 2, 3, 7, 1, 3, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 2, 6, 3, 7, 1, 3, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 5, 3, 3, 7, 1, 5, 0, 1, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 4, 2, 6, 3, 7, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 4, 5, 4, 6, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 1, 1, 3, 1, 5, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 0, 2, 1, 3, 1, 5, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 4, 4, 5, 4, 6, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 0, 1, 4, 5, 4, 6, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 9, 3, 0, 2, 2, 6, 2, 3, 1, 3, 1, 5, 0, 1, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 6, 4, 4, 5, 4, 6, 2, 6, 2, 3, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 2, 2, 3, 3, 7, 1, 3, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 0, 1, 4, 5, 4, 6, 0, 2, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 7, 3, 0, 1, 2, 3, 3, 7, 1, 5, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 4, 4, 5, 4, 6, 0, 2, 2, 3, 3, 7, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 3, 2, 6, 3, 7, 1, 3, 0, 2, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 4, 4, 6, 2, 6, 3, 7, 1, 3, 0, 1, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 8, 4, 3, 7, 1, 5, 0, 1, 0, 2, 2, 6, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 5, 3, 3, 7, 2, 6, 4, 6, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 3, 1, 5, 7, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 4, 0, 2, 0, 1, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 5, 7, 4, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 1, 3, 5, 7, 4, 5, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 2, 2, 6, 2, 3, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 0, 4, 2, 6, 2, 3, 0, 1, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 7, 3, 1, 3, 5, 7, 4, 5, 0, 1, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 4, 4, 5, 0, 4, 2, 6, 2, 3, 1, 3, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 2, 5, 7, 4, 5, 1, 5, 1, 3, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 9, 3, 0, 1, 0, 4, 0, 2, 2, 3, 3, 7, 1, 3, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 5, 3, 0, 1, 2, 3, 3, 7, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 5, 7, 4, 5, 0, 4, 0, 2, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 3, 1, 3, 0, 2, 2, 6, 3, 7, 5, 7, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 2, 6, 3, 7, 1, 3, 0, 1, 0, 4, 5, 7, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 6, 4, 5, 7, 4, 5, 0, 1, 0, 2, 2, 6, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 2, 6, 0, 4, 4, 5, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 4, 6, 0, 4, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 4, 6, 0, 2, 0, 1, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 5, 3, 5, 7, 4, 6, 0, 4, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 2, 1, 3, 5, 7, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 0, 4, 1, 5, 5, 7, 4, 6, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 4, 1, 5, 5, 7, 4, 6, 2, 6, 2, 3, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 8, 4, 5, 7, 4, 6, 0, 4, 0, 1, 1, 3, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 5, 3, 5, 7, 1, 3, 2, 3, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 7, 3, 5, 7, 4, 6, 0, 4, 1, 5, 1, 3, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 4, 6, 0, 2, 0, 1, 1, 5, 5, 7, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 6, 4, 3, 7, 5, 7, 4, 6, 0, 4, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 4, 6, 5, 7, 3, 7, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 8, 4, 3, 7, 1, 3, 0, 2, 2, 6, 1, 5, 5, 7, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 0, 0 }, { 7, 5, 3, 7, 2, 6, 4, 6, 5, 7, 1, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 7, 5, 4, 6, 5, 7, 3, 7, 2, 6, 0, 2, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 4, 2, 2, 6, 4, 6, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 2, 0, 1, 0, 4, 4, 6, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 1, 3, 1, 5, 0, 1, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 0, 2, 1, 3, 1, 5, 0, 4, 4, 6, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 4, 2, 4, 6, 6, 7, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 2, 3, 0, 1, 0, 4, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 7, 3, 0, 2, 4, 6, 6, 7, 2, 3, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 4, 4, 6, 6, 7, 2, 3, 1, 3, 1, 5, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 2, 3, 7, 1, 3, 2, 3, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 9, 3, 2, 3, 3, 7, 1, 3, 0, 1, 0, 4, 0, 2, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 7, 3, 3, 7, 1, 5, 0, 1, 2, 3, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 1, 5, 0, 4, 0, 2, 2, 3, 3, 7, 4, 6, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 5, 3, 0, 2, 4, 6, 6, 7, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 4, 6, 6, 7, 3, 7, 1, 3, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 4, 6, 7, 3, 7, 1, 5, 0, 1, 0, 2, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 1, 5, 3, 7, 6, 7, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 6, 7, 2, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 4, 5, 6, 7, 2, 6, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 7, 3, 4, 5, 6, 7, 2, 6, 0, 4, 0, 1, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 4, 2, 6, 0, 2, 1, 3, 1, 5, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 6, 7, 2, 3, 0, 2, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 1, 4, 5, 6, 7, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 8, 4, 6, 7, 2, 3, 0, 2, 0, 4, 4, 5, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 5, 3, 6, 7, 4, 5, 1, 5, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 7, 3, 2, 6, 0, 4, 4, 5, 6, 7, 3, 7, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 4, 5, 6, 7, 2, 6, 0, 2, 0, 1, 3, 7, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 8, 4, 1, 5, 0, 1, 2, 3, 3, 7, 0, 4, 4, 5, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 0, 0 }, { 7, 5, 6, 7, 4, 5, 1, 5, 3, 7, 2, 3, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 4, 3, 7, 1, 3, 0, 2, 0, 4, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 4, 5, 0, 1, 1, 3, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 7, 5, 1, 5, 3, 7, 6, 7, 4, 5, 0, 4, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 4, 2, 4, 5, 1, 5, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 4, 5, 1, 5, 5, 7, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 9, 3, 4, 5, 1, 5, 5, 7, 6, 7, 2, 6, 4, 6, 0, 4, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 7, 3, 4, 5, 0, 1, 1, 3, 5, 7, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 1, 3, 5, 7, 4, 5, 0, 4, 0, 2, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 3, 6, 7, 2, 3, 0, 2, 4, 6, 4, 5, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 2, 3, 0, 1, 0, 4, 4, 6, 6, 7, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 8, 4, 4, 6, 6, 7, 2, 3, 0, 2, 5, 7, 4, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 0, 0 }, { 7, 5, 5, 7, 1, 3, 2, 3, 6, 7, 4, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 9, 3, 6, 7, 2, 6, 4, 6, 4, 5, 1, 5, 5, 7, 3, 7, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 12, 4, 0, 1, 0, 4, 0, 2, 2, 6, 4, 6, 6, 7, 2, 3, 3, 7, 1, 3, 1, 5, 5, 7, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0 }, { 8, 4, 0, 1, 2, 3, 3, 7, 5, 7, 4, 5, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 9, 5, 4, 6, 0, 4, 4, 5, 5, 7, 3, 7, 6, 7, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 8, 4, 0, 2, 4, 6, 6, 7, 3, 7, 1, 3, 4, 5, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 9, 5, 5, 7, 3, 7, 6, 7, 4, 6, 0, 4, 4, 5, 1, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 7, 5, 4, 6, 0, 2, 0, 1, 4, 5, 5, 7, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 4, 5, 7, 3, 7, 6, 7, 4, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 5, 3, 0, 4, 1, 5, 5, 7, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 2, 0, 1, 1, 5, 5, 7, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 4, 6, 7, 2, 6, 0, 4, 0, 1, 1, 3, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 1, 3, 0, 2, 2, 6, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 2, 0, 4, 1, 5, 5, 7, 6, 7, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 2, 3, 6, 7, 5, 7, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 7, 5, 2, 3, 6, 7, 5, 7, 1, 3, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 4, 2, 1, 3, 2, 3, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 8, 4, 0, 4, 1, 5, 5, 7, 6, 7, 2, 6, 1, 3, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 9, 5, 1, 3, 1, 5, 0, 1, 0, 2, 2, 6, 2, 3, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 7, 5, 2, 3, 0, 1, 0, 4, 2, 6, 6, 7, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 4, 2, 3, 0, 2, 2, 6, 6, 7, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 7, 5, 1, 5, 0, 4, 0, 2, 1, 3, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 4, 1, 5, 0, 1, 1, 3, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 6, 2, 0, 1, 0, 4, 0, 2, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 0, 1, 0, 4, 0, 2, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 2, 1, 5, 0, 1, 1, 3, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 1, 5, 0, 4, 0, 2, 1, 3, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 6, 2, 2, 3, 0, 2, 2, 6, 6, 7, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 2, 3, 0, 1, 0, 4, 2, 6, 6, 7, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 9, 3, 1, 3, 1, 5, 0, 1, 0, 2, 2, 6, 2, 3, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 8, 4, 0, 4, 2, 6, 2, 3, 1, 3, 1, 5, 6, 7, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 4, 2, 1, 3, 2, 3, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 2, 3, 6, 7, 5, 7, 1, 3, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 5, 3, 2, 3, 6, 7, 5, 7, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 5, 7, 1, 5, 0, 4, 0, 2, 2, 3, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 1, 3, 0, 2, 2, 6, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 6, 7, 5, 7, 1, 3, 0, 1, 0, 4, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 4, 6, 7, 5, 7, 1, 5, 0, 1, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 0, 4, 1, 5, 5, 7, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 6, 2, 5, 7, 3, 7, 6, 7, 4, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 4, 6, 0, 2, 0, 1, 4, 5, 5, 7, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 9, 3, 5, 7, 3, 7, 6, 7, 4, 6, 0, 4, 4, 5, 1, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 8, 4, 0, 2, 1, 3, 1, 5, 4, 5, 4, 6, 3, 7, 6, 7, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 9, 3, 4, 6, 0, 4, 4, 5, 5, 7, 3, 7, 6, 7, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0 }, { 8, 4, 0, 1, 4, 5, 4, 6, 2, 6, 2, 3, 5, 7, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 12, 4, 1, 3, 1, 5, 0, 1, 0, 4, 4, 5, 4, 6, 0, 2, 2, 6, 2, 3, 3, 7, 6, 7, 5, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0 }, { 9, 5, 6, 7, 2, 6, 4, 6, 4, 5, 1, 5, 5, 7, 3, 7, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 7, 3, 5, 7, 1, 3, 2, 3, 6, 7, 4, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 4, 5, 4, 6, 0, 2, 0, 1, 6, 7, 5, 7, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 0, 0 }, { 8, 4, 2, 3, 6, 7, 5, 7, 1, 5, 0, 1, 4, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 5, 6, 7, 2, 3, 0, 2, 4, 6, 4, 5, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 8, 4, 1, 3, 0, 2, 2, 6, 6, 7, 5, 7, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 5, 4, 5, 0, 1, 1, 3, 5, 7, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 9, 5, 4, 5, 1, 5, 5, 7, 6, 7, 2, 6, 4, 6, 0, 4, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 6, 4, 4, 5, 1, 5, 5, 7, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 4, 2, 4, 5, 1, 5, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 1, 5, 3, 7, 6, 7, 4, 5, 0, 4, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 5, 3, 4, 5, 0, 1, 1, 3, 3, 7, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 3, 7, 6, 7, 4, 5, 0, 4, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 3, 6, 7, 4, 5, 1, 5, 3, 7, 2, 3, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 2, 6, 2, 3, 0, 1, 0, 4, 3, 7, 6, 7, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 0, 0 }, { 8, 4, 4, 5, 0, 1, 1, 3, 3, 7, 6, 7, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 5, 2, 6, 0, 4, 4, 5, 6, 7, 3, 7, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 5, 3, 6, 7, 4, 5, 1, 5, 1, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 8, 4, 6, 7, 4, 5, 1, 5, 1, 3, 2, 3, 0, 4, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 4, 2, 0, 1, 2, 3, 6, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 6, 7, 2, 3, 0, 2, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 6, 4, 1, 5, 1, 3, 0, 2, 2, 6, 6, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 5, 4, 5, 6, 7, 2, 6, 0, 4, 0, 1, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 5, 3, 4, 5, 6, 7, 2, 6, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 6, 7, 2, 6, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 1, 5, 3, 7, 6, 7, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 6, 7, 4, 6, 0, 2, 0, 1, 1, 5, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 6, 4, 3, 7, 6, 7, 4, 6, 0, 4, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 0, 2, 4, 6, 6, 7, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 8, 4, 1, 5, 3, 7, 6, 7, 4, 6, 0, 4, 2, 3, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 5, 3, 7, 1, 5, 0, 1, 2, 3, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 9, 5, 2, 3, 3, 7, 1, 3, 0, 1, 0, 4, 0, 2, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 6, 4, 3, 7, 1, 3, 2, 3, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 6, 4, 4, 6, 0, 4, 1, 5, 1, 3, 2, 3, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 5, 0, 2, 4, 6, 6, 7, 2, 3, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 5, 3, 2, 3, 0, 1, 0, 4, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 4, 6, 6, 7, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 5, 0, 2, 1, 3, 1, 5, 0, 4, 4, 6, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 2, 1, 3, 1, 5, 0, 1, 2, 6, 4, 6, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 2, 0, 1, 0, 4, 4, 6, 6, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 3, 1, 6, 7, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 2, 6, 4, 6, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 7, 3, 4, 6, 5, 7, 3, 7, 2, 6, 0, 2, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 7, 3, 3, 7, 2, 6, 4, 6, 5, 7, 1, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0 }, { 8, 4, 0, 4, 0, 2, 1, 3, 1, 5, 2, 6, 4, 6, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 0, 0 }, { 5, 3, 4, 6, 5, 7, 3, 7, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 3, 7, 2, 3, 0, 1, 0, 4, 4, 6, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 8, 4, 4, 6, 5, 7, 3, 7, 2, 3, 0, 2, 1, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 5, 5, 7, 4, 6, 0, 4, 1, 5, 1, 3, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 5, 3, 5, 7, 1, 3, 2, 3, 2, 6, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 8, 4, 5, 7, 1, 3, 2, 3, 2, 6, 4, 6, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 6, 4, 1, 5, 0, 1, 2, 3, 2, 6, 4, 6, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 5, 0, 4, 1, 5, 5, 7, 4, 6, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 4, 2, 0, 2, 4, 6, 5, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 5, 7, 4, 6, 0, 4, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 5, 3, 4, 6, 0, 2, 0, 1, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 4, 6, 0, 4, 1, 5, 5, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 2, 6, 0, 4, 4, 5, 5, 7, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 6, 4, 5, 7, 3, 7, 2, 6, 0, 2, 0, 1, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 8, 4, 2, 6, 0, 4, 4, 5, 5, 7, 3, 7, 0, 1, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 7, 5, 1, 3, 0, 2, 2, 6, 3, 7, 5, 7, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 4, 5, 7, 3, 7, 2, 3, 0, 2, 0, 4, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 5, 3, 0, 1, 2, 3, 3, 7, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 9, 5, 0, 1, 0, 4, 0, 2, 2, 3, 3, 7, 1, 3, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 6, 4, 5, 7, 4, 5, 1, 5, 1, 3, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 6, 4, 2, 3, 2, 6, 0, 4, 4, 5, 5, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 5, 1, 3, 5, 7, 4, 5, 0, 1, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 7, 5, 0, 4, 2, 6, 2, 3, 0, 1, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 2, 0, 2, 2, 6, 2, 3, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 1, 3, 5, 7, 4, 5, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 5, 7, 4, 5, 0, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 4, 0, 2, 0, 1, 1, 5, 5, 7, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 3, 1, 5, 7, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 3, 7, 2, 6, 4, 6, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 0, 0, 0, 0, 0 }, { 8, 4, 3, 7, 2, 6, 4, 6, 4, 5, 1, 5, 0, 2, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7, 0, 0, 0 }, { 6, 4, 1, 3, 3, 7, 2, 6, 4, 6, 4, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 5, 2, 6, 3, 7, 1, 3, 0, 2, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 4, 2, 3, 0, 2, 4, 6, 4, 5, 1, 5, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 7, 5, 0, 1, 2, 3, 3, 7, 1, 5, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 7, 5, 0, 1, 4, 5, 4, 6, 0, 2, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }, { 6, 2, 2, 3, 3, 7, 1, 3, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 4, 1, 3, 2, 3, 2, 6, 4, 6, 4, 5, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 0, 0 }, { 9, 5, 0, 2, 2, 6, 2, 3, 1, 3, 1, 5, 0, 1, 0, 4, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }, { 5, 3, 0, 1, 4, 5, 4, 6, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 4, 4, 5, 4, 6, 2, 6, 2, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 5, 3, 0, 2, 1, 3, 1, 5, 4, 5, 4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 1, 1, 3, 1, 5, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 4, 2, 4, 5, 4, 6, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 4, 5, 4, 6, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 4, 1, 5, 3, 7, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 3, 7, 1, 5, 0, 1, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 5, 3, 2, 6, 3, 7, 1, 3, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 3, 7, 1, 3, 0, 2, 2, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 1, 5, 0, 4, 0, 2, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 4, 2, 1, 5, 0, 1, 2, 3, 3, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 6, 4, 0, 1, 0, 4, 0, 2, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 3, 1, 2, 3, 3, 7, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 5, 3, 0, 4, 2, 6, 2, 3, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 0, 0, 0, 0, 0 }, { 6, 4, 1, 3, 1, 5, 0, 1, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2, 0, 0, 0 }, { 4, 2, 2, 6, 2, 3, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 0, 2, 2, 6, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 4, 2, 0, 4, 0, 2, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 3, 1, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }}; return topologyTable; } // Get the configuration type for the voxel, which is one of the // string names of the 'void Bits* (int32_t[8])' functions. static std::string GetConfigurationType(int32_t entry) { if (0 <= entry && entry < 256) { return ConfigurationString()[ConfigurationTable()[entry].type]; } return ""; } protected: // Support for lookup construction and access. // mTable[i][0] = numVertices // mTable[i][1] = numTriangles // mTable[i][2..25] = pairs of corner indices (maximum of 12 pairs) // mTable[i][26..40] = triples of indices (maximum of 5 triples) static std::array<Topology, 256>& TopologyTable() { static std::array<Topology, 256> topologyTable; return topologyTable; } // The constructor iterates mEntry from 0 to 255 and calls configuration // functions, each calling SetTable(...). The mEntry value is the table // index to be used. int32_t mEntry; void SetTable(int32_t numV, int32_t const* vpair, int32_t numT, int32_t const* itriple) { // The item is already zeroed in the constructor. Topology& topology = TopologyTable()[mEntry]; topology.numVertices = numV; topology.numTriangles = numT; // Store vertex pairs with minimum index occurring first. for (int32_t i = 0; i < numV; ++i, vpair += 2) { topology.vpair[i][0] = std::min(vpair[0], vpair[1]); topology.vpair[i][1] = std::max(vpair[0], vpair[1]); } // Store triangle triples as is. for (int32_t i = 0; i < numT; ++i, itriple += 3) { topology.itriple[i] = { itriple[0], itriple[1], itriple[2] }; } } // The precomputed information about the 256 configurations for voxels. void Bits0(int32_t[8]) { SetTable(0, nullptr, 0, nullptr); } void Bits1(int32_t index[8]) { int32_t const numV = 3; int32_t vpair[2 * numV] = { index[1], index[0], index[4], index[0], index[2], index[0] }; int32_t const numT = 1; int32_t itriple[3 * numT] = { 0, 1, 2 }; SetTable(numV, vpair, numT, itriple); } void Bits7(int32_t index[8]) { int32_t const numV = 3; int32_t vpair[2 * numV] = { index[1], index[0], index[4], index[0], index[2], index[0] }; int32_t const numT = 1; int32_t itriple[3 * numT] = { 0, 2, 1 }; SetTable(numV, vpair, numT, itriple); } void Bits2Edge(int32_t index[8]) { int32_t const numV = 4; int32_t vpair[2 * numV] = { index[4], index[0], index[2], index[0], index[3], index[1], index[5], index[1] }; int32_t const numT = 2; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3 }; SetTable(numV, vpair, numT, itriple); } void Bits6Edge(int32_t index[8]) { int32_t const numV = 4; int32_t vpair[2 * numV] = { index[4], index[0], index[2], index[0], index[3], index[1], index[5], index[1] }; int32_t const numT = 2; int32_t itriple[3 * numT] = { 0, 2, 1, 0, 3, 2 }; SetTable(numV, vpair, numT, itriple); } void Bits2FaceDiag(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[1], index[0], index[4], index[0], index[2], index[0], index[2], index[3], index[7], index[3], index[1], index[3] }; int32_t const numT = 2; int32_t itriple[3 * numT] = { 0, 1, 2, 3, 4, 5 }; SetTable(numV, vpair, numT, itriple); } void Bits6FaceDiag(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[1], index[0], index[4], index[0], index[2], index[0], index[2], index[3], index[7], index[3], index[1], index[3] }; // Not the reverse ordering from Bit2FaceDiag due to ambiguous face // handling. int32_t const numT = 4; int32_t itriple[3 * numT] = { 1, 0, 5, 1, 5, 4, 1, 4, 3, 1, 3, 2 }; SetTable(numV, vpair, numT, itriple); } void Bits2BoxDiag(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[1], index[0], index[4], index[0], index[2], index[0], index[3], index[7], index[6], index[7], index[5], index[7] }; int32_t const numT = 2; int32_t itriple[3 * numT] = { 0, 1, 2, 3, 4, 5 }; SetTable(numV, vpair, numT, itriple); } void Bits6BoxDiag(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[1], index[0], index[4], index[0], index[2], index[0], index[3], index[7], index[6], index[7], index[5], index[7] }; int32_t const numT = 2; int32_t itriple[3 * numT] = { 0, 2, 1, 3, 5, 4 }; SetTable(numV, vpair, numT, itriple); } void Bits3SameFace(int32_t index[8]) { int32_t const numV = 5; int32_t vpair[2 * numV] = { index[4], index[0], index[2], index[6], index[2], index[3], index[1], index[3], index[1], index[5] }; int32_t const numT = 3; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 0, 3, 4 }; SetTable(numV, vpair, numT, itriple); } void Bits5SameFace(int32_t index[8]) { int32_t const numV = 5; int32_t vpair[2 * numV] = { index[4], index[0], index[2], index[6], index[2], index[3], index[1], index[3], index[1], index[5] }; int32_t const numT = 3; int32_t itriple[3 * numT] = { 0, 2, 1, 0, 3, 2, 0, 4, 3 }; SetTable(numV, vpair, numT, itriple); } void Bits3EdgeFaceDiag(int32_t index[8]) { int32_t const numV = 7; int32_t vpair[2 * numV] = { index[0], index[1], index[4], index[5], index[4], index[6], index[0], index[2], index[2], index[3], index[3], index[7], index[1], index[3] }; int32_t const numT = 3; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 4, 5, 6 }; SetTable(numV, vpair, numT, itriple); } void Bits5EdgeFaceDiag(int32_t index[8]) { int32_t const numV = 7; int32_t vpair[2 * numV] = { index[0], index[1], index[4], index[5], index[4], index[6], index[0], index[2], index[2], index[3], index[3], index[7], index[1], index[3] }; // Not the reverse ordering from Bit3EdgeFaceDiag due to ambiguous face // handling. int32_t const numT = 5; int32_t itriple[3 * numT] = { 5, 0, 6, 5, 1, 0, 5, 2, 1, 5, 3, 2, 5, 4, 3 }; SetTable(numV, vpair, numT, itriple); } void Bits3FaceDiagFaceDiag(int32_t index[8]) { int32_t const numV = 9; int32_t vpair[2 * numV] = { index[0], index[1], index[0], index[4], index[0], index[2], index[2], index[3], index[3], index[7], index[1], index[3], index[1], index[5], index[5], index[7], index[4], index[5] }; int32_t const numT = 3; int32_t itriple[3 * numT] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; SetTable(numV, vpair, numT, itriple); } void Bits5FaceDiagFaceDiag(int32_t index[8]) { int32_t const numV = 9; int32_t vpair[2 * numV] = { index[0], index[1], index[0], index[4], index[0], index[2], index[2], index[3], index[3], index[7], index[1], index[3], index[1], index[5], index[5], index[7], index[4], index[5] }; // Not the reverse ordering from Bit3FaceDiagFaceDiag due to ambiguous face // handling. int32_t const numT = 5; int32_t itriple[3 * numT] = { 1, 3, 2, 1, 4, 3, 1, 7, 4, 1, 8, 7, 0, 5, 6 }; SetTable(numV, vpair, numT, itriple); } void Bits4SameFace(int32_t index[8]) { int32_t const numV = 4; int32_t vpair[2 * numV] = { index[0], index[4], index[2], index[6], index[3], index[7], index[1], index[5] }; int32_t const numT = 2; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3 }; SetTable(numV, vpair, numT, itriple); } void Bits4FaceEdge(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[4], index[5], index[4], index[6], index[2], index[6], index[2], index[3], index[1], index[3], index[1], index[5] }; int32_t const numT = 4; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5 }; SetTable(numV, vpair, numT, itriple); } void Bits4FaceFaceDiagL(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[4], index[5], index[0], index[4], index[2], index[6], index[2], index[3], index[1], index[3], index[5], index[7] }; int32_t const numT = 4; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5 }; SetTable(numV, vpair, numT, itriple); } void Bits4FaceFaceDiagR(int32_t index[8]) { int32_t const numV = 6; int32_t vpair[2 * numV] = { index[4], index[6], index[6], index[7], index[2], index[3], index[1], index[3], index[1], index[5], index[0], index[4] }; int32_t const numT = 4; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5 }; SetTable(numV, vpair, numT, itriple); } void Bits4FaceBoxDiag(int32_t index[8]) { int32_t const numV = 8; int32_t vpair[2 * numV] = { index[0], index[4], index[2], index[6], index[2], index[3], index[1], index[3], index[1], index[5], index[6], index[7], index[5], index[7], index[3], index[7] }; int32_t const numT = 4; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 0, 3, 4, 5, 6, 7 }; SetTable(numV, vpair, numT, itriple); } void Bits4EdgeEdgePara(int32_t index[8]) { int32_t const numV = 8; int32_t vpair[2 * numV] = { index[0], index[4], index[0], index[2], index[1], index[3], index[1], index[5], index[2], index[6], index[4], index[6], index[5], index[7], index[3], index[7] }; int32_t const numT = 4; int32_t itriple[3 * numT] = { 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7 }; SetTable(numV, vpair, numT, itriple); } void Bits4EdgeEdgePerp(int32_t index[8]) { int32_t const numV = 12; int32_t vpair[2 * numV] = { index[0], index[1], index[0], index[4], index[0], index[2], index[2], index[6], index[4], index[6], index[6], index[7], index[2], index[3], index[3], index[7], index[1], index[3], index[1], index[5], index[5], index[7], index[4], index[5] }; int32_t const numT = 4; int32_t itriple[3 * numT] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; SetTable(numV, vpair, numT, itriple); } enum ConfigurationType { CT_Bits0, CT_Bits1, CT_Bits7, CT_Bits2Edge, CT_Bits6Edge, CT_Bits2FaceDiag, CT_Bits6FaceDiag, CT_Bits2BoxDiag, CT_Bits6BoxDiag, CT_Bits3SameFace, CT_Bits5SameFace, CT_Bits3EdgeFaceDiag, CT_Bits5EdgeFaceDiag, CT_Bits3FaceDiagFaceDiag, CT_Bits5FaceDiagFaceDiag, CT_Bits4SameFace, CT_Bits4FaceEdge, CT_Bits4FaceFaceDiagL, CT_Bits4FaceFaceDiagR, CT_Bits4FaceBoxDiag, CT_Bits4EdgeEdgePara, CT_Bits4EdgeEdgePerp, CT_NUM_TYPES }; typedef void (MarchingCubes::*Function)(int32_t[8]); struct Configuration { ConfigurationType type; Function F; int32_t index[8]; }; static std::array<Configuration, 256>& ConfigurationTable() { static std::array<Configuration, 256> configuration = {{ /*00000000*/{ GTE_MC_ENTRY(Bits0), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00000001*/{ GTE_MC_ENTRY(Bits1), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00000010*/{ GTE_MC_ENTRY(Bits1), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00000011*/{ GTE_MC_ENTRY(Bits2Edge), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00000100*/{ GTE_MC_ENTRY(Bits1), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00000101*/{ GTE_MC_ENTRY(Bits2Edge), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00000110*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00000111*/{ GTE_MC_ENTRY(Bits3SameFace), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00001000*/{ GTE_MC_ENTRY(Bits1), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00001001*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00001010*/{ GTE_MC_ENTRY(Bits2Edge), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00001011*/{ GTE_MC_ENTRY(Bits3SameFace), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00001100*/{ GTE_MC_ENTRY(Bits2Edge), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00001101*/{ GTE_MC_ENTRY(Bits3SameFace), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00001110*/{ GTE_MC_ENTRY(Bits3SameFace), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00001111*/{ GTE_MC_ENTRY(Bits4SameFace), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00010000*/{ GTE_MC_ENTRY(Bits1), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*00010001*/{ GTE_MC_ENTRY(Bits2Edge), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*00010010*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*00010011*/{ GTE_MC_ENTRY(Bits3SameFace), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*00010100*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*00010101*/{ GTE_MC_ENTRY(Bits3SameFace), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*00010110*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00010111*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00011000*/{ GTE_MC_ENTRY(Bits2BoxDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00011001*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00011010*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*00011011*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00011100*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 2, 6, 0, 4, 3, 7, 1, 5 }}, /*00011101*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00011110*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00011111*/{ GTE_MC_ENTRY(Bits5SameFace), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*00100000*/{ GTE_MC_ENTRY(Bits1), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*00100001*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*00100010*/{ GTE_MC_ENTRY(Bits2Edge), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*00100011*/{ GTE_MC_ENTRY(Bits3SameFace), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*00100100*/{ GTE_MC_ENTRY(Bits2BoxDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00100101*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*00100110*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00100111*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00101000*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*00101001*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*00101010*/{ GTE_MC_ENTRY(Bits3SameFace), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*00101011*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*00101100*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 3, 1, 7, 5, 2, 0, 6, 4 }}, /*00101101*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*00101110*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00101111*/{ GTE_MC_ENTRY(Bits5SameFace), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*00110000*/{ GTE_MC_ENTRY(Bits2Edge), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*00110001*/{ GTE_MC_ENTRY(Bits3SameFace), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*00110010*/{ GTE_MC_ENTRY(Bits3SameFace), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*00110011*/{ GTE_MC_ENTRY(Bits4SameFace), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*00110100*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*00110101*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*00110110*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*00110111*/{ GTE_MC_ENTRY(Bits5SameFace), { 7, 6, 3, 2, 5, 4, 1, 0 }}, /*00111000*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*00111001*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*00111010*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*00111011*/{ GTE_MC_ENTRY(Bits5SameFace), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*00111100*/{ GTE_MC_ENTRY(Bits4EdgeEdgePara), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*00111101*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*00111110*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*00111111*/{ GTE_MC_ENTRY(Bits6Edge), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*01000000*/{ GTE_MC_ENTRY(Bits1), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*01000001*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*01000010*/{ GTE_MC_ENTRY(Bits2BoxDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*01000011*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*01000100*/{ GTE_MC_ENTRY(Bits2Edge), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*01000101*/{ GTE_MC_ENTRY(Bits3SameFace), { 2, 6, 0, 4, 3, 7, 1, 5 }}, /*01000110*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*01000111*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*01001000*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*01001001*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*01001010*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*01001011*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*01001100*/{ GTE_MC_ENTRY(Bits3SameFace), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*01001101*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*01001110*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*01001111*/{ GTE_MC_ENTRY(Bits5SameFace), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*01010000*/{ GTE_MC_ENTRY(Bits2Edge), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*01010001*/{ GTE_MC_ENTRY(Bits3SameFace), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*01010010*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*01010011*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*01010100*/{ GTE_MC_ENTRY(Bits3SameFace), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*01010101*/{ GTE_MC_ENTRY(Bits4SameFace), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*01010110*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*01010111*/{ GTE_MC_ENTRY(Bits5SameFace), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*01011000*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*01011001*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*01011010*/{ GTE_MC_ENTRY(Bits4EdgeEdgePara), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*01011011*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 7, 6, 3, 2, 5, 4, 1, 0 }}, /*01011100*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*01011101*/{ GTE_MC_ENTRY(Bits5SameFace), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*01011110*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*01011111*/{ GTE_MC_ENTRY(Bits6Edge), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*01100000*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*01100001*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*01100010*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*01100011*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*01100100*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*01100101*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 2, 6, 0, 4, 3, 7, 1, 5 }}, /*01100110*/{ GTE_MC_ENTRY(Bits4EdgeEdgePara), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*01100111*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*01101000*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*01101001*/{ GTE_MC_ENTRY(Bits4EdgeEdgePerp), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*01101010*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*01101011*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*01101100*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*01101101*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*01101110*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*01101111*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*01110000*/{ GTE_MC_ENTRY(Bits3SameFace), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*01110001*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*01110010*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*01110011*/{ GTE_MC_ENTRY(Bits5SameFace), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*01110100*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*01110101*/{ GTE_MC_ENTRY(Bits5SameFace), { 3, 1, 7, 5, 2, 0, 6, 4 }}, /*01110110*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*01110111*/{ GTE_MC_ENTRY(Bits6Edge), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*01111000*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*01111001*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*01111010*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*01111011*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*01111100*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*01111101*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*01111110*/{ GTE_MC_ENTRY(Bits6BoxDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*01111111*/{ GTE_MC_ENTRY(Bits7), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*10000000*/{ GTE_MC_ENTRY(Bits1), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*10000001*/{ GTE_MC_ENTRY(Bits2BoxDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*10000010*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*10000011*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*10000100*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*10000101*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*10000110*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*10000111*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*10001000*/{ GTE_MC_ENTRY(Bits2Edge), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*10001001*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*10001010*/{ GTE_MC_ENTRY(Bits3SameFace), { 3, 1, 7, 5, 2, 0, 6, 4 }}, /*10001011*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*10001100*/{ GTE_MC_ENTRY(Bits3SameFace), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*10001101*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*10001110*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*10001111*/{ GTE_MC_ENTRY(Bits5SameFace), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*10010000*/{ GTE_MC_ENTRY(Bits2FaceDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*10010001*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*10010010*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*10010011*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*10010100*/{ GTE_MC_ENTRY(Bits3FaceDiagFaceDiag), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*10010101*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*10010110*/{ GTE_MC_ENTRY(Bits4EdgeEdgePerp), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*10010111*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*10011000*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*10011001*/{ GTE_MC_ENTRY(Bits4EdgeEdgePara), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*10011010*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 3, 1, 7, 5, 2, 0, 6, 4 }}, /*10011011*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*10011100*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*10011101*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*10011110*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*10011111*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*10100000*/{ GTE_MC_ENTRY(Bits2Edge), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*10100001*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*10100010*/{ GTE_MC_ENTRY(Bits3SameFace), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*10100011*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*10100100*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 7, 6, 3, 2, 5, 4, 1, 0 }}, /*10100101*/{ GTE_MC_ENTRY(Bits4EdgeEdgePara), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*10100110*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*10100111*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*10101000*/{ GTE_MC_ENTRY(Bits3SameFace), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*10101001*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*10101010*/{ GTE_MC_ENTRY(Bits4SameFace), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*10101011*/{ GTE_MC_ENTRY(Bits5SameFace), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*10101100*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*10101101*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*10101110*/{ GTE_MC_ENTRY(Bits5SameFace), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*10101111*/{ GTE_MC_ENTRY(Bits6Edge), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*10110000*/{ GTE_MC_ENTRY(Bits3SameFace), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*10110001*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*10110010*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*10110011*/{ GTE_MC_ENTRY(Bits5SameFace), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*10110100*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 5, 4, 7, 6, 1, 0, 3, 2 }}, /*10110101*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*10110110*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*10110111*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 3, 7, 2, 6, 1, 5, 0, 4 }}, /*10111000*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*10111001*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*10111010*/{ GTE_MC_ENTRY(Bits5SameFace), { 2, 6, 0, 4, 3, 7, 1, 5 }}, /*10111011*/{ GTE_MC_ENTRY(Bits6Edge), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*10111100*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*10111101*/{ GTE_MC_ENTRY(Bits6BoxDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*10111110*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*10111111*/{ GTE_MC_ENTRY(Bits7), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*11000000*/{ GTE_MC_ENTRY(Bits2Edge), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*11000001*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*11000010*/{ GTE_MC_ENTRY(Bits3EdgeFaceDiag), { 7, 3, 5, 1, 6, 2, 4, 0 }}, /*11000011*/{ GTE_MC_ENTRY(Bits4EdgeEdgePara), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11000100*/{ GTE_MC_ENTRY(Bits3SameFace), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*11000101*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 2, 6, 0, 4, 3, 7, 1, 5 }}, /*11000110*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 6, 2, 7, 3, 4, 0, 5, 1 }}, /*11000111*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*11001000*/{ GTE_MC_ENTRY(Bits3SameFace), { 7, 6, 3, 2, 5, 4, 1, 0 }}, /*11001001*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 7, 6, 3, 2, 5, 4, 1, 0 }}, /*11001010*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 7, 6, 3, 2, 5, 4, 1, 0 }}, /*11001011*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*11001100*/{ GTE_MC_ENTRY(Bits4SameFace), { 2, 3, 6, 7, 0, 1, 4, 5 }}, /*11001101*/{ GTE_MC_ENTRY(Bits5SameFace), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*11001110*/{ GTE_MC_ENTRY(Bits5SameFace), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*11001111*/{ GTE_MC_ENTRY(Bits6Edge), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*11010000*/{ GTE_MC_ENTRY(Bits3SameFace), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*11010001*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*11010010*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*11010011*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 3, 1, 7, 5, 2, 0, 6, 4 }}, /*11010100*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 6, 4, 2, 0, 7, 5, 3, 1 }}, /*11010101*/{ GTE_MC_ENTRY(Bits5SameFace), { 1, 5, 3, 7, 0, 4, 2, 6 }}, /*11010110*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11010111*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*11011000*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 6, 7, 4, 5, 2, 3, 0, 1 }}, /*11011001*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*11011010*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*11011011*/{ GTE_MC_ENTRY(Bits6BoxDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*11011100*/{ GTE_MC_ENTRY(Bits5SameFace), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*11011101*/{ GTE_MC_ENTRY(Bits6Edge), { 5, 1, 4, 0, 7, 3, 6, 2 }}, /*11011110*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*11011111*/{ GTE_MC_ENTRY(Bits7), { 5, 7, 1, 3, 4, 6, 0, 2 }}, /*11100000*/{ GTE_MC_ENTRY(Bits3SameFace), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*11100001*/{ GTE_MC_ENTRY(Bits4FaceBoxDiag), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*11100010*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagL), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*11100011*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 2, 6, 0, 4, 3, 7, 1, 5 }}, /*11100100*/{ GTE_MC_ENTRY(Bits4FaceFaceDiagR), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*11100101*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*11100110*/{ GTE_MC_ENTRY(Bits5EdgeFaceDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11100111*/{ GTE_MC_ENTRY(Bits6BoxDiag), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*11101000*/{ GTE_MC_ENTRY(Bits4FaceEdge), { 7, 5, 6, 4, 3, 1, 2, 0 }}, /*11101001*/{ GTE_MC_ENTRY(Bits5FaceDiagFaceDiag), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*11101010*/{ GTE_MC_ENTRY(Bits5SameFace), { 0, 2, 4, 6, 1, 3, 5, 7 }}, /*11101011*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*11101100*/{ GTE_MC_ENTRY(Bits5SameFace), { 0, 4, 1, 5, 2, 6, 3, 7 }}, /*11101101*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 1, 0, 5, 4, 3, 2, 7, 6 }}, /*11101110*/{ GTE_MC_ENTRY(Bits6Edge), { 4, 0, 6, 2, 5, 1, 7, 3 }}, /*11101111*/{ GTE_MC_ENTRY(Bits7), { 4, 5, 0, 1, 6, 7, 2, 3 }}, /*11110000*/{ GTE_MC_ENTRY(Bits4SameFace), { 4, 6, 5, 7, 0, 2, 1, 3 }}, /*11110001*/{ GTE_MC_ENTRY(Bits5SameFace), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*11110010*/{ GTE_MC_ENTRY(Bits5SameFace), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*11110011*/{ GTE_MC_ENTRY(Bits6Edge), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*11110100*/{ GTE_MC_ENTRY(Bits5SameFace), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*11110101*/{ GTE_MC_ENTRY(Bits6Edge), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*11110110*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11110111*/{ GTE_MC_ENTRY(Bits7), { 3, 2, 1, 0, 7, 6, 5, 4 }}, /*11111000*/{ GTE_MC_ENTRY(Bits5SameFace), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11111001*/{ GTE_MC_ENTRY(Bits6FaceDiag), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*11111010*/{ GTE_MC_ENTRY(Bits6Edge), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*11111011*/{ GTE_MC_ENTRY(Bits7), { 2, 0, 3, 1, 6, 4, 7, 5 }}, /*11111100*/{ GTE_MC_ENTRY(Bits6Edge), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11111101*/{ GTE_MC_ENTRY(Bits7), { 1, 3, 0, 2, 5, 7, 4, 6 }}, /*11111110*/{ GTE_MC_ENTRY(Bits7), { 0, 1, 2, 3, 4, 5, 6, 7 }}, /*11111111*/{ GTE_MC_ENTRY(Bits0), { 0, 1, 2, 3, 4, 5, 6, 7 }} }}; return configuration; } static std::array<std::string, CT_NUM_TYPES>& ConfigurationString() { static std::array<std::string, CT_NUM_TYPES> configurationString = { "Bits0", "Bits1", "Bits7", "Bits2Edge", "Bits6Edge", "Bits2FaceDiag", "Bits6FaceDiag", "Bits2BoxDiag", "Bits6BoxDiag", "Bits3SameFace", "Bits5SameFace", "Bits3EdgeFaceDiag", "Bits5EdgeFaceDiag", "Bits3FaceDiagFaceDiag", "Bits5FaceDiagFaceDiag", "Bits4SameFace", "Bits4FaceEdge", "Bits4FaceFaceDiagL", "Bits4FaceFaceDiagR", "Bits4FaceBoxDiag", "Bits4EdgeEdgePara", "Bits4EdgeEdgePerp" }; return configurationString; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Delaunay3Mesh.h
.h
4,045
127
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.02.01 #pragma once #include <Mathematics/Delaunay3.h> namespace gte { template <typename InputType, typename ComputeType, typename RationalType> class Delaunay3Mesh { public: // Construction. Delaunay3Mesh(Delaunay3<InputType, ComputeType> const& delaunay) : mDelaunay(&delaunay) { } // Mesh information. inline int32_t GetNumVertices() const { return mDelaunay->GetNumVertices(); } inline int32_t GetNumTetrahedra() const { return mDelaunay->GetNumTetrahedra(); } inline Vector3<InputType> const* GetVertices() const { return mDelaunay->GetVertices(); } inline int32_t const* GetIndices() const { return &mDelaunay->GetIndices()[0]; } inline int32_t const* GetAdjacencies() const { return &mDelaunay->GetAdjacencies()[0]; } // Containment queries. int32_t GetContainingTetrahedron(Vector3<InputType> const& P) const { typename Delaunay3<InputType, ComputeType>::SearchInfo info; return mDelaunay->GetContainingTetrahedron(P, info); } bool GetVertices(int32_t t, std::array<Vector3<InputType>, 4>& vertices) const { if (mDelaunay->GetDimension() == 3) { std::array<int32_t, 4> indices; if (mDelaunay->GetIndices(t, indices)) { PrimalQuery3<ComputeType> const& query = mDelaunay->GetQuery(); Vector3<ComputeType> const* ctVertices = query.GetVertices(); for (int32_t i = 0; i < 4; ++i) { Vector3<ComputeType> const& V = ctVertices[indices[i]]; for (int32_t j = 0; j < 3; ++j) { vertices[i][j] = (InputType)V[j]; } } return true; } } return false; } bool GetIndices(int32_t t, std::array<int32_t, 4>& indices) const { return mDelaunay->GetIndices(t, indices); } bool GetAdjacencies(int32_t t, std::array<int32_t, 4>& adjacencies) const { return mDelaunay->GetAdjacencies(t, adjacencies); } bool GetBarycentrics(int32_t t, Vector3<InputType> const& P, std::array<InputType, 4>& bary) const { std::array<int32_t, 4> indices; if (mDelaunay->GetIndices(t, indices)) { PrimalQuery3<ComputeType> const& query = mDelaunay->GetQuery(); Vector3<ComputeType> const* vertices = query.GetVertices(); Vector3<RationalType> rtP{ P[0], P[1], P[2] }; std::array<Vector3<RationalType>, 4> rtV; for (int32_t i = 0; i < 4; ++i) { Vector3<ComputeType> const& V = vertices[indices[i]]; for (int32_t j = 0; j < 3; ++j) { rtV[i][j] = (RationalType)V[j]; } }; std::array<RationalType, 4> rtBary{}; if (ComputeBarycentrics(rtP, rtV[0], rtV[1], rtV[2], rtV[3], rtBary)) { for (int32_t i = 0; i < 4; ++i) { bary[i] = (InputType)rtBary[i]; } return true; } } return false; } private: Delaunay3<InputType, ComputeType> const* mDelaunay; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRay3Rectangle3.h
.h
2,245
65
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3Rectangle3.h> #include <Mathematics/DistPointRectangle.h> #include <Mathematics/Ray.h> // Compute the distance between a ray and a solid rectangle in 3D. // // The ray is P + t * D for t >= 0, where D is not required to be unit length. // // The rectangle has center C, unit-length axis directions W[0] and W[1], and // extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i] // where |s[i]| <= e[i] for all i. // // The closest point on the ray is stored in closest[0] with parameter t. The // closest point on the rectangle is stored in closest[1] with U-coordinates // (s[0],s[1]). When there are infinitely many choices for the pair of closest // points, only one of them is returned. // // TODO: Modify to support non-unit-length W[]. namespace gte { template <typename T> class DCPQuery<T, Ray3<T>, Rectangle3<T>> { public: using LRQuery = DCPQuery<T, Line3<T>, Rectangle3<T>>; using Result = typename LRQuery::Result; Result operator()(Ray3<T> const& ray, Rectangle3<T> const& rectangle) { Result result{}; T const zero = static_cast<T>(0); Line3<T> line(ray.origin, ray.direction); LRQuery lrQuery{}; auto lrResult = lrQuery(line, rectangle); if (lrResult.parameter >= zero) { result = lrResult; } else { DCPQuery<T, Vector3<T>, Rectangle3<T>> prQuery{}; auto prResult = prQuery(ray.origin, rectangle); result.distance = prResult.distance; result.sqrDistance = prResult.sqrDistance; result.parameter = zero; result.cartesian = prResult.cartesian; result.closest[0] = ray.origin; result.closest[1] = prResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpAkima1.h
.h
4,424
155
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <algorithm> #include <array> #include <vector> namespace gte { template <typename Real> class IntpAkima1 { protected: // Construction (abstract base class). IntpAkima1(int32_t quantity, Real const* F) : mQuantity(quantity), mF(F) { // At least three data points are needed to construct the // estimates of the boundary derivatives. LogAssert(mQuantity >= 3, "Invalid input to IntpAkima1 constructor."); mPoly.resize(static_cast<size_t>(mQuantity) - 1); } public: // Abstract base class. virtual ~IntpAkima1() = default; // Member access. inline int32_t GetQuantity() const { return mQuantity; } inline Real const* GetF() const { return mF; } virtual Real GetXMin() const = 0; virtual Real GetXMax() const = 0; // Evaluate the function and its derivatives. The functions clamp the // inputs to xmin <= x <= xmax. The first operator is for function // evaluation. The second operator is for function or derivative // evaluations. The 'order' argument is the order of the derivative // or zero for the function itself. Real operator()(Real x) const { x = std::min(std::max(x, GetXMin()), GetXMax()); int32_t index; Real dx; Lookup(x, index, dx); return mPoly[index](dx); } Real operator()(int32_t order, Real x) const { x = std::min(std::max(x, GetXMin()), GetXMax()); int32_t index; Real dx; Lookup(x, index, dx); return mPoly[index](order, dx); } protected: class Polynomial { public: // P(x) = c[0] + c[1]*x + c[2]*x^2 + c[3]*x^3 inline Real& operator[](int32_t i) { return mCoeff[i]; } Real operator()(Real x) const { return mCoeff[0] + x * (mCoeff[1] + x * (mCoeff[2] + x * mCoeff[3])); } Real operator()(int32_t order, Real x) const { switch (order) { case 0: return mCoeff[0] + x * (mCoeff[1] + x * (mCoeff[2] + x * mCoeff[3])); case 1: return mCoeff[1] + x * ((Real)2 * mCoeff[2] + x * (Real)3 * mCoeff[3]); case 2: return (Real)2 * mCoeff[2] + x * (Real)6 * mCoeff[3]; case 3: return (Real)6 * mCoeff[3]; } return (Real)0; } private: std::array<Real, 4> mCoeff; }; Real ComputeDerivative(Real* slope) const { if (slope[1] != slope[2]) { if (slope[0] != slope[1]) { if (slope[2] != slope[3]) { Real ad0 = std::fabs(slope[3] - slope[2]); Real ad1 = std::fabs(slope[0] - slope[1]); return (ad0 * slope[1] + ad1 * slope[2]) / (ad0 + ad1); } else { return slope[2]; } } else { if (slope[2] != slope[3]) { return slope[1]; } else { return ((Real)0.5)* (slope[1] + slope[2]); } } } else { return slope[1]; } } virtual void Lookup(Real x, int32_t& index, Real& dx) const = 0; int32_t mQuantity; Real const* mF; std::vector<Polynomial> mPoly; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRectangle3AlignedBox3.h
.h
2,294
64
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistRectangle3CanonicalBox3.h> #include <Mathematics/DistSegment3CanonicalBox3.h> #include <Mathematics/AlignedBox.h> // Compute the distance between a rectangle and a solid aligned box in 3D. // // The rectangle has center C, unit-length axis directions W[0] and W[1], and // extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i] // where |s[i]| <= e[i] for all i. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The closest point on the rectangle is stored in closest[0] with // W-coordinates (s[0],s[1]). The closest point on the box is stored in // closest[1]. When there are infinitely many choices for the pair of closest // points, only one of them is returned. // // TODO: Modify to support non-unit-length W[]. namespace gte { template <typename T> class DCPQuery<T, Rectangle3<T>, AlignedBox3<T>> { public: using RBQuery = DCPQuery<T, Rectangle3<T>, CanonicalBox3<T>>; using Result = typename RBQuery::Result; Result operator()(Rectangle3<T> const& rectangle, AlignedBox3<T> const& box) { Result result{}; // Translate the rectangle and box so that the box has center at // the origin. Vector3<T> boxCenter{}; CanonicalBox3<T> cbox{}; box.GetCenteredForm(boxCenter, cbox.extent); Vector3<T> xfrmCenter = rectangle.center - boxCenter; // The query computes 'output' relative to the box with center // at the origin. Rectangle3<T> xfrmRectangle(xfrmCenter, rectangle.axis, rectangle.extent); RBQuery rbQuery{}; result = rbQuery(xfrmRectangle, cbox); // Translate the closest points to the original coordinates. result.closest[0] += boxCenter; result.closest[1] += boxCenter; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Math.h
.h
25,533
656
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.07.04 #pragma once // This file extends the <cmath> support to include convenient constants and // functions. The shared constants for CPU, Intel SSE and GPU lead to // correctly rounded approximations of the constants when using 'float' or // 'double'. The file also includes a type trait, is_arbitrary_precision, // to support selecting between floating-point arithmetic (float, double, //long double) or arbitrary-precision arithmetic (BSNumber<T>, BSRational<T>) // in an implementation using std::enable_if. There is also a type trait, // has_division_operator, to support selecting between numeric types that // have a division operator (BSRational<T>) and those that do not have a // division operator (BSNumber<T>). #include <cfenv> #include <cmath> #include <cstdint> #include <limits> #include <type_traits> // Maximum number of iterations for bisection before a subinterval // degenerates to a single point. TODO: Verify these. I used the formula: // 3 + std::numeric_limits<T>::digits - std::numeric_limits<T>::min_exponent. // IEEEBinary16: digits = 11, min_exponent = -13 // float: digits = 27, min_exponent = -125 // double: digits = 53, min_exponent = -1021 // BSNumber and BSRational use std::numeric_limits<uint32_t>::max(), // but maybe these should be set to a large number or be user configurable. // The MAX_BISECTIONS_GENERIC is an arbitrary choice for now and is used // in template code where Real is the template parameter. #define GTE_C_MAX_BISECTIONS_FLOAT16 27u #define GTE_C_MAX_BISECTIONS_FLOAT32 155u #define GTE_C_MAX_BISECTIONS_FLOAT64 1077u #define GTE_C_MAX_BISECTIONS_BSNUMBER 0xFFFFFFFFu #define GTE_C_MAX_BISECTIONS_BSRATIONAL 0xFFFFFFFFu #define GTE_C_MAX_BISECTIONS_GENERIC 2048u // Constants involving pi. #define GTE_C_PI 3.1415926535897931 #define GTE_C_HALF_PI 1.5707963267948966 #define GTE_C_QUARTER_PI 0.7853981633974483 #define GTE_C_TWO_PI 6.2831853071795862 #define GTE_C_INV_PI 0.3183098861837907 #define GTE_C_INV_TWO_PI 0.1591549430918953 #define GTE_C_INV_HALF_PI 0.6366197723675813 // Conversions between degrees and radians. #define GTE_C_DEG_TO_RAD 0.0174532925199433 #define GTE_C_RAD_TO_DEG 57.295779513082321 // Common constants. #define GTE_C_SQRT_2 1.4142135623730951 #define GTE_C_INV_SQRT_2 0.7071067811865475 #define GTE_C_LN_2 0.6931471805599453 #define GTE_C_INV_LN_2 1.4426950408889634 #define GTE_C_LN_10 2.3025850929940459 #define GTE_C_INV_LN_10 0.43429448190325176 // Constants for minimax polynomial approximations to sqrt(x). // The algorithm minimizes the maximum absolute error on [1,2]. #define GTE_C_SQRT_DEG1_C0 +1.0 #define GTE_C_SQRT_DEG1_C1 +4.1421356237309505e-01 #define GTE_C_SQRT_DEG1_MAX_ERROR 1.7766952966368793e-2 #define GTE_C_SQRT_DEG2_C0 +1.0 #define GTE_C_SQRT_DEG2_C1 +4.8563183076125260e-01 #define GTE_C_SQRT_DEG2_C2 -7.1418268388157458e-02 #define GTE_C_SQRT_DEG2_MAX_ERROR 1.1795695163108744e-3 #define GTE_C_SQRT_DEG3_C0 +1.0 #define GTE_C_SQRT_DEG3_C1 +4.9750045320242231e-01 #define GTE_C_SQRT_DEG3_C2 -1.0787308044477850e-01 #define GTE_C_SQRT_DEG3_C3 +2.4586189615451115e-02 #define GTE_C_SQRT_DEG3_MAX_ERROR 1.1309620116468910e-4 #define GTE_C_SQRT_DEG4_C0 +1.0 #define GTE_C_SQRT_DEG4_C1 +4.9955939832918816e-01 #define GTE_C_SQRT_DEG4_C2 -1.2024066151943025e-01 #define GTE_C_SQRT_DEG4_C3 +4.5461507257698486e-02 #define GTE_C_SQRT_DEG4_C4 -1.0566681694362146e-02 #define GTE_C_SQRT_DEG4_MAX_ERROR 1.2741170151556180e-5 #define GTE_C_SQRT_DEG5_C0 +1.0 #define GTE_C_SQRT_DEG5_C1 +4.9992197660031912e-01 #define GTE_C_SQRT_DEG5_C2 -1.2378506719245053e-01 #define GTE_C_SQRT_DEG5_C3 +5.6122776972699739e-02 #define GTE_C_SQRT_DEG5_C4 -2.3128836281145482e-02 #define GTE_C_SQRT_DEG5_C5 +5.0827122737047148e-03 #define GTE_C_SQRT_DEG5_MAX_ERROR 1.5725568940708201e-6 #define GTE_C_SQRT_DEG6_C0 +1.0 #define GTE_C_SQRT_DEG6_C1 +4.9998616695784914e-01 #define GTE_C_SQRT_DEG6_C2 -1.2470733323278438e-01 #define GTE_C_SQRT_DEG6_C3 +6.0388587356982271e-02 #define GTE_C_SQRT_DEG6_C4 -3.1692053551807930e-02 #define GTE_C_SQRT_DEG6_C5 +1.2856590305148075e-02 #define GTE_C_SQRT_DEG6_C6 -2.6183954624343642e-03 #define GTE_C_SQRT_DEG6_MAX_ERROR 2.0584155535630089e-7 #define GTE_C_SQRT_DEG7_C0 +1.0 #define GTE_C_SQRT_DEG7_C1 +4.9999754817809228e-01 #define GTE_C_SQRT_DEG7_C2 -1.2493243476353655e-01 #define GTE_C_SQRT_DEG7_C3 +6.1859954146370910e-02 #define GTE_C_SQRT_DEG7_C4 -3.6091595023208356e-02 #define GTE_C_SQRT_DEG7_C5 +1.9483946523450868e-02 #define GTE_C_SQRT_DEG7_C6 -7.5166134568007692e-03 #define GTE_C_SQRT_DEG7_C7 +1.4127567687864939e-03 #define GTE_C_SQRT_DEG7_MAX_ERROR 2.8072302919734948e-8 #define GTE_C_SQRT_DEG8_C0 +1.0 #define GTE_C_SQRT_DEG8_C1 +4.9999956583056759e-01 #define GTE_C_SQRT_DEG8_C2 -1.2498490369914350e-01 #define GTE_C_SQRT_DEG8_C3 +6.2318494667579216e-02 #define GTE_C_SQRT_DEG8_C4 -3.7982961896432244e-02 #define GTE_C_SQRT_DEG8_C5 +2.3642612312869460e-02 #define GTE_C_SQRT_DEG8_C6 -1.2529377587270574e-02 #define GTE_C_SQRT_DEG8_C7 +4.5382426960713929e-03 #define GTE_C_SQRT_DEG8_C8 -7.8810995273670414e-04 #define GTE_C_SQRT_DEG8_MAX_ERROR 3.9460605685825989e-9 // Constants for minimax polynomial approximations to 1/sqrt(x). // The algorithm minimizes the maximum absolute error on [1,2]. #define GTE_C_INVSQRT_DEG1_C0 +1.0 #define GTE_C_INVSQRT_DEG1_C1 -2.9289321881345254e-01 #define GTE_C_INVSQRT_DEG1_MAX_ERROR 3.7814314552701983e-2 #define GTE_C_INVSQRT_DEG2_C0 +1.0 #define GTE_C_INVSQRT_DEG2_C1 -4.4539812104566801e-01 #define GTE_C_INVSQRT_DEG2_C2 +1.5250490223221547e-01 #define GTE_C_INVSQRT_DEG2_MAX_ERROR 4.1953446330581234e-3 #define GTE_C_INVSQRT_DEG3_C0 +1.0 #define GTE_C_INVSQRT_DEG3_C1 -4.8703230993068791e-01 #define GTE_C_INVSQRT_DEG3_C2 +2.8163710486669835e-01 #define GTE_C_INVSQRT_DEG3_C3 -8.7498013749463421e-02 #define GTE_C_INVSQRT_DEG3_MAX_ERROR 5.6307702007266786e-4 #define GTE_C_INVSQRT_DEG4_C0 +1.0 #define GTE_C_INVSQRT_DEG4_C1 -4.9710061558048779e-01 #define GTE_C_INVSQRT_DEG4_C2 +3.4266247597676802e-01 #define GTE_C_INVSQRT_DEG4_C3 -1.9106356536293490e-01 #define GTE_C_INVSQRT_DEG4_C4 +5.2608486153198797e-02 #define GTE_C_INVSQRT_DEG4_MAX_ERROR 8.1513919987605266e-5 #define GTE_C_INVSQRT_DEG5_C0 +1.0 #define GTE_C_INVSQRT_DEG5_C1 -4.9937760586004143e-01 #define GTE_C_INVSQRT_DEG5_C2 +3.6508741295133973e-01 #define GTE_C_INVSQRT_DEG5_C3 -2.5884890281853501e-01 #define GTE_C_INVSQRT_DEG5_C4 +1.3275782221320753e-01 #define GTE_C_INVSQRT_DEG5_C5 -3.2511945299404488e-02 #define GTE_C_INVSQRT_DEG5_MAX_ERROR 1.2289367475583346e-5 #define GTE_C_INVSQRT_DEG6_C0 +1.0 #define GTE_C_INVSQRT_DEG6_C1 -4.9987029229547453e-01 #define GTE_C_INVSQRT_DEG6_C2 +3.7220923604495226e-01 #define GTE_C_INVSQRT_DEG6_C3 -2.9193067713256937e-01 #define GTE_C_INVSQRT_DEG6_C4 +1.9937605991094642e-01 #define GTE_C_INVSQRT_DEG6_C5 -9.3135712130901993e-02 #define GTE_C_INVSQRT_DEG6_C6 +2.0458166789566690e-02 #define GTE_C_INVSQRT_DEG6_MAX_ERROR 1.9001451223750465e-6 #define GTE_C_INVSQRT_DEG7_C0 +1.0 #define GTE_C_INVSQRT_DEG7_C1 -4.9997357250704977e-01 #define GTE_C_INVSQRT_DEG7_C2 +3.7426216884998809e-01 #define GTE_C_INVSQRT_DEG7_C3 -3.0539882498248971e-01 #define GTE_C_INVSQRT_DEG7_C4 +2.3976005607005391e-01 #define GTE_C_INVSQRT_DEG7_C5 -1.5410326351684489e-01 #define GTE_C_INVSQRT_DEG7_C6 +6.5598809723041995e-02 #define GTE_C_INVSQRT_DEG7_C7 -1.3038592450470787e-02 #define GTE_C_INVSQRT_DEG7_MAX_ERROR 2.9887724993168940e-7 #define GTE_C_INVSQRT_DEG8_C0 +1.0 #define GTE_C_INVSQRT_DEG8_C1 -4.9999471066120371e-01 #define GTE_C_INVSQRT_DEG8_C2 +3.7481415745794067e-01 #define GTE_C_INVSQRT_DEG8_C3 -3.1023804387422160e-01 #define GTE_C_INVSQRT_DEG8_C4 +2.5977002682930106e-01 #define GTE_C_INVSQRT_DEG8_C5 -1.9818790717727097e-01 #define GTE_C_INVSQRT_DEG8_C6 +1.1882414252613671e-01 #define GTE_C_INVSQRT_DEG8_C7 -4.6270038088550791e-02 #define GTE_C_INVSQRT_DEG8_C8 +8.3891541755747312e-03 #define GTE_C_INVSQRT_DEG8_MAX_ERROR 4.7596926146947771e-8 // Constants for minimax polynomial approximations to sin(x). // The algorithm minimizes the maximum absolute error on [-pi/2,pi/2]. #define GTE_C_SIN_DEG3_C0 +1.0 #define GTE_C_SIN_DEG3_C1 -1.4727245910375519e-01 #define GTE_C_SIN_DEG3_MAX_ERROR 1.3481903639145865e-2 #define GTE_C_SIN_DEG5_C0 +1.0 #define GTE_C_SIN_DEG5_C1 -1.6600599923812209e-01 #define GTE_C_SIN_DEG5_C2 +7.5924178409012000e-03 #define GTE_C_SIN_DEG5_MAX_ERROR 1.4001209384639779e-4 #define GTE_C_SIN_DEG7_C0 +1.0 #define GTE_C_SIN_DEG7_C1 -1.6665578084732124e-01 #define GTE_C_SIN_DEG7_C2 +8.3109378830028557e-03 #define GTE_C_SIN_DEG7_C3 -1.8447486103462252e-04 #define GTE_C_SIN_DEG7_MAX_ERROR 1.0205878936686563e-6 #define GTE_C_SIN_DEG9_C0 +1.0 #define GTE_C_SIN_DEG9_C1 -1.6666656235308897e-01 #define GTE_C_SIN_DEG9_C2 +8.3329962509886002e-03 #define GTE_C_SIN_DEG9_C3 -1.9805100675274190e-04 #define GTE_C_SIN_DEG9_C4 +2.5967200279475300e-06 #define GTE_C_SIN_DEG9_MAX_ERROR 5.2010746265374053e-9 #define GTE_C_SIN_DEG11_C0 +1.0 #define GTE_C_SIN_DEG11_C1 -1.6666666601721269e-01 #define GTE_C_SIN_DEG11_C2 +8.3333303183525942e-03 #define GTE_C_SIN_DEG11_C3 -1.9840782426250314e-04 #define GTE_C_SIN_DEG11_C4 +2.7521557770526783e-06 #define GTE_C_SIN_DEG11_C5 -2.3828544692960918e-08 #define GTE_C_SIN_DEG11_MAX_ERROR 1.9295870457014530e-11 // Constants for minimax polynomial approximations to cos(x). // The algorithm minimizes the maximum absolute error on [-pi/2,pi/2]. #define GTE_C_COS_DEG2_C0 +1.0 #define GTE_C_COS_DEG2_C1 -4.0528473456935105e-01 #define GTE_C_COS_DEG2_MAX_ERROR 5.4870946878404048e-2 #define GTE_C_COS_DEG4_C0 +1.0 #define GTE_C_COS_DEG4_C1 -4.9607181958647262e-01 #define GTE_C_COS_DEG4_C2 +3.6794619653489236e-02 #define GTE_C_COS_DEG4_MAX_ERROR 9.1879932449712154e-4 #define GTE_C_COS_DEG6_C0 +1.0 #define GTE_C_COS_DEG6_C1 -4.9992746217057404e-01 #define GTE_C_COS_DEG6_C2 +4.1493920348353308e-02 #define GTE_C_COS_DEG6_C3 -1.2712435011987822e-03 #define GTE_C_COS_DEG6_MAX_ERROR 9.2028470133065365e-6 #define GTE_C_COS_DEG8_C0 +1.0 #define GTE_C_COS_DEG8_C1 -4.9999925121358291e-01 #define GTE_C_COS_DEG8_C2 +4.1663780117805693e-02 #define GTE_C_COS_DEG8_C3 -1.3854239405310942e-03 #define GTE_C_COS_DEG8_C4 +2.3154171575501259e-05 #define GTE_C_COS_DEG8_MAX_ERROR 5.9804533020235695e-8 #define GTE_C_COS_DEG10_C0 +1.0 #define GTE_C_COS_DEG10_C1 -4.9999999508695869e-01 #define GTE_C_COS_DEG10_C2 +4.1666638865338612e-02 #define GTE_C_COS_DEG10_C3 -1.3888377661039897e-03 #define GTE_C_COS_DEG10_C4 +2.4760495088926859e-05 #define GTE_C_COS_DEG10_C5 -2.6051615464872668e-07 #define GTE_C_COS_DEG10_MAX_ERROR 2.7006769043325107e-10 // Constants for minimax polynomial approximations to tan(x). // The algorithm minimizes the maximum absolute error on [-pi/4,pi/4]. #define GTE_C_TAN_DEG3_C0 1.0 #define GTE_C_TAN_DEG3_C1 4.4295926544736286e-01 #define GTE_C_TAN_DEG3_MAX_ERROR 1.1661892256204731e-2 #define GTE_C_TAN_DEG5_C0 1.0 #define GTE_C_TAN_DEG5_C1 3.1401320403542421e-01 #define GTE_C_TAN_DEG5_C2 2.0903948109240345e-01 #define GTE_C_TAN_DEG5_MAX_ERROR 5.8431854390143118e-4 #define GTE_C_TAN_DEG7_C0 1.0 #define GTE_C_TAN_DEG7_C1 3.3607213284422555e-01 #define GTE_C_TAN_DEG7_C2 1.1261037305184907e-01 #define GTE_C_TAN_DEG7_C3 9.8352099470524479e-02 #define GTE_C_TAN_DEG7_MAX_ERROR 3.5418688397723108e-5 #define GTE_C_TAN_DEG9_C0 1.0 #define GTE_C_TAN_DEG9_C1 3.3299232843941784e-01 #define GTE_C_TAN_DEG9_C2 1.3747843432474838e-01 #define GTE_C_TAN_DEG9_C3 3.7696344813028304e-02 #define GTE_C_TAN_DEG9_C4 4.6097377279281204e-02 #define GTE_C_TAN_DEG9_MAX_ERROR 2.2988173242199927e-6 #define GTE_C_TAN_DEG11_C0 1.0 #define GTE_C_TAN_DEG11_C1 3.3337224456224224e-01 #define GTE_C_TAN_DEG11_C2 1.3264516053824593e-01 #define GTE_C_TAN_DEG11_C3 5.8145237645931047e-02 #define GTE_C_TAN_DEG11_C4 1.0732193237572574e-02 #define GTE_C_TAN_DEG11_C5 2.1558456793513869e-02 #define GTE_C_TAN_DEG11_MAX_ERROR 1.5426257940140409e-7 #define GTE_C_TAN_DEG13_C0 1.0 #define GTE_C_TAN_DEG13_C1 3.3332916426394554e-01 #define GTE_C_TAN_DEG13_C2 1.3343404625112498e-01 #define GTE_C_TAN_DEG13_C3 5.3104565343119248e-02 #define GTE_C_TAN_DEG13_C4 2.5355038312682154e-02 #define GTE_C_TAN_DEG13_C5 1.8253255966556026e-03 #define GTE_C_TAN_DEG13_C6 1.0069407176615641e-02 #define GTE_C_TAN_DEG13_MAX_ERROR 1.0550264249037378e-8 // Constants for minimax polynomial approximations to acos(x), where the // approximation is of the form acos(x) = sqrt(1 - x)*p(x) with p(x) a // polynomial. The algorithm minimizes the maximum error // |acos(x)/sqrt(1-x) - p(x)| on [0,1]. At the same time we get an // approximation for asin(x) = pi/2 - acos(x). #define GTE_C_ACOS_DEG1_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG1_C1 -1.5658276442180141e-01 #define GTE_C_ACOS_DEG1_MAX_ERROR 1.1659002803738105e-2 #define GTE_C_ACOS_DEG2_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG2_C1 -2.0347053865798365e-01 #define GTE_C_ACOS_DEG2_C2 +4.6887774236182234e-02 #define GTE_C_ACOS_DEG2_MAX_ERROR 9.0311602490029258e-4 #define GTE_C_ACOS_DEG3_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG3_C1 -2.1253291899190285e-01 #define GTE_C_ACOS_DEG3_C2 +7.4773789639484223e-02 #define GTE_C_ACOS_DEG3_C3 -1.8823635069382449e-02 #define GTE_C_ACOS_DEG3_MAX_ERROR 9.3066396954288172e-5 #define GTE_C_ACOS_DEG4_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG4_C1 -2.1422258835275865e-01 #define GTE_C_ACOS_DEG4_C2 +8.4936675142844198e-02 #define GTE_C_ACOS_DEG4_C3 -3.5991475120957794e-02 #define GTE_C_ACOS_DEG4_C4 +8.6946239090712751e-03 #define GTE_C_ACOS_DEG4_MAX_ERROR 1.0930595804481413e-5 #define GTE_C_ACOS_DEG5_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG5_C1 -2.1453292139805524e-01 #define GTE_C_ACOS_DEG5_C2 +8.7973089282889383e-02 #define GTE_C_ACOS_DEG5_C3 -4.5130266382166440e-02 #define GTE_C_ACOS_DEG5_C4 +1.9467466687281387e-02 #define GTE_C_ACOS_DEG5_C5 -4.3601326117634898e-03 #define GTE_C_ACOS_DEG5_MAX_ERROR 1.3861070257241426-6 #define GTE_C_ACOS_DEG6_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG6_C1 -2.1458939285677325e-01 #define GTE_C_ACOS_DEG6_C2 +8.8784960563641491e-02 #define GTE_C_ACOS_DEG6_C3 -4.8887131453156485e-02 #define GTE_C_ACOS_DEG6_C4 +2.7011519960012720e-02 #define GTE_C_ACOS_DEG6_C5 -1.1210537323478320e-02 #define GTE_C_ACOS_DEG6_C6 +2.3078166879102469e-03 #define GTE_C_ACOS_DEG6_MAX_ERROR 1.8491291330427484e-7 #define GTE_C_ACOS_DEG7_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG7_C1 -2.1459960076929829e-01 #define GTE_C_ACOS_DEG7_C2 +8.8986946573346160e-02 #define GTE_C_ACOS_DEG7_C3 -5.0207843052845647e-02 #define GTE_C_ACOS_DEG7_C4 +3.0961594977611639e-02 #define GTE_C_ACOS_DEG7_C5 -1.7162031184398074e-02 #define GTE_C_ACOS_DEG7_C6 +6.7072304676685235e-03 #define GTE_C_ACOS_DEG7_C7 -1.2690614339589956e-03 #define GTE_C_ACOS_DEG7_MAX_ERROR 2.5574620927948377e-8 #define GTE_C_ACOS_DEG8_C0 +1.5707963267948966 #define GTE_C_ACOS_DEG8_C1 -2.1460143648688035e-01 #define GTE_C_ACOS_DEG8_C2 +8.9034700107934128e-02 #define GTE_C_ACOS_DEG8_C3 -5.0625279962389413e-02 #define GTE_C_ACOS_DEG8_C4 +3.2683762943179318e-02 #define GTE_C_ACOS_DEG8_C5 -2.0949278766238422e-02 #define GTE_C_ACOS_DEG8_C6 +1.1272900916992512e-02 #define GTE_C_ACOS_DEG8_C7 -4.1160981058965262e-03 #define GTE_C_ACOS_DEG8_C8 +7.1796493341480527e-04 #define GTE_C_ACOS_DEG8_MAX_ERROR 3.6340015129032732e-9 // Constants for minimax polynomial approximations to atan(x). // The algorithm minimizes the maximum absolute error on [-1,1]. #define GTE_C_ATAN_DEG3_C0 +1.0 #define GTE_C_ATAN_DEG3_C1 -2.1460183660255172e-01 #define GTE_C_ATAN_DEG3_MAX_ERROR 1.5970326392614240e-2 #define GTE_C_ATAN_DEG5_C0 +1.0 #define GTE_C_ATAN_DEG5_C1 -3.0189478312144946e-01 #define GTE_C_ATAN_DEG5_C2 +8.7292946518897740e-02 #define GTE_C_ATAN_DEG5_MAX_ERROR 1.3509832247372636e-3 #define GTE_C_ATAN_DEG7_C0 +1.0 #define GTE_C_ATAN_DEG7_C1 -3.2570157599356531e-01 #define GTE_C_ATAN_DEG7_C2 +1.5342994884206673e-01 #define GTE_C_ATAN_DEG7_C3 -4.2330209451053591e-02 #define GTE_C_ATAN_DEG7_MAX_ERROR 1.5051227215514412e-4 #define GTE_C_ATAN_DEG9_C0 +1.0 #define GTE_C_ATAN_DEG9_C1 -3.3157878236439586e-01 #define GTE_C_ATAN_DEG9_C2 +1.8383034738018011e-01 #define GTE_C_ATAN_DEG9_C3 -8.9253037587244677e-02 #define GTE_C_ATAN_DEG9_C4 +2.2399635968909593e-02 #define GTE_C_ATAN_DEG9_MAX_ERROR 1.8921598624582064e-5 #define GTE_C_ATAN_DEG11_C0 +1.0 #define GTE_C_ATAN_DEG11_C1 -3.3294527685374087e-01 #define GTE_C_ATAN_DEG11_C2 +1.9498657165383548e-01 #define GTE_C_ATAN_DEG11_C3 -1.1921576270475498e-01 #define GTE_C_ATAN_DEG11_C4 +5.5063351366968050e-02 #define GTE_C_ATAN_DEG11_C5 -1.2490720064867844e-02 #define GTE_C_ATAN_DEG11_MAX_ERROR 2.5477724974187765e-6 #define GTE_C_ATAN_DEG13_C0 +1.0 #define GTE_C_ATAN_DEG13_C1 -3.3324998579202170e-01 #define GTE_C_ATAN_DEG13_C2 +1.9856563505717162e-01 #define GTE_C_ATAN_DEG13_C3 -1.3374657325451267e-01 #define GTE_C_ATAN_DEG13_C4 +8.1675882859940430e-02 #define GTE_C_ATAN_DEG13_C5 -3.5059680836411644e-02 #define GTE_C_ATAN_DEG13_C6 +7.2128853633444123e-03 #define GTE_C_ATAN_DEG13_MAX_ERROR 3.5859104691865484e-7 // Constants for minimax polynomial approximations to exp2(x) = 2^x. // The algorithm minimizes the maximum absolute error on [0,1]. #define GTE_C_EXP2_DEG1_C0 1.0 #define GTE_C_EXP2_DEG1_C1 1.0 #define GTE_C_EXP2_DEG1_MAX_ERROR 8.6071332055934313e-2 #define GTE_C_EXP2_DEG2_C0 1.0 #define GTE_C_EXP2_DEG2_C1 6.5571332605741528e-01 #define GTE_C_EXP2_DEG2_C2 3.4428667394258472e-01 #define GTE_C_EXP2_DEG2_MAX_ERROR 3.8132476831060358e-3 #define GTE_C_EXP2_DEG3_C0 1.0 #define GTE_C_EXP2_DEG3_C1 6.9589012084456225e-01 #define GTE_C_EXP2_DEG3_C2 2.2486494900110188e-01 #define GTE_C_EXP2_DEG3_C3 7.9244930154334980e-02 #define GTE_C_EXP2_DEG3_MAX_ERROR 1.4694877755186408e-4 #define GTE_C_EXP2_DEG4_C0 1.0 #define GTE_C_EXP2_DEG4_C1 6.9300392358459195e-01 #define GTE_C_EXP2_DEG4_C2 2.4154981722455560e-01 #define GTE_C_EXP2_DEG4_C3 5.1744260331489045e-02 #define GTE_C_EXP2_DEG4_C4 1.3701998859367848e-02 #define GTE_C_EXP2_DEG4_MAX_ERROR 4.7617792624521371e-6 #define GTE_C_EXP2_DEG5_C0 1.0 #define GTE_C_EXP2_DEG5_C1 6.9315298010274962e-01 #define GTE_C_EXP2_DEG5_C2 2.4014712313022102e-01 #define GTE_C_EXP2_DEG5_C3 5.5855296413199085e-02 #define GTE_C_EXP2_DEG5_C4 8.9477503096873079e-03 #define GTE_C_EXP2_DEG5_C5 1.8968500441332026e-03 #define GTE_C_EXP2_DEG5_MAX_ERROR 1.3162098333463490e-7 #define GTE_C_EXP2_DEG6_C0 1.0 #define GTE_C_EXP2_DEG6_C1 6.9314698914837525e-01 #define GTE_C_EXP2_DEG6_C2 2.4023013440952923e-01 #define GTE_C_EXP2_DEG6_C3 5.5481276898206033e-02 #define GTE_C_EXP2_DEG6_C4 9.6838443037086108e-03 #define GTE_C_EXP2_DEG6_C5 1.2388324048515642e-03 #define GTE_C_EXP2_DEG6_C6 2.1892283501756538e-04 #define GTE_C_EXP2_DEG6_MAX_ERROR 3.1589168225654163e-9 #define GTE_C_EXP2_DEG7_C0 1.0 #define GTE_C_EXP2_DEG7_C1 6.9314718588750690e-01 #define GTE_C_EXP2_DEG7_C2 2.4022637363165700e-01 #define GTE_C_EXP2_DEG7_C3 5.5505235570535660e-02 #define GTE_C_EXP2_DEG7_C4 9.6136265387940512e-03 #define GTE_C_EXP2_DEG7_C5 1.3429234504656051e-03 #define GTE_C_EXP2_DEG7_C6 1.4299202757683815e-04 #define GTE_C_EXP2_DEG7_C7 2.1662892777385423e-05 #define GTE_C_EXP2_DEG7_MAX_ERROR 6.6864513925679603e-11 // Constants for minimax polynomial approximations to log2(x). // The algorithm minimizes the maximum absolute error on [1,2]. // The polynomials all have constant term zero. #define GTE_C_LOG2_DEG1_C1 +1.0 #define GTE_C_LOG2_DEG1_MAX_ERROR 8.6071332055934202e-2 #define GTE_C_LOG2_DEG2_C1 +1.3465553856377803 #define GTE_C_LOG2_DEG2_C2 -3.4655538563778032e-01 #define GTE_C_LOG2_DEG2_MAX_ERROR 7.6362868906658110e-3 #define GTE_C_LOG2_DEG3_C1 +1.4228653756681227 #define GTE_C_LOG2_DEG3_C2 -5.8208556916449616e-01 #define GTE_C_LOG2_DEG3_C3 +1.5922019349637218e-01 #define GTE_C_LOG2_DEG3_MAX_ERROR 8.7902902652883808e-4 #define GTE_C_LOG2_DEG4_C1 +1.4387257478171547 #define GTE_C_LOG2_DEG4_C2 -6.7778401359918661e-01 #define GTE_C_LOG2_DEG4_C3 +3.2118898377713379e-01 #define GTE_C_LOG2_DEG4_C4 -8.2130717995088531e-02 #define GTE_C_LOG2_DEG4_MAX_ERROR 1.1318551355360418e-4 #define GTE_C_LOG2_DEG5_C1 +1.4419170408633741 #define GTE_C_LOG2_DEG5_C2 -7.0909645927612530e-01 #define GTE_C_LOG2_DEG5_C3 +4.1560609399164150e-01 #define GTE_C_LOG2_DEG5_C4 -1.9357573729558908e-01 #define GTE_C_LOG2_DEG5_C5 +4.5149061716699634e-02 #define GTE_C_LOG2_DEG5_MAX_ERROR 1.5521274478735858e-5 #define GTE_C_LOG2_DEG6_C1 +1.4425449435950917 #define GTE_C_LOG2_DEG6_C2 -7.1814525675038965e-01 #define GTE_C_LOG2_DEG6_C3 +4.5754919692564044e-01 #define GTE_C_LOG2_DEG6_C4 -2.7790534462849337e-01 #define GTE_C_LOG2_DEG6_C5 +1.2179791068763279e-01 #define GTE_C_LOG2_DEG6_C6 -2.5841449829670182e-02 #define GTE_C_LOG2_DEG6_MAX_ERROR 2.2162051216689793e-6 #define GTE_C_LOG2_DEG7_C1 +1.4426664401536078 #define GTE_C_LOG2_DEG7_C2 -7.2055423726162360e-01 #define GTE_C_LOG2_DEG7_C3 +4.7332419162501083e-01 #define GTE_C_LOG2_DEG7_C4 -3.2514018752954144e-01 #define GTE_C_LOG2_DEG7_C5 +1.9302965529095673e-01 #define GTE_C_LOG2_DEG7_C6 -7.8534970641157997e-02 #define GTE_C_LOG2_DEG7_C7 +1.5209108363023915e-02 #define GTE_C_LOG2_DEG7_MAX_ERROR 3.2546531700261561e-7 #define GTE_C_LOG2_DEG8_C1 +1.4426896453621882 #define GTE_C_LOG2_DEG8_C2 -7.2115893912535967e-01 #define GTE_C_LOG2_DEG8_C3 +4.7861716616785088e-01 #define GTE_C_LOG2_DEG8_C4 -3.4699935395019565e-01 #define GTE_C_LOG2_DEG8_C5 +2.4114048765477492e-01 #define GTE_C_LOG2_DEG8_C6 -1.3657398692885181e-01 #define GTE_C_LOG2_DEG8_C7 +5.1421382871922106e-02 #define GTE_C_LOG2_DEG8_C8 -9.1364020499895560e-03 #define GTE_C_LOG2_DEG8_MAX_ERROR 4.8796219218050219e-8 // These functions are convenient for some applications. The classes // BSNumber, BSRational and IEEEBinary16 have implementations that // (for now) use typecasting to call the 'float' or 'double' versions. namespace gte { inline float atandivpi(float x) { return std::atan(x) * (float)GTE_C_INV_PI; } inline float atan2divpi(float y, float x) { return std::atan2(y, x) * (float)GTE_C_INV_PI; } inline float clamp(float x, float xmin, float xmax) { return (x <= xmin ? xmin : (x >= xmax ? xmax : x)); } inline float cospi(float x) { return std::cos(x * (float)GTE_C_PI); } inline float exp10(float x) { return std::exp(x * (float)GTE_C_LN_10); } inline float invsqrt(float x) { return 1.0f / std::sqrt(x); } inline int32_t isign(float x) { return (x > 0.0f ? 1 : (x < 0.0f ? -1 : 0)); } inline float saturate(float x) { return (x <= 0.0f ? 0.0f : (x >= 1.0f ? 1.0f : x)); } inline float sign(float x) { return (x > 0.0f ? 1.0f : (x < 0.0f ? -1.0f : 0.0f)); } inline float sinpi(float x) { return std::sin(x * (float)GTE_C_PI); } inline float sqr(float x) { return x * x; } inline double atandivpi(double x) { return std::atan(x) * GTE_C_INV_PI; } inline double atan2divpi(double y, double x) { return std::atan2(y, x) * GTE_C_INV_PI; } inline double clamp(double x, double xmin, double xmax) { return (x <= xmin ? xmin : (x >= xmax ? xmax : x)); } inline double cospi(double x) { return std::cos(x * GTE_C_PI); } inline double exp10(double x) { return std::exp(x * GTE_C_LN_10); } inline double invsqrt(double x) { return 1.0 / std::sqrt(x); } inline double sign(double x) { return (x > 0.0 ? 1.0 : (x < 0.0 ? -1.0 : 0.0f)); } inline int32_t isign(double x) { return (x > 0.0 ? 1 : (x < 0.0 ? -1 : 0)); } inline double saturate(double x) { return (x <= 0.0 ? 0.0 : (x >= 1.0 ? 1.0 : x)); } inline double sinpi(double x) { return std::sin(x * GTE_C_PI); } inline double sqr(double x) { return x * x; } } // Type traits to support std::enable_if conditional compilation for // numerical computations. namespace gte { // The trait is_arbitrary_precision<T> for type T of float, double or // long double generates is_arbitrary_precision<T>::value of false. The // implementations for arbitrary-precision arithmetic are found in // ArbitraryPrecision.h. template <typename T> struct is_arbitrary_precision_internal : std::false_type {}; template <typename T> struct is_arbitrary_precision : is_arbitrary_precision_internal<T>::type {}; // The trait has_division_operator<T> for type T of float, double or // long double generates has_division_operator<T>::value of true. The // implementations for arbitrary-precision arithmetic are found in // ArbitraryPrecision.h. template <typename T> struct has_division_operator_internal : std::false_type {}; template <typename T> struct has_division_operator : has_division_operator_internal<T>::type {}; template <> struct has_division_operator_internal<float> : std::true_type {}; template <> struct has_division_operator_internal<double> : std::true_type {}; template <> struct has_division_operator_internal<long double> : std::true_type {}; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ACosEstimate.h
.h
4,873
138
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> // Approximations to acos(x) of the form f(x) = sqrt(1-x)*p(x) // where the polynomial p(x) of degree D minimizes the quantity // maximum{|acos(x)/sqrt(1-x) - p(x)| : x in [0,1]} over all // polynomials of degree D. namespace gte { template <typename Real> class ACosEstimate { public: // The input constraint is x in [0,1]. For example, // float x; // in [0,1] // float result = ACosEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { return Evaluate(degree<D>(), x); } private: // Metaprogramming and private implementation to allow specialization // of a template member function. template <int32_t D> struct degree {}; inline static Real Evaluate(degree<1>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG1_C1; poly = (Real)GTE_C_ACOS_DEG1_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<2>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG2_C2; poly = (Real)GTE_C_ACOS_DEG2_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG2_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<3>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG3_C3; poly = (Real)GTE_C_ACOS_DEG3_C2 + poly * x; poly = (Real)GTE_C_ACOS_DEG3_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG3_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<4>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG4_C4; poly = (Real)GTE_C_ACOS_DEG4_C3 + poly * x; poly = (Real)GTE_C_ACOS_DEG4_C2 + poly * x; poly = (Real)GTE_C_ACOS_DEG4_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG4_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<5>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG5_C5; poly = (Real)GTE_C_ACOS_DEG5_C4 + poly * x; poly = (Real)GTE_C_ACOS_DEG5_C3 + poly * x; poly = (Real)GTE_C_ACOS_DEG5_C2 + poly * x; poly = (Real)GTE_C_ACOS_DEG5_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG5_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<6>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG6_C6; poly = (Real)GTE_C_ACOS_DEG6_C5 + poly * x; poly = (Real)GTE_C_ACOS_DEG6_C4 + poly * x; poly = (Real)GTE_C_ACOS_DEG6_C3 + poly * x; poly = (Real)GTE_C_ACOS_DEG6_C2 + poly * x; poly = (Real)GTE_C_ACOS_DEG6_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG6_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<7>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG7_C7; poly = (Real)GTE_C_ACOS_DEG7_C6 + poly * x; poly = (Real)GTE_C_ACOS_DEG7_C5 + poly * x; poly = (Real)GTE_C_ACOS_DEG7_C4 + poly * x; poly = (Real)GTE_C_ACOS_DEG7_C3 + poly * x; poly = (Real)GTE_C_ACOS_DEG7_C2 + poly * x; poly = (Real)GTE_C_ACOS_DEG7_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG7_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } inline static Real Evaluate(degree<8>, Real x) { Real poly; poly = (Real)GTE_C_ACOS_DEG8_C8; poly = (Real)GTE_C_ACOS_DEG8_C7 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C6 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C5 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C4 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C3 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C2 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C1 + poly * x; poly = (Real)GTE_C_ACOS_DEG8_C0 + poly * x; poly = poly * std::sqrt((Real)1 - x); return poly; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox2OrientedBox2.h
.h
10,346
294
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/OrientedBox.h> #include <Mathematics/Vector2.h> #include <vector> // The queries consider the box to be a solid. // // The test-intersection query uses the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The set of potential separating directions includes the 2 edge normals of // box0 and the 2 edge normals of box1. The integer 'separating' identifies // the axis that reported separation; there may be more than one but only one // is reported. The value is 0 when box0.axis[0] separates, 1 when // box0.axis[1] separates, 2 when box1.axis[0] separates or 3 when // box1.axis[1] separates. namespace gte { template <typename T> class TIQuery<T, OrientedBox2<T>, OrientedBox2<T>> { public: struct Result { Result() : intersect(false), separating(0) { } bool intersect; int32_t separating; }; Result operator()(OrientedBox2<T> const& box0, OrientedBox2<T> const& box1) { Result result{}; // Convenience variables. Vector2<T> const* A0 = &box0.axis[0]; Vector2<T> const* A1 = &box1.axis[0]; Vector2<T> const& E0 = box0.extent; Vector2<T> const& E1 = box1.extent; // Compute difference of box centers, D = C1-C0. Vector2<T> D = box1.center - box0.center; std::array<std::array<T, 2>, 2> absA0dA1{}; T rSum{}; // Test box0.axis[0]. absA0dA1[0][0] = std::fabs(Dot(A0[0], A1[0])); absA0dA1[0][1] = std::fabs(Dot(A0[0], A1[1])); rSum = E0[0] + E1[0] * absA0dA1[0][0] + E1[1] * absA0dA1[0][1]; if (std::fabs(Dot(A0[0], D)) > rSum) { result.intersect = false; result.separating = 0; return result; } // Test axis box0.axis[1]. absA0dA1[1][0] = std::fabs(Dot(A0[1], A1[0])); absA0dA1[1][1] = std::fabs(Dot(A0[1], A1[1])); rSum = E0[1] + E1[0] * absA0dA1[1][0] + E1[1] * absA0dA1[1][1]; if (std::fabs(Dot(A0[1], D)) > rSum) { result.intersect = false; result.separating = 1; return result; } // Test axis box1.axis[0]. rSum = E1[0] + E0[0] * absA0dA1[0][0] + E0[1] * absA0dA1[1][0]; if (std::fabs(Dot(A1[0], D)) > rSum) { result.intersect = false; result.separating = 2; return result; } // Test axis box1.axis[1]. rSum = E1[1] + E0[0] * absA0dA1[0][1] + E0[1] * absA0dA1[1][1]; if (std::fabs(Dot(A1[1], D)) > rSum) { result.intersect = false; result.separating = 3; return result; } result.intersect = true; return result; } }; template <typename T> class FIQuery<T, OrientedBox2<T>, OrientedBox2<T>> { public: struct Result { Result() : intersect(false), polygon{} { } bool intersect; // If 'intersect' is true, the boxes intersect in a convex // 'polygon'. std::vector<Vector2<T>> polygon; }; Result operator()(OrientedBox2<T> const& box0, OrientedBox2<T> const& box1) { Result result{}; result.intersect = true; // Initialize the intersection polygon to box0, listing the // vertices in counterclockwise order. std::array<Vector2<T>, 4> vertex{}; box0.GetVertices(vertex); result.polygon.push_back(vertex[0]); // C - e0 * U0 - e1 * U1 result.polygon.push_back(vertex[1]); // C + e0 * U0 - e1 * U1 result.polygon.push_back(vertex[3]); // C + e0 * U0 + e1 * U1 result.polygon.push_back(vertex[2]); // C - e0 * U0 + e1 * U1 // Clip the polygon using the lines defining edges of box1. The // line normal points inside box1. The line origin is the first // vertex of the edge when traversing box1 counterclockwise. box1.GetVertices(vertex); std::array<Vector2<T>, 4> normal = { box1.axis[1], -box1.axis[0], box1.axis[0], -box1.axis[1] }; for (int32_t i = 0; i < 4; ++i) { if (Outside(vertex[i], normal[i], result.polygon)) { // The boxes are separated. result.intersect = false; result.polygon.clear(); break; } } return result; } private: // The line normals are inner pointing. The function returns true // when the incoming polygon is outside the line, in which case the // boxes do not intersect. If the function returns false, the // outgoing polygon is the incoming polygon intersected with the // closed halfspacedefined by the line. bool Outside(Vector2<T> const& origin, Vector2<T> const& normal, std::vector<Vector2<T>>& polygon) { // Determine whether the polygon vertices are outside the polygon, // inside the polygon, or on the polygon boundary. int32_t const numVertices = static_cast<int32_t>(polygon.size()); std::vector<T> distance(numVertices); int32_t positive = 0, negative = 0, positiveIndex = -1; for (int32_t i = 0; i < numVertices; ++i) { distance[i] = Dot(normal, polygon[i] - origin); if (distance[i] > (T)0) { ++positive; if (positiveIndex == -1) { positiveIndex = i; } } else if (distance[i] < (T)0) { ++negative; } } if (positive == 0) { // The polygon is strictly outside the line. return true; } if (negative == 0) { // The polygon is contained in the closed halfspace whose // boundary is the line. It is fully visible and no clipping // is necessary. return false; } // The line transversely intersects the polygon. Clip the polygon. std::vector<Vector2<T>> clipPolygon; Vector2<T> vertex; int32_t curr, prev; T t; if (positiveIndex > 0) { // Compute the first clip vertex on the line. curr = positiveIndex; prev = curr - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); clipPolygon.push_back(vertex); // Include the vertices on the positive side of line. while (curr < numVertices && distance[curr] >(T)0) { clipPolygon.push_back(polygon[curr++]); } // Compute the kast clip vertex on the line. if (curr < numVertices) { prev = curr - 1; } else { curr = 0; prev = numVertices - 1; } t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); clipPolygon.push_back(vertex); } else // positiveIndex is 0 { // Include the vertices on the positive side of line. curr = 0; while (curr < numVertices && distance[curr] >(T)0) { clipPolygon.push_back(polygon[curr++]); } // Compute the last clip vertex on the line. prev = curr - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); clipPolygon.push_back(vertex); // Skip the vertices on the negative side of the line. while (curr < numVertices && distance[curr] <= (T)0) { curr++; } // Compute the first clip vertex on the line. if (curr < numVertices) { prev = curr - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); clipPolygon.push_back(vertex); // Keep the vertices on the positive side of the line. while (curr < numVertices && distance[curr] >(T)0) { clipPolygon.push_back(polygon[curr++]); } } else { curr = 0; prev = numVertices - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); clipPolygon.push_back(vertex); } } polygon = clipPolygon; return false; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IEEEBinary16.h
.h
23,265
677
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/BitHacks.h> #include <Mathematics/Math.h> #include <Mathematics/IEEEBinary.h> namespace gte { class IEEEBinary16 : public IEEEBinary<int16_t, uint16_t, 16, 11> { public: // Construction and destruction. The base class destructor is hidden, // but this is safe because there are no side effects of the // destruction. ~IEEEBinary16() = default; // The default construction does not initialize the union member of // the base class. Use one of the Set*(*) functions to set the // member. IEEEBinary16() : IEEEBinary<int16_t, uint16_t, 16, 11>() { // uninitialized } IEEEBinary16(IEEEBinary16 const& object) : IEEEBinary<int16_t, uint16_t, 16, 11>(object) { } IEEEBinary16(float inNumber) : IEEEBinary<int16_t, uint16_t, 16, 11>() { union { float n; uint32_t e; } temp = { inNumber }; encoding = Convert32To16(temp.e); } IEEEBinary16(double inNumber) : IEEEBinary<int16_t, uint16_t, 16, 11>() { union { float n; uint32_t e; } temp; temp.n = static_cast<float>(inNumber); encoding = Convert32To16(temp.e); } IEEEBinary16(uint16_t inEncoding) : IEEEBinary<int16_t, uint16_t, 16, 11>(inEncoding) { } // Implicit conversions. operator float() const { union { uint32_t e; float n; } temp = { Convert16To32(encoding) }; return temp.n; } operator double() const { union { uint32_t e; float n; } temp = { Convert16To32(encoding) }; return static_cast<double>(temp.n); } // Assignment. IEEEBinary16& operator=(IEEEBinary16 const& object) { IEEEBinary<int16_t, uint16_t, 16, 11>::operator=(object); return *this; } // Comparison. bool operator==(IEEEBinary16 const& object) const { return static_cast<float>(*this) == static_cast<float>(object); } bool operator!=(IEEEBinary16 const& object) const { return static_cast<float>(*this) != static_cast<float>(object); } bool operator< (IEEEBinary16 const& object) const { return static_cast<float>(*this) < static_cast<float>(object); } bool operator<=(IEEEBinary16 const& object) const { return static_cast<float>(*this) <= static_cast<float>(object); } bool operator> (IEEEBinary16 const& object) const { return static_cast<float>(*this) > static_cast<float>(object); } bool operator>=(IEEEBinary16 const& object) const { return static_cast<float>(*this) >= static_cast<float>(object); } private: // Members from the base class IEEEBinary<int16_t, uint16_t, 16, 11>. // // NUM_ENCODING_BITS = 16 // NUM_EXPONENT_BITS = 5 // NUM_SIGNIFICAND_BITS = 11 // NUM_TRAILING_BITS = 10 // EXPONENT_BIAS = 15 // MAX_BIASED_EXPONENT = 31 // MIN_SUB_EXPONENT = -14 // MIN_EXPONENT = -24 // SIGN_SHIFT = 15 // SIGN_MASK = 0x8000 // NOT_SIGN_MASK = 0x7FFF // TRAILING_MASK = 0x03FF // EXPONENT_MASK = 0x7C00 // NAN_QUIET_MASK = 0x0200 // NAN_PAYLOAD_MASK = 0x01FF // MAX_TRAILING = 0x03FF // SUP_TRAILING = 0x0400 // POS_ZERO = 0x0000 // NEG_ZERO = 0x8000 // MIN_SUBNORMAL = 0x0001 // MAX_SUBNORMAL = 0x03FF // MIN_NORMAL = 0x0400 // MAX_NORMAL = 0x7BFF // POS_INFINITY = 0x7C00 // NEG_INFINITY = 0xFC00 // Support for conversions between 16-bit and 32-bit numbers. using F16 = IEEEBinary16; using F32 = IEEEBinary32; // Encodings of special numbers on the "continuous 16-bit // number line" as 32-bit float numbers. static uint32_t const F16_AVR_MIN_SUB_ZER = 0x33000000; // 2^{-25} static uint32_t const F16_MIN_SUB = 0x33800000; // 2^{-24} static uint32_t const F16_MIN_NOR = 0x38800000; // 2^{-14} static uint32_t const F16_MAX_NOR = 0x477FE000; // 2^{16)*(1-2^{-11}) static uint32_t const F16_AVR_MAX_NOR_INF = 0x477FF000; // 2^{16)*(1-2^{-12}) // The amount to shift when converting between signs of 16-bit and // 32-bit numbers. static uint32_t const CONVERSION_SIGN_SHIFT = F32::NUM_ENCODING_BITS - F16::NUM_ENCODING_BITS; // The amount to shift when converting between trailing significands // of 16-bit and 32-bit numbers. static uint32_t const CONVERSION_TRAILING_SHIFT = F32::NUM_SIGNIFICAND_BITS - F16::NUM_SIGNIFICAND_BITS; // The half value for round-to-nearest-ties-to-even. The fractional // part in the rounding is shifted left so that the leading bit is // the high-order bit of a 32-bit unsigned integer. static uint32_t const FRACTION_HALF = F32::SIGN_MASK; static uint16_t Convert32To16(uint32_t inEncoding) { // In the comments of this function, x refers to the 32-bit // floating-point number corresponding to inEncoding and y refers // to the 16-bit floating-point number that x is converted to. // Extract the channels for x. uint32_t sign32 = (inEncoding & F32::SIGN_MASK); uint32_t biased32 = ((inEncoding & F32::EXPONENT_MASK) >> F32::NUM_TRAILING_BITS); uint32_t trailing32 = (inEncoding & F32::TRAILING_MASK); uint32_t nonneg32 = (inEncoding & F32::NOT_SIGN_MASK); // Generate the channels for y. uint16_t sign16 = static_cast<uint16_t>(sign32 >> CONVERSION_SIGN_SHIFT); uint16_t biased16, trailing16; uint32_t frcpart; if (biased32 == 0) { // x is zero or 32-subnormal, the nearest y is zero. return sign16; } if (biased32 < F32::MAX_BIASED_EXPONENT) { // x is 32-normal. if (nonneg32 <= F16_AVR_MIN_SUB_ZER) { // x <= 2^{-25}, the nearest y is zero. return sign16; } if (nonneg32 <= F16_MIN_SUB) { // 2^{-25} < x <= 2^{-24}, the nearest y is // 16-min-subnormal. return sign16 | F16::MIN_SUBNORMAL; } if (nonneg32 < F16_MIN_NOR) { // 2^{-24} < x < 2^{-14}, compute nearest 16-bit subnormal // y using round-to-nearest-ties-to-even. // // y = 0.s9 ... s0 * 2^{14} // x = 1.t22 ... t0 * 2^e, where -24 <= e <= -15 // = (0.1 t22 ... t0 * 2^{e+15}) * 2^{-14} // = (0.1 t22 ... t0 * 2^p) * 2^{-14} // where p = e+15 with -9 = p <= 0. The term // (0.1 t22 ... t0 * 2^p) must be rounded to // 0.s9 ... s0 * 2^{-14}. int32_t p = static_cast<int32_t>(biased32) - F32::EXPONENT_BIAS + F16::EXPONENT_BIAS; // x is 32-normal, so there is an implied 1-bit that must // first be appended to the 32-trailing significand to // obtain all the bits necessary for the 16-trailing // significand for the 16-subnormal y. The resulting number // is 000000001 t22 ... t0. trailing32 |= F32::SUP_TRAILING; // Get the integer part. uint32_t rshift = static_cast<uint32_t>( -F16::MIN_SUB_EXPONENT - p); trailing16 = static_cast<uint16_t>(trailing32 >> rshift); // Get the fractional part. uint32_t lshift = static_cast<uint32_t>( F32::NUM_ENCODING_BITS + F16::MIN_SUB_EXPONENT + p); frcpart = (trailing32 << lshift); // Round to nearest with ties to even. if (frcpart > FRACTION_HALF || (frcpart == FRACTION_HALF && (trailing16 & 1))) { // If there is a carry into the exponent, the nearest // is actually 16-min-normal 1.0*2^{-14}, so the // high-order bit of trailing16 makes biased16 equal // to 1 and the result is correct. ++trailing16; } return sign16 | trailing16; } if (nonneg32 <= F16_MAX_NOR) { // 2^{-14} <= x <= 1.1111111111*2^{15}, compute nearest // 16-bit subnormal y using round-to-nearest-ties-to-even. // The exponents of x and y are the same, although the // biased exponents are different because of different // exponent-bias parameters. int32_t e = static_cast<int32_t>(biased32) - F32::EXPONENT_BIAS; biased16 = static_cast<uint16_t>(e + F16::EXPONENT_BIAS); biased16 = (biased16 << F16::NUM_TRAILING_BITS); // Let x = 1.t22...t0 * 2^e and y = 1.s9...s0 * 2^e. Both // x and y have an implied leading 1-bit (both are normal), // so we can ignore it. The number 0.t22...t0 must be // rounded to the number 0.s9...s0. // Get the integer part. trailing16 = static_cast<uint16_t>( trailing32 >> CONVERSION_TRAILING_SHIFT); // Get the fractional part. uint32_t lshift = static_cast<uint32_t>( F32::NUM_ENCODING_BITS + F16::MIN_SUB_EXPONENT + 1); frcpart = (trailing32 << lshift); // Round to nearest with ties to even. if (frcpart > FRACTION_HALF || (frcpart == FRACTION_HALF && (trailing16 & 1))) { // If there is a carry into the exponent, the addition // of trailing16 to biased16 (rather than or-ing) // produces the correct result. ++trailing16; } return sign16 | (biased16 + trailing16); } if (nonneg32 < F16_AVR_MAX_NOR_INF) { // 1.1111111111*2^{15} < x < (MAX_NORMAL+INFINITY)/2, // so the number is closest to 16-max-normal. return sign16 | F16::MAX_NORMAL; } // nonneg32 >= (MAX_NORMAL+INFINITY)/2, so convert to // 16-infinite. return sign16 | F16::POS_INFINITY; } if (trailing32 == 0) { // The number is 32-infinite. Convert to 16-infinite. return sign16 | F16::POS_INFINITY; } // The number is 32-NaN. Convert to 16-NaN with 16-payload the // high-order 9 bits of the 32-payload. The 32-quiet-NaN mask // bit is copied in the conversion. uint16_t maskPayload = static_cast<uint16_t>( trailing32 >> CONVERSION_TRAILING_SHIFT); return sign16 | F16::EXPONENT_MASK | maskPayload; } static uint32_t Convert16To32(uint16_t inEncoding) { // Extract the channels for the IEEEBinary16 number. uint16_t sign16 = (inEncoding & F16::SIGN_MASK); uint16_t biased16 = ((inEncoding & F16::EXPONENT_MASK) >> F16::NUM_TRAILING_BITS); uint16_t trailing16 = (inEncoding & F16::TRAILING_MASK); // Generate the channels for the binary32 number. uint32_t sign32 = static_cast<uint32_t>(sign16 << CONVERSION_SIGN_SHIFT); uint32_t biased32, trailing32; if (biased16 == 0) { if (trailing16 == 0) { // The number is 16-zero. Convert to 32-zero. return sign32; } else { // The number is 16-subnormal. Convert to 32-normal. trailing32 = static_cast<uint32_t>(trailing16); int32_t leading = BitHacks::GetLeadingBit(trailing32); int32_t shift = 23 - leading; biased32 = static_cast<uint32_t>(F32::EXPONENT_BIAS - 1 - shift); trailing32 = (trailing32 << shift) & F32::TRAILING_MASK; return sign32 | (biased32 << F32::NUM_TRAILING_BITS) | trailing32; } } if (biased16 < F16::MAX_BIASED_EXPONENT) { // The number is 16-normal. Convert to 32-normal. biased32 = static_cast<uint32_t>(biased16 - F16::EXPONENT_BIAS + F32::EXPONENT_BIAS); trailing32 = (static_cast<uint32_t>(trailing16) << CONVERSION_TRAILING_SHIFT); return sign32 | (biased32 << F32::NUM_TRAILING_BITS) | trailing32; } if (trailing16 == 0) { // The number is 16-infinite. Convert to 32-infinite. return sign32 | F32::EXPONENT_MASK; } // The number is 16-NaN. Convert to 32-NaN with 32-payload // whose high-order 9 bits are from the 16-payload. The // 16-quiet-NaN mask bit is copied in the conversion. uint32_t maskPayload = (static_cast<uint32_t>(trailing16) << CONVERSION_TRAILING_SHIFT); return sign32 | F32::EXPONENT_MASK | maskPayload; } }; // Arithmetic operations (high-precision). inline IEEEBinary16 operator-(IEEEBinary16 x) { uint16_t result = static_cast<uint16_t>(x) ^ IEEEBinary16::SIGN_MASK; return result; } inline float operator+(IEEEBinary16 x, IEEEBinary16 y) { return static_cast<float>(x) + static_cast<float>(y); } inline float operator-(IEEEBinary16 x, IEEEBinary16 y) { return static_cast<float>(x) - static_cast<float>(y); } inline float operator*(IEEEBinary16 x, IEEEBinary16 y) { return static_cast<float>(x)* static_cast<float>(y); } inline float operator/(IEEEBinary16 x, IEEEBinary16 y) { return static_cast<float>(x) / static_cast<float>(y); } inline float operator+(IEEEBinary16 x, float y) { return static_cast<float>(x) + y; } inline float operator-(IEEEBinary16 x, float y) { return static_cast<float>(x) - y; } inline float operator*(IEEEBinary16 x, float y) { return static_cast<float>(x)* y; } inline float operator/(IEEEBinary16 x, float y) { return static_cast<float>(x) / y; } inline float operator+(float x, IEEEBinary16 y) { return x + static_cast<float>(y); } inline float operator-(float x, IEEEBinary16 y) { return x - static_cast<float>(y); } inline float operator*(float x, IEEEBinary16 y) { return x * static_cast<float>(y); } inline float operator/(float x, IEEEBinary16 y) { return x / static_cast<float>(y); } // Arithmetic updates. inline IEEEBinary16& operator+=(IEEEBinary16& x, IEEEBinary16 y) { x = static_cast<float>(x) + static_cast<float>(y); return x; } inline IEEEBinary16& operator-=(IEEEBinary16& x, IEEEBinary16 y) { x = static_cast<float>(x) - static_cast<float>(y); return x; } inline IEEEBinary16& operator*=(IEEEBinary16& x, IEEEBinary16 y) { x = static_cast<float>(x)* static_cast<float>(y); return x; } inline IEEEBinary16& operator/=(IEEEBinary16& x, IEEEBinary16 y) { x = static_cast<float>(x) / static_cast<float>(y); return x; } inline IEEEBinary16& operator+=(IEEEBinary16& x, float y) { x = static_cast<float>(x) + y; return x; } inline IEEEBinary16& operator-=(IEEEBinary16& x, float y) { x = static_cast<float>(x) - y; return x; } inline IEEEBinary16& operator*=(IEEEBinary16& x, float y) { x = static_cast<float>(x)* y; return x; } inline IEEEBinary16& operator/=(IEEEBinary16& x, float y) { x = static_cast<float>(x) / y; return x; } } namespace std { inline gte::IEEEBinary16 acos(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::acos(static_cast<float>(x))); } inline gte::IEEEBinary16 acosh(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::acosh(static_cast<float>(x))); } inline gte::IEEEBinary16 asin(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::asin(static_cast<float>(x))); } inline gte::IEEEBinary16 asinh(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::asinh(static_cast<float>(x))); } inline gte::IEEEBinary16 atan(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::atan(static_cast<float>(x))); } inline gte::IEEEBinary16 atanh(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::atanh(static_cast<float>(x))); } inline gte::IEEEBinary16 atan2(gte::IEEEBinary16 y, gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::atan2(static_cast<float>(y), static_cast<float>(x))); } inline gte::IEEEBinary16 ceil(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::ceil(static_cast<float>(x))); } inline gte::IEEEBinary16 cos(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::cos(static_cast<float>(x))); } inline gte::IEEEBinary16 cosh(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::cosh(static_cast<float>(x))); } inline gte::IEEEBinary16 exp(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::exp(static_cast<float>(x))); } inline gte::IEEEBinary16 exp2(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::exp2(static_cast<float>(x))); } inline gte::IEEEBinary16 fabs(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::fabs(static_cast<float>(x))); } inline gte::IEEEBinary16 floor(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::floor(static_cast<float>(x))); } inline gte::IEEEBinary16 fmod(gte::IEEEBinary16 x, gte::IEEEBinary16 y) { return static_cast<gte::IEEEBinary16>(std::fmod(static_cast<float>(x), static_cast<float>(y))); } inline gte::IEEEBinary16 frexp(gte::IEEEBinary16 x, int32_t* exponent) { return static_cast<gte::IEEEBinary16>(std::frexp(static_cast<float>(x), exponent)); } inline gte::IEEEBinary16 ldexp(gte::IEEEBinary16 x, int32_t exponent) { return static_cast<gte::IEEEBinary16>(std::ldexp(static_cast<float>(x), exponent)); } inline gte::IEEEBinary16 log(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::log(static_cast<float>(x))); } inline gte::IEEEBinary16 log2(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::log2(static_cast<float>(x))); } inline gte::IEEEBinary16 log10(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::log10(static_cast<float>(x))); } inline gte::IEEEBinary16 pow(gte::IEEEBinary16 x, gte::IEEEBinary16 y) { return static_cast<gte::IEEEBinary16>(std::pow(static_cast<float>(x), static_cast<float>(y))); } inline gte::IEEEBinary16 sin(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::sin(static_cast<float>(x))); } inline gte::IEEEBinary16 sinh(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::sinh(static_cast<float>(x))); } inline gte::IEEEBinary16 sqrt(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::sqrt(static_cast<float>(x))); } inline gte::IEEEBinary16 tan(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::tan(static_cast<float>(x))); } inline gte::IEEEBinary16 tanh(gte::IEEEBinary16 x) { return static_cast<gte::IEEEBinary16>(std::tanh(static_cast<float>(x))); } } namespace gte { inline IEEEBinary16 atandivpi(IEEEBinary16 x) { return static_cast<IEEEBinary16>(atandivpi(static_cast<float>(x))); } inline IEEEBinary16 atan2divpi(IEEEBinary16 y, IEEEBinary16 x) { return static_cast<IEEEBinary16>(atan2divpi(static_cast<float>(y), static_cast<float>(x))); } inline IEEEBinary16 clamp(IEEEBinary16 x, IEEEBinary16 xmin, IEEEBinary16 xmax) { return static_cast<IEEEBinary16>(clamp(static_cast<float>(x), static_cast<float>(xmin), static_cast<float>(xmax))); } inline IEEEBinary16 cospi(IEEEBinary16 x) { return static_cast<IEEEBinary16>(cospi(static_cast<float>(x))); } inline IEEEBinary16 exp10(IEEEBinary16 x) { return static_cast<IEEEBinary16>(exp10(static_cast<float>(x))); } inline IEEEBinary16 invsqrt(IEEEBinary16 x) { return static_cast<IEEEBinary16>(invsqrt(static_cast<float>(x))); } inline int32_t isign(IEEEBinary16 x) { return isign(static_cast<float>(x)); } inline IEEEBinary16 saturate(IEEEBinary16 x) { return static_cast<IEEEBinary16>(saturate(static_cast<float>(x))); } inline IEEEBinary16 sign(IEEEBinary16 x) { return static_cast<IEEEBinary16>(sign(static_cast<float>(x))); } inline IEEEBinary16 sinpi(IEEEBinary16 x) { return static_cast<IEEEBinary16>(sinpi(static_cast<float>(x))); } inline IEEEBinary16 sqr(IEEEBinary16 x) { return static_cast<IEEEBinary16>(sqr(static_cast<float>(x))); } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay3Ellipsoid3.h
.h
4,760
144
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine3Ellipsoid3.h> #include <Mathematics/Ray.h> #include <Mathematics/Matrix3x3.h> // The queries consider the ellipsoid to be a solid. // // The ellipsoid is (X-C)^T*M*(X-C)-1 = 0 and the ray is X = P+t*D for t >= 0. // Substitute the ray equation into the ellipsoid equation to obtain a // quadratic equation Q(t) = a2*t^2 + 2*a1*t + a0 = 0, where a2 = D^T*M*D, // a1 = D^T*M*(P-C) and a0 = (P-C)^T*M*(P-C)-1. The algorithm involves an // analysis of the real-valued roots of Q(t) for t >= 0. namespace gte { template <typename T> class TIQuery<T, Ray3<T>, Ellipsoid3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Ray3<T> const& ray, Ellipsoid3<T> const& ellipsoid) { Result result{}; Matrix3x3<T> M{}; ellipsoid.GetM(M); T const zero = static_cast<T>(0); Vector3<T> diff = ray.origin - ellipsoid.center; Vector3<T> matDir = M * ray.direction; Vector3<T> matDiff = M * diff; T a0 = Dot(diff, matDiff) - static_cast<T>(1); if (a0 <= zero) { // P is inside the ellipsoid. result.intersect = true; return result; } // else: P is outside the ellipsoid T a1 = Dot(ray.direction, matDiff); if (a1 >= zero) { // Q(t) >= a0 > 0 for t >= 0, so Q(t) cannot be zero for // t in [0,+infinity) and the ray does not intersect the // ellipsoid. result.intersect = false; return result; } // The minimum of Q(t) occurs for some t in (0,+infinity). An // intersection occurs when Q(t) has real roots. T a2 = Dot(ray.direction, matDir); T discr = a1 * a1 - a0 * a2; result.intersect = (discr >= zero); return result; } }; template <typename T> class FIQuery<T, Ray3<T>, Ellipsoid3<T>> : public FIQuery<T, Line3<T>, Ellipsoid3<T>> { public: struct Result : public FIQuery<T, Line3<T>, Ellipsoid3<T>>::Result { Result() : FIQuery<T, Line3<T>, Ellipsoid3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Ray3<T> const& ray, Ellipsoid3<T> const& ellipsoid) { Result result{}; DoQuery(ray.origin, ray.direction, ellipsoid, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = ray.origin + result.parameter[i] * ray.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& rayOrigin, Vector3<T> const& rayDirection, Ellipsoid3<T> const& ellipsoid, Result& result) { FIQuery<T, Line3<T>, Ellipsoid3<T>>::DoQuery(rayOrigin, rayDirection, ellipsoid, result); if (result.intersect) { // The line containing the ray intersects the ellipsoid; the // t-interval is [t0,t1]. The ray intersects the capsule as // long as [t0,t1] overlaps the ray t-interval [0,+infinity). FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; auto iiResult = iiQuery(result.parameter, static_cast<T>(0), true); if (iiResult.intersect) { result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } else { // The line containing the ray does not intersect the // ellipsoid. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TetrahedraRasterizer.h
.h
14,096
381
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <array> #include <cmath> #include <cstdint> #include <stdexcept> #include <thread> #include <vector> namespace gte { template <typename T> class TetrahedraRasterizer { public: // The tetrahedra are stored as indexed primitives where the indices // are relative to the vertices[] array. The vertices of the // tetrahedra are vertices[tetrahedra[t][i]] for 0 <= i < 4. If // v0, v1, v2 and v3 are those vertices, the triangle faces have // vertices {v0,v2,v1}, {v0,v1,v3}, {v0,v3,v2} and {v1,v2,v3}. The // faces are counterclockwise ordered when viewed by an observer // outside the tetrahedron. The canonical tetrahedron is // {v0,v1,v2,v3} where v0 = (0,0,0), v1 = (1,0,0), v2 = (0,1,0) and // v3 = (0,0,1). TetrahedraRasterizer(size_t numVertices, std::array<T, 3> const* vertices, size_t numTetrahedra, std::array<size_t, 4> const* tetrahedra) : mNumVertices(numVertices), mVertices(vertices), mNumTetrahedra(numTetrahedra), mTetrahedra(tetrahedra), mTetraMin(numTetrahedra), mTetraMax(numTetrahedra), mValid(numTetrahedra), mGridVertices(numVertices), mGridTetraMin(numTetrahedra), mGridTetraMax(numTetrahedra) { if (numVertices == 0 || !vertices || numTetrahedra == 0 || !tetrahedra) { LogError("Invalid argument."); } ComputeTetrahedraAABBs(); } // Rasterize the tetrahedra into a 3D grid. The input region is a // box in the coordinate system of the vertices. The box is associated // with a 3D grid of specified bounds. A grid point is a 3-tuple // (x,y,z) with integer coordinates satisfying 0 <= x < xBound, // 0 <= y < yBound and 0 <= z < zBound. The point is classified based // on whether or not it is contained by a tetrahedron, and the // classification is stored as an integer in grid[i] where the index // is i = x + bound[0] * (y + bound[1] * z). If the point is not // contained by a tetrahedron, grid[i] is set to -1. If the point is // contained by a tetrahedron, grid[i] is set to the tetrahedron // index t where 0 <= t < numTetrahedra. // // To run in the main thread only, choose numThreads to be 0. For // multithreading, choose numThreads > 0. The number of available // hardware threads is std::thread::hardware_concurrency(). A // reasonable choice for numThreads will not exceed the number of // available hardware threads. You might want to keep 1 or 2 threads // available for the operating system and other applications running // on the machine. void operator()(size_t numThreads, std::array<T, 3> const& regionMin, std::array<T, 3> const& regionMax, std::array<size_t, 3> const& bound, std::vector<int32_t>& grid) { if (bound[0] < 2 || bound[1] < 2 || bound[2] < 2) { LogError("Invalid argument."); } // Initialize the grid values to -1. When a grid cell is contained // in a tetrahedron, the index of that tetrahedron is stored in // grid[i]. All such contained grid[] values are nonnegative. grid.resize(bound[0] * bound[1] * bound[2]); std::fill(grid.begin(), grid.end(), -1); // Clip-cull the tetrahedra bounding boxes against the region. ClipCullAABBs(regionMin, regionMax); // Transform the vertices and tetrahedra bounding boxes to // grid coordinates. TransformToGridCoordinates(regionMin, regionMax, bound); if (numThreads > 0) { MultiThreadedRasterizer(numThreads, bound, grid); } else { SingleThreadedRasterizer(bound, grid); } } private: // Compute the axis-aligned bounding boxes of the tetrahedra. void ComputeTetrahedraAABBs() { for (size_t t = 0; t < mNumTetrahedra; ++t) { auto& tetraMin = mTetraMin[t]; auto& tetraMax = mTetraMax[t]; tetraMin = mVertices[mTetrahedra[t][0]]; tetraMax = tetraMin; for (size_t j = 1; j < 4; ++j) { auto const& vertex = mVertices[mTetrahedra[t][j]]; for (size_t i = 0; i < 3; ++i) { if (vertex[i] < tetraMin[i]) { tetraMin[i] = vertex[i]; } else if (vertex[i] > tetraMax[i]) { tetraMax[i] = vertex[i]; } } } } } // Clip-cull the tetrahedra bounding boxes against the region. // The mValid[t] is true whenever the mAABB[t] intersects the // region. void ClipCullAABBs(std::array<T, 3> const& regionMin, std::array<T, 3> const& regionMax) { for (size_t t = 0; t < mNumTetrahedra; ++t) { auto& tetraMin = mTetraMin[t]; auto& tetraMax = mTetraMax[t]; mValid[t] = true; for (size_t i = 0; i < 3; ++i) { tetraMin[i] = std::max(tetraMin[i], regionMin[i]); tetraMax[i] = std::min(tetraMax[i], regionMax[i]); if (tetraMin[i] > tetraMax[i]) { mValid[t] = false; } } } } void TransformToGridCoordinates(std::array<T, 3> const& regionMin, std::array<T, 3> const& regionMax, std::array<size_t, 3> const& bound) { std::array<T, 3> multiplier{}; for (size_t i = 0; i < 3; ++i) { multiplier[i] = static_cast<T>(bound[i] - 1) / (regionMax[i] - regionMin[i]); } for (size_t v = 0; v < mNumVertices; ++v) { auto const& vertex = mVertices[v]; auto& gridVertex = mGridVertices[v]; for (size_t i = 0; i < 3; ++i) { gridVertex[i] = multiplier[i] * (vertex[i] - regionMin[i]); } } for (size_t t = 0; t < mNumTetrahedra; ++t) { auto const& tetraMin = mTetraMin[t]; auto const& tetraMax = mTetraMax[t]; auto& gridTetraMin = mGridTetraMin[t]; auto& gridTetraMax = mGridTetraMax[t]; for (size_t i = 0; i < 3; ++i) { gridTetraMin[i] = static_cast<size_t>(std::ceil( multiplier[i] * (tetraMin[i] - regionMin[i]))); gridTetraMax[i] = static_cast<size_t>(std::floor( multiplier[i] * (tetraMax[i] - regionMin[i]))); } } } void SingleThreadedRasterizer(std::array<size_t, 3> const& bound, std::vector<int32_t>& grid) { for (size_t t = 0; t < mNumTetrahedra; ++t) { if (mValid[t]) { Rasterize(t, bound, grid); } } } void MultiThreadedRasterizer(size_t numThreads, std::array<size_t, 3> const& bound, std::vector<int32_t>& grid) { // Partition the data for multiple threads. size_t const numTetrahedraPerThread = mNumTetrahedra / numThreads; std::vector<size_t> nmin(numThreads), nsup(numThreads); for (size_t k = 0; k < numThreads; ++k) { nmin[k] = k * numTetrahedraPerThread; nsup[k] = (k + 1) * numTetrahedraPerThread; } nsup[numThreads - 1] = mNumTetrahedra; std::vector<std::thread> process(numThreads); for (size_t k = 0; k < numThreads; ++k) { process[k] = std::thread([this, k, &nmin, &nsup, &bound, &grid]() { for (size_t t = nmin[k]; t < nsup[k]; ++t) { if (mValid[t]) { Rasterize(t, bound, grid); } } }); } for (size_t t = 0; t < numThreads; ++t) { process[t].join(); } } void Rasterize(size_t t, std::array<size_t, 3> const& bound, std::vector<int32_t>& grid) { auto const& imin = mGridTetraMin[t]; auto const& imax = mGridTetraMax[t]; std::array<T, 3> gridP{}; for (size_t i2 = imin[2]; i2 <= imax[2]; ++i2) { gridP[2] = static_cast<T>(i2); for (size_t i1 = imin[1]; i1 <= imax[1]; ++i1) { gridP[1] = static_cast<T>(i1); size_t i0min; for (i0min = imin[0]; i0min <= imax[0]; ++i0min) { gridP[0] = static_cast<T>(i0min); if (PointInTetrahedron(gridP, mGridVertices[mTetrahedra[t][0]], mGridVertices[mTetrahedra[t][1]], mGridVertices[mTetrahedra[t][2]], mGridVertices[mTetrahedra[t][3]])) { break; } } if (i0min > imax[0]) { continue; } size_t i0max; for (i0max = imax[0]; i0max >= i0min; --i0max) { gridP[0] = static_cast<T>(i0max); if (PointInTetrahedron(gridP, mGridVertices[mTetrahedra[t][0]], mGridVertices[mTetrahedra[t][1]], mGridVertices[mTetrahedra[t][2]], mGridVertices[mTetrahedra[t][3]])) { break; } } size_t const base = bound[0] * (i1 + bound[1] * i2); int32_t const tetrahedronIndex = static_cast<int32_t>(t); for (size_t i0 = i0min, j = i0 + base; i0 <= i0max; ++i0, ++j) { grid[j] = tetrahedronIndex; } } } } static bool PointInTetrahedron(std::array<T, 3> const& P, std::array<T, 3> const& V0, std::array<T, 3> const& V1, std::array<T, 3> const& V2, std::array<T, 3> const& V3) { T const zero = static_cast<T>(0); std::array<T, 3> PmV0 = Sub(P, V0); std::array<T, 3> V1mV0 = Sub(V1, V0); std::array<T, 3> V2mV0 = Sub(V2, V0); if (DotCross(PmV0, V2mV0, V1mV0) > zero) { return false; } std::array<T, 3> V3mV0 = Sub(V3, V0); if (DotCross(PmV0, V1mV0, V3mV0) > zero) { return false; } if (DotCross(PmV0, V3mV0, V2mV0) > zero) { return false; } std::array<T, 3> PmV1 = Sub(P, V1); std::array<T, 3> V2mV1 = Sub(V2, V1); std::array<T, 3> V3mV1 = Sub(V3, V1); if (DotCross(PmV1, V2mV1, V3mV1) > zero) { return false; } return true; } inline static std::array<T, 3> Sub(std::array<T, 3> const& U, std::array<T, 3> const& V) { std::array<T, 3> sub = { U[0] - V[0], U[1] - V[1], U[2] - V[2] }; return sub; } inline static T Dot(std::array<T, 3> const& U, std::array<T, 3> const& V) { T dot = U[0] * V[0] + U[1] * V[1] + U[2] * V[2]; return dot; } inline static std::array<T, 3> Cross(std::array<T, 3> const& U, std::array<T, 3> const& V) { std::array<T, 3> cross = { U[1] * V[2] - U[2] * V[1], U[2] * V[0] - U[0] * V[2], U[0] * V[1] - U[1] * V[0] }; return cross; } inline static T DotCross(std::array<T, 3> const& U, std::array<T, 3> const& V, std::array<T, 3> const& W) { return Dot(U, Cross(V, W)); } // Constructor arguments. size_t mNumVertices; std::array<T, 3> const* mVertices; size_t mNumTetrahedra; std::array<size_t, 4> const* mTetrahedra; // Axis-aligned bounding boxes for the tetrahedra. std::vector<std::array<T, 3>> mTetraMin; std::vector<std::array<T, 3>> mTetraMax; std::vector<bool> mValid; // Vertices and axis-aligned bounding boxes in grid coordinates. std::vector<std::array<T, 3>> mGridVertices; std::vector<std::array<size_t, 3>> mGridTetraMin; std::vector<std::array<size_t, 3>> mGridTetraMax; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MeshSmoother.h
.h
5,788
191
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.3.2022.03.29 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Vector3.h> #include <vector> namespace gte { template <typename T> class MeshSmoother { public: MeshSmoother() : mNumVertices(0), mVertices(nullptr), mNumTriangles(0), mIndices(nullptr), mNormals{}, mMeans{}, mNeighborCounts{} { } virtual ~MeshSmoother() = default; // The input to operator() is a triangle mesh with the specified // vertex buffer and index buffer. The number of elements of // 'indices' must be a multiple of 3, each triple of indices // (3*t, 3*t+1, 3*t+2) representing the triangle with vertices // (vertices[3*t], vertices[3*t+1], vertices[3*t+2]). void operator()(size_t numVertices, Vector3<T>* vertices, size_t numTriangles, int32_t const* indices) { LogAssert( numVertices >= 3 && vertices != nullptr && numTriangles >= 1 && indices != nullptr, "Invalid input."); mNumVertices = numVertices; mVertices = vertices; mNumTriangles = numTriangles; mIndices = indices; mNormals.resize(mNumVertices); mMeans.resize(mNumVertices); mNeighborCounts.resize(mNumVertices); // Count the number of vertex neighbors. std::fill(mNeighborCounts.begin(), mNeighborCounts.end(), 0); int32_t const* current = mIndices; for (size_t i = 0; i < mNumTriangles; ++i) { mNeighborCounts[*current++] += 2; mNeighborCounts[*current++] += 2; mNeighborCounts[*current++] += 2; } } void operator()(std::vector<Vector3<T>>& vertices, std::vector<int32_t> const& indices) { operator()(vertices.size(), vertices.data(), indices.size() / 3, indices.data()); } inline size_t GetNumVertices() const { return mNumVertices; } inline Vector3<T> const* GetVertices() const { return mVertices; } inline size_t GetNumTriangles() const { return mNumTriangles; } inline int32_t const* GetIndices() const { return mIndices; } inline std::vector<Vector3<T>> const& GetNormals() const { return mNormals; } inline std::vector<Vector3<T>> const& GetMeans() const { return mMeans; } inline std::vector<size_t> const& GetNeighborCounts() const { return mNeighborCounts; } // Apply one iteration of the smoother. The input time is supported // for applications where the surface evolution is time-dependent. void Update(T t = static_cast<T>(0)) { std::fill(mNormals.begin(), mNormals.end(), Vector3<T>::Zero()); std::fill(mMeans.begin(), mMeans.end(), Vector3<T>::Zero()); int32_t const* current = mIndices; for (size_t i = 0; i < mNumTriangles; ++i) { int32_t v0 = *current++; int32_t v1 = *current++; int32_t v2 = *current++; Vector3<T>& V0 = mVertices[v0]; Vector3<T>& V1 = mVertices[v1]; Vector3<T>& V2 = mVertices[v2]; Vector3<T> edge1 = V1 - V0; Vector3<T> edge2 = V2 - V0; Vector3<T> normal = Cross(edge1, edge2); mNormals[v0] += normal; mNormals[v1] += normal; mNormals[v2] += normal; mMeans[v0] += V1 + V2; mMeans[v1] += V2 + V0; mMeans[v2] += V0 + V1; } for (size_t i = 0; i < mNumVertices; ++i) { Normalize(mNormals[i]); mMeans[i] /= static_cast<T>(mNeighborCounts[i]); } for (size_t i = 0; i < mNumVertices; ++i) { if (VertexInfluenced(i, t)) { Vector3<T> diff = mMeans[i] - mVertices[i]; T dotDifNor = Dot(diff, mNormals[i]); Vector3<T> surfaceNormal = dotDifNor * mNormals[i]; Vector3<T> tangent = diff - surfaceNormal; T tanWeight = GetTangentWeight(i, t); T norWeight = GetNormalWeight(i, t); mVertices[i] += tanWeight * tangent + norWeight * mNormals[i]; } } } protected: // The input parameters are "size_t i, T t". They are unused by // default, so the names are hidden according to ANSI standards. virtual bool VertexInfluenced(size_t, T) { return true; } virtual T GetTangentWeight(size_t, T) { return static_cast<T>(0.5); } virtual T GetNormalWeight(size_t, T) { return static_cast<T>(0.0); } size_t mNumVertices; Vector3<T>* mVertices; size_t mNumTriangles; int32_t const* mIndices; std::vector<Vector3<T>> mNormals; std::vector<Vector3<T>> mMeans; std::vector<size_t> mNeighborCounts; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointRay.h
.h
2,243
77
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Ray.h> // Compute the distance between a point and a ray in nD. // // The ray is P + t * D for t >= 0, where D is not required to be unit length. // // The input point is stored in closest[0]. The closest point on the ray is // stored in closest[1]. namespace gte { template <int32_t N, typename T> class DCPQuery<T, Vector<N, T>, Ray<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter(static_cast<T>(0)), closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; T parameter; std::array<Vector<N, T>, 2> closest; }; Result operator()(Vector<N, T> const& point, Ray<N, T> const& ray) { Result result{}; T const zero = static_cast<T>(0); Vector<N, T> diff = point - ray.origin; result.parameter = Dot(ray.direction, diff); result.closest[0] = point; if (result.parameter > zero) { result.closest[1] = ray.origin + result.parameter * ray.direction; } else { result.parameter = zero; result.closest[1] = ray.origin; } diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPPointRay = DCPQuery<T, Vector<N, T>, Ray<N, T>>; template <typename T> using DCPPoint2Ray2 = DCPPointRay<2, T>; template <typename T> using DCPPoint3Ray3 = DCPPointRay<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContCapsule3.h
.h
8,534
270
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprOrthogonalLine3.h> #include <Mathematics/Capsule.h> #include <Mathematics/DistPointLine.h> #include <Mathematics/DistPointSegment.h> #include <Mathematics/Hypersphere.h> namespace gte { // Compute the axis of the capsule segment using least-squares fitting. // The radius is the maximum distance from the points to the axis. // Hemispherical caps are chosen as close together as possible. template <typename Real> bool GetContainer(int32_t numPoints, Vector3<Real> const* points, Capsule3<Real>& capsule) { ApprOrthogonalLine3<Real> fitter; fitter.Fit(numPoints, points); Line3<Real> line = fitter.GetParameters(); DCPQuery<Real, Vector3<Real>, Line3<Real>> plQuery; Real maxRadiusSqr = (Real)0; for (int32_t i = 0; i < numPoints; ++i) { auto result = plQuery(points[i], line); if (result.sqrDistance > maxRadiusSqr) { maxRadiusSqr = result.sqrDistance; } } Vector3<Real> basis[3]; basis[0] = line.direction; ComputeOrthogonalComplement(1, basis); Real minValue = std::numeric_limits<Real>::max(); Real maxValue = -std::numeric_limits<Real>::max(); for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - line.origin; Real uDotDiff = Dot(diff, basis[1]); Real vDotDiff = Dot(diff, basis[2]); Real wDotDiff = Dot(diff, basis[0]); Real discr = maxRadiusSqr - (uDotDiff * uDotDiff + vDotDiff * vDotDiff); Real radical = std::sqrt(std::max(discr, (Real)0)); Real test = wDotDiff + radical; if (test < minValue) { minValue = test; } test = wDotDiff - radical; if (test > maxValue) { maxValue = test; } } Vector3<Real> center = line.origin + ((Real)0.5 * (minValue + maxValue)) * line.direction; Real extent; if (maxValue > minValue) { // Container is a capsule. extent = (Real)0.5 * (maxValue - minValue); } else { // Container is a sphere. extent = (Real)0; } capsule.segment = Segment3<Real>(center, line.direction, extent); capsule.radius = std::sqrt(maxRadiusSqr); return true; } // Test for containment of a point by a capsule. template <typename Real> bool InContainer(Vector3<Real> const& point, Capsule3<Real> const& capsule) { DCPQuery<Real, Vector3<Real>, Segment3<Real>> psQuery; auto result = psQuery(point, capsule.segment); return result.distance <= capsule.radius; } // Test for containment of a sphere by a capsule. template <typename Real> bool InContainer(Sphere3<Real> const& sphere, Capsule3<Real> const& capsule) { Real rDiff = capsule.radius - sphere.radius; if (rDiff >= (Real)0) { DCPQuery<Real, Vector3<Real>, Segment3<Real>> psQuery; auto result = psQuery(sphere.center, capsule.segment); return result.distance <= rDiff; } return false; } // Test for containment of a capsule by a capsule. template <typename Real> bool InContainer(Capsule3<Real> const& testCapsule, Capsule3<Real> const& capsule) { Sphere3<Real> spherePosEnd(testCapsule.segment.p[1], testCapsule.radius); Sphere3<Real> sphereNegEnd(testCapsule.segment.p[0], testCapsule.radius); return InContainer<Real>(spherePosEnd, capsule) && InContainer<Real>(sphereNegEnd, capsule); } // Compute a capsule that contains the input capsules. The returned // capsule is not necessarily the one of smallest volume that contains // the inputs. template <typename Real> bool MergeContainers(Capsule3<Real> const& capsule0, Capsule3<Real> const& capsule1, Capsule3<Real>& merge) { if (InContainer<Real>(capsule0, capsule1)) { merge = capsule1; return true; } if (InContainer<Real>(capsule1, capsule0)) { merge = capsule0; return true; } Vector3<Real> P0, P1, D0, D1; Real extent0, extent1; capsule0.segment.GetCenteredForm(P0, D0, extent0); capsule1.segment.GetCenteredForm(P1, D1, extent1); // Axis of final capsule. Line3<Real> line; // Axis center is average of input axis centers. line.origin = (Real)0.5 * (P0 + P1); // Axis unit direction is average of input axis unit directions. if (Dot(D0, D1) >= (Real)0) { line.direction = D0 + D1; } else { line.direction = D0 - D1; } Normalize(line.direction); // Cylinder with axis 'line' must contain the spheres centered at the // endpoints of the input capsules. DCPQuery<Real, Vector3<Real>, Line3<Real>> plQuery; Vector3<Real> posEnd0 = capsule0.segment.p[1]; Real radius = plQuery(posEnd0, line).distance + capsule0.radius; Vector3<Real> negEnd0 = capsule0.segment.p[0]; Real tmp = plQuery(negEnd0, line).distance + capsule0.radius; Vector3<Real> posEnd1 = capsule1.segment.p[1]; tmp = plQuery(posEnd1, line).distance + capsule1.radius; if (tmp > radius) { radius = tmp; } Vector3<Real> negEnd1 = capsule1.segment.p[0]; tmp = plQuery(negEnd1, line).distance + capsule1.radius; if (tmp > radius) { radius = tmp; } // In the following blocks of code, theoretically k1*k1-k0 >= 0, but // numerical rounding errors can make it slightly negative. Guard // against this. // Process sphere <posEnd0,r0>. Real rDiff = radius - capsule0.radius; Real rDiffSqr = rDiff * rDiff; Vector3<Real> diff = line.origin - posEnd0; Real k0 = Dot(diff, diff) - rDiffSqr; Real k1 = Dot(diff, line.direction); Real discr = k1 * k1 - k0; Real root = std::sqrt(std::max(discr, (Real)0)); Real tPos = -k1 - root; Real tNeg = -k1 + root; // Process sphere <negEnd0,r0>. diff = line.origin - negEnd0; k0 = Dot(diff, diff) - rDiffSqr; k1 = Dot(diff, line.direction); discr = k1 * k1 - k0; root = std::sqrt(std::max(discr, (Real)0)); tmp = -k1 - root; if (tmp > tPos) { tPos = tmp; } tmp = -k1 + root; if (tmp < tNeg) { tNeg = tmp; } // Process sphere <posEnd1,r1>. rDiff = radius - capsule1.radius; rDiffSqr = rDiff * rDiff; diff = line.origin - posEnd1; k0 = Dot(diff, diff) - rDiffSqr; k1 = Dot(diff, line.direction); discr = k1 * k1 - k0; root = std::sqrt(std::max(discr, (Real)0)); tmp = -k1 - root; if (tmp > tPos) { tPos = tmp; } tmp = -k1 + root; if (tmp < tNeg) { tNeg = tmp; } // Process sphere <negEnd1,r1>. diff = line.origin - negEnd1; k0 = Dot(diff, diff) - rDiffSqr; k1 = Dot(diff, line.direction); discr = k1 * k1 - k0; root = std::sqrt(std::max(discr, (Real)0)); tmp = -k1 - root; if (tmp > tPos) { tPos = tmp; } tmp = -k1 + root; if (tmp < tNeg) { tNeg = tmp; } Vector3<Real> center = line.origin + (Real)0.5 * (tPos + tNeg) * line.direction; Real extent; if (tPos > tNeg) { // Container is a capsule. extent = (Real)0.5 * (tPos - tNeg); } else { // Container is a sphere. extent = (Real)0; } merge.segment = Segment3<Real>(center, line.direction, extent); merge.radius = radius; return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrHalfspace2Polygon2.h
.h
5,704
167
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/Halfspace.h> #include <Mathematics/OrientedBox.h> #include <Mathematics/Vector2.h> #include <vector> // The queries consider the box to be a solid and the polygon to be a // convex solid. namespace gte { template <typename T> class FIQuery<T, Halfspace<2, T>, std::vector<Vector2<T>>> { public: struct Result { Result() : intersect(false), polygon{} { } bool intersect; // If 'intersect' is true, the halfspace and polygon intersect // in a convex polygon. std::vector<Vector2<T>> polygon; }; Result operator()(Halfspace<2, T> const& halfspace, std::vector<Vector2<T>> const& polygon) { Result result{}; // Determine whether the polygon vertices are outside the // halfspace, inside the halfspace, or on the halfspace boundary. int32_t const numVertices = static_cast<int32_t>(polygon.size()); std::vector<T> distance(numVertices); int32_t positive = 0, negative = 0, positiveIndex = -1; for (int32_t i = 0; i < numVertices; ++i) { distance[i] = Dot(halfspace.normal, polygon[i]) - halfspace.constant; if (distance[i] > (T)0) { ++positive; if (positiveIndex == -1) { positiveIndex = i; } } else if (distance[i] < (T)0) { ++negative; } } if (positive == 0) { // The polygon is strictly outside the halfspace. result.intersect = false; return result; } if (negative == 0) { // The polygon is contained in the closed halfspace, so it is // fully visible and no clipping is necessary. result.intersect = true; return result; } // The line transversely intersects the polygon. Clip the polygon. Vector2<T> vertex; int32_t curr, prev; T t; if (positiveIndex > 0) { // Compute the first clip vertex on the line. curr = positiveIndex; prev = curr - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); result.polygon.push_back(vertex); // Include the vertices on the positive side of line. while (curr < numVertices && distance[curr] >(T)0) { result.polygon.push_back(polygon[curr++]); } // Compute the kast clip vertex on the line. if (curr < numVertices) { prev = curr - 1; } else { curr = 0; prev = numVertices - 1; } t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); result.polygon.push_back(vertex); } else // positiveIndex is 0 { // Include the vertices on the positive side of line. curr = 0; while (curr < numVertices && distance[curr] >(T)0) { result.polygon.push_back(polygon[curr++]); } // Compute the last clip vertex on the line. prev = curr - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); result.polygon.push_back(vertex); // Skip the vertices on the negative side of the line. while (curr < numVertices && distance[curr] <= (T)0) { curr++; } // Compute the first clip vertex on the line. if (curr < numVertices) { prev = curr - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); result.polygon.push_back(vertex); // Keep the vertices on the positive side of the line. while (curr < numVertices && distance[curr] >(T)0) { result.polygon.push_back(polygon[curr++]); } } else { curr = 0; prev = numVertices - 1; t = distance[curr] / (distance[curr] - distance[prev]); vertex = polygon[curr] + t * (polygon[prev] - polygon[curr]); result.polygon.push_back(vertex); } } result.intersect = true; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Ellipse3.h
.h
3,559
130
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector2.h> #include <Mathematics/Vector3.h> // The plane containing ellipse is Dot(N,X-C) = 0 where X is any point in the // plane, C is the ellipse center, and N is a unit-length normal to the plane. // Vectors A0, A1, and N form an orthonormal right-handed set. The ellipse in // the plane is parameterized by X = C + e0*cos(t)*A0 + e1*sin(t)*A1, where A0 // is the major axis, A1 is the minor axis, and e0 and e1 are the extents // along those axes. The angle t is in [-pi,pi) and e0 >= e1 > 0. namespace gte { template <typename Real> class Ellipse3 { public: // Construction and destruction. The default constructor sets center // to (0,0,0), A0 to (1,0,0), A1 to (0,1,0), normal to (0,0,1), e0 // to 1, and e1 to 1. Ellipse3() : center(Vector3<Real>::Zero()), normal(Vector3<Real>::Unit(2)), axis{ Vector3<Real>::Unit(0), Vector3<Real>::Unit(1) }, extent{ (Real)1, (Real)1 } { } Ellipse3(Vector3<Real> const& inCenter, Vector3<Real> const& inNormal, std::array<Vector3<Real>, 2> const& inAxis, Vector2<Real> const& inExtent) : center(inCenter), normal(inNormal), axis(inAxis), extent(inExtent) { } // Public member access. Vector3<Real> center, normal; std::array<Vector3<Real>, 2> axis; Vector2<Real> extent; public: // Comparisons to support sorted containers. bool operator==(Ellipse3 const& ellipse) const { return center == ellipse.center && normal == ellipse.normal && axis[0] == ellipse.axis[0] && axis[1] == ellipse.axis[1] && extent == ellipse.extent; } bool operator!=(Ellipse3 const& ellipse) const { return !operator==(ellipse); } bool operator< (Ellipse3 const& ellipse) const { if (center < ellipse.center) { return true; } if (center > ellipse.center) { return false; } if (normal < ellipse.normal) { return true; } if (normal > ellipse.normal) { return false; } if (axis[0] < ellipse.axis[0]) { return true; } if (axis[0] > ellipse.axis[0]) { return false; } if (axis[1] < ellipse.axis[1]) { return true; } if (axis[1] > ellipse.axis[1]) { return false; } return extent < ellipse.extent; } bool operator<=(Ellipse3 const& ellipse) const { return !ellipse.operator<(*this); } bool operator> (Ellipse3 const& ellipse) const { return ellipse.operator<(*this); } bool operator>=(Ellipse3 const& ellipse) const { return !operator<(ellipse); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistCircle3Circle3.h
.h
17,137
414
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/DCPQuery.h> #include <Mathematics/Circle3.h> #include <Mathematics/Polynomial1.h> #include <Mathematics/RootsPolynomial.h> #include <set> // The 3D circle-circle distance algorithm is described in // https://www.geometrictools.com/Documentation/DistanceToCircle3.pdf // The notation used in the code matches that of the document. namespace gte { template <typename T> class DCPQuery<T, Circle3<T>, Circle3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), numClosestPairs(0), circle0Closest{ Vector3<T>::Zero(), Vector3<T>::Zero() }, circle1Closest{ Vector3<T>::Zero(), Vector3<T>::Zero() }, equidistant(false) { static_assert( std::is_floating_point<T>::value, "For now, only floating-point types are supported."); } T distance, sqrDistance; size_t numClosestPairs; std::array<Vector3<T>, 2> circle0Closest, circle1Closest; bool equidistant; }; Result operator()(Circle3<T> const& circle0, Circle3<T> const& circle1) { Result result{}; Vector3<T> const vzero = Vector3<T>::Zero(); T const zero = (T)0; Vector3<T> N0 = circle0.normal, N1 = circle1.normal; T r0 = circle0.radius, r1 = circle1.radius; Vector3<T> D = circle1.center - circle0.center; Vector3<T> N0xN1 = Cross(N0, N1); if (N0xN1 != vzero) { // Get parameters for constructing the degree-8 polynomial phi. T const one = (T)1, two = (T)2; T r0sqr = r0 * r0, r1sqr = r1 * r1; // Compute U1 and V1 for the plane of circle1. std::array<Vector3<T>, 3> basis{}; basis[0] = circle1.normal; ComputeOrthogonalComplement(1, basis.data()); Vector3<T> U1 = basis[1], V1 = basis[2]; // Construct the polynomial phi(cos(theta)). Vector3<T> N0xD = Cross(N0, D); Vector3<T> N0xU1 = Cross(N0, U1), N0xV1 = Cross(N0, V1); T a0 = r1 * Dot(D, U1), a1 = r1 * Dot(D, V1); T a2 = Dot(N0xD, N0xD), a3 = r1 * Dot(N0xD, N0xU1); T a4 = r1 * Dot(N0xD, N0xV1), a5 = r1sqr * Dot(N0xU1, N0xU1); T a6 = r1sqr * Dot(N0xU1, N0xV1), a7 = r1sqr * Dot(N0xV1, N0xV1); Polynomial1<T> p0{ a2 + a7, two * a3, a5 - a7 }; Polynomial1<T> p1{ two * a4, two * a6 }; Polynomial1<T> p2{ zero, a1 }; Polynomial1<T> p3{ -a0 }; Polynomial1<T> p4{ -a6, a4, two * a6 }; Polynomial1<T> p5{ -a3, a7 - a5 }; Polynomial1<T> tmp0{ one, zero, -one }; Polynomial1<T> tmp1 = p2 * p2 + tmp0 * p3 * p3; Polynomial1<T> tmp2 = two * p2 * p3; Polynomial1<T> tmp3 = p4 * p4 + tmp0 * p5 * p5; Polynomial1<T> tmp4 = two * p4 * p5; Polynomial1<T> p6 = p0 * tmp1 + tmp0 * p1 * tmp2 - r0sqr * tmp3; Polynomial1<T> p7 = p0 * tmp2 + p1 * tmp1 - r0sqr * tmp4; // Parameters for polynomial root finding. The roots[] array // stores the roots. We need only the unique ones, which is // the responsibility of the set uniqueRoots. The pairs[] // array stores the (cosine,sine) information mentioned in the // PDF. TODO: Choose the maximum number of iterations for root // finding based on specific polynomial data? uint32_t const maxIterations = 128; int32_t degree = 0; size_t numRoots = 0; std::array<T, 8> roots{}; std::set<T> uniqueRoots{}; size_t numPairs = 0; std::array<std::pair<T, T>, 16> pairs{}; T temp = zero, sn = zero; if (p7.GetDegree() > 0 || p7[0] != zero) { // H(cs,sn) = p6(cs) + sn * p7(cs) Polynomial1<T> phi = p6 * p6 - tmp0 * p7 * p7; degree = static_cast<int32_t>(phi.GetDegree()); LogAssert(degree > 0, "Unexpected degree for phi."); numRoots = RootsPolynomial<T>::Find(degree, &phi[0], maxIterations, roots.data()); for (size_t i = 0; i < numRoots; ++i) { uniqueRoots.insert(roots[i]); } for (auto const& cs : uniqueRoots) { if (std::fabs(cs) <= one) { temp = p7(cs); if (temp != zero) { sn = -p6(cs) / temp; pairs[numPairs++] = std::make_pair(cs, sn); } else { temp = std::max(one - cs * cs, zero); sn = std::sqrt(temp); pairs[numPairs++] = std::make_pair(cs, sn); if (sn != zero) { pairs[numPairs++] = std::make_pair(cs, -sn); } } } } } else { // H(cs,sn) = p6(cs) degree = static_cast<int32_t>(p6.GetDegree()); LogAssert(degree > 0, "Unexpected degree for p6."); numRoots = RootsPolynomial<T>::Find(degree, &p6[0], maxIterations, roots.data()); for (size_t i = 0; i < numRoots; ++i) { uniqueRoots.insert(roots[i]); } for (auto const& cs : uniqueRoots) { if (std::fabs(cs) <= one) { temp = std::max(one - cs * cs, zero); sn = std::sqrt(temp); pairs[numPairs++] = std::make_pair(cs, sn); if (sn != zero) { pairs[numPairs++] = std::make_pair(cs, -sn); } } } } std::array<ClosestInfo, 16> candidates{}; for (size_t i = 0; i < numPairs; ++i) { ClosestInfo& info = candidates[i]; Vector3<T> delta = D + r1 * (pairs[i].first * U1 + pairs[i].second * V1); info.circle1Closest = circle0.center + delta; T N0dDelta = Dot(N0, delta); T lenN0xDelta = Length(Cross(N0, delta)); if (lenN0xDelta > (T)0) { T diff = lenN0xDelta - r0; info.sqrDistance = N0dDelta * N0dDelta + diff * diff; delta -= N0dDelta * circle0.normal; Normalize(delta); info.circle0Closest = circle0.center + r0 * delta; info.equidistant = false; } else { Vector3<T> r0U0 = r0 * GetOrthogonal(N0, true); Vector3<T> diff = delta - r0U0; info.sqrDistance = Dot(diff, diff); info.circle0Closest = circle0.center + r0U0; info.equidistant = true; } } std::sort(candidates.begin(), candidates.begin() + numPairs); result.numClosestPairs = 1; result.sqrDistance = candidates[0].sqrDistance; result.circle0Closest[0] = candidates[0].circle0Closest; result.circle1Closest[0] = candidates[0].circle1Closest; result.equidistant = candidates[0].equidistant; if (numRoots > 1 && candidates[1].sqrDistance == candidates[0].sqrDistance) { result.numClosestPairs = 2; result.circle0Closest[1] = candidates[1].circle0Closest; result.circle1Closest[1] = candidates[1].circle1Closest; } } else { // The planes of the circles are parallel. Whether the planes // are the same or different, the problem reduces to // determining how two circles in the same plane are // separated, tangent with one circle outside the other, // overlapping, or one circle contained inside the other // circle. DoQueryParallelPlanes(circle0, circle1, D, result); } result.distance = std::sqrt(result.sqrDistance); return result; } private: class SCPolynomial { public: SCPolynomial() : mPoly{} { } SCPolynomial(T const& oneTerm, T const& cosTerm, T const& sinTerm) : mPoly{ Polynomial1<T>{ oneTerm, cosTerm }, Polynomial1<T>{ sinTerm } } { } inline Polynomial1<T> const& operator[] (uint32_t i) const { return mPoly[i]; } inline Polynomial1<T>& operator[] (uint32_t i) { return mPoly[i]; } SCPolynomial operator+(SCPolynomial const& object) const { SCPolynomial result{}; result.mPoly[0] = mPoly[0] + object.mPoly[0]; result.mPoly[1] = mPoly[1] + object.mPoly[1]; return result; } SCPolynomial operator-(SCPolynomial const& object) const { SCPolynomial result{}; result.mPoly[0] = mPoly[0] - object.mPoly[0]; result.mPoly[1] = mPoly[1] - object.mPoly[1]; return result; } SCPolynomial operator*(SCPolynomial const& object) const { // 1 - c^2 Polynomial1<T> omcsqr{ (T)1, (T)0, (T)-1 }; SCPolynomial result{}; result.mPoly[0] = mPoly[0] * object.mPoly[0] + omcsqr * mPoly[1] * object.mPoly[1]; result.mPoly[1] = mPoly[0] * object.mPoly[1] + mPoly[1] * object.mPoly[0]; return result; } SCPolynomial operator*(T scalar) const { SCPolynomial result{}; result.mPoly[0] = scalar * mPoly[0]; result.mPoly[1] = scalar * mPoly[1]; return result; } private: // poly0(c) + s * poly1(c) std::array<Polynomial1<T>, 2> mPoly; }; struct ClosestInfo { ClosestInfo() : sqrDistance((T)0), circle0Closest(Vector3<T>::Zero()), circle1Closest(Vector3<T>::Zero()), equidistant(false) { } T sqrDistance; Vector3<T> circle0Closest, circle1Closest; bool equidistant; inline bool operator< (ClosestInfo const& info) const { return sqrDistance < info.sqrDistance; } }; // The two circles are in parallel planes where D = C1 - C0, the // difference of circle centers. void DoQueryParallelPlanes(Circle3<T> const& circle0, Circle3<T> const& circle1, Vector3<T> const& D, Result& result) { T N0dD = Dot(circle0.normal, D); Vector3<T> normProj = N0dD * circle0.normal; Vector3<T> compProj = D - normProj; Vector3<T> U = compProj; T d = Normalize(U); // The configuration is determined by the relative location of the // intervals of projection of the circles on to the D-line. // Circle0 projects to [-r0,r0] and circle1 projects to // [d-r1,d+r1]. T r0 = circle0.radius, r1 = circle1.radius; T dmr1 = d - r1; T distance; if (dmr1 >= r0) // d >= r0 + r1 { // The circles are separated (d > r0 + r1) or tangent with one // outside the other (d = r0 + r1). distance = dmr1 - r0; result.numClosestPairs = 1; result.circle0Closest[0] = circle0.center + r0 * U; result.circle1Closest[0] = circle1.center - r1 * U; result.equidistant = false; } else // d < r0 + r1 { // The cases implicitly use the knowledge that d >= 0. T dpr1 = d + r1; if (dpr1 <= r0) { // Circle1 is inside circle0. distance = r0 - dpr1; result.numClosestPairs = 1; if (d > (T)0) { result.circle0Closest[0] = circle0.center + r0 * U; result.circle1Closest[0] = circle1.center + r1 * U; result.equidistant = false; } else { // The circles are concentric, so U = (0,0,0). // Construct a vector perpendicular to N0 to use for // closest points. U = GetOrthogonal(circle0.normal, true); result.circle0Closest[0] = circle0.center + r0 * U; result.circle1Closest[0] = circle1.center + r1 * U; result.equidistant = true; } } else if (dmr1 <= -r0) { // Circle0 is inside circle1. distance = -r0 - dmr1; result.numClosestPairs = 1; if (d > (T)0) { result.circle0Closest[0] = circle0.center - r0 * U; result.circle1Closest[0] = circle1.center - r1 * U; result.equidistant = false; } else { // The circles are concentric, so U = (0,0,0). // Construct a vector perpendicular to N0 to use for // closest points. U = GetOrthogonal(circle0.normal, true); result.circle0Closest[0] = circle0.center + r0 * U; result.circle1Closest[0] = circle1.center + r1 * U; result.equidistant = true; } } else { // The circles are overlapping. The two points of // intersection are C0 + s*(C1-C0) +/- h*Cross(N,U), where // s = (1 + (r0^2 - r1^2)/d^2)/2 and // h = sqrt(r0^2 - s^2 * d^2). T r0sqr = r0 * r0, r1sqr = r1 * r1, dsqr = d * d; T s = ((T)1 + (r0sqr - r1sqr) / dsqr) / (T)2; T arg = std::max(r0sqr - dsqr * s * s, (T)0); T h = std::sqrt(arg); Vector3<T> midpoint = circle0.center + s * compProj; Vector3<T> hNxU = h * Cross(circle0.normal, U); distance = (T)0; result.numClosestPairs = 2; result.circle0Closest[0] = midpoint + hNxU; result.circle0Closest[1] = midpoint - hNxU; result.circle1Closest[0] = result.circle0Closest[0] + normProj; result.circle1Closest[1] = result.circle0Closest[1] + normProj; result.equidistant = false; } } result.sqrDistance = distance * distance + N0dD * N0dD; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpVectorField2.h
.h
2,905
76
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Delaunay2Mesh.h> #include <Mathematics/IntpQuadraticNonuniform2.h> #include <memory> // Given points (x0[i],y0[i]) which are mapped to (x1[i],y1[i]) for // 0 <= i < N, interpolate positions (xIn,yIn) to (xOut,yOut). namespace gte { template <typename InputType, typename ComputeType, typename RationalType> class IntpVectorField2 { public: // Construction and destruction. ~IntpVectorField2() = default; IntpVectorField2(int32_t numPoints, Vector2<InputType> const* domain, Vector2<InputType> const* range) : mMesh(mDelaunay) { // Repackage the output vectors into individual components. This // is required because of the format that the quadratic // interpolator expects for its input data. mXRange.resize(numPoints); mYRange.resize(numPoints); for (int32_t i = 0; i < numPoints; ++i) { mXRange[i] = range[i][0]; mYRange[i] = range[i][1]; } // Common triangulator for the interpolators. mDelaunay(numPoints, &domain[0], (ComputeType)0); // Create interpolator for x-coordinate of vector field. mXInterp = std::make_unique<IntpQuadraticNonuniform2<InputType, TriangleMesh>>( mMesh, &mXRange[0], (InputType)1); // Create interpolator for y-coordinate of vector field, but share the // already created triangulation for the x-interpolator. mYInterp = std::make_unique<IntpQuadraticNonuniform2<InputType, TriangleMesh>>( mMesh, &mYRange[0], (InputType)1); } // The return value is 'true' if and only if (xIn,yIn) is in the // convex hull of the input domain points, in which case the // interpolation is valid. bool operator()(Vector2<InputType> const& input, Vector2<InputType>& output) const { InputType xDeriv, yDeriv; return (*mXInterp)(input, output[0], xDeriv, yDeriv) && (*mYInterp)(input, output[1], xDeriv, yDeriv); } protected: typedef Delaunay2Mesh<InputType, ComputeType, RationalType> TriangleMesh; Delaunay2<InputType, ComputeType> mDelaunay; TriangleMesh mMesh; std::vector<InputType> mXRange; std::vector<InputType> mYRange; std::unique_ptr<IntpQuadraticNonuniform2<InputType, TriangleMesh>> mXInterp; std::unique_ptr<IntpQuadraticNonuniform2<InputType, TriangleMesh>> mYInterp; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/InvSqrtEstimate.h
.h
5,731
161
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> // Minimax polynomial approximations to 1/sqrt(x). The polynomial p(x) of // degree D minimizes the quantity maximum{|1/sqrt(x) - p(x)| : x in [1,2]} // over all polynomials of degree D. namespace gte { template <typename Real> class InvSqrtEstimate { public: // The input constraint is x in [1,2]. For example, // float x; // in [1,2] // float result = InvSqrtEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { Real t = x - (Real)1; // t in (0,1] return Evaluate(degree<D>(), t); } // The input constraint is x > 0. Range reduction is used to generate // a/ value y in [1,2], call Evaluate(y), and combine the output with // the proper exponent to obtain the approximation. For example, // float x; // x > 0 // float result = InvSqrtEstimate<float>::DegreeRR<3>(x); template <int32_t D> inline static Real DegreeRR(Real x) { Real adj, y; int32_t p; Reduce(x, adj, y, p); Real poly = Degree<D>(y); Real result = Combine(adj, poly, p); return result; } private: // Metaprogramming and private implementation to allow specialization // of a template member function. template <int32_t D> struct degree {}; inline static Real Evaluate(degree<1>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG1_C1; poly = (Real)GTE_C_INVSQRT_DEG1_C0 + poly * t; return poly; } inline static Real Evaluate(degree<2>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG2_C2; poly = (Real)GTE_C_INVSQRT_DEG2_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG2_C0 + poly * t; return poly; } inline static Real Evaluate(degree<3>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG3_C3; poly = (Real)GTE_C_INVSQRT_DEG3_C2 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG3_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG3_C0 + poly * t; return poly; } inline static Real Evaluate(degree<4>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG4_C4; poly = (Real)GTE_C_INVSQRT_DEG4_C3 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG4_C2 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG4_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG4_C0 + poly * t; return poly; } inline static Real Evaluate(degree<5>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG5_C5; poly = (Real)GTE_C_INVSQRT_DEG5_C4 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG5_C3 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG5_C2 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG5_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG5_C0 + poly * t; return poly; } inline static Real Evaluate(degree<6>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG6_C6; poly = (Real)GTE_C_INVSQRT_DEG6_C5 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG6_C4 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG6_C3 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG6_C2 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG6_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG6_C0 + poly * t; return poly; } inline static Real Evaluate(degree<7>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG7_C7; poly = (Real)GTE_C_INVSQRT_DEG7_C6 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG7_C5 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG7_C4 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG7_C3 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG7_C2 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG7_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG7_C0 + poly * t; return poly; } inline static Real Evaluate(degree<8>, Real t) { Real poly; poly = (Real)GTE_C_INVSQRT_DEG8_C8; poly = (Real)GTE_C_INVSQRT_DEG8_C7 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C6 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C5 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C4 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C3 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C2 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C1 + poly * t; poly = (Real)GTE_C_INVSQRT_DEG8_C0 + poly * t; return poly; } // Support for range reduction. inline static void Reduce(Real x, Real& adj, Real& y, int32_t& p) { y = std::frexp(x, &p); // y in [1/2,1) y = ((Real)2) * y; // y in [1,2) --p; adj = (1 & p) * (Real)GTE_C_INV_SQRT_2 + (1 & ~p) * (Real)1; p = -(p >> 1); } inline static Real Combine(Real adj, Real y, int32_t p) { return adj * std::ldexp(y, p); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSplineGeodesic.h
.h
2,467
72
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/RiemannianGeodesic.h> #include <Mathematics/BSplineSurface.h> namespace gte { template <typename Real> class BSplineGeodesic : public RiemannianGeodesic<Real> { public: BSplineGeodesic(BSplineSurface<3, Real> const& spline) : RiemannianGeodesic<Real>(2), mSpline(&spline), mJet{} { } virtual ~BSplineGeodesic() { } private: virtual void ComputeMetric(const GVector<Real>& point) override { mSpline->Evaluate(point[0], point[1], 2, mJet.data()); Vector<3, Real> const& der0 = mJet[1]; Vector<3, Real> const& der1 = mJet[2]; this->mMetric(0, 0) = Dot(der0, der0); this->mMetric(0, 1) = Dot(der0, der1); this->mMetric(1, 0) = this->mMetric(0, 1); this->mMetric(1, 1) = Dot(der1, der1); } virtual void ComputeChristoffel1(const GVector<Real>&) override { Vector<3, Real> const& der0 = mJet[1]; Vector<3, Real> const& der1 = mJet[2]; Vector<3, Real> const& der00 = mJet[3]; Vector<3, Real> const& der01 = mJet[4]; Vector<3, Real> const& der11 = mJet[5]; this->mChristoffel1[0](0, 0) = Dot(der00, der0); this->mChristoffel1[0](0, 1) = Dot(der01, der0); this->mChristoffel1[0](1, 0) = this->mChristoffel1[0](0, 1); this->mChristoffel1[0](1, 1) = Dot(der11, der0); this->mChristoffel1[1](0, 0) = Dot(der00, der1); this->mChristoffel1[1](0, 1) = Dot(der01, der1); this->mChristoffel1[1](1, 0) = this->mChristoffel1[1](0, 1); this->mChristoffel1[1](1, 1) = Dot(der11, der1); } BSplineSurface<3, Real> const* mSpline; // We are guaranteed that RiemannianGeodesic calls ComputeMetric // before ComputeChristoffel1. Thus, we can compute the B-spline // first- and second-order derivatives in ComputeMetric and cache // the results for use in ComputeChristoffel1. std::array<Vector<3, Real>, 6> mJet; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/CubicRootsQR.h
.h
7,942
217
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <array> #include <cmath> #include <cstdint> // An implementation of the QR algorithm described in "Matrix Computations, // 2nd edition" by G. H. Golub and C. F. Van Loan, The Johns Hopkins // University Press, Baltimore MD, Fourth Printing 1993. In particular, // the implementation is based on Chapter 7 (The Unsymmetric Eigenvalue // Problem), Section 7.5 (The Practical QR Algorithm). The algorithm is // specialized for the companion matrix associated with a cubic polynomial. namespace gte { template <typename Real> class CubicRootsQR { public: typedef std::array<std::array<Real, 3>, 3> Matrix; // Solve p(x) = c0 + c1 * x + c2 * x^2 + x^3 = 0. uint32_t operator() (uint32_t maxIterations, Real c0, Real c1, Real c2, uint32_t& numRoots, std::array<Real, 3>& roots) const { // Create the companion matrix for the polynomial. The matrix is // in upper Hessenberg form. Matrix A; A[0][0] = (Real)0; A[0][1] = (Real)0; A[0][2] = -c0; A[1][0] = (Real)1; A[1][1] = (Real)0; A[1][2] = -c1; A[2][0] = (Real)0; A[2][1] = (Real)1; A[2][2] = -c2; // Avoid the QR-cycle when c1 = c2 = 0 and avoid the slow // convergence when c1 and c2 are nearly zero. std::array<Real, 3> V{ (Real)1, (Real)0.36602540378443865, (Real)0.36602540378443865 }; DoIteration(V, A); return operator()(maxIterations, A, numRoots, roots); } // Compute the real eigenvalues of the upper Hessenberg matrix A. The // matrix is modified by in-place operations, so if you need to remember // A, you must make your own copy before calling this function. uint32_t operator() (uint32_t maxIterations, Matrix& A, uint32_t& numRoots, std::array<Real, 3>& roots) const { numRoots = 0; std::fill(roots.begin(), roots.end(), (Real)0); for (uint32_t numIterations = 0; numIterations < maxIterations; ++numIterations) { // Apply a Francis QR iteration. Real tr = A[1][1] + A[2][2]; Real det = A[1][1] * A[2][2] - A[1][2] * A[2][1]; std::array<Real, 3> X{ A[0][0] * A[0][0] + A[0][1] * A[1][0] - tr * A[0][0] + det, A[1][0] * (A[0][0] + A[1][1] - tr), A[1][0] * A[2][1] }; std::array<Real, 3> V = House<3>(X); DoIteration(V, A); // Test for uncoupling of A. Real tr01 = A[0][0] + A[1][1]; if (tr01 + A[1][0] == tr01) { numRoots = 1; roots[0] = A[0][0]; GetQuadraticRoots(1, 2, A, numRoots, roots); return numIterations; } Real tr12 = A[1][1] + A[2][2]; if (tr12 + A[2][1] == tr12) { numRoots = 1; roots[0] = A[2][2]; GetQuadraticRoots(0, 1, A, numRoots, roots); return numIterations; } } return maxIterations; } private: void DoIteration(std::array<Real, 3> const& V, Matrix& A) const { Real multV = (Real)-2 / (V[0] * V[0] + V[1] * V[1] + V[2] * V[2]); std::array<Real, 3> MV{ multV * V[0], multV * V[1], multV * V[2] }; RowHouse<3>(0, 2, 0, 2, V, MV, A); ColHouse<3>(0, 2, 0, 2, V, MV, A); std::array<Real, 2> Y{ A[1][0], A[2][0] }; std::array<Real, 2> W = House<2>(Y); Real multW = (Real)-2 / (W[0] * W[0] + W[1] * W[1]); std::array<Real, 2> MW{ multW * W[0], multW * W[1] }; RowHouse<2>(1, 2, 0, 2, W, MW, A); ColHouse<2>(0, 2, 1, 2, W, MW, A); } template <int32_t N> std::array<Real, N> House(std::array<Real, N> const& X) const { std::array<Real, N> V; Real length = (Real)0; for (int32_t i = 0; i < N; ++i) { length += X[i] * X[i]; } length = std::sqrt(length); if (length != (Real)0) { Real sign = (X[0] >= (Real)0 ? (Real)1 : (Real)-1); Real denom = X[0] + sign * length; for (int32_t i = 1; i < N; ++i) { V[i] = X[i] / denom; } } else { V.fill((Real)0); } V[0] = (Real)1; return V; } template <int32_t N> void RowHouse(int32_t rmin, int32_t rmax, int32_t cmin, int32_t cmax, std::array<Real, N> const& V, std::array<Real, N> const& MV, Matrix& A) const { // Only the elements cmin through cmax are used. std::array<Real, 3> W; for (int32_t c = cmin; c <= cmax; ++c) { W[c] = (Real)0; for (int32_t r = rmin, k = 0; r <= rmax; ++r, ++k) { W[c] += V[k] * A[r][c]; } } for (int32_t r = rmin, k = 0; r <= rmax; ++r, ++k) { for (int32_t c = cmin; c <= cmax; ++c) { A[r][c] += MV[k] * W[c]; } } } template <int32_t N> void ColHouse(int32_t rmin, int32_t rmax, int32_t cmin, int32_t cmax, std::array<Real, N> const& V, std::array<Real, N> const& MV, Matrix& A) const { // Only elements rmin through rmax are used. std::array<Real, 3> W; for (int32_t r = rmin; r <= rmax; ++r) { W[r] = (Real)0; for (int32_t c = cmin, k = 0; c <= cmax; ++c, ++k) { W[r] += V[k] * A[r][c]; } } for (int32_t r = rmin; r <= rmax; ++r) { for (int32_t c = cmin, k = 0; c <= cmax; ++c, ++k) { A[r][c] += W[r] * MV[k]; } } } void GetQuadraticRoots(int32_t i0, int32_t i1, Matrix const& A, uint32_t& numRoots, std::array<Real, 3>& roots) const { // Solve x^2 - t * x + d = 0, where t is the trace and d is the // determinant of the 2x2 matrix defined by indices i0 and i1. // The discriminant is D = (t/2)^2 - d. When D >= 0, the roots // are real values t/2 - sqrt(D) and t/2 + sqrt(D). To avoid // potential numerical issues with subtractive cancellation, the // roots are computed as // r0 = t/2 + sign(t/2)*sqrt(D), r1 = trace - r0. Real trace = A[i0][i0] + A[i1][i1]; Real halfTrace = trace * (Real)0.5; Real determinant = A[i0][i0] * A[i1][i1] - A[i0][i1] * A[i1][i0]; Real discriminant = halfTrace * halfTrace - determinant; if (discriminant >= (Real)0) { Real sign = (trace >= (Real)0 ? (Real)1 : (Real)-1); Real root = halfTrace + sign * std::sqrt(discriminant); roots[numRoots++] = root; roots[numRoots++] = trace - root; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment3Triangle3.h
.h
6,991
198
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Segment.h> #include <Mathematics/Triangle.h> #include <Mathematics/Vector3.h> namespace gte { template <typename Real> class TIQuery<Real, Segment3<Real>, Triangle3<Real>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Segment3<Real> const& segment, Triangle3<Real> const& triangle) { Result result{}; Vector3<Real> segOrigin{}, segDirection{}; Real segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); // Compute the offset origin, edges, and normal. Vector3<Real> diff = segOrigin - triangle.v[0]; Vector3<Real> edge1 = triangle.v[1] - triangle.v[0]; Vector3<Real> edge2 = triangle.v[2] - triangle.v[0]; Vector3<Real> normal = Cross(edge1, edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = diff, D = segment direction, // E1 = edge1, E2 = edge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) Real DdN = Dot(segDirection, normal); Real sign = (Real)0; if (DdN > (Real)0) { sign = (Real)1; } else if (DdN < (Real)0) { sign = (Real)-1; DdN = -DdN; } else { // Segment and triangle are parallel, call it a "no // intersection" even if the segment does intersect. result.intersect = false; return result; } Real DdQxE2 = sign * DotCross(segDirection, diff, edge2); if (DdQxE2 >= (Real)0) { Real DdE1xQ = sign * DotCross(segDirection, edge1, diff); if (DdE1xQ >= (Real)0) { if (DdQxE2 + DdE1xQ <= DdN) { // Line intersects triangle, check whether segment // does. Real QdN = -sign * Dot(diff, normal); Real extDdN = segExtent * DdN; if (-extDdN <= QdN && QdN <= extDdN) { // Segment intersects triangle. result.intersect = true; return result; } // else: |t| > extent, no intersection } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection result.intersect = false; return result; } }; template <typename Real> class FIQuery<Real, Segment3<Real>, Triangle3<Real>> { public: struct Result { Result() : intersect(false), parameter((Real)0), triangleBary{ (Real)0, (Real)0, (Real)0 }, point(Vector3<Real>::Zero()) { } bool intersect; Real parameter; std::array<Real, 3> triangleBary; Vector3<Real> point; }; Result operator()(Segment3<Real> const& segment, Triangle3<Real> const& triangle) { Result result{}; Vector3<Real> segOrigin{}, segDirection{}; Real segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); // Compute the offset origin, edges, and normal. Vector3<Real> diff = segOrigin - triangle.v[0]; Vector3<Real> edge1 = triangle.v[1] - triangle.v[0]; Vector3<Real> edge2 = triangle.v[2] - triangle.v[0]; Vector3<Real> normal = Cross(edge1, edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = diff, D = segment direction, // E1 = edge1, E2 = edge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) Real DdN = Dot(segDirection, normal); Real sign = (Real)0; if (DdN > (Real)0) { sign = (Real)1; } else if (DdN < (Real)0) { sign = (Real)-1; DdN = -DdN; } else { // Segment and triangle are parallel, call it a "no // intersection" even if the segment does intersect. result.intersect = false; return result; } Real DdQxE2 = sign * DotCross(segDirection, diff, edge2); if (DdQxE2 >= (Real)0) { Real DdE1xQ = sign * DotCross(segDirection, edge1, diff); if (DdE1xQ >= (Real)0) { if (DdQxE2 + DdE1xQ <= DdN) { // Line intersects triangle, check whether segment // does. Real QdN = -sign * Dot(diff, normal); Real extDdN = segExtent * DdN; if (-extDdN <= QdN && QdN <= extDdN) { // Segment intersects triangle. result.intersect = true; result.parameter = QdN / DdN; result.triangleBary[1] = DdQxE2 / DdN; result.triangleBary[2] = DdE1xQ / DdN; result.triangleBary[0] = (Real)1 - result.triangleBary[1] - result.triangleBary[2]; result.point = segOrigin + result.parameter * segDirection; return result; } // else: |t| > extent, no intersection } // else: b1+b2 > 1, no intersection } // else: b2 < 0, no intersection } // else: b1 < 0, no intersection result.intersect = false; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment3Cone3.h
.h
4,763
135
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Segment.h> #include <Mathematics/IntrLine3Cone3.h> // The queries consider the cone to be single sided and solid. The // cone height range is [hmin,hmax]. The cone can be infinite where // hmin = 0 and hmax = +infinity, infinite truncated where hmin > 0 // and hmax = +infinity, finite where hmin = 0 and hmax < +infinity, // or a cone frustum where hmin > 0 and hmax < +infinity. The // algorithm details are found in // https://www.geometrictools.com/Documentation/IntersectionLineCone.pdf namespace gte { template <typename T> class FIQuery<T, Segment3<T>, Cone3<T>> : public FIQuery<T, Line3<T>, Cone3<T>> { public: struct Result : public FIQuery<T, Line3<T>, Cone3<T>>::Result { Result() : FIQuery<T, Line3<T>, Cone3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment3<T> const& segment, Cone3<T> const& cone) { // Execute the line-cone query. Result result{}; Vector3<T> segOrigin = segment.p[0]; Vector3<T> segDirection = segment.p[1] - segment.p[0]; this->DoQuery(segOrigin, segDirection, cone, result); // Adjust the t-interval depending on whether the line-cone // t-interval overlaps the segment interval [0,1]. The block // numbers are a continuation of those in IntrRay3Cone3.h, which // themselves are a continuation of those in IntrLine3Cone3.h. if (result.type != Result::isEmpty) { using QFN1 = typename FIQuery<T, Line3<T>, Cone3<T>>::QFN1; QFN1 zero(0, 0, result.t[0].d), one(1, 0, result.t[0].d); if (result.type == Result::isPoint) { if (result.t[0] < zero || result.t[0] > one) { // Block 21. this->SetEmpty(result); } // else: Block 22. } else if (result.type == Result::isSegment) { if (result.t[1] < zero || result.t[0] > one) { // Block 23. this->SetEmpty(result); } else { QFN1 t0 = std::max(zero, result.t[0]); QFN1 t1 = std::min(one, result.t[1]); if (t0 < t1) { // Block 24. this->SetSegment(t0, t1, result); } else { // Block 25. this->SetPoint(t0, result); } } } else if (result.type == Result::isRayPositive) { if (one < result.t[0]) { // Block 26. this->SetEmpty(result); } else if (one > result.t[0]) { // Block 27. this->SetSegment(std::max(zero, result.t[0]), one, result); } else { // Block 28. this->SetPoint(one, result); } } else // result.type == Result::isRayNegative { if (zero > result.t[1]) { // Block 29. this->SetEmpty(result); } else if (zero < result.t[1]) { // Block 30. this->SetSegment(zero, std::min(one, result.t[1]), result); } else { // Block 31. this->SetPoint(zero, result); } } } result.ComputePoints(segment.p[0], segDirection); result.intersect = (result.type != Result::isEmpty); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSPrecision.h
.h
8,136
246
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <algorithm> #include <cstdint> #include <limits> // Support for determining the number of bits of precision required to compute // an expression using BSNumber or BSRational. namespace gte { class BSPrecision { public: enum class Type { IS_FLOAT, IS_DOUBLE, IS_INT32, IS_INT64, IS_UINT32, IS_UINT64 }; struct Parameters { Parameters() : minExponent(0), maxExponent(0), maxBits(0), maxWords(0) { } Parameters(int32_t inMinExponent, int32_t inMaxExponent, int32_t inMaxBits) : minExponent(inMinExponent), maxExponent(inMaxExponent), maxBits(inMaxBits), maxWords(GetMaxWords()) { } inline int32_t GetMaxWords() const { return maxBits / 32 + ((maxBits % 32) > 0 ? 1 : 0); } int32_t minExponent, maxExponent, maxBits, maxWords; }; Parameters bsn, bsr; BSPrecision() = default; BSPrecision(Type type) : bsn{}, bsr{} { switch (type) { case Type::IS_FLOAT: bsn = Parameters(-149, 127, 24); break; case Type::IS_DOUBLE: bsn = Parameters(-1074, 1023, 53); break; case Type::IS_INT32: bsn = Parameters(0, 30, 31); break; case Type::IS_INT64: bsn = Parameters(0, 62, 63); break; case Type::IS_UINT32: bsn = Parameters(0, 31, 32); break; case Type::IS_UINT64: bsn = Parameters(0, 63, 64); break; } bsr = bsn; } BSPrecision(int32_t minExponent, int32_t maxExponent, int32_t maxBits) : bsn(minExponent, maxExponent, maxBits), bsr(minExponent, maxExponent, maxBits) { } }; inline BSPrecision operator+(BSPrecision const& bsp0, BSPrecision const& bsp1) { BSPrecision result{}; result.bsn.minExponent = std::min(bsp0.bsn.minExponent, bsp1.bsn.minExponent); if (bsp0.bsn.maxExponent >= bsp1.bsn.maxExponent) { result.bsn.maxExponent = bsp0.bsn.maxExponent; if (bsp0.bsn.maxExponent - bsp0.bsn.maxBits + 1 <= bsp1.bsn.maxExponent) { ++result.bsn.maxExponent; } result.bsn.maxBits = bsp0.bsn.maxExponent - bsp1.bsn.minExponent + 1; if (result.bsn.maxBits <= bsp0.bsn.maxBits + bsp1.bsn.maxBits - 1) { ++result.bsn.maxBits; } } else { result.bsn.maxExponent = bsp1.bsn.maxExponent; if (bsp1.bsn.maxExponent - bsp1.bsn.maxBits + 1 <= bsp0.bsn.maxExponent) { ++result.bsn.maxExponent; } result.bsn.maxBits = bsp1.bsn.maxExponent - bsp0.bsn.minExponent + 1; if (result.bsn.maxBits <= bsp0.bsn.maxBits + bsp1.bsn.maxBits - 1) { ++result.bsn.maxBits; } } result.bsn.maxWords = result.bsn.GetMaxWords(); // Addition is n0/d0 + n1/d1 = (n0*d1 + n1*d0)/(d0*d1). The numerator // and denominator of a number are assumed to have the same // parameters, so for the addition, the numerator is used for the // parameter computations. // Compute the parameters for the multiplication. int32_t mulMinExponent = bsp0.bsr.minExponent + bsp1.bsr.minExponent; int32_t mulMaxExponent = bsp0.bsr.maxExponent + bsp1.bsr.maxExponent + 1; int32_t mulMaxBits = bsp0.bsr.maxBits + bsp1.bsr.maxBits; // Compute the parameters for the addition. The number n0*d1 and n1*d0 // are in the same arbitrary-precision set. result.bsr.minExponent = mulMinExponent; result.bsr.maxExponent = mulMaxExponent + 1; // Always a carry-out. result.bsr.maxBits = mulMaxExponent - mulMinExponent + 1; if (result.bsr.maxBits <= 2 * mulMaxBits - 1) { ++result.bsr.maxBits; } result.bsr.maxWords = result.bsr.GetMaxWords(); return result; } inline BSPrecision operator-(BSPrecision const& bsp0, BSPrecision const& bsp1) { return bsp0 + bsp1; } inline BSPrecision operator*(BSPrecision const& bsp0, BSPrecision const& bsp1) { BSPrecision result{}; result.bsn.minExponent = bsp0.bsn.minExponent + bsp1.bsn.minExponent; result.bsn.maxExponent = bsp0.bsn.maxExponent + bsp1.bsn.maxExponent + 1; result.bsn.maxBits = bsp0.bsn.maxBits + bsp1.bsn.maxBits; result.bsn.maxWords = result.bsn.GetMaxWords(); // Multiplication is (n0/d0) * (n1/d1) = (n0 * n1) / (d0 * d1). The // parameters are the same as for numerator/denominator. result.bsr.minExponent = bsp0.bsr.minExponent + bsp1.bsr.minExponent; result.bsr.maxExponent = bsp0.bsr.maxExponent + bsp1.bsr.maxExponent + 1; result.bsr.maxBits = bsp0.bsr.maxBits + bsp1.bsr.maxBits; result.bsr.maxWords = result.bsr.GetMaxWords(); return result; } inline BSPrecision operator/(BSPrecision const& bsp0, BSPrecision const& bsp1) { BSPrecision result{}; // BSNumber does not support division, so result.bsr has all members // set to zero. // Division is (n0/d0) / (n1/d1) = (n0 * d1) / (n1 * d0). The // parameters are the same as for multiplication. result.bsr.minExponent = bsp0.bsr.minExponent + bsp1.bsr.minExponent; result.bsr.maxExponent = bsp0.bsr.maxExponent + bsp1.bsr.maxExponent + 1; result.bsr.maxBits = bsp0.bsr.maxBits + bsp1.bsr.maxBits; result.bsr.maxWords = result.bsr.GetMaxWords(); return result; } // Comparisons for BSNumber do not involve dynamic allocations, so // the results are the extremes of the inputs. Comparisons for BSRational // involve multiplications of numerators and denominators. inline BSPrecision operator==(BSPrecision const& bsp0, BSPrecision const& bsp1) { BSPrecision result{}; result.bsn.minExponent = std::min(bsp0.bsn.minExponent, bsp1.bsn.minExponent); result.bsn.maxExponent = std::max(bsp0.bsn.maxExponent, bsp1.bsn.maxExponent); result.bsn.maxBits = std::max(bsp0.bsn.maxBits, bsp1.bsn.maxBits); result.bsn.maxWords = result.bsn.GetMaxWords(); result.bsr.minExponent = bsp0.bsr.minExponent + bsp1.bsr.minExponent; result.bsr.maxExponent = bsp0.bsr.maxExponent + bsp1.bsr.maxExponent + 1; result.bsr.maxBits = bsp0.bsr.maxBits + bsp1.bsr.maxBits; result.bsr.maxWords = result.bsr.GetMaxWords(); return result; } inline BSPrecision operator!=(BSPrecision const& bsp0, BSPrecision const& bsp1) { return operator==(bsp0, bsp1); } inline BSPrecision operator<(BSPrecision const& bsp0, BSPrecision const& bsp1) { return operator==(bsp0, bsp1); } inline BSPrecision operator<=(BSPrecision const& bsp0, BSPrecision const& bsp1) { return operator==(bsp0, bsp1); } inline BSPrecision operator>(BSPrecision const& bsp0, BSPrecision const& bsp1) { return operator==(bsp0, bsp1); } inline BSPrecision operator>=(BSPrecision const& bsp0, BSPrecision const& bsp1) { return operator==(bsp0, bsp1); } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TubeMesh.h
.h
8,255
232
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Mesh.h> #include <Mathematics/FrenetFrame.h> #include <functional> #include <memory> namespace gte { template <typename Real> class TubeMesh : public Mesh<Real> { public: // Create a mesh (x(u,v),y(u,v),z(u,v)) defined by the specified // medial curve and radial function. The mesh has torus topology // when 'closed' is true and has cylinder topology when 'closed' is // false. The client is responsible for setting the topology // correctly in the 'description' input. The rows correspond to // medial samples and the columns correspond to radial samples. The // medial curve is sampled according to its natural t-parameter when // 'sampleByArcLength' is false; otherwise, it is sampled uniformly // in arclength. TODO: Allow TORUS and remove the 'closed' input TubeMesh(MeshDescription const& description, std::shared_ptr<ParametricCurve<3, Real>> const& medial, std::function<Real(Real)> const& radial, bool closed, bool sampleByArcLength, Vector3<Real> upVector) : Mesh<Real>(description, { MeshTopology::CYLINDER }), mMedial(medial), mRadial(radial), mClosed(closed), mSampleByArcLength(sampleByArcLength), mUpVector(upVector) { if (!this->mDescription.constructed) { // The logger system will report these errors in the Mesh // constructor. mMedial = nullptr; return; } LogAssert(mMedial != nullptr, "A nonnull medial curve is required."); mCosAngle.resize(this->mDescription.numCols); mSinAngle.resize(this->mDescription.numCols); Real invRadialSamples = (Real)1 / (Real)(this->mDescription.numCols - 1); for (uint32_t i = 0; i < this->mDescription.numCols - 1; ++i) { Real angle = i * invRadialSamples * (Real)GTE_C_TWO_PI; mCosAngle[i] = std::cos(angle); mSinAngle[i] = std::sin(angle); } mCosAngle[this->mDescription.numCols - 1] = mCosAngle[0]; mSinAngle[this->mDescription.numCols - 1] = mSinAngle[0]; Real invDenom; if (mClosed) { invDenom = (Real)1 / (Real)this->mDescription.numRows; } else { invDenom = (Real)1 / (Real)(this->mDescription.numRows - 1); } Real factor; if (mSampleByArcLength) { factor = mMedial->GetTotalLength() * invDenom; mTSampler = [this, factor](uint32_t row) { return mMedial->GetTime(row * factor); }; } else { factor = (mMedial->GetTMax() - mMedial->GetTMin()) * invDenom; mTSampler = [this, factor](uint32_t row) { return mMedial->GetTMin() + row * factor; }; } if (mUpVector != Vector3<Real>::Zero()) { mFSampler = [this](Real t) { std::array<Vector3<Real>, 4> frame; frame[0] = mMedial->GetPosition(t); frame[1] = mMedial->GetTangent(t); frame[3] = UnitCross(frame[1], mUpVector); frame[2] = UnitCross(frame[3], frame[1]); return frame; }; } else { mFrenet = std::make_unique<FrenetFrame3<Real>>(mMedial); mFSampler = [this](Real t) { std::array<Vector3<Real>, 4> frame; (*mFrenet)(t, frame[0], frame[1], frame[2], frame[3]); return frame; }; } if (!this->mTCoords) { mDefaultTCoords.resize(this->mDescription.numVertices); this->mTCoords = mDefaultTCoords.data(); this->mTCoordStride = sizeof(Vector2<Real>); this->mDescription.allowUpdateFrame = this->mDescription.wantDynamicTangentSpaceUpdate; if (this->mDescription.allowUpdateFrame) { if (!this->mDescription.hasTangentSpaceVectors) { this->mDescription.allowUpdateFrame = false; } if (!this->mNormals) { this->mDescription.allowUpdateFrame = false; } } } this->ComputeIndices(); InitializeTCoords(); UpdatePositions(); if (this->mDescription.allowUpdateFrame) { this->UpdateFrame(); } else if (this->mNormals) { this->UpdateNormals(); } } // Member access. inline std::shared_ptr<ParametricCurve<3, Real>> const& GetMedial() const { return mMedial; } inline std::function<Real(Real)> const& GetRadial() const { return mRadial; } inline bool IsClosed() const { return mClosed; } inline bool IsSampleByArcLength() const { return mSampleByArcLength; } inline Vector3<Real> const& GetUpVector() const { return mUpVector; } private: void InitializeTCoords() { Vector2<Real>tcoord; for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { tcoord[1] = (Real)r / (Real)this->mDescription.rMax; for (uint32_t c = 0; c <= this->mDescription.numCols; ++c, ++i) { tcoord[0] = (Real)c / (Real)this->mDescription.numCols; this->TCoord(i) = tcoord; } } } virtual void UpdatePositions() override { uint32_t row, col, v, save; for (row = 0, v = 0; row < this->mDescription.numRows; ++row, ++v) { Real t = mTSampler(row); Real radius = mRadial(t); // frame = (position, tangent, normal, binormal) std::array<Vector3<Real>, 4> frame = mFSampler(t); for (col = 0, save = v; col < this->mDescription.numCols; ++col, ++v) { this->Position(v) = frame[0] + radius * (mCosAngle[col] * frame[2] + mSinAngle[col] * frame[3]); } this->Position(v) = this->Position(save); } if (mClosed) { for (col = 0; col < this->mDescription.numCols; ++col) { uint32_t i0 = col; uint32_t i1 = col + this->mDescription.numCols * (this->mDescription.numRows - 1); this->Position(i1) = this->Position(i0); } } } std::shared_ptr<ParametricCurve<3, Real>> mMedial; std::function<Real(Real)> mRadial; bool mClosed, mSampleByArcLength; Vector3<Real> mUpVector; std::vector<Real> mCosAngle, mSinAngle; std::function<Real(uint32_t)> mTSampler; std::function<std::array<Vector3<Real>, 4>(Real)> mFSampler; std::unique_ptr<FrenetFrame3<Real>> mFrenet; // If the client does not request texture coordinates, they will be // computed internally for use in evaluation of the surface geometry. std::vector<Vector2<Real>> mDefaultTCoords; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Torus3.h
.h
7,730
232
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector3.h> #include <cstdint> // A torus with origin (0,0,0), outer radius r0 and inner radius r1 (with // (r0 >= r1) is defined implicitly as follows. The point P0 = (x,y,z) is on // the torus. Its projection onto the xy-plane is P1 = (x,y,0). The circular // cross section of the torus that contains the projection has radius r0 and // center P2 = r0*(x,y,0)/sqrt(x^2+y^2). The points triangle <P0,P1,P2> is a // right triangle with right angle at P1. The hypotenuse <P0,P2> has length // r1, leg <P1,P2> has length z and leg <P0,P1> has length // |r0 - sqrt(x^2+y^2)|. The Pythagorean theorem says // z^2 + |r0 - sqrt(x^2+y^2)|^2 = r1^2. This can be algebraically // manipulated to // (x^2 + y^2 + z^2 + r0^2 - r1^2)^2 - 4 * r0^2 * (x^2 + y^2) = 0 // // A parametric form is // x = (r0 + r1 * cos(v)) * cos(u) // y = (r0 + r1 * cos(v)) * sin(u) // z = r1 * sin(v) // for u in [0,2*pi) and v in [0,2*pi). // // Generally, let the torus center be C with plane of symmetry containing C // and having directions D0 and D1. The axis of symmetry is the line // containing C and having direction N (the plane normal). The radius from // the center of the torus is r0 and the radius of the tube of the torus is // r1. A point P may be written as P = C + x*D0 + y*D1 + z*N, where matrix // [D0 D1 N] is orthonormal and has determinant 1. Thus, x = Dot(D0,P-C), // y = Dot(D1,P-C) and z = Dot(N,P-C). The implicit form is // [|P-C|^2 + r0^2 - r1^2]^2 - 4*r0^2*[|P-C|^2 - (Dot(N,P-C))^2] = 0 // Observe that D0 and D1 are not present in the equation, which is to be // expected by the symmetry. The parametric form is // P(u,v) = C + (r0 + r1*cos(v))*(cos(u)*D0 + sin(u)*D1) + r1*sin(v)*N // for u in [0,2*pi) and v in [0,2*pi). // // In the class Torus3, the members are 'center' C, 'direction0' D0, // 'direction1' D1, 'normal' N, 'radius0' r0 and 'radius1' r1. namespace gte { template <typename Real> class Torus3 { public: // Construction and destruction. The default constructor sets center // to (0,0,0), direction0 to (1,0,0), direction1 to (0,1,0), normal // to (0,0,1), radius0 to 2 and radius1 to 1. Torus3() : center(Vector3<Real>::Zero()), direction0(Vector3<Real>::Unit(0)), direction1(Vector3<Real>::Unit(1)), normal(Vector3<Real>::Unit(2)), radius0((Real)2), radius1((Real)1) { } Torus3(Vector3<Real> const& inCenter, Vector3<Real> const& inDirection0, Vector3<Real> const& inDirection1, Vector3<Real> const& inNormal, Real inRadius0, Real inRadius1) : center(inCenter), direction0(inDirection0), direction1(inDirection1), normal(inNormal), radius0(inRadius0), radius1(inRadius1) { } // Evaluation of the surface. The function supports derivative // calculation through order 2; that is, maxOrder <= 2 is required. // If you want only the position, pass in maxOrder of 0. If you want // the position and first-order derivatives, pass in maxOrder of 1, // and so on. The output 'values' are ordered as: position X; // first-order derivatives dX/du, dX/dv; second-order derivatives // d2X/du2, d2X/dudv, d2X/dv2. The input array 'jet' must have enough // storage for the specified order. void Evaluate(Real u, Real v, uint32_t maxOrder, Vector3<Real>* jet) const { // Compute position. Real csu = std::cos(u); Real snu = std::sin(u); Real csv = std::cos(v); Real snv = std::sin(v); Real r1csv = radius1 * csv; Real r1snv = radius1 * snv; Real r0pr1csv = radius0 + r1csv; Vector3<Real> combo0 = csu * direction0 + snu * direction1; Vector3<Real> r0pr1csvcombo0 = r0pr1csv * combo0; Vector3<Real> r1snvnormal = r1snv * normal; jet[0] = center + r0pr1csvcombo0 + r1snvnormal; if (maxOrder >= 1) { // Compute first-order derivatives. Vector3<Real> combo1 = -snu * direction0 + csu * direction1; jet[1] = r0pr1csv * combo1; jet[2] = -r1snv * combo0 + r1csv * normal; if (maxOrder == 2) { // Compute second-order derivatives. jet[3] = -r0pr1csvcombo0; jet[4] = -r1snv * combo1; jet[5] = -r1csv * combo0 - r1snvnormal; } } } // Reverse lookup of parameters from position. void GetParameters(Vector3<Real> const& X, Real& u, Real& v) const { Vector3<Real> delta = X - center; // (r0 + r1*cos(v))*cos(u) Real dot0 = Dot(direction0, delta); // (r0 + r1*cos(v))*sin(u) Real dot1 = Dot(direction1, delta); // r1*sin(v) Real dot2 = Dot(normal, delta); // r1*cos(v) Real r1csv = std::sqrt(dot0 * dot0 + dot1 * dot1) - radius0; u = std::atan2(dot1, dot0); v = std::atan2(dot2, r1csv); } Vector3<Real> center, direction0, direction1, normal; Real radius0, radius1; public: // Comparisons to support sorted containers. bool operator==(Torus3 const& torus) const { return center == torus.center && direction0 == torus.direction0 && direction1 == torus.direction1 && normal == torus.normal && radius0 == torus.radius0 && radius1 == torus.radius1; } bool operator!=(Torus3 const& torus) const { return !operator==(torus); } bool operator< (Torus3 const& torus) const { if (center < torus.center) { return true; } if (center > torus.center) { return false; } if (direction0 < torus.direction0) { return true; } if (direction0 > torus.direction0) { return false; } if (direction1 < torus.direction1) { return true; } if (direction1 > torus.direction1) { return false; } if (normal < torus.normal) { return true; } if (normal > torus.normal) { return false; } if (radius0 < torus.radius0) { return true; } if (radius0 > torus.radius0) { return false; } return radius1 < torus.radius1; } bool operator<=(Torus3 const& torus) const { return !torus.operator<(*this); } bool operator> (Torus3 const& torus) const { return torus.operator<(*this); } bool operator>=(Torus3 const& torus) const { return !operator<(torus); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ParametricSurface.h
.h
3,520
117
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.08 #pragma once #include <Mathematics/Vector.h> #include <cstdint> namespace gte { template <int32_t N, typename Real> class ParametricSurface { protected: // Abstract base class for a parameterized surface X(u,v). The // parametric domain is either rectangular or triangular. Valid // (u,v) values for a rectangular domain satisfy // umin <= u <= umax, vmin <= v <= vmax // and valid (u,v) values for a triangular domain satisfy // umin <= u <= umax, vmin <= v <= vmax, // (vmax-vmin)*(u-umin)+(umax-umin)*(v-vmax) <= 0 ParametricSurface(Real umin, Real umax, Real vmin, Real vmax, bool rectangular) : mUMin(umin), mUMax(umax), mVMin(vmin), mVMax(vmax), mRectangular(rectangular), mConstructed(false) { } public: virtual ~ParametricSurface() { } // To validate construction, create an object as shown: // DerivedClassSurface<Real> surface(parameters); // if (!surface) { <constructor failed, handle accordingly>; } inline operator bool() const { return mConstructed; } // Member access. inline Real GetUMin() const { return mUMin; } inline Real GetUMax() const { return mUMax; } inline Real GetVMin() const { return mVMin; } inline Real GetVMax() const { return mVMax; } inline bool IsRectangular() const { return mRectangular; } // Evaluation of the surface. The function supports derivative // calculation through order 2; that is, order <= 2 is required. If // you want only the position, pass in order of 0. If you want the // position and first-order derivatives, pass in order of 1, and so // on. The output array 'jet' must have enough storage to support the // maximum order. The values are ordered as: position X; first-order // derivatives dX/du, dX/dv; second-order derivatives d2X/du2, // d2X/dudv, d2X/dv2. enum { SUP_ORDER = 6 }; virtual void Evaluate(Real u, Real v, uint32_t order, Vector<N, Real>* jet) const = 0; // Differential geometric quantities. Vector<N, Real> GetPosition(Real u, Real v) const { std::array<Vector<N, Real>, SUP_ORDER> jet{}; Evaluate(u, v, 0, jet.data()); return jet[0]; } Vector<N, Real> GetUTangent(Real u, Real v) const { std::array<Vector<N, Real>, SUP_ORDER> jet{}; Evaluate(u, v, 1, jet.data()); Normalize(jet[1]); return jet[1]; } Vector<N, Real> GetVTangent(Real u, Real v) const { std::array<Vector<N, Real>, SUP_ORDER> jet{}; Evaluate(u, v, 1, jet.data()); Normalize(jet[2]); return jet[2]; } protected: Real mUMin, mUMax, mVMin, mVMax; bool mRectangular; bool mConstructed; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MinimizeN.h
.h
7,506
203
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/GVector.h> #include <Mathematics/Minimize1.h> #include <cstring> // The Cartesian-product domain provided to GetMinimum(*) has minimum values // stored in t0[0..d-1] and maximum values stored in t1[0..d-1], where d is // 'dimensions'. The domain is searched along lines through the current // estimate of the minimum location. Each such line is searched for a minimum // using a Minimize1<Real> object. This is called "Powell's Direction Set // Method". The parameters 'maxLevel' and 'maxBracket' are used by // Minimize1<Real>, so read the documentation for that class (in its header // file) to understand what these mean. The input 'maxIterations' is the // number of iterations for the direction-set method. namespace gte { template <typename Real> class MinimizeN { public: // Construction. MinimizeN(int32_t dimensions, std::function<Real(Real const*)> const& F, int32_t maxLevel, int32_t maxBracket, int32_t maxIterations, Real epsilon = (Real)1e-06) : mDimensions(dimensions), mFunction(F), mMaxIterations(maxIterations), mEpsilon(0), mDirections(static_cast<size_t>(dimensions) + 1), mDConjIndex(dimensions), mDCurrIndex(0), mTCurr(dimensions), mTSave(dimensions), mMinimizer([this](Real t){ return mFunction(&(mTCurr + t * mDirections[mDCurrIndex])[0]); }, maxLevel, maxBracket) { SetEpsilon(epsilon); for (auto& direction : mDirections) { direction.SetSize(dimensions); } } // Member access. inline void SetEpsilon(Real epsilon) { mEpsilon = (epsilon > (Real)0 ? epsilon : (Real)0); } inline Real GetEpsilon() const { return mEpsilon; } // Find the minimum on the Cartesian-product domain whose minimum // values are stored in t0[0..d-1] and whose maximum values are stored // in t1[0..d-1], where d is 'dimensions'. An initial guess is // specified in tInitial[0..d-1]. The location of the minimum is // tMin[0..d-1] and the value of the minimum is 'fMin'. void GetMinimum(Real const* t0, Real const* t1, Real const* tInitial, Real* tMin, Real& fMin) { // The initial guess. size_t numBytes = mDimensions * sizeof(Real); mFCurr = mFunction(tInitial); std::memcpy(&mTSave[0], tInitial, numBytes); std::memcpy(&mTCurr[0], tInitial, numBytes); // Initialize the direction set to the standard Euclidean basis. for (int32_t i = 0; i < mDimensions; ++i) { mDirections[i].MakeUnit(i); } Real ell0 = static_cast<Real>(0); Real ell1 = static_cast<Real>(0); Real ellMin = static_cast<Real>(0); for (int32_t iter = 0; iter < mMaxIterations; ++iter) { // Find minimum in each direction and update current location. for (int32_t i = 0; i < mDimensions; ++i) { mDCurrIndex = i; ComputeDomain(t0, t1, ell0, ell1); mMinimizer.GetMinimum(ell0, ell1, (Real)0, ellMin, mFCurr); mTCurr += ellMin * mDirections[i]; } // Estimate a unit-length conjugate direction. mDirections[mDConjIndex] = mTCurr - mTSave; Real length = Length(mDirections[mDConjIndex]); if (length <= mEpsilon) { // New position did not change significantly from old one. // Should there be a better convergence criterion here? break; } mDirections[mDConjIndex] /= length; // Minimize in conjugate direction. mDCurrIndex = mDConjIndex; ComputeDomain(t0, t1, ell0, ell1); mMinimizer.GetMinimum(ell0, ell1, (Real)0, ellMin, mFCurr); mTCurr += ellMin * mDirections[mDCurrIndex]; // Cycle the directions and add conjugate direction to set. mDConjIndex = 0; for (int32_t i = 0, ip1 = 1; i < mDimensions; ++i, ++ip1) { mDirections[i] = mDirections[ip1]; } // Set parameters for next pass. mTSave = mTCurr; } std::memcpy(tMin, &mTCurr[0], numBytes); fMin = mFCurr; } private: // The current estimate of the minimum location is mTCurr[0..d-1]. The // direction of the current line to search is mDCurr[0..d-1]. This // line must be clipped against the Cartesian-product domain, a // process implemented in this function. If the line is // mTCurr+s*mDCurr, the clip result is the s-interval [ell0,ell1]. void ComputeDomain(Real const* t0, Real const* t1, Real& ell0, Real& ell1) { ell0 = -std::numeric_limits<Real>::max(); ell1 = +std::numeric_limits<Real>::max(); for (int32_t i = 0; i < mDimensions; ++i) { Real value = mDirections[mDCurrIndex][i]; if (value != (Real)0) { Real b0 = t0[i] - mTCurr[i]; Real b1 = t1[i] - mTCurr[i]; Real inv = ((Real)1) / value; if (value > (Real)0) { // The valid t-interval is [b0,b1]. b0 *= inv; if (b0 > ell0) { ell0 = b0; } b1 *= inv; if (b1 < ell1) { ell1 = b1; } } else { // The valid t-interval is [b1,b0]. b0 *= inv; if (b0 < ell1) { ell1 = b0; } b1 *= inv; if (b1 > ell0) { ell0 = b1; } } } } // Correction if numerical errors lead to values nearly zero. if (ell0 > (Real)0) { ell0 = (Real)0; } if (ell1 < (Real)0) { ell1 = (Real)0; } } int32_t mDimensions; std::function<Real(Real const*)> mFunction; int32_t mMaxIterations; Real mEpsilon; std::vector<GVector<Real>> mDirections; int32_t mDConjIndex; int32_t mDCurrIndex; GVector<Real> mTCurr; GVector<Real> mTSave; Real mFCurr; Minimize1<Real> mMinimizer; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ETNonmanifoldMesh.h
.h
13,177
383
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/WeakPtrCompare.h> #include <Mathematics/EdgeKey.h> #include <Mathematics/TriangleKey.h> #include <map> #include <set> #include <vector> namespace gte { class ETNonmanifoldMesh { public: // Edge data types. class Edge; typedef std::shared_ptr<Edge>(*ECreator)(int32_t, int32_t); typedef std::map<EdgeKey<false>, std::shared_ptr<Edge>> EMap; // Triangle data types. class Triangle; typedef std::shared_ptr<Triangle>(*TCreator)(int32_t, int32_t, int32_t); typedef std::map<TriangleKey<true>, std::shared_ptr<Triangle>> TMap; // Edge object. class Edge { public: virtual ~Edge() = default; Edge(int32_t v0, int32_t v1) : V{ v0, v1 } { } bool operator<(Edge const& other) const { return EdgeKey<false>(V[0], V[1]) < EdgeKey<false>(other.V[0], other.V[1]); } // Vertices of the edge. std::array<int32_t, 2> V; // Triangles sharing the edge. std::set<std::weak_ptr<Triangle>, WeakPtrLT<Triangle>> T; }; // Triangle object. class Triangle { public: virtual ~Triangle() = default; Triangle(int32_t v0, int32_t v1, int32_t v2) : V{ v0, v1, v2 } { } bool operator<(Triangle const& other) const { return TriangleKey<true>(V[0], V[1], V[2]) < TriangleKey<true>(other.V[0], other.V[1], other.V[2]); } // Vertices listed in counterclockwise order (V[0],V[1],V[2]). std::array<int32_t, 3> V; // Adjacent edges. E[i] points to edge (V[i],V[(i+1)%3]). std::array<std::weak_ptr<Edge>, 3> E; }; // Construction and destruction. virtual ~ETNonmanifoldMesh() = default; ETNonmanifoldMesh(ECreator eCreator = nullptr, TCreator tCreator = nullptr) : mECreator(eCreator ? eCreator : CreateEdge), mTCreator(tCreator ? tCreator : CreateTriangle) { } // Support for a deep copy of the mesh. The mEMap and mTMap objects // have dynamically allocated memory for edges and triangles. A // shallow copy of the pointers to this memory is problematic. // Allowing sharing, say, via std::shared_ptr, is an option but not // really the intent of copying the mesh graph. ETNonmanifoldMesh(ETNonmanifoldMesh const& mesh) { *this = mesh; } ETNonmanifoldMesh& operator=(ETNonmanifoldMesh const& mesh) { Clear(); mECreator = mesh.mECreator; mTCreator = mesh.mTCreator; for (auto const& element : mesh.mTMap) { Insert(element.first.V[0], element.first.V[1], element.first.V[2]); } return *this; } // Member access. inline EMap const& GetEdges() const { return mEMap; } inline TMap const& GetTriangles() const { return mTMap; } // If <v0,v1,v2> is not in the mesh, a Triangle object is created and // returned; otherwise, <v0,v1,v2> is in the mesh and nullptr is // returned. virtual std::shared_ptr<Triangle> Insert(int32_t v0, int32_t v1, int32_t v2) { TriangleKey<true> tkey(v0, v1, v2); if (mTMap.find(tkey) != mTMap.end()) { // The triangle already exists. Return a null pointer as a // signal to the caller that the insertion failed. return nullptr; } // Create the new triangle. It will be added to mTMap at the end // of the function so that if an assertion is triggered and the // function returns early, the (bad) triangle will not be part of // the mesh. std::shared_ptr<Triangle> tri = mTCreator(v0, v1, v2); // Add the edges to the mesh if they do not already exist. for (int32_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++) { EdgeKey<false> ekey(tri->V[i0], tri->V[i1]); std::shared_ptr<Edge> edge; auto eiter = mEMap.find(ekey); if (eiter == mEMap.end()) { // This is the first time the edge is encountered. edge = mECreator(tri->V[i0], tri->V[i1]); mEMap[ekey] = edge; } else { // The edge was previously encountered and created. edge = eiter->second; LogAssert(edge != nullptr, "Unexpected condition."); } // Associate the edge with the triangle. tri->E[i0] = edge; // Update the adjacent set of triangles for the edge. edge->T.insert(tri); } mTMap[tkey] = tri; return tri; } // If <v0,v1,v2> is in the mesh, it is removed and 'true' is returned; // otherwise, <v0,v1,v2> is not in the mesh and 'false' is returned. virtual bool Remove(int32_t v0, int32_t v1, int32_t v2) { TriangleKey<true> tkey(v0, v1, v2); auto titer = mTMap.find(tkey); if (titer == mTMap.end()) { // The triangle does not exist. return false; } // Get the triangle. std::shared_ptr<Triangle> tri = titer->second; // Remove the edges and update adjacent triangles if necessary. for (int32_t i = 0; i < 3; ++i) { // Inform the edges the triangle is being deleted. auto edge = tri->E[i].lock(); LogAssert(edge != nullptr, "Unexpected condition."); // Remove the triangle from the edge's set of adjacent // triangles. size_t numRemoved = edge->T.erase(tri); LogAssert(numRemoved > 0, "Unexpected condition."); // Remove the edge if you have the last reference to it. if (edge->T.size() == 0) { EdgeKey<false> ekey(edge->V[0], edge->V[1]); mEMap.erase(ekey); } } // Remove the triangle from the graph. mTMap.erase(tkey); return true; } // Destroy the edges and triangles to obtain an empty mesh. virtual void Clear() { mEMap.clear(); mTMap.clear(); } // A manifold mesh has the property that an edge is shared by at most // two triangles sharing. bool IsManifold() const { for (auto const& element : mEMap) { if (element.second->T.size() > 2) { return false; } } return true; } // A manifold mesh is closed if each edge is shared twice. A closed // mesh is not necessarily oriented. For example, you could have a // mesh with spherical topology. The upper hemisphere has outer-facing // normals and the lower hemisphere has inner-facing normals. The // discontinuity in orientation occurs on the circle shared by the // hemispheres. bool IsClosed() const { for (auto const& element : mEMap) { if (element.second->T.size() != 2) { return false; } } return true; } // Compute the connected components of the edge-triangle graph that // the mesh represents. The first function returns pointers into // 'this' object's containers, so you must consume the components // before clearing or destroying 'this'. The second function returns // triangle keys, which requires three times as much storage as the // pointers but allows you to clear or destroy 'this' before consuming // the components. void GetComponents(std::vector<std::vector<std::shared_ptr<Triangle>>>& components) const { // visited: 0 (unvisited), 1 (discovered), 2 (finished) std::map<std::shared_ptr<Triangle>, int32_t> visited; for (auto const& element : mTMap) { visited.insert(std::make_pair(element.second, 0)); } for (auto& element : mTMap) { auto tri = element.second; if (visited[tri] == 0) { std::vector<std::shared_ptr<Triangle>> component; DepthFirstSearch(tri, visited, component); components.push_back(component); } } } void GetComponents(std::vector<std::vector<TriangleKey<true>>>& components) const { // visited: 0 (unvisited), 1 (discovered), 2 (finished) std::map<std::shared_ptr<Triangle>, int32_t> visited; for (auto const& element : mTMap) { visited.insert(std::make_pair(element.second, 0)); } for (auto& element : mTMap) { std::shared_ptr<Triangle> tri = element.second; if (visited[tri] == 0) { std::vector<std::shared_ptr<Triangle>> component; DepthFirstSearch(tri, visited, component); std::vector<TriangleKey<true>> keyComponent; keyComponent.reserve(component.size()); for (auto const& t : component) { keyComponent.push_back(TriangleKey<true>(t->V[0], t->V[1], t->V[2])); } components.push_back(keyComponent); } } } protected: // The edge data and default edge creation. static std::shared_ptr<Edge> CreateEdge(int32_t v0, int32_t v1) { return std::make_shared<Edge>(v0, v1); } ECreator mECreator; EMap mEMap; // The triangle data and default triangle creation. static std::shared_ptr<Triangle> CreateTriangle(int32_t v0, int32_t v1, int32_t v2) { return std::make_shared<Triangle>(v0, v1, v2); } TCreator mTCreator; TMap mTMap; // Support for computing connected components. This is a // straightforward depth-first search of the graph but uses a // preallocated stack rather than a recursive function that could // possibly overflow the call stack. void DepthFirstSearch(std::shared_ptr<Triangle> const& tInitial, std::map<std::shared_ptr<Triangle>, int32_t>& visited, std::vector<std::shared_ptr<Triangle>>& component) const { // Allocate the maximum-size stack that can occur in the // depth-first search. The stack is empty when the index top // is -1. std::vector<std::shared_ptr<Triangle>> tStack(mTMap.size()); int32_t top = -1; tStack[++top] = tInitial; while (top >= 0) { std::shared_ptr<Triangle> tri = tStack[top]; visited[tri] = 1; int32_t i; for (i = 0; i < 3; ++i) { auto edge = tri->E[i].lock(); LogAssert(edge != nullptr, "Unexpected condition."); bool foundUnvisited = false; for (auto const& adjw : edge->T) { auto adj = adjw.lock(); LogAssert(adj != nullptr, "Unexpected condition."); if (visited[adj] == 0) { tStack[++top] = adj; foundUnvisited = true; break; } } if (foundUnvisited) { break; } } if (i == 3) { visited[tri] = 2; component.push_back(tri); --top; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BitHacks.h
.h
7,048
210
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.05.30 #pragma once #include <Mathematics/Logger.h> #include <array> #include <cstdint> // The leadingBit table in GetLeadingBit and the trailingBit table in // GetTrailingBit are based on De Bruijn sequences. The leadingBit table // is taken from // https://stackoverflow.com/questions/17027878/algorithm-to-find-the-most-significant-bit // The trailingBit table is taken from // https://www.dotnetperls.com/trailing-bits // The int32_t inputs to the bit-hack functions are required to be // nonnegative. Expose this if you want exceptions thrown when the // int32_t inputs are negative. #define GTE_THROW_ON_BITHACKS_ERROR namespace gte { class BitHacks { public: static bool IsPowerOfTwo(uint32_t value) { return (value > 0) && ((value & (value - 1)) == 0); } static bool IsPowerOfTwo(int32_t value) { #if defined(GTE_THROW_ON_BITHACKS_ERROR) LogAssert(value >= 0, "Invalid input."); #endif return IsPowerOfTwo(static_cast<uint32_t>(value)); } static uint32_t Log2OfPowerOfTwo(uint32_t powerOfTwo) { uint32_t log2 = (powerOfTwo & 0xAAAAAAAAu) != 0; log2 |= ((powerOfTwo & 0xFFFF0000u) != 0) << 4; log2 |= ((powerOfTwo & 0xFF00FF00u) != 0) << 3; log2 |= ((powerOfTwo & 0xF0F0F0F0u) != 0) << 2; log2 |= ((powerOfTwo & 0xCCCCCCCCu) != 0) << 1; return log2; } static int32_t Log2OfPowerOfTwo(int32_t powerOfTwo) { #if defined(GTE_THROW_ON_BITHACKS_ERROR) LogAssert(powerOfTwo >= 0, "Invalid input."); #endif return static_cast<int32_t>(Log2OfPowerOfTwo(static_cast<uint32_t>(powerOfTwo))); } // The return value of the function is the index into the 32-bit value. // For example, GetLeadingBit(10) = 3 and GetTrailingBit(10) = 2. The // value in binary is 0x0000000000001010. The bit locations start at 0 // on the right of the pattern and end at 31 on the left of the pattern. // If the input value is zero, there is no leading bit and no trailing // bit. However, the functions return 0, which is considered invalid. // Try to call these functions only for positive inputs. static int32_t GetLeadingBit(uint32_t value) { static std::array<int32_t, 32> const leadingBitTable = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; uint32_t key = (value * 0x07C4ACDDu) >> 27; return leadingBitTable[key]; } static int32_t GetLeadingBit(int32_t value) { #if defined(GTE_THROW_ON_BITHACKS_ERROR) LogAssert(value != 0, "Invalid input."); #endif return GetLeadingBit(static_cast<uint32_t>(value)); } static int32_t GetLeadingBit(uint64_t value) { uint32_t v1 = static_cast<uint32_t>((value >> 32) & 0x00000000FFFFFFFFull); if (v1 != 0) { return GetLeadingBit(v1) + 32; } uint32_t v0 = static_cast<uint32_t>(value & 0x00000000FFFFFFFFull); return GetLeadingBit(v0); } static int32_t GetLeadingBit(int64_t value) { #if defined(GTE_THROW_ON_BITHACKS_ERROR) LogAssert(value != 0, "Invalid input."); #endif return GetLeadingBit(static_cast<uint64_t>(value)); } static int32_t GetTrailingBit(int32_t value) { static std::array<int32_t, 32> const trailingBitTable = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; #if defined(GTE_THROW_ON_BITHACKS_ERROR) LogAssert(value != 0, "Invalid input."); #endif uint32_t key = (static_cast<uint32_t>((value & -value) * 0x077CB531u)) >> 27; return trailingBitTable[key]; } static int32_t GetTrailingBit(uint32_t value) { // The GetTrailingBit(int32_t) function contains the actual // implementation. If the uint32_t-based function were to be // implemented, the (value & -value) statement generates a compiler // warning about negating an unsigned integer, which requires // additional logic to avoid. return GetTrailingBit(static_cast<int32_t>(value)); } static int32_t GetTrailingBit(uint64_t value) { uint32_t v0 = static_cast<uint32_t>(value & 0x00000000FFFFFFFFull); if (v0 != 0) { return GetTrailingBit(v0); } uint32_t v1 = static_cast<uint32_t>((value >> 32) & 0x00000000FFFFFFFFull); if (v1 != 0) { return GetTrailingBit(v1) + 32; } return 0; } static int32_t GetTrailingBit(int64_t value) { #if defined(GTE_THROW_ON_BITHACKS_ERROR) LogAssert(value != 0, "Invalid input."); #endif return GetTrailingBit(static_cast<uint64_t>(value)); } // Round up to a power of two. If input is zero, the return is 1. If // input is larger than 2^{31}, the return is 2^{32}. static uint64_t RoundUpToPowerOfTwo(uint32_t value) { if (value > 0) { int32_t leading = GetLeadingBit(value); uint32_t mask = (1 << leading); if ((value & ~mask) == 0) { // value is a power of two return static_cast<uint64_t>(value); } else { // round up to a power of two return (static_cast<uint64_t>(mask) << 1); } } else { return 1ull; } } // Round down to a power of two. If input is zero, the return is 0. static uint32_t RoundDownToPowerOfTwo(uint32_t value) { if (value > 0) { int32_t leading = GetLeadingBit(value); uint32_t mask = (1 << leading); return mask; } else { return 0; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NURBSVolume.h
.h
9,735
247
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/BasisFunction.h> #include <Mathematics/Vector.h> namespace gte { template <int32_t N, typename Real> class NURBSVolume { public: // Construction. If the input controls is non-null, a copy is made of // the controls. To defer setting the control points or weights, pass // null pointers and later access the control points or weights via // GetControls(), GetWeights(), SetControl(), or SetWeight() member // functions. The 'controls' and 'weights' must be stored in // lexicographical order, // attribute[i0 + numControls0 * (i1 + numControls1 * i2)] // As a 3D array, this corresponds to attribute3D[i2][i1][i0]. NURBSVolume(BasisFunctionInput<Real> const& input0, BasisFunctionInput<Real> const& input1, BasisFunctionInput<Real> const& input2, Vector<N, Real> const* controls, Real const* weights) : mConstructed(false) { BasisFunctionInput<Real> const* input[3] = { &input0, &input1, &input2 }; for (int32_t i = 0; i < 3; ++i) { mNumControls[i] = input[i]->numControls; mBasisFunction[i].Create(*input[i]); } // The replication of control points for periodic splines is // avoided by wrapping the i-loop index in Evaluate. int32_t numControls = mNumControls[0] * mNumControls[1] * mNumControls[2]; mControls.resize(numControls); mWeights.resize(numControls); if (controls) { std::copy(controls, controls + numControls, mControls.begin()); } else { Vector<N, Real> zero{ (Real)0 }; std::fill(mControls.begin(), mControls.end(), zero); } if (weights) { std::copy(weights, weights + numControls, mWeights.begin()); } else { std::fill(mWeights.begin(), mWeights.end(), (Real)0); } mConstructed = true; } // To validate construction, create an object as shown: // NURBSVolume<N, Real> volume(parameters); // if (!volume) { <constructor failed, handle accordingly>; } inline operator bool() const { return mConstructed; } // Member access. The index 'dim' must be in {0,1,2}. inline BasisFunction<Real> const& GetBasisFunction(int32_t dim) const { return mBasisFunction[dim]; } inline Real GetMinDomain(int32_t dim) const { return mBasisFunction[dim].GetMinDomain(); } inline Real GetMaxDomain(int32_t dim) const { return mBasisFunction[dim].GetMaxDomain(); } inline int32_t GetNumControls(int32_t dim) const { return mNumControls[dim]; } inline Vector<N, Real> const* GetControls() const { return mControls.data(); } inline Vector<N, Real>* GetControls() { return mControls.data(); } inline Real const* GetWeights() const { return mWeights.data(); } inline Real* GetWeights() { return mWeights.data(); } // Evaluation of the volume. The function supports derivative // calculation through order 2; that is, order <= 2 is required. If // you want only the position, pass in order of 0. If you want the // position and first-order derivatives, pass in order of 1, and so // on. The output array 'jet' muist have enough storage to support // the maximum order. The values are ordered as: position X; // first-order derivatives dX/du, dX/dv, dX/dw; second-order // derivatives d2X/du2, d2X/dv2, d2X/dw2, d2X/dudv, d2X/dudw, // d2X/dvdw. enum { SUP_ORDER = 10 }; void Evaluate(Real u, Real v, Real w, uint32_t order, Vector<N, Real>* jet) const { if (!mConstructed || order >= SUP_ORDER) { // Errors were already generated during construction. for (uint32_t i = 0; i < SUP_ORDER; ++i) { jet[i].MakeZero(); } return; } int32_t iumin, iumax, ivmin, ivmax, iwmin, iwmax; mBasisFunction[0].Evaluate(u, order, iumin, iumax); mBasisFunction[1].Evaluate(v, order, ivmin, ivmax); mBasisFunction[2].Evaluate(w, order, iwmin, iwmax); // Compute position. Vector<N, Real> X; Real h; Compute(0, 0, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, X, h); Real invH = (Real)1 / h; jet[0] = invH * X; if (order >= 1) { // Compute first-order derivatives. Vector<N, Real> XDerU; Real hDerU; Compute(1, 0, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerU, hDerU); jet[1] = invH * (XDerU - hDerU * jet[0]); Vector<N, Real> XDerV; Real hDerV; Compute(0, 1, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerV, hDerV); jet[2] = invH * (XDerV - hDerV * jet[0]); Vector<N, Real> XDerW; Real hDerW; Compute(0, 0, 1, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerW, hDerW); jet[3] = invH * (XDerW - hDerW * jet[0]); if (order >= 2) { // Compute second-order derivatives. Vector<N, Real> XDerUU; Real hDerUU; Compute(2, 0, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerUU, hDerUU); jet[4] = invH * (XDerUU - (Real)2 * hDerU * jet[1] - hDerUU * jet[0]); Vector<N, Real> XDerVV; Real hDerVV; Compute(0, 2, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerVV, hDerVV); jet[5] = invH * (XDerVV - (Real)2 * hDerV * jet[2] - hDerVV * jet[0]); Vector<N, Real> XDerWW; Real hDerWW; Compute(0, 0, 2, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerWW, hDerWW); jet[6] = invH * (XDerWW - (Real)2 * hDerW * jet[3] - hDerWW * jet[0]); Vector<N, Real> XDerUV; Real hDerUV; Compute(1, 1, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerUV, hDerUV); jet[7] = invH * (XDerUV - hDerU * jet[2] - hDerV * jet[1] - hDerUV * jet[0]); Vector<N, Real> XDerUW; Real hDerUW; Compute(1, 0, 1, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerUW, hDerUW); jet[8] = invH * (XDerUW - hDerU * jet[3] - hDerW * jet[1] - hDerUW * jet[0]); Vector<N, Real> XDerVW; Real hDerVW; Compute(0, 1, 1, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerVW, hDerVW); jet[9] = invH * (XDerVW - hDerV * jet[3] - hDerW * jet[2] - hDerVW * jet[0]); } } } private: // Support for Evaluate(...). void Compute(uint32_t uOrder, uint32_t vOrder, uint32_t wOrder, int32_t iumin, int32_t iumax, int32_t ivmin, int32_t ivmax, int32_t iwmin, int32_t iwmax, Vector<N, Real>& X, Real& h) const { // The j*-indices introduce a tiny amount of overhead in order to // handle both aperiodic and periodic splines. For aperiodic // splines, j* = i* always. int32_t const numControls0 = mNumControls[0]; int32_t const numControls1 = mNumControls[1]; int32_t const numControls2 = mNumControls[2]; X.MakeZero(); h = (Real)0; for (int32_t iw = iwmin; iw <= iwmax; ++iw) { Real tmpw = mBasisFunction[2].GetValue(wOrder, iw); int32_t jw = (iw >= numControls2 ? iw - numControls2 : iw); for (int32_t iv = ivmin; iv <= ivmax; ++iv) { Real tmpv = mBasisFunction[1].GetValue(vOrder, iv); Real tmpvw = tmpv * tmpw; int32_t jv = (iv >= numControls1 ? iv - numControls1 : iv); for (int32_t iu = iumin; iu <= iumax; ++iu) { Real tmpu = mBasisFunction[0].GetValue(uOrder, iu); int32_t ju = (iu >= numControls0 ? iu - numControls0 : iu); int32_t index = ju + numControls0 * (jv + numControls1 * jw); Real tmp = (tmpu * tmpvw) * mWeights[index]; X += tmp * mControls[index]; h += tmp; } } } } std::array<BasisFunction<Real>, 3> mBasisFunction; std::array<int32_t, 3> mNumControls; std::vector<Vector<N, Real>> mControls; std::vector<Real> mWeights; bool mConstructed; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Cylinder3.h
.h
3,500
131
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Line.h> // The cylinder axis is a line. The origin of the cylinder is chosen to be // the line origin. The cylinder wall is at a distance R units from the axis. // An infinite cylinder has infinite height. A finite cylinder has center C // at the line origin and has a finite height H. The segment for the finite // cylinder has endpoints C-(H/2)*D and C+(H/2)*D where D is a unit-length // direction of the line. // // NOTE: Some of the geometric queries involve infinite cylinders. To support // exact arithmetic, it is necessary to avoid std::numeric_limits members // such as infinity() and max(). Instead, the queries require you to set // the infinite cylinder 'height' to -1. namespace gte { template <typename T> class Cylinder3 { public: // Construction and destruction. The default constructor sets axis // to (0,0,1), radius to 1, and height to 1. Cylinder3() : axis(Line3<T>()), radius((T)1), height((T)1) { } Cylinder3(Line3<T> const& inAxis, T inRadius, T inHeight) : axis(inAxis), radius(inRadius), height(inHeight) { } // Please read the NOTE at the beginning of this file about setting // the 'height' member for infinite cylinders. inline void MakeInfiniteCylinder() { height = static_cast<T>(-1); } inline void MakeFiniteCylinder(T const& inHeight) { if (inHeight >= static_cast<T>(0)) { height = inHeight; } } inline bool IsFinite() const { return height >= static_cast<T>(0); } inline bool IsInfinite() const { return height < static_cast<T>(0); } Line3<T> axis; T radius, height; public: // Comparisons to support sorted containers. bool operator==(Cylinder3 const& cylinder) const { return axis == cylinder.axis && radius == cylinder.radius && height == cylinder.height; } bool operator!=(Cylinder3 const& cylinder) const { return !operator==(cylinder); } bool operator< (Cylinder3 const& cylinder) const { if (axis < cylinder.axis) { return true; } if (axis > cylinder.axis) { return false; } if (radius < cylinder.radius) { return true; } if (radius > cylinder.radius) { return false; } return height < cylinder.height; } bool operator<=(Cylinder3 const& cylinder) const { return !cylinder.operator<(*this); } bool operator> (Cylinder3 const& cylinder) const { return cylinder.operator<(*this); } bool operator>=(Cylinder3 const& cylinder) const { return !operator<(cylinder); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprPolynomialSpecial3.h
.h
11,832
320
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/GMatrix.h> #include <array> // Fit the data with a polynomial of the form // w = sum_{i=0}^{n-1} c[i]*x^{p[i]}*y^{q[i]} // where <p[i],q[i]> are distinct pairs of nonnegative powers provided by the // caller. A least-squares fitting algorithm is used, but the input data is // first mapped to (x,y,w) in [-1,1]^3 for numerical robustness. namespace gte { template <typename Real> class ApprPolynomialSpecial3 : public ApprQuery<Real, std::array<Real, 3>> { public: // Initialize the model parameters to zero. The degrees must be // nonnegative and strictly increasing. ApprPolynomialSpecial3(std::vector<int32_t> const& xDegrees, std::vector<int32_t> const& yDegrees) : mXDegrees(xDegrees), mYDegrees(yDegrees), mParameters(mXDegrees.size() * mYDegrees.size(), (Real)0) { #if !defined(GTE_NO_LOGGER) LogAssert(mXDegrees.size() == mYDegrees.size(), "The input arrays must have the same size."); LogAssert(mXDegrees.size() > 0, "The input array must have elements."); int32_t lastDegree = -1; for (auto degree : mXDegrees) { LogAssert(degree > lastDegree, "Degrees must be increasing."); lastDegree = degree; } LogAssert(mYDegrees.size() > 0, "The input array must have elements."); lastDegree = -1; for (auto degree : mYDegrees) { LogAssert(degree > lastDegree, "Degrees must be increasing."); lastDegree = degree; } #endif mXDomain[0] = std::numeric_limits<Real>::max(); mXDomain[1] = -mXDomain[0]; mYDomain[0] = std::numeric_limits<Real>::max(); mYDomain[1] = -mYDomain[0]; mWDomain[0] = std::numeric_limits<Real>::max(); mWDomain[1] = -mWDomain[0]; mScale[0] = (Real)0; mScale[1] = (Real)0; mScale[2] = (Real)0; mInvTwoWScale = (Real)0; // Powers of x and y are computed up to twice the powers when // constructing the fitted polynomial. Powers of x and y are // computed up to the powers for the evaluation of the fitted // polynomial. mXPowers.resize(2 * static_cast<size_t>(mXDegrees.back()) + 1); mXPowers[0] = (Real)1; mYPowers.resize(2 * static_cast<size_t>(mYDegrees.back()) + 1); mYPowers[0] = (Real)1; } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numObservations, std::array<Real, 3> const* observations, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numObservations, observations, numIndices, indices)) { // Transform the observations to [-1,1]^3 for numerical // robustness. std::vector<std::array<Real, 3>> transformed; Transform(observations, numIndices, indices, transformed); // Fit the transformed data using a least-squares algorithm. return DoLeastSquares(transformed); } std::fill(mParameters.begin(), mParameters.end(), (Real)0); return false; } // Get the parameters for the best fit. std::vector<Real> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return mParameters.size(); } // Compute the model error for the specified observation for the // current model parameters. The returned value for observation // (x0,y0,w0) is |w(x0,y0) - w0|, where w(x,y) is the fitted // polynomial. virtual Real Error(std::array<Real, 3> const& observation) const override { Real w = Evaluate(observation[0], observation[1]); Real error = std::fabs(w - observation[2]); return error; } virtual void CopyParameters(ApprQuery<Real, std::array<Real, 3>> const* input) override { auto source = dynamic_cast<ApprPolynomialSpecial3 const*>(input); if (source) { *this = *source; } } // Evaluate the polynomial. The domain interval is provided so you can // interpolate ((x,y) in domain) or extrapolate ((x,y) not in domain). std::array<Real, 2> const& GetXDomain() const { return mXDomain; } std::array<Real, 2> const& GetYDomain() const { return mYDomain; } Real Evaluate(Real x, Real y) const { // Transform (x,y) to (x',y') in [-1,1]^2. x = (Real)-1 + (Real)2 * mScale[0] * (x - mXDomain[0]); y = (Real)-1 + (Real)2 * mScale[1] * (y - mYDomain[0]); // Compute relevant powers of x and y. int32_t jmax = mXDegrees.back(); for (int32_t j = 1, jm1 = 0; j <= jmax; ++j, ++jm1) { mXPowers[j] = mXPowers[jm1] * x; } jmax = mYDegrees.back(); for (int32_t j = 1, jm1 = 0; j <= jmax; ++j, ++jm1) { mYPowers[j] = mYPowers[jm1] * y; } Real w = (Real)0; int32_t isup = static_cast<int32_t>(mXDegrees.size()); for (int32_t i = 0; i < isup; ++i) { Real xp = mXPowers[mXDegrees[i]]; Real yp = mYPowers[mYDegrees[i]]; w += mParameters[i] * xp * yp; } // Transform w from [-1,1] back to the original space. w = (w + (Real)1) * mInvTwoWScale + mWDomain[0]; return w; } private: // Transform the (x,y,w) values to (x',y',w') in [-1,1]^3. void Transform(std::array<Real, 3> const* observations, size_t numIndices, int32_t const* indices, std::vector<std::array<Real, 3>> & transformed) { int32_t numSamples = static_cast<int32_t>(numIndices); transformed.resize(numSamples); std::array<Real, 3> omin = observations[indices[0]]; std::array<Real, 3> omax = omin; std::array<Real, 3> obs; int32_t s, i; for (s = 1; s < numSamples; ++s) { obs = observations[indices[s]]; for (i = 0; i < 3; ++i) { if (obs[i] < omin[i]) { omin[i] = obs[i]; } else if (obs[i] > omax[i]) { omax[i] = obs[i]; } } } mXDomain[0] = omin[0]; mXDomain[1] = omax[0]; mYDomain[0] = omin[1]; mYDomain[1] = omax[1]; mWDomain[0] = omin[2]; mWDomain[1] = omax[2]; for (i = 0; i < 3; ++i) { mScale[i] = (Real)1 / (omax[i] - omin[i]); } for (s = 0; s < numSamples; ++s) { obs = observations[indices[s]]; for (i = 0; i < 3; ++i) { transformed[s][i] = (Real)-1 + (Real)2 * mScale[i] * (obs[i] - omin[i]); } } mInvTwoWScale = (Real)0.5 / mScale[2]; } // The least-squares fitting algorithm for the transformed data. bool DoLeastSquares(std::vector<std::array<Real, 3>> & transformed) { // Set up a linear system A*X = B, where X are the polynomial // coefficients. int32_t size = static_cast<int32_t>(mXDegrees.size()); GMatrix<Real> A(size, size); A.MakeZero(); GVector<Real> B(size); B.MakeZero(); int32_t numSamples = static_cast<int32_t>(transformed.size()); int32_t twoMaxXDegree = 2 * mXDegrees.back(); int32_t twoMaxYDegree = 2 * mYDegrees.back(); int32_t row, col; for (int32_t i = 0; i < numSamples; ++i) { // Compute relevant powers of x and y. Real x = transformed[i][0]; Real y = transformed[i][1]; Real w = transformed[i][2]; for (int32_t j = 1, jm1 = 0; j <= twoMaxXDegree; ++j, ++jm1) { mXPowers[j] = mXPowers[jm1] * x; } for (int32_t j = 1, jm1 = 0; j <= twoMaxYDegree; ++j, ++jm1) { mYPowers[j] = mYPowers[jm1] * y; } for (row = 0; row < size; ++row) { // Update the upper-triangular portion of the symmetric // matrix. Real xp, yp; for (col = row; col < size; ++col) { xp = mXPowers[static_cast<size_t>(mXDegrees[row]) + static_cast<size_t>(mXDegrees[col])]; yp = mYPowers[static_cast<size_t>(mYDegrees[row]) + static_cast<size_t>(mYDegrees[col])]; A(row, col) += xp * yp; } // Update the right-hand side of the system. xp = mXPowers[mXDegrees[row]]; yp = mYPowers[mYDegrees[row]]; B[row] += xp * yp * w; } } // Copy the upper-triangular portion of the symmetric matrix to // the lower-triangular portion. for (row = 0; row < size; ++row) { for (col = 0; col < row; ++col) { A(row, col) = A(col, row); } } // Precondition by normalizing the sums. Real invNumSamples = (Real)1 / (Real)numSamples; A *= invNumSamples; B *= invNumSamples; // Solve for the polynomial coefficients. GVector<Real> coefficients = Inverse(A) * B; bool hasNonzero = false; for (int32_t i = 0; i < size; ++i) { mParameters[i] = coefficients[i]; if (coefficients[i] != (Real)0) { hasNonzero = true; } } return hasNonzero; } std::vector<int32_t> mXDegrees, mYDegrees; std::vector<Real> mParameters; // Support for evaluation. The coefficients were generated for the // samples mapped to [-1,1]^3. The Evaluate() function must // transform (x,y) to (x',y') in [-1,1]^2, compute w' in [-1,1], then // transform w' to w. std::array<Real, 2> mXDomain, mYDomain, mWDomain; std::array<Real, 3> mScale; Real mInvTwoWScale; // This array is used by Evaluate() to avoid reallocation of the // 'vector's for each call. The members are mutable because, to the // user, the call to Evaluate does not modify the polynomial. mutable std::vector<Real> mXPowers, mYPowers; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRectangle3OrientedBox3.h
.h
2,865
80
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistRectangle3CanonicalBox3.h> #include <Mathematics/OrientedBox.h> // Compute the distance between a rectangle and a solid oriented box in 3D. // // The rectangle has center C, unit-length axis directions W[0] and W[1], and // extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i] // where |s[i]| <= e[i] for all i. // // The oriented box has center C, unit-length axis directions U[i] and extents // e[i] for all i. A box point is X = C + sum_i y[i] * U[i], where // |y[i]| <= e[i] for all i. // // The closest point on the rectangle is stored in closest[0] with // W-coordinates (s[0],s[1]). The closest point on the box is stored in // closest[1]. When there are infinitely many choices for the pair of closest // points, only one of them is returned. // // TODO: Modify to support non-unit-length W[]. namespace gte { template <typename T> class DCPQuery<T, Rectangle3<T>, OrientedBox3<T>> { public: using RBQuery = DCPQuery<T, Rectangle3<T>, CanonicalBox3<T>>; using Result = typename RBQuery::Result; Result operator()(Rectangle3<T> const& rectangle, OrientedBox3<T> const& box) { Result result{}; // Rotate and translate the rectangle and box so that the box is // aligned and has center at the origin. CanonicalBox3<T> cbox(box.extent); Vector3<T> delta = rectangle.center - box.center; Vector3<T> xfrmCenter{}; std::array<Vector3<T>, 2> xfrmAxis{}; for (int32_t i = 0; i < 3; ++i) { xfrmCenter[i] = Dot(box.axis[i], delta); for (size_t j = 0; j < 2; ++j) { xfrmAxis[j][i] = Dot(box.axis[i], rectangle.axis[j]); } } // The query computes 'output' relative to the box with center // at the origin. Rectangle3<T> xfrmRectangle(xfrmCenter, xfrmAxis, rectangle.extent); RBQuery rbQuery{}; result = rbQuery(xfrmRectangle, cbox); // Rotate and translate the closest points to the original // coordinates. std::array<Vector3<T>, 2> closest{ box.center, box.center }; for (size_t i = 0; i < 2; ++i) { for (int32_t j = 0; j < 3; ++j) { closest[i] += result.closest[i][j] * box.axis[j]; } } result.closest = closest; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TriangulateEC.h
.h
49,368
1,242
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/PolygonTree.h> #include <Mathematics/PrimalQuery2.h> #include <memory> #include <map> #include <queue> #include <vector> // Triangulate polygons using ear clipping. The algorithm is described in // https://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf // The algorithm for processing nested polygons involves a division, so the // ComputeType must be rational-based, say, BSRational. If you process only // triangles that are simple, you may use BSNumber for the ComputeType. namespace gte { template <typename InputType, typename ComputeType> class TriangulateEC { public: // The fundamental problem is to compute the triangulation of a // polygon tree. The outer polygons have counterclockwise ordered // vertices. The inner polygons have clockwise ordered vertices. typedef std::vector<int32_t> Polygon; // The class is a functor to support triangulating multiple polygons // that share vertices in a collection of points. The interpretation // of 'numPoints' and 'points' is described before each operator() // function. Preconditions are numPoints >= 3 and points is a nonnull // pointer to an array of at least numPoints elements. If the // preconditions are satisfied, then operator() functions will return // 'true'; otherwise, they return 'false'. TriangulateEC(int32_t numPoints, Vector2<InputType> const* points) : mNumPoints(numPoints), mPoints(points), mCFirst(-1), mCLast(-1), mRFirst(-1), mRLast(-1), mEFirst(-1), mELast(-1) { LogAssert(numPoints >= 3 && points != nullptr, "Invalid input."); mComputePoints.resize(mNumPoints); mIsConverted.resize(mNumPoints); std::fill(mIsConverted.begin(), mIsConverted.end(), false); mQuery.Set(mNumPoints, &mComputePoints[0]); } TriangulateEC(std::vector<Vector2<InputType>> const& points) : mNumPoints(static_cast<int32_t>(points.size())), mPoints(points.data()), mCFirst(-1), mCLast(-1), mRFirst(-1), mRLast(-1), mEFirst(-1), mELast(-1) { LogAssert(mNumPoints >= 3 && mPoints != nullptr, "Invalid input."); mComputePoints.resize(mNumPoints); mIsConverted.resize(mNumPoints); std::fill(mIsConverted.begin(), mIsConverted.end(), false); mQuery.Set(mNumPoints, &mComputePoints[0]); } // Access the triangulation after each operator() call. inline std::vector<std::array<int32_t, 3>> const& GetTriangles() const { return mTriangles; } // The input 'points' represents an array of vertices for a simple // polygon. The vertices are points[0] through points[numPoints-1] and // are listed in counterclockwise order. bool operator()() { mTriangles.clear(); if (mPoints) { // Compute the points for the queries. for (int32_t i = 0; i < mNumPoints; ++i) { if (!mIsConverted[i]) { mIsConverted[i] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[i][j] = mPoints[i][j]; } } } // Triangulate the unindexed polygon. InitializeVertices(mNumPoints, nullptr); DoEarClipping(mNumPoints, nullptr); return true; } else { return false; } } // The input 'points' represents an array of vertices that contains // the vertices of a simple polygon. bool operator()(Polygon const& polygon) { mTriangles.clear(); if (mPoints) { // Compute the points for the queries. int32_t const numIndices = static_cast<int32_t>(polygon.size()); int32_t const* indices = polygon.data(); for (int32_t i = 0; i < numIndices; ++i) { int32_t index = indices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } // Triangulate the indexed polygon. InitializeVertices(numIndices, indices); DoEarClipping(numIndices, indices); return true; } else { return false; } } // The input 'points' is a shared array of vertices that contains the // vertices for two simple polygons, an outer polygon and an inner // polygon. The inner polygon must be strictly inside the outer // polygon. bool operator()(Polygon const& outer, Polygon const& inner) { mTriangles.clear(); if (mPoints) { // Two extra elements are needed to duplicate the endpoints of // the edge introduced to combine outer and inner polygons. int32_t numPointsPlusExtras = mNumPoints + 2; if (numPointsPlusExtras > static_cast<int32_t>(mComputePoints.size())) { mComputePoints.resize(numPointsPlusExtras); mIsConverted.resize(numPointsPlusExtras); mIsConverted[mNumPoints] = false; mIsConverted[static_cast<size_t>(mNumPoints) + 1] = false; mQuery.Set(numPointsPlusExtras, &mComputePoints[0]); } // Convert any points that have not been encountered in other // triangulation calls. int32_t const numOuterIndices = static_cast<int32_t>(outer.size()); int32_t const* outerIndices = outer.data(); for (int32_t i = 0; i < numOuterIndices; ++i) { int32_t index = outerIndices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } int32_t const numInnerIndices = static_cast<int32_t>(inner.size()); int32_t const* innerIndices = inner.data(); for (int32_t i = 0; i < numInnerIndices; ++i) { int32_t index = innerIndices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } // Combine the outer polygon and the inner polygon into a // simple polygon by inserting two edges connecting mutually // visible vertices, one from the outer polygon and one from // the inner polygon. int32_t nextElement = mNumPoints; // The next available element. std::map<int32_t, int32_t> indexMap; std::vector<int32_t> combined; if (!CombinePolygons(nextElement, outer, inner, indexMap, combined)) { // An unexpected condition was encountered. return false; } // The combined polygon is now in the format of a simple // polygon, albeit one with coincident edges. int32_t numVertices = static_cast<int32_t>(combined.size()); int32_t* const indices = &combined[0]; InitializeVertices(numVertices, indices); DoEarClipping(numVertices, indices); // Map the duplicate indices back to the original indices. RemapIndices(indexMap); return true; } else { return false; } } // The input 'points' is a shared array of vertices that contains the // vertices for multiple simple polygons, an outer polygon and one or // more inner polygons. The inner polygons must be nonoverlapping and // strictly inside the outer polygon. bool operator()(Polygon const& outer, std::vector<Polygon> const& inners) { mTriangles.clear(); if (mPoints) { // Two extra elements per inner polygon are needed to // duplicate the endpoints of the edges introduced to combine // outer and inner polygons. int32_t numPointsPlusExtras = mNumPoints + 2 * (int32_t)inners.size(); if (numPointsPlusExtras > static_cast<int32_t>(mComputePoints.size())) { mComputePoints.resize(numPointsPlusExtras); mIsConverted.resize(numPointsPlusExtras); for (int32_t i = mNumPoints; i < numPointsPlusExtras; ++i) { mIsConverted[i] = false; } mQuery.Set(numPointsPlusExtras, &mComputePoints[0]); } // Convert any points that have not been encountered in other // triangulation calls. int32_t const numOuterIndices = static_cast<int32_t>(outer.size()); int32_t const* outerIndices = outer.data(); for (int32_t i = 0; i < numOuterIndices; ++i) { int32_t index = outerIndices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } for (auto const& inner : inners) { int32_t const numInnerIndices = static_cast<int32_t>(inner.size()); int32_t const* innerIndices = inner.data(); for (int32_t i = 0; i < numInnerIndices; ++i) { int32_t index = innerIndices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } } // Combine the outer polygon and the inner polygons into a // simple polygon by inserting two edges per inner polygon // connecting mutually visible vertices. int32_t nextElement = mNumPoints; // The next available element. std::map<int32_t, int32_t> indexMap; std::vector<int32_t> combined; if (!ProcessOuterAndInners(nextElement, outer, inners, indexMap, combined)) { // An unexpected condition was encountered. return false; } // The combined polygon is now in the format of a simple // polygon, albeit with coincident edges. int32_t numVertices = static_cast<int32_t>(combined.size()); int32_t* const indices = &combined[0]; InitializeVertices(numVertices, indices); DoEarClipping(numVertices, indices); // Map the duplicate indices back to the original indices. RemapIndices(indexMap); return true; } else { return false; } } // The input 'positions' is a shared array of vertices that contains // the vertices for multiple simple polygons in a tree of polygons. bool operator()(std::shared_ptr<PolygonTree> const& tree) { mTriangles.clear(); if (mPoints) { // Two extra elements per inner polygon are needed to // duplicate the endpoints of the edges introduced to combine // outer and inner polygons. int32_t numPointsPlusExtras = mNumPoints + InitializeFromTree(tree); if (numPointsPlusExtras > static_cast<int32_t>(mComputePoints.size())) { mComputePoints.resize(numPointsPlusExtras); mIsConverted.resize(numPointsPlusExtras); for (int32_t i = mNumPoints; i < numPointsPlusExtras; ++i) { mIsConverted[i] = false; } mQuery.Set(numPointsPlusExtras, &mComputePoints[0]); } int32_t nextElement = mNumPoints; std::map<int32_t, int32_t> indexMap; std::queue<std::shared_ptr<PolygonTree>> treeQueue; treeQueue.push(tree); while (treeQueue.size() > 0) { std::shared_ptr<PolygonTree> outer = treeQueue.front(); treeQueue.pop(); int32_t numChildren = static_cast<int32_t>(outer->child.size()); int32_t numVertices; int32_t const* indices; if (numChildren == 0) { // The outer polygon is a simple polygon (no nested // inner polygons). Triangulate the simple polygon. numVertices = static_cast<int32_t>(outer->polygon.size()); indices = outer->polygon.data(); InitializeVertices(numVertices, indices); DoEarClipping(numVertices, indices); } else { // Place the next level of outer polygon nodes on the // queue for triangulation. std::vector<Polygon> inners(numChildren); for (int32_t c = 0; c < numChildren; ++c) { std::shared_ptr<PolygonTree> inner = outer->child[c]; inners[c] = inner->polygon; int32_t numGrandChildren = static_cast<int32_t>(inner->child.size()); for (int32_t g = 0; g < numGrandChildren; ++g) { treeQueue.push(inner->child[g]); } } // Combine the outer polygon and the inner polygons // into a simple polygon by inserting two edges per // inner polygon connecting mutually visible vertices. std::vector<int32_t> combined; ProcessOuterAndInners(nextElement, outer->polygon, inners, indexMap, combined); // The combined polygon is now in the format of a // simple polygon, albeit with coincident edges. numVertices = static_cast<int32_t>(combined.size()); indices = &combined[0]; InitializeVertices(numVertices, indices); DoEarClipping(numVertices, indices); } } // Map the duplicate indices back to the original indices. RemapIndices(indexMap); return true; } else { return false; } } private: // Create the vertex objects that store the various lists required by // the ear-clipping algorithm. void InitializeVertices(int32_t numVertices, int32_t const* indices) { mVertices.clear(); mVertices.resize(numVertices); mCFirst = -1; mCLast = -1; mRFirst = -1; mRLast = -1; mEFirst = -1; mELast = -1; // Create a circular list of the polygon vertices for dynamic // removal of vertices. int32_t numVerticesM1 = numVertices - 1; for (int32_t i = 0; i <= numVerticesM1; ++i) { Vertex& vertex = V(i); vertex.index = (indices ? indices[i] : i); vertex.vPrev = (i > 0 ? i - 1 : numVerticesM1); vertex.vNext = (i < numVerticesM1 ? i + 1 : 0); } // Create a circular list of the polygon vertices for dynamic // removal of vertices. Keep track of two linear sublists, one // for the convex vertices and one for the reflex vertices. // This is an O(N) process where N is the number of polygon // vertices. for (int32_t i = 0; i <= numVerticesM1; ++i) { if (IsConvex(i)) { InsertAfterC(i); } else { InsertAfterR(i); } } } // Apply ear clipping to the input polygon. Polygons with holes are // preprocessed to obtain an index array that is nearly a simple // polygon. This outer polygon has a pair of coincident edges per // inner polygon. void DoEarClipping(int32_t numVertices, int32_t const* indices) { // If the polygon is convex, just create a triangle fan. if (mRFirst == -1) { int32_t numVerticesM1 = numVertices - 1; if (indices) { for (int32_t i = 1; i < numVerticesM1; ++i) { mTriangles.push_back( { indices[0], indices[i], indices[i + 1] } ); } } else { for (int32_t i = 1; i < numVerticesM1; ++i) { mTriangles.push_back( { 0, i, i + 1 } ); } } return; } // Identify the ears and build a circular list of them. Let V0, // V1, and V2 be consecutive vertices forming a triangle T. The // vertex V1 is an ear if no other vertices of the polygon lie // inside T. Although it is enough to show that V1 is not an ear // by finding at least one other vertex inside T, it is sufficient // to search only the reflex vertices. This is an O(C*R) process, // where C is the number of convex vertices and R is the number of // reflex vertices with N = C+R. The order is O(N^2), for example // when C = R = N/2. for (int32_t i = mCFirst; i != -1; i = V(i).sNext) { if (IsEar(i)) { InsertEndE(i); } } V(mEFirst).ePrev = mELast; V(mELast).eNext = mEFirst; // Remove the ears, one at a time. bool bRemoveAnEar = true; while (bRemoveAnEar) { // Add the triangle with the ear to the output list of // triangles. int32_t iVPrev = V(mEFirst).vPrev; int32_t iVNext = V(mEFirst).vNext; mTriangles.push_back( { V(iVPrev).index, V(mEFirst).index, V(iVNext).index } ); // Remove the vertex corresponding to the ear. RemoveV(mEFirst); if (--numVertices == 3) { // Only one triangle remains, just remove the ear and // copy it. mEFirst = RemoveE(mEFirst); iVPrev = V(mEFirst).vPrev; iVNext = V(mEFirst).vNext; mTriangles.push_back( { V(iVPrev).index, V(mEFirst).index, V(iVNext).index } ); bRemoveAnEar = false; continue; } // Removal of the ear can cause an adjacent vertex to become // an ear or to stop being an ear. Vertex& vPrev = V(iVPrev); if (vPrev.isEar) { if (!IsEar(iVPrev)) { RemoveE(iVPrev); } } else { bool wasReflex = !vPrev.isConvex; if (IsConvex(iVPrev)) { if (wasReflex) { RemoveR(iVPrev); } if (IsEar(iVPrev)) { InsertBeforeE(iVPrev); } } } Vertex& vNext = V(iVNext); if (vNext.isEar) { if (!IsEar(iVNext)) { RemoveE(iVNext); } } else { bool wasReflex = !vNext.isConvex; if (IsConvex(iVNext)) { if (wasReflex) { RemoveR(iVNext); } if (IsEar(iVNext)) { InsertAfterE(iVNext); } } } // Remove the ear. mEFirst = RemoveE(mEFirst); } } // Given an outer polygon that contains an inner polygon, this // function determines a pair of visible vertices and inserts two // coincident edges to generate a nearly simple polygon. bool CombinePolygons(int32_t nextElement, Polygon const& outer, Polygon const& inner, std::map<int32_t, int32_t>& indexMap, std::vector<int32_t>& combined) { int32_t const numOuterIndices = static_cast<int32_t>(outer.size()); int32_t const* outerIndices = outer.data(); int32_t const numInnerIndices = static_cast<int32_t>(inner.size()); int32_t const* innerIndices = inner.data(); // Locate the inner-polygon vertex of maximum x-value, call this // vertex M. ComputeType xmax = mComputePoints[innerIndices[0]][0]; int32_t xmaxIndex = 0; for (int32_t i = 1; i < numInnerIndices; ++i) { ComputeType x = mComputePoints[innerIndices[i]][0]; if (x > xmax) { xmax = x; xmaxIndex = i; } } Vector2<ComputeType> M = mComputePoints[innerIndices[xmaxIndex]]; // Find the edge whose intersection Intr with the ray M+t*(1,0) // minimizes // the ray parameter t >= 0. ComputeType const cmax = static_cast<ComputeType>(std::numeric_limits<InputType>::max()); ComputeType const zero = static_cast<ComputeType>(0); Vector2<ComputeType> intr{ cmax, M[1] }; int32_t v0min = -1, v1min = -1, endMin = -1; int32_t i0, i1; ComputeType s = cmax; ComputeType t = cmax; for (i0 = numOuterIndices - 1, i1 = 0; i1 < numOuterIndices; i0 = i1++) { // Consider only edges for which the first vertex is below // (or on) the ray and the second vertex is above (or on) // the ray. Vector2<ComputeType> diff0 = mComputePoints[outerIndices[i0]] - M; if (diff0[1] > zero) { continue; } Vector2<ComputeType> diff1 = mComputePoints[outerIndices[i1]] - M; if (diff1[1] < zero) { continue; } // At this time, diff0.y <= 0 and diff1.y >= 0. int32_t currentEndMin = -1; if (diff0[1] < zero) { if (diff1[1] > zero) { // The intersection of the edge and ray occurs at an // interior edge point. s = diff0[1] / (diff0[1] - diff1[1]); t = diff0[0] + s * (diff1[0] - diff0[0]); } else // diff1.y == 0 { // The vertex Outer[i1] is the intersection of the // edge and the ray. t = diff1[0]; currentEndMin = i1; } } else // diff0.y == 0 { if (diff1[1] > zero) { // The vertex Outer[i0] is the intersection of the // edge and the ray; t = diff0[0]; currentEndMin = i0; } else // diff1.y == 0 { if (diff0[0] < diff1[0]) { t = diff0[0]; currentEndMin = i0; } else { t = diff1[0]; currentEndMin = i1; } } } if (zero <= t && t < intr[0]) { intr[0] = t; v0min = i0; v1min = i1; if (currentEndMin == -1) { // The current closest point is an edge-interior // point. endMin = -1; } else { // The current closest point is a vertex. endMin = currentEndMin; } } else if (t == intr[0]) { // The current closest point is a vertex shared by // multiple edges; thus, endMin and currentMin refer to // the same point. LogAssert(endMin != -1 && currentEndMin != -1, "Unexpected condition."); // We need to select the edge closest to M. The previous // closest edge is <outer[v0min],outer[v1min]>. The // current candidate is <outer[i0],outer[i1]>. Vector2<ComputeType> shared = mComputePoints[outerIndices[i1]]; // For the previous closest edge, endMin refers to a // vertex of the edge. Get the index of the other vertex. int32_t other = (endMin == v0min ? v1min : v0min); // The new edge is closer if the other vertex of the old // edge is left-of the new edge. diff0 = mComputePoints[outerIndices[i0]] - shared; diff1 = mComputePoints[outerIndices[other]] - shared; ComputeType dotperp = DotPerp(diff0, diff1); if (dotperp > zero) { // The new edge is closer to M. v0min = i0; v1min = i1; endMin = currentEndMin; } } } // The intersection intr[0] stored only the t-value of the ray. // The actual point is (mx,my)+t*(1,0), so intr[0] must be // adjusted. intr[0] += M[0]; int32_t maxCosIndex; if (endMin == -1) { // If you reach this assert, there is a good chance that you // have two inner polygons that share a vertex or an edge. LogAssert(v0min >= 0 && v1min >= 0, "Is this an invalid nested polygon?"); // Select one of Outer[v0min] and Outer[v1min] that has an // x-value larger than M.x, call this vertex P. The triangle // <M,I,P> must contain an outer-polygon vertex that is // visible to M, which is possibly P itself. Vector2<ComputeType> sTriangle[3]; // <P,M,I> or <P,I,M> int32_t pIndex; if (mComputePoints[outerIndices[v0min]][0] > mComputePoints[outerIndices[v1min]][0]) { sTriangle[0] = mComputePoints[outerIndices[v0min]]; sTriangle[1] = intr; sTriangle[2] = M; pIndex = v0min; } else { sTriangle[0] = mComputePoints[outerIndices[v1min]]; sTriangle[1] = M; sTriangle[2] = intr; pIndex = v1min; } // If any outer-polygon vertices other than P are inside the // triangle <M,I,P>, then at least one of these vertices must // be a reflex vertex. It is sufficient to locate the reflex // vertex R (if any) in <M,I,P> that minimizes the angle // between R-M and (1,0). The data member mQuery is used for // the reflex query. Vector2<ComputeType> diff = sTriangle[0] - M; ComputeType maxSqrLen = Dot(diff, diff); ComputeType maxCos = diff[0] * diff[0] / maxSqrLen; PrimalQuery2<ComputeType> localQuery(3, sTriangle); maxCosIndex = pIndex; for (int32_t i = 0; i < numOuterIndices; ++i) { if (i == pIndex) { continue; } int32_t curr = outerIndices[i]; int32_t prev = outerIndices[(i + numOuterIndices - 1) % numOuterIndices]; int32_t next = outerIndices[(i + 1) % numOuterIndices]; if (mQuery.ToLine(curr, prev, next) <= 0 && localQuery.ToTriangle(mComputePoints[curr], 0, 1, 2) <= 0) { // The vertex is reflex and inside the <M,I,P> // triangle. diff = mComputePoints[curr] - M; ComputeType sqrLen = Dot(diff, diff); ComputeType cs = diff[0] * diff[0] / sqrLen; if (cs > maxCos) { // The reflex vertex forms a smaller angle with // the positive x-axis, so it becomes the new // visible candidate. maxSqrLen = sqrLen; maxCos = cs; maxCosIndex = i; } else if (cs == maxCos && sqrLen < maxSqrLen) { // The reflex vertex has angle equal to the // current minimum but the length is smaller, so // it becomes the new visible candidate. maxSqrLen = sqrLen; maxCosIndex = i; } } } } else { maxCosIndex = endMin; } // The visible vertices are Position[Inner[xmaxIndex]] and // Position[Outer[maxCosIndex]]. Two coincident edges with // these endpoints are inserted to connect the outer and inner // polygons into a simple polygon. Each of the two Position[] // values must be duplicated, because the original might be // convex (or reflex) and the duplicate is reflex (or convex). // The ear-clipping algorithm needs to distinguish between them. combined.resize(static_cast<size_t>(numOuterIndices) + static_cast<size_t>(numInnerIndices) + 2); int32_t cIndex = 0; for (int32_t i = 0; i <= maxCosIndex; ++i, ++cIndex) { combined[cIndex] = outerIndices[i]; } for (int32_t i = 0; i < numInnerIndices; ++i, ++cIndex) { int32_t j = (xmaxIndex + i) % numInnerIndices; combined[cIndex] = innerIndices[j]; } int32_t innerIndex = innerIndices[xmaxIndex]; mComputePoints[nextElement] = mComputePoints[innerIndex]; combined[cIndex] = nextElement; auto iter = indexMap.find(innerIndex); if (iter != indexMap.end()) { innerIndex = iter->second; } indexMap[nextElement] = innerIndex; ++cIndex; ++nextElement; int32_t outerIndex = outerIndices[maxCosIndex]; mComputePoints[nextElement] = mComputePoints[outerIndex]; combined[cIndex] = nextElement; iter = indexMap.find(outerIndex); if (iter != indexMap.end()) { outerIndex = iter->second; } indexMap[nextElement] = outerIndex; ++cIndex; ++nextElement; for (int32_t i = maxCosIndex + 1; i < numOuterIndices; ++i, ++cIndex) { combined[cIndex] = outerIndices[i]; } return true; } // Given an outer polygon that contains a set of nonoverlapping inner // polygons, this function determines pairs of visible vertices and // inserts coincident edges to generate a nearly simple polygon. It // repeatedly calls CombinePolygons for each inner polygon of the // outer polygon. bool ProcessOuterAndInners(int32_t& nextElement, Polygon const& outer, std::vector<Polygon> const& inners, std::map<int32_t, int32_t>& indexMap, std::vector<int32_t>& combined) { // Sort the inner polygons based on maximum x-values. int32_t numInners = static_cast<int32_t>(inners.size()); std::vector<std::pair<ComputeType, int32_t>> pairs(numInners); for (int32_t p = 0; p < numInners; ++p) { int32_t numIndices = static_cast<int32_t>(inners[p].size()); int32_t const* indices = inners[p].data(); ComputeType xmax = mComputePoints[indices[0]][0]; for (int32_t j = 1; j < numIndices; ++j) { ComputeType x = mComputePoints[indices[j]][0]; if (x > xmax) { xmax = x; } } pairs[p].first = xmax; pairs[p].second = p; } std::sort(pairs.begin(), pairs.end()); // Merge the inner polygons with the outer polygon. Polygon currentPolygon = outer; for (int32_t p = numInners - 1; p >= 0; --p) { Polygon const& polygon = inners[pairs[p].second]; Polygon currentCombined; if (!CombinePolygons(nextElement, currentPolygon, polygon, indexMap, currentCombined)) { return false; } currentPolygon = std::move(currentCombined); nextElement += 2; } for (auto index : currentPolygon) { combined.push_back(index); } return true; } // The insertion of coincident edges to obtain a nearly simple polygon // requires duplication of vertices in order that the ear-clipping // algorithm work correctly. After the triangulation, the indices of // the duplicated vertices are converted to the original indices. void RemapIndices(std::map<int32_t, int32_t> const& indexMap) { // The triangulation includes indices to the duplicated outer and // inner vertices. These indices must be mapped back to the // original ones. for (auto& tri : mTriangles) { for (int32_t i = 0; i < 3; ++i) { auto iter = indexMap.find(tri[i]); if (iter != indexMap.end()) { tri[i] = iter->second; } } } } // Two extra elements are needed in the position array per // outer-inners polygon. This function computes the total number of // extra elements needed for the input tree and it converts InputType // vertices to ComputeType values. int32_t InitializeFromTree(std::shared_ptr<PolygonTree> const& tree) { // Use a breadth-first search to process the outer-inners pairs // of the tree of nested polygons. int32_t numExtraPoints = 0; std::queue<std::shared_ptr<PolygonTree>> treeQueue; treeQueue.push(tree); while (treeQueue.size() > 0) { // The 'root' is an outer polygon. std::shared_ptr<PolygonTree> outer = treeQueue.front(); treeQueue.pop(); // Count number of extra points for this outer-inners pair. int32_t numChildren = static_cast<int32_t>(outer->child.size()); numExtraPoints += 2 * numChildren; // Convert outer points from InputType to ComputeType. int32_t const numOuterIndices = static_cast<int32_t>(outer->polygon.size()); int32_t const* outerIndices = outer->polygon.data(); for (int32_t i = 0; i < numOuterIndices; ++i) { int32_t index = outerIndices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } // The grandchildren of the outer polygon are also outer // polygons. Insert them into the queue for processing. for (int32_t c = 0; c < numChildren; ++c) { // The 'child' is an inner polygon. std::shared_ptr<PolygonTree> inner = outer->child[c]; // Convert inner points from InputType to ComputeType. int32_t const numInnerIndices = static_cast<int32_t>(inner->polygon.size()); int32_t const* innerIndices = inner->polygon.data(); for (int32_t i = 0; i < numInnerIndices; ++i) { int32_t index = innerIndices[i]; if (!mIsConverted[index]) { mIsConverted[index] = true; for (int32_t j = 0; j < 2; ++j) { mComputePoints[index][j] = mPoints[index][j]; } } } int32_t numGrandChildren = static_cast<int32_t>(inner->child.size()); for (int32_t g = 0; g < numGrandChildren; ++g) { treeQueue.push(inner->child[g]); } } } return numExtraPoints; } // The input polygon. int32_t mNumPoints; Vector2<InputType> const* mPoints; // The output triangulation. std::vector<std::array<int32_t, 3>> mTriangles; // The array of points used for geometric queries. If you want to be // certain of a correct result, choose ComputeType to be BSNumber. // The InputType points are convertex to ComputeType points on demand; // the mIsConverted array keeps track of which input points have been // converted. std::vector<Vector2<ComputeType>> mComputePoints; std::vector<bool> mIsConverted; PrimalQuery2<ComputeType> mQuery; // Doubly linked lists for storing specially tagged vertices. class Vertex { public: Vertex() : index(-1), vPrev(-1), vNext(-1), sPrev(-1), sNext(-1), ePrev(-1), eNext(-1), isConvex(false), isEar(false) { } int32_t index; // index of vertex in position array int32_t vPrev, vNext; // vertex links for polygon int32_t sPrev, sNext; // convex/reflex vertex links (disjoint lists) int32_t ePrev, eNext; // ear links bool isConvex, isEar; }; inline Vertex& V(int32_t i) { LogAssert(0 <= i && i < static_cast<int32_t>(mVertices.size()), "Index out of range. Do you have coincident vertex-edge or edge-edge? These violate the assumptions for the algorithm."); return mVertices[i]; } bool IsConvex(int32_t i) { Vertex& vertex = V(i); int32_t curr = vertex.index; int32_t prev = V(vertex.vPrev).index; int32_t next = V(vertex.vNext).index; vertex.isConvex = (mQuery.ToLine(curr, prev, next) > 0); return vertex.isConvex; } bool IsEar(int32_t i) { Vertex& vertex = V(i); if (mRFirst == -1) { // The remaining polygon is convex. vertex.isEar = true; return true; } // Search the reflex vertices and test if any are in the triangle // <V[prev],V[curr],V[next]>. int32_t prev = V(vertex.vPrev).index; int32_t curr = vertex.index; int32_t next = V(vertex.vNext).index; vertex.isEar = true; for (int32_t j = mRFirst; j != -1; j = V(j).sNext) { // Check if the test vertex is already one of the triangle // vertices. if (j == vertex.vPrev || j == i || j == vertex.vNext) { continue; } // V[j] has been ruled out as one of the original vertices of // the triangle <V[prev],V[curr],V[next]>. When triangulating // polygons with holes, V[j] might be a duplicated vertex, in // which case it does not affect the earness of V[curr]. int32_t test = V(j).index; if (mComputePoints[test] == mComputePoints[prev] || mComputePoints[test] == mComputePoints[curr] || mComputePoints[test] == mComputePoints[next]) { continue; } // Test if the vertex is inside or on the triangle. When it // is, it causes V[curr] not to be an ear. if (mQuery.ToTriangle(test, prev, curr, next) <= 0) { vertex.isEar = false; break; } } return vertex.isEar; } // insert convex vertex void InsertAfterC(int32_t i) { if (mCFirst == -1) { // Add the first convex vertex. mCFirst = i; } else { V(mCLast).sNext = i; V(i).sPrev = mCLast; } mCLast = i; } // insert reflex vertesx void InsertAfterR(int32_t i) { if (mRFirst == -1) { // Add the first reflex vertex. mRFirst = i; } else { V(mRLast).sNext = i; V(i).sPrev = mRLast; } mRLast = i; } // insert ear at end of list void InsertEndE(int32_t i) { if (mEFirst == -1) { // Add the first ear. mEFirst = i; mELast = i; } V(mELast).eNext = i; V(i).ePrev = mELast; mELast = i; } // insert ear after efirst void InsertAfterE(int32_t i) { Vertex& first = V(mEFirst); int32_t currENext = first.eNext; Vertex& vertex = V(i); vertex.ePrev = mEFirst; vertex.eNext = currENext; first.eNext = i; V(currENext).ePrev = i; } // insert ear before efirst void InsertBeforeE(int32_t i) { Vertex& first = V(mEFirst); int32_t currEPrev = first.ePrev; Vertex& vertex = V(i); vertex.ePrev = currEPrev; vertex.eNext = mEFirst; first.ePrev = i; V(currEPrev).eNext = i; } // remove vertex void RemoveV(int32_t i) { int32_t currVPrev = V(i).vPrev; int32_t currVNext = V(i).vNext; V(currVPrev).vNext = currVNext; V(currVNext).vPrev = currVPrev; } // remove ear at i int32_t RemoveE(int32_t i) { int32_t currEPrev = V(i).ePrev; int32_t currENext = V(i).eNext; V(currEPrev).eNext = currENext; V(currENext).ePrev = currEPrev; return currENext; } // remove reflex vertex void RemoveR(int32_t i) { LogAssert(mRFirst != -1 && mRLast != -1, "Reflex vertices must exist."); if (i == mRFirst) { mRFirst = V(i).sNext; if (mRFirst != -1) { V(mRFirst).sPrev = -1; } V(i).sNext = -1; } else if (i == mRLast) { mRLast = V(i).sPrev; if (mRLast != -1) { V(mRLast).sNext = -1; } V(i).sPrev = -1; } else { int32_t currSPrev = V(i).sPrev; int32_t currSNext = V(i).sNext; V(currSPrev).sNext = currSNext; V(currSNext).sPrev = currSPrev; V(i).sNext = -1; V(i).sPrev = -1; } } // The doubly linked list. std::vector<Vertex> mVertices; int32_t mCFirst, mCLast; // linear list of convex vertices int32_t mRFirst, mRLast; // linear list of reflex vertices int32_t mEFirst, mELast; // cyclical list of ears }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Array4.h
.h
5,561
188
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstddef> #include <cstdint> #include <vector> // The Array4 class represents a 4-dimensional array that minimizes the number // of new and delete calls. The T objects are stored in a contiguous array. namespace gte { template <typename T> class Array4 { public: // Construction. The first constructor generates an array of objects // that are owned by Array4. The second constructor is given an array // of objects that are owned by the caller. The array has bound0 // columns, bound1 rows, bound2 slices, and bound3 cuboids. Array4(size_t bound0, size_t bound1, size_t bound2, size_t bound3) : mBound0(bound0), mBound1(bound1), mBound2(bound2), mBound3(bound3), mObjects(bound0 * bound1 * bound2 * bound3), mIndirect1(bound1 * bound2 * bound3), mIndirect2(bound2 * bound3), mIndirect3(bound3) { SetPointers(mObjects.data()); } Array4(size_t bound0, size_t bound1, size_t bound2, size_t bound3, T* objects) : mBound0(bound0), mBound1(bound1), mBound2(bound2), mBound3(bound3), mIndirect1(bound1 * bound2 * bound3), mIndirect2(bound2 * bound3), mIndirect3(bound3) { SetPointers(objects); } // Support for dynamic resizing, copying, or moving. If 'other' does // not own the original 'objects', they are not copied by the // assignment operator. Array4() : mBound0(0), mBound1(0), mBound2(0), mBound3(0) { } Array4(Array4 const& other) : mBound0(other.mBound0), mBound1(other.mBound1), mBound2(other.mBound2), mBound3(other.mBound3) { *this = other; } Array4& operator=(Array4 const& other) { // The copy is valid whether or not other.mObjects has elements. mObjects = other.mObjects; SetPointers(other); return *this; } Array4(Array4&& other) noexcept : mBound0(other.mBound0), mBound1(other.mBound1), mBound2(other.mBound2), mBound3(other.mBound3) { *this = std::move(other); } Array4& operator=(Array4&& other) noexcept { // The move is valid whether or not other.mObjects has elements. mObjects = std::move(other.mObjects); SetPointers(other); return *this; } // Access to the array. Sample usage is // Array4<T> myArray(5, 4, 3, 2); // T*** cuboid1 = myArray[1]; // T** cuboid1Slice2 = myArray[1][2]; // T* cuboid1Slice2Row3 = myArray[1][2][3]; // T cuboid1Slice2Row3Col4 = myArray[1][2][3][4]; inline size_t GetBound0() const { return mBound0; } inline size_t GetBound1() const { return mBound1; } inline size_t GetBound2() const { return mBound2; } inline size_t GetBound3() const { return mBound3; } inline T** const* operator[](int32_t cuboid) const { return mIndirect3[cuboid]; } inline T*** operator[](int32_t cuboid) { return mIndirect3[cuboid]; } private: void SetPointers(T* objects) { for (size_t i3 = 0; i3 < mBound3; ++i3) { size_t j2 = mBound2 * i3; // = bound2*(i3 + j3) where j3 = 0 mIndirect3[i3] = &mIndirect2[j2]; for (size_t i2 = 0; i2 < mBound2; ++i2) { size_t j1 = mBound1 * (i2 + j2); mIndirect3[i3][i2] = &mIndirect1[j1]; for (size_t i1 = 0; i1 < mBound1; ++i1) { size_t j0 = mBound0 * (i1 + j1); mIndirect3[i3][i2][i1] = &objects[j0]; } } } } void SetPointers(Array4 const& other) { mBound0 = other.mBound0; mBound1 = other.mBound1; mBound2 = other.mBound2; mBound3 = other.mBound3; mIndirect1.resize(mBound1 * mBound2 * mBound3); mIndirect2.resize(mBound2 * mBound3); mIndirect3.resize(mBound3); if (mBound0 > 0) { // The objects are owned. SetPointers(mObjects.data()); } else if (mIndirect1.size() > 0) { // The objects are not owned. SetPointers(other.mIndirect3[0][0][0]); } // else 'other' is an empty Array3. } size_t mBound0, mBound1, mBound2, mBound3; std::vector<T> mObjects; std::vector<T*> mIndirect1; std::vector<T**> mIndirect2; std::vector<T***> mIndirect3; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment3Cylinder3.h
.h
3,055
90
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine3Cylinder3.h> #include <Mathematics/Segment.h> // The queries consider the cylinder to be a solid. namespace gte { template <typename T> class FIQuery<T, Segment3<T>, Cylinder3<T>> : public FIQuery<T, Line3<T>, Cylinder3<T>> { public: struct Result : public FIQuery<T, Line3<T>, Cylinder3<T>>::Result { Result() : FIQuery<T, Line3<T>, Cylinder3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment3<T> const& segment, Cylinder3<T> const& cylinder) { Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, cylinder, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = segOrigin + result.parameter[i] * segDirection; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& segOrigin, Vector3<T> const& segDirection, T segExtent, Cylinder3<T> const& cylinder, Result& result) { FIQuery<T, Line3<T>, Cylinder3<T>>::DoQuery( segOrigin, segDirection, cylinder, result); if (result.intersect) { // The line containing the segment intersects the cylinder; // the t-interval is [t0,t1]. The segment intersects the // cylinder as long as [t0,t1] overlaps the segment t-interval // [-segExtent,+segExtent]. FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; std::array<T, 2> segInterval = { -segExtent, segExtent }; auto iiResult = iiQuery(result.parameter, segInterval); if (iiResult.intersect) { result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } else { // The line containing the segment does not intersect // the cylinder. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3Ellipsoid3.h
.h
4,761
140
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/Line.h> #include <Mathematics/Matrix3x3.h> // The queries consider the ellipsoid to be a solid. // // The ellipsoid is (X-C)^T*M*(X-C)-1 = 0 and the line is X = P+t*D. // Substitute the line equation into the ellipsoid equation to obtain a // quadratic equation Q(t) = a2*t^2 + 2*a1*t + a0 = 0, where a2 = D^T*M*D, // a1 = D^T*M*(P-C) and a0 = (P-C)^T*M*(P-C)-1. The algorithm involves an // analysis of the real-valued roots of Q(t) for all real t. namespace gte { template <typename T> class TIQuery<T, Line3<T>, Ellipsoid3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Line3<T> const& line, Ellipsoid3<T> const& ellipsoid) { Result result{}; Matrix3x3<T> M{}; ellipsoid.GetM(M); Vector3<T> diff = line.origin - ellipsoid.center; Vector3<T> matDir = M * line.direction; Vector3<T> matDiff = M * diff; T a2 = Dot(line.direction, matDir); T a1 = Dot(line.direction, matDiff); T a0 = Dot(diff, matDiff) - static_cast<T>(1); // An intersection occurs when Q(t) has real roots. T discr = a1 * a1 - a0 * a2; result.intersect = (discr >= static_cast<T>(0)); return result; } }; template <typename T> class FIQuery<T, Line3<T>, Ellipsoid3<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } bool intersect; size_t numIntersections; std::array<T, 2> parameter; std::array<Vector3<T>, 2> point; }; Result operator()(Line3<T> const& line, Ellipsoid3<T> const& ellipsoid) { Result result{}; DoQuery(line.origin, line.direction, ellipsoid, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& lineOrigin, Vector3<T> const& lineDirection, Ellipsoid3<T> const& ellipsoid, Result& result) { Matrix3x3<T> M{}; ellipsoid.GetM(M); Vector3<T> diff = lineOrigin - ellipsoid.center; Vector3<T> matDir = M * lineDirection; Vector3<T> matDiff = M * diff; T a2 = Dot(lineDirection, matDir); T a1 = Dot(lineDirection, matDiff); T a0 = Dot(diff, matDiff) - static_cast<T>(1); // Intersection occurs when Q(t) has real roots. T const zero = static_cast<T>(0); T discr = a1 * a1 - a0 * a2; if (discr > zero) { // The line intersects the ellipsoid in 2 distinct points. result.intersect = true; result.numIntersections = 2; T root = std::sqrt(discr); result.parameter[0] = (-a1 - root) / a2; result.parameter[1] = (-a1 + root) / a2; } else if (discr == zero) { // The line is tangent to the ellipsoid, so the intersection // is a single point. The parameter[1] value is set, because // callers will access the degenerate interval // [-a1/a2, -a1/a2]. result.intersect = true; result.numIntersections = 1; result.parameter[0] = -a1 / a2; result.parameter[1] = result.parameter[0]; } // else: The line is outside the ellipsoid, no intersection. } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprCylinder3.h
.h
30,445
764
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Cylinder3.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/SymmetricEigensolver3x3.h> #include <Mathematics/ApprCircle2.h> #include <cstdint> #include <vector> #include <thread> // The algorithm for least-squares fitting of a point set by a cylinder is // described in // https://www.geometrictools.com/Documentation/CylinderFitting.pdf // This document shows how to compute the cylinder radius r and the cylinder // axis as a line C + h * W with origin C, unit-length direction W, and any // real-valued h. The implementation here adds one addition step. It // projects the point set onto the cylinder axis, computes the bounding // h-interval [hmin, hmax] for the projections and sets the cylinder center // to C + ((hmin + hmax) / 2) * W and the cylinder height to hmax - hmin. // // TODO: ApprCylinder3 needs to be redesigned in GTL to have at most a // single constructor but multiple operator()(...) functions, one per // ConstructorType. namespace gte { template <typename T> class ApprCylinder3 { public: // Search the hemisphere for a minimum, choose numThetaSamples and // numPhiSamples to be positive (and preferably large). These are // used to generate a hemispherical grid of samples to be evaluated // to find the cylinder axis-direction W. If the grid samples is // quite large and the number of points to be fitted is large, you // most likely will want to run multithreaded. Set numThreads to 0 // to run single-threaded in the main process. Set numThreads > 0 to // run multithreaded. // // Set fitPoints to 'true' to use the algorithm described in the // aforementioned PDF file. Set fitPoints to 'false' if you want to // fit a cylinder to a triangle mesh. TODO: The PDF needs to be // updated to describe the new algorithm. The description is in this // file, before the second operator()(...) implementation. ApprCylinder3(size_t numThreads, size_t numThetaSamples, size_t numPhiSamples, bool fitPoints = true) : mConstructorType(fitPoints ? ConstructorType::FIT_BY_HEMISPHERE_SEARCH : ConstructorType::FIT_TO_MESH), mNumThreads(numThreads), mNumThetaSamples(numThetaSamples), mNumPhiSamples(numPhiSamples), mEigenIndex(0), mCylinderAxis{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, mX{}, mMu{}, mF0{}, mF1{}, mF2{} { } // Choose one of the eigenvectors for the covariance matrix as the // cylinder axis direction. If eigenIndex is 0, the eigenvector // associated with the smallest eigenvalue is chosen. If eigenIndex // is 2, the eigenvector associated with the largest eigenvalue is // chosen. If eigenIndex is 1, the eigenvector associated with the // median eigenvalue is chosen; keep in mind that this could be the // minimum or maximum eigenvalue if the eigenspace has dimension 2 // or 3. ApprCylinder3(size_t eigenIndex) : mConstructorType(ConstructorType::FIT_USING_COVARIANCE_EIGENVECTOR), mNumThreads(0), mNumThetaSamples(0), mNumPhiSamples(0), mEigenIndex(eigenIndex), mCylinderAxis{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, mX{}, mMu{}, mF0{}, mF1{}, mF2{} { } // Choose the cylinder axis. If cylinderAxis is not the zero vector, // the constructor will normalize it. ApprCylinder3(Vector3<T> const& cylinderAxis) : mConstructorType(ConstructorType::FIT_USING_SPECIFIED_AXIS), mNumThreads(0), mNumThetaSamples(0), mNumPhiSamples(0), mEigenIndex(0), mCylinderAxis(cylinderAxis), mX{}, mMu{}, mF0{}, mF1{}, mF2{} { Normalize(mCylinderAxis, true); } // The algorithm must estimate 6 parameters, so the number of points // must be at least 6 but preferably larger. The returned value is // the root-mean-square of the least-squares error. T operator()(size_t numPoints, Vector3<T> const* points, Cylinder3<T>& cylinder) { LogAssert( mConstructorType != ConstructorType::FIT_TO_MESH, "Call operator()(numPoints, points, triangles, cylinder) for fitting to a mesh."); LogAssert( numPoints >= 6 && points != nullptr, "Fitting requires at least 6 points."); T const zero = static_cast<T>(0); mX.clear(); cylinder.axis.origin = { zero, zero, zero }; cylinder.axis.direction = { zero, zero, zero }; cylinder.radius = zero; cylinder.height = zero; Vector3<T> average{ zero, zero, zero }; Preprocess(numPoints, points, average); // Fit the points based on which constructor the caller used. The // direction is either estimated or selected directly or // indirectly by the caller. The center and squared radius are // estimated. Vector3<T> minPC{}, minW{}; T minRSqr = zero, minError = zero; if (mConstructorType == ConstructorType::FIT_BY_HEMISPHERE_SEARCH) { LogAssert( mNumThetaSamples > 0 && mNumPhiSamples > 0, "The number of theta and psi samples must be positive."); // Search the hemisphere for the vector that leads to minimum // error and use it for the cylinder axis. if (mNumThreads == 0) { // Execute the algorithm in the main process. minError = ComputeSingleThreaded(minPC, minW, minRSqr); } else { // Execute the algorithm in multiple threads. minError = ComputeMultiThreaded(minPC, minW, minRSqr); } } else if (mConstructorType == ConstructorType::FIT_USING_COVARIANCE_EIGENVECTOR) { LogAssert( mEigenIndex < 3, "Eigenvector index is out of range."); // Use the eigenvector corresponding to the mEigenIndex of the // eigenvectors of the covariance matrix as the cylinder axis // direction. The eigenvectors are sorted from smallest // eigenvalue (mEigenIndex = 0) to largest eigenvalue // (mEigenIndex = 2). minError = ComputeUsingCovariance(minPC, minW, minRSqr); } else // mConstructorType == ApprCylinder3<T>::FIT_USING_SPECIFIED_AXIS { LogAssert( mCylinderAxis != Vector3<T>::Zero(), "The cylinder axis must be nonzero."); minError = ComputeUsingDirection(minPC, minW, minRSqr); } // Translate back to the original space by the average of the // points. cylinder.axis.origin = minPC + average; cylinder.axis.direction = minW; // Compute the cylinder radius. cylinder.radius = std::sqrt(minRSqr); // Project the points onto the cylinder axis and choose the // cylinder center and cylinder height as described in the // comments at the top of this header file. T hmin = zero, hmax = zero; for (size_t i = 0; i < numPoints; ++i) { T h = Dot(cylinder.axis.direction, points[i] - cylinder.axis.origin); hmin = std::min(h, hmin); hmax = std::max(h, hmax); } T hmid = static_cast<T>(0.5) * (hmin + hmax); cylinder.axis.origin += hmid * cylinder.axis.direction; cylinder.height = hmax - hmin; return minError; } // Use this operator for fitting a cylinder to a mesh. For each // candidate cone axis direction on the hemisphere, project the // triangles onto a plane perpendicular to the axis. Compute the // sum of 2*area for the projected triangles. The direction that // minimizes this measurement is used as the cone axis direction. // The projected points for this direction are fit with a circle // whose center is used to generate the cylinder center and whose // radius is used for the cylinder radius. The projection of the // points onto the axis are used to determine the minimum and // maximum coordinates along the axis, which are then used to // compute the cone height. The cone center is adjusted to be // midway between the minimum and maximum coordinates along the axis. void operator()(size_t numPoints, Vector3<T> const* points, size_t numTriangles, int32_t const* indices, Cylinder3<T>& cylinder) { LogAssert( mConstructorType == ConstructorType::FIT_TO_MESH, "Call operator()(numPoints, points, cylinder) for fitting to points."); LogAssert( numPoints >= 6 && points != nullptr && numTriangles >= 2 && indices != nullptr, "Fitting requires at least 6 points and 2 triangles."); T const zero = static_cast<T>(0); mX.clear(); cylinder.axis.origin = { zero, zero, zero }; cylinder.axis.direction = { zero, zero, zero }; cylinder.radius = zero; cylinder.height = zero; // Translate the points by translating their average to the // origin. This helps with numerical stability. mX.resize(numPoints); Vector3<T> average{ zero, zero, zero }; for (size_t i = 0; i < numPoints; ++i) { average += points[i]; } average /= static_cast<T>(numPoints); for (size_t i = 0; i < numPoints; ++i) { mX[i] = points[i] - average; } // Search the hemisphere for the vector that leads to minimum // error and use it for the cylinder axis. if (mNumThreads == 0) { // Execute the algorithm in the main process. FitToMeshSingleThreaded(numPoints, mX.data(), numTriangles, indices, cylinder); } else { // Execute the algorithm in multiple threads. FitToMeshMultiThreaded(numPoints, mX.data(), numTriangles, indices, cylinder); } // Translate to the original coordinate system. cylinder.axis.origin += average; } private: enum class ConstructorType { FIT_BY_HEMISPHERE_SEARCH, FIT_USING_COVARIANCE_EIGENVECTOR, FIT_USING_SPECIFIED_AXIS, FIT_TO_MESH }; void Preprocess(size_t numPoints, Vector3<T> const* points, Vector3<T>& average) { // Copy the points and translate by the average for numerical // robustness. mX.resize(numPoints); T rNumPoints = static_cast<T>(numPoints); average.MakeZero(); for (size_t i = 0; i < numPoints; ++i) { average += points[i]; } average /= rNumPoints; for (size_t i = 0; i < numPoints; ++i) { mX[i] = points[i] - average; } T const zero = static_cast<T>(0); T const two = static_cast<T>(2); Vector<6, T> vzero{ zero, zero, zero, zero, zero, zero }; std::vector<Vector<6, T>> products(mX.size(), vzero); mMu = vzero; for (size_t i = 0; i < mX.size(); ++i) { products[i][0] = mX[i][0] * mX[i][0]; products[i][1] = mX[i][0] * mX[i][1]; products[i][2] = mX[i][0] * mX[i][2]; products[i][3] = mX[i][1] * mX[i][1]; products[i][4] = mX[i][1] * mX[i][2]; products[i][5] = mX[i][2] * mX[i][2]; mMu[0] += products[i][0]; mMu[1] += two * products[i][1]; mMu[2] += two * products[i][2]; mMu[3] += products[i][3]; mMu[4] += two * products[i][4]; mMu[5] += products[i][5]; } mMu /= rNumPoints; mF0.MakeZero(); mF1.MakeZero(); mF2.MakeZero(); for (size_t i = 0; i < mX.size(); ++i) { Vector<6, T> delta{}; delta[0] = products[i][0] - mMu[0]; delta[1] = two * products[i][1] - mMu[1]; delta[2] = two * products[i][2] - mMu[2]; delta[3] = products[i][3] - mMu[3]; delta[4] = two * products[i][4] - mMu[4]; delta[5] = products[i][5] - mMu[5]; mF0(0, 0) += products[i][0]; mF0(0, 1) += products[i][1]; mF0(0, 2) += products[i][2]; mF0(1, 1) += products[i][3]; mF0(1, 2) += products[i][4]; mF0(2, 2) += products[i][5]; mF1 += OuterProduct(mX[i], delta); mF2 += OuterProduct(delta, delta); } mF0 /= rNumPoints; mF0(1, 0) = mF0(0, 1); mF0(2, 0) = mF0(0, 2); mF0(2, 1) = mF0(1, 2); mF1 /= rNumPoints; mF2 /= rNumPoints; } T ComputeUsingDirection(Vector3<T>& minPC, Vector3<T>& minW, T& minRSqr) { minW = mCylinderAxis; return G(minW, minPC, minRSqr); } T ComputeUsingCovariance(Vector3<T>& minPC, Vector3<T>& minW, T& minRSqr) { Matrix3x3<T> covar{}; // zero matrix for (auto const& X : mX) { covar += OuterProduct(X, X); } covar /= static_cast<T>(mX.size()); std::array<T, 3> eval{}; std::array<std::array<T, 3>, 3> evec{}; SymmetricEigensolver3x3<T>()( covar(0, 0), covar(0, 1), covar(0, 2), covar(1, 1), covar(1, 2), covar(2, 2), true, +1, eval, evec); minW = evec[mEigenIndex]; return G(minW, minPC, minRSqr); } T ComputeSingleThreaded(Vector3<T>& minPC, Vector3<T>& minW, T& minRSqr) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const iMultiplier = static_cast<T>(GTE_C_TWO_PI) / static_cast<T>(mNumThetaSamples); T const jMultiplier = static_cast<T>(GTE_C_HALF_PI) / static_cast<T>(mNumPhiSamples); // Handle the north pole (0,0,1) separately. minW = { zero, zero, one }; T minError = G(minW, minPC, minRSqr); for (size_t j = 1; j <= mNumPhiSamples; ++j) { T phi = jMultiplier * static_cast<T>(j); // in [0,pi/2] T csphi = std::cos(phi); T snphi = std::sin(phi); for (size_t i = 0; i < mNumThetaSamples; ++i) { T theta = iMultiplier * static_cast<T>(i); // in [0,2*pi) T cstheta = std::cos(theta); T sntheta = std::sin(theta); Vector3<T> W{ cstheta * snphi, sntheta * snphi, csphi }; Vector3<T> PC{}; T rsqr; T error = G(W, PC, rsqr); if (error < minError) { minError = error; minRSqr = rsqr; minW = W; minPC = PC; } } } return minError; } T ComputeMultiThreaded(Vector3<T>& minPC, Vector3<T>& minW, T& minRSqr) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const iMultiplier = static_cast<T>(GTE_C_TWO_PI) / static_cast<T>(mNumThetaSamples); T const jMultiplier = static_cast<T>(GTE_C_HALF_PI) / static_cast<T>(mNumPhiSamples); // Handle the north pole (0,0,1) separately. minW = { zero, zero, one }; T minError = G(minW, minPC, minRSqr); struct Local { Local() : error(std::numeric_limits<T>::max()), rsqr(static_cast<T>(0)), W{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, PC{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, jmin(0), jmax(0) { } T error; T rsqr; Vector3<T> W; Vector3<T> PC; size_t jmin; size_t jmax; }; std::vector<Local> local(mNumThreads); size_t numPhiSamplesPerThread = mNumPhiSamples / mNumThreads; for (size_t t = 0; t < mNumThreads; ++t) { local[t].jmin = numPhiSamplesPerThread * t; local[t].jmax = numPhiSamplesPerThread * (t + 1); } local[mNumThreads - 1].jmax = mNumPhiSamples + 1; std::vector<std::thread> process(mNumThreads); for (size_t t = 0; t < mNumThreads; ++t) { process[t] = std::thread ( [this, t, iMultiplier, jMultiplier, &local]() { for (size_t j = local[t].jmin; j < local[t].jmax; ++j) { // phi in [0,pi/2] T phi = jMultiplier * static_cast<T>(j); T csphi = std::cos(phi); T snphi = std::sin(phi); for (size_t i = 0; i < mNumThetaSamples; ++i) { // theta in [0,2*pi) T theta = iMultiplier * static_cast<T>(i); T cstheta = std::cos(theta); T sntheta = std::sin(theta); Vector3<T> W{ cstheta * snphi, sntheta * snphi, csphi }; Vector3<T> PC{}; T rsqr; T error = G(W, PC, rsqr); if (error < local[t].error) { local[t].error = error; local[t].rsqr = rsqr; local[t].W = W; local[t].PC = PC; } } } } ); } for (size_t t = 0; t < mNumThreads; ++t) { process[t].join(); if (local[t].error < minError) { minError = local[t].error; minRSqr = local[t].rsqr; minW = local[t].W; minPC = local[t].PC; } } return minError; } T G(Vector3<T> const& W, Vector3<T>& PC, T& rsqr) { T const zero = static_cast<T>(0); T const four = static_cast<T>(4); Matrix3x3<T> P = Matrix3x3<T>::Identity() - OuterProduct(W, W); Matrix3x3<T> S { zero, -W[2], W[1], W[2], zero, -W[0], -W[1], W[0], zero }; Matrix<3, 3, T> A = P * mF0 * P; Matrix<3, 3, T> hatA = -(S * A * S); Matrix<3, 3, T> hatAA = hatA * A; T trace = Trace(hatAA); Matrix<3, 3, T> Q = hatA / trace; Vector<6, T> pVec{ P(0, 0), P(0, 1), P(0, 2), P(1, 1), P(1, 2), P(2, 2) }; Vector<3, T> alpha = mF1 * pVec; Vector<3, T> beta = Q * alpha; T term0 = Dot(pVec, mF2 * pVec); T term1 = four * Dot(alpha, beta); T term2 = four * Dot(beta, mF0 * beta); T gValue = (term0 - term1 + term2) / static_cast<T>(mX.size()); PC = beta; rsqr = Dot(pVec, mMu) + Dot(PC, PC); return gValue; } void FitToMeshSingleThreaded(size_t numPoints, Vector3<T> const* points, size_t numTriangles, int32_t const* indices, Cylinder3<T>& cylinder) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const iMultiplier = static_cast<T>(GTE_C_TWO_PI) / static_cast<T>(mNumThetaSamples); T const jMultiplier = static_cast<T>(GTE_C_HALF_PI) / static_cast<T>(mNumPhiSamples); // Handle the north pole (0,0,1) separately. Vector3<T> minDirection{ zero, zero, one }; T minMeasure = GetProjectionMeasure(minDirection, numPoints, points, numTriangles, indices); // Process a regular grid of (theta,phi) angles. for (size_t j = 1; j <= mNumPhiSamples; ++j) { T phi = jMultiplier * static_cast<T>(j); // in [0,pi/2] T csphi = std::cos(phi); T snphi = std::sin(phi); for (size_t i = 0; i < mNumThetaSamples; ++i) { T theta = iMultiplier * static_cast<T>(i); // in [0,2*pi) T cstheta = std::cos(theta); T sntheta = std::sin(theta); Vector3<T> direction { cstheta * snphi, sntheta * snphi, csphi }; T measure = GetProjectionMeasure(direction, numPoints, points, numTriangles, indices); if (measure < minMeasure) { minDirection = direction; minMeasure = measure; } } } FinishCylinder(minDirection, numPoints, points, cylinder); } void FitToMeshMultiThreaded(size_t numPoints, Vector3<T> const* points, size_t numTriangles, int32_t const* indices, Cylinder3<T>& cylinder) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const iMultiplier = static_cast<T>(GTE_C_TWO_PI) / static_cast<T>(mNumThetaSamples); T const jMultiplier = static_cast<T>(GTE_C_HALF_PI) / static_cast<T>(mNumPhiSamples); // Handle the north pole (0,0,1) separately. Vector3<T> minDirection{ zero, zero, one }; T minMeasure = GetProjectionMeasure(minDirection, numPoints, points, numTriangles, indices); struct Local { Local() : direction{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, measure{ std::numeric_limits<T>::max() }, jmin(0), jmax(0) { } Vector3<T> direction; T measure; size_t jmin; size_t jmax; }; std::vector<Local> local(mNumThreads); size_t numPhiSamplesPerThread = mNumPhiSamples / mNumThreads; for (size_t t = 0; t < mNumThreads; ++t) { local[t].jmin = numPhiSamplesPerThread * t; local[t].jmax = numPhiSamplesPerThread * (t + 1); } local[mNumThreads - 1].jmax = mNumPhiSamples + 1; std::vector<std::thread> process(mNumThreads); for (size_t t = 0; t < mNumThreads; ++t) { process[t] = std::thread ( [this, t, iMultiplier, jMultiplier, &local, numPoints, points, numTriangles, indices]() { for (size_t j = local[t].jmin; j < local[t].jmax; ++j) { // phi in [0,pi/2] T phi = jMultiplier * static_cast<T>(j); T csphi = std::cos(phi); T snphi = std::sin(phi); for (size_t i = 0; i < mNumThetaSamples; ++i) { // theta in [0,2*pi) T theta = iMultiplier * static_cast<T>(i); T cstheta = std::cos(theta); T sntheta = std::sin(theta); Vector3<T> direction { cstheta * snphi, sntheta * snphi, csphi }; T measure = GetProjectionMeasure(direction, numPoints, points, numTriangles, indices); if (measure < local[t].measure) { local[t].direction = direction; local[t].measure = measure; } } } } ); } for (size_t t = 0; t < mNumThreads; ++t) { process[t].join(); if (local[t].measure < minMeasure) { minMeasure = local[t].measure; minDirection = local[t].direction; } } FinishCylinder(minDirection, numPoints, points, cylinder); } T GetProjectionMeasure(Vector3<T> const& direction, size_t numPoints, Vector3<T> const* points, size_t numTriangles, int32_t const* indices) { std::array<Vector3<T>, 3> basis{}; basis[0] = direction; ComputeOrthogonalComplement(1, basis.data()); std::vector<Vector2<T>> projections(numPoints); for (size_t i = 0; i < numPoints; ++i) { projections[i][0] = Dot(basis[1], points[i]); projections[i][1] = Dot(basis[2], points[i]); } // Add up 2*area of the triangles. T measure = static_cast<T>(0); for (size_t t = 0; t < numTriangles; ++t) { auto const& V0 = projections[*indices++]; auto const& V1 = projections[*indices++]; auto const& V2 = projections[*indices++]; auto edge10 = V1 - V0; auto edge20 = V2 - V0; measure += std::fabs(DotPerp(edge10, edge20)); } return measure; } void FinishCylinder(Vector3<T> const& minDirection, size_t numPoints, Vector3<T> const* points, Cylinder3<T>& cylinder) { std::array<Vector3<T>, 3> basis{}; basis[0] = minDirection; ComputeOrthogonalComplement(1, basis.data()); std::vector<Vector2<T>> projections(numPoints); T hmin = std::numeric_limits<T>::max(); T hmax = static_cast<T>(0); for (size_t i = 0; i < numPoints; ++i) { T h = Dot(basis[0], points[i]); if (h < hmin) { hmin = h; } if (h > hmax) { hmax = h; } projections[i][0] = Dot(basis[1], points[i]); projections[i][1] = Dot(basis[2], points[i]); } ApprCircle2<T> fitter{}; Circle2<T> circle{}; fitter.FitUsingSquaredLengths(static_cast<int32_t>(projections.size()), projections.data(), circle); Vector3<T> minCenter = circle.center[0] * basis[1] + circle.center[1] * basis[2]; cylinder.axis.origin = minCenter + (static_cast<T>(0.5) * (hmax + hmin)) * minDirection; cylinder.axis.direction = minDirection; cylinder.radius = circle.radius; cylinder.height = hmax - hmin; } ConstructorType mConstructorType; // Parameters for the hemisphere-search constructor. size_t mNumThreads; size_t mNumThetaSamples; size_t mNumPhiSamples; // Parameters for the eigenvector-index constructor. size_t mEigenIndex; // Parameters for the specified-axis constructor. Vector3<T> mCylinderAxis; // A copy of the input points but translated by their average for // numerical robustness. std::vector<Vector3<T>> mX; // Preprocessed information that depends only on the sample points. // This allows precomputed summations so that G(...) can be evaluated // extremely fast. Vector<6, T> mMu; Matrix<3, 3, T> mF0; Matrix<3, 6, T> mF1; Matrix<6, 6, T> mF2; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/UIntegerAP32.h
.h
6,595
232
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/UIntegerALU32.h> #include <limits> #include <istream> #include <ostream> #include <vector> // Class UIntegerAP32 is designed to support arbitrary precision arithmetic // using BSNumber and BSRational. It is not a general-purpose class for // arithmetic of unsigned integers. // Uncomment this to collect statistics on how large the UIntegerAP32 storage // becomes when using it for the UInteger of BSNumber. If you use this // feature, you must define gsUIntegerAP32MaxSize somewhere in your code. // After a sequence of BSNumber operations, look at gsUIntegerAP32MaxSize in // the debugger watch window. If the number is not too large, you might be // safe in replacing UIntegerAP32 by UIntegerFP32<N>, where N is the value of // gsUIntegerAP32MaxSize. This leads to much faster code because you no // longer have dynamic memory allocations and deallocations that occur // regularly with std::vector<uint32_t> during BSNumber operations. A safer // choice is to argue mathematically that the maximum size is bounded by N. // This requires an analysis of how many bits of precision you need for the // types of computation you perform. See class BSPrecision for code that // allows you to compute maximum N. // //#define GTE_COLLECT_UINTEGERAP32_STATISTICS #if defined(GTE_COLLECT_UINTEGERAP32_STATISTICS) #include <Mathematics/AtomicMinMax.h> namespace gte { extern std::atomic<size_t> gsUIntegerAP32MaxSize; } #endif namespace gte { class UIntegerAP32 : public UIntegerALU32<UIntegerAP32> { public: // Construction. UIntegerAP32() : mNumBits(0) { } UIntegerAP32(UIntegerAP32 const& number) { *this = number; } UIntegerAP32(uint32_t number) { if (number > 0) { int32_t first = BitHacks::GetLeadingBit(number); int32_t last = BitHacks::GetTrailingBit(number); mNumBits = first - last + 1; mBits.resize(1); mBits[0] = (number >> last); } else { mNumBits = 0; } #if defined(GTE_COLLECT_UINTEGERAP32_STATISTICS) AtomicMax(gsUIntegerAP32MaxSize, mBits.size()); #endif } UIntegerAP32(uint64_t number) { if (number > 0) { int32_t first = BitHacks::GetLeadingBit(number); int32_t last = BitHacks::GetTrailingBit(number); number >>= last; mNumBits = first - last + 1; mBits.resize(static_cast<size_t>(1) + (mNumBits - 1) / 32); mBits[0] = (uint32_t)(number & 0x00000000FFFFFFFFull); if (mBits.size() > 1) { mBits[1] = (uint32_t)((number >> 32) & 0x00000000FFFFFFFFull); } } else { mNumBits = 0; } #if defined(GTE_COLLECT_UINTEGERAP32_STATISTICS) AtomicMax(gsUIntegerAP32MaxSize, mBits.size()); #endif } // Assignment. UIntegerAP32& operator=(UIntegerAP32 const& number) { mNumBits = number.mNumBits; mBits = number.mBits; return *this; } // Support for std::move. UIntegerAP32(UIntegerAP32&& number) noexcept { *this = std::move(number); } UIntegerAP32& operator=(UIntegerAP32&& number) noexcept { mNumBits = number.mNumBits; mBits = std::move(number.mBits); number.mNumBits = 0; return *this; } // Member access. void SetNumBits(int32_t numBits) { if (numBits > 0) { mNumBits = numBits; mBits.resize(static_cast<size_t>(1) + (numBits - 1) / 32); } else if (numBits == 0) { mNumBits = 0; mBits.clear(); } else { LogError("The number of bits must be nonnegative."); } #if defined(GTE_COLLECT_UINTEGERAP32_STATISTICS) AtomicMax(gsUIntegerAP32MaxSize, mBits.size()); #endif } inline int32_t GetNumBits() const { return mNumBits; } inline std::vector<uint32_t> const& GetBits() const { return mBits; } inline std::vector<uint32_t>& GetBits() { return mBits; } inline void SetBack(uint32_t value) { mBits.back() = value; } inline uint32_t GetBack() const { return mBits.back(); } inline int32_t GetSize() const { return static_cast<int32_t>(mBits.size()); } inline static int32_t GetMaxSize() { return std::numeric_limits<int32_t>::max(); } inline void SetAllBitsToZero() { std::fill(mBits.begin(), mBits.end(), 0u); } // Disk input/output. The return value is 'true' iff the operation // was successful. bool Write(std::ostream& output) const { if (output.write((char const*)& mNumBits, sizeof(mNumBits)).bad()) { return false; } std::size_t size = mBits.size(); if (output.write((char const*)& size, sizeof(size)).bad()) { return false; } return output.write((char const*)& mBits[0], size * sizeof(mBits[0])).good(); } bool Read(std::istream& input) { if (input.read((char*)& mNumBits, sizeof(mNumBits)).bad()) { return false; } std::size_t size; if (input.read((char*)& size, sizeof(size)).bad()) { return false; } mBits.resize(size); return input.read((char*)& mBits[0], size * sizeof(mBits[0])).good(); } private: int32_t mNumBits; std::vector<uint32_t> mBits; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLine2OrientedBox2.h
.h
2,506
68
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine2AlignedBox2.h> // Compute the distance between a line and a solid oriented box in 2D. // // The line is P + t * D, where D is not required to be unit length. // // The oriented box has center C, unit-length axis directions U[i] and extents // e[i] for all i. A box point is X = C + sum_i y[i] * U[i], where // |y[i]| <= e[i] for all i. // // The closest point on the line is stored in closest[0] with parameter t. The // closest point on the box is stored in closest[1]. When there are infinitely // many choices for the pair of closest points, only one of them is returned. namespace gte { template <typename T> class DCPQuery<T, Line2<T>, OrientedBox2<T>> { public: using AlignedQuery = DCPQuery<T, Line2<T>, AlignedBox2<T>>; using Result = typename AlignedQuery::Result; Result operator()(Line2<T> const& line, OrientedBox2<T> const& box) { Result result{}; // Rotate and translate the line and box so that the box is // aligned and has center at the origin. Vector2<T> delta = line.origin - box.center; Vector2<T> origin{}, direction{}; for (int32_t i = 0; i < 2; ++i) { origin[i] = Dot(box.axis[i], delta); direction[i] = Dot(box.axis[i], line.direction); } // The query computes 'result' relative to the box with center // at the origin. AlignedQuery::DoQuery(origin, direction, box.extent, result); // Rotate and translate the closest points to the original // coordinates. std::array<Vector2<T>, 2> temp{ result.closest[0], result.closest[1] }; for (size_t i = 0; i < 2; ++i) { result.closest[i] = box.center + temp[i][0] * box.axis[0] + temp[i][1] * box.axis[1]; } // Compute the distance and squared distance. Vector2<T> diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Halfspace.h
.h
2,379
91
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector.h> // The halfspace is represented as Dot(N,X) >= c where N is a unit-length // normal vector, c is the plane constant, and X is any point in space. // The user must ensure that the normal vector is unit length. namespace gte { template <int32_t N, typename Real> class Halfspace { public: // Construction and destruction. The default constructor sets the // normal to (0,...,0,1) and the constant to zero (halfspace // x[N-1] >= 0). Halfspace() : constant((Real)0) { normal.MakeUnit(N - 1); } // Specify N and c directly. Halfspace(Vector<N, Real> const& inNormal, Real inConstant) : normal(inNormal), constant(inConstant) { } // Public member access. Vector<N, Real> normal; Real constant; public: // Comparisons to support sorted containers. bool operator==(Halfspace const& halfspace) const { return normal == halfspace.normal && constant == halfspace.constant; } bool operator!=(Halfspace const& halfspace) const { return !operator==(halfspace); } bool operator< (Halfspace const& halfspace) const { if (normal < halfspace.normal) { return true; } if (normal > halfspace.normal) { return false; } return constant < halfspace.constant; } bool operator<=(Halfspace const& halfspace) const { return !halfspace.operator<(*this); } bool operator> (Halfspace const& halfspace) const { return halfspace.operator<(*this); } bool operator>=(Halfspace const& halfspace) const { return !operator<(halfspace); } }; // Template alias for convenience. template <typename Real> using Halfspace3 = Halfspace<3, Real>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContEllipse2MinCR.h
.h
9,679
226
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Matrix2x2.h> // Compute the minimum-area ellipse, (X-C)^T R D R^T (X-C) = 1, given the // center C and the orientation matrix R. The columns of R are the axes of // the ellipse. The algorithm computes the diagonal matrix D. The minimum // area is pi/sqrt(D[0]*D[1]), where D = diag(D[0],D[1]). The problem is // equivalent to maximizing the product D[0]*D[1] for a given C and R, and // subject to the constraints // (P[i]-C)^T R D R^T (P[i]-C) <= 1 // for all input points P[i] with 0 <= i < N. Each constraint has the form // A[0]*D[0] + A[1]*D[1] <= 1 // where A[0] >= 0 and A[1] >= 0. namespace gte { template <typename Real> class ContEllipse2MinCR { public: void operator()(int32_t numPoints, Vector2<Real> const* points, Vector2<Real> const& C, Matrix2x2<Real> const& R, Real D[2]) const { // Compute the constraint coefficients, of the form (A[0],A[1]) // for each i. std::vector<Vector2<Real>> A(numPoints); for (int32_t i = 0; i < numPoints; ++i) { Vector2<Real> diff = points[i] - C; // P[i] - C Vector2<Real> prod = diff * R; // R^T*(P[i] - C) = (u,v) A[i] = prod * prod; // (u^2, v^2) } // Use a lexicographical sort to eliminate redundant constraints. // Remove all but the first entry in blocks with x0 = x1 because // the corresponding constraint lines for the first entry hides // all the others from the origin. std::sort(A.begin(), A.end(), [](Vector2<Real> const& P0, Vector2<Real> const& P1) { if (P0[0] > P1[0]) { return true; } if (P0[0] < P1[0]) { return false; } return P0[1] > P1[1]; } ); auto end = std::unique(A.begin(), A.end(), [](Vector2<Real> const& P0, Vector2<Real> const& P1) { return P0[0] == P1[0]; } ); A.erase(end, A.end()); // Use a lexicographical sort to eliminate redundant constraints. // Remove all but the first entry in blocks/ with y0 = y1 because // the corresponding constraint lines for the first entry hides // all the others from the origin. std::sort(A.begin(), A.end(), [](Vector2<Real> const& P0, Vector2<Real> const& P1) { if (P0[1] > P1[1]) { return true; } if (P0[1] < P1[1]) { return false; } return P0[0] > P1[0]; } ); end = std::unique(A.begin(), A.end(), [](Vector2<Real> const& P0, Vector2<Real> const& P1) { return P0[1] == P1[1]; } ); A.erase(end, A.end()); MaxProduct(A, D); } private: static void MaxProduct(std::vector<Vector2<Real>>& A, Real D[2]) { // Keep track of which constraint lines have already been used in // the search. int32_t numConstraints = static_cast<int32_t>(A.size()); std::vector<bool> used(A.size()); std::fill(used.begin(), used.end(), false); // Find the constraint line whose y-intercept (0,ymin) is closest // to the origin. This line contributes to the convex hull of the // constraints and the search for the maximum starts here. Also // find the constraint line whose x-intercept (xmin,0) is closest // to the origin. This line contributes to the convex hull of the // constraints and the search for the maximum terminates before or // at this line. int32_t i, iYMin = -1; int32_t iXMin = -1; Real axMax = (Real)0, ayMax = (Real)0; // A[i] >= (0,0) by design for (i = 0; i < numConstraints; ++i) { // The minimum x-intercept is 1/A[iXMin][0] for A[iXMin][0] // the maximum of the A[i][0]. if (A[i][0] > axMax) { axMax = A[i][0]; iXMin = i; } // The minimum y-intercept is 1/A[iYMin][1] for A[iYMin][1] // the maximum of the A[i][1]. if (A[i][1] > ayMax) { ayMax = A[i][1]; iYMin = i; } } LogAssert(iXMin != -1 && iYMin != -1, "Unexpected condition."); used[iYMin] = true; // The convex hull is searched in a clockwise manner starting with // the constraint line constructed above. The next vertex of the // hull occurs as the closest point to the first vertex on the // current constraint line. The following loop finds each // consecutive vertex. Real x0 = (Real)0, xMax = ((Real)1) / axMax; int32_t j; for (j = 0; j < numConstraints; ++j) { // Find the line whose intersection with the current line is // closest to the last hull vertex. The last vertex is at // (x0,y0) on the current line. Real x1 = xMax; int32_t line = -1; for (i = 0; i < numConstraints; ++i) { if (!used[i]) { // This line not yet visited, process it. Given // current constraint line a0*x+b0*y =1 and candidate // line a1*x+b1*y = 1, find the point of intersection. // The determinant of the system is d = a0*b1-a1*b0. // We care only about lines that have more negative // slope than the previous one, that is, // -a1/b1 < -a0/b0, in which case we process only // lines for which d < 0. Real det = DotPerp(A[iYMin], A[i]); if (det < (Real)0) { // Compute the x-value for the point of // intersection, (x1,y1). There may be floating // point error issues in the comparision // 'D[0] <= x1'. Consider modifying to // 'D[0] <= x1 + epsilon'. D[0] = (A[i][1] - A[iYMin][1]) / det; if (x0 < D[0] && D[0] <= x1) { line = i; x1 = D[0]; } } } } // Next vertex is at (x1,y1) whose x-value was computed above. // First check for the maximum of x*y on the current line for // x in [x0,x1]. On this interval the function is // f(x) = x*(1-a0*x)/b0. The derivative is // f'(x) = (1-2*a0*x)/b0 and f'(r) = 0 when r = 1/(2*a0). // The three candidates for the maximum are f(x0), f(r) and // f(x1). Comparisons are made between r and the endpoints // x0 and x1. Because a0 = 0 is possible (constraint line is // horizontal and f is increasing on line), the division in r // is not performed and the comparisons are made between // 1/2 = a0*r and a0*x0 or a0*x1. // Compare r < x0. if ((Real)0.5 < A[iYMin][0] * x0) { // The maximum is f(x0) since the quadratic f decreases // for x > r. The value D[1] is f(x0). D[0] = x0; D[1] = ((Real)1 - A[iYMin][0] * D[0]) / A[iYMin][1]; break; } // Compare r < x1. if ((Real)0.5 < A[iYMin][0] * x1) { // The maximum is f(r). The search ends here because the // current line is tangent to the level curve of // f(x) = f(r) and x*y can therefore only decrease as we // traverse farther around the hull in the clockwise // direction. The value D[1] is f(r). D[0] = (Real)0.5 / A[iYMin][0]; D[1] = (Real)0.5 / A[iYMin][1]; break; } // The maximum is f(x1). The function x*y is potentially // larger on the next line, so continue the search. LogAssert(line != -1, "Unexpected condition."); x0 = x1; x1 = xMax; used[line] = true; iYMin = line; } LogAssert(j < numConstraints, "Unexpected condition."); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprQuadratic2.h
.h
7,904
230
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/Vector2.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/SymmetricEigensolver.h> namespace gte { // The quadratic fit is // 0 = C[0] + C[1]*x + C[2]*y + C[3]*x^2 + C[4]*x*y + C[5]*y^2 // which has one degree of freedom in the coefficients. Eliminate the // degree of freedom by minimizing the quadratic form E(C) = C^T M C // subject to Length(C) = 1 with M = (sum_i V[i])(sum_i V[i])^T where // V = (1, x, y, x^2, x*y, y^2) // The minimum value is the smallest eigenvalue of M and C is a // corresponding unit length eigenvector. // // Input: // n = number of points to fit // P[0..n-1] = array of points to fit // // Output: // C[0..5] = coefficients of quadratic fit (the eigenvector) // return value of function is nonnegative and a measure of the fit // (the minimum eigenvalue; 0 = exact fit, positive otherwise) // // Canonical forms. The quadratic equation can be factored into // P^T A P + B^T P + K = 0 where P = (x,y), K = C[0],B = (C[1],C[2]) // and A is a 2x2 symmetric matrix with A00 = C[3], A01 = C[4]/2 and // A11 = C[5]. Using an eigendecomposition, matrix A = R^T D R where // R is orthogonal and D is diagonal. Define V = R*P = (v0,v1), // E = R*B = (e0,e1), D = diag(d0,d1) and f = K to obtain // d0 v0^2 + d1 v1^2 + e0 v0 + e1 v1 + f = 0 // The classification depends on the signs of the d_i. template <typename Real> class ApprQuadratic2 { public: Real operator()(int32_t numPoints, Vector2<Real> const* points, std::array<Real, 6>& coefficients) { Matrix<6, 6, Real> M{}; // constructor sets M to zero for (int32_t i = 0; i < numPoints; ++i) { Real x = points[i][0]; Real y = points[i][1]; Real x2 = x * x; Real y2 = y * y; Real xy = x * y; Real x3 = x * x2; Real xy2 = x * y2; Real x2y = x * xy; Real y3 = y * y2; Real x4 = x * x3; Real x2y2 = x * xy2; Real x3y = x * x2y; Real y4 = y * y3; Real xy3 = x * y3; // M(0, 0) += 1 M(0, 1) += x; M(0, 2) += y; M(0, 3) += x2; M(0, 4) += xy; M(0, 5) += y2; // M(1, 1) += x2 [M(0,3)] // M(1, 2) += xy [M(0,4)] M(1, 3) += x3; M(1, 4) += x2y; M(1, 5) += xy2; // M(2, 2) += y2 [M(0,5)] // M(2, 3) += x2y [M(1,4)] // M(2, 4) += xy2 [M(1,5)] M(2, 5) += y3; M(3, 3) += x4; M(3, 4) += x3y; M(3, 5) += x2y2; // M(4, 4) += x2y2 [M(3,5)] M(4, 5) += xy3; M(5, 5) += y4; } Real const rNumPoints = static_cast<Real>(numPoints); M(0, 0) = rNumPoints; M(1, 1) = M(0, 3); // x2 M(1, 2) = M(0, 4); // xy M(2, 2) = M(0, 5); // y2 M(2, 3) = M(1, 4); // x2y M(2, 4) = M(1, 5); // xy2 M(4, 4) = M(3, 5); // x2y2 for (int32_t row = 0; row < 6; ++row) { for (int32_t col = 0; col < row; ++col) { M(row, col) = M(col, row); } } for (int32_t row = 0; row < 6; ++row) { for (int32_t col = 0; col < 6; ++col) { M(row, col) /= rNumPoints; } } M(0, 0) = static_cast<Real>(1); SymmetricEigensolver<Real> es(6, 1024); es.Solve(&M[0], +1); es.GetEigenvector(0, coefficients.data()); // For an exact fit, numeric round-off errors might make the // minimum eigenvalue just slightly negative. Return the clamped // value because the application might rely on the return value // being nonnegative. return std::max(es.GetEigenvalue(0), static_cast<Real>(0)); } }; // If you believe your points are nearly circular, use this function. The // circle is of the form // C'[0] + C'[1]*x + C'[2]*y + C'[3]*(x^2 + y^2) = 0 // where Length(C') = 1. The function returns // C = (C'[0] / C'[3], C'[1] / C'[3], C'[2] / C'[3]) // = (C[0], C[1], C[2]) // so the fitted circle is // C[0] + C[1]*x + C[2]*y + x^2 + y^2 = 0 // The center is (xc,yc) = -(C[1],C[2])/2 and the radius is // r = sqrt(xc * xc + yc * yc - C[0]). template <typename Real> class ApprQuadraticCircle2 { public: Real operator()(int32_t numPoints, Vector2<Real> const* points, Circle2<Real>& circle) { Matrix<4, 4, Real> M{}; // constructor sets M to zero for (int32_t i = 0; i < numPoints; ++i) { Real x = points[i][0]; Real y = points[i][1]; Real x2 = x * x; Real y2 = y * y; Real xy = x * y; Real r2 = x2 + y2; Real xr2 = x * r2; Real yr2 = y * r2; Real r4 = r2 * r2; // M(0, 0) += 1 M(0, 1) += x; M(0, 2) += y; M(0, 3) += r2; M(1, 1) += x2; M(1, 2) += xy; M(1, 3) += xr2; M(2, 2) += y2; M(2, 3) += yr2; M(3, 3) += r4; } Real const rNumPoints = static_cast<Real>(numPoints); M(0, 0) = rNumPoints; for (int32_t row = 0; row < 4; ++row) { for (int32_t col = 0; col < row; ++col) { M(row, col) = M(col, row); } } for (int32_t row = 0; row < 4; ++row) { for (int32_t col = 0; col < 4; ++col) { M(row, col) /= rNumPoints; } } M(0, 0) = static_cast<Real>(1); SymmetricEigensolver<Real> es(4, 1024); es.Solve(&M[0], +1); Vector<4, Real> evector{}; es.GetEigenvector(0, &evector[0]); std::array<Real, 3> coefficients{}; for (int32_t row = 0; row < 3; ++row) { coefficients[row] = evector[row] / evector[3]; } // Clamp the radius to nonnegative values in case rounding errors // cause sqrRadius to be slightly negative. Real const negHalf = static_cast<Real>(-0.5); circle.center[0] = negHalf * coefficients[1]; circle.center[1] = negHalf * coefficients[2]; Real sqrRadius = Dot(circle.center, circle.center) - coefficients[0]; circle.radius = std::sqrt(std::max(sqrRadius, static_cast<Real>(0))); // For an exact fit, numeric round-off errors might make the // minimum eigenvalue just slightly negative. Return the clamped // value because the application might rely on the return value // being nonnegative. return std::max(es.GetEigenvalue(0), static_cast<Real>(0)); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment3Sphere3.h
.h
5,757
160
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrIntervals.h> #include <Mathematics/IntrLine3Sphere3.h> #include <Mathematics/Segment.h> // The queries consider the sphere to be a solid. // // The sphere is (X-C)^T*(X-C)-r^2 = 0. The segment has endpoints P0 and P1. // The segment origin (center) is P = (P0+P1)/2, the segment direction is // D = (P1-P0)/|P1-P0| and the segment extent (half the segment length) is // e = |P1-P0|/2. The segment is X = P+t*D for t in [-e,e]. Substitute the // segment equation into the sphere equation to obtain a quadratic equation // Q(t) = t^2 + 2*a1*t + a0 = 0, where a1 = (P1-P0)^T*(P0-C) and // a0 = (P0-C)^T*(P0-C)-r^2. The algorithm involves an analysis of the // real-valued roots of Q(t) for -e <= t <= e. namespace gte { template <typename T> class TIQuery<T, Segment3<T>, Sphere3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Segment3<T> const& segment, Sphere3<T> const& sphere) { Result result{}; Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); T const zero = static_cast<T>(0); Vector3<T> diff = segOrigin - sphere.center; T a0 = Dot(diff, diff) - sphere.radius * sphere.radius; T a1 = Dot(segDirection, diff); T discr = a1 * a1 - a0; if (discr < zero) { // Q(t) has no real-valued roots. The segment does not // intersect the sphere. result.intersect = false; return result; } // Q(-e) = e^2 - 2*a1*e + a0, Q(e) = e^2 + 2*a1*e + a0 T tmp0 = segExtent * segExtent + a0; // e^2 + a0 T tmp1 = static_cast<T>(2) * a1 * segExtent; // 2*a1*e T qm = tmp0 - tmp1; // Q(-e) T qp = tmp0 + tmp1; // Q(e) if (qm * qp <= zero) { // Q(t) has a root on the interval [-e,e]. The segment // intesects the sphere. result.intersect = true; return result; } // Either (Q(-e) > 0 and Q(e) > 0) or (Q(-e) < 0 and Q(e) < 0). // When Q at the endpoints is negative, Q(t) < 0 for all t in // [-e,e] and the segment does not intersect the sphere. // Otherwise, Q(-e) > 0 [and Q(e) > 0]. The minimum of Q(t) // occurs at t = -a1. We know that discr >= 0, so Q(t) has a // root on (-e,e) when -a1 is in (-e,e). The combined test for // intersection is (Q(-e) > 0 and |a1| < e). result.intersect = (qm > zero && std::fabs(a1) < segExtent); return result; } }; template <typename T> class FIQuery<T, Segment3<T>, Sphere3<T>> : public FIQuery<T, Line3<T>, Sphere3<T>> { public: struct Result : public FIQuery<T, Line3<T>, Sphere3<T>>::Result { Result() : FIQuery<T, Line3<T>, Sphere3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment3<T> const& segment, Sphere3<T> const& sphere) { Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, sphere, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = segOrigin + result.parameter[i] * segDirection; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& segOrigin, Vector3<T> const& segDirection, T segExtent, Sphere3<T> const& sphere, Result& result) { FIQuery<T, Line3<T>, Sphere3<T>>::DoQuery( segOrigin, segDirection, sphere, result); if (result.intersect) { // The line containing the segment intersects the sphere; the // t-interval is [t0,t1]. The segment intersects the sphere // as long as [t0,t1] overlaps the segment t-interval // [-segExtent,+segExtent]. FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{}; std::array<T, 2> segInterval = { -segExtent, segExtent }; auto iiResult = iiQuery(result.parameter, segInterval); if (iiResult.intersect) { result.numIntersections = iiResult.numIntersections; result.parameter = iiResult.overlap; } else { // The line containing the segment does not intersect // the sphere. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprPolynomialSpecial4.h
.h
13,572
359
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/GMatrix.h> #include <array> // Fit the data with a polynomial of the form // w = sum_{i=0}^{n-1} c[i]*x^{p[i]}*y^{q[i]}*z^{r[i]} // where <p[i],q[i],r[i]> are distinct triples of nonnegative powers provided // by the caller. A least-squares fitting algorithm is used, but the input // data is first mapped to (x,y,z,w) in [-1,1]^4 for numerical robustness. namespace gte { template <typename Real> class ApprPolynomialSpecial4 : public ApprQuery<Real, std::array<Real, 4>> { public: // Initialize the model parameters to zero. The degrees must be // nonnegative and strictly increasing. ApprPolynomialSpecial4(std::vector<int32_t> const& xDegrees, std::vector<int32_t> const& yDegrees, std::vector<int32_t> const& zDegrees) : mXDegrees(xDegrees), mYDegrees(yDegrees), mZDegrees(zDegrees), mParameters(mXDegrees.size() * mYDegrees.size() * mZDegrees.size(), (Real)0) { #if !defined(GTE_NO_LOGGER) LogAssert(mXDegrees.size() == mYDegrees.size() && mXDegrees.size() == mZDegrees.size(), "The input arrays must have the same size."); LogAssert(mXDegrees.size() > 0, "The input array must have elements."); int32_t lastDegree = -1; for (auto degree : mXDegrees) { LogAssert(degree > lastDegree, "Degrees must be increasing."); lastDegree = degree; } LogAssert(mYDegrees.size() > 0, "The input array must have elements."); lastDegree = -1; for (auto degree : mYDegrees) { LogAssert(degree > lastDegree, "Degrees must be increasing."); lastDegree = degree; } LogAssert(mZDegrees.size() > 0, "The input array must have elements."); lastDegree = -1; for (auto degree : mZDegrees) { LogAssert(degree > lastDegree, "Degrees must be increasing."); lastDegree = degree; } #endif mXDomain[0] = std::numeric_limits<Real>::max(); mXDomain[1] = -mXDomain[0]; mYDomain[0] = std::numeric_limits<Real>::max(); mYDomain[1] = -mYDomain[0]; mZDomain[0] = std::numeric_limits<Real>::max(); mZDomain[1] = -mZDomain[0]; mWDomain[0] = std::numeric_limits<Real>::max(); mWDomain[1] = -mWDomain[0]; mScale[0] = (Real)0; mScale[1] = (Real)0; mScale[2] = (Real)0; mScale[3] = (Real)0; mInvTwoWScale = (Real)0; // Powers of x, y, and z are computed up to twice the powers when // constructing the fitted polynomial. Powers of x, y, and z are // computed up to the powers for the evaluation of the fitted // polynomial. mXPowers.resize(2 * static_cast<size_t>(mXDegrees.back()) + 1); mXPowers[0] = (Real)1; mYPowers.resize(2 * static_cast<size_t>(mYDegrees.back()) + 1); mYPowers[0] = (Real)1; mZPowers.resize(2 * static_cast<size_t>(mZDegrees.back()) + 1); mZPowers[0] = (Real)1; } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numObservations, std::array<Real, 4> const* observations, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numObservations, observations, numIndices, indices)) { // Transform the observations to [-1,1]^4 for numerical // robustness. std::vector<std::array<Real, 4>> transformed; Transform(observations, numIndices, indices, transformed); // Fit the transformed data using a least-squares algorithm. return DoLeastSquares(transformed); } std::fill(mParameters.begin(), mParameters.end(), (Real)0); return false; } // Get the parameters for the best fit. std::vector<Real> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return mParameters.size(); } // Compute the model error for the specified observation for the // current model parameters. The returned value for observation // (x0,y0,z0,w0) is |w(x0,y0,z0) - w0|, where w(x,y,z) is the fitted // polynomial. virtual Real Error(std::array<Real, 4> const& observation) const override { Real w = Evaluate(observation[0], observation[1], observation[2]); Real error = std::fabs(w - observation[3]); return error; } virtual void CopyParameters(ApprQuery<Real, std::array<Real, 4>> const* input) override { auto source = dynamic_cast<ApprPolynomialSpecial4 const*>(input); if (source) { *this = *source; } } // Evaluate the polynomial. The domain interval is provided so you can // interpolate ((x,y,z) in domain) or extrapolate ((x,y,z) not in // domain). std::array<Real, 2> const& GetXDomain() const { return mXDomain; } std::array<Real, 2> const& GetYDomain() const { return mYDomain; } std::array<Real, 2> const& GetZDomain() const { return mZDomain; } Real Evaluate(Real x, Real y, Real z) const { // Transform (x,y,z) to (x',y',z') in [-1,1]^3. x = (Real)-1 + (Real)2 * mScale[0] * (x - mXDomain[0]); y = (Real)-1 + (Real)2 * mScale[1] * (y - mYDomain[0]); z = (Real)-1 + (Real)2 * mScale[2] * (z - mZDomain[0]); // Compute relevant powers of x, y, and z. int32_t jmax = mXDegrees.back(); for (int32_t j = 1, jm1 = 0; j <= jmax; ++j, ++jm1) { mXPowers[j] = mXPowers[jm1] * x; } jmax = mYDegrees.back(); for (int32_t j = 1, jm1 = 0; j <= jmax; ++j, ++jm1) { mYPowers[j] = mYPowers[jm1] * y; } jmax = mZDegrees.back(); for (int32_t j = 1, jm1 = 0; j <= jmax; ++j, ++jm1) { mZPowers[j] = mZPowers[jm1] * z; } Real w = (Real)0; int32_t isup = static_cast<int32_t>(mXDegrees.size()); for (int32_t i = 0; i < isup; ++i) { Real xp = mXPowers[mXDegrees[i]]; Real yp = mYPowers[mYDegrees[i]]; Real zp = mYPowers[mZDegrees[i]]; w += mParameters[i] * xp * yp * zp; } // Transform w from [-1,1] back to the original space. w = (w + (Real)1) * mInvTwoWScale + mWDomain[0]; return w; } private: // Transform the (x,y,z,w) values to (x',y',z',w') in [-1,1]^4. void Transform(std::array<Real, 4> const* observations, size_t numIndices, int32_t const* indices, std::vector<std::array<Real, 4>> & transformed) { int32_t numSamples = static_cast<int32_t>(numIndices); transformed.resize(numSamples); std::array<Real, 4> omin = observations[indices[0]]; std::array<Real, 4> omax = omin; std::array<Real, 4> obs; int32_t s, i; for (s = 1; s < numSamples; ++s) { obs = observations[indices[s]]; for (i = 0; i < 4; ++i) { if (obs[i] < omin[i]) { omin[i] = obs[i]; } else if (obs[i] > omax[i]) { omax[i] = obs[i]; } } } mXDomain[0] = omin[0]; mXDomain[1] = omax[0]; mYDomain[0] = omin[1]; mYDomain[1] = omax[1]; mZDomain[0] = omin[2]; mZDomain[1] = omax[2]; mWDomain[0] = omin[3]; mWDomain[1] = omax[3]; for (i = 0; i < 4; ++i) { mScale[i] = (Real)1 / (omax[i] - omin[i]); } for (s = 0; s < numSamples; ++s) { obs = observations[indices[s]]; for (i = 0; i < 4; ++i) { transformed[s][i] = (Real)-1 + (Real)2 * mScale[i] * (obs[i] - omin[i]); } } mInvTwoWScale = (Real)0.5 / mScale[3]; } // The least-squares fitting algorithm for the transformed data. bool DoLeastSquares(std::vector<std::array<Real, 4>> & transformed) { // Set up a linear system A*X = B, where X are the polynomial // coefficients. int32_t size = static_cast<int32_t>(mXDegrees.size()); GMatrix<Real> A(size, size); A.MakeZero(); GVector<Real> B(size); B.MakeZero(); int32_t numSamples = static_cast<int32_t>(transformed.size()); int32_t twoMaxXDegree = 2 * mXDegrees.back(); int32_t twoMaxYDegree = 2 * mYDegrees.back(); int32_t twoMaxZDegree = 2 * mZDegrees.back(); int32_t row, col; for (int32_t i = 0; i < numSamples; ++i) { // Compute relevant powers of x, y, and z. Real x = transformed[i][0]; Real y = transformed[i][1]; Real z = transformed[i][2]; Real w = transformed[i][3]; for (int32_t j = 1, jm1 = 0; j <= twoMaxXDegree; ++j, ++jm1) { mXPowers[j] = mXPowers[jm1] * x; } for (int32_t j = 1, jm1 = 0; j <= twoMaxYDegree; ++j, ++jm1) { mYPowers[j] = mYPowers[jm1] * y; } for (int32_t j = 1, jm1 = 0; j <= twoMaxZDegree; ++j, ++jm1) { mZPowers[j] = mZPowers[jm1] * z; } for (row = 0; row < size; ++row) { // Update the upper-triangular portion of the symmetric // matrix. Real xp, yp, zp; for (col = row; col < size; ++col) { xp = mXPowers[static_cast<size_t>(mXDegrees[row]) + static_cast<size_t>(mXDegrees[col])]; yp = mYPowers[static_cast<size_t>(mYDegrees[row]) + static_cast<size_t>(mYDegrees[col])]; zp = mZPowers[static_cast<size_t>(mZDegrees[row]) + static_cast<size_t>(mZDegrees[col])]; A(row, col) += xp * yp * zp; } // Update the right-hand side of the system. xp = mXPowers[mXDegrees[row]]; yp = mYPowers[mYDegrees[row]]; zp = mZPowers[mZDegrees[row]]; B[row] += xp * yp * zp * w; } } // Copy the upper-triangular portion of the symmetric matrix to // the lower-triangular portion. for (row = 0; row < size; ++row) { for (col = 0; col < row; ++col) { A(row, col) = A(col, row); } } // Precondition by normalizing the sums. Real invNumSamples = (Real)1 / (Real)numSamples; A *= invNumSamples; B *= invNumSamples; // Solve for the polynomial coefficients. GVector<Real> coefficients = Inverse(A) * B; bool hasNonzero = false; for (int32_t i = 0; i < size; ++i) { mParameters[i] = coefficients[i]; if (coefficients[i] != (Real)0) { hasNonzero = true; } } return hasNonzero; } std::vector<int32_t> mXDegrees, mYDegrees, mZDegrees; std::vector<Real> mParameters; // Support for evaluation. The coefficients were generated for the // samples mapped to [-1,1]^4. The Evaluate() function must transform // (x,y,z) to (x',y',z') in [-1,1]^3, compute w' in [-1,1], then // transform w' to w. std::array<Real, 2> mXDomain, mYDomain, mZDomain, mWDomain; std::array<Real, 4> mScale; Real mInvTwoWScale; // This array is used by Evaluate() to avoid reallocation of the // 'vector's for each call. The members are mutable because, to the // user, the call to Evaluate does not modify the polynomial. mutable std::vector<Real> mXPowers, mYPowers, mZPowers; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3Cone3.h
.h
18,098
482
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector3.h> #include <Mathematics/Cone.h> #include <Mathematics/Line.h> #include <Mathematics/QFNumber.h> #include <Mathematics/IntrIntervals.h> // The queries consider the cone to be single sided and solid. The // cone height range is [hmin,hmax]. The cone can be infinite where // hmin = 0 and hmax = +infinity, infinite truncated where hmin > 0 // and hmax = +infinity, finite where hmin = 0 and hmax < +infinity, // or a cone frustum where hmin > 0 and hmax < +infinity. The // algorithm details are found in // https://www.geometrictools.com/Documentation/IntersectionLineCone.pdf namespace gte { template <typename Real> class FIQuery<Real, Line3<Real>, Cone3<Real>> { public: // The rational quadratic field type with elements x + y * sqrt(d). // This type supports error-free computation. using QFN1 = QFNumber<Real, 1>; // Convenient naming for interval find-intersection queries. using IIQuery = FIIntervalInterval<QFN1>; struct Result { // Because the intersection of line and cone with infinite height // can be a ray or a line, we use a 'type' value that allows you // to decide how to interpret the t[] and P[] values. // No interesection. static int32_t constexpr isEmpty = 0; // t[0] is finite, t[1] is set to t[0], P[0] is the point of // intersection, P[1] is set to P[0]. static int32_t constexpr isPoint = 1; // t[0] and t[1] are finite with t[0] < t[1], P[0] and P[1] are // the endpoints of the segment of intersection. static int32_t constexpr isSegment = 2; // Dot(line.direction, cone.ray.direction) > 0: // t[0] is finite, t[1] is +infinity (set to +1), P[0] is the ray // origin, P[1] is the ray direction (set to line.direction). // NOTE: The ray starts at P[0] and you walk away from it in the // line direction. static int32_t constexpr isRayPositive = 3; // Dot(line.direction, cone.ray.direction) < 0: // t[0] is -infinity (set to -1), t[1] is finite, P[0] is the ray // endpoint, P[1] is the ray direction (set to line.direction). // NOTE: The ray ends at P[1] and you walk towards it in the line // direction. static int32_t constexpr isRayNegative = 4; Result() : intersect(false), type(Result::isEmpty), t{}, P{} { } void ComputePoints(Vector3<Real> const& origin, Vector3<Real> const& direction) { switch (type) { case Result::isEmpty: for (int32_t i = 0; i < 3; ++i) { P[0][i] = QFN1(); P[1][i] = P[0][i]; } break; case Result::isPoint: for (int32_t i = 0; i < 3; ++i) { P[0][i] = origin[i] + direction[i] * t[0]; P[1][i] = P[0][i]; } break; case Result::isSegment: for (int32_t i = 0; i < 3; ++i) { P[0][i] = origin[i] + direction[i] * t[0]; P[1][i] = origin[i] + direction[i] * t[1]; } break; case Result::isRayPositive: for (int32_t i = 0; i < 3; ++i) { P[0][i] = origin[i] + direction[i] * t[0]; P[1][i] = QFN1(direction[i], 0, t[0].d); } break; case Result::isRayNegative: for (int32_t i = 0; i < 3; ++i) { P[0][i] = origin[i] + direction[i] * t[1]; P[1][i] = QFN1(direction[i], 0, t[1].d); } break; default: LogError("Invalid case."); break; } } template <typename OutputType> static void Convert(QFN1 const& input, OutputType& output) { output = static_cast<Real>(input); } template <typename OutputType> static void Convert(Vector3<QFN1> const& input, Vector3<OutputType>& output) { for (int32_t i = 0; i < 3; ++i) { output[i] = static_cast<Real>(input[i]); } } bool intersect; int32_t type; std::array<QFN1, 2> t; std::array<Vector3<QFN1>, 2> P; }; Result operator()(Line3<Real> const& line, Cone3<Real> const& cone) { Result result{}; DoQuery(line.origin, line.direction, cone, result); result.ComputePoints(line.origin, line.direction); result.intersect = (result.type != Result::isEmpty); return result; } protected: // The result.type and result.t[] values are computed by DoQuery. The // result.P[] and result.intersect values are computed from them in // the operator()(...) function. void DoQuery(Vector3<Real> const& lineOrigin, Vector3<Real> const& lineDirection, Cone3<Real> const& cone, Result& result) { // The algorithm implemented in DoQuery avoids extra branches if // we choose a line whose direction forms an acute angle with the // cone direction. if (Dot(lineDirection, cone.ray.direction) >= (Real)0) { DoQuerySpecial(lineOrigin, lineDirection, cone, result); } else { DoQuerySpecial(lineOrigin, -lineDirection, cone, result); result.t[0] = -result.t[0]; result.t[1] = -result.t[1]; std::swap(result.t[0], result.t[1]); if (result.type == Result::isRayPositive) { result.type = Result::isRayNegative; } } } void DoQuerySpecial(Vector3<Real> const& lineOrigin, Vector3<Real> const& lineDirection, Cone3<Real> const& cone, Result& result) { // Compute the number of real-valued roots and represent them // using rational quadratic field elements to support when Real // is an exact rational arithmetic type. TODO: Adjust by noting // that we should use D/|D| because a normalized floating-point // D still might not have |D| = 1 (although it is close to 1). Vector3<Real> PmV = lineOrigin - cone.ray.origin; Real UdU = Dot(lineDirection, lineDirection); Real DdU = Dot(cone.ray.direction, lineDirection); // >= 0 Real DdPmV = Dot(cone.ray.direction, PmV); Real UdPmV = Dot(lineDirection, PmV); Real PmVdPmV = Dot(PmV, PmV); Real c2 = DdU * DdU - cone.cosAngleSqr * UdU; Real c1 = DdU * DdPmV - cone.cosAngleSqr * UdPmV; Real c0 = DdPmV * DdPmV - cone.cosAngleSqr * PmVdPmV; if (c2 != (Real)0) { Real discr = c1 * c1 - c0 * c2; if (discr < (Real)0) { CaseC2NotZeroDiscrNeg(result); } else if (discr > (Real)0) { CaseC2NotZeroDiscrPos(c1, c2, discr, DdU, DdPmV, cone, result); } else // discr == 0 { CaseC2NotZeroDiscrZero(c1, c2, UdU, UdPmV, DdU, DdPmV, cone, result); } } else if (c1 != (Real)0) { CaseC2ZeroC1NotZero(c0, c1, DdU, DdPmV, cone, result); } else { CaseC2ZeroC1Zero(c0, UdU, UdPmV, DdU, DdPmV, cone, result); } } void CaseC2NotZeroDiscrNeg(Result& result) { // Block 0. The quadratic has no real-valued roots. The line does // not intersect the double-sided cone. SetEmpty(result); } void CaseC2NotZeroDiscrPos(Real const& c1, Real const& c2, Real const& discr, Real const& DdU, Real const& DdPmV, Cone3<Real> const& cone, Result& result) { // The quadratic has two distinct real-valued roots, t[0] and t[1] // with t[0] < t[1]. Real x = -c1 / c2; Real y = (c2 > (Real)0 ? (Real)1 / c2 : (Real)-1 / c2); std::array<QFN1, 2> t = { QFN1(x, -y, discr), QFN1(x, y, discr) }; // Compute the signed heights at the intersection points, h[0] and // h[1] with h[0] <= h[1]. The ordering is guaranteed because we // have arranged for the input line to satisfy Dot(D,U) >= 0. std::array<QFN1, 2> h = { t[0] * DdU + DdPmV, t[1] * DdU + DdPmV }; QFN1 zero(0, 0, discr); if (h[0] >= zero) { // Block 1. The line intersects the positive cone in two // points. SetSegmentClamp(t, h, DdU, DdPmV, cone, result); } else if (h[1] <= zero) { // Block 2. The line intersects the negative cone in two // points. SetEmpty(result); } else // h[0] < 0 < h[1] { // Block 3. The line intersects the positive cone in a single // point and the negative cone in a single point. SetRayClamp(h[1], DdU, DdPmV, cone, result); } } void CaseC2NotZeroDiscrZero(Real const& c1, Real const& c2, Real const& UdU, Real const& UdPmV, Real const& DdU, Real const& DdPmV, Cone3<Real> const& cone, Result& result) { Real t = -c1 / c2; if (t * UdU + UdPmV == (Real)0) { // To get here, it must be that V = P + (-c1/c2) * U, where // U is not necessarily a unit-length vector. The line // intersects the cone vertex. if (c2 < (Real)0) { // Block 4. The line is outside the double-sided cone and // intersects it only at V. SetPointClamp(QFN1(t, 0, 0), QFN1(0, 0, 0), cone, result); } else { // Block 5. The line is inside the double-sided cone, so // the intersection is a ray with origin V. SetRayClamp(QFN1(0, 0, 0), DdU, DdPmV, cone, result); } } else { // The line is tangent to the cone at a point different from // the vertex. Real h = t * DdU + DdPmV; if (h >= (Real)0) { // Block 6. The line is tangent to the positive cone. SetPointClamp(QFN1(t, 0, 0), QFN1(h, 0, 0), cone, result); } else { // Block 7. The line is tangent to the negative cone. SetEmpty(result); } } } void CaseC2ZeroC1NotZero(Real const& c0, Real const& c1, Real const& DdU, Real const& DdPmV, Cone3<Real> const& cone, Result& result) { // U is a direction vector on the cone boundary. Compute the // t-value for the intersection point and compute the // corresponding height h to determine whether that point is on // the positive cone or negative cone. Real t = (Real)-0.5 * c0 / c1; Real h = t * DdU + DdPmV; if (h > (Real)0) { // Block 8. The line intersects the positive cone and the ray // of intersection is interior to the positive cone. The // intersection is a ray or segment. SetRayClamp(QFN1(h, 0, 0), DdU, DdPmV, cone, result); } else { // Block 9. The line intersects the negative cone and the ray // of intersection is interior to the negative cone. SetEmpty(result); } } void CaseC2ZeroC1Zero(Real const& c0, Real const& UdU, Real const& UdPmV, Real const& DdU, Real const& DdPmV, Cone3<Real> const& cone, Result& result) { if (c0 != (Real)0) { // Block 10. The line does not intersect the double-sided // cone. SetEmpty(result); } else { // Block 11. The line is on the cone boundary. The // intersection with the positive cone is a ray that contains // the cone vertex. The intersection is either a ray or // segment. Real t = -UdPmV / UdU; Real h = t * DdU + DdPmV; SetRayClamp(QFN1(h, 0, 0), DdU, DdPmV, cone, result); } } void SetEmpty(Result& result) { result.type = Result::isEmpty; result.t[0] = QFN1(); result.t[1] = QFN1(); } void SetPoint(QFN1 const& t, Result& result) { result.type = Result::isPoint; result.t[0] = t; result.t[1] = result.t[0]; } void SetSegment(QFN1 const& t0, QFN1 const& t1, Result& result) { result.type = Result::isSegment; result.t[0] = t0; result.t[1] = t1; } void SetRayPositive(QFN1 const& t, Result& result) { result.type = Result::isRayPositive; result.t[0] = t; result.t[1] = QFN1(+1, 0, t.d); // +infinity } void SetRayNegative(QFN1 const& t, Result& result) { result.type = Result::isRayNegative; result.t[0] = QFN1(-1, 0, t.d); // +infinity result.t[1] = t; } void SetPointClamp(QFN1 const& t, QFN1 const& h, Cone3<Real> const& cone, Result& result) { if (cone.HeightInRange(h.x[0])) { // P0. SetPoint(t, result); } else { // P1. SetEmpty(result); } } void SetSegmentClamp(std::array<QFN1, 2> const& t, std::array<QFN1, 2> const& h, Real const& DdU, Real const& DdPmV, Cone3<Real> const& cone, Result& result) { std::array<QFN1, 2> hrange = { QFN1(cone.GetMinHeight(), 0, h[0].d), QFN1(cone.GetMaxHeight(), 0, h[0].d) }; if (h[1] > h[0]) { auto iir = (cone.IsFinite() ? IIQuery()(h, hrange) : IIQuery()(h, hrange[0], true)); if (iir.numIntersections == 2) { // S0. SetSegment((iir.overlap[0] - DdPmV) / DdU, (iir.overlap[1] - DdPmV) / DdU, result); } else if (iir.numIntersections == 1) { // S1. SetPoint((iir.overlap[0] - DdPmV) / DdU, result); } else // iir.numIntersections == 0 { // S2. SetEmpty(result); } } else // h[1] == h[0] { if (hrange[0] <= h[0] && (cone.IsFinite() ? h[0] <= hrange[1] : true)) { // S3. DdU > 0 and the line is not perpendicular to the // cone axis. SetSegment(t[0], t[1], result); } else { // S4. DdU == 0 and the line is perpendicular to the // cone axis. SetEmpty(result); } } } void SetRayClamp(QFN1 const& h, Real const& DdU, Real const& DdPmV, Cone3<Real> const& cone, Result& result) { std::array<QFN1, 2> hrange = { QFN1(cone.GetMinHeight(), 0, h.d), QFN1(cone.GetMaxHeight(), 0, h.d) }; if (cone.IsFinite()) { auto iir = IIQuery()(hrange, h, true); if (iir.numIntersections == 2) { // R0. SetSegment((iir.overlap[0] - DdPmV) / DdU, (iir.overlap[1] - DdPmV) / DdU, result); } else if (iir.numIntersections == 1) { // R1. SetPoint((iir.overlap[0] - DdPmV) / DdU, result); } else // iir.numIntersections == 0 { // R2. SetEmpty(result); } } else { // R3. SetRayPositive((std::max(hrange[0], h) - DdPmV) / DdU, result); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprGaussian2.h
.h
4,616
129
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/OrientedBox.h> #include <Mathematics/SymmetricEigensolver2x2.h> #include <Mathematics/Vector2.h> // Fit points with a Gaussian distribution. The center is the mean of the // points, the axes are the eigenvectors of the covariance matrix and the // extents are the eigenvalues of the covariance matrix and are returned in // increasing order. An oriented box is used to store the mean, axes and // extents. namespace gte { template <typename Real> class ApprGaussian2 : public ApprQuery<Real, Vector2<Real>> { public: // Initialize the model parameters to zero. ApprGaussian2() { mParameters.center = Vector2<Real>::Zero(); mParameters.axis[0] = Vector2<Real>::Zero(); mParameters.axis[1] = Vector2<Real>::Zero(); mParameters.extent = Vector2<Real>::Zero(); } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numPoints, Vector2<Real> const* points, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numPoints, points, numIndices, indices)) { // Compute the mean of the points. Vector2<Real> mean = Vector2<Real>::Zero(); int32_t const* currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { mean += points[*currentIndex++]; } Real invSize = (Real)1 / (Real)numIndices; mean *= invSize; if (std::isfinite(mean[0]) && std::isfinite(mean[1])) { // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar11 = (Real)0; currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { Vector2<Real> diff = points[*currentIndex++] - mean; covar00 += diff[0] * diff[0]; covar01 += diff[0] * diff[1]; covar11 += diff[1] * diff[1]; } covar00 *= invSize; covar01 *= invSize; covar11 *= invSize; // Solve the eigensystem. SymmetricEigensolver2x2<Real> es; std::array<Real, 2> eval; std::array<std::array<Real, 2>, 2> evec; es(covar00, covar01, covar11, +1, eval, evec); mParameters.center = mean; mParameters.axis[0] = evec[0]; mParameters.axis[1] = evec[1]; mParameters.extent = eval; return true; } } mParameters.center = Vector2<Real>::Zero(); mParameters.axis[0] = Vector2<Real>::Zero(); mParameters.axis[1] = Vector2<Real>::Zero(); mParameters.extent = Vector2<Real>::Zero(); return false; } // Get the parameters for the best fit. OrientedBox2<Real> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return 2; } virtual Real Error(Vector2<Real> const& point) const override { Vector2<Real> diff = point - mParameters.center; Real error = (Real)0; for (int32_t i = 0; i < 2; ++i) { if (mParameters.extent[i] > (Real)0) { Real ratio = Dot(diff, mParameters.axis[i]) / mParameters.extent[i]; error += ratio * ratio; } } return error; } virtual void CopyParameters(ApprQuery<Real, Vector2<Real>> const* input) override { auto source = dynamic_cast<ApprGaussian2 const*>(input); if (source) { *this = *source; } } private: OrientedBox2<Real> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment2Arc2.h
.h
2,745
95
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrSegment2Circle2.h> #include <Mathematics/Arc2.h> // The queries consider the arc to be a 1-dimensional object. namespace gte { template <typename T> class TIQuery<T, Segment2<T>, Arc2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Segment2<T> const& segment, Arc2<T> const& arc) { Result result{}; FIQuery<T, Segment2<T>, Arc2<T>> saQuery{}; auto saResult = saQuery(segment, arc); result.intersect = saResult.intersect; return result; } }; template <typename T> class FIQuery<T, Segment2<T>, Arc2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ (T)0, (T)0 }, point{ Vector2<T>::Zero(), Vector2<T>::Zero() } { } bool intersect; int32_t numIntersections; std::array<T, 2> parameter; std::array<Vector2<T>, 2> point; }; Result operator()(Segment2<T> const& segment, Arc2<T> const& arc) { Result result{}; result.intersect = false; result.numIntersections = 0; result.parameter[0] = (T)0; result.parameter[0] = (T)0; result.point[0] = { (T)0, (T)0 }; result.point[1] = { (T)0, (T)0 }; FIQuery<T, Segment2<T>, Circle2<T>> scQuery{}; Circle2<T> circle(arc.center, arc.radius); auto scResult = scQuery(segment, circle); if (scResult.intersect) { // Test whether line-circle intersections are on the arc. for (int32_t i = 0; i < scResult.numIntersections; ++i) { if (arc.Contains(scResult.point[i])) { result.intersect = true; result.parameter[result.numIntersections] = scResult.parameter[i]; result.point[result.numIntersections] = scResult.point[i]; ++result.numIntersections; } } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/StringUtility.h
.h
4,370
139
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <algorithm> #include <cctype> #include <iterator> #include <string> #include <vector> namespace gte { inline std::wstring ConvertNarrowToWide(std::string const& input) { std::wstring output; std::transform(input.begin(), input.end(), std::back_inserter(output), [](char c) { return static_cast<wchar_t>(c); }); return output; } inline std::string ConvertWideToNarrow(std::wstring const& input) { std::string output; std::transform(input.begin(), input.end(), std::back_inserter(output), [](wchar_t c) { return static_cast<char>(c); }); return output; } inline std::string ToLower(std::string const& input) { std::string output; std::transform(input.begin(), input.end(), std::back_inserter(output), [](int32_t c) { return static_cast<char>(::tolower(c)); }); return output; } inline std::string ToUpper(std::string const& input) { std::string output; std::transform(input.begin(), input.end(), std::back_inserter(output), [](int32_t c) { return static_cast<char>(::toupper(c)); }); return output; } // In the default locale for C++ strings, the whitespace characters are // space (0x20, ' '), form feed (0x0C, '\f'), line feed (0x0A, '\n'), // carriage return (0x0D, 'r'), horizontal tab (0x09, 't') and // vertical tab (0x0B, '\v'). See // https://en.cppreference.com/w/cpp/string/byte/isspace // for a table of ASCII values and related is* and isw* functions (with // 'int32_t ch' input) that return 0 or !0. inline void GetTokens(std::string const& input, std::string const& whiteSpace, std::vector<std::string>& tokens) { std::string tokenString(input); tokens.clear(); while (tokenString.length() > 0) { // Find the beginning of a token. auto begin = tokenString.find_first_not_of(whiteSpace); if (begin == std::string::npos) { // All tokens have been found. break; } // Strip off the white space. if (begin > 0) { tokenString = tokenString.substr(begin); } // Find the end of the token. auto end = tokenString.find_first_of(whiteSpace); if (end != std::string::npos) { std::string token = tokenString.substr(0, end); tokens.push_back(token); tokenString = tokenString.substr(end); } else { // This is the last token. tokens.push_back(tokenString); break; } } } // For basic text extraction, choose 'whiteSpace' to be ASCII values // 0x00-0x20,0x7F-0xFF in GetTokens(...). inline void GetTextTokens(std::string const& input, std::vector<std::string>& tokens) { static std::string const whiteSpace = [] { std::string temp; for (int32_t i = 0; i <= 32; ++i) { temp += char(i); } for (int32_t i = 127; i < 255; ++i) { temp += char(i); } return temp; } (); GetTokens(input, whiteSpace, tokens); } // For advanced text extraction, choose 'whiteSpace' to be ASCII values // 0x00-0x20,0x7F in GetTokens(...). Any special characters for ASCII // values 0x80 or larger are retained as text. inline void GetAdvancedTextTokens(std::string const& input, std::vector<std::string>& tokens) { static std::string const whiteSpace = [] { std::string temp; for (int32_t i = 0; i <= 32; ++i) { temp += char(i); } temp += char(127); return temp; } (); GetTokens(input, whiteSpace, tokens); } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRay3AlignedBox3.h
.h
2,048
60
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3AlignedBox3.h> #include <Mathematics/DistPointAlignedBox.h> #include <Mathematics/Ray.h> // Compute the distance between a ray and a solid aligned box in 3D. // // The ray is P + t * D for t >= 0, where D is not required to be unit length. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The closest point on the ray is stored in closest[0] with parameter t. The // closest point on the box is stored in closest[1]. When there are infinitely // many choices for the pair of closest points, only one of them is returned. namespace gte { template <typename T> class DCPQuery<T, Ray3<T>, AlignedBox3<T>> { public: using AlignedQuery = DCPQuery<T, Line3<T>, AlignedBox3<T>>; using Result = typename AlignedQuery::Result; Result operator()(Ray3<T> const& ray, AlignedBox3<T> const& box) { Result result{}; Line3<T> line(ray.origin, ray.direction); AlignedQuery lbQuery{}; auto lbOutput = lbQuery(line, box); T const zero = static_cast<T>(0); if (lbOutput.parameter >= zero) { result = lbOutput; } else { DCPQuery<T, Vector3<T>, AlignedBox3<T>> pbQuery{}; auto pbOutput = pbQuery(ray.origin, box); result.distance = pbOutput.distance; result.sqrDistance = pbOutput.sqrDistance; result.parameter = zero; result.closest[0] = ray.origin; result.closest[1] = pbOutput.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpBilinear2.h
.h
8,603
297
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <array> // The interpolator is for uniformly spaced (x,y)-values. The input samples // F must be stored in row-major order to represent f(x,y); that is, // F[c + xBound*r] corresponds to f(x,y), where c is the index corresponding // to x and r is the index corresponding to y. namespace gte { template <typename Real> class IntpBilinear2 { public: // Construction. IntpBilinear2(int32_t xBound, int32_t yBound, Real xMin, Real xSpacing, Real yMin, Real ySpacing, Real const* F) : mXBound(xBound), mYBound(yBound), mQuantity(xBound* yBound), mXMin(xMin), mXSpacing(xSpacing), mYMin(yMin), mYSpacing(ySpacing), mF(F) { // At least a 3x3 block of data points are needed to construct the // estimates of the boundary derivatives. LogAssert(mXBound >= 2 && mYBound >= 2 && mF != nullptr, "Invalid input."); LogAssert(mXSpacing > (Real)0 && mYSpacing > (Real)0, "Invalid input."); mXMax = mXMin + mXSpacing * static_cast<Real>(mXBound) - static_cast<Real>(1); mInvXSpacing = (Real)1 / mXSpacing; mYMax = mYMin + mYSpacing * static_cast<Real>(mYBound) - static_cast<Real>(1); mInvYSpacing = (Real)1 / mYSpacing; mBlend[0][0] = (Real)1; mBlend[0][1] = (Real)-1; mBlend[1][0] = (Real)0; mBlend[1][1] = (Real)1; } // Member access. inline int32_t GetXBound() const { return mXBound; } inline int32_t GetYBound() const { return mYBound; } inline int32_t GetQuantity() const { return mQuantity; } inline Real const* GetF() const { return mF; } inline Real GetXMin() const { return mXMin; } inline Real GetXMax() const { return mXMax; } inline Real GetXSpacing() const { return mXSpacing; } inline Real GetYMin() const { return mYMin; } inline Real GetYMax() const { return mYMax; } inline Real GetYSpacing() const { return mYSpacing; } // Evaluate the function and its derivatives. The functions clamp the // inputs to xmin <= x <= xmax and ymin <= y <= ymax. The first // operator is for function evaluation. The second operator is for // function or derivative evaluations. The xOrder argument is the // order of the x-derivative and the yOrder argument is the order of // the y-derivative. Both orders are zero to get the function value // itself. Real operator()(Real x, Real y) const { // Compute x-index and clamp to image. Real xIndex = (x - mXMin) * mInvXSpacing; int32_t ix = static_cast<int32_t>(xIndex); if (ix < 0) { ix = 0; } else if (ix >= mXBound) { ix = mXBound - 1; } // Compute y-index and clamp to image. Real yIndex = (y - mYMin) * mInvYSpacing; int32_t iy = static_cast<int32_t>(yIndex); if (iy < 0) { iy = 0; } else if (iy >= mYBound) { iy = mYBound - 1; } std::array<Real, 2> U; U[0] = (Real)1; U[1] = xIndex - ix; std::array<Real, 2> V; V[0] = (Real)1; V[1] = yIndex - iy; // Compute P = M*U and Q = M*V. std::array<Real, 2> P, Q; for (int32_t row = 0; row < 2; ++row) { P[row] = (Real)0; Q[row] = (Real)0; for (int32_t col = 0; col < 2; ++col) { P[row] += mBlend[row][col] * U[col]; Q[row] += mBlend[row][col] * V[col]; } } // Compute (M*U)^t D (M*V) where D is the 2x2 subimage // containing (x,y). Real result = (Real)0; for (int32_t row = 0; row < 2; ++row) { int32_t yClamp = iy + row; if (yClamp >= mYBound) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 2; ++col) { int32_t xClamp = ix + col; if (xClamp >= mXBound) { xClamp = mXBound - 1; } result += P[col] * Q[row] * mF[xClamp + mXBound * yClamp]; } } return result; } Real operator()(int32_t xOrder, int32_t yOrder, Real x, Real y) const { // Compute x-index and clamp to image. Real xIndex = (x - mXMin) * mInvXSpacing; int32_t ix = static_cast<int32_t>(xIndex); if (ix < 0) { ix = 0; } else if (ix >= mXBound) { ix = mXBound - 1; } // Compute y-index and clamp to image. Real yIndex = (y - mYMin) * mInvYSpacing; int32_t iy = static_cast<int32_t>(yIndex); if (iy < 0) { iy = 0; } else if (iy >= mYBound) { iy = mYBound - 1; } std::array<Real, 2> U; Real dx, xMult; switch (xOrder) { case 0: dx = xIndex - ix; U[0] = (Real)1; U[1] = dx; xMult = (Real)1; break; case 1: dx = xIndex - ix; U[0] = (Real)0; U[1] = (Real)1; xMult = mInvXSpacing; break; default: return (Real)0; } std::array<Real, 2> V; Real dy, yMult; switch (yOrder) { case 0: dy = yIndex - iy; V[0] = (Real)1; V[1] = dy; yMult = (Real)1; break; case 1: dy = yIndex - iy; V[0] = (Real)0; V[1] = (Real)1; yMult = mInvYSpacing; break; default: return (Real)0; } // Compute P = M*U and Q = M*V. std::array<Real, 2> P, Q; for (int32_t row = 0; row < 2; ++row) { P[row] = (Real)0; Q[row] = (Real)0; for (int32_t col = 0; col < 2; ++col) { P[row] += mBlend[row][col] * U[col]; Q[row] += mBlend[row][col] * V[col]; } } // Compute (M*U)^t D (M*V) where D is the 2x2 subimage containing (x,y). Real result = (Real)0; for (int32_t row = 0; row < 2; ++row) { int32_t yClamp = iy + row; if (yClamp >= mYBound) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 2; ++col) { int32_t xClamp = ix + col; if (xClamp >= mXBound) { xClamp = mXBound - 1; } result += P[col] * Q[row] * mF[xClamp + mXBound * yClamp]; } } result *= xMult * yMult; return result; } private: int32_t mXBound, mYBound, mQuantity; Real mXMin, mXMax, mXSpacing, mInvXSpacing; Real mYMin, mYMax, mYSpacing, mInvYSpacing; Real const* mF; std::array<std::array<Real, 2>, 2> mBlend; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OdeImplicitEuler.h
.h
2,242
60
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/GMatrix.h> #include <Mathematics/OdeSolver.h> // The TVector template parameter allows you to create solvers with // Vector<N,Real> when the dimension N is known at compile time or // GVector<Real> when the dimension N is known at run time. Both classes // have 'int32_t GetSize() const' that allow OdeSolver-derived classes to query // for the dimension. The TMatrix parameter must be either Matrix<N,N,Real> // or GMatrix<Real> accordingly. // // The function F(t,x) has input t, a scalar, and input x, an N-vector. // The first derivative matrix with respect to x is DF(t,x), an // N-by-N matrix. Entry DF(r,c) is the derivative of F[r] with // respect to x[c]. namespace gte { template <typename Real, typename TVector, typename TMatrix> class OdeImplicitEuler : public OdeSolver<Real, TVector> { public: // Construction and destruction. virtual ~OdeImplicitEuler() = default; OdeImplicitEuler(Real tDelta, std::function<TVector(Real, TVector const&)> const& F, std::function<TMatrix(Real, TVector const&)> const& DF) : OdeSolver<Real, TVector>(tDelta, F), mDerivativeFunction(DF) { } // Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). You may // allow xIn and xOut to be the same object. virtual void Update(Real tIn, TVector const& xIn, Real& tOut, TVector& xOut) override { TVector fVector = this->mFunction(tIn, xIn); TMatrix dfMatrix = mDerivativeFunction(tIn, xIn); TMatrix dgMatrix = TMatrix::Identity() - this->mTDelta * dfMatrix; TMatrix dgInverse = Inverse(dgMatrix); fVector = dgInverse * fVector; tOut = tIn + this->mTDelta; xOut = xIn + this->mTDelta * fVector; } private: std::function<TMatrix(Real, TVector const&)> mDerivativeFunction; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpBSplineUniform.h
.h
56,124
1,441
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <Mathematics/Polynomial1.h> #include <array> // IntpBSplineUniform is the class for B-spline interpolation of uniformly // spaced N-dimensional data. The algorithm is described in // https://www.geometrictools.com/Documentation/BSplineInterpolation.pdf // A sample application for this topic is // GeometricTools/GTEngine/Samples/Imagics/BSplineInterpolation // // The Controls adapter allows access to your control points without regard // to how you organize your data. You can even defer the computation of a // control point until it is needed via the operator()(...) calls that // Controls must provide, and you can cache the points according to your own // needs. The minimal interface for a Controls adapter is // // struct Controls // { // // The control_point_type is of your choosing. It must support // // assignment, scalar multiplication and addition. Specifically, if // // C0, C1 and C2 are control points and s is a scalar, the interpolator // // needs to perform operations // // C1 = C0; // // C1 = C0 * s; // // C2 = C0 + C1; // typedef control_point_type Type; // // // The number of elements in the specified dimension. // int32_t GetSize(int32_t dimension) const; // // // Get a control point based on an n-tuple lookup. The interpolator // // does not need to know your organization; all it needs is the // // desired control point. The 'tuple' input must have n elements. // Type operator() (int32_t const* tuple) const; // // // If you choose to use the specialized interpolators for dimensions // // 1, 2 or 3, you must also provide the following accessor, where // // the input is an n-tuple listed component-by-component (1, 2 or 3 // // components). // Type operator() (int32_t i0, int32_t i1, ..., int32_t inm1) const; // } namespace gte { template <typename Real, typename Controls> class IntpBSplineUniformShared { protected: // Abstract base class construction. A virtual destructor is not // provided because there are no required side effects in the base // class when destroying objects from the derived classes. IntpBSplineUniformShared(int32_t numDimensions, int32_t const* degrees, Controls const& controls, typename Controls::Type ctZero, int32_t cacheMode) : mNumDimensions(numDimensions), mDegree(numDimensions), mControls(&controls), mCTZero(ctZero), mCacheMode(cacheMode), mNumLocalControls(0), mDegreeP1(numDimensions), mNumControls(numDimensions), mTMin(numDimensions), mTMax(numDimensions), mBlender(numDimensions), mDCoefficient(numDimensions), mLMax(numDimensions), mPowerDSDT(numDimensions), mITuple(numDimensions), mJTuple(numDimensions), mKTuple(numDimensions), mLTuple(numDimensions), mSumIJTuple(numDimensions), mUTuple(numDimensions), mPTuple(numDimensions) { // The condition c+1 > d+1 is required so that when s = c+1-d, its // maximum value, we have at least two s-knots (d and d + 1). for (int32_t dim = 0; dim < mNumDimensions; ++dim) { if (mControls->GetSize(dim) <= degrees[dim] + 1) { LogError("Incompatible degree and number of controls."); } } mNumLocalControls = 1; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { mDegree[dim] = degrees[dim]; mDegreeP1[dim] = degrees[dim] + 1; mNumLocalControls *= mDegreeP1[dim]; mNumControls[dim] = controls.GetSize(dim); mTMin[dim] = (Real)-0.5; mTMax[dim] = static_cast<Real>(mNumControls[dim]) - (Real)0.5; ComputeBlendingMatrix(mDegree[dim], mBlender[dim]); ComputeDCoefficients(mDegree[dim], mDCoefficient[dim], mLMax[dim]); ComputePowers(mDegree[dim], mNumControls[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim]); } if (mCacheMode == NO_CACHING) { mPhi.resize(mNumDimensions); for (int32_t dim = 0; dim < mNumDimensions; ++dim) { mPhi[dim].resize(mDegreeP1[dim]); } } else { InitializeTensors(); } } #if !defined(GTE_INTP_BSPLINE_UNIFORM_NO_SPECIALIZATION) IntpBSplineUniformShared() : mNumDimensions(0), mControls(nullptr), mCTZero(), mCacheMode(0), mNumLocalControls(0) { } #endif public: // Support for caching the intermediate tensor product of control // points with the blending matrices. A precached container has all // elements precomputed before any Evaluate(...) calls. The 'bool' // flags are all set to 'true'. A cached container fills the elements // on demand. The 'bool' flags are initially 'false', indicating the // EvalType component has not yet been computed. After it is computed // and stored, the flag is set to 'true'. enum { NO_CACHING, PRE_CACHING, ON_DEMAND_CACHING }; // Member access. inline int32_t GetDegree(int32_t dim) const { return mDegree[dim]; } inline int32_t GetNumControls(int32_t dim) const { return mNumControls[dim]; } inline Real GetTMin(int32_t dim) const { return mTMin[dim]; } inline Real GetTMax(int32_t dim) const { return mTMax[dim]; } inline int32_t GetCacheMode() const { return mCacheMode; } protected: // Disallow copying and moving. IntpBSplineUniformShared(IntpBSplineUniformShared const&) = delete; IntpBSplineUniformShared& operator=(IntpBSplineUniformShared const&) = delete; IntpBSplineUniformShared(IntpBSplineUniformShared&&) = delete; IntpBSplineUniformShared& operator=(IntpBSplineUniformShared&&) = delete; // ComputeBlendingMatrix, ComputeDCoefficients, ComputePowers and // GetKey are used by the general-dimension derived classes and by // the specializations for dimensions 1, 2 and 3. // Compute the blending matrix that combines the control points and // the polynomial vector. The matrix A is stored in row-major order. static void ComputeBlendingMatrix(int32_t degree, std::vector<Real>& A) { int32_t const degreeP1 = degree + 1; A.resize(static_cast<size_t>(degreeP1) * static_cast<size_t>(degreeP1)); if (degree == 0) { A[0] = (Real)1; return; } // P_{0,0}(s) std::vector<Polynomial1<Real>> P(degreeP1); P[0][0] = (Real)1; // L0 = s/j Polynomial1<Real> L0(1); L0[0] = (Real)0; // L1(s) = (j + 1 - s)/j Polynomial1<Real> L1(1); // s-1 is used in computing translated P_{j-1,k-1}(s-1) Polynomial1<Real> sm1 = { (Real)-1, (Real)1 }; // Compute // P_{j,k}(s) = L0(s)*P_{j-1,k}(s) + L1(s)*P_{j-1,k-1}(s-1) // for 0 <= k <= j where 1 <= j <= degree. When k = 0, // P_{j-1,-1}(s) = 0, so P_{j,0}(s) = L0(s)*P_{j-1,0}(s). When // k = j, P_{j-1,j}(s) = 0, so P_{j,j}(s) = L1(s)*P_{j-1,j-1}(s). // The polynomials at level j-1 are currently stored in P[0] // through P[j-1]. The polynomials at level j are computed and // stored in P[0] through P[j]; that is, they are computed in // place to reduce memory usage and copying. This requires // computing P[k] (level j) from P[k] (level j-1) and P[k-1] // (level j-1), which means we have to process k = j down to // k = 0. for (int32_t j = 1; j <= degree; ++j) { Real invJ = (Real)1 / (Real)j; L0[1] = invJ; L1[0] = (Real)1 + invJ; L1[1] = -invJ; for (int32_t k = j; k >= 0; --k) { Polynomial1<Real> result = { (Real)0 }; if (k > 0) { result += L1 * P[static_cast<size_t>(k) - 1].GetTranslation((Real)1); } if (k < j) { result += L0 * P[k]; } P[k] = result; } } // Compute Q_{d,k}(s) = P_{d,k}(s + k). std::vector<Polynomial1<Real>> Q(degreeP1); for (int32_t k = 0; k <= degree; ++k) { Q[k] = P[k].GetTranslation(static_cast<Real>(-k)); } // Extract the matrix A from the Q-polynomials. Row r of A // contains the coefficients of Q_{d,d-r}(s). for (int32_t k = 0, row = degree; k <= degree; ++k, --row) { for (int32_t col = 0; col <= degree; ++col) { A[col + static_cast<size_t>(degreeP1) * row] = Q[k][col]; } } } // Compute the coefficients for the derivative polynomial terms. static void ComputeDCoefficients(int32_t degree, std::vector<Real>& dCoefficients, std::vector<int32_t>& ellMax) { int32_t numDCoefficients = (degree + 1) * (degree + 2) / 2; dCoefficients.resize(numDCoefficients); for (int32_t i = 0; i < numDCoefficients; ++i) { dCoefficients[i] = 1; } for (int32_t order = 1, col0 = 0, col1 = degree + 1; order <= degree; ++order) { ++col0; for (int32_t c = order, m = 1; c <= degree; ++c, ++m, ++col0, ++col1) { dCoefficients[col1] = dCoefficients[col0] * m; } } ellMax.resize(static_cast<size_t>(degree) + 1); ellMax[0] = degree; for (int32_t i0 = 0, i1 = 1; i1 <= degree; i0 = i1++) { ellMax[i1] = ellMax[i0] + degree - i0; } } // Compute powers of ds/dt. void ComputePowers(int32_t degree, int32_t numControls, Real tmin, Real tmax, std::vector<Real>& powerDSDT) { Real dsdt = (static_cast<Real>(numControls) - static_cast<Real>(degree)) / (tmax - tmin); powerDSDT.resize(static_cast<size_t>(degree) + 1); powerDSDT[0] = (Real)1; powerDSDT[1] = dsdt; for (int32_t i = 2, im1 = 1; i <= degree; ++i, ++im1) { powerDSDT[i] = powerDSDT[im1] * dsdt; } } // Determine the interval [index,index+1) corresponding to the // specified value of t and compute u in that interval. static void GetKey(Real t, Real tmin, Real tmax, Real dsdt, int32_t numControls, int32_t degree, int32_t& index, Real& u) { // Compute s - d = ((c + 1 - d)/(c + 1))(t + 1/2), the index for // which d + index <= s < d + index + 1. Let u = s - d - index so // that 0 <= u < 1. if (t > tmin) { if (t < tmax) { Real smd = dsdt * (t - tmin); index = static_cast<uint32_t>(std::floor(smd)); u = smd - static_cast<float>(index); } else { // In the evaluation, s = c + 1 - d and i = c - d. This // causes s-d-i to be 1 in G_c(c+1-d). Effectively, the // selection of i extends the s-domain [d,c+1) to its // support [d,c+1]. index = numControls - 1 - degree; u = (Real)1; } } else { index = 0; u = (Real)0; } } // The remaining functions are used only by the general-dimension // derived classes when caching is enabled. // For the multidimensional tensor Phi{iTuple, kTuple), compute the // portion of the 1-dimensional index that corresponds to iTuple. int32_t GetRowIndex(std::vector<int32_t> const& i) const { int32_t rowIndex = i[static_cast<size_t>(mNumDimensions) - 1]; int32_t j1 = 2 * mNumDimensions - 2; for (int32_t j0 = mNumDimensions - 2; j0 >= 0; --j0, --j1) { rowIndex = mTBound[j1] * rowIndex + i[j0]; } rowIndex = mTBound[j1] * rowIndex; return rowIndex; } // For the multidimensional tensor Phi{iTuple, kTuple), combine the // GetRowIndex(...) output with kTuple to produce the full // 1-dimensional index. int32_t GetIndex(int32_t rowIndex, std::vector<int32_t> const& k) const { int32_t index = rowIndex + k[static_cast<size_t>(mNumDimensions) - 1]; for (int32_t j = mNumDimensions - 2; j >= 0; --j) { index = mTBound[j] * index + k[j]; } return index; } // Compute Phi(iTuple, kTuple). The 'index' value is an already // computed 1-dimensional index for the tensor. void ComputeTensor(int32_t const* i, int32_t const* k, int32_t index) { typename Controls::Type element = mCTZero; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { mComputeJTuple[dim] = 0; } for (int32_t iterate = 0; iterate < mNumLocalControls; ++iterate) { Real blend(1); for (int32_t dim = 0; dim < mNumDimensions; ++dim) { blend *= mBlender[dim][k[dim] + static_cast<size_t>(mDegreeP1[dim]) * mComputeJTuple[dim]]; mComputeSumIJTuple[dim] = i[dim] + mComputeJTuple[dim]; } element = element + (*mControls)(mComputeSumIJTuple.data()) * blend; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { if (++mComputeJTuple[dim] < mDegreeP1[dim]) { break; } mComputeJTuple[dim] = 0; } } mTensor[index] = element; } // Allocate the containers used for caching and fill in the tensor // for precaching when that mode is selected. void InitializeTensors() { mTBound.resize(2 * static_cast<size_t>(mNumDimensions)); mComputeJTuple.resize(mNumDimensions); mComputeSumIJTuple.resize(mNumDimensions); mDegreeMinusOrder.resize(mNumDimensions); mTerm.resize(mNumDimensions); int32_t current = 0; int32_t numCached = 1; for (int32_t dim = 0; dim < mNumDimensions; ++dim, ++current) { mTBound[current] = mDegreeP1[dim]; numCached *= mTBound[current]; } for (int32_t dim = 0; dim < mNumDimensions; ++dim, ++current) { mTBound[current] = mNumControls[dim] - mDegree[dim]; numCached *= mTBound[current]; } mTensor.resize(numCached); mCached.resize(numCached); if (mCacheMode == PRE_CACHING) { std::vector<int32_t> tuple(2 * static_cast<size_t>(mNumDimensions), 0); for (int32_t index = 0; index < numCached; ++index) { ComputeTensor(&tuple[mNumDimensions], &tuple[0], index); for (int32_t i = 0; i < 2 * mNumDimensions; ++i) { if (++tuple[i] < mTBound[i]) { break; } tuple[i] = 0; } } std::fill(mCached.begin(), mCached.end(), true); } else { std::fill(mCached.begin(), mCached.end(), false); } } // Evaluate the interpolator. Each element of 'order' indicates the // order of the derivative you want to compute. For the function // value itself, pass in 'order' that has all 0 elements. typename Controls::Type EvaluateNoCaching(int32_t const* order, Real const* t) { typename Controls::Type result = mCTZero; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { if (order[dim] < 0 || order[dim] > mDegree[dim]) { return result; } } for (int32_t dim = 0; dim < mNumDimensions; ++dim) { GetKey(t[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim][1], mNumControls[dim], mDegree[dim], mITuple[dim], mUTuple[dim]); } for (int32_t dim = 0; dim < mNumDimensions; ++dim) { int32_t jIndex = 0; for (int32_t j = 0; j <= mDegree[dim]; ++j) { int32_t kjIndex = mDegree[dim] + jIndex; int32_t ell = mLMax[dim][order[dim]]; mPhi[dim][j] = (Real)0; for (int32_t k = mDegree[dim]; k >= order[dim]; --k) { mPhi[dim][j] = mPhi[dim][j] * mUTuple[dim] + mBlender[dim][kjIndex--] * mDCoefficient[dim][ell--]; } jIndex += mDegreeP1[dim]; } } for (int32_t dim = 0; dim < mNumDimensions; ++dim) { mJTuple[dim] = 0; mSumIJTuple[dim] = mITuple[dim]; mPTuple[dim] = mPhi[dim][0]; } for (int32_t iterate = 0; iterate < mNumLocalControls; ++iterate) { Real product(1); for (int32_t dim = 0; dim < mNumDimensions; ++dim) { product *= mPTuple[dim]; } result = result + (*mControls)(mSumIJTuple.data()) * product; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { if (++mJTuple[dim] <= mDegree[dim]) { mSumIJTuple[dim] = mITuple[dim] + mJTuple[dim]; mPTuple[dim] = mPhi[dim][mJTuple[dim]]; break; } mJTuple[dim] = 0; mSumIJTuple[dim] = mITuple[dim]; mPTuple[dim] = mPhi[dim][0]; } } Real adjust(1); for (int32_t dim = 0; dim < mNumDimensions; ++dim) { adjust *= mPowerDSDT[dim][order[dim]]; } result = result * adjust; return result; } typename Controls::Type EvaluateCaching(int32_t const* order, Real const* t) { int32_t numIterates = 1; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { mDegreeMinusOrder[dim] = mDegree[dim] - order[dim]; if (mDegreeMinusOrder[dim] < 0 || mDegreeMinusOrder[dim] > mDegree[dim]) { return mCTZero; } numIterates *= mDegreeMinusOrder[dim] + 1; } for (int32_t dim = 0; dim < mNumDimensions; ++dim) { GetKey(t[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim][1], mNumControls[dim], mDegree[dim], mITuple[dim], mUTuple[dim]); } int32_t rowIndex = GetRowIndex(mITuple); for (int32_t dim = 0; dim < mNumDimensions; ++dim) { mJTuple[dim] = 0; mKTuple[dim] = mDegree[dim]; mLTuple[dim] = mLMax[dim][order[dim]]; mTerm[dim] = mCTZero; } for (int32_t iterate = 0; iterate < numIterates; ++iterate) { int32_t index = GetIndex(rowIndex, mKTuple); if (mCacheMode == ON_DEMAND_CACHING && !mCached[index]) { ComputeTensor(mITuple.data(), mKTuple.data(), index); mCached[index] = true; } mTerm[0] = mTerm[0] * mUTuple[0] + mTensor[index] * mDCoefficient[0][mLTuple[0]]; for (int32_t dim = 0; dim < mNumDimensions; ++dim) { if (++mJTuple[dim] <= mDegreeMinusOrder[dim]) { --mKTuple[dim]; --mLTuple[dim]; break; } int32_t dimp1 = dim + 1; if (dimp1 < mNumDimensions) { mTerm[dimp1] = mTerm[dimp1] * mUTuple[dimp1] + mTerm[dim] * mDCoefficient[dimp1][mLTuple[dimp1]]; mTerm[dim] = mCTZero; mJTuple[dim] = 0; mKTuple[dim] = mDegree[dim]; mLTuple[dim] = mLMax[dim][order[dim]]; } } } typename Controls::Type result = mTerm[static_cast<size_t>(mNumDimensions) - 1]; Real adjust(1); for (int32_t dim = 0; dim < mNumDimensions; ++dim) { adjust *= mPowerDSDT[dim][order[dim]]; } result = result * adjust; return result; } // Constructor inputs. int32_t const mNumDimensions; // N std::vector<int32_t> mDegree; // degree[N] Controls const* mControls; typename Controls::Type const mCTZero; int32_t const mCacheMode; // Parameters for B-spline evaluation. All std::vector containers // have N elements. int32_t mNumLocalControls; // product of (degree[]+1) std::vector<int32_t> mDegreeP1; std::vector<int32_t> mNumControls; std::vector<Real> mTMin; std::vector<Real> mTMax; std::vector<std::vector<Real>> mBlender; std::vector<std::vector<Real>> mDCoefficient; std::vector<std::vector<int32_t>> mLMax; std::vector<std::vector<Real>> mPowerDSDT; std::vector<int32_t> mITuple; std::vector<int32_t> mJTuple; std::vector<int32_t> mKTuple; std::vector<int32_t> mLTuple; std::vector<int32_t> mSumIJTuple; std::vector<Real> mUTuple; std::vector<Real> mPTuple; // Support for no-cached B-spline evaluation. The std::vector // container has N elements. std::vector<std::vector<Real>> mPhi; // Support for cached B-spline evaluation. std::vector<int32_t> mTBound; // tbound[2*N] std::vector<int32_t> mComputeJTuple; // computejtuple[N] std::vector<int32_t> mComputeSumIJTuple; // computesumijtuple[N] std::vector<int32_t> mDegreeMinusOrder; // degreeminusorder[N] std::vector<typename Controls::Type> mTerm; // mTerm[N] std::vector<typename Controls::Type> mTensor; // depends on numcontrols std::vector<bool> mCached; // same size as mTensor }; } // Implementation for B-spline interpolation whose dimension is known at // compile time. namespace gte { template <typename Real, typename Controls, int32_t N = 0> class IntpBSplineUniform : public IntpBSplineUniformShared<Real, Controls> { public: // The caller is responsible for ensuring that the IntpBSplineUniform // object persists as long as the input 'controls' exists. IntpBSplineUniform(std::array<int32_t, N> const& degrees, Controls const& controls, typename Controls::Type ctZero, int32_t cacheMode) : IntpBSplineUniformShared<Real, Controls>(N, degrees.data(), controls, ctZero, cacheMode) { } // Disallow copying and moving. IntpBSplineUniform(IntpBSplineUniform const&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform const&) = delete; IntpBSplineUniform(IntpBSplineUniform&&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform&&) = delete; // Evaluate the interpolator. Each element of 'order' indicates the // order of the derivative you want to compute. For the function // value itself, pass in 'order' that has all 0 elements. typename Controls::Type Evaluate(std::array<int32_t, N> const& order, std::array<Real, N> const& t) { if (this->mCacheMode == this->NO_CACHING) { return this->EvaluateNoCaching(order.data(), t.data()); } else { return this->EvaluateCaching(order.data(), t.data()); } } }; } // Implementation for B-spline interpolation whose dimension is known only // at run time. namespace gte { template <typename Real, typename Controls> class IntpBSplineUniform<Real, Controls, 0> : public IntpBSplineUniformShared<Real, Controls> { public: // The caller is responsible for ensuring that the IntpBSplineUniform // object persists as long as the input 'controls' exists. IntpBSplineUniform(std::vector<int32_t> const& degrees, Controls const& controls, typename Controls::Type ctZero, int32_t cacheMode) : IntpBSplineUniformShared<Real, Controls>(static_cast<int32_t>(degrees.size()), degrees.data(), controls, ctZero, cacheMode) { } // Disallow copying and moving. IntpBSplineUniform(IntpBSplineUniform const&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform const&) = delete; IntpBSplineUniform(IntpBSplineUniform&&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform&&) = delete; // Evaluate the interpolator. Each element of 'order' indicates the // order of the derivative you want to compute. For the function // value itself, pass in 'order' that has all 0 elements. typename Controls::Type Evaluate(std::vector<int32_t> const& order, std::vector<Real> const& t) { if (static_cast<int32_t>(order.size()) >= this->mNumDimensions && static_cast<int32_t>(t.size()) >= this->mNumDimensions) { if (this->mCacheMode == this->NO_CACHING) { return this->EvaluateNoCaching(order.data(), t.data()); } else { return this->EvaluateCaching(order.data(), t.data()); } } else { return this->mCTZero; } } }; } // To use only the N-dimensional template code above, define the symbol // GTE_INTP_BSPLINE_UNIFORM_NO_SPECIALIZATION to disable the specializations // that occur below. Notice that the interfaces are different between the // specializations and the general code. #if !defined(GTE_INTP_BSPLINE_UNIFORM_NO_SPECIALIZATION) // Specialization for 1-dimensional data. namespace gte { template <typename Real, typename Controls> class IntpBSplineUniform<Real, Controls, 1> : public IntpBSplineUniformShared<Real, Controls> { public: // The caller is responsible for ensuring that the IntpBSplineUniform // object persists as long as the input 'controls' exists. IntpBSplineUniform(int32_t degree, Controls const& controls, typename Controls::Type ctZero, int32_t cacheMode) : IntpBSplineUniformShared<Real, Controls>(), mDegree(degree), mControls(&controls), mCTZero(ctZero), mCacheMode(cacheMode) { // The condition c+1 > d+1 is required so that when s = c+1-d, its // maximum value, we have at least two s-knots (d and d + 1). if (mControls->GetSize(0) <= mDegree + 1) { LogError("Incompatible degree and number of controls."); } mDegreeP1 = mDegree + 1; mNumControls = mControls->GetSize(0); mTMin = (Real)-0.5; mTMax = static_cast<Real>(mNumControls) - (Real)0.5; mNumTRows = 0; mNumTCols = 0; this->ComputeBlendingMatrix(mDegree, mBlender); this->ComputeDCoefficients(mDegree, mDCoefficient, mLMax); this->ComputePowers(mDegree, mNumControls, mTMin, mTMax, mPowerDSDT); if (mCacheMode == this->NO_CACHING) { mPhi.resize(mDegreeP1); } else { InitializeTensors(); } } // Disallow copying and moving. IntpBSplineUniform(IntpBSplineUniform const&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform const&) = delete; IntpBSplineUniform(IntpBSplineUniform&&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform&&) = delete; // Member access. inline int32_t GetDegree(int32_t) const { return mDegree; } inline int32_t GetNumControls(int32_t) const { return mNumControls; } inline Real GetTMin(int32_t) const { return mTMin; } inline Real GetTMax(int32_t) const { return mTMax; } inline int32_t GetCacheMode() const { return mCacheMode; } // Evaluate the interpolator. The order is 0 when you want the B-spline // function value itself. The order is 1 for the first derivative of the // function, and so on. typename Controls::Type Evaluate(std::array<int32_t, 1> const& order, std::array<Real,1> const& t) { typename Controls::Type result = mCTZero; if (0 <= order[0] && order[0] <= mDegree) { int32_t i = 0; Real u = static_cast<Real>(0); this->GetKey(t[0], mTMin, mTMax, mPowerDSDT[1], mNumControls, mDegree, i, u); if (mCacheMode == this->NO_CACHING) { int32_t jIndex = 0; for (int32_t j = 0; j <= mDegree; ++j) { int32_t kjIndex = mDegree + jIndex; int32_t ell = mLMax[order[0]]; mPhi[j] = (Real)0; for (int32_t k = mDegree; k >= order[0]; --k) { mPhi[j] = mPhi[j] * u + mBlender[kjIndex--] * mDCoefficient[ell--]; } jIndex += mDegreeP1; } for (int32_t j = 0; j <= mDegree; ++j) { result = result + (*mControls)(i + j) * mPhi[j]; } } else { int32_t iIndex = mNumTCols * i; int32_t kiIndex = mDegree + iIndex; int32_t ell = mLMax[order[0]]; for (int32_t k = mDegree; k >= order[0]; --k) { if (mCacheMode == this->ON_DEMAND_CACHING && !mCached[kiIndex]) { ComputeTensor(i, k, kiIndex); mCached[kiIndex] = true; } result = result * u + mTensor[kiIndex--] * mDCoefficient[ell--]; } } result = result * mPowerDSDT[order[0]]; } return result; } protected: void ComputeTensor(int32_t r, int32_t c, int32_t index) { typename Controls::Type element = mCTZero; for (int32_t j = 0; j <= mDegree; ++j) { element = element + (*mControls)(r + j) * mBlender[c + static_cast<size_t>(mDegreeP1) * j]; } mTensor[index] = element; } void InitializeTensors() { mNumTRows = mNumControls - mDegree; mNumTCols = mDegreeP1; int32_t numCached = mNumTRows * mNumTCols; mTensor.resize(numCached); mCached.resize(numCached); if (mCacheMode == this->PRE_CACHING) { for (int32_t r = 0, index = 0; r < mNumTRows; ++r) { for (int32_t c = 0; c < mNumTCols; ++c, ++index) { ComputeTensor(r, c, index); } } std::fill(mCached.begin(), mCached.end(), true); } else { std::fill(mCached.begin(), mCached.end(), false); } } // Constructor inputs. int32_t mDegree; Controls const* mControls; typename Controls::Type mCTZero; int32_t mCacheMode; // Parameters for B-spline evaluation. int32_t mDegreeP1; int32_t mNumControls; Real mTMin, mTMax; std::vector<Real> mBlender; std::vector<Real> mDCoefficient; std::vector<int32_t> mLMax; std::vector<Real> mPowerDSDT; // Support for no-cached B-spline evaluation. std::vector<Real> mPhi; // Support for cached B-spline evaluation. int32_t mNumTRows, mNumTCols; std::vector<typename Controls::Type> mTensor; std::vector<bool> mCached; }; } // Specialization for 2-dimensional data. namespace gte { template <typename Real, typename Controls> class IntpBSplineUniform<Real, Controls, 2> : public IntpBSplineUniformShared<Real, Controls> { public: // The caller is responsible for ensuring that the IntpBSplineUniform2 // object persists as long as the input 'controls' exists. IntpBSplineUniform(std::array<int32_t, 2> const& degrees, Controls const& controls, typename Controls::Type ctZero, int32_t cacheMode) : IntpBSplineUniformShared<Real, Controls>(), mDegree(degrees), mControls(&controls), mCTZero(ctZero), mCacheMode(cacheMode) { // The condition c+1 > d+1 is required so that when s = c+1-d, its // maximum value, we have at least two s-knots (d and d + 1). for (int32_t dim = 0; dim < 2; ++dim) { if (mControls->GetSize(dim) <= mDegree[dim] + 1) { LogError("Incompatible degree and number of controls."); } } for (int32_t dim = 0; dim < 2; ++dim) { mDegreeP1[dim] = mDegree[dim] + 1; mNumControls[dim] = mControls->GetSize(dim); mTMin[dim] = (Real)-0.5; mTMax[dim] = static_cast<Real>(mNumControls[dim]) - (Real)0.5; mNumTRows[dim] = 0; mNumTCols[dim] = 0; this->ComputeBlendingMatrix(mDegree[dim], mBlender[dim]); this->ComputeDCoefficients(mDegree[dim], mDCoefficient[dim], mLMax[dim]); this->ComputePowers(mDegree[dim], mNumControls[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim]); } if (mCacheMode == this->NO_CACHING) { for (int32_t dim = 0; dim < 2; ++dim) { mPhi[dim].resize(mDegreeP1[dim]); } } else { InitializeTensors(); } } // Disallow copying and moving. IntpBSplineUniform(IntpBSplineUniform const&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform const&) = delete; IntpBSplineUniform(IntpBSplineUniform&&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform&&) = delete; // Member access. inline int32_t GetDegree(int32_t dim) const { return mDegree[dim]; } inline int32_t GetNumControls(int32_t dim) const { return mNumControls[dim]; } inline Real GetTMin(int32_t dim) const { return mTMin[dim]; } inline Real GetTMax(int32_t dim) const { return mTMax[dim]; } inline int32_t GetCacheMode() const { return mCacheMode; } // Evaluate the interpolator. The order is (0,0) when you want the // B-spline function value itself. The order0 is 1 for the first // derivative with respect to t0 and the order1 is 1 for the first // derivative with respect to t1. Higher-order derivatives in other // t-inputs are computed similarly. typename Controls::Type Evaluate(std::array<int32_t, 2> const& order, std::array<Real, 2> const& t) { typename Controls::Type result = mCTZero; if (0 <= order[0] && order[0] <= mDegree[0] && 0 <= order[1] && order[1] <= mDegree[1]) { std::array<int32_t, 2> i{ 0, 0 }; std::array<Real, 2> u{ (Real)0, (Real)0 }; for (int32_t dim = 0; dim < 2; ++dim) { this->GetKey(t[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim][1], mNumControls[dim], mDegree[dim], i[dim], u[dim]); } if (mCacheMode == this->NO_CACHING) { for (int32_t dim = 0; dim < 2; ++dim) { int32_t jIndex = 0; for (int32_t j = 0; j <= mDegree[dim]; ++j) { int32_t kjIndex = mDegree[dim] + jIndex; int32_t ell = mLMax[dim][order[dim]]; mPhi[dim][j] = (Real)0; for (int32_t k = mDegree[dim]; k >= order[dim]; --k) { mPhi[dim][j] = mPhi[dim][j] * u[dim] + mBlender[dim][kjIndex--] * mDCoefficient[dim][ell--]; } jIndex += mDegreeP1[dim]; } } for (int32_t j1 = 0; j1 <= mDegree[1]; ++j1) { Real phi1 = mPhi[1][j1]; for (int32_t j0 = 0; j0 <= mDegree[0]; ++j0) { Real phi0 = mPhi[0][j0]; Real phi01 = phi0 * phi1; result = result + (*mControls)(i[0] + j0, i[1] + j1) * phi01; } } } else { int32_t i0i1Index = mNumTCols[1] * (i[0] + mNumTRows[0] * i[1]); int32_t k1i0i1Index = mDegree[1] + i0i1Index; int32_t ell1 = mLMax[1][order[1]]; for (int32_t k1 = mDegree[1]; k1 >= order[1]; --k1) { int32_t k0k1i0i1Index = mDegree[0] + mNumTCols[0] * k1i0i1Index; int32_t ell0 = mLMax[0][order[0]]; typename Controls::Type term = mCTZero; for (int32_t k0 = mDegree[0]; k0 >= order[0]; --k0) { if (mCacheMode == this->ON_DEMAND_CACHING && !mCached[k0k1i0i1Index]) { ComputeTensor(i[0], i[1], k0, k1, k0k1i0i1Index); mCached[k0k1i0i1Index] = true; } term = term * u[0] + mTensor[k0k1i0i1Index--] * mDCoefficient[0][ell0--]; } result = result * u[1] + term * mDCoefficient[1][ell1--]; --k1i0i1Index; } } Real adjust(1); for (int32_t dim = 0; dim < 2; ++dim) { adjust *= mPowerDSDT[dim][order[dim]]; } result = result * adjust; } return result; } void ComputeTensor(int32_t r0, int32_t r1, int32_t c0, int32_t c1, int32_t index) { typename Controls::Type element = mCTZero; for (int32_t j1 = 0; j1 <= mDegree[1]; ++j1) { Real blend1 = mBlender[1][c1 + static_cast<size_t>(mDegreeP1[1]) * j1]; for (int32_t j0 = 0; j0 <= mDegree[0]; ++j0) { Real blend0 = mBlender[0][c0 + static_cast<size_t>(mDegreeP1[0]) * j0]; Real blend01 = blend0 * blend1; element = element + (*mControls)(r0 + j0, r1 + j1) * blend01; } } mTensor[index] = element; } void InitializeTensors() { int32_t numCached = 1; for (int32_t dim = 0; dim < 2; ++dim) { mNumTRows[dim] = mNumControls[dim] - mDegree[dim]; mNumTCols[dim] = mDegreeP1[dim]; numCached *= mNumTRows[dim] * mNumTCols[dim]; } mTensor.resize(numCached); mCached.resize(numCached); if (mCacheMode == this->PRE_CACHING) { for (int32_t r1 = 0, index = 0; r1 < mNumTRows[1]; ++r1) { for (int32_t r0 = 0; r0 < mNumTRows[0]; ++r0) { for (int32_t c1 = 0; c1 < mNumTCols[1]; ++c1) { for (int32_t c0 = 0; c0 < mNumTCols[0]; ++c0, ++index) { ComputeTensor(r0, r1, c0, c1, index); } } } } std::fill(mCached.begin(), mCached.end(), true); } else { std::fill(mCached.begin(), mCached.end(), false); } } // Constructor inputs. std::array<int32_t, 2> mDegree; Controls const* mControls; typename Controls::Type mCTZero; int32_t mCacheMode; // Parameters for B-spline evaluation. std::array<int32_t, 2> mDegreeP1; std::array<int32_t, 2> mNumControls; std::array<Real, 2> mTMin, mTMax; std::array<std::vector<Real>, 2> mBlender; std::array<std::vector<Real>, 2> mDCoefficient; std::array<std::vector<int32_t>, 2> mLMax; std::array<std::vector<Real>, 2> mPowerDSDT; // Support for no-cached B-spline evaluation. std::array<std::vector<Real>, 2> mPhi; // Support for cached B-spline evaluation. std::array<int32_t, 2> mNumTRows, mNumTCols; std::vector<typename Controls::Type> mTensor; std::vector<bool> mCached; }; } // Specialization for 3-dimensional data. namespace gte { template <typename Real, typename Controls> class IntpBSplineUniform<Real, Controls, 3> : public IntpBSplineUniformShared<Real, Controls> { public: // The caller is responsible for ensuring that the IntpBSplineUniform3 // object persists as long as the input 'controls' exists. IntpBSplineUniform(std::array<int32_t, 3> const& degrees, Controls const& controls, typename Controls::Type ctZero, int32_t cacheMode) : IntpBSplineUniformShared<Real, Controls>(), mDegree(degrees), mControls(&controls), mCTZero(ctZero), mCacheMode(cacheMode) { // The condition c+1 > d+1 is required so that when s = c+1-d, its // maximum value, we have at least two s-knots (d and d + 1). for (int32_t dim = 0; dim < 3; ++dim) { if (mControls->GetSize(dim) <= mDegree[dim] + 1) { LogError("Incompatible degree and number of controls."); } } for (int32_t dim = 0; dim < 3; ++dim) { mDegreeP1[dim] = mDegree[dim] + 1; mNumControls[dim] = mControls->GetSize(dim); mTMin[dim] = (Real)-0.5; mTMax[dim] = static_cast<Real>(mNumControls[dim]) - (Real)0.5; mNumTRows[dim] = 0; mNumTCols[dim] = 0; this->ComputeBlendingMatrix(mDegree[dim], mBlender[dim]); this->ComputeDCoefficients(mDegree[dim], mDCoefficient[dim], mLMax[dim]); this->ComputePowers(mDegree[dim], mNumControls[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim]); } if (mCacheMode == this->NO_CACHING) { for (int32_t dim = 0; dim < 3; ++dim) { mPhi[dim].resize(mDegreeP1[dim]); } } else { InitializeTensors(); } } // Disallow copying and moving. IntpBSplineUniform(IntpBSplineUniform const&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform const&) = delete; IntpBSplineUniform(IntpBSplineUniform&&) = delete; IntpBSplineUniform& operator=(IntpBSplineUniform&&) = delete; // Member access. The input i specifies the dimension (0, 1, 2). inline int32_t GetDegree(int32_t dim) const { return mDegree[dim]; } inline int32_t GetNumControls(int32_t dim) const { return mNumControls[dim]; } inline Real GetTMin(int32_t dim) const { return mTMin[dim]; } inline Real GetTMax(int32_t dim) const { return mTMax[dim]; } // Evaluate the interpolator. The order is (0,0,0) when you want the // B-spline function value itself. The order0 is 1 for the first // derivative with respect to t0, the order1 is 1 for the first // derivative with respect to t1 or the order2 is 1 for the first // derivative with respect to t2. Higher-order derivatives in other // t-inputs are computed similarly. typename Controls::Type Evaluate(std::array<int32_t, 3> const& order, std::array<Real, 3> const& t) { typename Controls::Type result = mCTZero; if (0 <= order[0] && order[0] <= mDegree[0] && 0 <= order[1] && order[1] <= mDegree[1] && 0 <= order[2] && order[2] <= mDegree[2]) { std::array<int32_t, 3> i{ 0, 0, 0 }; std::array<Real, 3> u{ (Real)0, (Real)0, (Real)0 }; for (int32_t dim = 0; dim < 3; ++dim) { this->GetKey(t[dim], mTMin[dim], mTMax[dim], mPowerDSDT[dim][1], mNumControls[dim], mDegree[dim], i[dim], u[dim]); } if (mCacheMode == this->NO_CACHING) { for (int32_t dim = 0; dim < 3; ++dim) { int32_t jIndex = 0; for (int32_t j = 0; j <= mDegree[dim]; ++j) { int32_t kjIndex = mDegree[dim] + jIndex; int32_t ell = mLMax[dim][order[dim]]; mPhi[dim][j] = (Real)0; for (int32_t k = mDegree[dim]; k >= order[dim]; --k) { mPhi[dim][j] = mPhi[dim][j] * u[dim] + mBlender[dim][kjIndex--] * mDCoefficient[dim][ell--]; } jIndex += mDegreeP1[dim]; } } for (int32_t j2 = 0; j2 <= mDegree[2]; ++j2) { Real phi2 = mPhi[2][j2]; for (int32_t j1 = 0; j1 <= mDegree[1]; ++j1) { Real phi1 = mPhi[1][j1]; Real phi12 = phi1 * phi2; for (int32_t j0 = 0; j0 <= mDegree[0]; ++j0) { Real phi0 = mPhi[0][j0]; Real phi012 = phi0 * phi12; result = result + (*mControls)(i[0] + j0, i[1] + j1, i[2] + j2) * phi012; } } } } else { int32_t i0i1i2Index = mNumTCols[2] * (i[0] + mNumTRows[0] * (i[1] + mNumTRows[1] * i[2])); int32_t k2i0i1i2Index = mDegree[2] + i0i1i2Index; int32_t ell2 = mLMax[2][order[2]]; for (int32_t k2 = mDegree[2]; k2 >= order[2]; --k2) { int32_t k1k2i0i1i2Index = mDegree[1] + mNumTCols[1] * k2i0i1i2Index; int32_t ell1 = mLMax[1][order[1]]; typename Controls::Type term1 = mCTZero; for (int32_t k1 = mDegree[1]; k1 >= order[1]; --k1) { int32_t k0k1k2i0i1i2Index = mDegree[0] + mNumTCols[0] * k1k2i0i1i2Index; int32_t ell0 = mLMax[0][order[0]]; typename Controls::Type term0 = mCTZero; for (int32_t k0 = mDegree[0]; k0 >= order[0]; --k0) { if (mCacheMode == this->ON_DEMAND_CACHING && !mCached[k0k1k2i0i1i2Index]) { ComputeTensor(i[0], i[1], i[2], k0, k1, k2, k0k1k2i0i1i2Index); mCached[k0k1k2i0i1i2Index] = true; } term0 = term0 * u[0] + mTensor[k0k1k2i0i1i2Index--] * mDCoefficient[0][ell0--]; } term1 = term1 * u[1] + term0 * mDCoefficient[1][ell1--]; --k1k2i0i1i2Index; } result = result * u[2] + term1 * mDCoefficient[2][ell2--]; --k2i0i1i2Index; } } Real adjust(1); for (int32_t dim = 0; dim < 3; ++dim) { adjust *= mPowerDSDT[dim][order[dim]]; } result = result * adjust; } return result; } protected: void ComputeTensor(int32_t r0, int32_t r1, int32_t r2, int32_t c0, int32_t c1, int32_t c2, int32_t index) { typename Controls::Type element = mCTZero; for (int32_t j2 = 0; j2 <= mDegree[2]; ++j2) { Real blend2 = mBlender[2][c2 + static_cast<size_t>(mDegreeP1[2]) * j2]; for (int32_t j1 = 0; j1 <= mDegree[1]; ++j1) { Real blend1 = mBlender[1][c1 + static_cast<size_t>(mDegreeP1[1]) * j1]; Real blend12 = blend1 * blend2; for (int32_t j0 = 0; j0 <= mDegree[0]; ++j0) { Real blend0 = mBlender[0][c0 + static_cast<size_t>(mDegreeP1[0]) * j0]; Real blend012 = blend0 * blend12; element = element + (*mControls)(r0 + j0, r1 + j1, r2 + j2) * blend012; } } } mTensor[index] = element; } void InitializeTensors() { int32_t numCached = 1; for (int32_t dim = 0; dim < 3; ++dim) { mNumTRows[dim] = mNumControls[dim] - mDegree[dim]; mNumTCols[dim] = mDegreeP1[dim]; numCached *= mNumTRows[dim] * mNumTCols[dim]; } mTensor.resize(numCached); mCached.resize(numCached); if (mCacheMode == this->PRE_CACHING) { for (int32_t r2 = 0, index = 0; r2 < mNumTRows[2]; ++r2) { for (int32_t r1 = 0; r1 < mNumTRows[1]; ++r1) { for (int32_t r0 = 0; r0 < mNumTRows[0]; ++r0) { for (int32_t c2 = 0; c2 < mNumTCols[2]; ++c2) { for (int32_t c1 = 0; c1 < mNumTCols[1]; ++c1) { for (int32_t c0 = 0; c0 < mNumTCols[0]; ++c0, ++index) { ComputeTensor(r0, r1, r2, c0, c1, c2, index); } } } } } } std::fill(mCached.begin(), mCached.end(), true); } else { std::fill(mCached.begin(), mCached.end(), false); } } // Constructor inputs. std::array<int32_t, 3> mDegree; Controls const* mControls; typename Controls::Type mCTZero; int32_t mCacheMode; // Parameters for B-spline evaluation. std::array<int32_t, 3> mDegreeP1; std::array<int32_t, 3> mNumControls; std::array<Real, 3> mTMin, mTMax; std::array<std::vector<Real>, 3> mBlender; std::array<std::vector<Real>, 3> mDCoefficient; std::array<std::vector<int32_t>, 3> mLMax; std::array<std::vector<Real>, 3> mPowerDSDT; // Support for no-cached B-spline evaluation. std::array<std::vector<Real>, 3> mPhi; // Support for cached B-spline evaluation. std::array<int32_t, 3> mNumTRows, mNumTCols; std::vector<typename Controls::Type> mTensor; std::vector<bool> mCached; }; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ExpEstimate.h
.h
1,557
45
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.06.08 #pragma once #include <Mathematics/Exp2Estimate.h> // Minimax polynomial approximations to 2^x. The polynomial p(x) of // degree D minimizes the quantity maximum{|2^x - p(x)| : x in [0,1]} // over all polynomials of degree D. The natural exponential is // computed using exp(x) = 2^{x/log(2)}, where log(2) is the natural // logarithm of 2. namespace gte { template <typename Real> class ExpEstimate { public: // The input constraint is x in [0,1]. For example, // float x; // in [0,1] // float result = ExpEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { return Exp2Estimate<Real>::template Degree<D>(x * (Real)GTE_C_INV_LN_2); } // The input x can be any real number. Range reduction is used to // generate a value y in [0,1], call Degree(y), and combine the output // with the proper exponent to obtain the approximation. For example, // float x; // x >= 0 // float result = ExpEstimate<float>::DegreeRR<3>(x); template <int32_t D> inline static Real DegreeRR(Real x) { return Exp2Estimate<Real>::template DegreeRR<D>(x * (Real)GTE_C_INV_LN_2); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSphere3Cone3.h
.h
13,464
359
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Cone.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector3.h> // The test-intersection query is based on the document // https://www.geometrictools.com/Documentation/IntersectionSphereCone.pdf // // The find-intersection returns a single point in the set of intersection // when that intersection is not empty. namespace gte { template <typename T> class TIQuery<T, Sphere3<T>, Cone3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Sphere3<T> const& sphere, Cone3<T> const& cone) { Result result{}; if (cone.GetMinHeight() > (T)0) { if (cone.IsFinite()) { result.intersect = DoQueryConeFrustum(sphere, cone); } else { result.intersect = DoQueryInfiniteTruncatedCone(sphere, cone); } } else { if (cone.IsFinite()) { result.intersect = DoQueryFiniteCone(sphere, cone); } else { result.intersect = DoQueryInfiniteCone(sphere, cone); } } return result; } private: bool DoQueryInfiniteCone(Sphere3<T> const& sphere, Cone3<T> const& cone) { Vector3<T> U = cone.ray.origin - (sphere.radius * cone.invSinAngle) * cone.ray.direction; Vector3<T> CmU = sphere.center - U; T AdCmU = Dot(cone.ray.direction, CmU); if (AdCmU > (T)0) { T sqrLengthCmU = Dot(CmU, CmU); if (AdCmU * AdCmU >= sqrLengthCmU * cone.cosAngleSqr) { Vector3<T> CmV = sphere.center - cone.ray.origin; T AdCmV = Dot(cone.ray.direction, CmV); if (AdCmV < -sphere.radius) { return false; } T rSinAngle = sphere.radius * cone.sinAngle; if (AdCmV >= -rSinAngle) { return true; } T sqrLengthCmV = Dot(CmV, CmV); return sqrLengthCmV <= sphere.radius * sphere.radius; } } return false; } bool DoQueryInfiniteTruncatedCone(Sphere3<T> const& sphere, Cone3<T> const& cone) { Vector3<T> U = cone.ray.origin - (sphere.radius * cone.invSinAngle) * cone.ray.direction; Vector3<T> CmU = sphere.center - U; T AdCmU = Dot(cone.ray.direction, CmU); if (AdCmU > (T)0) { T sqrLengthCmU = Dot(CmU, CmU); if (AdCmU * AdCmU >= sqrLengthCmU * cone.cosAngleSqr) { Vector3<T> CmV = sphere.center - cone.ray.origin; T AdCmV = Dot(cone.ray.direction, CmV); T minHeight = cone.GetMinHeight(); if (AdCmV < minHeight - sphere.radius) { return false; } T rSinAngle = sphere.radius * cone.sinAngle; if (AdCmV >= -rSinAngle) { return true; } Vector3<T> D = CmV - minHeight * cone.ray.direction; T lengthAxD = Length(Cross(cone.ray.direction, D)); T hminTanAngle = minHeight * cone.tanAngle; if (lengthAxD <= hminTanAngle) { return true; } T AdD = AdCmV - minHeight; T diff = lengthAxD - hminTanAngle; T sqrLengthCmK = AdD * AdD + diff * diff; return sqrLengthCmK <= sphere.radius * sphere.radius; } } return false; } bool DoQueryFiniteCone(Sphere3<T> const& sphere, Cone3<T> const& cone) { Vector3<T> U = cone.ray.origin - (sphere.radius * cone.invSinAngle) * cone.ray.direction; Vector3<T> CmU = sphere.center - U; T AdCmU = Dot(cone.ray.direction, CmU); if (AdCmU > (T)0) { T sqrLengthCmU = Dot(CmU, CmU); if (AdCmU * AdCmU >= sqrLengthCmU * cone.cosAngleSqr) { Vector3<T> CmV = sphere.center - cone.ray.origin; T AdCmV = Dot(cone.ray.direction, CmV); if (AdCmV < -sphere.radius) { return false; } T maxHeight = cone.GetMaxHeight(); if (AdCmV > cone.GetMaxHeight() + sphere.radius) { return false; } T rSinAngle = sphere.radius * cone.sinAngle; if (AdCmV >= -rSinAngle) { if (AdCmV <= maxHeight - rSinAngle) { return true; } else { Vector3<T> barD = CmV - maxHeight * cone.ray.direction; T lengthAxBarD = Length(Cross(cone.ray.direction, barD)); T hmaxTanAngle = maxHeight * cone.tanAngle; if (lengthAxBarD <= hmaxTanAngle) { return true; } T AdBarD = AdCmV - maxHeight; T diff = lengthAxBarD - hmaxTanAngle; T sqrLengthCmBarK = AdBarD * AdBarD + diff * diff; return sqrLengthCmBarK <= sphere.radius * sphere.radius; } } else { T sqrLengthCmV = Dot(CmV, CmV); return sqrLengthCmV <= sphere.radius * sphere.radius; } } } return false; } bool DoQueryConeFrustum(Sphere3<T> const& sphere, Cone3<T> const& cone) { Vector3<T> U = cone.ray.origin - (sphere.radius * cone.invSinAngle) * cone.ray.direction; Vector3<T> CmU = sphere.center - U; T AdCmU = Dot(cone.ray.direction, CmU); if (AdCmU > (T)0) { T sqrLengthCmU = Dot(CmU, CmU); if (AdCmU * AdCmU >= sqrLengthCmU * cone.cosAngleSqr) { Vector3<T> CmV = sphere.center - cone.ray.origin; T AdCmV = Dot(cone.ray.direction, CmV); T minHeight = cone.GetMinHeight(); if (AdCmV < minHeight - sphere.radius) { return false; } T maxHeight = cone.GetMaxHeight(); if (AdCmV > maxHeight + sphere.radius) { return false; } T rSinAngle = sphere.radius * cone.sinAngle; if (AdCmV >= minHeight - rSinAngle) { if (AdCmV <= maxHeight - rSinAngle) { return true; } else { Vector3<T> barD = CmV - maxHeight * cone.ray.direction; T lengthAxBarD = Length(Cross(cone.ray.direction, barD)); T hmaxTanAngle = maxHeight * cone.tanAngle; if (lengthAxBarD <= hmaxTanAngle) { return true; } T AdBarD = AdCmV - maxHeight; T diff = lengthAxBarD - hmaxTanAngle; T sqrLengthCmBarK = AdBarD * AdBarD + diff * diff; return sqrLengthCmBarK <= sphere.radius * sphere.radius; } } else { Vector3<T> D = CmV - minHeight * cone.ray.direction; T lengthAxD = Length(Cross(cone.ray.direction, D)); T hminTanAngle = minHeight * cone.tanAngle; if (lengthAxD <= hminTanAngle) { return true; } T AdD = AdCmV - minHeight; T diff = lengthAxD - hminTanAngle; T sqrLengthCmK = AdD * AdD + diff * diff; return sqrLengthCmK <= sphere.radius * sphere.radius; } } } return false; } }; template <typename T> class FIQuery<T, Sphere3<T>, Cone3<T>> { public: struct Result { Result() : intersect(false), point(Vector3<T>::Zero()) { } // If an intersection occurs, it is potentially an infinite set. // If the cone vertex is inside the sphere, 'point' is set to the // cone vertex. If the sphere center is inside the cone, 'point' // is set to the sphere center. Otherwise, 'point' is set to the // cone point that is closest to the cone vertex and inside the // sphere. bool intersect; Vector3<T> point; }; Result operator()(Sphere3<T> const& sphere, Cone3<T> const& cone) { Result result{}; // Test whether the cone vertex is inside the sphere. Vector3<T> diff = sphere.center - cone.ray.origin; T rSqr = sphere.radius * sphere.radius; T lenSqr = Dot(diff, diff); if (lenSqr <= rSqr) { // The cone vertex is inside the sphere, so the sphere and // cone intersect. result.intersect = true; result.point = cone.ray.origin; return result; } // Test whether the sphere center is inside the cone. T dot = Dot(diff, cone.ray.direction); T dotSqr = dot * dot; if (dotSqr >= lenSqr * cone.cosAngleSqr && dot > (T)0) { // The sphere center is inside cone, so the sphere and cone // intersect. result.intersect = true; result.point = sphere.center; return result; } // The sphere center is outside the cone. The problem now reduces // to computing an intersection between the circle and the ray in // the plane containing the cone vertex and spanned by the cone // axis and vector from the cone vertex to the sphere center. // The ray is parameterized by t * D + V with t >= 0, |D| = 1 and // dot(A,D) = cos(angle). Also, D = e * A + f * (C - V). // Substituting the ray equation into the sphere equation yields // R^2 = |t * D + V - C|^2, so the quadratic for intersections is // t^2 - 2 * dot(D, C - V) * t + |C - V|^2 - R^2 = 0. An // intersection occurs if and only if the discriminant is // nonnegative. This test becomes // dot(D, C - V)^2 >= dot(C - V, C - V) - R^2 // Note that if the right-hand side is nonpositive, then the // inequality is true (the sphere contains V). This is already // ruled out in the first block of code in this function. T uLen = std::sqrt(std::max(lenSqr - dotSqr, (T)0)); T test = cone.cosAngle * dot + cone.sinAngle * uLen; T discr = test * test - lenSqr + rSqr; if (discr >= (T)0 && test >= (T)0) { // Compute the point of intersection closest to the cone // vertex. result.intersect = true; T t = test - std::sqrt(std::max(discr, (T)0)); Vector3<T> B = diff - dot * cone.ray.direction; T tmp = cone.sinAngle / uLen; result.point = t * (cone.cosAngle * cone.ray.direction + tmp * B); } else { result.intersect = false; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/VETNonmanifoldMesh.h
.h
7,181
214
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/SharedPtrCompare.h> #include <Mathematics/ETNonmanifoldMesh.h> // The VETNonmanifoldMesh class represents an edge-triangle nonmanifold mesh // but additionally stores vertex adjacency information. namespace gte { class VETNonmanifoldMesh : public ETNonmanifoldMesh { public: // Vertex data types. class Vertex; typedef std::shared_ptr<Vertex>(*VCreator)(int32_t); typedef std::map<int32_t, std::shared_ptr<Vertex>> VMap; // Vertex object. class Vertex { public: virtual ~Vertex() = default; Vertex(int32_t vIndex) : V(vIndex) { } // The index into the vertex pool of the mesh. int32_t V; bool operator<(Vertex const& other) const { return V < other.V; } // Adjacent objects. std::set<int32_t> VAdjacent; std::set<std::shared_ptr<Edge>, SharedPtrLT<Edge>> EAdjacent; std::set<std::shared_ptr<Triangle>, SharedPtrLT<Triangle>> TAdjacent; }; // Construction and destruction. virtual ~VETNonmanifoldMesh() = default; VETNonmanifoldMesh(VCreator vCreator = nullptr, ECreator eCreator = nullptr, TCreator tCreator = nullptr) : ETNonmanifoldMesh(eCreator, tCreator), mVCreator(vCreator ? vCreator : CreateVertex) { } // Support for a deep copy of the mesh. The mVMap, mEMap, and mTMap // objects have dynamically allocated memory for vertices, edges, and // triangles. A shallow copy of the pointers to this memory is // problematic. Allowing sharing, say, via std::shared_ptr, is an // option but not really the intent of copying the mesh graph. VETNonmanifoldMesh(VETNonmanifoldMesh const& mesh) { *this = mesh; } VETNonmanifoldMesh& operator=(VETNonmanifoldMesh const& mesh) { Clear(); mVCreator = mesh.mVCreator; ETNonmanifoldMesh::operator=(mesh); return *this; } // Member access. inline VMap const& GetVertices() const { return mVMap; } // If <v0,v1,v2> is not in the mesh, a Triangle object is created and // returned; otherwise, <v0,v1,v2> is in the mesh and nullptr is // returned. virtual std::shared_ptr<Triangle> Insert(int32_t v0, int32_t v1, int32_t v2) override { std::shared_ptr<Triangle> tri = ETNonmanifoldMesh::Insert(v0, v1, v2); if (!tri) { return nullptr; } for (int32_t i = 0; i < 3; ++i) { int32_t vIndex = tri->V[i]; auto vItem = mVMap.find(vIndex); std::shared_ptr<Vertex> vertex; if (vItem == mVMap.end()) { vertex = mVCreator(vIndex); mVMap[vIndex] = vertex; } else { vertex = vItem->second; } vertex->TAdjacent.insert(tri); for (int32_t j = 0; j < 3; ++j) { auto edge = tri->E[j].lock(); LogAssert(edge != nullptr, "Unexpected condition."); if (edge->V[0] == vIndex) { vertex->VAdjacent.insert(edge->V[1]); vertex->EAdjacent.insert(edge); } else if (edge->V[1] == vIndex) { vertex->VAdjacent.insert(edge->V[0]); vertex->EAdjacent.insert(edge); } } } return tri; } // If <v0,v1,v2> is in the mesh, it is removed and 'true' is returned; // otherwise, <v0,v1,v2> is not in the mesh and 'false' is returned. virtual bool Remove(int32_t v0, int32_t v1, int32_t v2) override { auto tItem = mTMap.find(TriangleKey<true>(v0, v1, v2)); if (tItem == mTMap.end()) { return false; } std::shared_ptr<Triangle> tri = tItem->second; for (int32_t i = 0; i < 3; ++i) { int32_t vIndex = tri->V[i]; auto vItem = mVMap.find(vIndex); LogAssert(vItem != mVMap.end(), "Unexpected condition."); std::shared_ptr<Vertex> vertex = vItem->second; for (int32_t j = 0; j < 3; ++j) { auto edge = tri->E[j].lock(); LogAssert(edge != nullptr, "Unexpected condition."); // If the edge will be removed by // ETNonmanifoldMesh::Remove, remove the vertex // references to it. if (edge->T.size() == 1) { for (auto const& adjw : edge->T) { auto adj = adjw.lock(); LogAssert(adj != nullptr, "Unexpected condition."); if (edge->V[0] == vIndex) { vertex->VAdjacent.erase(edge->V[1]); vertex->EAdjacent.erase(edge); } else if (edge->V[1] == vIndex) { vertex->VAdjacent.erase(edge->V[0]); vertex->EAdjacent.erase(edge); } } } } vertex->TAdjacent.erase(tri); // If the vertex is no longer shared by any triangle, // remove it. if (vertex->TAdjacent.size() == 0) { LogAssert(vertex->VAdjacent.size() != 0 || vertex->EAdjacent.size() != 0, "Malformed mesh."); mVMap.erase(vItem); } } return ETNonmanifoldMesh::Remove(v0, v1, v2); } // Destroy the vertices, edges, and triangles to obtain an empty mesh. virtual void Clear() override { mVMap.clear(); ETNonmanifoldMesh::Clear(); } protected: // The vertex data and default vertex creation. static std::shared_ptr<Vertex> CreateVertex(int32_t vIndex) { return std::make_shared<Vertex>(vIndex); } VCreator mVCreator; VMap mVMap; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContEllipse2.h
.h
5,721
150
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprGaussian2.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/Projection.h> namespace gte { // The input points are fit with a Gaussian distribution. The center C of // the ellipse is chosen to be the mean of the distribution. The axes of // the ellipse are chosen to be the eigenvectors of the covariance matrix // M. The shape of the ellipse is determined by the absolute values of // the eigenvalues. NOTE: The construction is ill-conditioned if the // points are (nearly) collinear. In this case M has a (nearly) zero // eigenvalue, so inverting M can be a problem numerically. template <typename Real> bool GetContainer(int32_t numPoints, Vector2<Real> const* points, Ellipse2<Real>& ellipse) { // Fit the points with a Gaussian distribution. The covariance matrix // is M = sum_j D[j]*U[j]*U[j]^T, where D[j] are the eigenvalues and // U[j] are corresponding unit-length eigenvectors. ApprGaussian2<Real> fitter; if (fitter.Fit(numPoints, points)) { OrientedBox2<Real> box = fitter.GetParameters(); // If either eigenvalue is nonpositive, adjust the D[] values so // that we actually build an ellipse. for (int32_t j = 0; j < 2; ++j) { if (box.extent[j] < (Real)0) { box.extent[j] = -box.extent[j]; } } // Grow the ellipse, while retaining its shape determined by the // covariance matrix, to enclose all the input points. The // quadratic form that is used for the ellipse construction is // Q(X) = (X-C)^T*M*(X-C) // = (X-C)^T*(sum_j D[j]*U[j]*U[j]^T)*(X-C) // = sum_j D[j]*Dot(U[j],X-C)^2 // If the maximum value of Q(X[i]) for all input points is V^2, // then a bounding ellipse is Q(X) = V^2, because Q(X[i]) <= V^2 // for all i. Real maxValue = (Real)0; for (int32_t i = 0; i < numPoints; ++i) { Vector2<Real> diff = points[i] - box.center; Real dot[2] = { Dot(box.axis[0], diff), Dot(box.axis[1], diff) }; Real value = box.extent[0] * dot[0] * dot[0] + box.extent[1] * dot[1] * dot[1]; if (value > maxValue) { maxValue = value; } } // Arrange for the quadratic to satisfy Q(X) <= 1. ellipse.center = box.center; for (int32_t j = 0; j < 2; ++j) { ellipse.axis[j] = box.axis[j]; ellipse.extent[j] = std::sqrt(maxValue / box.extent[j]); } return true; } return false; } // Test for containment of a point inside an ellipse. template <typename Real> bool InContainer(Vector2<Real> const& point, Ellipse2<Real> const& ellipse) { Vector2<Real> diff = point - ellipse.center; Vector2<Real> standardized{ Dot(diff, ellipse.axis[0]) / ellipse.extent[0], Dot(diff, ellipse.axis[1]) / ellipse.extent[1] }; return Length(standardized) <= (Real)1; } // Construct a bounding ellipse for the two input ellipses. The result is // not necessarily the minimum-area ellipse containing the two ellipses. template <typename Real> bool MergeContainers(Ellipse2<Real> const& ellipse0, Ellipse2<Real> const& ellipse1, Ellipse2<Real>& merge) { // Compute the average of the input centers. merge.center = (Real)0.5 * (ellipse0.center + ellipse1.center); // The bounding ellipse orientation is the average of the input // orientations. if (Dot(ellipse0.axis[0], ellipse1.axis[0]) >= (Real)0) { merge.axis[0] = (Real)0.5 * (ellipse0.axis[0] + ellipse1.axis[0]); } else { merge.axis[0] = (Real)0.5 * (ellipse0.axis[0] - ellipse1.axis[0]); } Normalize(merge.axis[0]); merge.axis[1] = -Perp(merge.axis[0]); // Project the input ellipses onto the axes obtained by the average // of the orientations and that go through the center obtained by the // average of the centers. for (int32_t j = 0; j < 2; ++j) { // Projection axis. Line2<Real> line(merge.center, merge.axis[j]); // Project ellipsoids onto the axis. Real min0, max0, min1, max1; Project(ellipse0, line, min0, max0); Project(ellipse1, line, min1, max1); // Determine the smallest interval containing the projected // intervals. Real maxIntr = (max0 >= max1 ? max0 : max1); Real minIntr = (min0 <= min1 ? min0 : min1); // Update the average center to be the center of the bounding box // defined by the projected intervals. merge.center += line.direction * ((Real)0.5 * (minIntr + maxIntr)); // Compute the extents of the box based on the new center. merge.extent[j] = (Real)0.5 * (maxIntr - minIntr); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ChebyshevRatio.h
.h
7,099
156
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Math.h> // Let f(t,A) = sin(t*A)/sin(A). The slerp of quaternions q0 and q1 is // slerp(t,q0,q1) = f(1-t,A)*q0 + f(t,A)*q1. // Let y = 1-cos(A); we allow A in [0,pi], so y in [0,1]. As a function of y, // a series representation for f(t,y) is // f(t,y) = sum_{i=0}^{infinity} c_{i}(t) y^{i} // where c_0(t) = t, c_{i}(t) = c_{i-1}(t)*(i^2 - t^2)/(i*(2*i+1)) for i >= 1. // The c_{i}(t) are polynomials in t of degree 2*i+1. The document // https://www.geometrictools/com/Documentation/FastAndAccurateSlerp.pdf // derives an approximation // g(t,y) = sum_{i=0}^{n-1} c_{i}(t) y^{i} + (1+u_n) c_{n}(t) y^n // which has degree 2*n+1 in t and degree n in y. // // Given q0 and q1 such that cos(A) = dot(q0,q1) in [0,1], in which case // A in [0,pi/2], let qh = (q0+q1)/|q0 + q1| = slerp(1/2,q0,q1). Note that // |q0 + q1| = 2*cos(A/2) because // sin(A/2)/sin(A) = sin(A/2)/(2*sin(A/2)*cos(A/2)) = 1/(2*cos(A/2)) // The angle between q0 and qh is the same as the angle between qh and q1, // namely, A/2 in [0,pi/4]. It may be shown that // +-- // slerp(t,q0,q1) = | slerp(2*t,q0,qh), 0 <= t <= 1/2 // | slerp(2*t-1,qh,q1), 1/2 <= t <= 1 // +-- // The slerp functions on the right-hand side involve angles in [0,pi/4], so // the approximation is more accurate for those evaluations than using the // original. // // TODO: The constants in GetEstimate are those of the published paper. // Modify these to match the aforementioned GT document. namespace gte { template <typename Real> class ChebyshevRatio { public: // Compute f(t,A) = sin(t*A)/sin(A), where t in [0,1], A in [0,pi/2], // cosA = cos(A), f0 = f(1-t,A), and f1 = f(t,A). static void Get(Real t, Real cosA, Real& f0, Real& f1) { if (cosA < (Real)1) { // The angle A is in (0,pi/2]. Real A = std::acos(cosA); Real invSinA = (Real)1 / std::sin(A); f0 = std::sin(((Real)1 - t) * A) * invSinA; f1 = std::sin(t * A) * invSinA; } else { // The angle theta is 0. f0 = (Real)1 - t; f1 = (Real)t; } } // Compute estimates for f(t,y) = sin(t*A)/sin(A), where t in [0,1], // A in [0,pi/2], y = 1 - cos(A), f0 is the estimate for f(1-t,y), and // f1 is the estimate for f(t,y). The approximating function is a // polynomial of two variables. The template parameter N must be in // {1..16}. The degree in t is 2*N+1 and the degree in Y is N. template <int32_t N> static void GetEstimate(Real t, Real y, Real & f0, Real & f1) { static_assert(1 <= N && N <= 16, "Invalid degree."); // The ASM output shows that the constants/ in these arrays are // loaded to XMM registers as literal values, and only those // constants required for the specified degree D are loaded. // That is, the compiler does a good job of optimizing the code. Real const onePlusMu[16] = { (Real)1.62943436108234530, (Real)1.73965850021313961, (Real)1.79701067629566813, (Real)1.83291820510335812, (Real)1.85772477879039977, (Real)1.87596835698904785, (Real)1.88998444919711206, (Real)1.90110745351730037, (Real)1.91015881189952352, (Real)1.91767344933047190, (Real)1.92401541194159076, (Real)1.92944142668012797, (Real)1.93413793373091059, (Real)1.93824371262559758, (Real)1.94186426368404708, (Real)1.94508125972497303 }; Real const a[16] = { (N != 1 ? (Real)1 : onePlusMu[0]) / ((Real)1 * (Real)3), (N != 2 ? (Real)1 : onePlusMu[1]) / ((Real)2 * (Real)5), (N != 3 ? (Real)1 : onePlusMu[2]) / ((Real)3 * (Real)7), (N != 4 ? (Real)1 : onePlusMu[3]) / ((Real)4 * (Real)9), (N != 5 ? (Real)1 : onePlusMu[4]) / ((Real)5 * (Real)11), (N != 6 ? (Real)1 : onePlusMu[5]) / ((Real)6 * (Real)13), (N != 7 ? (Real)1 : onePlusMu[6]) / ((Real)7 * (Real)15), (N != 8 ? (Real)1 : onePlusMu[7]) / ((Real)8 * (Real)17), (N != 9 ? (Real)1 : onePlusMu[8]) / ((Real)9 * (Real)19), (N != 10 ? (Real)1 : onePlusMu[9]) / ((Real)10 * (Real)21), (N != 11 ? (Real)1 : onePlusMu[10]) / ((Real)11 * (Real)23), (N != 12 ? (Real)1 : onePlusMu[11]) / ((Real)12 * (Real)25), (N != 13 ? (Real)1 : onePlusMu[12]) / ((Real)13 * (Real)27), (N != 14 ? (Real)1 : onePlusMu[13]) / ((Real)14 * (Real)29), (N != 15 ? (Real)1 : onePlusMu[14]) / ((Real)15 * (Real)31), (N != 16 ? (Real)1 : onePlusMu[15]) / ((Real)16 * (Real)33) }; Real const b[16] = { (N != 1 ? (Real)1 : onePlusMu[0]) * (Real)1 / (Real)3, (N != 2 ? (Real)1 : onePlusMu[1]) * (Real)2 / (Real)5, (N != 3 ? (Real)1 : onePlusMu[2]) * (Real)3 / (Real)7, (N != 4 ? (Real)1 : onePlusMu[3]) * (Real)4 / (Real)9, (N != 5 ? (Real)1 : onePlusMu[4]) * (Real)5 / (Real)11, (N != 6 ? (Real)1 : onePlusMu[5]) * (Real)6 / (Real)13, (N != 7 ? (Real)1 : onePlusMu[6]) * (Real)7 / (Real)15, (N != 8 ? (Real)1 : onePlusMu[7]) * (Real)8 / (Real)17, (N != 9 ? (Real)1 : onePlusMu[8]) * (Real)9 / (Real)19, (N != 10 ? (Real)1 : onePlusMu[9]) * (Real)10 / (Real)21, (N != 11 ? (Real)1 : onePlusMu[10]) * (Real)11 / (Real)23, (N != 12 ? (Real)1 : onePlusMu[11]) * (Real)12 / (Real)25, (N != 13 ? (Real)1 : onePlusMu[12]) * (Real)13 / (Real)27, (N != 14 ? (Real)1 : onePlusMu[13]) * (Real)14 / (Real)29, (N != 15 ? (Real)1 : onePlusMu[14]) * (Real)15 / (Real)31, (N != 16 ? (Real)1 : onePlusMu[15]) * (Real)16 / (Real)33 }; Real term0 = (Real)1 - t, term1 = t; Real sqr0 = term0 * term0, sqr1 = term1 * term1; f0 = term0; f1 = term1; for (int32_t i = 0; i < N; ++i) { term0 *= (b[i] - a[i] * sqr0) * y; term1 *= (b[i] - a[i] * sqr1) * y; f0 += term0; f1 += term1; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RotatingCalipers.h
.h
9,864
264
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.2.2022.03.03 #pragma once #include <Mathematics/ArbitraryPrecision.h> #include <Mathematics/Vector2.h> // The rotating calipers algorithm finds all antipodal vertex-edge pairs for a // convex polygon. The algorithm is O(n) in time for n polygon edges. The // brute-force method that finds extreme points for a perpendicular direction // for each edge and searching all polygon vertices is O(n^2). The search for // extreme points can use a form of bisection, which reduces the algorithm to // O(n log n). A description can be found at // http://www-cgrl.cs.mcgill.ca/~godfried/research/calipers.html // https://web.archive.org/web/20150330010154/http://cgm.cs.mcgill.ca/~orm/rotcal.html namespace gte { template <typename T> class RotatingCalipers { public: // The Antipode members are lookups into the input vertices[] to // ComputeAntipodes(...). struct Antipode { Antipode() : vertex(0), edge{ 0, 0 } { } size_t vertex; std::array<size_t, 2> edge; }; static void ComputeAntipodes(std::vector<Vector2<T>> const& vertices, std::vector<Antipode>& antipodes) { static_assert(std::is_floating_point<T>::value, "The input type must be 'float' or 'double'."); // Internally, the Antipode members are lookups into indices[]. // The members are re-mapped to lookups into vertices[] after // all antipodes are created. std::vector<Vector2<Rational>> rVertices{}; std::vector<size_t> indices{}; CreatePolygon(vertices, rVertices, indices); LogAssert( indices.size() >= 3, "The convex polygon must have at least 3 noncollinear vertices."); Antipode antipode{}; ComputeInitialAntipode(rVertices, indices, antipode); antipodes.clear(); antipodes.push_back(antipode); for (size_t i = 1; i < indices.size(); ++i) { ComputeNextAntipode(rVertices, indices, antipode); antipodes.push_back(antipode); } // Re-map the antipode members to be lookups into vertices[]. for (auto& element : antipodes) { element.vertex = indices[element.vertex]; element.edge[0] = indices[element.edge[0]]; element.edge[1] = indices[element.edge[1]]; } } private: // Parameters for the largest rational number possible in the rational // arithmetic for angle comparison. static int32_t constexpr NumWords = std::is_same<T, float>::value ? 54 : 394; using Rational = BSNumber<UIntegerFP32<NumWords>>; // The rotating calipers algorithm requires the convex polygon to have // no duplicate points and no collinear points. Such points must be // removed first. To ensure correctness, rational arithmetic is used. // This requires converting the floating-point vertices to rational // vertices. To minimize rational operations for the conversion, only // the final convex polygon vertices are converted. static void CreatePolygon( std::vector<Vector2<T>> const& vertices, std::vector<Vector2<Rational>>& rVertices, std::vector<size_t>& indices) { size_t const numVertices = vertices.size(); rVertices.resize(numVertices); indices.reserve(numVertices); Rational const rzero = static_cast<Rational>(0); auto const& vback = vertices.back(); auto const& vfront = vertices.front(); Vector2<Rational> rV0 = { vback[0], vback[1] }; Vector2<Rational> rV1 = { vfront[0], vfront[1] }; Vector2<Rational> rEPrev = rV1 - rV0; for (size_t i0 = 0, i1 = 1; i0 < numVertices; ++i0) { auto const& V0 = vertices[i0]; auto const& V1 = vertices[i1]; rV0 = { V0[0], V0[1] }; rV1 = { V1[0], V1[1] }; Vector2<Rational> rENext = rV1 - rV0; Rational rDP = DotPerp(rEPrev, rENext); if (rDP != rzero) { indices.push_back(i0); rVertices[i0] = rV0; } rEPrev = rENext; if (++i1 == numVertices) { i1 = 0; } } } static void ComputeInitialAntipode( std::vector<Vector2<Rational>> const& vertices, std::vector<size_t>& indices, Antipode& antipode) { size_t const numIndices = indices.size(); antipode.edge = { numIndices - 1, 0 }; Vector2<Rational> const& origin = vertices[indices[antipode.edge[0]]]; Vector2<Rational> U = vertices[indices[antipode.edge[1]]] - origin; Rational const zero(0); Vector2<Rational> extreme{ zero, zero }; antipode.vertex = 0; for (size_t i = 0; i < numIndices; ++i) { Vector2<Rational> diff = vertices[indices[i]] - origin; Vector2<Rational> c = { U[0] * diff[0] + U[1] * diff[1], U[0] * diff[1] - U[1] * diff[0] }; if (c[1] > extreme[1] || (c[1] == extreme[1] && c[0] < extreme[0])) { antipode.vertex = i; extreme = c; } } } static void ComputeNextAntipode( std::vector<Vector2<Rational>> const& vertices, std::vector<size_t>& indices, Antipode& antipode) { // Given edges E0 and E1 we know that the angle between them is // determined by Dot(E0,E1)/(|E0|*|E1|) = cos(angle). The angle // is in (0,pi/2] when Dot(E0,E1) >= 0 or in (pi/2,pi) when // Dot(E0,E1) < 0. To allow for exact arithmetic, observe that // sin^2(angle) = 1 - cos^2(angle) // = 1 - Dot(E0,E1)^2/(|E0|^2*|E|^2) // The comparator function for angles in (0,pi) compares the // squared sine values and the signs of the dot product of edges. size_t const numIndices = indices.size(); // Compute the edges associated with the current antipodal edge. size_t i0 = indices[antipode.edge[0]]; size_t i1 = indices[antipode.edge[1]]; size_t enext = antipode.edge[1] + 1; if (enext == numIndices) { enext = 0; } size_t i2 = indices[enext]; // Compute the edges associated with the current antipodal vertex. size_t j0 = indices[antipode.vertex]; size_t vnext = antipode.vertex + 1; if (vnext == numIndices) { vnext = 0; } size_t j1 = indices[vnext]; std::array<Vector2<Rational>, 2> D0 = { vertices[j1] - vertices[j0], vertices[i0] - vertices[i1] }; std::array<Vector2<Rational>, 2> D1 = { -D0[1], vertices[i2] - vertices[i1] }; if (AngleLessThan(D0, D1)) { // The angle at the antipodal vertex is minimum. std::swap(antipode.vertex, antipode.edge[1]); antipode.edge[0] = antipode.edge[1]; antipode.edge[1] = vnext; } else { // The angle at the antipodal edge is minimum. The // antipodal vertex does not change. antipode.edge[0] = antipode.edge[1]; antipode.edge[1] = enext; } } // Test Angle(D0[0],D0[1]) < Angle(D1[0],D1[1]). It is known that // D1[0] = -D0[1]. static bool AngleLessThan( std::array<Vector2<Rational>, 2> const& D0, std::array<Vector2<Rational>, 2> const& D1) { Rational const zero = static_cast<Rational>(0); Rational dot0 = Dot(D0[0], D0[1]); Rational dot1 = Dot(D1[0], D1[1]); if (dot0 >= zero) { // angle0 in (0,pi/2] if (dot1 < zero) { // angle1 in (pi/2,pi), so angle0 < angle1 return true; } // angle1 in (0,pi/2], sin^2(angle) is increasing function Rational sqrLen00 = Dot(D0[0], D0[0]); Rational sqrLen11 = Dot(D1[1], D1[1]); return dot0 * dot0 * sqrLen11 > dot1 * dot1 * sqrLen00; } else { // angle0 in (pi/2,pi) if (dot1 >= zero) { // angle1 in (0,pi/2], so angle1 < angle0 return false; } // angle1 in (pi/2,pi), sin^2(angle) is decreasing function Rational sqrLen00 = Dot(D0[0], D0[0]); Rational sqrLen11 = Dot(D1[1], D1[1]); return dot0 * dot0 * sqrLen11 < dot1 * dot1 * sqrLen00; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSplineReduction.h
.h
8,599
239
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.07.04 #pragma once #include <Mathematics/BandedMatrix.h> #include <Mathematics/GMatrix.h> #include <Mathematics/Integration.h> #include <Mathematics/IntrIntervals.h> #include <Mathematics/Vector.h> // The BSplineReduction class is an implementation of the algorithm in // https://www.geometrictools.com/Documentation/BSplineReduction.pdf // for least-squares fitting of points in the continuous sense by // an L2 integral norm. The least-squares fitting implemented in the // file BSplineCurveFit.h is in the discrete sense by an L2 summation. // The intended use for this class is to take an open B-spline curve, // defined by its control points and degree, and reducing the number of // control points dramatically to obtain another curve that is close to // the original one. namespace gte { // The input numCtrlPoints must be 2 or larger. The input degree must // satisfy the condition 1 <= degree <= inControls.size()-1. The degree // of the output curve is the same as that of the input curve. The input // fraction must be in [0,1]. If the fraction is 1, the output curve // is identical to the input curve. If the fraction is too small to // produce a valid number of control points, outControls.size() is chosen // to be degree+1. template <int32_t N, typename Real> class BSplineReduction { public: BSplineReduction() : mDegree(0), mQuantity{ 0, 0 }, mNumKnots{ 0, 0 }, mKnot{}, mBasis{ 0, 0 }, mIndex{ 0, 0 } { } void operator()(std::vector<Vector<N, Real>> const& inControls, int32_t degree, Real fraction, std::vector<Vector<N, Real>>& outControls) { int32_t numInControls = static_cast<int32_t>(inControls.size()); LogAssert(numInControls >= 2 && 1 <= degree && degree < numInControls, "Invalid input."); // Clamp the number of control points to [degree+1,quantity-1]. int32_t numOutControls = static_cast<int32_t>(fraction * numInControls); if (numOutControls >= numInControls) { outControls = inControls; return; } if (numOutControls < degree + 1) { numOutControls = degree + 1; } // Allocate output control points. outControls.resize(numOutControls); // Set up basis function parameters. Function 0 corresponds to // the output curve. Function 1 corresponds to the input curve. mDegree = degree; mQuantity[0] = numOutControls; mQuantity[1] = numInControls; for (int32_t j = 0; j <= 1; ++j) { mNumKnots[j] = mQuantity[j] + mDegree + 1; mKnot[j].resize(mNumKnots[j]); int32_t i; for (i = 0; i <= mDegree; ++i) { mKnot[j][i] = (Real)0; } Real denom = static_cast<Real>(mQuantity[j]) - static_cast<Real>(mDegree); Real factor = (Real)1 / denom; for (/**/; i < mQuantity[j]; ++i) { mKnot[j][i] = (static_cast<size_t>(i) - mDegree) * factor; } for (/**/; i < mNumKnots[j]; ++i) { mKnot[j][i] = (Real)1; } } // Construct matrix A (depends only on the output basis function). Real value, tmin, tmax; int32_t i0, i1; mBasis[0] = 0; mBasis[1] = 0; std::function<Real(Real)> integrand = [this](Real t) { Real value0 = F(mBasis[0], mIndex[0], mDegree, t); Real value1 = F(mBasis[1], mIndex[1], mDegree, t); Real result = value0 * value1; return result; }; BandedMatrix<Real> A(mQuantity[0], mDegree, mDegree); for (i0 = 0; i0 < mQuantity[0]; ++i0) { mIndex[0] = i0; tmax = MaxSupport(0, i0); for (i1 = i0; i1 <= i0 + mDegree && i1 < mQuantity[0]; ++i1) { mIndex[1] = i1; tmin = MinSupport(0, i1); value = Integration<Real>::Romberg(8, tmin, tmax, integrand); A(i0, i1) = value; A(i1, i0) = value; } } // Construct A^{-1}. TODO: This is inefficient. Use an iterative // scheme to invert A? GMatrix<Real> invA(mQuantity[0], mQuantity[0]); bool invertible = A.template ComputeInverse<true>(&invA[0]); LogAssert(invertible, "Failed to invert matrix."); // Construct B (depends on both input and output basis functions). mBasis[1] = 1; GMatrix<Real> B(mQuantity[0], mQuantity[1]); FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>> query; for (i0 = 0; i0 < mQuantity[0]; ++i0) { mIndex[0] = i0; Real tmin0 = MinSupport(0, i0); Real tmax0 = MaxSupport(0, i0); for (i1 = 0; i1 < mQuantity[1]; ++i1) { mIndex[1] = i1; Real tmin1 = MinSupport(1, i1); Real tmax1 = MaxSupport(1, i1); std::array<Real, 2> interval0 = { tmin0, tmax0 }; std::array<Real, 2> interval1 = { tmin1, tmax1 }; auto result = query(interval0, interval1); if (result.numIntersections == 2) { value = Integration<Real>::Romberg(8, result.overlap[0], result.overlap[1], integrand); B(i0, i1) = value; } else { B(i0, i1) = (Real)0; } } } // Construct A^{-1}*B. GMatrix<Real> prod = invA * B; // Construct the control points for the least-squares curve. std::fill(outControls.begin(), outControls.end(), Vector<N, Real>::Zero()); for (i0 = 0; i0 < mQuantity[0]; ++i0) { for (i1 = 0; i1 < mQuantity[1]; ++i1) { outControls[i0] += inControls[i1] * prod(i0, i1); } } } private: inline Real MinSupport(int32_t basis, int32_t i) const { return mKnot[basis][i]; } inline Real MaxSupport(int32_t basis, int32_t i) const { return mKnot[basis][static_cast<size_t>(i) + 1 + static_cast<size_t>(mDegree)]; } Real F(int32_t basis, int32_t i, int32_t j, Real t) { if (j > 0) { Real result = (Real)0; Real denom = mKnot[basis][static_cast<size_t>(i) + static_cast<size_t>(j)] - mKnot[basis][i]; if (denom > (Real)0) { result += (t - mKnot[basis][i]) * F(basis, i, j - 1, t) / denom; } denom = mKnot[basis][static_cast<size_t>(i) + static_cast<size_t>(j) + 1] - mKnot[basis][static_cast<size_t>(i) + 1]; if (denom > (Real)0) { result += (mKnot[basis][static_cast<size_t>(i) + static_cast<size_t>(j) + 1] - t) * F(basis, i + 1, j - 1, t) / denom; } return result; } if (mKnot[basis][i] <= t && t < mKnot[basis][static_cast<size_t>(i) + 1]) { return (Real)1; } else { return (Real)0; } } int32_t mDegree; std::array<int32_t, 2> mQuantity; std::array<int32_t, 2> mNumKnots; // N+D+2 std::array<std::vector<Real>, 2> mKnot; // For the integration-based least-squares fitting. std::array<int32_t, 2> mBasis, mIndex; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrAlignedBox3OrientedBox3.h
.h
12,454
333
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/AlignedBox.h> #include <Mathematics/OrientedBox.h> #include <Mathematics/Vector3.h> // The queries consider the box to be a solid. // // The test-intersection query uses the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The set of potential separating directions includes the 3 face normals of // box0, the 3 face normals of box1, and 9 directions, each of which is the // cross product of an edge of box0 and and an edge of box1. // // The separating axes involving cross products of edges has numerical // robustness problems when the two edges are nearly parallel. The cross // product of the edges is nearly the zero vector, so normalization of the // cross product may produce unit-length directions that are not close to the // true direction. Such a pair of edges occurs when a box0 face normal N0 and // a box1 face normal N1 are nearly parallel. In this case, you may skip the // edge-edge directions, which is equivalent to projecting the boxes onto the // plane with normal N0 and applying a 2D separating axis test. The ability // to do so involves choosing a small nonnegative epsilon. It is used to // determine whether two face normals, one from each box, are nearly parallel: // |Dot(N0,N1)| >= 1 - epsilon. If the epsilon input to the operator()(...) // function is negative, it is clamped to zero. // // The pair of integers 'separating', say, (i0,i1), identifies the axis that // reported separation; there may be more than one but only one is reported. // If the separating axis is a face normal N[i0] of the aligned box0 in // dimension i0, then (i0,-1) is returned. If the axis is a face normal // box1.Axis[i1], then (-1,i1) is returned. If the axis is a cross product // of edges, Cross(N[i0],box1.Axis[i1]), then (i0,i1) is returned. If // 'intersect' is true, the separating[] values are invalid because there is // no separation. namespace gte { template <typename T> class TIQuery<T, AlignedBox3<T>, OrientedBox3<T>> { public: struct Result { Result() : intersect(false), separating{ 0, 0 } { } bool intersect; std::array<int32_t, 2> separating; }; Result operator()(AlignedBox3<T> const& box0, OrientedBox3<T> const& box1, T epsilon = static_cast<T>(0)) { Result result{}; // Get the centered form of the aligned box. The axes are // implicitly A0[0] = (1,0,0), A0[1] = (0,1,0) and // A0[2] = (0,0,1). Vector3<T> C0{}, E0{}; box0.GetCenteredForm(C0, E0); // Convenience variables. Vector3<T> const& C1 = box1.center; Vector3<T> const* A1 = &box1.axis[0]; Vector3<T> const& E1 = box1.extent; epsilon = std::max(epsilon, static_cast<T>(0)); T const cutoff = static_cast<T>(1) - epsilon; bool existsParallelPair = false; // Compute the difference of box centers. Vector3<T> D = C1 - C0; // dot01[i][j] = Dot(A0[i],A1[j]) = A1[j][i] std::array<std::array<T, 3>, 3> dot01{}; // |dot01[i][j]| std::array<std::array<T, 3>, 3> absDot01{}; // interval radii and distance between centers T r0{}, r1{}, r{}; // r0 + r1 T r01{}; // Test for separation on the axis C0 + t*A0[0]. for (size_t i = 0; i < 3; ++i) { dot01[0][i] = A1[i][0]; absDot01[0][i] = std::fabs(A1[i][0]); if (absDot01[0][i] >= cutoff) { existsParallelPair = true; } } r = std::fabs(D[0]); r1 = E1[0] * absDot01[0][0] + E1[1] * absDot01[0][1] + E1[2] * absDot01[0][2]; r01 = E0[0] + r1; if (r > r01) { result.intersect = false; result.separating[0] = 0; result.separating[1] = -1; return result; } // Test for separation on the axis C0 + t*A0[1]. for (size_t i = 0; i < 3; ++i) { dot01[1][i] = A1[i][1]; absDot01[1][i] = std::fabs(A1[i][1]); if (absDot01[1][i] >= cutoff) { existsParallelPair = true; } } r = std::fabs(D[1]); r1 = E1[0] * absDot01[1][0] + E1[1] * absDot01[1][1] + E1[2] * absDot01[1][2]; r01 = E0[1] + r1; if (r > r01) { result.intersect = false; result.separating[0] = 1; result.separating[1] = -1; return result; } // Test for separation on the axis C0 + t*A0[2]. for (size_t i = 0; i < 3; ++i) { dot01[2][i] = A1[i][2]; absDot01[2][i] = std::fabs(A1[i][2]); if (absDot01[2][i] >= cutoff) { existsParallelPair = true; } } r = std::fabs(D[2]); r1 = E1[0] * absDot01[2][0] + E1[1] * absDot01[2][1] + E1[2] * absDot01[2][2]; r01 = E0[2] + r1; if (r > r01) { result.intersect = false; result.separating[0] = 2; result.separating[1] = -1; return result; } // Test for separation on the axis C0 + t*A1[0]. r = std::fabs(Dot(D, A1[0])); r0 = E0[0] * absDot01[0][0] + E0[1] * absDot01[1][0] + E0[2] * absDot01[2][0]; r01 = r0 + E1[0]; if (r > r01) { result.intersect = false; result.separating[0] = -1; result.separating[1] = 0; return result; } // Test for separation on the axis C0 + t*A1[1]. r = std::fabs(Dot(D, A1[1])); r0 = E0[0] * absDot01[0][1] + E0[1] * absDot01[1][1] + E0[2] * absDot01[2][1]; r01 = r0 + E1[1]; if (r > r01) { result.intersect = false; result.separating[0] = -1; result.separating[1] = 1; return result; } // Test for separation on the axis C0 + t*A1[2]. r = std::fabs(Dot(D, A1[2])); r0 = E0[0] * absDot01[0][2] + E0[1] * absDot01[1][2] + E0[2] * absDot01[2][2]; r01 = r0 + E1[2]; if (r > r01) { result.intersect = false; result.separating[0] = -1; result.separating[1] = 2; return result; } // At least one pair of box axes was parallel, so the separation is // effectively in 2D. The edge-edge axes do not need to be tested. if (existsParallelPair) { // The result.separating[] values are invalid because there is // no separation. result.intersect = true; return result; } // Test for separation on the axis C0 + t*A0[0]xA1[0]. r = std::fabs(D[2] * dot01[1][0] - D[1] * dot01[2][0]); r0 = E0[1] * absDot01[2][0] + E0[2] * absDot01[1][0]; r1 = E1[1] * absDot01[0][2] + E1[2] * absDot01[0][1]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 0; result.separating[1] = 0; return result; } // Test for separation on the axis C0 + t*A0[0]xA1[1]. r = std::fabs(D[2] * dot01[1][1] - D[1] * dot01[2][1]); r0 = E0[1] * absDot01[2][1] + E0[2] * absDot01[1][1]; r1 = E1[0] * absDot01[0][2] + E1[2] * absDot01[0][0]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 0; result.separating[1] = 1; return result; } // Test for separation on the axis C0 + t*A0[0]xA1[2]. r = std::fabs(D[2] * dot01[1][2] - D[1] * dot01[2][2]); r0 = E0[1] * absDot01[2][2] + E0[2] * absDot01[1][2]; r1 = E1[0] * absDot01[0][1] + E1[1] * absDot01[0][0]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 0; result.separating[1] = 2; return result; } // Test for separation on the axis C0 + t*A0[1]xA1[0]. r = std::fabs(D[0] * dot01[2][0] - D[2] * dot01[0][0]); r0 = E0[0] * absDot01[2][0] + E0[2] * absDot01[0][0]; r1 = E1[1] * absDot01[1][2] + E1[2] * absDot01[1][1]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 1; result.separating[1] = 0; return result; } // Test for separation on the axis C0 + t*A0[1]xA1[1]. r = std::fabs(D[0] * dot01[2][1] - D[2] * dot01[0][1]); r0 = E0[0] * absDot01[2][1] + E0[2] * absDot01[0][1]; r1 = E1[0] * absDot01[1][2] + E1[2] * absDot01[1][0]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 1; result.separating[1] = 1; return result; } // Test for separation on the axis C0 + t*A0[1]xA1[2]. r = std::fabs(D[0] * dot01[2][2] - D[2] * dot01[0][2]); r0 = E0[0] * absDot01[2][2] + E0[2] * absDot01[0][2]; r1 = E1[0] * absDot01[1][1] + E1[1] * absDot01[1][0]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 1; result.separating[1] = 2; return result; } // Test for separation on the axis C0 + t*A0[2]xA1[0]. r = std::fabs(D[1] * dot01[0][0] - D[0] * dot01[1][0]); r0 = E0[0] * absDot01[1][0] + E0[1] * absDot01[0][0]; r1 = E1[1] * absDot01[2][2] + E1[2] * absDot01[2][1]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 2; result.separating[1] = 0; return result; } // Test for separation on the axis C0 + t*A0[2]xA1[1]. r = std::fabs(D[1] * dot01[0][1] - D[0] * dot01[1][1]); r0 = E0[0] * absDot01[1][1] + E0[1] * absDot01[0][1]; r1 = E1[0] * absDot01[2][2] + E1[2] * absDot01[2][0]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 2; result.separating[1] = 1; return result; } // Test for separation on the axis C0 + t*A0[2]xA1[2]. r = std::fabs(D[1] * dot01[0][2] - D[0] * dot01[1][2]); r0 = E0[0] * absDot01[1][2] + E0[1] * absDot01[0][2]; r1 = E1[0] * absDot01[2][1] + E1[1] * absDot01[2][0]; r01 = r0 + r1; if (r > r01) { result.intersect = false; result.separating[0] = 2; result.separating[1] = 2; return result; } // The result.separating[] values are invalid because there is no // separation. result.intersect = true; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContAlignedBox2Arc2.h
.h
2,006
65
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.5.2022.08.23 #pragma once #include <Mathematics/AlignedBox.h> #include <Mathematics/Arc2.h> // Compute the smallest-area axis-aligned box containing an arc. Let the arc // have endpoints E[0] and E[1] and live on a circle with center C and radius // r. The extreme circle points in the axis directions are P[0] = C+(r,0), // P[1] = C-(r,0), P[2] = C+(0,r) and P[3] = C-(0,r). The box is supported by // the E0 and E1 and points P[i] that are on the arc. namespace gte { template <typename T> bool GetContainer(Arc2<T> const& arc, AlignedBox2<T>& box) { // Store the arc endpoints. int32_t numPoints = 2; std::array<Vector2<T>, 6> points{}; points[0] = arc.end[0]; points[1] = arc.end[1]; // Store the circle points that are on the arc. points[numPoints] = { arc.center[0] + arc.radius, arc.center[1] }; if (arc.Contains(points[numPoints])) { ++numPoints; } points[numPoints] = { arc.center[0] - arc.radius, arc.center[1] }; if (arc.Contains(points[numPoints])) { ++numPoints; } points[numPoints] = { arc.center[0], arc.center[1] + arc.radius }; if (arc.Contains(points[numPoints])) { ++numPoints; } points[numPoints] = { arc.center[0], arc.center[1] - arc.radius }; if (arc.Contains(points[numPoints])) { ++numPoints; } if (0 < numPoints && numPoints <= 6) { // Compute the aligned bounding box. return ComputeExtremes(numPoints, points.data(), box.min, box.max); } // Code execution should never reach this point. return false; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OdeRungeKutta4.h
.h
2,119
59
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/OdeSolver.h> // The TVector template parameter allows you to create solvers with // Vector<N,Real> when the dimension N is known at compile time or // GVector<Real> when the dimension N is known at run time. Both classes // have 'int32_t GetSize() const' that allow OdeSolver-derived classes to query // for the dimension. namespace gte { template <typename Real, typename TVector> class OdeRungeKutta4 : public OdeSolver<Real, TVector> { public: // Construction and destruction. virtual ~OdeRungeKutta4() = default; OdeRungeKutta4(Real tDelta, std::function<TVector(Real, TVector const&)> const& F) : OdeSolver<Real, TVector>(tDelta, F) { } // Estimate x(t + tDelta) from x(t) using dx/dt = F(t,x). You may // allow xIn and xOut to be the same object. virtual void Update(Real tIn, TVector const& xIn, Real& tOut, TVector& xOut) override { // Compute the first step. Real halfTDelta = (Real)0.5 * this->mTDelta; TVector fTemp1 = this->mFunction(tIn, xIn); TVector xTemp = xIn + halfTDelta * fTemp1; // Compute the second step. Real halfT = tIn + halfTDelta; TVector fTemp2 = this->mFunction(halfT, xTemp); xTemp = xIn + halfTDelta * fTemp2; // Compute the third step. TVector fTemp3 = this->mFunction(halfT, xTemp); xTemp = xIn + this->mTDelta * fTemp3; // Compute the fourth step. Real sixthTDelta = this->mTDelta / (Real)6; tOut = tIn + this->mTDelta; TVector fTemp4 = this->mFunction(tOut, xTemp); xOut = xIn + sixthTDelta * (fTemp1 + (Real)2 * (fTemp2 + fTemp3) + fTemp4); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLine3CanonicalBox3.h
.h
20,019
498
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Line.h> #include <Mathematics/CanonicalBox.h> #include <Mathematics/Vector3.h> // Compute the distance between a line and a canonical box in 3D. // // The line is P + t * D, where D is not required to be unit length. // // The canonical box has center at the origin and is aligned with the // coordinate axes. The extents are E = (e[0],e[1],e[2]). A box point is // Y = (y[0],y[1],y[2]) with |y[i]| <= e[i] for all i. // // The closest point on the line is stored in closest[0] with parameter t. The // closest point on the box is stored in closest[1]. When there are infinitely // many choices for the pair of closest points, only one of them is returned. // // The DoQueryND functions are described in Section 10.9.4 Linear Component // to Oriented Bounding Box of // Geometric Tools for Computer Graphics, // Philip J. Schneider and David H. Eberly, // Morgan Kaufmnn, San Francisco CA, 2002 // // TODO: The code in DistLine2AlignedBox2.h effectively uses the same, // although in 2D. That code is cleaner than the 3D code here. Clean up the // 3D code. namespace gte { template <typename T> class DCPQuery<T, Line3<T>, CanonicalBox3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter(static_cast<T>(0)), closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; T parameter; std::array<Vector3<T>, 2> closest; }; Result operator()(Line3<T> const& line, CanonicalBox3<T> const& box) { Result result{}; // Copies are made so that we can transform the line direction to // the first octant (nonnegative components) using reflections. T const zero = static_cast<T>(0); Vector3<T> origin = line.origin; Vector3<T> direction = line.direction; std::array<bool, 3> reflect{ false, false, false }; for (int32_t i = 0; i < 3; ++i) { if (direction[i] < zero) { origin[i] = -origin[i]; direction[i] = -direction[i]; reflect[i] = true; } } // Compute the line-box distance and closest points. The DoQueryND // calls compute result.parameter and update result.sqrDistance. // The result.distance is computed after the specialized queries. // The result.closest[] points are computed afterwards. result.sqrDistance = zero; result.parameter = zero; if (direction[0] > zero) { if (direction[1] > zero) { if (direction[2] > zero) // (+,+,+) { DoQuery3D(origin, direction, box.extent, result); } else // (+,+,0) { DoQuery2D(0, 1, 2, origin, direction, box.extent, result); } } else { if (direction[2] > zero) // (+,0,+) { DoQuery2D(0, 2, 1, origin, direction, box.extent, result); } else // (+,0,0) { DoQuery1D(0, 1, 2, origin, direction, box.extent, result); } } } else { if (direction[1] > zero) { if (direction[2] > zero) // (0,+,+) { DoQuery2D(1, 2, 0, origin, direction, box.extent, result); } else // (0,+,0) { DoQuery1D(1, 0, 2, origin, direction, box.extent, result); } } else { if (direction[2] > zero) // (0,0,+) { DoQuery1D(2, 0, 1, origin, direction, box.extent, result); } else // (0,0,0) { DoQuery0D(origin, box.extent, result); } } } // Undo the reflections applied previously. for (int32_t i = 0; i < 3; ++i) { if (reflect[i]) { origin[i] = -origin[i]; } } result.distance = std::sqrt(result.sqrDistance); // Compute the closest point on the line. result.closest[0] = line.origin + result.parameter * line.direction; // Compute the closest point on the box. The original 'origin' is // modified by the DoQueryND functions to compute the closest // point. result.closest[1] = origin; return result; } private: static void Face(int32_t i0, int32_t i1, int32_t i2, Vector3<T>& origin, Vector3<T> const& direction, Vector3<T> const& PmE, Vector3<T> const& extent, Result& result) { T const zero = static_cast<T>(0); T const two = static_cast<T>(2); Vector3<T> PpE = origin + extent; if (direction[i0] * PpE[i1] >= direction[i1] * PmE[i0]) { if (direction[i0] * PpE[i2] >= direction[i2] * PmE[i0]) { // v[i1] >= -e[i1], v[i2] >= -e[i2] (distance = 0) origin[i0] = extent[i0]; origin[i1] -= direction[i1] * PmE[i0] / direction[i0]; origin[i2] -= direction[i2] * PmE[i0] / direction[i0]; result.parameter = -PmE[i0] / direction[i0]; } else { // v[i1] >= -e[i1], v[i2] < -e[i2] T lenSqr = direction[i0] * direction[i0] + direction[i2] * direction[i2]; T tmp = lenSqr * PpE[i1] - direction[i1] * (direction[i0] * PmE[i0] + direction[i2] * PpE[i2]); if (tmp <= two * lenSqr * extent[i1]) { T t = tmp / lenSqr; lenSqr += direction[i1] * direction[i1]; tmp = PpE[i1] - t; T delta = direction[i0] * PmE[i0] + direction[i1] * tmp + direction[i2] * PpE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + tmp * tmp + PpE[i2] * PpE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = t - extent[i1]; origin[i2] = -extent[i2]; } else { lenSqr += direction[i1] * direction[i1]; T delta = direction[i0] * PmE[i0] + direction[i1] * PmE[i1] + direction[i2] * PpE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PmE[i1] * PmE[i1] + PpE[i2] * PpE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = extent[i1]; origin[i2] = -extent[i2]; } } } else { if (direction[i0] * PpE[i2] >= direction[i2] * PmE[i0]) { // v[i1] < -e[i1], v[i2] >= -e[i2] T lenSqr = direction[i0] * direction[i0] + direction[i1] * direction[i1]; T tmp = lenSqr * PpE[i2] - direction[i2] * (direction[i0] * PmE[i0] + direction[i1] * PpE[i1]); if (tmp <= two * lenSqr * extent[i2]) { T t = tmp / lenSqr; lenSqr += direction[i2] * direction[i2]; tmp = PpE[i2] - t; T delta = direction[i0] * PmE[i0] + direction[i1] * PpE[i1] + direction[i2] * tmp; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PpE[i1] * PpE[i1] + tmp * tmp + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = -extent[i1]; origin[i2] = t - extent[i2]; } else { lenSqr += direction[i2] * direction[i2]; T delta = direction[i0] * PmE[i0] + direction[i1] * PpE[i1] + direction[i2] * PmE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PpE[i1] * PpE[i1] + PmE[i2] * PmE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = -extent[i1]; origin[i2] = extent[i2]; } } else { // v[i1] < -e[i1], v[i2] < -e[i2] T lenSqr = direction[i0] * direction[i0] + direction[i2] * direction[i2]; T tmp = lenSqr * PpE[i1] - direction[i1] * (direction[i0] * PmE[i0] + direction[i2] * PpE[i2]); if (tmp >= zero) { // v[i1]-edge is closest if (tmp <= two * lenSqr * extent[i1]) { T t = tmp / lenSqr; lenSqr += direction[i1] * direction[i1]; tmp = PpE[i1] - t; T delta = direction[i0] * PmE[i0] + direction[i1] * tmp + direction[i2] * PpE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + tmp * tmp + PpE[i2] * PpE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = t - extent[i1]; origin[i2] = -extent[i2]; } else { lenSqr += direction[i1] * direction[i1]; T delta = direction[i0] * PmE[i0] + direction[i1] * PmE[i1] + direction[i2] * PpE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PmE[i1] * PmE[i1] + PpE[i2] * PpE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = extent[i1]; origin[i2] = -extent[i2]; } return; } lenSqr = direction[i0] * direction[i0] + direction[i1] * direction[i1]; tmp = lenSqr * PpE[i2] - direction[i2] * (direction[i0] * PmE[i0] + direction[i1] * PpE[i1]); if (tmp >= zero) { // v[i2]-edge is closest if (tmp <= two * lenSqr * extent[i2]) { T t = tmp / lenSqr; lenSqr += direction[i2] * direction[i2]; tmp = PpE[i2] - t; T delta = direction[i0] * PmE[i0] + direction[i1] * PpE[i1] + direction[i2] * tmp; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PpE[i1] * PpE[i1] + tmp * tmp + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = -extent[i1]; origin[i2] = t - extent[i2]; } else { lenSqr += direction[i2] * direction[i2]; T delta = direction[i0] * PmE[i0] + direction[i1] * PpE[i1] + direction[i2] * PmE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PpE[i1] * PpE[i1] + PmE[i2] * PmE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = -extent[i1]; origin[i2] = extent[i2]; } return; } // (v[i1],v[i2])-corner is closest lenSqr += direction[i2] * direction[i2]; T delta = direction[i0] * PmE[i0] + direction[i1] * PpE[i1] + direction[i2] * PpE[i2]; result.parameter = -delta / lenSqr; result.sqrDistance += PmE[i0] * PmE[i0] + PpE[i1] * PpE[i1] + PpE[i2] * PpE[i2] + delta * result.parameter; origin[i0] = extent[i0]; origin[i1] = -extent[i1]; origin[i2] = -extent[i2]; } } } static void DoQuery3D(Vector3<T>& origin, Vector3<T> const& direction, Vector3<T> const& extent, Result& result) { Vector3<T> PmE = origin - extent; T prodDxPy = direction[0] * PmE[1]; T prodDyPx = direction[1] * PmE[0]; if (prodDyPx >= prodDxPy) { T prodDzPx = direction[2] * PmE[0]; T prodDxPz = direction[0] * PmE[2]; if (prodDzPx >= prodDxPz) { // line intersects x = e0 Face(0, 1, 2, origin, direction, PmE, extent, result); } else { // line intersects z = e2 Face(2, 0, 1, origin, direction, PmE, extent, result); } } else { T prodDzPy = direction[2] * PmE[1]; T prodDyPz = direction[1] * PmE[2]; if (prodDzPy >= prodDyPz) { // line intersects y = e1 Face(1, 2, 0, origin, direction, PmE, extent, result); } else { // line intersects z = e2 Face(2, 0, 1, origin, direction, PmE, extent, result); } } } static void DoQuery2D(int32_t i0, int32_t i1, int32_t i2, Vector3<T>& origin, Vector3<T> const& direction, Vector3<T> const& extent, Result& result) { T const zero = static_cast<T>(0); T PmE0 = origin[i0] - extent[i0]; T PmE1 = origin[i1] - extent[i1]; T prod0 = direction[i1] * PmE0; T prod1 = direction[i0] * PmE1; if (prod0 >= prod1) { // line intersects P[i0] = e[i0] origin[i0] = extent[i0]; T PpE1 = origin[i1] + extent[i1]; T delta = prod0 - direction[i0] * PpE1; if (delta >= zero) { T lenSqr = direction[i0] * direction[i0] + direction[i1] * direction[i1]; result.sqrDistance += delta * delta / lenSqr; origin[i1] = -extent[i1]; result.parameter = -(direction[i0] * PmE0 + direction[i1] * PpE1) / lenSqr; } else { origin[i1] -= prod0 / direction[i0]; result.parameter = -PmE0 / direction[i0]; } } else { // line intersects P[i1] = e[i1] origin[i1] = extent[i1]; T PpE0 = origin[i0] + extent[i0]; T delta = prod1 - direction[i1] * PpE0; if (delta >= zero) { T lenSqr = direction[i0] * direction[i0] + direction[i1] * direction[i1]; result.sqrDistance += delta * delta / lenSqr; origin[i0] = -extent[i0]; result.parameter = -(direction[i0] * PpE0 + direction[i1] * PmE1) / lenSqr; } else { origin[i0] -= prod1 / direction[i1]; result.parameter = -PmE1 / direction[i1]; } } if (origin[i2] < -extent[i2]) { T delta = origin[i2] + extent[i2]; result.sqrDistance += delta * delta; origin[i2] = -extent[i2]; } else if (origin[i2] > extent[i2]) { T delta = origin[i2] - extent[i2]; result.sqrDistance += delta * delta; origin[i2] = extent[i2]; } } static void DoQuery1D(int32_t i0, int32_t i1, int32_t i2, Vector3<T>& origin, Vector3<T> const& direction, Vector3<T> const& extent, Result& result) { result.parameter = (extent[i0] - origin[i0]) / direction[i0]; origin[i0] = extent[i0]; for (auto i : { i1, i2 }) { if (origin[i] < -extent[i]) { T delta = origin[i] + extent[i]; result.sqrDistance += delta * delta; origin[i] = -extent[i]; } else if (origin[i] > extent[i]) { T delta = origin[i] - extent[i]; result.sqrDistance += delta * delta; origin[i] = extent[i]; } } } static void DoQuery0D(Vector3<T>& origin, Vector3<T> const& extent, Result& result) { for (int32_t i = 0; i < 3; ++i) { if (origin[i] < -extent[i]) { T delta = origin[i] + extent[i]; result.sqrDistance += delta * delta; origin[i] = -extent[i]; } else if (origin[i] > extent[i]) { T delta = origin[i] - extent[i]; result.sqrDistance += delta * delta; origin[i] = extent[i]; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointAlignedBox.h
.h
2,203
67
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistPointCanonicalBox.h> #include <Mathematics/AlignedBox.h> // Compute the distance from a point to a solid aligned box in nD. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The input point is stored in closest[0]. The closest point on the box is // stored in closest[1]. When there are infinitely many choices for the pair // of closest points, only one of them is returned. namespace gte { template <int32_t N, typename T> class DCPQuery<T, Vector<N, T>, AlignedBox<N, T>> { public: using PCQuery = DCPQuery<T, Vector<N, T>, CanonicalBox<N, T>>; using Result = typename PCQuery::Result; Result operator()(Vector<N, T> const& point, AlignedBox<N, T> const& box) { Result result{}; // Translate the point and box so that the box has center at the // origin. Vector<N, T> boxCenter{}; CanonicalBox<N, T> cbox{}; box.GetCenteredForm(boxCenter, cbox.extent); Vector<N, T> xfrmPoint = point - boxCenter; // The query computes 'output' relative to the box with center // at the origin. PCQuery pcQuery{}; result = pcQuery(xfrmPoint, cbox); // Store the input point. result.closest[0] = point; // Translate the closest box point to the original coordinates. result.closest[1] += boxCenter; return result; } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPPointAlignedBox = DCPQuery<T, Vector<N, T>, AlignedBox<N, T>>; template <typename T> using DCPPoint2AlignedBox2 = DCPPointAlignedBox<2, T>; template <typename T> using DCPPoint3AlignedBox3 = DCPPointAlignedBox<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ThreadSafeMap.h
.h
3,124
132
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <map> #include <mutex> #include <vector> namespace gte { template <typename Key, typename Value> class ThreadSafeMap { public: // Construction and destruction. ThreadSafeMap() = default; virtual ~ThreadSafeMap() = default; // All the operations are thread-safe. bool HasElements() const { bool hasElements; mMutex.lock(); { hasElements = (mMap.size() > 0); } mMutex.unlock(); return hasElements; } bool Exists(Key key) const { bool exists; mMutex.lock(); { exists = (mMap.find(key) != mMap.end()); } mMutex.unlock(); return exists; } void Insert(Key key, Value value) { mMutex.lock(); { mMap[key] = value; } mMutex.unlock(); } bool Remove(Key key, Value& value) { bool exists; mMutex.lock(); { auto iter = mMap.find(key); if (iter != mMap.end()) { value = iter->second; mMap.erase(iter); exists = true; } else { exists = false; } } mMutex.unlock(); return exists; } void RemoveAll() { mMutex.lock(); { mMap.clear(); } mMutex.unlock(); } bool Get(Key key, Value& value) const { bool exists; mMutex.lock(); { auto iter = mMap.find(key); if (iter != mMap.end()) { value = iter->second; exists = true; } else { exists = false; } } mMutex.unlock(); return exists; } void GatherAll(std::vector<Value>& values) const { mMutex.lock(); { if (mMap.size() > 0) { values.resize(mMap.size()); auto viter = values.begin(); for (auto const& m : mMap) { *viter++ = m.second; } } else { values.clear(); } } mMutex.unlock(); } protected: std::map<Key, Value> mMap; mutable std::mutex mMutex; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2Ray2.h
.h
5,593
164
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.03.25 #pragma once #include <Mathematics/IntrLine2Line2.h> #include <Mathematics/Ray.h> namespace gte { template <typename T> class TIQuery<T, Line2<T>, Ray2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0) { } // If the line and ray do not intersect, // intersect = false // numIntersections = 0 // // If the line and ray intersect in a single point, // intersect = true // numIntersections = 1 // // If the line and ray are collinear, // intersect = true // numIntersections = std::numeric_limits<int32_t>::max() bool intersect; int32_t numIntersections; }; Result operator()(Line2<T> const& line, Ray2<T> const& ray) { Result result{}; FIQuery<T, Line2<T>, Line2<T>> llQuery{}; auto llResult = llQuery(line, Line2<T>(ray.origin, ray.direction)); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the ray. if (llResult.line1Parameter[0] >= static_cast<T>(0)) { result.intersect = true; result.numIntersections = 1; } else { result.intersect = false; result.numIntersections = 0; } } else { result.intersect = llResult.intersect; result.numIntersections = llResult.numIntersections; } return result; } }; template <typename T> class FIQuery<T, Line2<T>, Ray2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), lineParameter{ static_cast<T>(0), static_cast<T>(0) }, rayParameter{ static_cast<T>(0), static_cast<T>(0) }, point(Vector2<T>::Zero()) { } // If the line and ray do not intersect, // intersect = false // numIntersections = 0 // lineParameter[] = { 0, 0 } // invalid // rayParameter[] = { 0, 0 } // invalid // point = { 0, 0 } // invalid // // If the line and ray intersect in a single point, the parameter // for line is s0 and the parameter for ray is s1 >= 0, // intersect = true // numIntersections = 1 // lineParameter = { s0, s0 } // rayParameter = { s1, s1 } // point = line.origin + s0 * line.direction // = ray.origin + s1 * ray.direction // // If the line and ray are collinear, let // maxT = std::numeric_limits<T>::max(), // intersect = true // numIntersections = std::numeric_limits<int32_t>::max() // lineParameter[] = { -maxT, +maxT } // rayParameter[] = { 0, +maxT } // point = { 0, 0 } // invalid bool intersect; int32_t numIntersections; std::array<T, 2> lineParameter; std::array<T, 2> rayParameter; Vector2<T> point; }; Result operator()(Line2<T> const& line, Ray2<T> const& ray) { Result result{}; FIQuery<T, Line2<T>, Line2<T>> llQuery{}; auto llResult = llQuery(line, Line2<T>(ray.origin, ray.direction)); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the ray. if (llResult.line1Parameter[0] >= static_cast<T>(0)) { result.intersect = true; result.numIntersections = 1; result.lineParameter[0] = llResult.line0Parameter[0]; result.lineParameter[1] = result.lineParameter[0]; result.rayParameter[0] = llResult.line1Parameter[0]; result.rayParameter[1] = result.rayParameter[0]; result.point = llResult.point; } else { result.intersect = false; result.numIntersections = 0; } } else if (llResult.numIntersections == std::numeric_limits<int32_t>::max()) { result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); T maxT = std::numeric_limits<T>::max(); result.lineParameter[0] = -maxT; result.lineParameter[1] = +maxT; result.rayParameter[0] = static_cast<T>(0); result.rayParameter[1] = +maxT; } else { result.intersect = false; result.numIntersections = 0; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MassSpringArbitrary.h
.h
4,244
122
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ParticleSystem.h> #include <set> namespace gte { template <int32_t N, typename Real> class MassSpringArbitrary : public ParticleSystem<N, Real> { public: // Construction and destruction. This class represents a set of M // masses that are connected by S springs with arbitrary topology. // The function SetSpring(...) should be called for each spring that // you want in the system. virtual ~MassSpringArbitrary() = default; MassSpringArbitrary(int32_t numParticles, int32_t numSprings, Real step) : ParticleSystem<N, Real>(numParticles, step), mSpring(numSprings, Spring()), mAdjacent(numParticles) { } struct Spring { Spring() : particle0(0), particle1(0), constant((Real)0), length((Real)0) { } int32_t particle0, particle1; Real constant, length; }; // Member access. inline int32_t GetNumSprings() const { return static_cast<int32_t>(mSpring.size()); } void SetSpring(int32_t index, Spring const& spring) { mSpring[index] = spring; mAdjacent[spring.particle0].insert(index); mAdjacent[spring.particle1].insert(index); } inline Spring const& GetSpring(int32_t index) const { return mSpring[index]; } // The default external force is zero. Derive a class from this one // to provide nonzero external forces such as gravity, wind, friction, // and so on. This function is called by Acceleration(...) to compute // the impulse F/m generated by the external force F. virtual Vector<N, Real> ExternalAcceleration(int32_t, Real, std::vector<Vector<N, Real>> const&, std::vector<Vector<N, Real>> const&) { return Vector<N, Real>::Zero(); } protected: // Callback for acceleration (ODE solver uses x" = F/m) applied to // particle i. The positions and velocities are not necessarily // mPosition and mVelocity, because the ODE solver evaluates the // impulse function at intermediate positions. virtual Vector<N, Real> Acceleration(int32_t i, Real time, std::vector<Vector<N, Real>> const& position, std::vector<Vector<N, Real>> const& velocity) { // Compute spring forces on position X[i]. The positions are not // necessarily mPosition, because the RK4 solver in ParticleSystem // evaluates the acceleration function at intermediate positions. Vector<N, Real> acceleration = ExternalAcceleration(i, time, position, velocity); for (auto adj : mAdjacent[i]) { // Process a spring connected to particle i. Spring const& spring = mSpring[adj]; Vector<N, Real> diff; if (i != spring.particle0) { diff = position[spring.particle0] - position[i]; } else { diff = position[spring.particle1] - position[i]; } Real ratio = spring.length / Length(diff); Vector<N, Real> force = spring.constant * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } return acceleration; } std::vector<Spring> mSpring; // Each particle has an associated array of spring indices for those // springs adjacent to the particle. The set elements are spring // indices, not indices of adjacent particles. std::vector<std::set<int32_t>> mAdjacent; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/LexicoArray2.h
.h
3,696
163
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <cstdint> namespace gte { // A template class to provide 2D array access that conforms to row-major // order (RowMajor = true) or column-major order (RowMajor = false). The template <bool RowMajor, typename Real, int32_t... Dimensions> class LexicoArray2 {}; // The array dimensions are known only at run time. template <typename Real> class LexicoArray2<true, Real> { public: LexicoArray2(int32_t numRows, int32_t numCols, Real* matrix) : mNumRows(numRows), mNumCols(numCols), mMatrix(matrix) { } inline int32_t GetNumRows() const { return mNumRows; } inline int32_t GetNumCols() const { return mNumCols; } inline Real& operator()(int32_t r, int32_t c) { return mMatrix[c + mNumCols * r]; } inline Real const& operator()(int32_t r, int32_t c) const { return mMatrix[c + mNumCols * r]; } private: int32_t mNumRows, mNumCols; Real* mMatrix; }; template <typename Real> class LexicoArray2<false, Real> { public: LexicoArray2(int32_t numRows, int32_t numCols, Real* matrix) : mNumRows(numRows), mNumCols(numCols), mMatrix(matrix) { } inline int32_t GetNumRows() const { return mNumRows; } inline int32_t GetNumCols() const { return mNumCols; } inline Real& operator()(int32_t r, int32_t c) { return mMatrix[r + mNumRows * c]; } inline Real const& operator()(int32_t r, int32_t c) const { return mMatrix[r + mNumRows * c]; } private: int32_t mNumRows, mNumCols; Real* mMatrix; }; // The array dimensions are known at compile time. template <typename Real, int32_t NumRows, int32_t NumCols> class LexicoArray2<true, Real, NumRows, NumCols> { public: LexicoArray2(Real* matrix) : mMatrix(matrix) { } inline int32_t GetNumRows() const { return NumRows; } inline int32_t GetNumCols() const { return NumCols; } inline Real& operator()(int32_t r, int32_t c) { return mMatrix[c + NumCols * r]; } inline Real const& operator()(int32_t r, int32_t c) const { return mMatrix[c + NumCols * r]; } private: Real* mMatrix; }; template <typename Real, int32_t NumRows, int32_t NumCols> class LexicoArray2<false, Real, NumRows, NumCols> { public: LexicoArray2(Real* matrix) : mMatrix(matrix) { } inline int32_t GetNumRows() const { return NumRows; } inline int32_t GetNumCols() const { return NumCols; } inline Real& operator()(int32_t r, int32_t c) { return mMatrix[r + NumRows * c]; } inline Real const& operator()(int32_t r, int32_t c) const { return mMatrix[r + NumRows * c]; } private: Real* mMatrix; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistTetrahedron3Tetrahedron3.h
.h
6,519
162
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.1.2022.02.06 #pragma once #include <Mathematics/DistTriangle3Triangle3.h> #include <Mathematics/ContTetrahedron3.h> #include <array> // Compute the distance between two solid tetrahedra in 3D. // // Each tetrahedron has vertices <V[0],V[1],V[2],V[3]>. A tetrahedron point // is X = sum_{i=0}^3 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^3 b[i] = 1. // // The closest point on tetra0 is stored in closest[0] with barycentric // coordinates relative to its vertices. The closest point on tetra1 is stored // in closest[1] with barycentric coordinates relative to its vertices. When // there are infinitely many choices for the pair of closest points, only one // pair is returned. namespace gte { template <typename T> class DCPQuery<T, Tetrahedron3<T>, Tetrahedron3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), barycentric0{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, barycentric1{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<T, 4> barycentric0; std::array<T, 4> barycentric1; std::array<Vector3<T>, 2> closest; }; Result operator()(Tetrahedron3<T> const& tetra0, Tetrahedron3<T> const& tetra1) { Result result{}; DCPQuery<T, Triangle3<T>, Triangle3<T>> ttQuery{}; typename DCPQuery<T, Triangle3<T>, Triangle3<T>>::Result ttResult{}; Triangle3<T> triangle{}; T const zero = static_cast<T>(0); T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; // Compute the distances between pairs of faces, each pair having // a face from tetra0 and a face from tetra1. bool foundZeroDistance = false; for (size_t face0 = 0; face0 < 4; ++face0) { Triangle3<T> triangle0{}; auto const& indices0 = Tetrahedron3<T>::GetFaceIndices(face0); for (size_t j = 0; j < 3; ++j) { triangle0.v[j] = tetra0.v[indices0[j]]; } for (size_t face1 = 0; face1 < 4; ++face1) { Triangle3<T> triangle1{}; auto const& indices1 = Tetrahedron3<T>::GetFaceIndices(face1); for (size_t j = 0; j < 3; ++j) { triangle1.v[j] = tetra1.v[indices1[j]]; } ttResult = ttQuery(triangle0, triangle1); if (ttResult.sqrDistance == zero) { result.distance = zero; result.sqrDistance = zero; result.closest[0] = ttResult.closest[0]; result.closest[1] = ttResult.closest[1]; foundZeroDistance = true; break; } if (result.sqrDistance == invalid || ttResult.sqrDistance < result.sqrDistance) { result.distance = ttResult.distance; result.sqrDistance = ttResult.sqrDistance; result.closest[0] = ttResult.closest[0]; result.closest[1] = ttResult.closest[1]; } } if (foundZeroDistance) { break; } } if (!foundZeroDistance) { // The tetrahedra are either nested or separated. Test // for containment of the centroids to decide which case. Vector3<T> centroid0 = tetra0.ComputeCentroid(); bool centroid0InTetra1 = InContainer(centroid0, tetra1); if (centroid0InTetra1) { // Tetra0 is nested inside tetra1. Choose the centroid // of tetra0 as the closest point for both tetrahedra. result.distance = zero; result.sqrDistance = zero; result.closest[0] = centroid0; result.closest[1] = centroid0; } Vector3<T> centroid1 = tetra1.ComputeCentroid(); bool centroid1InTetra0 = InContainer(centroid1, tetra0); if (centroid1InTetra0) { // Tetra1 is nested inside tetra0. Choose the centroid // of tetra1 as the closest point for both tetrahedra. result.distance = zero; result.sqrDistance = zero; result.closest[0] = centroid1; result.closest[1] = centroid1; } // With exact arithmetic, at this point the tetrahedra are // separated. The output object already contains the distance // information. However, with floating-point arithmetic, it // is possible that a tetrahedron with volume nearly zero is // close enough to the other tetrahedron yet separated, but // rounding errors make it appear that the nearly-zero-volume // tetrahedron has centroid inside the other tetrahedron. This // situation is trapped by the previous two if-blocks. } // Compute the barycentric coordinates of the closest points. (void)ComputeBarycentrics(result.closest[0], tetra0.v[0], tetra0.v[1], tetra0.v[2], tetra0.v[3], result.barycentric0); (void)ComputeBarycentrics(result.closest[1], tetra1.v[0], tetra1.v[1], tetra1.v[2], tetra1.v[3], result.barycentric1); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine3Sphere3.h
.h
4,238
129
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/TIQuery.h> #include <Mathematics/Vector3.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/Line.h> // The queries consider the sphere to be a solid. // // The sphere is (X-C)^T*(X-C)-r^2 = 0 and the line is X = P+t*D. Substitute // the line equation into the sphere equation to obtain a quadratic equation // Q(t) = t^2 + 2*a1*t + a0 = 0, where a1 = D^T*(P-C) and // a0 = (P-C)^T*(P-C)-r^2. The algorithm involves an analysis of the // real-valued roots of Q(t) for all real t. namespace gte { template <typename T> class TIQuery<T, Line3<T>, Sphere3<T>> { public: struct Result { Result() : intersect(false) { }; bool intersect; }; Result operator()(Line3<T> const& line, Sphere3<T> const& sphere) { Result result{}; Vector3<T> diff = line.origin - sphere.center; T a0 = Dot(diff, diff) - sphere.radius * sphere.radius; T a1 = Dot(line.direction, diff); // An intersection occurs when Q(t) has real roots. T discr = a1 * a1 - a0; result.intersect = (discr >= static_cast<T>(0)); return result; } }; template <typename T> class FIQuery<T, Line3<T>, Sphere3<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), parameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } bool intersect; size_t numIntersections; std::array<T, 2> parameter; std::array<Vector3<T>, 2> point; }; Result operator()(Line3<T> const& line, Sphere3<T> const& sphere) { Result result{}; DoQuery(line.origin, line.direction, sphere, result); if (result.intersect) { for (size_t i = 0; i < 2; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } } return result; } protected: // The caller must ensure that on entry, 'result' is default // constructed as if there is no intersection. If an intersection is // found, the 'result' values will be modified accordingly. void DoQuery(Vector3<T> const& lineOrigin, Vector3<T> const& lineDirection, Sphere3<T> const& sphere, Result& result) { Vector3<T> diff = lineOrigin - sphere.center; T a0 = Dot(diff, diff) - sphere.radius * sphere.radius; T a1 = Dot(lineDirection, diff); // Intersection occurs when Q(t) has real roots. T const zero = static_cast<T>(0); T discr = a1 * a1 - a0; if (discr > zero) { // The line intersects the sphere in 2 distinct points. result.intersect = true; result.numIntersections = 2; T root = std::sqrt(discr); result.parameter[0] = -a1 - root; result.parameter[1] = -a1 + root; } else if (discr == zero) { // The line is tangent to the sphere, so the intersection is // a single point. The parameter[1] value is set, because // callers will access the degenerate interval [-a1,-a1]. result.intersect = true; result.numIntersections = 1; result.parameter[0] = -a1; result.parameter[1] = result.parameter[0]; } // else: The line is outside the sphere, no intersection. } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistTriangle3Rectangle3.h
.h
5,172
131
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistSegment3Rectangle3.h> #include <Mathematics/DistSegment3Triangle3.h> // Compute the distance between a solid triangle and a solid rectangle in 3D. // // The triangle has vertices <V[0],V[1],V[2]>. A triangle point is // X = sum_{i=0}^2 b[i] * V[i], where 0 <= b[i] <= 1 for all i and // sum_{i=0}^2 b[i] = 1. // // The rectangle has center C, unit-length axis directions W[0] and W[1], and // extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i] // where |s[i]| <= e[i] for all i. // // The closest point on the triangle is stored in closest[0] with barycentric // coordinates (b[0],b[1],b[2]). The closest point on the rectangle is stoed // closest[1] with cartesian[] coordinates (s[0],s[1]). When there are // infinitely many choices for the pair of closest points, only one of them is // returned. // // TODO: Modify to support non-unit-length W[]. namespace gte { template <typename T> class DCPQuery<T, Triangle3<T>, Rectangle3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), barycentric{ static_cast<T>(0), static_cast<T>(0), static_cast<T>(0) }, cartesian{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<T, 3> barycentric; std::array<T, 2> cartesian; std::array<Vector3<T>, 2> closest; }; Result operator()(Triangle3<T> const& triangle, Rectangle3<T> const& rectangle) { Result result{}; DCPQuery<T, Segment3<T>, Triangle3<T>> stQuery{}; typename DCPQuery<T, Segment3<T>, Triangle3<T>>::Result stResult{}; DCPQuery<T, Segment3<T>, Rectangle3<T>> srQuery{}; typename DCPQuery<T, Segment3<T>, Rectangle3<T>>::Result srResult{}; Segment3<T> segment{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const negOne = static_cast<T>(-1); T const two = static_cast<T>(2); T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; std::array<T, 4> const sign{ negOne, one, negOne, one }; std::array<int32_t, 4> j0{ 0, 0, 1, 1 }; std::array<int32_t, 4> j1{ 1, 1, 0, 0 }; std::array<std::array<size_t, 2>, 4> const edges {{ // horizontal edges (y = -e1, +e1) { 0, 1 }, { 2, 3 }, // vertical edges (x = -e0, +e0) { 0, 2 }, { 1, 3 } }}; std::array<Vector3<T>, 4> vertices{}; // Compare edges of triangle to the interior of rectangle. for (size_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++) { segment.p[0] = triangle.v[i0]; segment.p[1] = triangle.v[i1]; srResult = srQuery(segment, rectangle); if (result.sqrDistance == invalid || srResult.sqrDistance < result.sqrDistance) { result.distance = srResult.distance; result.sqrDistance = srResult.sqrDistance; result.barycentric[i0] = one - srResult.parameter; result.barycentric[i1] = srResult.parameter; result.barycentric[i2] = zero; result.cartesian = srResult.cartesian; result.closest = srResult.closest; } } // Compare edges of rectangle to the interior of triangle. rectangle.GetVertices(vertices); for (size_t i = 0; i < 4; ++i) { auto const& edge = edges[i]; segment.p[0] = vertices[edge[0]]; segment.p[1] = vertices[edge[1]]; stResult = stQuery(segment, triangle); if (result.sqrDistance == invalid || stResult.sqrDistance < result.sqrDistance) { result.distance = stResult.distance; result.sqrDistance = stResult.sqrDistance; result.barycentric = stResult.barycentric; T const scale = two * stResult.parameter - one; result.cartesian[j0[i]] = scale * rectangle.extent[j0[i]]; result.cartesian[j1[i]] = sign[i] * rectangle.extent[j1[i]]; result.closest[0] = stResult.closest[1]; result.closest[1] = stResult.closest[0]; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContSphere3.h
.h
2,712
89
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector3.h> #include <vector> namespace gte { // Compute the smallest bounding sphere whose center is the average of // the input points. template <typename Real> bool GetContainer(int32_t numPoints, Vector3<Real> const* points, Sphere3<Real>& sphere) { sphere.center = points[0]; for (int32_t i = 1; i < numPoints; ++i) { sphere.center += points[i]; } sphere.center /= (Real)numPoints; sphere.radius = (Real)0; for (int32_t i = 0; i < numPoints; ++i) { Vector3<Real> diff = points[i] - sphere.center; Real radiusSqr = Dot(diff, diff); if (radiusSqr > sphere.radius) { sphere.radius = radiusSqr; } } sphere.radius = std::sqrt(sphere.radius); return true; } template <typename Real> bool GetContainer(std::vector<Vector3<Real>> const& points, Sphere3<Real>& sphere) { return GetContainer(static_cast<int32_t>(points.size()), points.data(), sphere); } // Test for containment of a point inside a sphere. template <typename Real> bool InContainer(Vector3<Real> const& point, Sphere3<Real> const& sphere) { Vector3<Real> diff = point - sphere.center; return Length(diff) <= sphere.radius; } // Compute the smallest bounding sphere that contains the input spheres. template <typename Real> bool MergeContainers(Sphere3<Real> const& sphere0, Sphere3<Real> const& sphere1, Sphere3<Real>& merge) { Vector3<Real> cenDiff = sphere1.center - sphere0.center; Real lenSqr = Dot(cenDiff, cenDiff); Real rDiff = sphere1.radius - sphere0.radius; Real rDiffSqr = rDiff * rDiff; if (rDiffSqr >= lenSqr) { merge = (rDiff >= (Real)0 ? sphere1 : sphere0); } else { Real length = std::sqrt(lenSqr); if (length > (Real)0) { Real coeff = (length + rDiff) / (((Real)2)*length); merge.center = sphere0.center + coeff * cenDiff; } else { merge.center = sphere0.center; } merge.radius = (Real)0.5 * (length + sphere0.radius + sphere1.radius); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpTrilinear3.h
.h
11,790
399
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <array> // The interpolator is for uniformly spaced(x,y z)-values. The input samples // must be stored in lexicographical order to represent f(x,y,z); that is, // F[c + xBound*(r + yBound*s)] corresponds to f(x,y,z), where c is the index // corresponding to x, r is the index corresponding to y, and s is the index // corresponding to z. namespace gte { template <typename Real> class IntpTrilinear3 { public: // Construction. IntpTrilinear3(int32_t xBound, int32_t yBound, int32_t zBound, Real xMin, Real xSpacing, Real yMin, Real ySpacing, Real zMin, Real zSpacing, Real const* F) : mXBound(xBound), mYBound(yBound), mZBound(zBound), mQuantity(xBound* yBound* zBound), mXMin(xMin), mXSpacing(xSpacing), mYMin(yMin), mYSpacing(ySpacing), mZMin(zMin), mZSpacing(zSpacing), mF(F) { // At least a 2x2x2 block of data points are needed to construct // the trilinear interpolation. LogAssert(xBound >= 2 && yBound >= 2 && zBound >= 2 && F != nullptr && xSpacing > (Real)0 && ySpacing > (Real)0 && zSpacing > (Real)0, "Invalid input."); mXMax = mXMin + mXSpacing * static_cast<Real>(mXBound) - static_cast<Real>(1); mInvXSpacing = (Real)1 / mXSpacing; mYMax = mYMin + mYSpacing * static_cast<Real>(mYBound) - static_cast<Real>(1); mInvYSpacing = (Real)1 / mYSpacing; mZMax = mZMin + mZSpacing * static_cast<Real>(mZBound) - static_cast<Real>(1); mInvZSpacing = (Real)1 / mZSpacing; mBlend[0][0] = (Real)1; mBlend[0][1] = (Real)-1; mBlend[1][0] = (Real)0; mBlend[1][1] = (Real)1; } // Member access. inline int32_t GetXBound() const { return mXBound; } inline int32_t GetYBound() const { return mYBound; } inline int32_t GetZBound() const { return mZBound; } inline int32_t GetQuantity() const { return mQuantity; } inline Real const* GetF() const { return mF; } inline Real GetXMin() const { return mXMin; } inline Real GetXMax() const { return mXMax; } inline Real GetXSpacing() const { return mXSpacing; } inline Real GetYMin() const { return mYMin; } inline Real GetYMax() const { return mYMax; } inline Real GetYSpacing() const { return mYSpacing; } inline Real GetZMin() const { return mZMin; } inline Real GetZMax() const { return mZMax; } inline Real GetZSpacing() const { return mZSpacing; } // Evaluate the function and its derivatives. The functions clamp the // inputs to xmin <= x <= xmax, ymin <= y <= ymax and // zmin <= z <= zmax. The first operator is for function evaluation. // The second operator is for function or derivative evaluations. The // xOrder argument is the order of the x-derivative, the yOrder // argument is the order of the y-derivative, and the zOrder argument // is the order of the z-derivative. All orders are zero to get the // function value itself. Real operator()(Real x, Real y, Real z) const { // Compute x-index and clamp to image. Real xIndex = (x - mXMin) * mInvXSpacing; int32_t ix = static_cast<int32_t>(xIndex); if (ix < 0) { ix = 0; } else if (ix >= mXBound) { ix = mXBound - 1; } // Compute y-index and clamp to image. Real yIndex = (y - mYMin) * mInvYSpacing; int32_t iy = static_cast<int32_t>(yIndex); if (iy < 0) { iy = 0; } else if (iy >= mYBound) { iy = mYBound - 1; } // Compute z-index and clamp to image. Real zIndex = (z - mZMin) * mInvZSpacing; int32_t iz = static_cast<int32_t>(zIndex); if (iz < 0) { iz = 0; } else if (iz >= mZBound) { iz = mZBound - 1; } std::array<Real, 2> U; U[0] = (Real)1; U[1] = xIndex - ix; std::array<Real, 2> V; V[0] = (Real)1; V[1] = yIndex - iy; std::array<Real, 2> W; W[0] = (Real)1; W[1] = zIndex - iz; // Compute P = M*U, Q = M*V, R = M*W. std::array<Real, 2> P, Q, R; for (int32_t row = 0; row < 2; ++row) { P[row] = (Real)0; Q[row] = (Real)0; R[row] = (Real)0; for (int32_t col = 0; col < 2; ++col) { P[row] += mBlend[row][col] * U[col]; Q[row] += mBlend[row][col] * V[col]; R[row] += mBlend[row][col] * W[col]; } } // compute the tensor product (M*U)(M*V)(M*W)*D where D is the 2x2x2 // subimage containing (x,y,z) Real result = (Real)0; for (int32_t slice = 0; slice < 2; ++slice) { int32_t zClamp = iz + slice; if (zClamp >= mZBound) { zClamp = mZBound - 1; } for (int32_t row = 0; row < 2; ++row) { int32_t yClamp = iy + row; if (yClamp >= mYBound) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 2; ++col) { int32_t xClamp = ix + col; if (xClamp >= mXBound) { xClamp = mXBound - 1; } result += P[col] * Q[row] * R[slice] * mF[xClamp + mXBound * (yClamp + mYBound * zClamp)]; } } } return result; } Real operator()(int32_t xOrder, int32_t yOrder, int32_t zOrder, Real x, Real y, Real z) const { // Compute x-index and clamp to image. Real xIndex = (x - mXMin) * mInvXSpacing; int32_t ix = static_cast<int32_t>(xIndex); if (ix < 0) { ix = 0; } else if (ix >= mXBound) { ix = mXBound - 1; } // Compute y-index and clamp to image. Real yIndex = (y - mYMin) * mInvYSpacing; int32_t iy = static_cast<int32_t>(yIndex); if (iy < 0) { iy = 0; } else if (iy >= mYBound) { iy = mYBound - 1; } // Compute z-index and clamp to image. Real zIndex = (z - mZMin) * mInvZSpacing; int32_t iz = static_cast<int32_t>(zIndex); if (iz < 0) { iz = 0; } else if (iz >= mZBound) { iz = mZBound - 1; } std::array<Real, 2> U; Real dx, xMult; switch (xOrder) { case 0: dx = xIndex - ix; U[0] = (Real)1; U[1] = dx; xMult = (Real)1; break; case 1: dx = xIndex - ix; U[0] = (Real)0; U[1] = (Real)1; xMult = mInvXSpacing; break; default: return (Real)0; } std::array<Real, 2> V; Real dy, yMult; switch (yOrder) { case 0: dy = yIndex - iy; V[0] = (Real)1; V[1] = dy; yMult = (Real)1; break; case 1: dy = yIndex - iy; V[0] = (Real)0; V[1] = (Real)1; yMult = mInvYSpacing; break; default: return (Real)0; } std::array<Real, 2> W; Real dz, zMult; switch (zOrder) { case 0: dz = zIndex - iz; W[0] = (Real)1; W[1] = dz; zMult = (Real)1; break; case 1: dz = zIndex - iz; W[0] = (Real)0; W[1] = (Real)1; zMult = mInvZSpacing; break; default: return (Real)0; } // Compute P = M*U, Q = M*V, and R = M*W. std::array<Real, 2> P, Q, R; for (int32_t row = 0; row < 2; ++row) { P[row] = (Real)0; Q[row] = (Real)0; R[row] = (Real)0; for (int32_t col = 0; col < 2; ++col) { P[row] += mBlend[row][col] * U[col]; Q[row] += mBlend[row][col] * V[col]; R[row] += mBlend[row][col] * W[col]; } } // Compute the tensor product (M*U)(M*V)(M*W)*D where D is the 2x2x2 // subimage containing (x,y,z). Real result = (Real)0; for (int32_t slice = 0; slice < 2; ++slice) { int32_t zClamp = iz + slice; if (zClamp >= mZBound) { zClamp = mZBound - 1; } for (int32_t row = 0; row < 2; ++row) { int32_t yClamp = iy + row; if (yClamp >= mYBound) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 2; ++col) { int32_t xClamp = ix + col; if (xClamp >= mXBound) { xClamp = mXBound - 1; } result += P[col] * Q[row] * R[slice] * mF[xClamp + mXBound * (yClamp + mYBound * zClamp)]; } } } result *= xMult * yMult * zMult; return result; } private: int32_t mXBound, mYBound, mZBound, mQuantity; Real mXMin, mXMax, mXSpacing, mInvXSpacing; Real mYMin, mYMax, mYSpacing, mInvYSpacing; Real mZMin, mZMax, mZSpacing, mInvZSpacing; Real const* mF; std::array<std::array<Real, 2>, 2> mBlend; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Delaunay3.h
.h
89,586
2,230
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/PrimalQuery3.h> #include <Mathematics/TSManifoldMesh.h> #include <Mathematics/Line.h> #include <Mathematics/Hyperplane.h> #include <Mathematics/SWInterval.h> #include <numeric> #include <set> #include <unordered_set> #include <vector> // Delaunay tetrahedralization of points (intrinsic dimensionality 3). // VQ = number of vertices // V = array of vertices // TQ = number of tetrahedra // I = Array of 4-tuples of indices into V that represent the tetrahedra // (4*TQ total elements). Access via GetIndices(*). // A = Array of 4-tuples of indices into I that represent the adjacent // tetrahedra (4*TQ total elements). Access via GetAdjacencies(*). // The i-th tetrahedron has vertices // vertex[0] = V[I[4*i+0]] // vertex[1] = V[I[4*i+1]] // vertex[2] = V[I[4*i+2]] // vertex[3] = V[I[4*i+3]] // and face index triples listed below. The face vertex ordering when // viewed from outside the tetrahedron is counterclockwise. // face[0] = <I[4*i+1],I[4*i+2],I[4*i+3]> // face[1] = <I[4*i+0],I[4*i+3],I[4*i+2]> // face[2] = <I[4*i+0],I[4*i+1],I[4*i+3]> // face[3] = <I[4*i+0],I[4*i+2],I[4*i+1]> // The tetrahedra adjacent to these faces have indices // adjacent[0] = A[4*i+0] is the tetrahedron opposite vertex[0], so it // is the tetrahedron sharing face[0]. // adjacent[1] = A[4*i+1] is the tetrahedron opposite vertex[1], so it // is the tetrahedron sharing face[1]. // adjacent[2] = A[4*i+2] is the tetrahedron opposite vertex[2], so it // is the tetrahedron sharing face[2]. // adjacent[3] = A[4*i+3] is the tetrahedron opposite vertex[3], so it // is the tetrahedron sharing face[3]. // If there is no adjacent tetrahedron, the A[*] value is set to -1. The // tetrahedron adjacent to face[j] has vertices // adjvertex[0] = V[I[4*adjacent[j]+0]] // adjvertex[1] = V[I[4*adjacent[j]+1]] // adjvertex[2] = V[I[4*adjacent[j]+2]] // adjvertex[3] = V[I[4*adjacent[j]+3]] // The only way to ensure a correct result for the input vertices (assumed to // be exact) is to choose ComputeType for exact rational arithmetic. You may // use BSNumber. No divisions are performed in this computation, so you do // not have to use BSRational. namespace gte { // The variadic template declaration supports the class // Delaunay3<InputType, ComputeType>, which is deprecated and will be // removed in a future release. The declaration also supports the // replacement class Delaunay3<InputType>. The new class uses a blend of // interval arithmetic and rational arithmetic. It also uses unordered // sets (hash tables). The replacement performs much better than the // deprecated class. template <typename T, typename...> class Delaunay3 {}; } namespace gte { // This class requires you to specify the ComputeType yourself. If it // is BSNumber<> or BSRational<>, the worst-case choices of N for the // chosen InputType are listed in the next table. The numerical // computations are encapsulated in PrimalQuery3<ComputeType>::ToPlane and // PrimalQuery3<ComputeType>::ToCircumsphere, the latter query the // dominant one in determining N. We recommend using only BSNumber, // because no divisions are performed in the triangulation computations. // // input type | compute type | N // -----------+--------------+------ // float | BSNumber | 44 // double | BSNumber | 329 // float | BSRational | 1875 // double | BSRational | 14167 template <typename InputType, typename ComputeType> class // [[deprecated("Use Delaunay3<T> instead.")]] Delaunay3<InputType, ComputeType> { public: // The class is a functor to support computing the Delaunay // tetrahedralization of multiple data sets using the same class // object. Delaunay3() : mEpsilon((InputType)0), mDimension(0), mLine(Vector3<InputType>::Zero(), Vector3<InputType>::Zero()), mPlane(Vector3<InputType>::Zero(), (InputType)0), mNumVertices(0), mNumUniqueVertices(0), mNumTetrahedra(0), mVertices(nullptr) { } virtual ~Delaunay3() = default; // The input is the array of vertices whose Delaunay // tetrahedralization is required. The epsilon value is used to // determine the intrinsic dimensionality of the vertices // (d = 0, 1, 2, or 3). When epsilon is positive, the determination // is fuzzy--vertices approximately the same point, approximately on // a line, approximately planar, or volumetric. bool operator()(int32_t numVertices, Vector3<InputType> const* vertices, InputType epsilon) { mEpsilon = std::max(epsilon, (InputType)0); mDimension = 0; mLine.origin = Vector3<InputType>::Zero(); mLine.direction = Vector3<InputType>::Zero(); mPlane.normal = Vector3<InputType>::Zero(); mPlane.constant = (InputType)0; mNumVertices = numVertices; mNumUniqueVertices = 0; mNumTetrahedra = 0; mVertices = vertices; mGraph.Clear(); mIndices.clear(); mAdjacencies.clear(); int32_t i, j; if (mNumVertices < 4) { // Delaunay3 should be called with at least four points. return false; } IntrinsicsVector3<InputType> info(mNumVertices, vertices, mEpsilon); if (info.dimension == 0) { // mDimension is 0; mGraph, mIndices, and mAdjacencies are // empty return false; } if (info.dimension == 1) { // The set is (nearly) collinear. mDimension = 1; mLine = Line3<InputType>(info.origin, info.direction[0]); return false; } if (info.dimension == 2) { // The set is (nearly) coplanar. mDimension = 2; mPlane = Plane3<InputType>(UnitCross(info.direction[0], info.direction[1]), info.origin); return false; } mDimension = 3; // Compute the vertices for the queries. mComputeVertices.resize(mNumVertices); mQuery.Set(mNumVertices, &mComputeVertices[0]); for (i = 0; i < mNumVertices; ++i) { for (j = 0; j < 3; ++j) { mComputeVertices[i][j] = vertices[i][j]; } } // Insert the (nondegenerate) tetrahedron constructed by the call // to GetInformation. This is necessary for the circumsphere // visibility algorithm to work correctly. if (!info.extremeCCW) { std::swap(info.extreme[2], info.extreme[3]); } if (!mGraph.Insert(info.extreme[0], info.extreme[1], info.extreme[2], info.extreme[3])) { return false; } // Incrementally update the tetrahedralization. The set of // processed points is maintained to eliminate duplicates, either // in the original input points or in the points obtained by snap // rounding. std::set<Vector3<InputType>> processed; for (i = 0; i < 4; ++i) { processed.insert(vertices[info.extreme[i]]); } for (i = 0; i < mNumVertices; ++i) { if (processed.find(vertices[i]) == processed.end()) { if (!Update(i)) { // A failure can occur if ComputeType is not an exact // arithmetic type. return false; } processed.insert(vertices[i]); } } mNumUniqueVertices = static_cast<int32_t>(processed.size()); // Assign integer values to the tetrahedra for use by the caller // and copy the tetrahedra information to compact arrays mIndices // and mAdjacencies. UpdateIndicesAdjacencies(); return true; } // Dimensional information. If GetDimension() returns 1, the points // lie on a line P+t*D (fuzzy comparison when epsilon > 0). You can // sort these if you need a polyline output by projecting onto the // line each vertex X = P+t*D, where t = Dot(D,X-P). If // GetDimension() returns 2, the points line on a plane P+s*U+t*V // (fuzzy comparison when epsilon > 0). You can project each vertex // X = P+s*U+t*V, where s = Dot(U,X-P) and t = Dot(V,X-P), then apply // Delaunay2 to the (s,t) tuples. inline InputType GetEpsilon() const { return mEpsilon; } inline int32_t GetDimension() const { return mDimension; } inline Line3<InputType> const& GetLine() const { return mLine; } inline Plane3<InputType> const& GetPlane() const { return mPlane; } // Member access. inline int32_t GetNumVertices() const { return mNumVertices; } inline int32_t GetNumUniqueVertices() const { return mNumUniqueVertices; } inline int32_t GetNumTetrahedra() const { return mNumTetrahedra; } inline Vector3<InputType> const* GetVertices() const { return mVertices; } inline PrimalQuery3<ComputeType> const& GetQuery() const { return mQuery; } inline TSManifoldMesh const& GetGraph() const { return mGraph; } inline std::vector<int32_t> const& GetIndices() const { return mIndices; } inline std::vector<int32_t> const& GetAdjacencies() const { return mAdjacencies; } // Locate those tetrahedra faces that do not share other tetrahedra. // The returned array has hull.size() = 3*numFaces indices, each // triple representing a triangle. The triangles are counterclockwise // ordered when viewed from outside the hull. The return value is // 'true' iff the dimension is 3. bool GetHull(std::vector<int32_t>& hull) const { if (mDimension == 3) { // Count the number of triangles that are not shared by two // tetrahedra. int32_t numTriangles = 0; for (auto adj : mAdjacencies) { if (adj == -1) { ++numTriangles; } } if (numTriangles > 0) { // Enumerate the triangles. The prototypical case is the // single tetrahedron V[0] = (0,0,0), V[1] = (1,0,0), // V[2] = (0,1,0) and V[3] = (0,0,1) with no adjacent // tetrahedra. The mIndices[] array is <0,1,2,3>. // i = 0, face = 0: // skip index 0, <x,1,2,3>, no swap, triangle = <1,2,3> // i = 1, face = 1: // skip index 1, <0,x,2,3>, swap, triangle = <0,3,2> // i = 2, face = 2: // skip index 2, <0,1,x,3>, no swap, triangle = <0,1,3> // i = 3, face = 3: // skip index 3, <0,1,2,x>, swap, triangle = <0,2,1> // To guarantee counterclockwise order of triangles when // viewed outside the tetrahedron, the swap of the last // two indices occurs when face is an odd number; // (face % 2) != 0. hull.resize(3 * static_cast<size_t>(numTriangles)); size_t current = 0, i = 0; for (auto adj : mAdjacencies) { if (adj == -1) { size_t tetra = i / 4, face = i % 4; for (size_t j = 0; j < 4; ++j) { if (j != face) { hull[current++] = mIndices[4 * tetra + j]; } } if ((face % 2) != 0) { std::swap(hull[current - 1], hull[current - 2]); } } ++i; } return true; } else { LogError("Unexpected. There must be at least one tetrahedron."); } } else { LogError("The dimension must be 3."); } } // Copy Delaunay tetrahedra to compact arrays mIndices and // mAdjacencies. The array information is accessible via the // functions GetIndices(int32_t, std::array<int32_t, 4>&) and // GetAdjacencies(int32_t, std::array<int32_t, 4>&). void UpdateIndicesAdjacencies() { // Assign integer values to the tetrahedra for use by the caller. auto const& smap = mGraph.GetTetrahedra(); std::map<Tetrahedron*, int32_t> permute; int32_t i = -1; permute[nullptr] = i++; for (auto const& element : smap) { permute[element.second.get()] = i++; } // Put Delaunay tetrahedra into an array (vertices and adjacency // info). mNumTetrahedra = static_cast<int32_t>(smap.size()); int32_t numIndices = 4 * mNumTetrahedra; if (mNumTetrahedra > 0) { mIndices.resize(numIndices); mAdjacencies.resize(numIndices); i = 0; for (auto const& element : smap) { Tetrahedron* tetra = element.second.get(); for (size_t j = 0; j < 4; ++j, ++i) { mIndices[i] = tetra->V[j]; mAdjacencies[i] = permute[tetra->S[j]]; } } } } // Get the vertex indices for tetrahedron i. The function returns // 'true' when the dimension is 3 and i is a valid tetrahedron index, // in which case the vertices are valid; otherwise, the function // returns 'false' and the vertices are invalid. bool GetIndices(int32_t i, std::array<int32_t, 4>& indices) const { if (mDimension == 3) { int32_t numTetrahedra = static_cast<int32_t>(mIndices.size() / 4); if (0 <= i && i < numTetrahedra) { size_t fourI = 4 * static_cast<size_t>(i); indices[0] = mIndices[fourI]; indices[1] = mIndices[fourI + 1]; indices[2] = mIndices[fourI + 2]; indices[3] = mIndices[fourI + 3]; return true; } } else { LogError("The dimension must be 3."); } return false; } // Get the indices for tetrahedra adjacent to tetrahedron i. The // function returns 'true' when the dimension is 3 and i is a valid // tetrahedron index, in which case the adjacencies are valid; // otherwise, the function returns 'false' and the adjacencies are // invalid. bool GetAdjacencies(int32_t i, std::array<int32_t, 4>& adjacencies) const { if (mDimension == 3) { int32_t numTetrahedra = static_cast<int32_t>(mIndices.size() / 4); if (0 <= i && i < numTetrahedra) { size_t fourI = 4 * static_cast<size_t>(i); adjacencies[0] = mAdjacencies[fourI]; adjacencies[1] = mAdjacencies[fourI + 1]; adjacencies[2] = mAdjacencies[fourI + 2]; adjacencies[3] = mAdjacencies[fourI + 3]; return true; } } else { LogError("The dimension must be 3."); } return false; } // Support for searching the tetrahedralization for a tetrahedron // that contains a point. If there is a containing tetrahedron, the // returned value is a tetrahedron index i with // 0 <= i < GetNumTetrahedra(). If there is not a containing // tetrahedron, -1 is returned. The computations are performed using // exact rational arithmetic. // // The SearchInfo input stores information about the tetrahedron // search when looking for the tetrahedron (if any) that contains p. // The first tetrahedron searched is 'initialTetrahedron'. On return // 'path' stores those (ordered) tetrahedron indices visited during // the search. The last visited tetrahedron has index // 'finalTetrahedron' and vertex indices 'finalV[0,1,2,3]', stored in // volumetric counterclockwise order. The last face of the search is // <finalV[0],finalV[1],finalV[2]>. For spatially coherent inputs p // for numerous calls to this function, you will want to specify // 'finalTetrahedron' from the previous call as 'initialTetrahedron' // for the next call, which should reduce search times. struct SearchInfo { SearchInfo() : initialTetrahedron(0), numPath(0), path{}, finalTetrahedron(0), finalV{ 0, 0, 0, 0 } { } int32_t initialTetrahedron; int32_t numPath; std::vector<int32_t> path; int32_t finalTetrahedron; std::array<int32_t, 4> finalV; }; int32_t GetContainingTetrahedron(Vector3<InputType> const& p, SearchInfo& info) const { if (mDimension == 3) { Vector3<ComputeType> test{ p[0], p[1], p[2] }; int32_t numTetrahedra = static_cast<int32_t>(mIndices.size() / 4); info.path.resize(numTetrahedra); info.numPath = 0; int32_t tetrahedron; if (0 <= info.initialTetrahedron && info.initialTetrahedron < numTetrahedra) { tetrahedron = info.initialTetrahedron; } else { info.initialTetrahedron = 0; tetrahedron = 0; } // Use tetrahedron faces as binary separating planes. for (int32_t i = 0; i < numTetrahedra; ++i) { int32_t ibase = 4 * tetrahedron; int32_t const* v = &mIndices[ibase]; info.path[info.numPath++] = tetrahedron; info.finalTetrahedron = tetrahedron; info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; info.finalV[3] = v[3]; // <V1,V2,V3> counterclockwise when viewed outside // tetrahedron. if (mQuery.ToPlane(test, v[1], v[2], v[3]) > 0) { tetrahedron = mAdjacencies[ibase]; if (tetrahedron == -1) { info.finalV[0] = v[1]; info.finalV[1] = v[2]; info.finalV[2] = v[3]; info.finalV[3] = v[0]; return -1; } continue; } // <V0,V3,V2> counterclockwise when viewed outside // tetrahedron. if (mQuery.ToPlane(test, v[0], v[2], v[3]) < 0) { tetrahedron = mAdjacencies[static_cast<size_t>(ibase) + 1]; if (tetrahedron == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[2]; info.finalV[2] = v[3]; info.finalV[3] = v[1]; return -1; } continue; } // <V0,V1,V3> counterclockwise when viewed outside // tetrahedron. if (mQuery.ToPlane(test, v[0], v[1], v[3]) > 0) { tetrahedron = mAdjacencies[static_cast<size_t>(ibase) + 2]; if (tetrahedron == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[3]; info.finalV[3] = v[2]; return -1; } continue; } // <V0,V2,V1> counterclockwise when viewed outside // tetrahedron. if (mQuery.ToPlane(test, v[0], v[1], v[2]) < 0) { tetrahedron = mAdjacencies[static_cast<size_t>(ibase) + 3]; if (tetrahedron == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; info.finalV[3] = v[3]; return -1; } continue; } return tetrahedron; } } else { LogError("The dimension must be 3."); } return -1; } private: // Support for incremental Delaunay tetrahedralization. typedef TSManifoldMesh::Tetrahedron Tetrahedron; bool GetContainingTetrahedron(int32_t i, Tetrahedron*& tetra) const { int32_t numTetrahedra = static_cast<int32_t>(mGraph.GetTetrahedra().size()); for (int32_t t = 0; t < numTetrahedra; ++t) { int32_t j; for (j = 0; j < 4; ++j) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace(); int32_t v0 = tetra->V[opposite[j][0]]; int32_t v1 = tetra->V[opposite[j][1]]; int32_t v2 = tetra->V[opposite[j][2]]; if (mQuery.ToPlane(i, v0, v1, v2) > 0) { // Point i sees face <v0,v1,v2> from outside the // tetrahedron. auto adjTetra = tetra->S[j]; if (adjTetra) { // Traverse to the tetrahedron sharing the face. tetra = adjTetra; break; } else { // We reached a hull face, so the point is outside // the hull. return false; } } } if (j == 4) { // The point is inside all four faces, so the point is inside // a tetrahedron. return true; } } LogError("Unexpected termination of loop."); } bool GetAndRemoveInsertionPolyhedron(int32_t i, std::set<Tetrahedron*>& candidates, std::set<TriangleKey<true>>& boundary) { // Locate the tetrahedra that make up the insertion polyhedron. TSManifoldMesh polyhedron; while (candidates.size() > 0) { Tetrahedron* tetra = *candidates.begin(); candidates.erase(candidates.begin()); for (int32_t j = 0; j < 4; ++j) { auto adj = tetra->S[j]; if (adj && candidates.find(adj) == candidates.end()) { int32_t a0 = adj->V[0]; int32_t a1 = adj->V[1]; int32_t a2 = adj->V[2]; int32_t a3 = adj->V[3]; if (mQuery.ToCircumsphere(i, a0, a1, a2, a3) <= 0) { // Point i is in the circumsphere. candidates.insert(adj); } } } int32_t v0 = tetra->V[0]; int32_t v1 = tetra->V[1]; int32_t v2 = tetra->V[2]; int32_t v3 = tetra->V[3]; if (!polyhedron.Insert(v0, v1, v2, v3)) { return false; } if (!mGraph.Remove(v0, v1, v2, v3)) { return false; } } // Get the boundary triangles of the insertion polyhedron. for (auto const& element : polyhedron.GetTetrahedra()) { Tetrahedron* tetra = element.second.get(); for (int32_t j = 0; j < 4; ++j) { if (!tetra->S[j]) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace(); int32_t v0 = tetra->V[opposite[j][0]]; int32_t v1 = tetra->V[opposite[j][1]]; int32_t v2 = tetra->V[opposite[j][2]]; boundary.insert(TriangleKey<true>(v0, v1, v2)); } } } return true; } bool Update(int32_t i) { // The return value of mGraph.Insert(...) is nullptr if there was // a failure to insert. The Update function will return 'false' // when the insertion fails. auto const& smap = mGraph.GetTetrahedra(); Tetrahedron* tetra = smap.begin()->second.get(); if (GetContainingTetrahedron(i, tetra)) { // The point is inside the convex hull. The insertion // polyhedron contains only tetrahedra in the current // tetrahedralization; the hull does not change. // Use a depth-first search for those tetrahedra whose // circumspheres contain point i. std::set<Tetrahedron*> candidates; candidates.insert(tetra); // Get the boundary of the insertion polyhedron C that // contains the tetrahedra whose circumspheres contain point // i. Polyhedron C contains the point i. std::set<TriangleKey<true>> boundary; if (!GetAndRemoveInsertionPolyhedron(i, candidates, boundary)) { return false; } // The insertion polyhedron consists of the tetrahedra formed // by point i and the faces of C. for (auto const& key : boundary) { int32_t v0 = key.V[0]; int32_t v1 = key.V[1]; int32_t v2 = key.V[2]; if (mQuery.ToPlane(i, v0, v1, v2) < 0) { if (!mGraph.Insert(i, v0, v1, v2)) { return false; } } // else: Point i is on an edge or face of 'tetra', so the // subdivision has degenerate tetrahedra. Ignore these. } } else { // The point is outside the convex hull. The insertion // polyhedron is formed by point i and any tetrahedra in the // current tetrahedralization whose circumspheres contain // point i. // Locate the convex hull of the tetrahedra. TODO: Maintain // a hull data structure that is updated incrementally. std::set<TriangleKey<true>> hull; for (auto const& element : smap) { Tetrahedron* t = element.second.get(); for (int32_t j = 0; j < 4; ++j) { if (!t->S[j]) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace(); int32_t v0 = t->V[opposite[j][0]]; int32_t v1 = t->V[opposite[j][1]]; int32_t v2 = t->V[opposite[j][2]]; hull.insert(TriangleKey<true>(v0, v1, v2)); } } } // Iterate over all the hull faces and use the ones visible to // point i to locate the insertion polyhedron. auto const& tmap = mGraph.GetTriangles(); std::set<Tetrahedron*> candidates; std::set<TriangleKey<true>> visible; for (auto const& key : hull) { int32_t v0 = key.V[0]; int32_t v1 = key.V[1]; int32_t v2 = key.V[2]; if (mQuery.ToPlane(i, v0, v1, v2) > 0) { auto iter = tmap.find(TriangleKey<false>(v0, v1, v2)); if (iter != tmap.end() && iter->second->T[1] == nullptr) { auto adj = iter->second->T[0]; if (adj && candidates.find(adj) == candidates.end()) { int32_t a0 = adj->V[0]; int32_t a1 = adj->V[1]; int32_t a2 = adj->V[2]; int32_t a3 = adj->V[3]; if (mQuery.ToCircumsphere(i, a0, a1, a2, a3) <= 0) { // Point i is in the circumsphere. candidates.insert(adj); } else { // Point i is not in the circumsphere but // the hull face is visible. visible.insert(key); } } } else { // TODO: Add a preprocessor symbol to this file // to allow throwing an exception. Currently, the // code exits gracefully when floating-point // rounding causes problems. // // LogError("Unexpected condition (ComputeType not exact?)"); return false; } } } // Get the boundary of the insertion subpolyhedron C that // contains the tetrahedra whose circumspheres contain // point i. std::set<TriangleKey<true>> boundary; if (!GetAndRemoveInsertionPolyhedron(i, candidates, boundary)) { return false; } // The insertion polyhedron P consists of the tetrahedra // formed by point i and the back faces of C *and* the visible // faces of mGraph-C. for (auto const& key : boundary) { int32_t v0 = key.V[0]; int32_t v1 = key.V[1]; int32_t v2 = key.V[2]; if (mQuery.ToPlane(i, v0, v1, v2) < 0) { // This is a back face of the boundary. if (!mGraph.Insert(i, v0, v1, v2)) { return false; } } } for (auto const& key : visible) { if (!mGraph.Insert(i, key.V[0], key.V[2], key.V[1])) { return false; } } } return true; } // The epsilon value is used for fuzzy determination of intrinsic // dimensionality. If the dimension is 0, 1, or 2, the constructor // returns early. The caller is responsible for retrieving the // dimension and taking an alternate path should the dimension be // smaller than 3. If the dimension is 0, the caller may as well // treat all vertices[] as a single point, say, vertices[0]. If the // dimension is 1, the caller can query for the approximating line // and project vertices[] onto it for further processing. If the // dimension is 2, the caller can query for the approximating plane // and project vertices[] onto it for further processing. InputType mEpsilon; int32_t mDimension; Line3<InputType> mLine; Plane3<InputType> mPlane; // The array of vertices used for geometric queries. If you want to // be certain of a correct result, choose ComputeType to be BSNumber. std::vector<Vector3<ComputeType>> mComputeVertices; PrimalQuery3<ComputeType> mQuery; // The graph information. int32_t mNumVertices; int32_t mNumUniqueVertices; int32_t mNumTetrahedra; Vector3<InputType> const* mVertices; TSManifoldMesh mGraph; std::vector<int32_t> mIndices; std::vector<int32_t> mAdjacencies; }; } namespace gte { // The input type must be 'float' or 'double'. The user no longer has // the responsibility to specify the compute type. template <typename T> class Delaunay3<T> { public: // The class is a functor to support computing the Delaunay // tetrahedralization of multiple data sets using the same class // object. Delaunay3() : mNumVertices(0), mVertices(nullptr), mIRVertices{}, mGraph(), mDuplicates{}, mNumUniqueVertices(0), mDimension(0), mLine(Vector3<T>::Zero(), Vector3<T>::Zero()), mPlane(Vector3<T>::Zero(), static_cast<T>(0)), mNumTetrahedra(0), mIndices{}, mAdjacencies{}, mQueryPoint(Vector3<T>::Zero()), mIRQueryPoint(Vector3<InputRational>::Zero()), mCRPool(maxNumCRPool) { static_assert( std::is_floating_point<T>::value, "The input type must be float or double."); } virtual ~Delaunay3() = default; // The input is the array of vertices whose Delaunay // tetrahedralization is required. The return value is 'true' if and // only if the intrinsic dimension of the points is 3. If the // intrinsic dimension is 2, the points lie exactly on a plane which // is accessible via GetPlane(). If the intrinsic dimension is 1, the // points lie exactly on a line which is accessible via GetLine(). If // the intrinsic dimension is 0, the points are all the same point. bool operator()(std::vector<Vector3<T>> const& vertices) { return operator()(vertices.size(), vertices.data()); } bool operator()(size_t numVertices, Vector3<T> const* vertices) { // Initialize values in case they were set by a previous call // to operator()(...). LogAssert( numVertices > 0 && vertices != nullptr, "Invalid argument."); T const zero = static_cast<T>(0); mNumVertices = numVertices; mVertices = vertices; mIRVertices.clear(); mGraph.Clear(); mDuplicates.clear(); mNumUniqueVertices = 0; mDimension = 0; mLine = Line3<T>(Vector3<T>::Zero(), Vector3<T>::Zero()); mPlane = Plane3<T>(Vector3<T>::Zero(), zero); mNumTetrahedra = 0; mIndices.clear(); mAdjacencies.clear(); mQueryPoint = Vector3<T>::Zero(); mIRQueryPoint = Vector3<InputRational>::Zero(); // Compute the intrinsic dimension and return early if that // dimension is 0, 1 or 2. IntrinsicsVector3<T> info(static_cast<int32_t>(mNumVertices), mVertices, zero); if (info.dimension == 0) { // The vertices are the same point. mDimension = 0; mLine.origin = info.origin; return false; } if (info.dimension == 1) { // The vertices are collinear. mDimension = 1; mLine = Line3<T>(info.origin, info.direction[0]); return false; } if (info.dimension == 2) { // The vertices are coplanar. mDimension = 2; mPlane = Plane3<T>(UnitCross(info.direction[0], info.direction[1]), info.origin); return false; } // The vertices necessarily will have a tetrahedralization. mDimension = 3; // Convert the floating-point inputs to rational type. mIRVertices.resize(mNumVertices); for (size_t i = 0; i < mNumVertices; ++i) { mIRVertices[i][0] = mVertices[i][0]; mIRVertices[i][1] = mVertices[i][1]; mIRVertices[i][2] = mVertices[i][2]; } // Assume initially the vertices are unique. If duplicates are // found during the Delaunay update, mDuplicates[] will be // modified accordingly. mDuplicates.resize(mNumVertices); std::iota(mDuplicates.begin(), mDuplicates.end(), 0); // Insert the nondegenerate tetrahedron constructed by the call to // IntrinsicsVector2{T}. This is necessary for the circumsphere // visibility algorithm to work correctly. if (!info.extremeCCW) { std::swap(info.extreme[2], info.extreme[3]); } auto inserted = mGraph.Insert(info.extreme[0], info.extreme[1], info.extreme[2], info.extreme[3]); LogAssert( inserted != nullptr, "The tetrahedron should not be degenerate."); // Incrementally update the tetrahedralization. The set of // processed points is maintained to eliminate duplicates. ProcessedVertexSet processed{}; for (size_t i = 0; i < 4; ++i) { int32_t j = info.extreme[i]; processed.insert(ProcessedVertex(mVertices[j], j)); mDuplicates[j] = j; } for (size_t i = 0; i < mNumVertices; ++i) { ProcessedVertex v(mVertices[i], i); auto iter = processed.find(v); if (iter == processed.end()) { Update(i); processed.insert(v); } else { mDuplicates[i] = iter->location; } } mNumUniqueVertices = processed.size(); // Assign integer values to the tetrahedra for use by the caller // and copy the tetrahedra information to compact arrays mIndices // and mAdjacencies. UpdateIndicesAdjacencies(); return true; } // Dimensional information. If GetDimension() returns 1, the points // lie on a line P+t*D. You can sort these if you need a polyline // output by projecting onto the line each vertex X = P+t*D, where // t = Dot(D,X-P). If GetDimension() returns 2, the points line on a // plane P+s*U+t*V. You can project each vertex X = P+s*U+t*V, where // s = Dot(U,X-P) and t = Dot(V,X-P) and then apply Delaunay2 to the // (s,t) tuples. inline size_t GetDimension() const { return mDimension; } inline Line3<T> const& GetLine() const { return mLine; } inline Plane3<T> const& GetPlane() const { return mPlane; } // Member access. inline size_t GetNumVertices() const { return mIRVertices.size(); } inline Vector3<T> const* GetVertices() const { return mVertices; } inline size_t GetNumUniqueVertices() const { return mNumUniqueVertices; } // If 'vertices' has no duplicates, GetDuplicates()[i] = i for all i. // If vertices[i] is the first occurrence of a vertex and if // vertices[j] is found later, then GetDuplicates()[j] = i. inline std::vector<size_t> const& GetDuplicates() const { return mDuplicates; } inline size_t GetNumTetrahedra() const { return mNumTetrahedra; } inline TSManifoldMesh const& GetGraph() const { return mGraph; } inline std::vector<int32_t> const& GetIndices() const { return mIndices; } inline std::vector<int32_t> const& GetAdjacencies() const { return mAdjacencies; } // Locate those tetrahedra faces that do not share other tetrahedra. // The returned array has hull.size() = 3*numFaces indices, each // triple representing a triangle. The triangles are counterclockwise // ordered when viewed from outside the hull. The return value is // 'true' iff the dimension is 3. bool GetHull(std::vector<size_t>& hull) const { if (mDimension == 3) { // Count the number of triangles that are not shared by two // tetrahedra. size_t numTriangles = 0; for (auto adj : mAdjacencies) { if (adj == -1) { ++numTriangles; } } if (numTriangles > 0) { // Enumerate the triangles. The prototypical case is the // single tetrahedron V[0] = (0,0,0), V[1] = (1,0,0), // V[2] = (0,1,0) and V[3] = (0,0,1) with no adjacent // tetrahedra. The mIndices[] array is <0,1,2,3>. // i = 0, face = 0: // skip index 0, <x,1,2,3>, no swap, triangle = <1,2,3> // i = 1, face = 1: // skip index 1, <0,x,2,3>, swap, triangle = <0,3,2> // i = 2, face = 2: // skip index 2, <0,1,x,3>, no swap, triangle = <0,1,3> // i = 3, face = 3: // skip index 3, <0,1,2,x>, swap, triangle = <0,2,1> // To guarantee counterclockwise order of triangles when // viewed outside the tetrahedron, the swap of the last // two indices occurs when face is an odd number; // (face % 2) != 0. hull.resize(3 * numTriangles); size_t current = 0, i = 0; for (auto adj : mAdjacencies) { if (adj == -1) { size_t tetra = i / 4, face = i % 4; for (size_t j = 0; j < 4; ++j) { if (j != face) { hull[current++] = mIndices[4 * tetra + j]; } } if ((face % 2) != 0) { std::swap(hull[current - 1], hull[current - 2]); } } ++i; } return true; } else { LogError("Unexpected. There must be at least one tetrahedron."); } } else { LogError("The dimension must be 3."); } } // Copy Delaunay tetrahedra to compact arrays mIndices and // mAdjacencies. The array information is accessible via the // functions GetIndices(size_t, std::array<int32_t, 4>&) and // GetAdjacencies(size_t, std::array<int32_t, 4>&). void UpdateIndicesAdjacencies() { // Assign integer values to the tetrahedra for use by the caller. auto const& smap = mGraph.GetTetrahedra(); std::map<Tetrahedron*, int32_t> permute{}; int32_t i = -1; permute[nullptr] = i++; for (auto const& element : smap) { permute[element.second.get()] = i++; } // Put Delaunay tetrahedra into an array (vertices and adjacency // info). mNumTetrahedra = smap.size(); size_t numIndices = 4 * mNumTetrahedra; if (mNumTetrahedra > 0) { mIndices.resize(numIndices); mAdjacencies.resize(numIndices); i = 0; for (auto const& element : smap) { Tetrahedron* tetra = element.second.get(); for (size_t j = 0; j < 4; ++j, ++i) { mIndices[i] = tetra->V[j]; mAdjacencies[i] = permute[tetra->S[j]]; } } } } // Get the vertex indices for tetrahedron i. The function returns // 'true' when the dimension is 3 and i is a valid tetrahedron index, // in which case the vertices are valid; otherwise, the function // returns 'false' and the vertices are invalid. bool GetIndices(size_t t, std::array<int32_t, 4>& indices) const { if (mDimension == 3) { size_t const numTetrahedra = mIndices.size() / 4; if (t < numTetrahedra) { size_t fourI = 4 * static_cast<size_t>(t); indices[0] = mIndices[fourI]; indices[1] = mIndices[fourI + 1]; indices[2] = mIndices[fourI + 2]; indices[3] = mIndices[fourI + 3]; return true; } } return false; } // Get the indices for tetrahedra adjacent to tetrahedron i. The // function returns 'true' when the dimension is 3 and i is a valid // tetrahedron index, in which case the adjacencies are valid; // otherwise, the function returns 'false' and the adjacencies are // invalid. bool GetAdjacencies(size_t t, std::array<int32_t, 4>& adjacencies) const { if (mDimension == 3) { size_t const numTetrahedra = mIndices.size() / 4; if (t < numTetrahedra) { size_t fourI = 4 * static_cast<size_t>(t); adjacencies[0] = mAdjacencies[fourI]; adjacencies[1] = mAdjacencies[fourI + 1]; adjacencies[2] = mAdjacencies[fourI + 2]; adjacencies[3] = mAdjacencies[fourI + 3]; return true; } } return false; } // Support for searching the tetrahedralization for a tetrahedron // that contains a point. If there is a containing tetrahedron, the // returned value is a tetrahedron index i with // 0 <= t < GetNumTetrahedra(). If there is not a containing // tetrahedron, -1 is returned. The computations are performed using // exact rational arithmetic. // // The SearchInfo input stores information about the tetrahedron // search when looking for the tetrahedron (if any) that contains p. // The first tetrahedron searched is 'initialTetrahedron'. On return // 'path' stores those (ordered) tetrahedron indices visited during // the search. The last visited tetrahedron has index // 'finalTetrahedron' and vertex indices 'finalV[0,1,2,3]', stored in // volumetric counterclockwise order. The last face of the search is // <finalV[0],finalV[1],finalV[2]>. For spatially coherent inputs p // for numerous calls to this function, you will want to specify // 'finalTetrahedron' from the previous call as 'initialTetrahedron' // for the next call, which should reduce search times. static size_t constexpr negOne = std::numeric_limits<size_t>::max(); struct SearchInfo { SearchInfo() : initialTetrahedron(0), numPath(0), finalTetrahedron(0), finalV{ 0, 0, 0, 0 }, path{} { } size_t initialTetrahedron; size_t numPath; size_t finalTetrahedron; std::array<int32_t, 4> finalV; std::vector<size_t> path; }; // If the point is in a tetrahedron, the return value is the index of // the tetrahedron. If the point is not in a tetrahedron, the return // value isstd::numeric_limits<size_t>::max(). size_t GetContainingTetrahedron(Vector3<T> const& inP, SearchInfo& info) const { LogAssert( mDimension == 3, "Invalid dimension for tetrahedron search."); mQueryPoint = inP; mIRQueryPoint = { inP[0], inP[1] }; size_t const numTetrahedra = mIndices.size() / 4; info.path.resize(numTetrahedra); info.numPath = 0; size_t tetrahedron{}; if (info.initialTetrahedron < numTetrahedra) { tetrahedron = info.initialTetrahedron; } else { info.initialTetrahedron = 0; tetrahedron = 0; } // Use tetrahedron faces as binary separating planes. int32_t adjacent{}; for (size_t i = 0; i < numTetrahedra; ++i) { size_t ibase = 4 * tetrahedron; int32_t const* v = &mIndices[ibase]; info.path[info.numPath++] = tetrahedron; info.finalTetrahedron = tetrahedron; info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; info.finalV[3] = v[3]; // <V1,V2,V3> counterclockwise when viewed outside // tetrahedron. if (ToPlane(negOne, v[1], v[2], v[3]) > 0) { adjacent = mAdjacencies[ibase]; if (adjacent == -1) { info.finalV[0] = v[1]; info.finalV[1] = v[2]; info.finalV[2] = v[3]; info.finalV[3] = v[0]; return negOne; } tetrahedron = static_cast<size_t>(adjacent); continue; } // <V0,V3,V2> counterclockwise when viewed outside // tetrahedron. if (ToPlane(negOne, v[0], v[2], v[3]) < 0) { adjacent = mAdjacencies[static_cast<size_t>(ibase) + 1]; if (adjacent == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[2]; info.finalV[2] = v[3]; info.finalV[3] = v[1]; return negOne; } tetrahedron = static_cast<size_t>(adjacent); continue; } // <V0,V1,V3> counterclockwise when viewed outside // tetrahedron. if (ToPlane(negOne, v[0], v[1], v[3]) > 0) { adjacent = mAdjacencies[static_cast<size_t>(ibase) + 2]; if (adjacent == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[3]; info.finalV[3] = v[2]; return negOne; } tetrahedron = static_cast<size_t>(adjacent); continue; } // <V0,V2,V1> counterclockwise when viewed outside // tetrahedron. if (ToPlane(negOne, v[0], v[1], v[2]) < 0) { adjacent = mAdjacencies[static_cast<size_t>(ibase) + 3]; if (adjacent == -1) { info.finalV[0] = v[0]; info.finalV[1] = v[1]; info.finalV[2] = v[2]; info.finalV[3] = v[3]; return negOne; } tetrahedron = static_cast<size_t>(adjacent); continue; } return tetrahedron; } LogError( "Unexpected termination of loop while searching for a triangle."); } protected: // The type of the read-only input vertices[] when converted for // rational arithmetic. static int32_t constexpr InputNumWords = std::is_same<T, float>::value ? 2 : 4; using InputRational = BSNumber<UIntegerFP32<InputNumWords>>; // The vector of vertices used for geometric queries. The input // vertices are read-only, so we can represent them by the type // InputRational. size_t mNumVertices; Vector3<T> const* mVertices; std::vector<Vector3<InputRational>> mIRVertices; TSManifoldMesh mGraph; private: // The compute type used for exact sign classification. static int32_t constexpr ComputeNumWords = std::is_same<T, float>::value ? 44 : 330; using ComputeRational = BSNumber<UIntegerFP32<ComputeNumWords>>; // Convenient renaming. typedef TSManifoldMesh::Tetrahedron Tetrahedron; struct ProcessedVertex { ProcessedVertex() : vertex(Vector3<T>::Zero()), location(0) { } ProcessedVertex(Vector3<T> const& inVertex, size_t inLocation) : vertex(inVertex), location(inLocation) { } // Support for hashing in std::unordered_set<>. The first // operator() is the hash function. The second operator() is // the equality comparison used for elements in the same bucket. std::size_t operator()(ProcessedVertex const& v) const { return HashValue(v.vertex[0], v.vertex[1], v.vertex[2], v.location); } bool operator()(ProcessedVertex const& v0, ProcessedVertex const& v1) const { return v0.vertex == v1.vertex && v0.location == v1.location; } Vector3<T> vertex; size_t location; }; using ProcessedVertexSet = std::unordered_set< ProcessedVertex, ProcessedVertex, ProcessedVertex>; using DirectedTriangleKeySet = std::unordered_set< TriangleKey<true>, TriangleKey<true>, TriangleKey<true>>; using TetrahedronPtrSet = std::unordered_set<Tetrahedron*>; static ComputeRational const& Copy(InputRational const& source, ComputeRational& target) { target.SetSign(source.GetSign()); target.SetBiasedExponent(source.GetBiasedExponent()); target.GetUInteger().CopyFrom(source.GetUInteger()); return target; } // Given a plane with origin V0 and normal N = Cross(V1-V0,V2-V0) // and given a query point P, ToPlane returns // +1, P on positive side of plane (side to which N points) // -1, P on negative side of plane (side to which -N points) // 0, P on the plane int32_t ToPlane(size_t pIndex, size_t v0Index, size_t v1Index, size_t v2Index) const { // The expression tree has 34 nodes consisting of 12 input // leaves and 22 compute nodes. // Use interval arithmetic to determine the sign if possible. auto const& inP = (pIndex != negOne ? mVertices[pIndex] : mQueryPoint); Vector3<T> const& inV0 = mVertices[v0Index]; Vector3<T> const& inV1 = mVertices[v1Index]; Vector3<T> const& inV2 = mVertices[v2Index]; // Evaluate the expression tree of intervals. auto x0 = SWInterval<T>::Sub(inP[0], inV0[0]); auto y0 = SWInterval<T>::Sub(inP[1], inV0[1]); auto z0 = SWInterval<T>::Sub(inP[2], inV0[2]); auto x1 = SWInterval<T>::Sub(inV1[0], inV0[0]); auto y1 = SWInterval<T>::Sub(inV1[1], inV0[1]); auto z1 = SWInterval<T>::Sub(inV1[2], inV0[2]); auto x2 = SWInterval<T>::Sub(inV2[0], inV0[0]); auto y2 = SWInterval<T>::Sub(inV2[1], inV0[1]); auto z2 = SWInterval<T>::Sub(inV2[2], inV0[2]); auto y0z1 = y0 * z1; auto y0z2 = y0 * z2; auto y1z0 = y1 * z0; auto y1z2 = y1 * z2; auto y2z0 = y2 * z0; auto y2z1 = y2 * z1; auto c0 = y1z2 - y2z1; auto c1 = y2z0 - y0z2; auto c2 = y0z1 - y1z0; auto x0c0 = x0 * c0; auto x1c1 = x1 * c1; auto x2c2 = x2 * c2; auto det = x0c0 + x1c1 + x2c2; T constexpr zero = 0; if (det[0] > zero) { return +1; } else if (det[1] < zero) { return -1; } // The exact sign of the determinant is not known, so compute // the determinant using rational arithmetic. // Name the nodes of the expression tree. auto const& irP = (pIndex != negOne ? mIRVertices[pIndex] : mIRQueryPoint); Vector3<InputRational> const& irV0 = mIRVertices[v0Index]; Vector3<InputRational> const& irV1 = mIRVertices[v1Index]; Vector3<InputRational> const& irV2 = mIRVertices[v2Index]; // Input nodes. auto const& crP0 = Copy(irP[0], mCRPool[0]); auto const& crP1 = Copy(irP[1], mCRPool[1]); auto const& crP2 = Copy(irP[2], mCRPool[2]); auto const& crV00 = Copy(irV0[0], mCRPool[3]); auto const& crV01 = Copy(irV0[1], mCRPool[4]); auto const& crV02 = Copy(irV0[2], mCRPool[5]); auto const& crV10 = Copy(irV1[0], mCRPool[6]); auto const& crV11 = Copy(irV1[1], mCRPool[7]); auto const& crV12 = Copy(irV1[2], mCRPool[8]); auto const& crV20 = Copy(irV2[0], mCRPool[9]); auto const& crV21 = Copy(irV2[1], mCRPool[10]); auto const& crV22 = Copy(irV2[2], mCRPool[11]); // Compute nodes. auto& crX0 = mCRPool[12]; auto& crY0 = mCRPool[13]; auto& crZ0 = mCRPool[14]; auto& crX1 = mCRPool[15]; auto& crY1 = mCRPool[16]; auto& crZ1 = mCRPool[17]; auto& crX2 = mCRPool[18]; auto& crY2 = mCRPool[19]; auto& crZ2 = mCRPool[20]; auto& crY0Z1 = mCRPool[21]; auto& crY0Z2 = mCRPool[22]; auto& crY1Z0 = mCRPool[23]; auto& crY1Z2 = mCRPool[24]; auto& crY2Z0 = mCRPool[25]; auto& crY2Z1 = mCRPool[26]; auto& crC0 = mCRPool[27]; auto& crC1 = mCRPool[28]; auto& crC2 = mCRPool[29]; auto& crX0C0 = mCRPool[30]; auto& crX1C1 = mCRPool[31]; auto& crX2C2 = mCRPool[32]; auto& crDet = mCRPool[33]; // Evaluate the expression tree of rational numbers. crX0 = crP0 - crV00; crY0 = crP1 - crV01; crZ0 = crP2 - crV02; crX1 = crV10 - crV00; crY1 = crV11 - crV01; crZ1 = crV12 - crV02; crX2 = crV20 - crV00; crY2 = crV21 - crV01; crZ2 = crV22 - crV02; crY0Z1 = crY0 * crZ1; crY0Z2 = crY0 * crZ2; crY1Z0 = crY1 * crZ0; crY1Z2 = crY1 * crZ2; crY2Z0 = crY2 * crZ0; crY2Z1 = crY2 * crZ1; crC0 = crY1Z2 - crY2Z1; crC1 = crY2Z0 - crY0Z2; crC2 = crY0Z1 - crY1Z0; crX0C0 = crX0 * crC0; crX1C1 = crX1 * crC1; crX2C2 = crX2 * crC2; crDet = crX0C0 + crX1C1 + crX2C2; return crDet.GetSign(); } // For a tetrahedron with vertices ordered as described in the file // TetrahedronKey.h, the function returns // +1, P outside circumsphere of tetrahedron // -1, P inside circumsphere of tetrahedron // 0, P on circumsphere of tetrahedron int32_t ToCircumsphere(size_t pIndex, size_t v0Index, size_t v1Index, size_t v2Index, size_t v3Index) const { // The expression tree has 98 nodes consisting of 15 input // leaves and 83 compute nodes. // Use interval arithmetic to determine the sign if possible. auto const& inP = (pIndex != negOne ? mVertices[pIndex] : mQueryPoint); Vector3<T> const& inV0 = mVertices[v0Index]; Vector3<T> const& inV1 = mVertices[v1Index]; Vector3<T> const& inV2 = mVertices[v2Index]; Vector3<T> const& inV3 = mVertices[v3Index]; // Evaluate the expression tree of intervals. auto x0 = SWInterval<T>::Sub(inV0[0], inP[0]); auto y0 = SWInterval<T>::Sub(inV0[1], inP[1]); auto z0 = SWInterval<T>::Sub(inV0[2], inP[2]); auto s00 = SWInterval<T>::Add(inV0[0], inP[0]); auto s01 = SWInterval<T>::Add(inV0[1], inP[1]); auto s02 = SWInterval<T>::Add(inV0[2], inP[2]); auto x1 = SWInterval<T>::Sub(inV1[0], inP[0]); auto y1 = SWInterval<T>::Sub(inV1[1], inP[1]); auto z1 = SWInterval<T>::Sub(inV1[2], inP[2]); auto s10 = SWInterval<T>::Add(inV1[0], inP[0]); auto s11 = SWInterval<T>::Add(inV1[1], inP[1]); auto s12 = SWInterval<T>::Add(inV1[2], inP[2]); auto x2 = SWInterval<T>::Sub(inV2[0], inP[0]); auto y2 = SWInterval<T>::Sub(inV2[1], inP[1]); auto z2 = SWInterval<T>::Sub(inV2[2], inP[2]); auto s20 = SWInterval<T>::Add(inV2[0], inP[0]); auto s21 = SWInterval<T>::Add(inV2[1], inP[1]); auto s22 = SWInterval<T>::Add(inV2[2], inP[2]); auto x3 = SWInterval<T>::Sub(inV3[0], inP[0]); auto y3 = SWInterval<T>::Sub(inV3[1], inP[1]); auto z3 = SWInterval<T>::Sub(inV3[2], inP[2]); auto s30 = SWInterval<T>::Add(inV3[0], inP[0]); auto s31 = SWInterval<T>::Add(inV3[1], inP[1]); auto s32 = SWInterval<T>::Add(inV3[2], inP[2]); auto t00 = s00 * x0; auto t01 = s01 * y0; auto t02 = s02 * z0; auto t10 = s10 * x1; auto t11 = s11 * y1; auto t12 = s12 * z1; auto t20 = s20 * x2; auto t21 = s21 * y2; auto t22 = s22 * z2; auto t30 = s30 * x3; auto t31 = s31 * y3; auto t32 = s32 * z3; auto w0 = t00 + t01 + t02; auto w1 = t10 + t11 + t12; auto w2 = t20 + t21 + t22; auto w3 = t30 + t31 + t32; auto x0y1 = x0 * y1; auto x0y2 = x0 * y2; auto x0y3 = x0 * y3; auto x1y0 = x1 * y0; auto x1y2 = x1 * y2; auto x1y3 = x1 * y3; auto x2y0 = x2 * y0; auto x2y1 = x2 * y1; auto x2y3 = x2 * y3; auto x3y0 = x3 * y0; auto x3y1 = x3 * y1; auto x3y2 = x3 * y2; auto z0w1 = z0 * w1; auto z0w2 = z0 * w2; auto z0w3 = z0 * w3; auto z1w0 = z1 * w0; auto z1w2 = z1 * w2; auto z1w3 = z1 * w3; auto z2w0 = z2 * w0; auto z2w1 = z2 * w1; auto z2w3 = z2 * w3; auto z3w0 = z3 * w0; auto z3w1 = z3 * w1; auto z3w2 = z3 * w2; auto u0 = x0y1 - x1y0; auto u1 = x0y2 - x2y0; auto u2 = x0y3 - x3y0; auto u3 = x1y2 - x2y1; auto u4 = x1y3 - x3y1; auto u5 = x2y3 - x3y2; auto v0 = z0w1 - z1w0; auto v1 = z0w2 - z2w0; auto v2 = z0w3 - z3w0; auto v3 = z1w2 - z2w1; auto v4 = z1w3 - z3w1; auto v5 = z2w3 - z3w2; auto u0v5 = u0 * v5; auto u1v4 = u1 * v4; auto u2v3 = u2 * v3; auto u3v2 = u3 * v2; auto u4v1 = u4 * v1; auto u5v0 = u5 * v0; auto det = u0v5 - u1v4 + u2v3 + u3v2 - u4v1 + u5v0; T constexpr zero = 0; if (det[0] > zero) { return +1; } else if (det[1] < zero) { return -1; } // The exact sign of the determinant is not known, so compute // the determinant using rational arithmetic. // Name the nodes of the expression tree. auto const& irP = (pIndex != negOne ? mIRVertices[pIndex] : mIRQueryPoint); Vector3<InputRational> const& irV0 = mIRVertices[v0Index]; Vector3<InputRational> const& irV1 = mIRVertices[v1Index]; Vector3<InputRational> const& irV2 = mIRVertices[v2Index]; Vector3<InputRational> const& irV3 = mIRVertices[v3Index]; // Input nodes. auto const& crP0 = Copy(irP[0], mCRPool[0]); auto const& crP1 = Copy(irP[1], mCRPool[1]); auto const& crP2 = Copy(irP[2], mCRPool[2]); auto const& crV00 = Copy(irV0[0], mCRPool[3]); auto const& crV01 = Copy(irV0[1], mCRPool[4]); auto const& crV02 = Copy(irV0[2], mCRPool[5]); auto const& crV10 = Copy(irV1[0], mCRPool[6]); auto const& crV11 = Copy(irV1[1], mCRPool[7]); auto const& crV12 = Copy(irV1[2], mCRPool[8]); auto const& crV20 = Copy(irV2[0], mCRPool[9]); auto const& crV21 = Copy(irV2[1], mCRPool[10]); auto const& crV22 = Copy(irV2[2], mCRPool[11]); auto const& crV30 = Copy(irV3[0], mCRPool[12]); auto const& crV31 = Copy(irV3[1], mCRPool[13]); auto const& crV32 = Copy(irV3[2], mCRPool[14]); // Compute nodes. auto& crX0 = mCRPool[15]; auto& crY0 = mCRPool[16]; auto& crZ0 = mCRPool[17]; auto& crS00 = mCRPool[18]; auto& crS01 = mCRPool[19]; auto& crS02 = mCRPool[20]; auto& crX1 = mCRPool[21]; auto& crY1 = mCRPool[22]; auto& crZ1 = mCRPool[23]; auto& crS10 = mCRPool[24]; auto& crS11 = mCRPool[25]; auto& crS12 = mCRPool[26]; auto& crX2 = mCRPool[27]; auto& crY2 = mCRPool[28]; auto& crZ2 = mCRPool[29]; auto& crS20 = mCRPool[30]; auto& crS21 = mCRPool[31]; auto& crS22 = mCRPool[32]; auto& crX3 = mCRPool[33]; auto& crY3 = mCRPool[34]; auto& crZ3 = mCRPool[35]; auto& crS30 = mCRPool[36]; auto& crS31 = mCRPool[37]; auto& crS32 = mCRPool[38]; auto& crT00 = mCRPool[39]; auto& crT01 = mCRPool[40]; auto& crT02 = mCRPool[41]; auto& crT10 = mCRPool[42]; auto& crT11 = mCRPool[43]; auto& crT12 = mCRPool[44]; auto& crT20 = mCRPool[45]; auto& crT21 = mCRPool[46]; auto& crT22 = mCRPool[47]; auto& crT30 = mCRPool[48]; auto& crT31 = mCRPool[49]; auto& crT32 = mCRPool[50]; auto& crW0 = mCRPool[51]; auto& crW1 = mCRPool[52]; auto& crW2 = mCRPool[53]; auto& crW3 = mCRPool[54]; auto& crX0Y1 = mCRPool[55]; auto& crX0Y2 = mCRPool[56]; auto& crX0Y3 = mCRPool[57]; auto& crX1Y0 = mCRPool[58]; auto& crX1Y2 = mCRPool[59]; auto& crX1Y3 = mCRPool[60]; auto& crX2Y0 = mCRPool[61]; auto& crX2Y1 = mCRPool[62]; auto& crX2Y3 = mCRPool[63]; auto& crX3Y0 = mCRPool[64]; auto& crX3Y1 = mCRPool[65]; auto& crX3Y2 = mCRPool[66]; auto& crZ0W1 = mCRPool[67]; auto& crZ0W2 = mCRPool[68]; auto& crZ0W3 = mCRPool[69]; auto& crZ1W0 = mCRPool[70]; auto& crZ1W2 = mCRPool[71]; auto& crZ1W3 = mCRPool[72]; auto& crZ2W0 = mCRPool[73]; auto& crZ2W1 = mCRPool[74]; auto& crZ2W3 = mCRPool[75]; auto& crZ3W0 = mCRPool[76]; auto& crZ3W1 = mCRPool[77]; auto& crZ3W2 = mCRPool[78]; auto& crU0 = mCRPool[79]; auto& crU1 = mCRPool[80]; auto& crU2 = mCRPool[81]; auto& crU3 = mCRPool[82]; auto& crU4 = mCRPool[83]; auto& crU5 = mCRPool[84]; auto& crV0 = mCRPool[85]; auto& crV1 = mCRPool[86]; auto& crV2 = mCRPool[87]; auto& crV3 = mCRPool[88]; auto& crV4 = mCRPool[89]; auto& crV5 = mCRPool[90]; auto& crU0V5 = mCRPool[91]; auto& crU1V4 = mCRPool[92]; auto& crU2V3 = mCRPool[93]; auto& crU3V2 = mCRPool[94]; auto& crU4V1 = mCRPool[95]; auto& crU5V0 = mCRPool[96]; auto& crDet = mCRPool[97]; // Evaluate the expression tree of rational numbers. crX0 = crV00 - crP0; crY0 = crV01 - crP1; crZ0 = crV02 - crP2; crS00 = crV00 + crP0; crS01 = crV01 + crP1; crS02 = crV02 + crP2; crX1 = crV10 - crP0; crY1 = crV11 - crP1; crZ1 = crV12 - crP2; crS10 = crV10 + crP0; crS11 = crV11 + crP1; crS12 = crV12 + crP2; crX2 = crV20 - crP0; crY2 = crV21 - crP1; crZ2 = crV22 - crP2; crS20 = crV20 + crP0; crS21 = crV21 + crP1; crS22 = crV22 + crP2; crX3 = crV30 - crP0; crY3 = crV31 - crP1; crZ3 = crV32 - crP2; crS30 = crV30 + crP0; crS31 = crV31 + crP1; crS32 = crV32 + crP2; crT00 = crS00 * crX0; crT01 = crS01 * crY0; crT02 = crS02 * crZ0; crT10 = crS10 * crX1; crT11 = crS11 * crY1; crT12 = crS12 * crZ1; crT20 = crS20 * crX2; crT21 = crS21 * crY2; crT22 = crS22 * crZ2; crT30 = crS30 * crX3; crT31 = crS31 * crY3; crT32 = crS32 * crZ3; crW0 = crT00 + crT01 + crT02; crW1 = crT10 + crT11 + crT12; crW2 = crT20 + crT21 + crT22; crW3 = crT30 + crT31 + crT32; crX0Y1 = crX0 * crY1; crX0Y2 = crX0 * crY2; crX0Y3 = crX0 * crY3; crX1Y0 = crX1 * crY0; crX1Y2 = crX1 * crY2; crX1Y3 = crX1 * crY3; crX2Y0 = crX2 * crY0; crX2Y1 = crX2 * crY1; crX2Y3 = crX2 * crY3; crX3Y0 = crX3 * crY0; crX3Y1 = crX3 * crY1; crX3Y2 = crX3 * crY2; crZ0W1 = crZ0 * crW1; crZ0W2 = crZ0 * crW2; crZ0W3 = crZ0 * crW3; crZ1W0 = crZ1 * crW0; crZ1W2 = crZ1 * crW2; crZ1W3 = crZ1 * crW3; crZ2W0 = crZ2 * crW0; crZ2W1 = crZ2 * crW1; crZ2W3 = crZ2 * crW3; crZ3W0 = crZ3 * crW0; crZ3W1 = crZ3 * crW1; crZ3W2 = crZ3 * crW2; crU0 = crX0Y1 - crX1Y0; crU1 = crX0Y2 - crX2Y0; crU2 = crX0Y3 - crX3Y0; crU3 = crX1Y2 - crX2Y1; crU4 = crX1Y3 - crX3Y1; crU5 = crX2Y3 - crX3Y2; crV0 = crZ0W1 - crZ1W0; crV1 = crZ0W2 - crZ2W0; crV2 = crZ0W3 - crZ3W0; crV3 = crZ1W2 - crZ2W1; crV4 = crZ1W3 - crZ3W1; crV5 = crZ2W3 - crZ3W2; crU0V5 = crU0 * crV5; crU1V4 = crU1 * crV4; crU2V3 = crU2 * crV3; crU3V2 = crU3 * crV2; crU4V1 = crU4 * crV1; crU5V0 = crU5 * crV0; crDet = crU0V5 - crU1V4 + crU2V3 + crU3V2 - crU4V1 + crU5V0; return crDet.GetSign(); } bool GetContainingTetrahedron(size_t pIndex, Tetrahedron*& tetra) const { size_t const numTetrahedra = mGraph.GetTetrahedra().size(); for (size_t t = 0; t < numTetrahedra; ++t) { size_t j; for (j = 0; j < 4; ++j) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace(); size_t v0Index = tetra->V[opposite[j][0]]; size_t v1Index = tetra->V[opposite[j][1]]; size_t v2Index = tetra->V[opposite[j][2]]; if (ToPlane(pIndex, v0Index, v1Index, v2Index) > 0) { // Point i sees face <v0,v1,v2> from outside the // tetrahedron. auto adjTetra = tetra->S[j]; if (adjTetra) { // Traverse to the tetrahedron sharing the face. tetra = adjTetra; break; } else { // We reached a hull face, so the point is outside // the hull. return false; } } } if (j == 4) { // The point is inside all four faces, so the point is inside // a tetrahedron. return true; } } LogError( "Unexpected termination of loop."); } void GetAndRemoveInsertionPolyhedron(size_t pIndex, TetrahedronPtrSet& candidates, DirectedTriangleKeySet& boundary) { // Locate the tetrahedra that make up the insertion polyhedron. TSManifoldMesh polyhedron; while (candidates.size() > 0) { Tetrahedron* tetra = *candidates.begin(); candidates.erase(candidates.begin()); for (size_t j = 0; j < 4; ++j) { auto adj = tetra->S[j]; if (adj && candidates.find(adj) == candidates.end()) { size_t v0Index = adj->V[0]; size_t v1Index = adj->V[1]; size_t v2Index = adj->V[2]; size_t v3Index = adj->V[3]; if (ToCircumsphere(pIndex, v0Index, v1Index, v2Index, v3Index) <= 0) { // Point P is in the circumsphere. candidates.insert(adj); } } } auto inserted = polyhedron.Insert(tetra->V[0], tetra->V[1], tetra->V[2], tetra->V[3]); LogAssert( inserted != nullptr, "Unexpected insertion failure."); auto removed = mGraph.Remove(tetra->V[0], tetra->V[1], tetra->V[2], tetra->V[3]); LogAssert( removed, "Unexpected removal failure."); } // Get the boundary triangles of the insertion polyhedron. for (auto const& element : polyhedron.GetTetrahedra()) { Tetrahedron* tetra = element.second.get(); for (size_t j = 0; j < 4; ++j) { if (!tetra->S[j]) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace(); int32_t v0 = tetra->V[opposite[j][0]]; int32_t v1 = tetra->V[opposite[j][1]]; int32_t v2 = tetra->V[opposite[j][2]]; boundary.insert(TriangleKey<true>(v0, v1, v2)); } } } } void Update(size_t pIndex) { auto const& smap = mGraph.GetTetrahedra(); Tetrahedron* tetra = smap.begin()->second.get(); if (GetContainingTetrahedron(pIndex, tetra)) { // The point is inside the convex hull. The insertion // polyhedron contains only tetrahedra in the current // tetrahedralization; the hull does not change. // Use a depth-first search for those tetrahedra whose // circumspheres contain point P. TetrahedronPtrSet candidates{}; candidates.insert(tetra); // Get the boundary of the insertion polyhedron C that // contains the tetrahedra whose circumspheres contain point // P. Polyhedron C contains this point. DirectedTriangleKeySet boundary{}; GetAndRemoveInsertionPolyhedron(pIndex, candidates, boundary); // The insertion polyhedron consists of the tetrahedra formed // by point i and the faces of C. for (auto const& key : boundary) { size_t v0Index = static_cast<size_t>(key.V[0]); size_t v1Index = static_cast<size_t>(key.V[1]); size_t v2Index = static_cast<size_t>(key.V[2]); if (ToPlane(pIndex, v0Index, v1Index, v2Index) < 0) { auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex), key.V[0], key.V[1], key.V[2]); LogAssert( inserted != nullptr, "Unexpected insertion failure."); } } } else { // The point is outside the convex hull. The insertion // polyhedron is formed by point P and any tetrahedra in the // current tetrahedralization whose circumspheres contain // point P. // Locate the convex hull of the tetrahedra. DirectedTriangleKeySet hull{}; for (auto const& element : smap) { Tetrahedron* t = element.second.get(); for (size_t j = 0; j < 4; ++j) { if (!t->S[j]) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace(); hull.insert(TriangleKey<true>(t->V[opposite[j][0]], t->V[opposite[j][1]], t->V[opposite[j][2]])); } } } // Iterate over all the hull faces and use the ones visible to // point i to locate the insertion polyhedron. auto const& tmap = mGraph.GetTriangles(); TetrahedronPtrSet candidates{}; DirectedTriangleKeySet visible{}; for (auto const& key : hull) { size_t v0Index = static_cast<size_t>(key.V[0]); size_t v1Index = static_cast<size_t>(key.V[1]); size_t v2Index = static_cast<size_t>(key.V[2]); if (ToPlane(pIndex, v0Index, v1Index, v2Index) > 0) { auto iter = tmap.find(TriangleKey<false>(key.V[0], key.V[1], key.V[2])); if (iter != tmap.end() && iter->second->T[1] == nullptr) { auto adj = iter->second->T[0]; if (adj && candidates.find(adj) == candidates.end()) { size_t a0Index = static_cast<size_t>(adj->V[0]); size_t a1Index = static_cast<size_t>(adj->V[1]); size_t a2Index = static_cast<size_t>(adj->V[2]); size_t a3Index = static_cast<size_t>(adj->V[3]); if (ToCircumsphere(pIndex, a0Index, a1Index, a2Index, a3Index) <= 0) { // Point P is in the circumsphere. candidates.insert(adj); } else { // Point P is not in the circumsphere but // the hull face is visible. visible.insert(key); } } } else { LogError( "This condition should not occur for rational arithmetic."); } } } // Get the boundary of the insertion subpolyhedron C that // contains the tetrahedra whose circumspheres contain // point P. DirectedTriangleKeySet boundary{}; GetAndRemoveInsertionPolyhedron(pIndex, candidates, boundary); // The insertion polyhedron P consists of the tetrahedra // formed by point i and the back faces of C *and* the visible // faces of mGraph-C. for (auto const& key : boundary) { size_t v0Index = static_cast<size_t>(key.V[0]); size_t v1Index = static_cast<size_t>(key.V[1]); size_t v2Index = static_cast<size_t>(key.V[2]); if (ToPlane(pIndex, v0Index, v1Index, v2Index) < 0) { // This is a back face of the boundary. auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex), key.V[0], key.V[1], key.V[2]); LogAssert( inserted != nullptr, "Unexpected insertion failure."); } } for (auto const& key : visible) { auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex), key.V[0], key.V[2], key.V[1]); LogAssert( inserted != nullptr, "Unexpected insertion failure."); } } } // If a vertex occurs multiple times in the 'vertices' input to the // constructor, the first processed occurrence of that vertex has an // index stored in this array. If there are no duplicates, then // mDuplicates[i] = i for all i. std::vector<size_t> mDuplicates; size_t mNumUniqueVertices; // If the intrinsic dimension of the input vertices is 0, 1 or 2, the // constructor returns early. The caller is responsible for retrieving // the dimension and taking an alternate path should the dimension be // smaller than 3. If the dimension is 0, all vertices are the same. // If the dimension is 1, the vertices lie on a line, in which case // the caller can project vertices[] onto the line for further // processing. If the dimension is 2, the vertices lie on a plane, in // which case the caller can project vertices[] onto the plane for // further processing. size_t mDimension; Line3<T> mLine; Plane3<T> mPlane; // These are computed by UpdateIndicesAdjacencies(). They are used // for point-containment queries in the tetrahedron mesh. size_t mNumTetrahedra; std::vector<int32_t> mIndices; std::vector<int32_t> mAdjacencies; private: // The query point for Update, GetContainingTriangle and // GetAndRemoveInsertionPolyhedron when the point is not an input // vertex to the constructor. ToPlane(...) and ToCircumsphere(...) // are passed indices into the vertex array. When the vertex is // valid, mVertices[] and mCRVertices[] are used for lookups. When the // vertex is 'negOne', the query point is used for lookups. mutable Vector3<T> mQueryPoint; mutable Vector3<InputRational> mIRQueryPoint; // Sufficient storage for the expression trees related to computing // the exact signs in ToPlane(...) and ToCircumsphere(...). static size_t constexpr maxNumCRPool = 98; mutable std::vector<ComputeRational> mCRPool; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSphere3Triangle3.h
.h
27,344
626
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FIQuery.h> #include <Mathematics/DistPointTriangle.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/Vector3.h> #include <Mathematics/QFNumber.h> namespace gte { // Currently, only a dynamic query is supported. A static query will // need to compute the intersection set of triangle and sphere. template <typename T> class FIQuery<T, Sphere3<T>, Triangle3<T>> { public: // The implementation for floating-point types. struct Result { Result() : intersectionType(0), contactTime((T)0), contactPoint(Vector3<T>::Zero()) { } // The cases are // 1. Objects initially overlapping. The contactPoint is only one // of infinitely many points in the overlap. // intersectionType = -1 // contactTime = 0 // contactPoint = triangle point closest to sphere.center // 2. Objects initially separated but do not intersect later. The // contactTime and contactPoint are invalid. // intersectionType = 0 // contactTime = 0 // contactPoint = (0,0,0) // 3. Objects initially separated but intersect later. // intersectionType = +1 // contactTime = first time T > 0 // contactPoint = corresponding first contact int32_t intersectionType; T contactTime; Vector3<T> contactPoint; }; template <typename Dummy = T> typename std::enable_if<!is_arbitrary_precision<Dummy>::value, Result>::type operator()(Sphere3<T> const& sphere, Vector3<T> const& sphereVelocity, Triangle3<T> const& triangle, Vector3<T> const& triangleVelocity) { Result result{}; // Test for initial overlap or contact. DCPQuery<T, Vector3<T>, Triangle3<T>> ptQuery; auto ptResult = ptQuery(sphere.center, triangle); T rsqr = sphere.radius * sphere.radius; if (ptResult.sqrDistance <= rsqr) { result.intersectionType = (ptResult.sqrDistance < rsqr ? -1 : +1); result.contactTime = (T)0; result.contactPoint = ptResult.closest[1]; return result; } // To reach here, the sphere and triangle are initially separated. // Compute the velocity of the sphere relative to the triangle. Vector3<T> V = sphereVelocity - triangleVelocity; T sqrLenV = Dot(V, V); if (sqrLenV == (T)0) { // The sphere and triangle are separated and the sphere is not // moving relative to the triangle, so there is no contact. // The 'result' is already set to the correct state for this // case. return result; } // Compute the triangle edge directions E[], the vector U normal // to the plane of the triangle, and compute the normals to the // edges in the plane of the triangle. TODO: For a nondeforming // triangle (or mesh of triangles), these quantities can all be // precomputed to reduce the computational cost of the query. Add // another operator()-query that accepts the precomputed values. // TODO: When the triangle is deformable, these quantities must be // computed, either by the caller or here. Optimize the code to // compute the quantities on-demand (i.e. only when they are // needed, but cache them for later use). std::array<Vector3<T>, 3> E = { triangle.v[1] - triangle.v[0], triangle.v[2] - triangle.v[1], triangle.v[0] - triangle.v[2] }; std::array<T, 3> sqrLenE = { Dot(E[0], E[0]), Dot(E[1], E[1]), Dot(E[2], E[2]) }; Vector3<T> U = UnitCross(E[0], E[1]); std::array<Vector3<T>, 3> ExU = { Cross(E[0], U), Cross(E[1], U), Cross(E[2], U) }; // Compute the vectors from the triangle vertices to the sphere // center. std::array<Vector3<T>,3 > Delta = { sphere.center - triangle.v[0], sphere.center - triangle.v[1], sphere.center - triangle.v[2] }; // Determine where the sphere center is located relative to the // planes of the triangle offset faces of the sphere-swept volume. T dotUDelta0 = Dot(U, Delta[0]); if (dotUDelta0 >= sphere.radius) { // The sphere is on the positive side of Dot(U,X-C) = r. If // the sphere will contact the sphere-swept volume at a // triangular face, it can do so only on the face of the // aforementioned plane. T dotUV = Dot(U, V); if (dotUV >= (T)0) { // The sphere is moving away from, or parallel to, the // plane of the triangle. The 'result' is already set to // the correct state for this case. return result; } T tbar = (sphere.radius - dotUDelta0) / dotUV; bool foundContact = true; for (int32_t i = 0; i < 3; ++i) { T phi = Dot(ExU[i], Delta[i]); T psi = Dot(ExU[i], V); if (phi + psi * tbar > (T)0) { foundContact = false; break; } } if (foundContact) { result.intersectionType = 1; result.contactTime = tbar; result.contactPoint = sphere.center + tbar * sphereVelocity; return result; } } else if (dotUDelta0 <= -sphere.radius) { // The sphere is on the positive side of Dot(-U,X-C) = r. If // the sphere will contact the sphere-swept volume at a // triangular face, it can do so only on the face of the // aforementioned plane. T dotUV = Dot(U, V); if (dotUV <= (T)0) { // The sphere is moving away from, or parallel to, the // plane of the triangle. The 'result' is already set to // the correct state for this case. return result; } T tbar = (-sphere.radius - dotUDelta0) / dotUV; bool foundContact = true; for (int32_t i = 0; i < 3; ++i) { T phi = Dot(ExU[i], Delta[i]); T psi = Dot(ExU[i], V); if (phi + psi * tbar > (T)0) { foundContact = false; break; } } if (foundContact) { result.intersectionType = 1; result.contactTime = tbar; result.contactPoint = sphere.center + tbar * sphereVelocity; return result; } } // else: The ray-sphere-swept-volume contact point (if any) cannot // be on a triangular face of the sphere-swept-volume. // The sphere is moving towards the slab between the two planes // of the sphere-swept volume triangular faces. Determine whether // the ray intersects the half cylinders or sphere wedges of the // sphere-swept volume. // Test for contact with half cylinders of the sphere-swept // volume. First, precompute some dot products required in the // computations. TODO: Optimize the code to compute the quantities // on-demand (i.e. only when they are needed, but cache them for // later use). std::array<T, 3> del{}, delp{}, nu{}; for (int32_t im1 = 2, i = 0; i < 3; im1 = i++) { del[i] = Dot(E[i], Delta[i]); delp[im1] = Dot(E[im1], Delta[i]); nu[i] = Dot(E[i], V); } for (int32_t i = 2, ip1 = 0; ip1 < 3; i = ip1++) { Vector3<T> hatV = V - E[i] * nu[i] / sqrLenE[i]; T sqrLenHatV = Dot(hatV, hatV); if (sqrLenHatV > (T)0) { Vector3<T> hatDelta = Delta[i] - E[i] * del[i] / sqrLenE[i]; T alpha = -Dot(hatV, hatDelta); if (alpha >= (T)0) { T sqrLenHatDelta = Dot(hatDelta, hatDelta); T beta = alpha * alpha - sqrLenHatV * (sqrLenHatDelta - rsqr); if (beta >= (T)0) { T tbar = (alpha - std::sqrt(beta)) / sqrLenHatV; T mu = Dot(ExU[i], Delta[i]); T omega = Dot(ExU[i], hatV); if (mu + omega * tbar >= (T)0) { if (del[i] + nu[i] * tbar >= (T)0) { if (delp[i] + nu[i] * tbar <= (T)0) { // The constraints are satisfied, so // tbar is the first time of contact. result.intersectionType = 1; result.contactTime = tbar; result.contactPoint = sphere.center + tbar * sphereVelocity; return result; } } } } } } } // Test for contact with sphere wedges of the sphere-swept // volume. We know that |V|^2 > 0 because of a previous // early-exit test. for (int32_t im1 = 2, i = 0; i < 3; im1 = i++) { T alpha = -Dot(V, Delta[i]); if (alpha >= (T)0) { T sqrLenDelta = Dot(Delta[i], Delta[i]); T beta = alpha * alpha - sqrLenV * (sqrLenDelta - rsqr); if (beta >= (T)0) { T tbar = (alpha - std::sqrt(beta)) / sqrLenV; if (delp[im1] + nu[im1] * tbar >= (T)0) { if (del[i] + nu[i] * tbar <= (T)0) { // The constraints are satisfied, so tbar // is the first time of contact. result.intersectionType = 1; result.contactTime = tbar; result.contactPoint = sphere.center + tbar * sphereVelocity; return result; } } } } } // The ray and sphere-swept volume do not intersect, so the sphere // and triangle do not come into contact. The 'result' is already // set to the correct state for this case. return result; } // The implementation for arbitrary-precision types. using QFN1 = QFNumber<T, 1>; struct ExactResult { ExactResult() : intersectionType(0), contactTime{}, contactPoint{} { } // The cases are // 1. Objects initially overlapping. The contactPoint is only one // of infinitely many points in the overlap. // intersectionType = -1 // contactTime = 0 // contactPoint = triangle point closest to sphere.center // 2. Objects initially separated but do not intersect later. The // contactTime and contactPoint are invalid. // intersectionType = 0 // contactTime = 0 // contactPoint = (0,0,0) // 3. Objects initially separated but intersect later. // intersectionType = +1 // contactTime = first time T > 0 // contactPoint = corresponding first contact int32_t intersectionType; // The exact representation of the contact time and point. To // convert to a floating-point type, use // FloatType contactTime; // Vector3<FloatType> contactPoint; // Result::Convert(result.contactTime, contactTime); // Result::Convert(result.contactPoint, contactPoint); template <typename OutputType> static void Convert(QFN1 const& input, OutputType& output) { output = static_cast<T>(input); } template <typename OutputType> static void Convert(Vector3<QFN1> const& input, Vector3<OutputType>& output) { for (int32_t i = 0; i < 3; ++i) { output[i] = static_cast<T>(input[i]); } } QFN1 contactTime; Vector3<QFN1> contactPoint; }; template <typename Dummy = T> typename std::enable_if<is_arbitrary_precision<Dummy>::value, ExactResult>::type operator()(Sphere3<T> const& sphere, Vector3<T> const& sphereVelocity, Triangle3<T> const& triangle, Vector3<T> const& triangleVelocity) { // The default constructors for the members of 'result' set their // own members to zero. ExactResult result{}; // Test for initial overlap or contact. DCPQuery<T, Vector3<T>, Triangle3<T>> ptQuery{}; auto ptResult = ptQuery(sphere.center, triangle); T rsqr = sphere.radius * sphere.radius; if (ptResult.sqrDistance <= rsqr) { // The values result.contactTime and result.contactPoint[] // are both zero, so we need only set the // result.contactPoint[].x values. result.intersectionType = (ptResult.sqrDistance < rsqr ? -1 : +1); for (int32_t j = 0; j < 3; ++j) { result.contactPoint[j].x = ptResult.closest[j]; } return result; } // To reach here, the sphere and triangle are initially separated. // Compute the velocity of the sphere relative to the triangle. Vector3<T> V = sphereVelocity - triangleVelocity; T sqrLenV = Dot(V, V); if (sqrLenV == (T)0) { // The sphere and triangle are separated and the sphere is not // moving relative to the triangle, so there is no contact. // The 'result' is already set to the correct state for this // case. return result; } // Compute the triangle edge directions E[], the vector U normal // to the plane of the triangle, and compute the normals to the // edges in the plane of the triangle. TODO: For a nondeforming // triangle (or mesh of triangles), these quantities can all be // precomputed to reduce the computational cost of the query. Add // another operator()-query that accepts the precomputed values. // TODO: When the triangle is deformable, these quantities must be // computed, either by the caller or here. Optimize the code to // compute the quantities on-demand (i.e. only when they are // needed, but cache them for later use). std::array<Vector3<T>, 3> E = { triangle.v[1] - triangle.v[0], triangle.v[2] - triangle.v[1], triangle.v[0] - triangle.v[2] }; std::array<T, 3> sqrLenE = { Dot(E[0], E[0]), Dot(E[1], E[1]), Dot(E[2], E[2]) }; // Use an unnormalized U for the plane of the triangle. This // allows us to use quadratic fields for the comparisons of the // constraints. Vector3<T> U = Cross(E[0], E[1]); T sqrLenU = Dot(U, U); std::array<Vector3<T>, 3> ExU = { Cross(E[0], U), Cross(E[1], U), Cross(E[2], U) }; // Compute the vectors from the triangle vertices to the sphere // center. std::array<Vector3<T>, 3> Delta = { sphere.center - triangle.v[0], sphere.center - triangle.v[1], sphere.center - triangle.v[2] }; // Determine where the sphere center is located relative to the // planes of the triangle offset faces of the sphere-swept volume. QFN1 const qfzero((T)0, (T)0, sqrLenU); QFN1 element(Dot(U, Delta[0]), -sphere.radius, sqrLenU); if (element >= qfzero) { // The sphere is on the positive side of Dot(U,X-C) = r|U|. // If the sphere will contact the sphere-swept volume at a // triangular face, it can do so only on the face of the // aforementioned plane. T dotUV = Dot(U, V); if (dotUV >= (T)0) { // The sphere is moving away from, or parallel to, the // plane of the triangle. The 'result' is already set // to the correct state for this case. return result; } bool foundContact = true; for (int32_t i = 0; i < 3; ++i) { T phi = Dot(ExU[i], Delta[i]); T psi = Dot(ExU[i], V); QFN1 arg(psi * element.x - phi * dotUV, psi * element.y, sqrLenU); if (arg > qfzero) { foundContact = false; break; } } if (foundContact) { result.intersectionType = 1; result.contactTime.x = -element.x / dotUV; result.contactTime.y = -element.y / dotUV; for (int32_t j = 0; j < 3; ++j) { result.contactPoint[j].x = sphere.center[j] + result.contactTime.x * sphereVelocity[j]; result.contactPoint[j].y = result.contactTime.y * sphereVelocity[j]; } return result; } } else { element.y = -element.y; if (element <= qfzero) { // The sphere is on the positive side of Dot(-U,X-C) = r|U|. // If the sphere will contact the sphere-swept volume at a // triangular face, it can do so only on the face of the // aforementioned plane. T dotUV = Dot(U, V); if (dotUV <= (T)0) { // The sphere is moving away from, or parallel to, the // plane of the triangle. The 'result' is already set // to the correct state for this case. return result; } bool foundContact = true; for (int32_t i = 0; i < 3; ++i) { T phi = Dot(ExU[i], Delta[i]); T psi = Dot(ExU[i], V); QFN1 arg(phi * dotUV - psi * element.x, -psi * element.y, sqrLenU); if (arg > qfzero) { foundContact = false; break; } } if (foundContact) { result.intersectionType = 1; result.contactTime.x = -element.x / dotUV; result.contactTime.y = -element.y / dotUV; for (int32_t j = 0; j < 3; ++j) { result.contactPoint[j].x = sphere.center[j] + result.contactTime.x * sphereVelocity[j]; result.contactPoint[j].y = result.contactTime.y * sphereVelocity[j]; } return result; } } // else: The ray-sphere-swept-volume contact point (if any) // cannot be on a triangular face of the sphere-swept-volume. } // The sphere is moving towards the slab between the two planes // of the sphere-swept volume triangular faces. Determine whether // the ray intersects the half cylinders or sphere wedges of the // sphere-swept volume. // Test for contact with half cylinders of the sphere-swept // volume. First, precompute some dot products required in the // computations. TODO: Optimize the code to compute the quantities // on-demand (i.e. only when they are needed, but cache them for // later use). std::array<T, 3> del{}, delp{}, nu{}; for (int32_t im1 = 2, i = 0; i < 3; im1 = i++) { del[i] = Dot(E[i], Delta[i]); delp[im1] = Dot(E[im1], Delta[i]); nu[i] = Dot(E[i], V); } for (int32_t i = 2, ip1 = 0; ip1 < 3; i = ip1++) { Vector3<T> hatV = V - E[i] * nu[i] / sqrLenE[i]; T sqrLenHatV = Dot(hatV, hatV); if (sqrLenHatV > (T)0) { Vector3<T> hatDelta = Delta[i] - E[i] * del[i] / sqrLenE[i]; T alpha = -Dot(hatV, hatDelta); if (alpha >= (T)0) { T sqrLenHatDelta = Dot(hatDelta, hatDelta); T beta = alpha * alpha - sqrLenHatV * (sqrLenHatDelta - rsqr); if (beta >= (T)0) { QFN1 const qfzero((T)0, (T)0, beta); T mu = Dot(ExU[i], Delta[i]); T omega = Dot(ExU[i], hatV); QFN1 arg0(mu * sqrLenHatV + omega * alpha, -omega, beta); if (arg0 >= qfzero) { QFN1 arg1(del[i] * sqrLenHatV + nu[i] * alpha, -nu[i], beta); if (arg1 >= qfzero) { QFN1 arg2(delp[i] * sqrLenHatV + nu[i] * alpha, -nu[i], beta); if (arg2 <= qfzero) { result.intersectionType = 1; result.contactTime.x = alpha / sqrLenHatV; result.contactTime.y = (T)-1 / sqrLenHatV; for (int32_t j = 0; j < 3; ++j) { result.contactPoint[j].x = sphere.center[j] + result.contactTime.x * sphereVelocity[j]; result.contactPoint[j].y = result.contactTime.y * sphereVelocity[j]; } return result; } } } } } } } // Test for contact with sphere wedges of the sphere-swept // volume. We know that |V|^2 > 0 because of a previous // early-exit test. for (int32_t im1 = 2, i = 0; i < 3; im1 = i++) { T alpha = -Dot(V, Delta[i]); if (alpha >= (T)0) { T sqrLenDelta = Dot(Delta[i], Delta[i]); T beta = alpha * alpha - sqrLenV * (sqrLenDelta - rsqr); if (beta >= (T)0) { QFN1 const qfzero((T)0, (T)0, beta); QFN1 arg0(delp[im1] * sqrLenV + nu[im1] * alpha, -nu[im1], beta); if (arg0 >= qfzero) { QFN1 arg1(del[i] * sqrLenV + nu[i] * alpha, -nu[i], beta); if (arg1 <= qfzero) { result.intersectionType = 1; result.contactTime.x = alpha / sqrLenV; result.contactTime.y = (T)-1 / sqrLenV; for (int32_t j = 0; j < 3; ++j) { result.contactPoint[j].x = sphere.center[j] + result.contactTime.x * sphereVelocity[j]; result.contactPoint[j].y = result.contactTime.y * sphereVelocity[j]; } return result; } } } } } // The ray and sphere-swept volume do not intersect, so the sphere // and triangle do not come into contact. The 'result' is already // set to the correct state for this case. return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SingularValueDecomposition.h
.h
35,486
925
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <algorithm> #include <functional> #include <vector> // The SingularValueDecomposition class is an implementation of Algorithm // 8.3.2 (The SVD Algorithm) described in "Matrix Computations, 2nd // edition" by G. H. Golub and Charles F. Van Loan, The Johns Hopkins // Press, Baltimore MD, Fourth Printing 1993. Algorithm 5.4.2 (Householder // Bidiagonalization) is used to reduce A to bidiagonal B. Algorithm 8.3.1 // (Golub-Kahan SVD Step) is used for the iterative reduction from bidiagonal // to diagonal. If A is the original matrix, S is the matrix whose diagonal // entries are the singular values, and U and V are corresponding matrices, // then theoretically U^T*A*V = S. Numerically, we have errors E = U^T*A*V-S. // Algorithm 8.3.2 mentions that one expects |E| is approximately // unitRoundoff*|A|, where |A| denotes the Frobenius norm of A and where // unitRoundoff is 2^{-23} for Real=float, which is // std::numeric_limits<float>::epsilon() = 1.192092896e-7f // or 2^{-52} for Real=double, which is // std::numeric_limits<double>::epsilon() = 2.2204460492503131e-16. // // During the iterations that process B, the bidiagonalized A, a superdiagonal // entry is determined to be effectively zero when compared to its neighboring // diagonal and superdiagonal elements, // |b(i,i+1)| <= e * (|b(i,i) + b(i+1,i+1)|) // The suggestion by Golub and van Loan is to choose e to be a small positive // multiple of the unit roundoff, e = multiplier * unitRoundoff. A diagonal // entry is determined to be effectively zero relative to a norm of B, // |b(i,i)| <= e * |B| // The implementation uses the L-infinity norm for |B|, which is the largest // absolute value of the diagonal and superdiagonal elements of B. // // The authors suggest that once you have the bidiagonal matrix, a practical // implementation will store the diagonal and superdiagonal entries in linear // arrays, ignoring the theoretically zero values not in the 2-band. This is // good for cache coherence. The implementation uses separate storage for // the Householder u-vectors, so the essential parts of these vectors is not // stored in the local copy of A (as suggested by Golub and van Loan) in order // to make the implementation more readable. namespace gte { template <typename Real> class SingularValueDecomposition { public: // The solver processes MxN symmetric matrices, where M >= N > 1 // ('numRows' is M and 'numCols' is N) and the matrix is stored in // row-major order. The maximum number of iterations ('maxIterations') // must be specified for the reduction of a bidiagonal matrix to a // diagonal matrix. The goal is to compute MxM orthogonal U, NxN // orthogonal V and MxN matrix S for which U^T*A*V = S. The only // nonzero entries of S are on the diagonal; the diagonal entries // are the singular values of the original matrix. SingularValueDecomposition(size_t numRows, size_t numCols, size_t maxIterations) : mNumRows(numRows), mNumCols(numCols), mMaxIterations(maxIterations), mMatrix{}, mUMatrix{}, mVMatrix{}, mSMatrix{}, mDiagonal{}, mSuperdiagonal{}, mLHouseholder{}, mRHouseholder{}, mLGivens{}, mRGivens{} { LogAssert( mNumCols >= 2 && mNumRows >= mNumCols && mMaxIterations > 0, "Invalid input."); mMatrix.resize(mNumRows * mNumCols); mUMatrix.resize(mNumRows * mNumRows); mVMatrix.resize(mNumCols * mNumCols); mSMatrix.resize(mNumRows * mNumCols); mDiagonal.resize(mNumCols); mSuperdiagonal.resize(mNumCols - 1); mLHouseholder.resize(mNumCols); for (size_t col = 0; col < mLHouseholder.size(); ++col) { mLHouseholder[col].resize(mNumRows); } mRHouseholder.resize(mNumCols - 2); for (size_t row = 0; row < mRHouseholder.size(); ++row) { mRHouseholder[row].resize(mNumCols); } mLGivens.reserve(mMaxIterations* (mNumCols - 1)); mRGivens.reserve(mMaxIterations* (mNumCols - 1)); } // A copy of the MxN input is made internally. The multiplier is a // small positive number used to compute e that is described in the // preamble comments of this file. The default is 8, but you can // adjust this based on the needs of your application. The return // value is the number of iterations consumed when convergence // occurs or std::numeric_limits<size_t>::max() when convergence // does not occur. size_t Solve(Real const* input, Real multiplier = static_cast<Real>(8)) { Real const zero = static_cast<Real>(0); LogAssert( input != nullptr && multiplier > zero, "Invalid input to Solve."); // Copy the input to mMatrix. The latter matrix is modified // internally by the solver. for (size_t i = 0; i < mMatrix.size(); ++i) { mMatrix[i] = input[i]; } // Reduce mMatrix to bidiagonal form, storing the diagonal // mMatrix(d,d) and superdiagonal mMatrix(d,d+1) in mDiagonal // and mSuperdiagonal, respectively. Bidiagonalize(); // The threshold is used to determine whether a diagonal entry of // the bidiagonal matrix B is sufficiently small so that it is // considered tobe zero. It is defined by // threshold = multiplier * unitRoundoff * |B|, where // unitRoundoff is std::numeric_limits<Real>::epsilon(), |B| is a // matrix norm and the multiplier is a small number [as suggested // before Algorithm 8.3.2 (The SVD Algorithm) in Golub and Van // Loan]. The L-infinity norm is used for B. Real epsilon{}, threshold{}; ComputeCutoffs(multiplier, epsilon, threshold); size_t constexpr invalid = std::numeric_limits<size_t>::max(); mRGivens.clear(); mLGivens.clear(); for (size_t iteration = 0; iteration < mMaxIterations; ++iteration) { // Set superdiagonal entries to zero if they are effectively // zero compared to the neighboring diagonal entries. size_t numZero = 0; for (size_t i = 0; i <= mNumCols - 2; ++i) { Real absSuper = std::fabs(mSuperdiagonal[i]); Real absDiag0 = std::fabs(mDiagonal[i]); Real absDiag1 = std::fabs(mDiagonal[i + 1]); if (absSuper <= epsilon * (absDiag0 + absDiag1)) { mSuperdiagonal[i] = zero; ++numZero; } } if (numZero == mNumCols - 1) { // The superdiagonal terms are all effectively zero, so // the algorithm has converged. Compute U, V and S. ComputeOrthogonalMatrices(); return iteration; } // Find the largest sequence {iMin,...,iMax} for which the // superdiagonal entries are all not effectively zero. On // loop termination, iMax != invalid because if all // superdiagonal terms were zero, the previous if-statement // "if (numZero == mNumCols - 1)" would ensure an exit from // the function. size_t iMax; for (iMax = mNumCols - 2; iMax != 0; --iMax) { if (mSuperdiagonal[iMax] != zero) { break; } } ++iMax; size_t iMin; for (iMin = iMax - 1; iMin != invalid; --iMin) { if (mSuperdiagonal[iMin] == zero) { break; } } ++iMin; // The subblock corresponding to {iMin,...,iMax} has all // superdiagonal entries not effectively zero. Determine // whether this subblock has a diagonal entry that is // effectively zero. If it does, use Givens rotations to // zero-out the row containing that entry. if (DiagonalEntriesNonzero(iMin, iMax, threshold)) { DoGolubKahanStep(iMin, iMax); } } return invalid; } // Get the U-matrix, which is MxM and stored in row-major order. void GetU(Real* uMatrix) const { LogAssert( uMatrix != nullptr, "Nonnull pointer required for uMatrix."); for (size_t i = 0; i < mUMatrix.size(); ++i) { uMatrix[i] = mUMatrix[i]; } } // Get the V-matrix, which is NxN and stored in row-major order. void GetV(Real* vMatrix) const { LogAssert( vMatrix != nullptr, "Nonnull pointer required for vMatrix."); for (size_t i = 0; i < mUMatrix.size(); ++i) { vMatrix[i] = mVMatrix[i]; } } // Get the S-matrix, which is MxN and stored in row-major order. void GetS(Real* sMatrix) const { LogAssert( sMatrix != nullptr, "Nonnull pointer required for sMatrix."); for (size_t i = 0; i < mSMatrix.size(); ++i) { sMatrix[i] = mSMatrix[i]; } } Real GetSingularValue(size_t index) const { LogAssert( index < mNumCols, "Invalid index for singular value."); return mSMatrix[index + mNumCols * index]; } void GetUColumn(size_t index, Real* uColumn) const { LogAssert( index < mNumRows && uColumn != nullptr, "Invalid index or null pointer for U-column."); for (size_t row = 0; row < mNumRows; ++row) { uColumn[row] = mUMatrix[index + mNumRows * row]; } } void GetVColumn(size_t index, Real* vColumn) const { LogAssert( index < mNumCols && vColumn != nullptr, "Invalid index or null pointer for V-column."); for (size_t row = 0; row < mNumCols; ++row) { vColumn[row] = mVMatrix[index + mNumCols * row]; } } // Get the singular values, which is an N-element array. void GetSingularValues(Real* singularValues) const { LogAssert( singularValues != nullptr, "Nonnull pointer required for singularValues."); for (size_t index = 0; index < mNumCols; ++index) { singularValues[index] = mSMatrix[index + mNumCols * index]; } } private: static Real constexpr unitRoundoff = std::numeric_limits<Real>::epsilon(); // Algorithm 5.1.1 (Householder Vector). The matrix A has size // numRows-by-numCols with numRows >= numCols and the vector v has // size numRows. static void ComputeHouseholderU(size_t numRows, size_t numCols, Real const* A, size_t selectCol, Real* v) { // Extract the column vector v[] where v[row] = A(row, selectCol). // The elements v[row] = 0 for 0 <= row < selectCol to avoid // conceptual uninitialized memory; the caller should not // reference these elements. Real const zero = static_cast<Real>(0); size_t row; for (row = 0; row < selectCol; ++row) { v[row] = zero; } Real mu = zero; for (; row < numRows; ++row) { Real element = A[selectCol + numCols * row]; mu += element * element; v[row] = element; } mu = std::sqrt(mu); if (mu != zero) { Real beta = v[selectCol] + (v[selectCol] >= zero ? mu : -mu); for (row = selectCol + 1; row < numRows; ++row) { v[row] /= beta; } } v[selectCol] = static_cast<Real>(1); } // Algorithm 5.1.1 (Householder Vector). The matrix A has size // numRows-by-numCols with numRows >= numCols and the vector v has // size numCols. static void ComputeHouseholderV(size_t numRows, size_t numCols, Real const* A, size_t selectRow, Real* v) { // Extract the row vector v[] where v[col] = A(selectRow, col). // The elements v[col] = 0 for 0 <= col <= selectRow to avoid // conceptual uninitialized memory; the caller should not // reference these elements. (void)numRows; Real const zero = static_cast<Real>(0); size_t selectRowP1 = selectRow + 1; size_t col; for (col = 0; col < selectRowP1; ++col) { v[col] = zero; } Real mu = zero; for (; col < numCols; ++col) { Real element = A[col + numCols * selectRow]; mu += element * element; v[col] = element; } mu = std::sqrt(mu); if (mu != zero) { Real beta = v[selectRowP1] + (v[selectRowP1] >= zero ? mu : -mu); for (col = selectRowP1 + 1; col < numCols; ++col) { v[col] /= beta; } } v[selectRowP1] = static_cast<Real>(1); } // Algorithm 5.1.2 (Householder Pre-Multiplication) static void DoHouseholderPremultiply(size_t numRows, size_t numCols, Real const* v, size_t selectCol, Real* A) { Real const zero = static_cast<Real>(0); Real vSqrLength = zero; for (size_t row = selectCol; row < numRows; ++row) { vSqrLength += v[row] * v[row]; } Real beta = static_cast<Real>(-2) / vSqrLength; std::vector<Real> w(numCols); for (size_t col = selectCol; col < numCols; ++col) { w[col] = zero; for (size_t row = selectCol; row < numRows; ++row) { w[col] += v[row] * A[col + numCols * row]; } w[col] *= beta; } for (size_t row = selectCol; row < numRows; ++row) { for (size_t col = selectCol; col < numCols; ++col) { A[col + numCols * row] += v[row] * w[col]; } } } // Algorithm 5.1.3 (Householder Post-Multiplication) static void DoHouseholderPostmultiply(size_t numRows, size_t numCols, Real const* v, size_t selectRow, Real* A) { Real const zero = static_cast<Real>(0); Real vSqrLength = zero; for (size_t col = selectRow; col < numCols; ++col) { vSqrLength += v[col] * v[col]; } Real beta = static_cast<Real>(-2) / vSqrLength; std::vector<Real> w(numRows); for (size_t row = selectRow; row < numRows; ++row) { w[row] = zero; for (size_t col = selectRow; col < numCols; ++col) { w[row] += A[col + numCols * row] * v[col]; } w[row] *= beta; } for (size_t row = selectRow; row < numRows; ++row) { for (size_t col = selectRow; col < numCols; ++col) { A[col + numCols * row] += w[row] * v[col]; } } } // Bidiagonalize using Householder reflections. On input, mMatrix is // a copy of the input matrix passed to Solve(...). On output, // mDiagonal and mSuperdiagonal contain the bidiagonalized results. void Bidiagonalize() { std::vector<Real> uVector(mNumRows), vVector(mNumCols); for (size_t i = 0; i < mNumCols; ++i) { // Compute the u-Householder vector. ComputeHouseholderU(mNumRows, mNumCols, mMatrix.data(), i, mLHouseholder[i].data()); // Update A = (I - 2*u*u^T/u^T*u) * A. DoHouseholderPremultiply(mNumRows, mNumCols, mLHouseholder[i].data(), i, mMatrix.data()); if (i < mRHouseholder.size()) { // Compute the v-Householder vectors. ComputeHouseholderV(mNumRows, mNumCols, mMatrix.data(), i, mRHouseholder[i].data()); // Update A = A * (I - 2*v*v^T/v^T*v). DoHouseholderPostmultiply(mNumRows, mNumCols, mRHouseholder[i].data(), i, mMatrix.data()); } } // Copy the diagonal and subdiagonal for cache coherence in the // Golub-Kahan iterations. for (size_t d = 0; d < mNumCols; ++d) { mDiagonal[d] = mMatrix[d + mNumCols * d]; } for (size_t s = 0; s < mNumCols - 1; ++s) { mSuperdiagonal[s] = mMatrix[(s + 1) + mNumCols * s]; } } void ComputeCutoffs(Real multiplier, Real& epsilon, Real& threshold) const { Real norm = static_cast<Real>(0); for (size_t i = 0; i < mNumCols; ++i) { Real abs = std::fabs(mDiagonal[i]); if (abs > norm) { norm = abs; } } for (size_t i = 0; i < mNumCols - 1; ++i) { Real abs = std::fabs(mSuperdiagonal[i]); if (abs > norm) { norm = abs; } } epsilon = multiplier * unitRoundoff; threshold = epsilon * norm; } // A helper for generating Givens rotation sine and cosine robustly // when solving sn * x + cs * y = 0. void GetSinCos(Real x, Real y, Real& cs, Real& sn) { Real const zero = static_cast<Real>(0); Real const one = static_cast<Real>(1); Real tau; if (y != zero) { if (std::fabs(y) > std::fabs(x)) { tau = -x / y; sn = one / std::sqrt(one + tau * tau); cs = sn * tau; } else { tau = -y / x; cs = one / std::sqrt(one + tau * tau); sn = cs * tau; } } else { cs = one; sn = zero; } } // Test for diagonal entries that are effectively zero through all // but the last. For each such entry, the B matrix decouples. Perform // that decoupling. If there are no zero-valued entries, then the // Golub-Kahan step must be performed. bool DiagonalEntriesNonzero(size_t iMin, size_t iMax, Real threshold) { Real const zero = static_cast<Real>(0); for (size_t i = iMin; i < iMax; ++i) { if (std::fabs(mDiagonal[i]) <= threshold) { // Use planar rotations to chase the superdiagonal entry // out of the matrix, which produces a row of zeros. Real x, z, cs, sn; Real y = mSuperdiagonal[i]; mSuperdiagonal[i] = zero; for (size_t j = i + 1; j <= iMax; ++j) { x = mDiagonal[j]; GetSinCos(x, y, cs, sn); // NOTE: The Givens parameters are (cs,-sn). The // negative sign is not a coding error. mLGivens.push_back(GivensRotation(i, j, cs, -sn)); mDiagonal[j] = cs * x - sn * y; if (j < iMax) { z = mSuperdiagonal[j]; mSuperdiagonal[j] = cs * z; y = sn * z; } } return false; } } return true; } // Algorithm 8.3.1 (Golub-Kahan SVD Step). void DoGolubKahanStep(size_t iMin, size_t iMax) { // The implicit shift. Let A = {{a00,a01},{a01,a11}} be the lower // right 2x2 block of B^T*B. Compute the eigenvalue u of A that // is closer to a11 than to a00. Real const zero = static_cast<Real>(0); Real f0, f1, d1, d2; if (iMax > 1) { f0 = mSuperdiagonal[iMax - 2]; f1 = mSuperdiagonal[iMax - 1]; d1 = mDiagonal[iMax - 1]; d2 = mDiagonal[iMax]; } else { f0 = zero; f1 = mSuperdiagonal[0]; d1 = mDiagonal[0]; d2 = mDiagonal[1]; } // Compute the lower right 2x2 block of B^T*B. Real a00 = d1 * d1 + f0 * f0; Real a01 = d1 * f1; Real a11 = d2 * d2 + f1 * f1; // The eigenvalues are ((a00+a11) +/- sqrt((a00-a11)^2+a01^2))/2, // which are equidistant from (a00+a11)/2. If a11 >= a00, the // required eigenvalue uses the (+) sqrt term. If a11 <= a00, the // required eigenvalue uses the (-) sqrt term. Real sum = a00 + a11; Real dif = a00 - a11; Real root = std::sqrt(dif * dif + a01 * a01); Real lambda = static_cast<Real>(0.5) * (a11 >= a00 ? sum + root : sum - root); Real x = mDiagonal[iMin] * mDiagonal[iMin] - lambda; Real y = mDiagonal[iMin] * mSuperdiagonal[iMin]; Real a12, a21, a22, a23, cs, sn; Real a02 = zero; for (size_t i0 = iMin - 1, i1 = iMin, i2 = iMin + 1; i1 <= iMax - 1; ++i0, ++i1, ++i2) { // Compute the Givens rotation G and save it for use in // computing V in U^T*A*V = S. GetSinCos(x, y, cs, sn); mRGivens.push_back(GivensRotation(i1, i2, cs, sn)); // Update B0 = B*G. if (i1 > iMin) { mSuperdiagonal[i0] = cs * mSuperdiagonal[i0] - sn * a02; } a11 = mDiagonal[i1]; a12 = mSuperdiagonal[i1]; a22 = mDiagonal[i2]; mDiagonal[i1] = cs * a11 - sn * a12; mSuperdiagonal[i1] = sn * a11 + cs * a12; mDiagonal[i2] = cs * a22; a21 = -sn * a22; // Update the parameters for the next Givens rotations. x = mDiagonal[i1]; y = a21; // Compute the Givens rotation G and save it for use in // computing U in U^T*A*V = S. GetSinCos(x, y, cs, sn); mLGivens.push_back(GivensRotation(i1, i2, cs, sn)); // Update B1 = G^T*B0. a11 = mDiagonal[i1]; a12 = mSuperdiagonal[i1]; a22 = mDiagonal[i2]; mDiagonal[i1] = cs * a11 - sn * a21; mSuperdiagonal[i1] = cs * a12 - sn * a22; mDiagonal[i2] = sn * a12 + cs * a22; if (i1 < iMax - 1) { a23 = mSuperdiagonal[i2]; a02 = -sn * a23; mSuperdiagonal[i2] = cs * a23; // Update the parameters for the next Givens rotations. x = mSuperdiagonal[i1]; y = a02; } } } void ComputeOrthogonalMatrices() { // Compute U and V given the current signed singular values. ComputeUOrthogonal(); ComputeVOrthogonal(); // Ensure the singular values are nonnegative. The sign changes // are absorbed by the U-matrix. The nonnegative values are // stored in the S-matrix. EnsureNonnegativeSingularValues(); // Sort the singular values in descending order. The sort // permutations are absorbed by the U-matrix and V-matrix. SortSingularValues(); } void ComputeUOrthogonal() { // Start with the identity matrix for U. Real const zero = static_cast<Real>(0); Real const one = static_cast<Real>(1); std::fill(mUMatrix.begin(), mUMatrix.end(), zero); for (size_t d = 0; d < mNumRows; ++d) { mUMatrix[d + mNumRows * d] = one; } // Multiply the Householder reflections using backward // accumulation. This allows DoHouseholderPremultiply. A forward // accumulation using DoHouseholderPostmultiply does not work // because the semantics of DoHouseholderPostmultiply are // slightly different from those of DoHouseholderPremultiply. for (size_t k = 0, col = mNumCols - 1; k <= mNumCols - 1; ++k, --col) { DoHouseholderPremultiply(mNumRows, mNumRows, mLHouseholder[col].data(), col, mUMatrix.data()); } // Multiply the Givens rotations using forward accumulation. for (auto const& givens : mLGivens) { size_t j0 = givens.index0; size_t j1 = givens.index1; for (size_t row = 0; row < mNumRows; ++row, j0 += mNumRows, j1 += mNumRows) { Real& q0 = mUMatrix[j0]; Real& q1 = mUMatrix[j1]; Real prd0 = givens.cs * q0 - givens.sn * q1; Real prd1 = givens.sn * q0 + givens.cs * q1; q0 = prd0; q1 = prd1; } } } void ComputeVOrthogonal() { // Start with the identity matrix for V. Real const zero = static_cast<Real>(0); Real const one = static_cast<Real>(1); std::fill(mVMatrix.begin(), mVMatrix.end(), zero); for (size_t d = 0; d < mNumCols; ++d) { mVMatrix[d + mNumCols * d] = one; } // Multiply the Householder reflections using backward // accumulation. This allows DoHouseholderPremultiply. A forward // accumulation using DoHouseholderPostmultiply does not work // because the semantics of DoHouseholderPostmultiply are // slightly different from those of DoHouseholderPremultiply. for (size_t k = 0, col = mNumCols - 3; k <= mNumCols - 3; ++k, --col) { DoHouseholderPremultiply(mNumCols, mNumCols, mRHouseholder[col].data(), col, mVMatrix.data()); } // Multiply the Givens rotations using forward accumulation. for (auto const& givens : mRGivens) { size_t j0 = givens.index0; size_t j1 = givens.index1; for (size_t col = 0; col < mNumCols; ++col, j0 += mNumCols, j1 += mNumCols) { Real& q0 = mVMatrix[j0]; Real& q1 = mVMatrix[j1]; Real prd0 = givens.cs * q0 - givens.sn * q1; Real prd1 = givens.sn * q0 + givens.cs * q1; q0 = prd0; q1 = prd1; } } } void EnsureNonnegativeSingularValues() { Real const zero = static_cast<Real>(0); std::fill(mSMatrix.begin(), mSMatrix.end(), zero); for (size_t i = 0; i < mNumCols; ++i) { if (mDiagonal[i] >= zero) { mSMatrix[i + mNumCols * i] = mDiagonal[i]; } else { mSMatrix[i + mNumCols * i] = -mDiagonal[i]; for (size_t row = 0; row < mNumRows; ++row) { Real& element = mUMatrix[i + mNumRows * row]; element = -element; } } } } void SortSingularValues() { // Sort the nonnegative singular values. std::vector<SingularInfo> sorted(mNumCols); for (size_t i = 0; i < mNumCols; ++i) { sorted[i].singular = mSMatrix[i + mNumCols * i]; sorted[i].inversePermute = i; } std::sort(sorted.begin(), sorted.end(), std::greater<SingularInfo>()); for (size_t i = 0; i < mNumCols; ++i) { mSMatrix[i + mNumCols * i] = sorted[i].singular; } // Compute the inverse permutation of the sorting. std::vector<size_t> permute(mNumCols); for (size_t i = 0; i < mNumCols; ++i) { permute[sorted[i].inversePermute] = i; } // Permute the columns of the U-matrix to be consistent with the // sorted singular values. std::vector<Real> sortedUMatrix(mNumRows * mNumRows); size_t col; for (col = 0; col < mNumCols; ++col) { for (size_t row = 0; row < mNumRows; ++row) { Real const& source = mUMatrix[col + mNumRows * row]; Real& target = sortedUMatrix[permute[col] + mNumRows * row]; target = source; } } for (; col < mNumRows; ++col) { for (size_t row = 0; row < mNumRows; ++row) { Real const& source = mUMatrix[col + mNumRows * row]; Real& target = sortedUMatrix[col + mNumRows * row]; target = source; } } mUMatrix = std::move(sortedUMatrix); // Permute the columns of the U-matrix to be consistent with the // sorted singular values. std::vector<Real> sortedVMatrix(mNumCols * mNumCols); for (col = 0; col < mNumCols; ++col) { for (size_t row = 0; row < mNumCols; ++row) { Real const& source = mVMatrix[col + mNumCols * row]; Real& target = sortedVMatrix[permute[col] + mNumCols * row]; target = source; } } mVMatrix = std::move(sortedVMatrix); } // The number rows and columns of the matrices to be processed. size_t mNumRows, mNumCols; // The maximum number of iterations for reducing the bidiagonal matrix // to a diagonal matrix. size_t mMaxIterations; // The internal copy of a matrix passed to the solver. This is // stored in row-major order. std::vector<Real> mMatrix; // MxN elements // The U-matrix, V-matrix and S-matrix for which U*A*V^T = S. These // are stored in row-major order. std::vector<Real> mUMatrix; // MxM std::vector<Real> mVMatrix; // NxN std::vector<Real> mSMatrix; // MxN // The diagonal and superdiagonal of the bidiagonalized matrix. std::vector<Real> mDiagonal; // N elements std::vector<Real> mSuperdiagonal; // N-1 elements // The Householder reflections used to reduce the input matrix to // a bidiagonal matrix. std::vector<std::vector<Real>> mLHouseholder; std::vector<std::vector<Real>> mRHouseholder; // The Givens rotations used to reduce the initial bidiagonal matrix // to a diagonal matrix. A rotation is the identity with the following // replacement entries: R(index0,index0) = cs, R(index0,index1) = sn, // R(index1,index0) = -sn and R(index1,index1) = cs. If N is the // number of matrix columns and K is the maximum number of iterations, // the maximum number of right or left Givens rotations is K*(N-1). // The maximum amount of memory is allocated to store these. However, // we also potentially need left rotations to decouple the matrix when // diagonal terms are zero. Worst case is a number of matrices // quadratic in N, so for now we just use std::vector<GivensRotation> // whose initial capacity is K*(N-1). struct GivensRotation { GivensRotation() : index0(0), index1(0), cs(static_cast<Real>(0)), sn(static_cast<Real>(0)) { } GivensRotation(size_t inIndex0, size_t inIndex1, Real inCs, Real inSn) : index0(inIndex0), index1(inIndex1), cs(inCs), sn(inSn) { } size_t index0, index1; Real cs, sn; }; std::vector<GivensRotation> mLGivens; std::vector<GivensRotation> mRGivens; // Support for sorting singular values. struct SingularInfo { SingularInfo() : singular(static_cast<Real>(0)), inversePermute(0) { } bool operator>(SingularInfo const& p) const { return singular > p.singular; } Real singular; size_t inversePermute; }; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Circle3.h
.h
2,453
100
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector3.h> // The circle is the intersection of the sphere |X-C|^2 = r^2 and the // plane Dot(N,X-C) = 0, where C is the circle center, r is the radius, // and N is a unit-length plane normal. namespace gte { template <typename Real> class Circle3 { public: // Construction and destruction. The default constructor sets center // to (0,0,0), normal to (0,0,1), and radius to 1. Circle3() : center(Vector3<Real>::Zero()), normal(Vector3<Real>::Unit(2)), radius((Real)1) { } Circle3(Vector3<Real> const& inCenter, Vector3<Real> const& inNormal, Real inRadius) : center(inCenter), normal(inNormal), radius(inRadius) { } // Public member access. Vector3<Real> center, normal; Real radius; public: // Comparisons to support sorted containers. bool operator==(Circle3 const& circle) const { return center == circle.center && normal == circle.normal && radius == circle.radius; } bool operator!=(Circle3 const& circle) const { return !operator==(circle); } bool operator< (Circle3 const& circle) const { if (center < circle.center) { return true; } if (center > circle.center) { return false; } if (normal < circle.normal) { return true; } if (normal > circle.normal) { return false; } return radius < circle.radius; } bool operator<=(Circle3 const& circle) const { return !circle.operator<(*this); } bool operator> (Circle3 const& circle) const { return circle.operator<(*this); } bool operator>=(Circle3 const& circle) const { return !operator<(circle); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Capsule.h
.h
2,168
88
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Segment.h> // A capsule is the set of points that are equidistant from a segment, the // common distance called the radius. namespace gte { template <int32_t N, typename Real> class Capsule { public: // Construction and destruction. The default constructor sets the // segment to have endpoints p0 = (-1,0,...,0) and p1 = (1,0,...,0), // and the radius is 1. Capsule() : radius((Real)1) { } Capsule(Segment<N, Real> const& inSegment, Real inRadius) : segment(inSegment), radius(inRadius) { } // Public member access. Segment<N, Real> segment; Real radius; public: // Comparisons to support sorted containers. bool operator==(Capsule const& capsule) const { return segment == capsule.segment && radius == capsule.radius; } bool operator!=(Capsule const& capsule) const { return !operator==(capsule); } bool operator< (Capsule const& capsule) const { if (segment < capsule.segment) { return true; } if (segment > capsule.segment) { return false; } return radius < capsule.radius; } bool operator<=(Capsule const& capsule) const { return !capsule.operator<(*this); } bool operator> (Capsule const& capsule) const { return capsule.operator<(*this); } bool operator>=(Capsule const& capsule) const { return !operator<(capsule); } }; // Template alias for convenience. template <typename Real> using Capsule3 = Capsule<3, Real>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RectangleMesh.h
.h
5,016
155
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Mesh.h> #include <Mathematics/Rectangle.h> #include <Mathematics/Vector3.h> #include <memory> namespace gte { template <typename Real> class RectangleMesh : public Mesh<Real> { public: // Create a mesh that tessellates a rectangle. RectangleMesh(MeshDescription const& description, Rectangle<3, Real> const& rectangle) : Mesh<Real>(description, { MeshTopology::RECTANGLE }), mRectangle(rectangle) { if (!this->mDescription.constructed) { // The logger system will report these errors in the Mesh // constructor. return; } if (!this->mTCoords) { mDefaultTCoords.resize(this->mDescription.numVertices); this->mTCoords = mDefaultTCoords.data(); this->mTCoordStride = sizeof(Vector2<Real>); this->mDescription.allowUpdateFrame = this->mDescription.wantDynamicTangentSpaceUpdate; if (this->mDescription.allowUpdateFrame) { if (!this->mDescription.hasTangentSpaceVectors) { this->mDescription.allowUpdateFrame = false; } if (!this->mNormals) { this->mDescription.allowUpdateFrame = false; } } } this->ComputeIndices(); InitializeTCoords(); InitializePositions(); if (this->mDescription.allowUpdateFrame) { InitializeFrame(); } else if (this->mNormals) { InitializeNormals(); } } // Member access. inline Rectangle<3, Real> const& GetRectangle() const { return mRectangle; } protected: void InitializeTCoords() { Vector2<Real> tcoord; for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { tcoord[1] = (Real)r / (Real)(this->mDescription.numRows - 1); for (uint32_t c = 0; c < this->mDescription.numCols; ++c, ++i) { tcoord[0] = (Real)c / (Real)(this->mDescription.numCols - 1); this->TCoord(i) = tcoord; } } } void InitializePositions() { for (uint32_t r = 0, i = 0; r < this->mDescription.numRows; ++r) { for (uint32_t c = 0; c < this->mDescription.numCols; ++c, ++i) { Vector2<Real> tcoord = this->TCoord(i); Real w0 = ((Real)2 * tcoord[0] - (Real)1) * mRectangle.extent[0]; Real w1 = ((Real)2 * tcoord[1] - (Real)1) * mRectangle.extent[1]; this->Position(i) = mRectangle.center + w0 * mRectangle.axis[0] + w1 * mRectangle.axis[1]; } } } void InitializeNormals() { Vector3<Real> normal = UnitCross(mRectangle.axis[0], mRectangle.axis[1]); for (uint32_t i = 0; i < this->mDescription.numVertices; ++i) { this->Normal(i) = normal; } } void InitializeFrame() { Vector3<Real> normal = UnitCross(mRectangle.axis[0], mRectangle.axis[1]); Vector3<Real> tangent{ (Real)1, (Real)0, (Real)0 }; Vector3<Real> bitangent{ (Real)0, (Real)1, (Real)0 }; // bitangent = Cross(normal,tangent) // TODO: Are tangent and bitangent correct? for (uint32_t i = 0; i < this->mDescription.numVertices; ++i) { if (this->mNormals) { this->Normal(i) = normal; } if (this->mTangents) { this->Tangent(i) = tangent; } if (this->mBitangents) { this->Bitangent(i) = bitangent; } if (this->mDPDUs) { this->DPDU(i) = tangent; } if (this->mDPDVs) { this->DPDV(i) = bitangent; } } } Rectangle<3, Real> mRectangle; // If the client does not request texture coordinates, they will be // computed internally for use in evaluation of the surface geometry. std::vector<Vector2<Real>> mDefaultTCoords; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegment3AlignedBox3.h
.h
2,766
77
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/DistLine3AlignedBox3.h> #include <Mathematics/DistPointAlignedBox.h> #include <Mathematics/Segment.h> // Compute the distance between a segmet and a solid aligned box in 3D. // // The segment is P0 + t * (P1 - P0) for 0 <= t <= 1. The direction D = P1-P0 // is generally not unit length. // // The aligned box has minimum corner A and maximum corner B. A box point is X // where A <= X <= B; the comparisons are componentwise. // // The closest point on the segment is stored in closest[0] with parameter t. // The closest point on the box is stored in closest[1]. When there are // infinitely many choices for the pair of closest points, only one of them is // returned. namespace gte { template <typename T> class DCPQuery<T, Segment3<T>, AlignedBox3<T>> { public: using LBQuery = DCPQuery<T, Line3<T>, AlignedBox3<T>>; using Result = typename LBQuery::Result; Result operator()(Segment3<T> const& segment, AlignedBox3<T> const& box) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector3<T> segDirection = segment.p[1] - segment.p[0]; Line3<T> line(segment.p[0], segDirection); LBQuery lbQuery{}; auto lbOutput = lbQuery(line, box); if (lbOutput.parameter >= zero) { if (lbOutput.parameter <= one) { result = lbOutput; } else { DCPQuery<T, Vector3<T>, AlignedBox3<T>> pbQuery{}; auto pbOutput = pbQuery(segment.p[1], box); result.sqrDistance = pbOutput.sqrDistance; result.distance = pbOutput.distance; result.parameter = one; result.closest[0] = segment.p[1]; result.closest[1] = pbOutput.closest[1]; } } else { DCPQuery<T, Vector3<T>, AlignedBox3<T>> pbQuery{}; auto pbOutput = pbQuery(segment.p[0], box); result.sqrDistance = pbOutput.sqrDistance; result.distance = pbOutput.distance; result.parameter = zero; result.closest[0] = segment.p[0]; result.closest[1] = pbOutput.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SurfaceExtractor.h
.h
17,478
464
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/Math.h> #include <algorithm> #include <array> #include <cstdint> #include <map> #include <vector> namespace gte { // The image type T must be one of the integer types: int8_t, int16_t, // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations // are performed using int64_t. The type Real is for extraction to // floating-point vertices. template <typename T, typename Real> class SurfaceExtractor { public: // Abstract base class. virtual ~SurfaceExtractor() = default; // The level surfaces form a graph of vertices, edges and triangles. // The vertices are computed as triples of nonnegative rational // numbers. Vertex represents the rational triple // (xNumer/xDenom, yNumer/yDenom, zNumer/zDenom) // as // (xNumer, xDenom, yNumer, yDenom, zNumer, zDenom) // where all components are nonnegative. The edges connect pairs of // vertices and the triangles connect triples of vertices, forming // a graph that represents the level set. struct Vertex { Vertex() = default; Vertex(int64_t inXNumer, int64_t inXDenom, int64_t inYNumer, int64_t inYDenom, int64_t inZNumer, int64_t inZDenom) { // The vertex generation leads to the numerator and // denominator having the same sign. This constructor changes // sign to ensure the numerator and denominator are both // positive. if (inXDenom > 0) { xNumer = inXNumer; xDenom = inXDenom; } else { xNumer = -inXNumer; xDenom = -inXDenom; } if (inYDenom > 0) { yNumer = inYNumer; yDenom = inYDenom; } else { yNumer = -inYNumer; yDenom = -inYDenom; } if (inZDenom > 0) { zNumer = inZNumer; zDenom = inZDenom; } else { zNumer = -inZNumer; zDenom = -inZDenom; } } // The non-default constructor guarantees that xDenom > 0, // yDenom > 0 and zDenom > 0. The following comparison operators // assume that the denominators are positive. bool operator==(Vertex const& other) const { return // xn0/xd0 == xn1/xd1 xNumer * other.xDenom == other.xNumer * xDenom && // yn0/yd0 == yn1/yd1 yNumer * other.yDenom == other.yNumer * yDenom && // zn0/zd0 == zn1/zd1 zNumer * other.zDenom == other.zNumer * zDenom; } bool operator<(Vertex const& other) const { int64_t xn0txd1 = xNumer * other.xDenom; int64_t xn1txd0 = other.xNumer * xDenom; if (xn0txd1 < xn1txd0) { // xn0/xd0 < xn1/xd1 return true; } if (xn0txd1 > xn1txd0) { // xn0/xd0 > xn1/xd1 return false; } int64_t yn0tyd1 = yNumer * other.yDenom; int64_t yn1tyd0 = other.yNumer * yDenom; if (yn0tyd1 < yn1tyd0) { // yn0/yd0 < yn1/yd1 return true; } if (yn0tyd1 > yn1tyd0) { // yn0/yd0 > yn1/yd1 return false; } int64_t zn0tzd1 = zNumer * other.zDenom; int64_t zn1tzd0 = other.zNumer * zDenom; // zn0/zd0 < zn1/zd1 return zn0tzd1 < zn1tzd0; } int64_t xNumer, xDenom, yNumer, yDenom, zNumer, zDenom; }; struct Triangle { Triangle() = default; Triangle(int32_t v0, int32_t v1, int32_t v2) { // After the code is executed, (v[0],v[1],v[2]) is a cyclic // permutation of (v0,v1,v2) with v[0] = min{v0,v1,v2}. if (v0 < v1) { if (v0 < v2) { v[0] = v0; v[1] = v1; v[2] = v2; } else { v[0] = v2; v[1] = v0; v[2] = v1; } } else { if (v1 < v2) { v[0] = v1; v[1] = v2; v[2] = v0; } else { v[0] = v2; v[1] = v0; v[2] = v1; } } } bool operator==(Triangle const& other) const { return v[0] == other.v[0] && v[1] == other.v[1] && v[2] == other.v[2]; } bool operator<(Triangle const& other) const { for (int32_t i = 0; i < 3; ++i) { if (v[i] < other.v[i]) { return true; } if (v[i] > other.v[i]) { return false; } } return false; } std::array<int32_t, 3> v; }; // Extract level surfaces and return rational vertices. virtual void Extract(T level, std::vector<Vertex>& vertices, std::vector<Triangle>& triangles) = 0; void Extract(T level, bool removeDuplicateVertices, std::vector<std::array<Real, 3>>& vertices, std::vector<Triangle>& triangles) { std::vector<Vertex> rationalVertices; Extract(level, rationalVertices, triangles); if (removeDuplicateVertices) { MakeUnique(rationalVertices, triangles); } Convert(rationalVertices, vertices); } // The extraction has duplicate vertices on edges shared by voxels. // This function will eliminate the duplicates. void MakeUnique(std::vector<Vertex>& vertices, std::vector<Triangle>& triangles) { size_t numVertices = vertices.size(); size_t numTriangles = triangles.size(); if (numVertices == 0 || numTriangles == 0) { return; } // Compute the map of unique vertices and assign to them new and // unique indices. std::map<Vertex, int32_t> vmap; int32_t nextVertex = 0; for (size_t v = 0; v < numVertices; ++v) { // Keep only unique vertices. auto result = vmap.insert(std::make_pair(vertices[v], nextVertex)); if (result.second) { ++nextVertex; } } // Compute the map of unique triangles and assign to them new and // unique indices. std::map<Triangle, int32_t> tmap; int32_t nextTriangle = 0; for (size_t t = 0; t < numTriangles; ++t) { Triangle& triangle = triangles[t]; for (int32_t i = 0; i < 3; ++i) { auto iter = vmap.find(vertices[triangle.v[i]]); LogAssert(iter != vmap.end(), "Expecting the vertex to be in the vmap."); triangle.v[i] = iter->second; } // Keep only unique triangles. auto result = tmap.insert(std::make_pair(triangle, nextTriangle)); if (result.second) { ++nextTriangle; } } // Pack the vertices into an array. vertices.resize(vmap.size()); for (auto const& element : vmap) { vertices[element.second] = element.first; } // Pack the triangles into an array. triangles.resize(tmap.size()); for (auto const& element : tmap) { triangles[element.second] = element.first; } } // Convert from Vertex to std::array<Real, 3> rationals. void Convert(std::vector<Vertex> const& input, std::vector<std::array<Real, 3>>& output) { output.resize(input.size()); for (size_t i = 0; i < input.size(); ++i) { Real rxNumer = static_cast<Real>(input[i].xNumer); Real rxDenom = static_cast<Real>(input[i].xDenom); Real ryNumer = static_cast<Real>(input[i].yNumer); Real ryDenom = static_cast<Real>(input[i].yDenom); Real rzNumer = static_cast<Real>(input[i].zNumer); Real rzDenom = static_cast<Real>(input[i].zDenom); output[i][0] = rxNumer / rxDenom; output[i][1] = ryNumer / ryDenom; output[i][2] = rzNumer / rzDenom; } } // The extraction does not use any topological information about the // level surfaces. The triangles can be a mixture of clockwise-ordered // and counterclockwise-ordered. This function is an attempt to give // the triangles a consistent ordering by selecting a normal in // approximately the same direction as the average gradient at the // vertices (when sameDir is true), or in the opposite direction (when // sameDir is false). This might not always produce a consistent // order, but is fast. A consistent order can be computed by // choosing a winding order for each triangle so that any corner of // the voxel containing the triangle and that has positive sign sees // a counterclockwise order. Of course, you can also choose that the // positive sign corners of the voxel always see the voxel-contained // triangles in clockwise order. void OrientTriangles(std::vector<std::array<Real, 3>>& vertices, std::vector<Triangle>& triangles, bool sameDir) { for (auto& triangle : triangles) { // Get the triangle vertices. std::array<Real, 3> v0 = vertices[triangle.v[0]]; std::array<Real, 3> v1 = vertices[triangle.v[1]]; std::array<Real, 3> v2 = vertices[triangle.v[2]]; // Construct the triangle normal based on the current // orientation. std::array<Real, 3> edge1, edge2, normal; for (int32_t i = 0; i < 3; ++i) { edge1[i] = v1[i] - v0[i]; edge2[i] = v2[i] - v0[i]; } normal[0] = edge1[1] * edge2[2] - edge1[2] * edge2[1]; normal[1] = edge1[2] * edge2[0] - edge1[0] * edge2[2]; normal[2] = edge1[0] * edge2[1] - edge1[1] * edge2[0]; // Get the image gradient at the vertices. std::array<Real, 3> grad0 = GetGradient(v0); std::array<Real, 3> grad1 = GetGradient(v1); std::array<Real, 3> grad2 = GetGradient(v2); // Compute the average gradient. std::array<Real, 3> gradAvr; for (int32_t i = 0; i < 3; ++i) { gradAvr[i] = (grad0[i] + grad1[i] + grad2[i]) / (Real)3; } // Compute the dot product of normal and average gradient. Real dot = gradAvr[0] * normal[0] + gradAvr[1] * normal[1] + gradAvr[2] * normal[2]; // Choose triangle orientation based on gradient direction. if (sameDir) { if (dot < (Real)0) { // Wrong orientation, reorder it. std::swap(triangle.v[1], triangle.v[2]); } } else { if (dot > (Real)0) { // Wrong orientation, reorder it. std::swap(triangle.v[1], triangle.v[2]); } } } } // Use this function if you want vertex normals for dynamic lighting // of the mesh. void ComputeNormals(std::vector<std::array<Real, 3>> const& vertices, std::vector<Triangle> const& triangles, std::vector<std::array<Real, 3>>& normals) { // Compute a vertex normal to be area-weighted sums of the normals // to the triangles that share that vertex. std::array<Real, 3> const zero{ (Real)0, (Real)0, (Real)0 }; normals.resize(vertices.size()); std::fill(normals.begin(), normals.end(), zero); for (auto const& triangle : triangles) { // Get the triangle vertices. std::array<Real, 3> v0 = vertices[triangle.v[0]]; std::array<Real, 3> v1 = vertices[triangle.v[1]]; std::array<Real, 3> v2 = vertices[triangle.v[2]]; // Construct the triangle normal. std::array<Real, 3> edge1, edge2, normal; for (int32_t i = 0; i < 3; ++i) { edge1[i] = v1[i] - v0[i]; edge2[i] = v2[i] - v0[i]; } normal[0] = edge1[1] * edge2[2] - edge1[2] * edge2[1]; normal[1] = edge1[2] * edge2[0] - edge1[0] * edge2[2]; normal[2] = edge1[0] * edge2[1] - edge1[1] * edge2[0]; // Maintain the sum of normals at each vertex. for (int32_t i = 0; i < 3; ++i) { for (int32_t j = 0; j < 3; ++j) { normals[triangle.v[i]][j] += normal[j]; } } } // The normal vector storage was used to accumulate the sum of // triangle normals. Now these vectors must be rescaled to be // unit length. for (auto& normal : normals) { Real sqrLength = normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]; Real length = std::sqrt(sqrLength); if (length > (Real)0) { for (int32_t i = 0; i < 3; ++i) { normal[i] /= length; } } else { for (int32_t i = 0; i < 3; ++i) { normal[i] = (Real)0; } } } } protected: // The input is a 3D image with lexicographically ordered voxels // (x,y,z) stored in a linear array. Voxel (x,y,z) is stored in the // array at location index = x + xBound * (y + yBound * z). The // inputs xBound, yBound and zBound must each be 2 or larger so that // there is at least one image cube to process. The inputVoxels must // be nonnull and point to contiguous storage that contains at least // xBound * yBound * zBound elements. SurfaceExtractor(int32_t xBound, int32_t yBound, int32_t zBound, T const* inputVoxels) : mXBound(xBound), mYBound(yBound), mZBound(zBound), mXYBound(xBound * yBound), mInputVoxels(inputVoxels), mVoxels{} { static_assert(std::is_integral<T>::value && sizeof(T) <= 4, "Type T must be int32_t{8,16,32}_t or uint{8,16,32}_t."); LogAssert(xBound > 1 && yBound > 1 && zBound > 1 && mInputVoxels != nullptr, "Invalid input."); mVoxels.resize(static_cast<size_t>(mXBound) * static_cast<size_t>(mYBound) * static_cast<size_t>(mZBound)); } virtual std::array<Real, 3> GetGradient(std::array<Real, 3> const& pos) = 0; int32_t mXBound, mYBound, mZBound, mXYBound; T const* mInputVoxels; std::vector<int64_t> mVoxels; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContOrientedBox2.h
.h
6,410
177
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/ApprGaussian2.h> namespace gte { // Compute an oriented bounding box of the points. The box center is the // average of the points. The box axes are the eigenvectors of the // covariance matrix. template <typename Real> bool GetContainer(int32_t numPoints, Vector2<Real> const* points, OrientedBox2<Real>& box) { // Fit the points with a Gaussian distribution. ApprGaussian2<Real> fitter; if (fitter.Fit(numPoints, points)) { box = fitter.GetParameters(); // Let C be the box center and let U0 and U1 be the box axes. // Each input point is of the form X = C + y0*U0 + y1*U1. The // following code computes min(y0), max(y0), min(y1), and max(y1). // The box center is then adjusted to be // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 Vector2<Real> diff = points[0] - box.center; Vector2<Real> pmin{ Dot(diff, box.axis[0]), Dot(diff, box.axis[1]) }; Vector2<Real> pmax = pmin; for (int32_t i = 1; i < numPoints; ++i) { diff = points[i] - box.center; for (int32_t j = 0; j < 2; ++j) { Real dot = Dot(diff, box.axis[j]); if (dot < pmin[j]) { pmin[j] = dot; } else if (dot > pmax[j]) { pmax[j] = dot; } } } for (int32_t j = 0; j < 2; ++j) { box.center += ((Real)0.5 * (pmin[j] + pmax[j])) * box.axis[j]; box.extent[j] = (Real)0.5 * (pmax[j] - pmin[j]); } return true; } return false; } template <typename Real> bool GetContainer(std::vector<Vector2<Real>> const& points, OrientedBox2<Real>& box) { return GetContainer(static_cast<int32_t>(points.size()), points.data(), box); } // Test for containment. Let X = C + y0*U0 + y1*U1 where C is the box // center and U0 and U1 are the orthonormal axes of the box. X is in the // box when |y_i| <= E_i for all i, where E_i are the extents of the box. template <typename Real> bool InContainer(Vector2<Real> const& point, OrientedBox2<Real> const& box) { Vector2<Real> diff = point - box.center; for (int32_t i = 0; i < 2; ++i) { Real coeff = Dot(diff, box.axis[i]); if (std::fabs(coeff) > box.extent[i]) { return false; } } return true; } // Construct an oriented box that contains two other oriented boxes. The // result is not guaranteed to be the minimum area box containing the // input boxes. template <typename Real> bool MergeContainers(OrientedBox2<Real> const& box0, OrientedBox2<Real> const& box1, OrientedBox2<Real>& merge) { // The first guess at the box center. This value will be updated // later after the input box vertices are projected onto axes // determined by an average of box axes. merge.center = (Real)0.5 * (box0.center + box1.center); // The merged box axes are the averages of the input box axes. The // axes of the second box are negated, if necessary, so they form // acute angles with the axes of the first box. if (Dot(box0.axis[0], box1.axis[0]) >= (Real)0) { merge.axis[0] = (Real)0.5 * (box0.axis[0] + box1.axis[0]); } else { merge.axis[0] = (Real)0.5 * (box0.axis[0] - box1.axis[0]); } Normalize(merge.axis[0]); merge.axis[1] = -Perp(merge.axis[0]); // Project the input box vertices onto the merged-box axes. Each // axis D[i] containing the current center C has a minimum projected // value min[i] and a maximum projected value max[i]. The // corresponding endpoints on the axes are C+min[i]*D[i] and // C+max[i]*D[i]. The point C is not necessarily the midpoint for // any of the intervals. The actual box center will be adjusted from // C to a point C' that is the midpoint of each interval, // C' = C + sum_{i=0}^1 0.5*(min[i]+max[i])*D[i] // The box extents are // e[i] = 0.5*(max[i]-min[i]) std::array<Vector2<Real>, 4> vertex; Vector2<Real> pmin{ (Real)0, (Real)0 }; Vector2<Real> pmax{ (Real)0, (Real)0 }; box0.GetVertices(vertex); for (int32_t i = 0; i < 4; ++i) { Vector2<Real> diff = vertex[i] - merge.center; for (int32_t j = 0; j < 2; ++j) { Real dot = Dot(diff, merge.axis[j]); if (dot > pmax[j]) { pmax[j] = dot; } else if (dot < pmin[j]) { pmin[j] = dot; } } } box1.GetVertices(vertex); for (int32_t i = 0; i < 4; ++i) { Vector2<Real> diff = vertex[i] - merge.center; for (int32_t j = 0; j < 2; ++j) { Real dot = Dot(diff, merge.axis[j]); if (dot > pmax[j]) { pmax[j] = dot; } else if (dot < pmin[j]) { pmin[j] = dot; } } } // [min,max] is the axis-aligned box in the coordinate system of the // merged box axes. Update the current box center to be the center of // the new box. Compute the extents based on the new center. Real const half = (Real)0.5; for (int32_t j = 0; j < 2; ++j) { merge.center += half * (pmax[j] + pmin[j]) * merge.axis[j]; merge.extent[j] = half * (pmax[j] - pmin[j]); } return true; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ImageUtility3.h
.h
20,455
563
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Image3.h> #include <functional> // Image utilities for Image3<int32_t> objects. TODO: Extend this to a template // class to allow the pixel type to be int32_t*_t and uint*_t for * in // {8,16,32,64}. // // All but the Draw* functions are operations on binary images. Let the image // have d0 columns, d1 rows and d2 slices. The input image must have zeros on // its boundaries x = 0, x = d0-1, y = 0, y = d1-1, z = 0 and z = d2-1. The // 0-valued voxels are considered to be background. The 1-valued voxels are // considered to be foreground. In some of the operations, to save memory and // time the input image is modified by the algorithms. If you need to // preserve the input image, make a copy of it before calling these // functions. namespace gte { class ImageUtility3 { public: // Compute the 6-connected components of a binary image. The input // image is modified to avoid the cost of making a copy. On output, // the image values are the labels for the components. The array // components[k], k >= 1, contains the indices for the k-th component. static void GetComponents6(Image3<int32_t>& image, std::vector<std::vector<size_t>>& components) { std::array<int32_t, 6> neighbors; image.GetNeighborhood(neighbors); GetComponents(6, &neighbors[0], image, components); } // Compute the 18-connected components of a binary image. The input // image is modified to avoid the cost of making a copy. On output, // the image values are the labels for the components. The array // components[k], k >= 1, contains the indices for the k-th component. static void GetComponents18(Image3<int32_t>& image, std::vector<std::vector<size_t>>& components) { std::array<int32_t, 18> neighbors; image.GetNeighborhood(neighbors); GetComponents(18, &neighbors[0], image, components); } // Compute the 26-connected components of a binary image. The input // image is modified to avoid the cost of making a copy. On output, // the image values are the labels for the components. The array // components[k], k >= 1, contains the indices for the k-th component. static void GetComponents26(Image3<int32_t>& image, std::vector<std::vector<size_t>>& components) { std::array<int32_t, 26> neighbors; image.GetNeighborhood(neighbors); GetComponents(26, &neighbors[0], image, components); } // Dilate the image using a structuring element that contains the // 6-connected neighbors. static void Dilate6(Image3<int32_t> const& inImage, Image3<int32_t>& outImage) { std::array<std::array<int32_t, 3>, 6> neighbors; inImage.GetNeighborhood(neighbors); Dilate(6, &neighbors[0], inImage, outImage); } // Dilate the image using a structuring element that contains the // 18-connected neighbors. static void Dilate18(Image3<int32_t> const& inImage, Image3<int32_t>& outImage) { std::array<std::array<int32_t, 3>, 18> neighbors; inImage.GetNeighborhood(neighbors); Dilate(18, &neighbors[0], inImage, outImage); } // Dilate the image using a structuring element that contains the // 26-connected neighbors. static void Dilate26(Image3<int32_t> const& inImage, Image3<int32_t>& outImage) { std::array<std::array<int32_t, 3>, 26> neighbors; inImage.GetNeighborhood(neighbors); Dilate(26, &neighbors[0], inImage, outImage); } // Compute coordinate-directional convex set. For a given coordinate // direction (x, y, or z), identify the first and last 1-valued voxels // on a segment of voxels in that direction. All voxels from first to // last are set to 1. This is done for all segments in each of the // coordinate directions. static void ComputeCDConvex(Image3<int32_t>& image) { int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); int32_t const dim2 = image.GetDimension(2); Image3<int32_t> temp = image; int32_t i0, i1, i2; for (i1 = 0; i1 < dim1; ++i1) { for (i0 = 0; i0 < dim0; ++i0) { int32_t i2min; for (i2min = 0; i2min < dim2; ++i2min) { if ((temp(i0, i1, i2min) & 1) == 0) { temp(i0, i1, i2min) |= 2; } else { break; } } if (i2min < dim2) { int32_t i2max; for (i2max = dim2 - 1; i2max >= i2min; --i2max) { if ((temp(i0, i1, i2max) & 1) == 0) { temp(i0, i1, i2max) |= 2; } else { break; } } } } } for (i2 = 0; i2 < dim2; ++i2) { for (i0 = 0; i0 < dim0; ++i0) { int32_t i1min; for (i1min = 0; i1min < dim1; ++i1min) { if ((temp(i0, i1min, i2) & 1) == 0) { temp(i0, i1min, i2) |= 2; } else { break; } } if (i1min < dim1) { int32_t i1max; for (i1max = dim1 - 1; i1max >= i1min; --i1max) { if ((temp(i0, i1max, i2) & 1) == 0) { temp(i0, i1max, i2) |= 2; } else { break; } } } } } for (i2 = 0; i2 < dim2; ++i2) { for (i1 = 0; i1 < dim1; ++i1) { int32_t i0min; for (i0min = 0; i0min < dim0; ++i0min) { if ((temp(i0min, i1, i2) & 1) == 0) { temp(i0min, i1, i2) |= 2; } else { break; } } if (i0min < dim0) { int32_t i0max; for (i0max = dim0 - 1; i0max >= i0min; --i0max) { if ((temp(i0max, i1, i2) & 1) == 0) { temp(i0max, i1, i2) |= 2; } else { break; } } } } } for (size_t i = 0; i < image.GetNumPixels(); ++i) { image[i] = (temp[i] & 2 ? 0 : 1); } } // Use a depth-first search for filling a 6-connected region. This is // nonrecursive, simulated by using a heap-allocated "stack". The input // (x,y,z) is the seed point that starts the fill. template <typename PixelType> static void FloodFill6(Image3<PixelType> & image, int32_t x, int32_t y, int32_t z, PixelType foreColor, PixelType backColor) { // Test for a valid seed. int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); int32_t const dim2 = image.GetDimension(2); if (x < 0 || x >= dim0 || y < 0 || y >= dim1 || z < 0 || z >= dim2) { // The seed point is outside the image domain, so there is // nothing to fill. return; } // Allocate the maximum amount of space needed for the stack. An // empty stack has top == -1. size_t const numVoxels = image.GetNumPixels(); std::vector<int32_t> xStack(numVoxels), yStack(numVoxels), zStack(numVoxels); // Push seed point onto stack if it has the background color. All // points pushed onto stack have background color backColor. int32_t top = 0; xStack[top] = x; yStack[top] = y; zStack[top] = z; while (top >= 0) // stack is not empty { // Read top of stack. Do not pop since we need to return to // this top value later to restart the fill in a different // direction. x = xStack[top]; y = yStack[top]; z = zStack[top]; // Fill the pixel. image(x, y, z) = foreColor; int32_t xp1 = x + 1; if (xp1 < dim0 && image(xp1, y, z) == backColor) { // Push pixel with background color. ++top; xStack[top] = xp1; yStack[top] = y; zStack[top] = z; continue; } int32_t xm1 = x - 1; if (0 <= xm1 && image(xm1, y, z) == backColor) { // Push pixel with background color. ++top; xStack[top] = xm1; yStack[top] = y; zStack[top] = z; continue; } int32_t yp1 = y + 1; if (yp1 < dim1 && image(x, yp1, z) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = yp1; zStack[top] = z; continue; } int32_t ym1 = y - 1; if (0 <= ym1 && image(x, ym1, z) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = ym1; zStack[top] = z; continue; } int32_t zp1 = z + 1; if (zp1 < dim2 && image(x, y, zp1) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = y; zStack[top] = zp1; continue; } int32_t zm1 = z - 1; if (0 <= zm1 && image(x, y, zm1) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = y; zStack[top] = zm1; continue; } // Done in all directions, pop and return to search other // directions for the predecessor. --top; } } // Visit pixels using Bresenham's line drawing algorithm. The callback // represents the action you want applied to each voxel as it is visited. static void DrawLine(int32_t x0, int32_t y0, int32_t z0, int32_t x1, int32_t y1, int32_t z1, std::function<void(int32_t, int32_t, int32_t)> const& callback) { // Starting point of line. int32_t x = x0, y = y0, z = z0; // Direction of line. int32_t dx = x1 - x0, dy = y1 - y0, dz = z1 - z0; // Increment or decrement depending on direction of line. int32_t sx = (dx > 0 ? 1 : (dx < 0 ? -1 : 0)); int32_t sy = (dy > 0 ? 1 : (dy < 0 ? -1 : 0)); int32_t sz = (dz > 0 ? 1 : (dz < 0 ? -1 : 0)); // Decision parameters for voxel selection. if (dx < 0) { dx = -dx; } if (dy < 0) { dy = -dy; } if (dz < 0) { dz = -dz; } int32_t ax = 2 * dx, ay = 2 * dy, az = 2 * dz; int32_t decX, decY, decZ; // Determine largest direction component, single-step related // variable. int32_t maxValue = dx, var = 0; if (dy > maxValue) { maxValue = dy; var = 1; } if (dz > maxValue) { var = 2; } // Traverse Bresenham line. switch (var) { case 0: // Single-step in x-direction. decY = ay - dx; decZ = az - dx; for (/**/; /**/; x += sx, decY += ay, decZ += az) { // Process voxel. callback(x, y, z); // Take Bresenham step. if (x == x1) { break; } if (decY >= 0) { decY -= ax; y += sy; } if (decZ >= 0) { decZ -= ax; z += sz; } } break; case 1: // Single-step in y-direction. decX = ax - dy; decZ = az - dy; for (/**/; /**/; y += sy, decX += ax, decZ += az) { // Process voxel. callback(x, y, z); // Take Bresenham step. if (y == y1) { break; } if (decX >= 0) { decX -= ay; x += sx; } if (decZ >= 0) { decZ -= ay; z += sz; } } break; case 2: // Single-step in z-direction. decX = ax - dz; decY = ay - dz; for (/**/; /**/; z += sz, decX += ax, decY += ay) { // Process voxel. callback(x, y, z); // Take Bresenham step. if (z == z1) { break; } if (decX >= 0) { decX -= az; x += sx; } if (decY >= 0) { decY -= az; y += sy; } } break; } } private: // Dilation using the specified structuring element. static void Dilate(int32_t numNeighbors, std::array<int32_t, 3> const* delta, Image3<int32_t> const& inImage, Image3<int32_t> & outImage) { int32_t const bound0M1 = inImage.GetDimension(0) - 1; int32_t const bound1M1 = inImage.GetDimension(1) - 1; int32_t const bound2M1 = inImage.GetDimension(2) - 1; for (int32_t i2 = 1; i2 < bound2M1; ++i2) { for (int32_t i1 = 1; i1 < bound1M1; ++i1) { for (int32_t i0 = 1; i0 < bound0M1; ++i0) { if (inImage(i0, i1, i2) == 0) { for (int32_t n = 0; n < numNeighbors; ++n) { int32_t d0 = delta[n][0]; int32_t d1 = delta[n][1]; int32_t d2 = delta[n][2]; if (inImage(i0 + d0, i1 + d1, i2 + d2) == 1) { outImage(i0, i1, i2) = 1; break; } } } else { outImage(i0, i1, i2) = 1; } } } } } // Connected component labeling using depth-first search. static void GetComponents(int32_t numNeighbors, int32_t const* delta, Image3<int32_t> & image, std::vector<std::vector<size_t>> & components) { size_t const numVoxels = image.GetNumPixels(); std::vector<int32_t> numElements(numVoxels); std::vector<size_t> vstack(numVoxels); size_t i, numComponents = 0; int32_t label = 2; for (i = 0; i < numVoxels; ++i) { if (image[i] == 1) { int32_t top = -1; vstack[++top] = i; int32_t& count = numElements[numComponents + 1]; count = 0; while (top >= 0) { size_t v = vstack[top]; image[v] = -1; int32_t j; for (j = 0; j < numNeighbors; ++j) { size_t adj = v + delta[j]; if (image[adj] == 1) { vstack[++top] = adj; break; } } if (j == numNeighbors) { image[v] = label; ++count; --top; } } ++numComponents; ++label; } } if (numComponents > 0) { components.resize(numComponents + 1); for (i = 1; i <= numComponents; ++i) { components[i].resize(numElements[i]); numElements[i] = 0; } for (i = 0; i < numVoxels; ++i) { int32_t value = image[i]; if (value != 0) { // Labels started at 2 to support the depth-first // search, so they need to be decremented for the // correct labels. image[i] = --value; components[value][numElements[value]] = i; ++numElements[value]; } } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ConvexMesh3.h
.h
2,323
68
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Vector3.h> #include <cstdint> #include <vector> namespace gte { template <typename Real> class ConvexMesh3 { public: // A client of ConvexMesh3 is responsible for populating the vertices // and indices so that the resulting mesh represents a convex // polyhedron. // 1. All elements of 'vertices' must be used by the polyhedron. // 2. The triangle faces must have the same chirality when viewed // from outside the polyhedron. They are all counterclockwise // oriented or all clockwise oriented when viewed from outside // the polyhedron. // 3. The Real type must be an arbitrary-precision type that // supports division. // 4. The polyhedron can be degenerate. All the possibilities are // listed next. // point: // vertices.size() == 1, triangles.size() = 0 // // line segment: // vertices.size() == 2, triangles.size() == 0 // // convex polygon: // vertices.size() >= 3, triangles.size() > 0 and the // vertices are coplanar // // convex polyhedron: // vertices.size() >= 3, triangles.size() > 0 and the // vertices are not coplanar static int32_t constexpr CFG_EMPTY = 0x00000000; static int32_t constexpr CFG_POINT = 0x00000001; static int32_t constexpr CFG_SEGMENT = 0x00000002; static int32_t constexpr CFG_POLYGON = 0x00000004; static int32_t constexpr CFG_POLYHEDRON = 0x00000008; using Vertex = Vector3<Real>; using Triangle = std::array<int32_t, 3>; ConvexMesh3() : configuration(CFG_EMPTY), vertices{}, triangles{} { } int32_t configuration; std::vector<Vertex> vertices; std::vector<Triangle> triangles; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Vector3.h
.h
14,559
360
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.31 #pragma once #include <Mathematics/Vector.h> #include <array> namespace gte { // Template alias for convenience. template <typename Real> using Vector3 = Vector<3, Real>; // Cross, UnitCross, and DotCross have a template parameter N that should // be 3 or 4. The latter case supports affine vectors in 4D (last // component w = 0) when you want to use 4-tuples and 4x4 matrices for // affine algebra. // Compute the cross product using the formal determinant: // cross = det{{e0,e1,e2},{x0,x1,x2},{y0,y1,y2}} // = (x1*y2-x2*y1, x2*y0-x0*y2, x0*y1-x1*y0) // where e0 = (1,0,0), e1 = (0,1,0), e2 = (0,0,1), v0 = (x0,x1,x2), and // v1 = (y0,y1,y2). template <int32_t N, typename Real> Vector<N, Real> Cross(Vector<N, Real> const& v0, Vector<N, Real> const& v1) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Vector<N, Real> result; result.MakeZero(); result[0] = v0[1] * v1[2] - v0[2] * v1[1]; result[1] = v0[2] * v1[0] - v0[0] * v1[2]; result[2] = v0[0] * v1[1] - v0[1] * v1[0]; return result; } // Compute the normalized cross product. template <int32_t N, typename Real> Vector<N, Real> UnitCross(Vector<N, Real> const& v0, Vector<N, Real> const& v1, bool robust = false) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); Vector<N, Real> unitCross = Cross(v0, v1); Normalize(unitCross, robust); return unitCross; } // Compute Dot((x0,x1,x2),Cross((y0,y1,y2),(z0,z1,z2)), the triple scalar // product of three vectors, where v0 = (x0,x1,x2), v1 = (y0,y1,y2), and // v2 is (z0,z1,z2). template <int32_t N, typename Real> Real DotCross(Vector<N, Real> const& v0, Vector<N, Real> const& v1, Vector<N, Real> const& v2) { static_assert(N == 3 || N == 4, "Dimension must be 3 or 4."); return Dot(v0, Cross(v1, v2)); } // Compute a right-handed orthonormal basis for the orthogonal complement // of the input vectors. The function returns the smallest length of the // unnormalized vectors computed during the process. If this value is // nearly zero, it is possible that the inputs are linearly dependent // (within numerical round-off errors). On input, numInputs must be 1 or // 2 and v[0] through v[numInputs-1] must be initialized. On output, the // vectors v[0] through v[2] form an orthonormal set. template <typename Real> Real ComputeOrthogonalComplement(int32_t numInputs, Vector3<Real>* v, bool robust = false) { if (numInputs == 1) { if (std::fabs(v[0][0]) > std::fabs(v[0][1])) { v[1] = { -v[0][2], (Real)0, +v[0][0] }; } else { v[1] = { (Real)0, +v[0][2], -v[0][1] }; } numInputs = 2; } if (numInputs == 2) { v[2] = Cross(v[0], v[1]); return Orthonormalize<3, Real>(3, v, robust); } return (Real)0; } // Compute the barycentric coordinates of the point P with respect to the // tetrahedron <V0,V1,V2,V3>, P = b0*V0 + b1*V1 + b2*V2 + b3*V3, where // b0 + b1 + b2 + b3 = 1. The return value is 'true' iff {V0,V1,V2,V3} is // a linearly independent set. Numerically, this is measured by // |det[V0 V1 V2 V3]| <= epsilon. The values bary[] are valid only when // the return value is 'true' but set to zero when the return value is // 'false'. template <typename Real> bool ComputeBarycentrics(Vector3<Real> const& p, Vector3<Real> const& v0, Vector3<Real> const& v1, Vector3<Real> const& v2, Vector3<Real> const& v3, std::array<Real, 4>& bary, Real epsilon = static_cast<Real>(0)) { // Compute the vectors relative to V3 of the tetrahedron. std::array<Vector3<Real>, 4> diff = { v0 - v3, v1 - v3, v2 - v3, p - v3 }; Real det = DotCross(diff[0], diff[1], diff[2]); if (det < -epsilon || det > epsilon) { bary[0] = DotCross(diff[3], diff[1], diff[2]) / det; bary[1] = DotCross(diff[3], diff[2], diff[0]) / det; bary[2] = DotCross(diff[3], diff[0], diff[1]) / det; bary[3] = static_cast<Real>(1) - bary[0] - bary[1] - bary[2]; return true; } bary.fill(static_cast<Real>(0)); return false; } // Get intrinsic information about the input array of vectors. The return // value is 'true' iff the inputs are valid (numVectors > 0, v is not // null, and epsilon >= 0), in which case the class members are valid. template <typename Real> class IntrinsicsVector3 { public: // The constructor sets the class members based on the input set. IntrinsicsVector3(int32_t numVectors, Vector3<Real> const* v, Real inEpsilon) : epsilon(inEpsilon), dimension(0), maxRange((Real)0), origin{ (Real)0, (Real)0, (Real)0 }, extremeCCW(false) { min[0] = (Real)0; min[1] = (Real)0; min[2] = (Real)0; max[0] = (Real)0; max[1] = (Real)0; max[2] = (Real)0; direction[0] = { (Real)0, (Real)0, (Real)0 }; direction[1] = { (Real)0, (Real)0, (Real)0 }; direction[2] = { (Real)0, (Real)0, (Real)0 }; extreme[0] = 0; extreme[1] = 0; extreme[2] = 0; extreme[3] = 0; if (numVectors > 0 && v && epsilon >= (Real)0) { // Compute the axis-aligned bounding box for the input vectors. // Keep track of the indices into 'vectors' for the current // min and max. int32_t j{}; std::array<int32_t, 3> indexMin{}, indexMax{}; for (j = 0; j < 3; ++j) { min[j] = v[0][j]; max[j] = min[j]; indexMin[j] = 0; indexMax[j] = 0; } int32_t i; for (i = 1; i < numVectors; ++i) { for (j = 0; j < 3; ++j) { if (v[i][j] < min[j]) { min[j] = v[i][j]; indexMin[j] = i; } else if (v[i][j] > max[j]) { max[j] = v[i][j]; indexMax[j] = i; } } } // Determine the maximum range for the bounding box. maxRange = max[0] - min[0]; extreme[0] = indexMin[0]; extreme[1] = indexMax[0]; Real range = max[1] - min[1]; if (range > maxRange) { maxRange = range; extreme[0] = indexMin[1]; extreme[1] = indexMax[1]; } range = max[2] - min[2]; if (range > maxRange) { maxRange = range; extreme[0] = indexMin[2]; extreme[1] = indexMax[2]; } // The origin is either the vector of minimum x0-value, vector // of minimum x1-value, or vector of minimum x2-value. origin = v[extreme[0]]; // Test whether the vector set is (nearly) a vector. if (maxRange <= epsilon) { dimension = 0; for (j = 0; j < 3; ++j) { extreme[j + 1] = extreme[0]; } return; } // Test whether the vector set is (nearly) a line segment. We // need {direction[2],direction[3]} to span the orthogonal // complement of direction[0]. direction[0] = v[extreme[1]] - origin; Normalize(direction[0], false); if (std::fabs(direction[0][0]) > std::fabs(direction[0][1])) { direction[1][0] = -direction[0][2]; direction[1][1] = (Real)0; direction[1][2] = +direction[0][0]; } else { direction[1][0] = (Real)0; direction[1][1] = +direction[0][2]; direction[1][2] = -direction[0][1]; } Normalize(direction[1], false); direction[2] = Cross(direction[0], direction[1]); // Compute the maximum distance of the points from the line // origin + t * direction[0]. Real maxDistance = (Real)0; Real distance, dot; extreme[2] = extreme[0]; for (i = 0; i < numVectors; ++i) { Vector3<Real> diff = v[i] - origin; dot = Dot(direction[0], diff); Vector3<Real> proj = diff - dot * direction[0]; distance = Length(proj, false); if (distance > maxDistance) { maxDistance = distance; extreme[2] = i; } } if (maxDistance <= epsilon * maxRange) { // The points are (nearly) on the line // origin + t * direction[0]. dimension = 1; extreme[2] = extreme[1]; extreme[3] = extreme[1]; return; } // Test whether the vector set is (nearly) a planar polygon. // The point v[extreme[2]] is farthest from the line: // origin + t * direction[0]. The vector // v[extreme[2]] - origin is not necessarily perpendicular to // direction[0], so project out the direction[0] component so // that the result is perpendicular to direction[0]. direction[1] = v[extreme[2]] - origin; dot = Dot(direction[0], direction[1]); direction[1] -= dot * direction[0]; Normalize(direction[1], false); // We need direction[2] to span the orthogonal complement of // {direction[0],direction[1]}. direction[2] = Cross(direction[0], direction[1]); // Compute the maximum distance of the points from the plane // origin+t0 * direction[0] + t1 * direction[1]. maxDistance = (Real)0; Real maxSign = (Real)0; extreme[3] = extreme[0]; for (i = 0; i < numVectors; ++i) { Vector3<Real> diff = v[i] - origin; distance = Dot(direction[2], diff); Real sign = (distance > (Real)0 ? (Real)1 : (distance < (Real)0 ? (Real)-1 : (Real)0)); distance = std::fabs(distance); if (distance > maxDistance) { maxDistance = distance; maxSign = sign; extreme[3] = i; } } if (maxDistance <= epsilon * maxRange) { // The points are (nearly) on the plane // origin + t0 * direction[0] + t1 * direction[1]. dimension = 2; extreme[3] = extreme[2]; return; } dimension = 3; extremeCCW = (maxSign > (Real)0); return; } } // A nonnegative tolerance that is used to determine the intrinsic // dimension of the set. Real epsilon; // The intrinsic dimension of the input set, computed based on the // nonnegative tolerance mEpsilon. int32_t dimension; // Axis-aligned bounding box of the input set. The maximum range is // the larger of max[0]-min[0], max[1]-min[1], and max[2]-min[2]. Real min[3], max[3]; Real maxRange; // Coordinate system. The origin is valid for any dimension d. The // unit-length direction vector is valid only for 0 <= i < d. The // extreme index is relative to the array of input points, and is also // valid only for 0 <= i < d. If d = 0, all points are effectively // the same, but the use of an epsilon may lead to an extreme index // that is not zero. If d = 1, all points effectively lie on a line // segment. If d = 2, all points effectively line on a plane. If // d = 3, the points are not coplanar. Vector3<Real> origin; Vector3<Real> direction[3]; // The indices that define the maximum dimensional extents. The // values extreme[0] and extreme[1] are the indices for the points // that define the largest extent in one of the coordinate axis // directions. If the dimension is 2, then extreme[2] is the index // for the point that generates the largest extent in the direction // perpendicular to the line through the points corresponding to // extreme[0] and extreme[1]. Furthermore, if the dimension is 3, // then extreme[3] is the index for the point that generates the // largest extent in the direction perpendicular to the triangle // defined by the other extreme points. The tetrahedron formed by the // points V[extreme[0]], V[extreme[1]], V[extreme[2]], and // V[extreme[3]] is clockwise or counterclockwise, the condition // stored in extremeCCW. int32_t extreme[4]; bool extremeCCW; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ArbitraryPrecision.h
.h
509
16
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/UIntegerALU32.h> #include <Mathematics/UIntegerAP32.h> #include <Mathematics/UIntegerFP32.h> #include <Mathematics/BSNumber.h> #include <Mathematics/BSRational.h> #include <Mathematics/BSPrecision.h>
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSplineCurveFit.h
.h
8,957
239
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/BasisFunction.h> #include <Mathematics/BandedMatrix.h> // The algorithm implemented here is based on the document // https://www.geometrictools.com/Documentation/BSplineCurveLeastSquaresFit.pdf namespace gte { template <typename Real> class BSplineCurveFit { public: // Construction. The preconditions for calling the constructor are // 1 <= degree && degree < numControls <= numSamples - degree - 1. // The samples points are contiguous blocks of 'dimension' real values // stored in sampleData. BSplineCurveFit(int32_t dimension, int32_t numSamples, Real const* sampleData, int32_t degree, int32_t numControls) : mDimension(dimension), mNumSamples(numSamples), mSampleData(sampleData), mDegree(degree), mNumControls(numControls), mControlData(static_cast<size_t>(dimension) * static_cast<size_t>(numControls)) { LogAssert(dimension >= 1, "Invalid dimension."); LogAssert(1 <= degree && degree < numControls, "Invalid degree."); LogAssert(sampleData, "Invalid sample data."); LogAssert(numControls <= numSamples - degree - 1, "Invalid number of controls."); BasisFunctionInput<Real> input; input.numControls = numControls; input.degree = degree; input.uniform = true; input.periodic = false; input.numUniqueKnots = numControls - degree + 1; input.uniqueKnots.resize(input.numUniqueKnots); input.uniqueKnots[0].t = (Real)0; input.uniqueKnots[0].multiplicity = degree + 1; int32_t last = input.numUniqueKnots - 1; Real factor = ((Real)1) / (Real)last; for (int32_t i = 1; i < last; ++i) { input.uniqueKnots[i].t = factor * (Real)i; input.uniqueKnots[i].multiplicity = 1; } input.uniqueKnots[last].t = (Real)1; input.uniqueKnots[last].multiplicity = degree + 1; mBasis.Create(input); // Fit the data points with a B-spline curve using a least-squares // error metric. The problem is of the form A^T*A*Q = A^T*P, // where A^T*A is a banded matrix, P contains the sample data, and // Q is the unknown vector of control points. Real tMultiplier = (Real)1 / ((Real)mNumSamples - (Real)1); Real t; int32_t i0, i1, i2, imin, imax, j; // Construct the matrix A^T*A. int32_t degp1 = mDegree + 1; int32_t numBands = (mNumControls > degp1 ? degp1 : mDegree); BandedMatrix<Real> ATAMat(mNumControls, numBands, numBands); for (i0 = 0; i0 < mNumControls; ++i0) { for (i1 = 0; i1 < i0; ++i1) { ATAMat(i0, i1) = ATAMat(i1, i0); } int32_t i1Max = i0 + mDegree; if (i1Max >= mNumControls) { i1Max = mNumControls - 1; } for (i1 = i0; i1 <= i1Max; ++i1) { Real value = (Real)0; for (i2 = 0; i2 < mNumSamples; ++i2) { t = tMultiplier * (Real)i2; mBasis.Evaluate(t, 0, imin, imax); if (imin <= i0 && i0 <= imax && imin <= i1 && i1 <= imax) { Real b0 = mBasis.GetValue(0, i0); Real b1 = mBasis.GetValue(0, i1); value += b0 * b1; } } ATAMat(i0, i1) = value; } } // Construct the matrix A^T. Array2<Real> ATMat(mNumSamples, mNumControls); std::memset(ATMat[0], 0, static_cast<size_t>(mNumControls) * static_cast<size_t>(mNumSamples) * sizeof(Real)); for (i0 = 0; i0 < mNumControls; ++i0) { for (i1 = 0; i1 < mNumSamples; ++i1) { t = tMultiplier * (Real)i1; mBasis.Evaluate(t, 0, imin, imax); if (imin <= i0 && i0 <= imax) { ATMat[i0][i1] = mBasis.GetValue(0, i0); } } } // Compute X0 = (A^T*A)^{-1}*A^T by solving the linear system // A^T*A*X = A^T. bool solved = ATAMat.template SolveSystem<true>(ATMat[0], mNumSamples); LogAssert(solved, "Failed to solve linear system."); // The control points for the fitted curve are stored in the // vector Q = X0*P, where P is the vector of sample data. std::fill(mControlData.begin(), mControlData.end(), (Real)0); for (i0 = 0; i0 < mNumControls; ++i0) { Real* Q = &mControlData[i0 * static_cast<size_t>(mDimension)]; for (i1 = 0; i1 < mNumSamples; ++i1) { Real const* P = mSampleData + i1 * static_cast<size_t>(mDimension); Real xValue = ATMat[i0][i1]; for (j = 0; j < mDimension; ++j) { Q[j] += xValue * P[j]; } } } // Set the first and last output control points to match the first // and last input samples. This supports the application of // fitting keyframe data with B-spline curves. The user expects // that the curve passes through the first and last positions in // order to support matching two consecutive keyframe sequences. Real* cEnd0 = &mControlData[0]; Real const* sEnd0 = mSampleData; Real* cEnd1 = &mControlData[static_cast<size_t>(mDimension) * (static_cast<size_t>(mNumControls) - 1)]; Real const* sEnd1 = &mSampleData[static_cast<size_t>(mDimension) * (static_cast<size_t>(mNumSamples) - 1)]; for (j = 0; j < mDimension; ++j) { *cEnd0++ = *sEnd0++; *cEnd1++ = *sEnd1++; } } // Access to input sample information. inline int32_t GetDimension() const { return mDimension; } inline int32_t GetNumSamples() const { return mNumSamples; } inline Real const* GetSampleData() const { return mSampleData; } // Access to output control point and curve information. inline int32_t GetDegree() const { return mDegree; } inline int32_t GetNumControls() const { return mNumControls; } inline Real const* GetControlData() const { return &mControlData[0]; } inline BasisFunction<Real> const& GetBasis() const { return mBasis; } // Evaluation of the B-spline curve. It is defined for 0 <= t <= 1. // If a t-value is outside [0,1], an open spline clamps it to [0,1]. // The caller must ensure that position[] has at least 'dimension' // elements. void Evaluate(Real t, uint32_t order, Real* value) const { int32_t imin, imax; mBasis.Evaluate(t, order, imin, imax); Real const* source = &mControlData[static_cast<size_t>(mDimension) * imin]; Real basisValue = mBasis.GetValue(order, imin); for (int32_t j = 0; j < mDimension; ++j) { value[j] = basisValue * (*source++); } for (int32_t i = imin + 1; i <= imax; ++i) { basisValue = mBasis.GetValue(order, i); for (int32_t j = 0; j < mDimension; ++j) { value[j] += basisValue * (*source++); } } } void GetPosition(Real t, Real* position) const { Evaluate(t, 0, position); } private: // Input sample information. int32_t mDimension; int32_t mNumSamples; Real const* mSampleData; // The fitted B-spline curve, open and with uniform knots. int32_t mDegree; int32_t mNumControls; std::vector<Real> mControlData; BasisFunction<Real> mBasis; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpAkimaUniform1.h
.h
3,550
110
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntpAkima1.h> namespace gte { template <typename Real> class IntpAkimaUniform1 : public IntpAkima1<Real> { public: // Construction and destruction. The interpolator is for uniformly // spaced x-values. IntpAkimaUniform1(int32_t quantity, Real xMin, Real xSpacing, Real const* F) : IntpAkima1<Real>(quantity, F), mXMin(xMin), mXSpacing(xSpacing) { LogAssert(mXSpacing > (Real)0, "Spacing must be positive."); mXMax = mXMin + mXSpacing * static_cast<Real>(static_cast<size_t>(quantity) - 1); // Compute slopes. Real invDX = (Real)1 / mXSpacing; std::vector<Real> slope(static_cast<size_t>(quantity) + 3); int32_t i, ip1, ip2; for (i = 0, ip1 = 1, ip2 = 2; i < quantity - 1; ++i, ++ip1, ++ip2) { slope[ip2] = (this->mF[ip1] - this->mF[i]) * invDX; } slope[1] = (Real)2 * slope[2] - slope[3]; slope[0] = (Real)2 * slope[1] - slope[2]; slope[static_cast<size_t>(quantity) + 1] = (Real)2 * slope[quantity] - slope[static_cast<size_t>(quantity) - 1]; slope[static_cast<size_t>(quantity) + 2] = (Real)2 * slope[static_cast<size_t>(quantity) + 1] - slope[quantity]; // Construct derivatives. std::vector<Real> FDer(quantity); for (i = 0; i < quantity; ++i) { FDer[i] = this->ComputeDerivative(&slope[i]); } // Construct polynomials. Real invDX2 = (Real)1 / (mXSpacing * mXSpacing); Real invDX3 = invDX2 / mXSpacing; for (i = 0, ip1 = 1; i < quantity - 1; ++i, ++ip1) { auto& poly = this->mPoly[i]; Real F0 = F[i]; Real F1 = F[ip1]; Real df = F1 - F0; Real FDer0 = FDer[i]; Real FDer1 = FDer[ip1]; poly[0] = F0; poly[1] = FDer0; poly[2] = ((Real)3 * df - mXSpacing * (FDer1 + (Real)2 * FDer0)) * invDX2; poly[3] = (mXSpacing * (FDer0 + FDer1) - (Real)2 * df) * invDX3; } } virtual ~IntpAkimaUniform1() = default; // Member access. inline virtual Real GetXMin() const override { return mXMin; } inline virtual Real GetXMax() const override { return mXMax; } inline Real GetXSpacing() const { return mXSpacing; } protected: virtual void Lookup(Real x, int32_t& index, Real& dx) const override { // The caller has ensured that mXMin <= x <= mXMax. int32_t indexP1; for (index = 0, indexP1 = 1; indexP1 < this->mQuantity; ++index, ++indexP1) { if (x < mXMin + mXSpacing * (indexP1)) { dx = x - (mXMin + mXSpacing * index); return; } } --index; dx = x - (mXMin + mXSpacing * index); } Real mXMin, mXMax, mXSpacing; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/EdgeKey.h
.h
1,524
61
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/FeatureKey.h> // An ordered edge has (V[0], V[1]) = (v0, v1). An unordered edge has // (V[0], V[1]) = (min(V[0],V[1]), max(V[0],V[1])). namespace gte { template <bool Ordered> class EdgeKey : public FeatureKey<2, Ordered> { public: // Initialize to invalid indices. EdgeKey() { this->V = { -1, -1 }; } // This constructor is specialized based on Ordered. explicit EdgeKey(int32_t v0, int32_t v1) { Initialize(v0, v1); } private: template <bool Dummy = Ordered> typename std::enable_if<Dummy, void>::type Initialize(int32_t v0, int32_t v1) { this->V[0] = v0; this->V[1] = v1; } template <bool Dummy = Ordered> typename std::enable_if<!Dummy, void>::type Initialize(int32_t v0, int32_t v1) { if (v0 < v1) { // v0 is minimum this->V[0] = v0; this->V[1] = v1; } else { // v1 is minimum this->V[0] = v1; this->V[1] = v0; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrArc2Arc2.h
.h
9,907
227
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/IntrCircle2Circle2.h> #include <Mathematics/Arc2.h> namespace gte { template <typename T> class FIQuery<T, Arc2<T>, Arc2<T>> { public: // The possible 'configuration' in Result are listed as an // enumeration. The valid array elements are listed in the comments. enum class Configuration { NO_INTERSECTION, NONCOCIRCULAR_ONE_POINT, // point[0] NONCOCIRCULAR_TWO_POINTS, // point[0], point[1] COCIRCULAR_ONE_POINT, // point[0] COCIRCULAR_TWO_POINTS, // point[0], point[1] COCIRCULAR_ONE_POINT_ONE_ARC, // point[0], arc[0] COCIRCULAR_ONE_ARC, // arc[0] COCIRCULAR_TWO_ARCS // arc[0], arc[1] }; struct Result { Result() : intersect(false), configuration(Configuration::NO_INTERSECTION), point{ Vector2<T>::Zero(), Vector2<T>::Zero() }, arc{ Arc2<T>(Vector2<T>::Zero(), (T)0, Vector2<T>::Zero(), Vector2<T>::Zero()), Arc2<T>(Vector2<T>::Zero(), (T)0, Vector2<T>::Zero(), Vector2<T>::Zero()) } { } // 'true' iff configuration != NO_INTERSECTION bool intersect; // one of the enumerations listed previously Configuration configuration; std::array<Vector2<T>, 2> point; std::array<Arc2<T>, 2> arc; }; Result operator()(Arc2<T> const& arc0, Arc2<T> const& arc1) { // Assume initially there are no intersections. If we find at // least one intersection, we will set result.intersect to 'true'. Result result{}; Circle2<T> circle0(arc0.center, arc0.radius); Circle2<T> circle1(arc1.center, arc1.radius); FIQuery<T, Circle2<T>, Circle2<T>> ccQuery; auto ccResult = ccQuery(circle0, circle1); if (!ccResult.intersect) { // The arcs do not intersect. result.configuration = Configuration::NO_INTERSECTION; return result; } if (ccResult.numIntersections == std::numeric_limits<int32_t>::max()) { // The arcs are cocircular. Determine whether they overlap. // Let arc0 be <A0,A1> and arc1 be <B0,B1>. The points are // ordered counterclockwise around the circle of the arc. if (arc1.Contains(arc0.end[0])) { result.intersect = true; if (arc1.Contains(arc0.end[1])) { if (arc0.Contains(arc1.end[0]) && arc0.Contains(arc1.end[1])) { if (arc0.end[0] == arc1.end[0] && arc0.end[1] == arc1.end[1]) { // The arcs are the same. result.configuration = Configuration::COCIRCULAR_ONE_ARC; result.arc[0] = arc0; } else { // arc0 and arc1 overlap in two disjoint // subsets. if (arc0.end[0] != arc1.end[1]) { if (arc1.end[0] != arc0.end[1]) { // The arcs overlap in two disjoint // subarcs, each of positive subtended // angle: <A0,B1>, <A1,B0> result.configuration = Configuration::COCIRCULAR_TWO_ARCS; result.arc[0] = Arc2<T>(arc0.center, arc0.radius, arc0.end[0], arc1.end[1]); result.arc[1] = Arc2<T>(arc0.center, arc0.radius, arc1.end[0], arc0.end[1]); } else // B0 = A1 { // The intersection is a point {A1} // and an arc <A0,B1>. result.configuration = Configuration::COCIRCULAR_ONE_POINT_ONE_ARC; result.point[0] = arc0.end[1]; result.arc[0] = Arc2<T>(arc0.center, arc0.radius, arc0.end[0], arc1.end[1]); } } else // A0 = B1 { if (arc1.end[0] != arc0.end[1]) { // The intersection is a point {A0} // and an arc <A1,B0>. result.configuration = Configuration::COCIRCULAR_ONE_POINT_ONE_ARC; result.point[0] = arc0.end[0]; result.arc[0] = Arc2<T>(arc0.center, arc0.radius, arc1.end[0], arc0.end[1]); } else { // The arcs shared endpoints, so the // union is a circle. result.configuration = Configuration::COCIRCULAR_TWO_POINTS; result.point[0] = arc0.end[0]; result.point[1] = arc0.end[1]; } } } } else { // Arc0 inside arc1, <B0,A0,A1,B1>. result.configuration = Configuration::COCIRCULAR_ONE_ARC; result.arc[0] = arc0; } } else { if (arc0.end[0] != arc1.end[1]) { // Arc0 and arc1 overlap, <B0,A0,B1,A1>. result.configuration = Configuration::COCIRCULAR_ONE_ARC; result.arc[0] = Arc2<T>(arc0.center, arc0.radius, arc0.end[0], arc1.end[1]); } else { // Arc0 and arc1 share endpoint, <B0,A0,B1,A1> // with A0 = B1. result.configuration = Configuration::COCIRCULAR_ONE_POINT; result.point[0] = arc0.end[0]; } } return result; } if (arc1.Contains(arc0.end[1])) { result.intersect = true; if (arc0.end[1] != arc1.end[0]) { // Arc0 and arc1 overlap in a single arc, // <A0,B0,A1,B1>. result.configuration = Configuration::COCIRCULAR_ONE_ARC; result.arc[0] = Arc2<T>(arc0.center, arc0.radius, arc1.end[0], arc0.end[1]); } else { // Arc0 and arc1 share endpoint, <A0,B0,A1,B1> // with B0 = A1. result.configuration = Configuration::COCIRCULAR_ONE_POINT; result.point[0] = arc1.end[0]; } return result; } if (arc0.Contains(arc1.end[0])) { // Arc1 inside arc0, <A0,B0,B1,A1>. result.intersect = true; result.configuration = Configuration::COCIRCULAR_ONE_ARC; result.arc[0] = arc1; } else { // Arcs do not overlap, <A0,A1,B0,B1>. result.configuration = Configuration::NO_INTERSECTION; } return result; } // Test whether circle-circle intersection points are on the arcs. int32_t numIntersections = 0; for (int32_t i = 0; i < ccResult.numIntersections; ++i) { if (arc0.Contains(ccResult.point[i]) && arc1.Contains(ccResult.point[i])) { result.point[numIntersections] = ccResult.point[i]; ++numIntersections; result.intersect = true; } } if (numIntersections == 2) { result.configuration = Configuration::NONCOCIRCULAR_TWO_POINTS; } else if (numIntersections == 1) { result.configuration = Configuration::NONCOCIRCULAR_ONE_POINT; } else { result.configuration = Configuration::NO_INTERSECTION; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox2Sector2.h
.h
5,095
137
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/TIQuery.h> #include <Mathematics/OrientedBox.h> #include <Mathematics/DistPointSegment.h> #include <Mathematics/IntrHalfspace2Polygon2.h> #include <Mathematics/Sector2.h> // The OrientedBox2 object is considered to be a solid. namespace gte { template <typename Real> class TIQuery<Real, OrientedBox2<Real>, Sector2<Real>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(OrientedBox2<Real> const& box, Sector2<Real> const& sector) { Result result{}; // Determine whether the vertex is inside the box. Vector2<Real> CmV = box.center - sector.vertex; Vector2<Real> P{ Dot(box.axis[0], CmV), Dot(box.axis[1], CmV) }; if (std::fabs(P[0]) <= box.extent[0] && std::fabs(P[1]) <= box.extent[1]) { // The vertex is inside the box. result.intersect = true; return result; } // Test whether the box is outside the right ray boundary of the // sector. Vector2<Real> U0 { +sector.cosAngle * sector.direction[0] + sector.sinAngle * sector.direction[1], -sector.sinAngle * sector.direction[0] + sector.cosAngle * sector.direction[1] }; Vector2<Real> N0 = Perp(U0); Real prjcen0 = Dot(N0, CmV); Real radius0 = box.extent[0] * std::fabs(Dot(N0, box.axis[0])) + box.extent[1] * std::fabs(Dot(N0, box.axis[1])); if (prjcen0 > radius0) { result.intersect = false; return result; } // Test whether the box is outside the ray of the left boundary // of the sector. Vector2<Real> U1 { +sector.cosAngle * sector.direction[0] - sector.sinAngle * sector.direction[1], +sector.sinAngle * sector.direction[0] + sector.cosAngle * sector.direction[1] }; Vector2<Real> N1 = -Perp(U1); Real prjcen1 = Dot(N1, CmV); Real radius1 = box.extent[0] * std::fabs(Dot(N1, box.axis[0])) + box.extent[1] * std::fabs(Dot(N1, box.axis[1])); if (prjcen1 > radius1) { result.intersect = false; return result; } // Initialize the polygon of intersection to be the box. Vector2<Real> e0U0 = box.extent[0] * box.axis[0]; Vector2<Real> e1U1 = box.extent[1] * box.axis[1]; std::vector<Vector2<Real>> polygon; polygon.reserve(8); polygon.push_back(box.center - e0U0 - e1U1); polygon.push_back(box.center + e0U0 - e1U1); polygon.push_back(box.center + e0U0 + e1U1); polygon.push_back(box.center - e0U0 + e1U1); FIQuery<Real, Halfspace<2, Real>, std::vector<Vector2<Real>>> hpQuery; typename FIQuery<Real, Halfspace<2, Real>, std::vector<Vector2<Real>>>::Result hpResult; Halfspace<2, Real> halfspace; // Clip the box against the right-ray sector boundary. if (prjcen0 >= -radius0) { halfspace.normal = -N0; halfspace.constant = Dot(halfspace.normal, sector.vertex); hpResult = hpQuery(halfspace, polygon); polygon = std::move(hpResult.polygon); } // Clip the box against the left-ray sector boundary. if (prjcen1 >= -radius1) { halfspace.normal = -N1; halfspace.constant = Dot(halfspace.normal, sector.vertex); hpResult = hpQuery(halfspace, polygon); polygon = std::move(hpResult.polygon); } DCPQuery<Real, Vector2<Real>, Segment2<Real>> psQuery; typename DCPQuery<Real, Vector2<Real>, Segment2<Real>>::Result psResult; int32_t const numVertices = static_cast<int32_t>(polygon.size()); if (numVertices >= 2) { for (int32_t i0 = numVertices - 1, i1 = 0; i1 < numVertices; i0 = i1++) { Segment2<Real> segment(polygon[i0], polygon[i1]); psResult = psQuery(sector.vertex, segment); if (psResult.distance <= sector.radius) { result.intersect = true; return result; } } } result.intersect = false; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/OBBTreeOfPoints.h
.h
12,171
332
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/BitHacks.h> #include <Mathematics/ContOrientedBox3.h> // The depth of a node in a (nonempty) tree is the distance from the node to // the root of the tree. The height is the maximum depth. A tree with a // single node has height 0. The set of nodes of a tree with the same depth // is refered to as a level of a tree (corresponding to that depth). A // complete binary tree of height H has 2^{H+1}-1 nodes. The level // corresponding to depth D has 2^D nodes, in which case the number of // leaf nodes (depth H) is 2^H. namespace gte { template <typename Real> class OBBTreeForPoints { public: struct Node { Node() : depth(0), minIndex(std::numeric_limits<uint32_t>::max()), maxIndex(std::numeric_limits<uint32_t>::max()), leftChild(std::numeric_limits<uint32_t>::max()), rightChild(std::numeric_limits<uint32_t>::max()) { } OrientedBox3<Real> box; uint32_t depth; uint32_t minIndex, maxIndex; uint32_t leftChild, rightChild; }; // The 'points' array is a collection of vertices, each occupying a // chunk of memory with 'stride' bytes. A vertex must start at the // first byte of this chunk but does not necessarily fill it. The // 'height' specifies the height of the tree and must be no larger // than 31. If it is set to std::numeric_limits<uint32_t>::max(), // then the entire tree is built and the actual height is computed // from 'numPoints'. OBBTreeForPoints(uint32_t numPoints, char const* points, size_t stride, uint32_t height = std::numeric_limits<uint32_t>::max()) : mNumPoints(numPoints), mPoints(points), mStride(stride), mHeight(height), mPartition(numPoints) { // The tree nodes are indexed by 32-bit unsigned integers, so // the number of nodes can be at most 2^{32} - 1. This limits // the height to 31. uint32_t numNodes; if (mHeight == std::numeric_limits<uint32_t>::max()) { uint32_t minPowerOfTwo = static_cast<uint32_t>(BitHacks::RoundUpToPowerOfTwo(mNumPoints)); mHeight = BitHacks::Log2OfPowerOfTwo(minPowerOfTwo); numNodes = 2 * mNumPoints - 1; } else { // The maximum level cannot exceed 30 because we are storing // the indices into the node array as 32-bit unsigned // integers. if (mHeight < 32) { numNodes = (uint32_t)(1ULL << (mHeight + 1)) - 1; } else { // When the precondition is not met, return a tree of // height 0 (a single node). mHeight = 0; numNodes = 1; } } // The tree is built recursively. A reference to a Node is // passed to BuildTree and nodes are appended to a std::vector. // Because the references are on the stack, we must guarantee no // reallocations to avoid invalidating the references. TODO: // This design can be modified to pass indices to the nodes so // that reallocation is not a problem. mTree.reserve(numNodes); // Build the tree recursively. The array mPartition stores the // indices into the 'points' array so that at a node, the points // represented by the node are those indexed by the range // [node.minIndex, node.maxIndex]. for (uint32_t i = 0; i < mNumPoints; ++i) { mPartition[i] = i; } mTree.push_back(Node()); BuildTree(mTree.back(), 0, mNumPoints - 1); } // Member access. inline uint32_t GetNumPoints() const { return mNumPoints; } inline char const* GetPoints() const { return mPoints; } inline size_t GetStride() const { return mStride; } inline std::vector<Node> const& GetTree() const { return mTree; } inline uint32_t GetHeight() const { return mHeight; } inline std::vector<uint32_t> const& GetPartition() const { return mPartition; } private: inline Vector3<Real> GetPosition(uint32_t index) const { return *reinterpret_cast<Vector3<Real> const*>(mPoints + index * mStride); } void BuildTree(Node& node, uint32_t i0, uint32_t i1) { node.minIndex = i0; node.maxIndex = i1; if (i0 == i1) { // We are at a leaf node. The left and right child indices // were set to std::numeric_limits<uint32_t>::max() during // construction. // Create a degenerate box whose center is the point. node.box.center = GetPosition(mPartition[i0]); node.box.axis[0] = Vector3<Real>{ (Real)1, (Real)0, (Real)0 }; node.box.axis[1] = Vector3<Real>{ (Real)0, (Real)1, (Real)0 }; node.box.axis[2] = Vector3<Real>{ (Real)0, (Real)0, (Real)1 }; node.box.extent = Vector3<Real>{ (Real)0, (Real)0, (Real)0 }; } else // i0 < i1 { // We are at an interior node. Compute an oriented bounding // box. ComputeOBB(i0, i1, node.box); if (node.depth == mHeight) { return; } // Use the box axis corresponding to largest extent for the // splitting axis. Partition the points into two subsets, one // for the left child and one for the right child. The subsets // have numbers of elements that differ by at most 1, so the // tree is balanced. Vector3<Real> axis2 = node.box.axis[2]; uint32_t j0, j1; SplitPoints(i0, i1, j0, j1, node.box.center, axis2); node.leftChild = static_cast<uint32_t>(mTree.size()); node.rightChild = node.leftChild + 1; mTree.push_back(Node()); Node& leftTree = mTree.back(); mTree.push_back(Node()); Node& rightTree = mTree.back(); leftTree.depth = node.depth + 1; rightTree.depth = node.depth + 1; BuildTree(leftTree, i0, j0); BuildTree(rightTree, j1, i1); } } void ComputeOBB(uint32_t i0, uint32_t i1, OrientedBox3<Real>& box) { // Compute the mean of the points. Vector3<Real> zero{ (Real)0, (Real)0, (Real)0 }; box.center = zero; for (uint32_t i = i0; i <= i1; ++i) { box.center += GetPosition(mPartition[i]); } int32_t denom = i1 - i0 + 1; Real invSize = ((Real)1) / (Real)denom; box.center *= invSize; // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (Real)0; for (uint32_t i = i0; i <= i1; ++i) { Vector3<Real> diff = GetPosition(mPartition[i]) - box.center; covar00 += diff[0] * diff[0]; covar01 += diff[0] * diff[1]; covar02 += diff[0] * diff[2]; covar11 += diff[1] * diff[1]; covar12 += diff[1] * diff[2]; covar22 += diff[2] * diff[2]; } covar00 *= invSize; covar01 *= invSize; covar02 *= invSize; covar11 *= invSize; covar12 *= invSize; covar22 *= invSize; // Solve the eigensystem and use the eigenvectors for the box // axes. SymmetricEigensolver3x3<Real> es; std::array<Real, 3> eval; std::array<std::array<Real, 3>, 3> evec; es(covar00, covar01, covar02, covar11, covar12, covar22, false, +1, eval, evec); for (int32_t i = 0; i < 3; ++i) { box.axis[i] = evec[i]; } box.extent = eval; // Let C be the box center and let U0, U1, and U2 be the box axes. // Each input point is of the form X = C + y0*U0 + y1*U1 + y2*U2. // The following code computes min(y0), max(y0), min(y1), max(y1), // min(y2), and max(y2). The box center is then adjusted to be // C' = C + 0.5*(min(y0)+max(y0))*U0 + 0.5*(min(y1)+max(y1))*U1 // + 0.5*(min(y2)+max(y2))*U2 Vector3<Real> pmin = zero, pmax = zero; for (uint32_t i = i0; i <= i1; ++i) { Vector3<Real> diff = GetPosition(mPartition[i]) - box.center; for (int32_t j = 0; j < 3; ++j) { Real dot = Dot(diff, box.axis[j]); if (dot < pmin[j]) { pmin[j] = dot; } else if (dot > pmax[j]) { pmax[j] = dot; } } } Real const half(0.5); for (int32_t j = 0; j < 3; ++j) { box.center += (half * (pmin[j] + pmax[j])) * box.axis[j]; box.extent[j] = half * (pmax[j] - pmin[j]); } } void SplitPoints(uint32_t i0, uint32_t i1, uint32_t& j0, uint32_t& j1, Vector3<Real> const& origin, Vector3<Real> const& direction) { // Project the points onto the splitting axis. uint32_t numProjections = i1 - i0 + 1; std::vector<ProjectionInfo> info(numProjections); uint32_t i, k; for (i = i0, k = 0; i <= i1; ++i, ++k) { Vector3<Real> diff = GetPosition(mPartition[i]) - origin; info[k].pointIndex = mPartition[i]; info[k].projection = Dot(direction, diff); } // Partition the projections by the median. uint32_t medianIndex = (numProjections - 1) / 2; std::nth_element(info.begin(), info.begin() + medianIndex, info.end()); // Partition the points by the median. for (k = 0, j0 = i0 - 1; k <= medianIndex; ++k) { mPartition[++j0] = info[k].pointIndex; } for (j1 = i1 + 1; k < numProjections; ++k) { mPartition[--j1] = info[k].pointIndex; } } struct ProjectionInfo { ProjectionInfo() : pointIndex(0), projection((Real)0) { } bool operator< (ProjectionInfo const& info) const { return projection < info.projection; } uint32_t pointIndex; Real projection; }; uint32_t mNumPoints; char const* mPoints; size_t mStride; uint32_t mHeight; std::vector<Node> mTree; std::vector<uint32_t> mPartition; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/LCPSolver.h
.h
23,632
639
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.01.06 #pragma once #include <Mathematics/Logger.h> #include <algorithm> #include <array> #include <vector> // A class for solving the Linear Complementarity Problem (LCP) // w = q + M * z, w^T * z = 0, w >= 0, z >= 0. The vectors q, w, and z are // n-tuples and the matrix M is n-by-n. The inputs to Solve(...) are q and M. // The outputs are w and z, which are valid when the returned bool is true but // are invalid when the returned bool is false. // // The comments at the end of this file explain what the preprocessor symbol // means regarding the LCP solver implementation. If the algorithm fails to // converge within the specified maximum number of iterations, consider // increasing the number and calling Solve(...) again. // Expose the following preprocessor symbol if you want the code to throw an // exception the algorithm fails to converge. You can choose to trap the // exception and handle it as you please. If you do not expose the // preprocessor symbol, you can pass a Result object and check whether the // algorithm failed to converge. Again, you can handle this as you please. // //#define GTE_THROW_ON_LCPSOLVER_ERRORS namespace gte { // Support templates for number of dimensions known at compile time or // known only at run time. template <typename T, int32_t... Dimensions> class LCPSolver {}; template <typename T> class LCPSolverShared { protected: // Abstract base class construction. A virtual destructor is not // provided because there are no required side effects when destroying // objects from the derived classes. The member mMaxIterations is set // by this call to the default value n*n. LCPSolverShared(int32_t n) : mNumIterations(0), mVarBasic(nullptr), mVarNonbasic(nullptr), mNumCols(0), mAugmented(nullptr), mQMin(nullptr), mMinRatio(nullptr), mRatio(nullptr), mPoly(nullptr), mZero((T)0), mOne((T)1) { if (n > 0) { mDimension = n; mMaxIterations = n * n; } else { mDimension = 0; mMaxIterations = 0; } } // Use this constructor when you need a specific representation of // zero and of one to be used when manipulating the polynomials of the // base class. In particular, this is needed to select the correct // zero and correct one for QFNumber objects. LCPSolverShared(int32_t n, T const& zero, T const& one) : mNumIterations(0), mVarBasic(nullptr), mVarNonbasic(nullptr), mNumCols(0), mAugmented(nullptr), mQMin(nullptr), mMinRatio(nullptr), mRatio(nullptr), mPoly(nullptr), mZero(zero), mOne(one) { if (n > 0) { mDimension = n; mMaxIterations = n * n; } else { mDimension = 0; mMaxIterations = 0; } } public: // Theoretically, when there is a solution the algorithm must converge // in a finite number of iterations. The number of iterations depends // on the problem at hand, but we need to guard against an infinite // loop by limiting the number. The implementation uses a maximum // number of n*n (chosen arbitrarily). You can set the number // yourself, perhaps when a call to Solve fails--increase the number // of iterations and call and solve again. inline void SetMaxIterations(int32_t maxIterations) { mMaxIterations = (maxIterations > 0 ? maxIterations : mDimension * mDimension); } inline int32_t GetMaxIterations() const { return mMaxIterations; } // Access the actual number of iterations used in a call to Solve. inline int32_t GetNumIterations() const { return mNumIterations; } enum class Result { HAS_TRIVIAL_SOLUTION, HAS_NONTRIVIAL_SOLUTION, NO_SOLUTION, FAILED_TO_CONVERGE, INVALID_INPUT }; protected: // Bookkeeping of variables during the iterations of the solver. The // name is either 'w' or 'z' and is used for human-readable debugging // help. The 'index' is that for the original variables w[index] or // z[index]. The 'complementary' index is the location of the // complementary variable in mVarBasic[] or in mVarNonbasic[]. The // 'tuple' is a pointer to &w[0] or &z[0], the choice based on name of // 'w' or 'z', and is used to fill in the solution values (the // variables are permuted during the pivoting algorithm). struct Variable { Variable() : name(0), index(0), complementary(0), tuple(nullptr) { } char name; int32_t index; int32_t complementary; T* tuple; }; // The augmented problem is w = q + M*z + z[n]*U = 0, where U is an // n-tuple of 1-values. We manipulate the augmented matrix // [M | U | p(t)] where p(t) is a column vector of polynomials of at // most degree n. If p[r](t) is the polynomial for row r, then // p[r](0) = q[r]. These are perturbations of q[r] designed so that // the algorithm avoids degeneracies (a q-term becomes zero during the // iterations). The basic variables are w[0] through w[n-1] and the // nonbasic variables are z[0] through z[n]. The returned z consists // only of z[0] through z[n-1]. // The derived classes ensure that the pointers point to the correct // of elements for each array. The matrix M must be stored in // row-major order. bool Solve(T const* q, T const* M, T* w, T* z, Result* result) { // Perturb the q[r] constants to be polynomials of degree r+1 // represented as an array of n+1 coefficients. The coefficient // with index r+1 is 1 and the coefficients with indices larger // than r+1 are 0. for (int32_t r = 0; r < mDimension; ++r) { mPoly[r] = &Augmented(r, mDimension + 1); MakeZero(mPoly[r]); mPoly[r][0] = q[r]; mPoly[r][r + 1] = mOne; } // Determine whether there is the trivial solution w = z = 0. Copy(mPoly[0], mQMin); int32_t basic = 0; for (int32_t r = 1; r < mDimension; ++r) { if (LessThan(mPoly[r], mQMin)) { Copy(mPoly[r], mQMin); basic = r; } } if (!LessThanZero(mQMin)) { for (int32_t r = 0; r < mDimension; ++r) { w[r] = q[r]; z[r] = mZero; } if (result) { *result = Result::HAS_TRIVIAL_SOLUTION; } return true; } // Initialize the remainder of the augmented matrix with M and U. for (int32_t r = 0; r < mDimension; ++r) { for (int32_t c = 0; c < mDimension; ++c) { Augmented(r, c) = M[c + mDimension * r]; } Augmented(r, mDimension) = mOne; } // Keep track of when the variables enter and exit the dictionary, // including where complementary variables are relocated. for (int32_t i = 0; i <= mDimension; ++i) { mVarBasic[i].name = 'w'; mVarBasic[i].index = i; mVarBasic[i].complementary = i; mVarBasic[i].tuple = w; mVarNonbasic[i].name = 'z'; mVarNonbasic[i].index = i; mVarNonbasic[i].complementary = i; mVarNonbasic[i].tuple = z; } // The augmented variable z[n] is the initial driving variable for // pivoting. The equation 'basic' is the one to solve for z[n] // and pivoting with w[basic]. The last column of M remains all // 1-values for this initial step, so no algebraic computations // occur for M[r][n]. int32_t driving = mDimension; for (int32_t r = 0; r < mDimension; ++r) { if (r != basic) { for (int32_t c = 0; c < mNumCols; ++c) { if (c != mDimension) { Augmented(r, c) -= Augmented(basic, c); } } } } for (int32_t c = 0; c < mNumCols; ++c) { if (c != mDimension) { Augmented(basic, c) = -Augmented(basic, c); } } mNumIterations = 0; for (int32_t i = 0; i < mMaxIterations; ++i, ++mNumIterations) { // The basic variable of equation 'basic' exited the // dictionary, so/ its complementary (nonbasic) variable must // become the next driving variable in order for it to enter // the dictionary. int32_t nextDriving = mVarBasic[basic].complementary; mVarNonbasic[nextDriving].complementary = driving; std::swap(mVarBasic[basic], mVarNonbasic[driving]); if (mVarNonbasic[driving].index == mDimension) { // The algorithm has converged. for (int32_t r = 0; r < mDimension; ++r) { mVarBasic[r].tuple[mVarBasic[r].index] = mPoly[r][0]; } for (int32_t c = 0; c <= mDimension; ++c) { int32_t index = mVarNonbasic[c].index; if (index < mDimension) { mVarNonbasic[c].tuple[index] = mZero; } } if (result) { *result = Result::HAS_NONTRIVIAL_SOLUTION; } return true; } // Determine the 'basic' equation for which the ratio // -q[r]/M(r,driving) is minimized among all equations r with // M(r,driving) < 0. driving = nextDriving; basic = -1; for (int32_t r = 0; r < mDimension; ++r) { if (Augmented(r, driving) < mZero) { T factor = -mOne / Augmented(r, driving); Multiply(mPoly[r], factor, mRatio); if (basic == -1 || LessThan(mRatio, mMinRatio)) { Copy(mRatio, mMinRatio); basic = r; } } } if (basic == -1) { // The coefficients of z[driving] in all the equations are // nonnegative, so the z[driving] variable cannot leave // the dictionary. There is no solution to the LCP. for (int32_t r = 0; r < mDimension; ++r) { w[r] = mZero; z[r] = mZero; } if (result) { *result = Result::NO_SOLUTION; } return false; } // Solve the basic equation so that z[driving] enters the // dictionary and w[basic] exits the dictionary. T invDenom = mOne / Augmented(basic, driving); for (int32_t r = 0; r < mDimension; ++r) { if (r != basic && Augmented(r, driving) != mZero) { T multiplier = Augmented(r, driving) * invDenom; for (int32_t c = 0; c < mNumCols; ++c) { if (c != driving) { Augmented(r, c) -= Augmented(basic, c) * multiplier; } else { Augmented(r, driving) = multiplier; } } } } for (int32_t c = 0; c < mNumCols; ++c) { if (c != driving) { Augmented(basic, c) = -Augmented(basic, c) * invDenom; } else { Augmented(basic, driving) = invDenom; } } } // Numerical round-off errors can cause the Lemke algorithm not to // converge. In particular, the code above has a test // if (mAugmented[r][driving] < (T)0) { ... } // to determine the 'basic' equation with which to pivot. It is // possible that theoretically mAugmented[r][driving]is zero but // rounding errors cause it to be slightly negative. If // theoretically all mAugmented[r][driving] >= 0, there is no // solution to the LCP. With the rounding errors, if the // algorithm fails to converge within the specified number of // iterations, NO_SOLUTION is returned, which is hopefully the // correct result. It is also possible that the rounding errors // lead to a NO_SOLUTION (returned from inside the loop) when in // fact there is a solution. When the LCP solver is used by // intersection testing algorithms, the hope is that // misclassifications occur only when the two objects are nearly // in tangential contact. // // To determine whether the rounding errors are the problem, you // can execute the query using exact arithmetic with the following // type used for 'T' (replacing 'float' or 'double') of // BSRational<UIntegerAP32> Rational. // // That said, if the algorithm fails to converge and you believe // that the rounding errors are not causing this, please file a // bug report and provide the input data to the solver. #if defined(GTE_THROW_ON_LCPSOLVER_ERRORS) LogError("LCPSolverShared::Solve failed to converge."); #endif if (result) { *result = Result::FAILED_TO_CONVERGE; } return false; } // Access mAugmented as a 2-dimensional array. inline T const& Augmented(int32_t row, int32_t col) const { return mAugmented[col + mNumCols * row]; } inline T& Augmented(int32_t row, int32_t col) { return mAugmented[col + mNumCols * row]; } // Support for polynomials with n+1 coefficients and degree no larger // than n. void MakeZero(T* poly) { for (int32_t i = 0; i <= mDimension; ++i) { poly[i] = mZero; } } void Copy(T const* poly0, T* poly1) { for (int32_t i = 0; i <= mDimension; ++i) { poly1[i] = poly0[i]; } } bool LessThan(T const* poly0, T const* poly1) { for (int32_t i = 0; i <= mDimension; ++i) { if (poly0[i] < poly1[i]) { return true; } if (poly0[i] > poly1[i]) { return false; } } return false; } bool LessThanZero(T const* poly) { for (int32_t i = 0; i <= mDimension; ++i) { if (poly[i] < mZero) { return true; } if (poly[i] > mZero) { return false; } } return false; } void Multiply(T const* poly, T scalar, T* product) { for (int32_t i = 0; i <= mDimension; ++i) { product[i] = poly[i] * scalar; } } int32_t mDimension; int32_t mMaxIterations; int32_t mNumIterations; // These pointers are set by the derived-class constructors to arrays // that have the correct number of elements. The arrays mVarBasic, // mVarNonbasic, mQMin, mMinRatio, and mRatio each have n+1 elements. // The mAugmented array has n rows and 2*(n+1) columns stored in // row-major order in a 1-dimensional array. The array of pointers // mPoly has n elements. Variable* mVarBasic; Variable* mVarNonbasic; int32_t mNumCols; T* mAugmented; T* mQMin; T* mMinRatio; T* mRatio; T** mPoly; T mZero, mOne; }; template <typename T, int32_t n> class LCPSolver<T, n> : public LCPSolverShared<T> { public: // Construction. The member mMaxIterations is set by this call to the // default value n*n. LCPSolver() : LCPSolverShared<T>(n) { this->mVarBasic = mArrayVarBasic.data(); this->mVarNonbasic = mArrayVarNonbasic.data(); this->mNumCols = 2 * (n + 1); this->mAugmented = mArrayAugmented.data(); this->mQMin = mArrayQMin.data(); this->mMinRatio = mArrayMinRatio.data(); this->mRatio = mArrayRatio.data(); this->mPoly = mArrayPoly.data(); } // Use this constructor when you need a specific representation of // zero and of one to be used when manipulating the polynomials of the // base class. In particular, this is needed to select the correct // zero and correct one for QFNumber objects. LCPSolver(T const& zero, T const& one) : LCPSolverShared<T>(n, zero, one) { this->mVarBasic = mArrayVarBasic.data(); this->mVarNonbasic = mArrayVarNonbasic.data(); this->mNumCols = 2 * (n + 1); this->mAugmented = mArrayAugmented.data(); this->mQMin = mArrayQMin.data(); this->mMinRatio = mArrayMinRatio.data(); this->mRatio = mArrayRatio.data(); this->mPoly = mArrayPoly.data(); } // If you want to know specifically why 'true' or 'false' was // returned, pass the address of a Result variable as the last // parameter. bool Solve(std::array<T, n> const& q, std::array<std::array<T, n>, n> const& M, std::array<T, n>& w, std::array<T, n>& z, typename LCPSolverShared<T>::Result* result = nullptr) { return LCPSolverShared<T>::Solve(q.data(), M.front().data(), w.data(), z.data(), result); } private: std::array<typename LCPSolverShared<T>::Variable, n + 1> mArrayVarBasic; std::array<typename LCPSolverShared<T>::Variable, n + 1> mArrayVarNonbasic; std::array<T, 2 * (n + 1)* n> mArrayAugmented; std::array<T, n + 1> mArrayQMin; std::array<T, n + 1> mArrayMinRatio; std::array<T, n + 1> mArrayRatio; std::array<T*, n> mArrayPoly; }; template <typename T> class LCPSolver<T> : public LCPSolverShared<T> { public: // Construction. The member mMaxIterations is set by this call to the // default value n*n. LCPSolver(int32_t n) : LCPSolverShared<T>(n) { if (n > 0) { size_t np1 = static_cast<size_t>(n) + 1; mVectorVarBasic.resize(np1); mVectorVarNonbasic.resize(np1); mVectorAugmented.resize(2 * np1 * n); mVectorQMin.resize(np1); mVectorMinRatio.resize(np1); mVectorRatio.resize(np1); mVectorPoly.resize(n); this->mVarBasic = mVectorVarBasic.data(); this->mVarNonbasic = mVectorVarNonbasic.data(); this->mNumCols = 2 * (n + 1); this->mAugmented = mVectorAugmented.data(); this->mQMin = mVectorQMin.data(); this->mMinRatio = mVectorMinRatio.data(); this->mRatio = mVectorRatio.data(); this->mPoly = mVectorPoly.data(); } } // The input q must have n elements and the input M must be an n-by-n // matrix stored in row-major order. The outputs w and z have n // elements. If you want to know specifically why 'true' or 'false' // was returned, pass the address of a Result variable as the last // parameter. bool Solve(std::vector<T> const& q, std::vector<T> const& M, std::vector<T>& w, std::vector<T>& z, typename LCPSolverShared<T>::Result* result = nullptr) { if (this->mDimension > static_cast<int32_t>(q.size()) || this->mDimension * this->mDimension > static_cast<int32_t>(M.size())) { if (result) { *result = LCPSolverShared<T>::Result::INVALID_INPUT; } return false; } if (this->mDimension > static_cast<int32_t>(w.size())) { w.resize(this->mDimension); } if (this->mDimension > static_cast<int32_t>(z.size())) { z.resize(this->mDimension); } return LCPSolverShared<T>::Solve(q.data(), M.data(), w.data(), z.data(), result); } private: std::vector<typename LCPSolverShared<T>::Variable> mVectorVarBasic; std::vector<typename LCPSolverShared<T>::Variable> mVectorVarNonbasic; std::vector<T> mVectorAugmented; std::vector<T> mVectorQMin; std::vector<T> mVectorMinRatio; std::vector<T> mVectorRatio; std::vector<T*> mVectorPoly; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SlerpEstimate.h
.h
5,657
152
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2022 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 6.0.2022.07.04 #pragma once #include <Mathematics/Quaternion.h> // The spherical linear interpolation (slerp) of unit-length quaternions // q0 and q1 for t in [0,1] and theta in (0,pi) is // slerp(t,q0,q1) = [sin((1-t)*theta)*q0 + sin(theta)*q1]/sin(theta) // where theta is the angle between q0 and q1 [cos(theta) = Dot(q0,q1)]. // This function is a parameterization of the great spherical arc between // q0 and q1 on the unit hypersphere. Moreover, the parameterization is // one of normalized arclength--a particle traveling along the arc through // time t does so with constant speed. // // Read the comments in ChebyshevRatio.h regarding estimates for the // ratio sin(t*theta)/sin(theta). // // When using slerp in animations involving sequences of quaternions, it is // typical that the quaternions are preprocessed so that consecutive ones // form an acute angle A in [0,pi/2]. Other preprocessing can help with // performance. See the function comments in the SLERP class. namespace gte { template <typename Real> class SLERP { public: // The angle between q0 and q1 is in [0,pi). There are no angle // restrictions and nothing is precomputed. template <int32_t N> inline static Quaternion<Real> Estimate(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1) { static_assert(1 <= N && N <= 16, "Invalid degree."); Real cs = Dot(q0, q1); Real sign; if (cs >= (Real)0) { sign = (Real)1; } else { cs = -cs; sign = (Real)-1; } Real f0, f1; ChebyshevRatio<Real>::template GetEstimate<N>(t, (Real)1 - cs, f0, f1); return q0 * f0 + q1 * (sign * f1); } // The angle between q0 and q1 must be in [0,pi/2]. The suffix R is // for 'Restricted'. The preprocessing code is // Quaternion<Real> q[n]; // assuming initialized // for (i0 = 0, i1 = 1; i1 < n; i0 = i1++) // { // cosA = Dot(q[i0], q[i1]); // if (cosA < 0) // { // q[i1] = -q[i1]; // now Dot(q[i0], q[i]1) >= 0 // } // } template <int32_t N> inline static Quaternion<Real> EstimateR(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1) { static_assert(1 <= N && N <= 16, "Invalid degree."); Real f0, f1; ChebyshevRatio<Real>::template GetEstimate<N>(t, (Real)1 - Dot(q0, q1), f0, f1); return q0 * f0 + q1 * f1; } // The angle between q0 and q1 must be in [0,pi/2]. The suffix R is // for 'Restricted' and the suffix P is for 'Preprocessed'. The // preprocessing code is // Quaternion<Real> q[n]; // assuming initialized // Real cosA[n-1], omcosA[n-1]; // to be precomputed // for (i0 = 0, i1 = 1; i1 < n; i0 = i1++) // { // cs = Dot(q[i0], q[i1]); // if (cosA[i0] < 0) // { // q[i1] = -q[i1]; // cs = -cs; // } // // // for Quaterion<T>::SlerpRP // cosA[i0] = cs; // // // for SLERP<T>::EstimateRP // omcosA[i0] = 1 - cs; // } template <int32_t N> inline static Quaternion<Real> EstimateRP(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1, Real omcosA) { static_assert(1 <= N && N <= 16, "Invalid degree."); Real f0, f1; ChebyshevRatio<Real>::template GetEstimate<N>(t, omcosA, f0, f1); return q0 * f0 + q1 * f1; } // The angle between q0 and q1 is A and must be in [0,pi/2]. // Quaternion qh is slerp(1/2,q0,q1) = (q0+q1)/|q0+q1|, so the angle // between q0 and qh is A/2 and the angle between qh and q1 is A/2. // The preprocessing code is // Quaternion<Real> q[n]; // assuming initialized // Quaternion<Real> qh[n-1]; // to be precomputed // Real omcosAH[n-1]; // to be precomputed // for (i0 = 0, i1 = 1; i1 < n; i0 = i1++) // { // cosA = Dot(q[i0], q[i1]); // if (cosA < 0) // { // q[i1] = -q[i1]; // cosA = -cosA; // } // cosAH = sqrt((1 + cosA)/2); // qh[i0] = (q0 + q1) / (2 * cosAH[i0]); // omcosAH[i0] = 1 - cosAH; // } template <int32_t N> inline static Quaternion<Real> EstimateRPH(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1, Quaternion<Real> const& qh, Real omcosAH) { static_assert(1 <= N && N <= 16, "Invalid degree."); Real f0, f1; Real twoT = t * (Real)2; if (twoT <= (Real)1) { ChebyshevRatio<Real>::template GetEstimate<N>(twoT, omcosAH, f0, f1); return q0 * f0 + qh * f1; } else { ChebyshevRatio<Real>::template GetEstimate<N>(twoT - (Real)1, omcosAH, f0, f1); return qh * f0 + q1 * f1; } } }; }
Unknown