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/DistTriangle3AlignedBox3.h
.h
2,249
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/DistTriangle3CanonicalBox3.h> #include <Mathematics/DistSegment3CanonicalBox3.h> #include <Mathematics/AlignedBox.h> // Compute the distance between a solid triangle and a solid aligned box // 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 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 triangle closest is stored in closest[0] with // barycentric coordinates (b[0],b[1],b[2). 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, Triangle3<T>, AlignedBox3<T>> { public: using TBQuery = DCPQuery<T, Triangle3<T>, CanonicalBox3<T>>; using Result = typename TBQuery::Result; Result operator()(Triangle3<T> const& triangle, AlignedBox3<T> const& box) { Result result{}; // Translate the triangle and box so that the box has center at // the origin. Vector3<T> boxCenter{}; CanonicalBox3<T> cbox{}; box.GetCenteredForm(boxCenter, cbox.extent); Triangle3<T> xfrmTriangle( triangle.v[0] - boxCenter, triangle.v[1] - boxCenter, triangle.v[2] - boxCenter); // The query computes 'result' relative to the box with center // at the origin. TBQuery tbQuery{}; result = tbQuery(xfrmTriangle, 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/IntpBicubic2.h
.h
12,215
396
// 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. Exact interpolation is // achieved by setting catmullRom to 'true', giving you the Catmull-Rom // blending matrix. If a smooth interpolation is desired, set catmullRom to // 'false' to obtain B-spline blending. namespace gte { template <typename Real> class IntpBicubic2 { public: // Construction. IntpBicubic2(int32_t xBound, int32_t yBound, Real xMin, Real xSpacing, Real yMin, Real ySpacing, Real const* F, bool catmullRom) : 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 >= 3 && mYBound >= 3 && 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; if (catmullRom) { mBlend[0][0] = (Real)0; mBlend[0][1] = (Real)-0.5; mBlend[0][2] = (Real)1; mBlend[0][3] = (Real)-0.5; mBlend[1][0] = (Real)1; mBlend[1][1] = (Real)0; mBlend[1][2] = (Real)-2.5; mBlend[1][3] = (Real)1.5; mBlend[2][0] = (Real)0; mBlend[2][1] = (Real)0.5; mBlend[2][2] = (Real)2; mBlend[2][3] = (Real)-1.5; mBlend[3][0] = (Real)0; mBlend[3][1] = (Real)0; mBlend[3][2] = (Real)-0.5; mBlend[3][3] = (Real)0.5; } else { mBlend[0][0] = (Real)1 / (Real)6; mBlend[0][1] = (Real)-3 / (Real)6; mBlend[0][2] = (Real)3 / (Real)6; mBlend[0][3] = (Real)-1 / (Real)6;; mBlend[1][0] = (Real)4 / (Real)6; mBlend[1][1] = (Real)0 / (Real)6; mBlend[1][2] = (Real)-6 / (Real)6; mBlend[1][3] = (Real)3 / (Real)6; mBlend[2][0] = (Real)1 / (Real)6; mBlend[2][1] = (Real)3 / (Real)6; mBlend[2][2] = (Real)3 / (Real)6; mBlend[2][3] = (Real)-3 / (Real)6; mBlend[3][0] = (Real)0 / (Real)6; mBlend[3][1] = (Real)0 / (Real)6; mBlend[3][2] = (Real)0 / (Real)6; mBlend[3][3] = (Real)1 / (Real)6; } } // 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, 4> U; U[0] = (Real)1; U[1] = xIndex - ix; U[2] = U[1] * U[1]; U[3] = U[1] * U[2]; std::array<Real, 4> V; V[0] = (Real)1; V[1] = yIndex - iy; V[2] = V[1] * V[1]; V[3] = V[1] * V[2]; // Compute P = M*U and Q = M*V. std::array<Real, 4> P, Q; for (int32_t row = 0; row < 4; ++row) { P[row] = (Real)0; Q[row] = (Real)0; for (int32_t col = 0; col < 4; ++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 4x4 subimage // containing (x,y). --ix; --iy; Real result = (Real)0; for (int32_t row = 0; row < 4; ++row) { int32_t yClamp = iy + row; if (yClamp < 0) { yClamp = 0; } else if (yClamp > mYBound - 1) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 4; ++col) { int32_t xClamp = ix + col; if (xClamp < 0) { xClamp = 0; } else if (xClamp > mXBound - 1) { 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, 4> U; Real dx, xMult; switch (xOrder) { case 0: dx = xIndex - ix; U[0] = (Real)1; U[1] = dx; U[2] = dx * U[1]; U[3] = dx * U[2]; xMult = (Real)1; break; case 1: dx = xIndex - ix; U[0] = (Real)0; U[1] = (Real)1; U[2] = (Real)2 * dx; U[3] = (Real)3 * dx * dx; xMult = mInvXSpacing; break; case 2: dx = xIndex - ix; U[0] = (Real)0; U[1] = (Real)0; U[2] = (Real)2; U[3] = (Real)6 * dx; xMult = mInvXSpacing * mInvXSpacing; break; case 3: U[0] = (Real)0; U[1] = (Real)0; U[2] = (Real)0; U[3] = (Real)6; xMult = mInvXSpacing * mInvXSpacing * mInvXSpacing; break; default: return (Real)0; } std::array<Real, 4> V; Real dy, yMult; switch (yOrder) { case 0: dy = yIndex - iy; V[0] = (Real)1; V[1] = dy; V[2] = dy * V[1]; V[3] = dy * V[2]; yMult = (Real)1; break; case 1: dy = yIndex - iy; V[0] = (Real)0; V[1] = (Real)1; V[2] = (Real)2 * dy; V[3] = (Real)3 * dy * dy; yMult = mInvYSpacing; break; case 2: dy = yIndex - iy; V[0] = (Real)0; V[1] = (Real)0; V[2] = (Real)2; V[3] = (Real)6 * dy; yMult = mInvYSpacing * mInvYSpacing; break; case 3: V[0] = (Real)0; V[1] = (Real)0; V[2] = (Real)0; V[3] = (Real)6; yMult = mInvYSpacing * mInvYSpacing * mInvYSpacing; break; default: return (Real)0; } // Compute P = M*U and Q = M*V. std::array<Real, 4> P, Q; for (int32_t row = 0; row < 4; ++row) { P[row] = (Real)0; Q[row] = (Real)0; for (int32_t col = 0; col < 4; ++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 4x4 subimage containing (x,y). --ix; --iy; Real result = (Real)0; for (int32_t row = 0; row < 4; ++row) { int32_t yClamp = iy + row; if (yClamp < 0) { yClamp = 0; } else if (yClamp > mYBound - 1) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 4; ++col) { int32_t xClamp = ix + col; if (xClamp < 0) { xClamp = 0; } else if (xClamp > mXBound - 1) { 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, 4>, 4> mBlend; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Minimize1.h
.h
11,766
344
// 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 <cstdint> #include <functional> // Search for a minimum of F(t) on [t0,t1] using successive parabolic // interpolation. The search is recursive based on the polyline associated // with (t,F(t)) at the endpoints and the midpoint of an interval. Let // f0 = F(t0), f1 = F(t1), tm is in (t0,t1) and fm = F(tm). The polyline is // {(t0,f0),(tm,fm),(t1,f1)}. // // If the polyline is V-shaped, the interval [t0,t1] contains a minimum // point. The polyline is fit with a parabola whose vertex tv is in (t0,t1). // Let fv = tv. If {(t0,f0),(tv,fv),(tm,fm)}} is a minimum bracket, the // parabolic interpolation continues in [t0,tm]. If instead // {(tm,fm),(tv,fv),(t1,f1)}} is a minimum bracket, the parabolic // interpolation continues in [tm,t1]. // // If the polyline is not V-shaped, both subintervals [t0,tm] and [tm,t1] // are searched for a minimum. namespace gte { template <typename T> class Minimize1 { public: // Construction. Minimize1(std::function<T(T)> const& F, int32_t maxSubdivisions, int32_t maxBisections, T epsilon = static_cast<T>(1e-08), T tolerance = static_cast<T>(1e-04)) : mFunction(F), mMaxSubdivisions(maxSubdivisions), mMaxBisections(maxBisections), mEpsilon(std::max(epsilon, static_cast<T>(0))), mTolerance(std::max(tolerance, static_cast<T>(0))) { LogAssert( mMaxSubdivisions > 0 && mMaxBisections > 0, "Invalid argument."); SetEpsilon(epsilon); SetTolerance(tolerance); } // Member access. inline void SetEpsilon(T epsilon) { mEpsilon = std::max(epsilon, static_cast<T>(0)); } inline void SetTolerance(T tolerance) { mTolerance = std::max(tolerance, static_cast<T>(0)); } inline T GetEpsilon() const { return mEpsilon; } inline T GetTolerance() const { return mTolerance; } // Search for a minimum of F(t) on the interval [t0,t1] using an // initial guess of (t0+t1)/2. The location of the minimum is tMin // and the value of the minimum is fMin = F(tMin). void GetMinimum(T t0, T t1, T& tMin, T& fMin) { GetMinimum(t0, t1, static_cast<T>(0.5) * (t0 + t1), tMin, fMin); } // Search for a minimum of F(t) on the interval [t0,t1] using an // initial guess of tInitial. The location of the minimum is tMin // and the value of the minimum is fMin = F(tMin). void GetMinimum(T t0, T t1, T tInitial, T& tMin, T& fMin) { LogAssert( t0 <= tInitial && tInitial <= t1, "Invalid initial t value."); // Compute the minimum for the 3 initial points. mTMin = std::numeric_limits<T>::max(); mFMin = std::numeric_limits<T>::max(); T f0 = mFunction(t0); if (f0 < mFMin) { mTMin = t0; mFMin = f0; } T fInitial = mFunction(tInitial); if (fInitial < mFMin) { mTMin = tInitial; mFMin = fInitial; } T f1 = mFunction(t1); if (f1 < mFMin) { mTMin = t1; mFMin = f1; } // Search for the global minimum on [t0,t1] with tInitial chosen // hopefully to start with a minimum bracket. if (((fInitial < f0) && (f1 >= fInitial)) || ((f1 > fInitial) && (f0 >= fInitial))) { // The polyline {(f0,f0), (tInitial,fInitial), (t1,f1)} is V-shaped. GetBracketedMinimum(t0, f0, tInitial, fInitial, t1, f1); } else { // The polyline {(f0,f0), (tInitial,fInitial), (t1,f1)} is not // V-shaped, so continue searching in subintervals // [t0,tInitial] and [tInitial,t1]. Subdivide(t0, f0, tInitial, fInitial, mMaxSubdivisions); Subdivide(tInitial, fInitial, t1, f1, mMaxSubdivisions); } tMin = mTMin; fMin = mFMin; } private: // Search [t0,t1] recursively for a global minimum. void Subdivide(T t0, T f0, T t1, T f1, int32_t subdivisionsRemaining) { if (subdivisionsRemaining-- == 0) { // The maximum number of subdivisions has been reached. return; } // Compute the function at the midpoint of [t0,t1]. T tm = static_cast<T>(0.5) * (t0 + t1); T fm = mFunction(tm); if (fm < mFMin) { mTMin = tm; mFMin = fm; } if (((fm < f0) && (f1 >= fm)) || ((f1 > fm) && (f0 >= fm))) { // The polyline {(f0,f0), (tm,fm), (t1,f1)} is V-shaped. GetBracketedMinimum(t0, f0, tm, fm, t1, f1); } else { // The polyline {(f0,f0), (tm,fm), (t1,f1)} is not V-shaped, // so continue searching in subintervals [t0,tm] and [tm,t1]. Subdivide(t0, f0, tm, fm, subdivisionsRemaining); Subdivide(tm, fm, t1, f1, subdivisionsRemaining); } } // This is called when {f0,f1,f2} brackets a minimum. void GetBracketedMinimum(T t0, T f0, T tm, T fm, T t1, T f1) { T const two = static_cast<T>(2); T const half = static_cast<T>(0.5); for (int32_t i = 0; i < mMaxBisections; ++i) { // Update the minimum location and value. if (fm < mFMin) { mTMin = tm; mFMin = fm; } // Test for convergence. T dt10 = t1 - t0; T dtBound = two * mTolerance * std::fabs(tm) + mEpsilon; if (dt10 <= dtBound) { break; } // Compute the vertex of the interpolating parabola. T dt0m = t0 - tm; T dt1m = t1 - tm; T df0m = f0 - fm; T df1m = f1 - fm; T tmp0 = dt0m * df1m; T tmp1 = dt1m * df0m; T denom = tmp1 - tmp0; if (std::fabs(denom) <= mEpsilon) { return; } // Compute tv and clamp to [t0,t1] to offset floating-point // rounding errors. T tv = tm + half * (dt1m * tmp1 - dt0m * tmp0) / denom; tv = std::max(t0, std::min(tv, t1)); T fv = mFunction(tv); if (fv < mFMin) { mTMin = tv; mFMin = fv; } if (tv < tm) { if (fv < fm) { t1 = tm; f1 = fm; tm = tv; fm = fv; } else { t0 = tv; f0 = fv; } } else if (tv > tm) { if (fv < fm) { t0 = tm; f0 = fm; tm = tv; fm = fv; } else { t1 = tv; f1 = fv; } } else { // The vertex of parabola is located at the middle sample // point. A minimum could occur on either subinterval, but // it is also possible the minimum occurs at the vertex. // In either case, the search is continued by examining a // neighborhood of the vertex. When two choices exist for // a bracket, the one with the smallest function value at // the midpoint is used. T tm0 = half * (t0 + tm); T fm0 = mFunction(tm0); T tm1 = half * (tm + t1); T fm1 = mFunction(tm1); if (fm0 < fm) { if (fm1 < fm) { if (fm0 < fm1) { // {(t0,f0),(tm0,fm0),(tm,fm)} t1 = tm; f1 = fm; tm = tm0; fm = fm0; } else { // {(tm,fm),(tm1,fm1),(t1,f1)} t0 = tm; f0 = fm; tm = tm1; fm = fm1; } } else // fm1 >= fm { // {(t0,f0),(tm0,fm0),(tm,fm)} t1 = tm; f1 = fm; tm = tm0; fm = fm0; } } else if (fm0 > fm) { if (fm1 < fm) { // {(tm,fm),(tm1,fm1),(t1,f1)} t0 = tm; f0 = fm; tm = tm1; fm = fm1; } else // fm1 >= fm { // {(tm0,fm0),(tm,fm),(tm1,fm1)} t0 = tm0; f0 = fm0; t1 = tm1; f1 = fm1; } } else // fm0 = fm { if (fm1 < fm) { // {(tm,fm),(tm1,fm1),(t1,f1)} t0 = tm; f0 = fm; tm = tm1; fm = fm1; } else // fm1 >= fm { // {(tm0,fm0),(tm,fm),(tm1,fm1)} t0 = tm0; f0 = fm0; t1 = tm1; f1 = fm1; } } } } } std::function<T(T)> mFunction; int32_t mMaxSubdivisions; int32_t mMaxBisections; T mTMin, mFMin; T mEpsilon, mTolerance; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Triangle.h
.h
2,088
85
// 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 triangle is represented as an array of three vertices. The dimension // N must be 2 or larger. namespace gte { template <int32_t N, typename Real> class Triangle { public: // Construction and destruction. The default constructor sets // the/ vertices to (0,..,0), (1,0,...,0) and (0,1,0,...,0). Triangle() : v{ Vector<N, Real>::Zero(), Vector<N, Real>::Unit(0), Vector<N, Real>::Unit(1) } { } Triangle(Vector<N, Real> const& v0, Vector<N, Real> const& v1, Vector<N, Real> const& v2) : v{ v0, v1, v2 } { } Triangle(std::array<Vector<N, Real>, 3> const& inV) : v(inV) { } // Public member access. std::array<Vector<N, Real>, 3> v; public: // Comparisons to support sorted containers. bool operator==(Triangle const& triangle) const { return v == triangle.v; } bool operator!=(Triangle const& triangle) const { return v != triangle.v; } bool operator< (Triangle const& triangle) const { return v < triangle.v; } bool operator<=(Triangle const& triangle) const { return v <= triangle.v; } bool operator> (Triangle const& triangle) const { return v > triangle.v; } bool operator>=(Triangle const& triangle) const { return v >= triangle.v; } }; // Template aliases for convenience. template <typename Real> using Triangle2 = Triangle<2, Real>; template <typename Real> using Triangle3 = Triangle<3, Real>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/QuarticRootsQR.h
.h
11,132
286
// 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/CubicRootsQR.h> // 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 quartic polynomial. namespace gte { template <typename Real> class QuarticRootsQR { public: typedef std::array<std::array<Real, 4>, 4> Matrix; // Solve p(x) = c0 + c1 * x + c2 * x^2 + c3 * x^3 + x^4 = 0. uint32_t operator() (uint32_t maxIterations, Real c0, Real c1, Real c2, Real c3, uint32_t& numRoots, std::array<Real, 4>& 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] = (Real)0; A[0][3] = -c0; A[1][0] = (Real)1; A[1][1] = (Real)0; A[1][2] = (Real)0; A[1][3] = -c1; A[2][0] = (Real)0; A[2][1] = (Real)1; A[2][2] = (Real)0; A[2][3] = -c2; A[3][0] = (Real)0; A[3][1] = (Real)0; A[3][2] = (Real)1; A[3][3] = -c3; // 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, 4>& 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[2][2] + A[3][3]; Real det = A[2][2] * A[3][3] - A[2][3] * A[3][2]; 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 tr12 = A[1][1] + A[2][2]; if (tr12 + A[2][1] == tr12) { GetQuadraticRoots(0, 1, A, numRoots, roots); GetQuadraticRoots(2, 3, A, numRoots, roots); return numIterations; } Real tr01 = A[0][0] + A[1][1]; if (tr01 + A[1][0] == tr01) { numRoots = 1; roots[0] = A[0][0]; // TODO: The cubic solver is not designed to process 3x3 // submatrices of an NxN matrix, so the copy of a // submatrix of A to B is a simple workaround for running // the solver. Write general root-finding/ code that // avoids such copying. uint32_t subMaxIterations = maxIterations - numIterations; typename CubicRootsQR<Real>::Matrix B{}; for (int32_t r = 0, rp1 = 1; r < 3; ++r, ++rp1) { for (int32_t c = 0, cp1 = 1; c < 3; ++c, ++cp1) { B[r][c] = A[rp1][cp1]; } } uint32_t numSubroots = 0; std::array<Real, 3> subroots; uint32_t numSubiterations = CubicRootsQR<Real>()(subMaxIterations, B, numSubroots, subroots); for (uint32_t i = 0; i < numSubroots; ++i) { roots[numRoots] = subroots[i]; ++numRoots; } return numIterations + numSubiterations; } Real tr23 = A[2][2] + A[3][3]; if (tr23 + A[3][2] == tr23) { numRoots = 1; roots[0] = A[3][3]; // TODO: The cubic solver is not designed to process 3x3 // submatrices of an NxN matrix, so the copy of a // submatrix of A to B is a simple workaround for running // the solver. Write general root-finding/ code that // avoids such copying. uint32_t subMaxIterations = maxIterations - numIterations; typename CubicRootsQR<Real>::Matrix B; for (int32_t r = 0; r < 3; ++r) { for (int32_t c = 0; c < 3; ++c) { B[r][c] = A[r][c]; } } uint32_t numSubroots = 0; std::array<Real, 3> subroots; uint32_t numSubiterations = CubicRootsQR<Real>()(subMaxIterations, B, numSubroots, subroots); for (uint32_t i = 0; i < numSubroots; ++i) { roots[numRoots] = subroots[i]; ++numRoots; } return numIterations + numSubiterations; } } 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, 3, V, MV, A); ColHouse<3>(0, 3, 0, 2, V, MV, A); std::array<Real, 3> X{ A[1][0], A[2][0], A[3][0] }; std::array<Real, 3> locV = House<3>(X); multV = (Real)-2 / (locV[0] * locV[0] + locV[1] * locV[1] + locV[2] * locV[2]); MV = { multV * locV[0], multV * locV[1], multV * locV[2] }; RowHouse<3>(1, 3, 0, 3, locV, MV, A); ColHouse<3>(0, 3, 1, 3, locV, MV, A); std::array<Real, 2> Y{ A[2][1], A[3][1] }; 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>(2, 3, 0, 3, W, MW, A); ColHouse<2>(0, 3, 2, 3, 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 elements cmin through cmax are used. std::array<Real, 4> 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, 4> 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, 4>& 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/NearestNeighborQuery.h
.h
12,219
349
// 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/Vector.h> #include <vector> // TODO: This is not a KD-tree nearest neighbor query. Instead, it is an // algorithm to get "approximate" nearest neighbors. Replace this by the // actual KD-tree query. // Use a kd-tree for sorting used in a query for finding nearest neighbors of // a point in a space of the specified dimension N. The split order is always // 0,1,2,...,N-1. The number of sites at a leaf node is controlled by // 'maxLeafSize' and the maximum level of the tree is controlled by // 'maxLevels'. The points are of type Vector<N,Real>. The 'Site' is a // structure of information that minimally implements the function // 'Vector<N,Real> GetPosition () const'. The Site template parameter // allows the query to be applied even when it has more local information // than just point location. namespace gte { // Predefined site structs for convenience. template <int32_t N, typename T> struct PositionSite { Vector<N, T> position; PositionSite(Vector<N, T> const& p) : position(p) { } Vector<N, T> GetPosition() const { return position; } }; // Predefined site structs for convenience. template <int32_t N, typename T> struct PositionDirectionSite { Vector<N, T> position; Vector<N, T> direction; PositionDirectionSite(Vector<N, T> const& p, Vector<N, T> const& d) : position(p), direction(d) { } Vector<N, T> GetPosition() const { return position; } }; template <int32_t N, typename Real, typename Site> class NearestNeighborQuery { public: // Supporting data structures. typedef std::pair<Vector<N, Real>, int32_t> SortedPoint; struct Node { Real split; int32_t axis; int32_t numSites; int32_t siteOffset; int32_t left; int32_t right; }; // Construction. NearestNeighborQuery(std::vector<Site> const& sites, int32_t maxLeafSize, int32_t maxLevel) : mMaxLeafSize(maxLeafSize), mMaxLevel(maxLevel), mSortedPoints(sites.size()), mDepth(0), mLargestNodeSize(0) { LogAssert(mMaxLevel > 0 && mMaxLevel <= 32, "Invalid max level."); int32_t const numSites = static_cast<int32_t>(sites.size()); for (int32_t i = 0; i < numSites; ++i) { mSortedPoints[i] = std::make_pair(sites[i].GetPosition(), i); } mNodes.push_back(Node()); Build(numSites, 0, 0, 0); } // Member access. inline int32_t GetMaxLeafSize() const { return mMaxLeafSize; } inline int32_t GetMaxLevel() const { return mMaxLevel; } inline int32_t GetDepth() const { return mDepth; } inline int32_t GetLargestNodeSize() const { return mLargestNodeSize; } int32_t GetNumNodes() const { return static_cast<int32_t>(mNodes.size()); } inline std::vector<Node> const& GetNodes() const { return mNodes; } // Compute up to MaxNeighbors nearest neighbors within the specified // radius of the point. The returned integer is the number of // neighbors found, possibly zero. The neighbors array stores indices // into the array passed to the constructor. template <int32_t MaxNeighbors> int32_t FindNeighbors(Vector<N, Real> const& point, Real radius, std::array<int32_t, MaxNeighbors>& neighbors) const { Real sqrRadius = radius * radius; int32_t numNeighbors = 0; std::array<int32_t, MaxNeighbors + 1> localNeighbors; std::array<Real, MaxNeighbors + 1> neighborSqrLength; for (int32_t i = 0; i <= MaxNeighbors; ++i) { localNeighbors[i] = -1; neighborSqrLength[i] = std::numeric_limits<Real>::max(); } // The kd-tree construction is recursive, simulated here by using // a stack. The maximum depth is limited to 32, because the number // of sites is limited to 2^{32} (the number of 32-bit integer // indices). std::array<int32_t, 32> stack{}; int32_t top = 0; stack[0] = 0; int32_t maxNeighbors = MaxNeighbors; if (maxNeighbors == 1) { while (top >= 0) { Node node = mNodes[stack[top--]]; if (node.siteOffset != -1) { for (int32_t i = 0, j = node.siteOffset; i < node.numSites; ++i, ++j) { auto diff = mSortedPoints[j].first - point; auto sqrLength = Dot(diff, diff); if (sqrLength <= sqrRadius) { // Maintain the nearest neighbors. if (sqrLength <= neighborSqrLength[0]) { localNeighbors[0] = mSortedPoints[j].second; neighborSqrLength[0] = sqrLength; numNeighbors = 1; } } } } if (node.left != -1 && point[node.axis] - radius <= node.split) { stack[++top] = node.left; } if (node.right != -1 && point[node.axis] + radius >= node.split) { #if defined(GTE_USE_MSWINDOWS) #pragma warning(disable : 28020) #endif stack[++top] = node.right; #if defined(GTE_USE_MSWINDOWS) #pragma warning(default : 28020) #endif } } } else { while (top >= 0) { Node node = mNodes[stack[top--]]; if (node.siteOffset != -1) { for (int32_t i = 0, j = node.siteOffset; i < node.numSites; ++i, ++j) { Vector<N, Real> diff = mSortedPoints[j].first - point; Real sqrLength = Dot(diff, diff); if (sqrLength <= sqrRadius) { // Maintain the nearest neighbors. int32_t k; for (k = 0; k < numNeighbors; ++k) { if (sqrLength <= neighborSqrLength[k]) { for (int32_t n = numNeighbors; n > k; --n) { localNeighbors[n] = localNeighbors[static_cast<size_t>(n) - 1]; neighborSqrLength[n] = neighborSqrLength[static_cast<size_t>(n) - 1]; } break; } } if (k < MaxNeighbors) { localNeighbors[k] = mSortedPoints[j].second; neighborSqrLength[k] = sqrLength; } if (numNeighbors < MaxNeighbors) { ++numNeighbors; } } } } if (node.left != -1 && point[node.axis] - radius <= node.split) { stack[++top] = node.left; } if (node.right != -1 && point[node.axis] + radius >= node.split) { #if defined(GTE_USE_MSWINDOWS) #pragma warning(disable : 28020) #endif stack[++top] = node.right; #if defined(GTE_USE_MSWINDOWS) #pragma warning(default : 28020) #endif } } } for (int32_t i = 0; i < numNeighbors; ++i) { neighbors[i] = localNeighbors[i]; } return numNeighbors; } inline std::vector<SortedPoint> const& GetSortedPoints() const { return mSortedPoints; } private: // Populate the node so that it contains the points split along the // coordinate axes. void Build(int32_t numSites, int32_t siteOffset, int32_t nodeIndex, int32_t level) { LogAssert(siteOffset != -1, "Invalid site offset."); LogAssert(nodeIndex != -1, "Invalid node index."); LogAssert(numSites > 0, "Empty point list."); mDepth = std::max(mDepth, level); Node& node = mNodes[nodeIndex]; node.numSites = numSites; if (numSites > mMaxLeafSize && level <= mMaxLevel) { int32_t halfNumSites = numSites / 2; // The point set is too large for a leaf node, so split it at // the median. The O(m log m) sort is not needed; rather, we // locate the median using an order statistic construction // that is expected time O(m). int32_t const axis = level % N; auto sorter = [axis](SortedPoint const& p0, SortedPoint const& p1) { return p0.first[axis] < p1.first[axis]; }; auto begin = mSortedPoints.begin() + siteOffset; auto mid = mSortedPoints.begin() + siteOffset + halfNumSites; auto end = mSortedPoints.begin() + siteOffset + numSites; std::nth_element(begin, mid, end, sorter); // Get the median position. node.split = mSortedPoints[static_cast<size_t>(siteOffset) + static_cast<size_t>(halfNumSites)].first[axis]; node.axis = axis; node.siteOffset = -1; // Apply a divide-and-conquer step. int32_t left = (int32_t)mNodes.size(), right = left + 1; node.left = left; node.right = right; mNodes.push_back(Node()); mNodes.push_back(Node()); int32_t nextLevel = level + 1; Build(halfNumSites, siteOffset, left, nextLevel); Build(numSites - halfNumSites, siteOffset + halfNumSites, right, nextLevel); } else { // The number of points is small enough or we have run out of // depth, so make this node a leaf. node.split = std::numeric_limits<Real>::max(); node.axis = -1; node.siteOffset = siteOffset; node.left = -1; node.right = -1; mLargestNodeSize = std::max(mLargestNodeSize, node.numSites); } } int32_t mMaxLeafSize; int32_t mMaxLevel; std::vector<SortedPoint> mSortedPoints; std::vector<Node> mNodes; int32_t mDepth; int32_t mLargestNodeSize; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RotationEstimate.h
.h
18,770
571
// 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 // Rotation matrices can be constructed using estimates of the coefficients // that involve trigonometric and polynomial terms. See // https://www.geometrictools.com/Documentation/RotationEstimation.pdf // for the length details. #pragma once #include <Mathematics/Matrix.h> #include <array> namespace gte { // Constants for rotc0(t) = sin(t)/t. std::array<std::array<double, 9>, 7> constexpr C_ROTC0_EST_COEFF = { { { // degree 4 +1.00000000000000000e+00, -1.58971650732578684e-01, +5.84121356311684790e-03 }, { // degree 6 +1.00000000000000000e+00, -1.66218398161274539e-01, +8.06129151017077016e-03, -1.50545944866583496e-04 }, { // degree 8 +1.00000000000000000e+00, -1.66651290458553397e-01, +8.31836205080888937e-03, -1.93853969255209339e-04, +2.19921657358978346e-06 }, { // degree 10 +1.00000000000000000e+00, -1.66666320608302304e-01, +8.33284074932796014e-03, -1.98184457544372085e-04, +2.70931602688878442e-06, -2.07033154672609224e-08 }, { // degree 12 +1.00000000000000000e+00, -1.66666661172424985e-01, +8.33332258782319701e-03, -1.98405693280704135e-04, +2.75362742468406608e-06, -2.47308402190765123e-08, +1.36149932075244694e-10 }, { // degree 14 +1.00000000000000000e+00, -1.66666666601880786e-01, +8.33333316679120591e-03, -1.98412553530683797e-04, +2.75567210003238900e-06, -2.50388692626200884e-08, +1.58972932135933544e-10, -6.61111627233688785e-13 }, { // degree 16 +1.00000000000000000e+00, -1.66666666666648478e-01, +8.33333333318112164e-03, -1.98412698077537775e-04, +2.75573162083557394e-06, -2.50519743096581360e-08, +1.60558314470477309e-10, -7.60488921303402553e-13, +2.52255089807125025e-15 } } }; std::array<double, 7> constexpr C_ROTC0_EST_MAX_ERROR = { 6.9656371186750e-03, // degree 4 2.2379506089580e-04, // degree 6 4.8670096434722e-06, // degree 8 7.5654711606532e-08, // degree 10 8.7939172610518e-10, // degree 12 7.9199615615755e-12, // degree 14 6.8001160258291e-16 // degree 16 }; // Constants for rotc1(t) = (1-cos(t))/t^2. std::array<std::array<double, 9>, 7> constexpr C_ROTC1_EST_COEFF = { { { // degree 4 +5.00000000000000000e-01, -4.06593520914583922e-02, +1.06698549928666312e-03 }, { // degree 6 +5.00000000000000000e-01, -4.16202835017619524e-02, +1.36087417563353699e-03, -1.99122437404000405e-05 }, { // degree 8 +5.00000000000000000e-01, -4.16653520191245796e-02, +1.38761160375298095e-03, -2.44138380330618480e-05, +2.28499434819148172e-07 }, { // degree 10 +5.00000000000000000e-01, -4.16666414534321572e-02, +1.38885303988537192e-03, -2.47850001122705350e-05, +2.72207208413898425e-07, -1.77358008600681907e-09 }, { // degree 12 +5.00000000000000000e-01, -4.16666663178411334e-02, +1.38888820709641924e-03, -2.48011431705518285e-05, +2.75439902962340229e-07, -2.06736081122602257e-09, +9.93003618302030503e-12 }, { // degree 14 +5.00000000000000000e-01, -4.16666666664263635e-02, +1.38888888750799658e-03, -2.48015851902670717e-05, +2.75571871163332658e-07, -2.08727380201649381e-09, +1.14076763269827225e-11, -4.28619236995285237e-14 }, { // degree 16 +5.00000000000000000e-01, -4.16666666666571719e-02, +1.38888888885105744e-03, -2.48015872513761947e-05, +2.75573160474227648e-07, -2.08766469798137579e-09, +1.14685460418668139e-11, -4.75415775440997119e-14, +1.40555891469552795e-16 } } }; std::array<double, 7> constexpr C_ROTC1_EST_MAX_ERROR = { 9.2119010150538e-04, // degree 4 2.3251261806301e-05, // degree 6 4.1693160884870e-07, // degree 8 5.5177887536839e-09, // degree 10 5.5865700954172e-11, // degree 12 7.1609385088323e-15, // degree 14 7.2164496600635e-16 // degree 16 }; // Constants for rotc2(t) = (sin(t) - t*cos(t))/t^3. std::array<std::array<double, 9>, 7> constexpr C_ROTC2_EST_COEFF = { { { // degree 4 +3.33333333333333315e-01, -3.24417271573718483e-02, +9.05201583387763454e-04 }, { // degree 6 +3.33333333333333315e-01, -3.32912781805089902e-02, +1.16506615743456146e-03, -1.76083105011587047e-05 }, { // degree 8 +3.33333333333333315e-01, -3.33321218985461534e-02, +1.18929901553194335e-03, -2.16884239911580259e-05, +2.07111898922214621e-07 }, { // degree 10 +3.33333333333333315e-01, -3.33333098285273563e-02, +1.19044276839748377e-03, -2.20303898188601926e-05, +2.47382309397892291e-07, -1.63412179599052932e-09 }, { // degree 12 +3.33333333333333315e-01, -3.33333330053029661e-02, +1.19047554930589209e-03, -2.20454376925152508e-05, +2.50395723787030737e-07, -1.90797721719554658e-09, +9.25661051509749896e-12 }, { // degree 14 +3.33333333333333315e-01, -3.33333333331133561e-02, +1.19047618918715682e-03, -2.20458533943125258e-05, +2.50519837811549507e-07, -1.92670551155064303e-09, +1.06463697865186991e-11, -4.03135292145519115e-14 }, { // degree 16 +3.33333333333333315e-01, -3.33333333333034956e-02, +1.19047619036920628e-03, -2.20458552540489507e-05, +2.50521015434838418e-07, -1.92706504721931338e-09, +1.07026043656398707e-11, -4.46498739610373537e-14, +1.30526089083317312e-16 } } }; std::array<double, 7> constexpr C_ROTC2_EST_MAX_ERROR = { 8.1461508460229e-04, // degree 4 2.1075025784856e-05, // degree 6 3.8414838612888e-07, // degree 8 5.1435967152180e-09, // degree 10 5.2533588590364e-11, // degree 12 7.7715611723761e-15, // degree 14 2.2759572004816e-15 // degree 16 }; // Constants for rotc3(t) = (2*(1-cos(t)) - t*sin(t))/t^4. std::array<std::array<double, 9>, 7> constexpr C_ROTC3_EST_COEFF = { { { // degree 4 +8.33333333333333287e-02, -5.46357009138465424e-03, +1.19638433962248889e-04 }, { // degree 6 +8.33333333333333287e-02, -5.55196372993948303e-03, +1.46646667516630680e-04, -1.82905866698780768e-06 }, { // degree 8 +8.33333333333333287e-02, -5.55546733314307706e-03, +1.48723933698110248e-04, -2.17865651989456709e-06, +1.77408035681006169e-08 }, { // degree 10 +8.33333333333333287e-02, -5.55555406357728914e-03, +1.48807404153008735e-04, -2.20360578108261882e-06, +2.06782449582308932e-08, -1.19178562817913197e-10 }, { // degree 12 +8.33333333333333287e-02, -5.55555555324832757e-03, +1.48809514798423797e-04, -2.20457622072950518e-06, +2.08728631685852690e-08, -1.36888190776165574e-10, +5.99292681875750821e-13 }, { // degree 14 +8.33333333333333287e-02, -5.55555555528319030e-03, +1.48809523101214977e-04, -2.20458493798151629e-06, +2.08765224186559757e-08, -1.37600800115177215e-10, +6.63762129016229865e-13, -2.19044013684859942e-15 }, { // degree 16 +8.33333333333333287e-02, -5.55555555501025672e-03, +1.48809521898935978e-04, -2.20458342827337994e-06, +2.08757075326674457e-08, -1.37379825035843510e-10, +6.32209097599974706e-13, +7.39204014316007136e-17, -6.43236558920699052e-17 } } }; std::array<double, 7> constexpr C_ROTC3_EST_MAX_ERROR = { 8.4612036888886e-05, // degree 4 1.8051973185995e-06, // degree 6 2.8016103950645e-08, // degree 8 3.2675415151395e-10, // degree 10 1.3714029911682e-13, // degree 12 3.2078506517763e-14, // degree 14 4.7774284528401e-14 // degree 16 }; } namespace gte { // Estimate rotc0(t) = sin(t)/t for t in [0,pi]. For example, a degree-6 // estimate is // float t; // in [0,pi] // float result = RotC0Estimate<float, 6>(t); template <typename Real, size_t Degree> inline Real RotC0Estimate(Real t) { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); size_t constexpr select = (Degree - 4) / 2; auto constexpr& coeff = C_ROTC0_EST_COEFF[select]; size_t constexpr last = Degree / 2; Real tsqr = t * t; Real poly = static_cast<Real>(coeff[last]); for (size_t i = 0, index = last - 1; i < last; ++i, --index) { poly = static_cast<Real>(coeff[index]) + poly * tsqr; } return poly; } // Estimate rotc1(t) = (1 - cos(t))/t^2 for t in [0,pi]. For example, // a degree-6 estimate is // float t; // in [0,pi] // float result = RotC1Estimate<float, 6>(t); template <typename Real, size_t Degree> inline Real RotC1Estimate(Real t) { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); size_t constexpr select = (Degree - 4) / 2; auto constexpr& coeff = C_ROTC1_EST_COEFF[select]; size_t constexpr last = Degree / 2; Real tsqr = t * t; Real poly = static_cast<Real>(coeff[last]); for (size_t i = 0, index = last - 1; i < last; ++i, --index) { poly = static_cast<Real>(coeff[index]) + poly * tsqr; } return poly; } // Estimate rotc2(t) = (sin(t) - t*cos(t))/t^3 for t in [0,pi]. For // example, a degree-6 estimate is // float t; // in [0,pi] // float result = RotC2Estimate<float, 6>(t); template <typename Real, size_t Degree> inline Real RotC2Estimate(Real t) { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); size_t constexpr select = (Degree - 4) / 2; auto constexpr& coeff = C_ROTC2_EST_COEFF[select]; size_t constexpr last = Degree / 2; Real tsqr = t * t; Real poly = static_cast<Real>(coeff[last]); for (size_t i = 0, index = last - 1; i < last; ++i, --index) { poly = static_cast<Real>(coeff[index]) + poly * tsqr; } return poly; } // Estimate rotc3(t) = (2*(1-cos(t)) - t*sin(t))/t^4 for t in // [0,pi]. For example, a degree-6 estimate is // float t; // in [0,pi] // float result = RotC3Estimate<float, 6>(t); template <typename Real, size_t Degree> inline Real RotC3Estimate(Real t) { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); size_t constexpr select = (Degree - 4) / 2; auto constexpr& coeff = C_ROTC3_EST_COEFF[select]; size_t constexpr last = Degree / 2; Real tsqr = t * t; Real poly = static_cast<Real>(coeff[last]); for (size_t i = 0, index = last - 1; i < last; ++i, --index) { poly = static_cast<Real>(coeff[index]) + poly * tsqr; } return poly; } template <typename Real, size_t Degree> Real constexpr GetRotC0EstimateMaxError() { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); return static_cast<Real>(C_ROTC0_EST_MAX_ERROR[(Degree - 4) / 2]); } template <typename Real, size_t Degree> Real constexpr GetRotC1EstimateMaxError() { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); return static_cast<Real>(C_ROTC1_EST_MAX_ERROR[(Degree - 4) / 2]); } template <typename Real, size_t Degree> Real constexpr GetRotC2EstimateMaxError() { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); return static_cast<Real>(C_ROTC2_EST_MAX_ERROR[(Degree - 4) / 2]); } template <typename Real, size_t Degree> Real constexpr GetRotC3EstimateMaxError() { static_assert((Degree & 1) == 0 && 4 <= Degree && Degree <= 16, "Invalid degree."); return static_cast<Real>(C_ROTC3_EST_MAX_ERROR[(Degree - 4) / 2]); } // Construct the estimate for the rotation matrix // R = exp(S) = I + rotc0(t) * S + rotc1(t) * S^2 // from a vector (p0,p1,p2) with length t = |(p0,p1,p2)| and // skew-symmetric matrix S = {{0,-p2,p1},{p2,0,-p0},{-p1,p0,0}}. template <typename Real, size_t Degree> void RotationEstimate(Vector<3, Real> const& p, Matrix<3, 3, Real>& R) { Real const zero(0), one(1); Matrix<3, 3, Real> I{ one, zero, zero, zero, one, zero, zero, zero, one }; Matrix<3, 3, Real> S{ zero, -p[2], p[1], p[2], zero, -p[0], -p[1], p[0], zero }; Real p0p0 = p[0] * p[0], p0p1 = p[0] * p[1], p0p2 = p[0] * p[2]; Real p1p1 = p[1] * p[1], p1p2 = p[1] * p[2], p2p2 = p[2] * p[2]; Matrix<3, 3, Real> Ssqr{ -(p1p1 + p2p2), p0p1, p0p2, p0p1, -(p0p0 + p2p2), p1p2, p0p2, p1p2, -(p0p0 + p1p1) }; Real t = Length(p); Real a = RotC0Estimate<Real, Degree>(t); Real b = RotC1Estimate<Real, Degree>(t); R = I + a * S + b * Ssqr; }; template <typename Real, size_t Degree> void RotationDerivativeEstimate(Vector<3, Real> const& p, std::array<Matrix<3, 3, Real>, 3>& Rder) { Real const zero(0), one(1), negOne(-1); std::array<Matrix<3, 3, Real>, 3> skewE = { Matrix<3, 3, Real>{ zero, zero, zero, zero, zero, negOne, zero, one, zero }, Matrix<3, 3, Real>{ zero, zero, one, zero, zero, zero, negOne, zero, zero }, Matrix<3, 3, Real>{ zero, negOne, zero, one, zero, zero, zero, zero, zero } }; Matrix<3, 3, Real> S{ zero, -p[2], p[1], p[2], zero, -p[0], -p[1], p[0], zero }; Real p0p0 = p[0] * p[0], p0p1 = p[0] * p[1], p0p2 = p[0] * p[2]; Real p1p1 = p[1] * p[1], p1p2 = p[1] * p[2], p2p2 = p[2] * p[2]; Matrix<3, 3, Real> Ssqr{ -(p1p1 + p2p2), p0p1, p0p2, p0p1, -(p0p0 + p2p2), p1p2, p0p2, p1p2, -(p0p0 + p1p1) }; Real t = Length(p); Real a = RotC0Estimate<Real, Degree>(t); Real b = RotC1Estimate<Real, Degree>(t); Real c = RotC2Estimate<Real, Degree>(t); Real d = RotC3Estimate<Real, Degree>(t); for (int32_t i = 0; i < 3; ++i) { Rder[i] = a * skewE[i] + b * (S * skewE[i] + skewE[i] * S) - p[i] * (c * S + d * Ssqr); } } template <typename Real, size_t Degree> void RotationAndDerivativeEstimate(Vector<3, Real> const& p, Matrix<3, 3, Real>& R, std::array<Matrix<3, 3, Real>, 3>& Rder) { Real const zero(0), one(1), negOne(-1); Matrix<3, 3, Real> I{ one, zero, zero, zero, one, zero, zero, zero, one }; std::array<Matrix<3, 3, Real>, 3> skewE = { Matrix<3, 3, Real>{ zero, zero, zero, zero, zero, negOne, zero, one, zero }, Matrix<3, 3, Real>{ zero, zero, one, zero, zero, zero, negOne, zero, zero }, Matrix<3, 3, Real>{ zero, negOne, zero, one, zero, zero, zero, zero, zero } }; Matrix<3, 3, Real> S{ zero, -p[2], p[1], p[2], zero, -p[0], -p[1], p[0], zero }; Real p0p0 = p[0] * p[0], p0p1 = p[0] * p[1], p0p2 = p[0] * p[2]; Real p1p1 = p[1] * p[1], p1p2 = p[1] * p[2], p2p2 = p[2] * p[2]; Matrix<3, 3, Real> Ssqr{ -(p1p1 + p2p2), p0p1, p0p2, p0p1, -(p0p0 + p2p2), p1p2, p0p2, p1p2, -(p0p0 + p1p1) }; Real t = Length(p); Real a = RotC0Estimate<Real, Degree>(t); Real b = RotC1Estimate<Real, Degree>(t); Real c = RotC2Estimate<Real, Degree>(t); Real d = RotC3Estimate<Real, Degree>(t); R = I + a * S + b * Ssqr; for (int32_t i = 0; i < 3; ++i) { Rder[i] = a * skewE[i] + b * (S * skewE[i] + skewE[i] * S) - p[i] * (c * S + d * Ssqr); } } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TCBSplineCurve.h
.h
11,299
306
// 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.08.25 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/ParametricCurve.h> // Compute the tension-continuity-bias (TCB) spline for a set of key frames. // The algorithm was invented by Kochanek and Bartels and is described in // https://www.geometrictools.com/Documentation/KBSplines.pdf namespace gte { template <int32_t N, typename T> class TCBSplineCurve : public ParametricCurve<N, T> { public: // The inputs point[], time[], tension[], continuity[] and bias[] must // have the same number of elements n >= 2. If you want the speed to be // continuous for the entire spline, the input lambda[] must have n // elements that are all positive; otherwise lambda[] should have 0 // elements. If you want to specify the outgoing tangent at time[0] // and the incoming tangent at time[n-1], pass nonnull pointers for // those parameters; otherwise, the boundary tangents are computed by // internally duplicating the boundary points, which effectively means // point[-1] = point[0] and point[n] = point[n-1]. TCBSplineCurve( std::vector<Vector<N, T>> const& point, std::vector<T> const& time, std::vector<T> const& tension, std::vector<T> const& continuity, std::vector<T> const& bias, std::vector<T> const& lambda, Vector<N, T> const* firstOutTangent, Vector<N, T> const* lastInTangent) : ParametricCurve<N, T>( (point.size() >= 2 ? static_cast<int32_t>(point.size() - 1) : 0), time.data()), mPoint(point), mTension(tension), mContinuity(continuity), mBias(bias), mLambda(lambda), mInTangent(point.size()), mOutTangent(point.size()), mA(this->GetNumSegments()), mB(this->GetNumSegments()), mC(this->GetNumSegments()), mD(this->GetNumSegments()) { LogAssert( point.size() >= 2 && time.size() == point.size() && tension.size() == point.size() && continuity.size() == point.size() && bias.size() == point.size() && (lambda.size() == 0 || lambda.size() == point.size()), "Invalid size in TCBSpline constructor."); ComputeFirstTangents(firstOutTangent); ComputeInteriorTangents(); ComputeLastTangents(lastInTangent); ComputeCoefficients(); } virtual ~TCBSplineCurve() = default; // Member access. inline size_t GetNumKeyFrames() const { return mPoint.size(); } inline std::vector<Vector<N, T>> const& GetPoints() const { return mPoint; } inline std::vector<T> const& GetTensions() const { return mTension; } inline std::vector<T> const& GetContinuities() const { return mContinuity; } inline std::vector<T> const& GetBiases() const { return mBias; } inline std::vector<T> const& GetLambdas() const { return mLambda; } inline std::vector<Vector<N, T>> const& GetInTangents() const { return mInTangent; } inline std::vector<Vector<N, T>> const& GetOutTangents() const { return mOutTangent; } // Evaluation of the curve. It is required that order <= 3, which // allows computing derivatives through order 3. If you want only the // position, pass in order of 0. If you want the position and first // derivative, pass in order of 1, and so on. The output array 'jet' // must have enough storage to support the specified order. The values // are ordered as: position, first derivative, second derivative, and // so on. virtual void Evaluate(T t, uint32_t order, Vector<N, T>* jet) const override { size_t key = 0; T u = static_cast<T>(0); GetKeyInfo(t, key, u); // Compute the position. jet[0] = mA[key] + u * (mB[key] + u * (mC[key] + u * mD[key])); if (order >= 1) { // Compute the first-order derivative. T delta = this->mTime[key + 1] - this->mTime[key]; jet[1] = mB[key] + u * (static_cast<T>(2) * mC[key] + (static_cast<T>(3) * u) * mD[key]); jet[1] /= delta; if (order >= 2) { // Compute the second-order derivative. T deltaSqr = delta * delta; jet[2] = static_cast<T>(2) * mC[key] + (static_cast<T>(6) * u) * mD[key]; jet[2] /= deltaSqr; if (order == 3) { T deltaCub = deltaSqr * delta; jet[3] = static_cast<T>(6) * mD[key]; jet[3] /= deltaCub; } } } } protected: // Support for construction. void ComputeFirstTangents(Vector<N, T> const* firstOutTangent) { if (firstOutTangent != nullptr) { mOutTangent[0] = *firstOutTangent; } else { T omT = static_cast<T>(1) - mTension[0]; T omC = static_cast<T>(1) - mContinuity[0]; T omB = static_cast<T>(1) - mBias[0]; T twoDelta = static_cast<T>(2) * (this->mTime[1] - this->mTime[0]); T coeff = omT * omC * omB / twoDelta; mOutTangent[0] = coeff * (mPoint[1] - mPoint[0]); } if (mLambda.size() > 0) { mOutTangent[0] *= mLambda[0]; } mInTangent[0] = mOutTangent[0]; } void ComputeLastTangents(Vector<N, T> const* lastInTangent) { size_t const nm1 = mPoint.size() - 1; if (lastInTangent != nullptr) { mInTangent[nm1] = *lastInTangent; } else { size_t const nm2 = nm1 - 1; T omT = static_cast<T>(1) - mTension[nm1]; T omC = static_cast<T>(1) - mContinuity[nm1]; T opB = static_cast<T>(1) + mBias[nm1]; T twoDelta = static_cast<T>(2) * (this->mTime[nm1] - this->mTime[nm2]); T coeff = omT * omC * opB / twoDelta; mInTangent[nm1] = coeff * (mPoint[nm1] - mPoint[nm2]); } if (mLambda.size() > 0) { mInTangent[nm1] *= mLambda[nm1]; } mOutTangent[nm1] = mInTangent[nm1]; } void ComputeInteriorTangents() { size_t const n = mPoint.size(); for (size_t km1 = 0, k = 1, kp1 = 2; kp1 < n; km1 = k, k = kp1++) { Vector<N, T> const& P0 = mPoint[km1]; Vector<N, T> const& P1 = mPoint[k]; Vector<N, T> const& P2 = mPoint[kp1]; Vector<N, T> P1mP0 = P1 - P0; Vector<N, T> P2mP1 = P2 - P1; T omT = static_cast<T>(1) - mTension[k]; T omC = static_cast<T>(1) - mContinuity[k]; T opC = static_cast<T>(1) + mContinuity[k]; T omB = static_cast<T>(1) - mBias[k]; T opB = static_cast<T>(1) + mBias[k]; T twoDelta0 = static_cast<T>(2) * (this->mTime[k] - this->mTime[km1]); T twoDelta1 = static_cast<T>(2) * (this->mTime[kp1] - this->mTime[k]); T inCoeff0 = omT * omC * opB / twoDelta0; T inCoeff1 = omT * opC * omB / twoDelta1; T outCoeff0 = omT * opC * opB / twoDelta0; T outCoeff1 = omT * omC * omB / twoDelta1; mInTangent[k] = inCoeff0 * P1mP0 + inCoeff1 * P2mP1; mOutTangent[k] = outCoeff0 * P1mP0 + outCoeff1 * P2mP1; } if (mLambda.size() > 0) { for (size_t k = 1, kp1 = 2; kp1 < n; k = kp1++) { T inLength = Length(mInTangent[k]); T outLength = Length(mOutTangent[k]); T common = static_cast<T>(2) * mLambda[k] / (inLength + outLength); T inCoeff = outLength * common; T outCoeff = inLength * common; mInTangent[k] *= inCoeff; mOutTangent[k] *= outCoeff; } } } void ComputeCoefficients() { for (size_t k = 0, kp1 = 1; kp1 < mPoint.size(); k = kp1++) { auto const& P0 = mPoint[k]; auto const& P1 = mPoint[kp1]; auto const& TOut0 = mOutTangent[k]; auto const& TIn1 = mInTangent[kp1]; Vector<N, T> P1mP0 = P1 - P0; T delta = this->mTime[kp1] - this->mTime[k]; mA[k] = P0; mB[k] = delta * TOut0; mC[k] = static_cast<T>(3) * P1mP0 - delta * (static_cast<T>(2) * TOut0 + TIn1); mD[k] = static_cast<T>(-2) * P1mP0 + delta * (TOut0 + TIn1); } } // Determine the index i for which time[i] <= t < time[i+1]. The // returned value is u is in [0,1]. void GetKeyInfo(T const& t, size_t& key, T& u) const { auto const* time = this->mTime.data(); if (t <= time[0]) { key = 0; u = static_cast<T>(0); return; } size_t const numSegments = mA.size(); if (t < time[numSegments]) { for (size_t i = 0; i < numSegments; ++i) { if (t < time[i + 1]) { key = i; u = (t - time[i]) / (time[i + 1] - time[i]); return; } } } key = numSegments - 1; u = static_cast<T>(1); } // The constructor inputs. std::vector<Vector<N, T>> mPoint; std::vector<T> mTension, mContinuity, mBias, mLambda; // Tangent vectors derived from the constructor inputs. std::vector<Vector<N, T>> mInTangent; std::vector<Vector<N, T>> mOutTangent; // Polynomial coefficients. The mA[] are the degree 0 coefficients, // the mB[] are the degree 1 coefficients, the mC[] are the degree 2 // coefficients and the mD[] are the degree 3 coefficients. std::vector<Vector<N, T>> mA, mB, mC, mD; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSphere3Frustum3.h
.h
1,061
41
// 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/DistPoint3Frustum3.h> #include <Mathematics/Hypersphere.h> namespace gte { template <typename Real> class TIQuery<Real, Sphere3<Real>, Frustum3<Real>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Sphere3<Real> const& sphere, Frustum3<Real> const& frustum) { Result result{}; DCPQuery<Real, Vector3<Real>, Frustum3<Real>> vfQuery; Real distance = vfQuery(sphere.center, frustum).distance; result.intersect = (distance <= sphere.radius); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprPolynomialSpecial2.h
.h
9,845
273
// 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]} // where p[i] are distinct nonnegative powers provided by the caller. A // least-squares fitting algorithm is used, but the input data is first // mapped to (x,w) in [-1,1]^2 for numerical robustness. namespace gte { template <typename Real> class ApprPolynomialSpecial2 : public ApprQuery<Real, std::array<Real, 2>> { public: // Initialize the model parameters to zero. The degrees must be // nonnegative and strictly increasing. ApprPolynomialSpecial2(std::vector<int32_t> const& degrees) : mDegrees(degrees), mParameters(degrees.size(), (Real)0) { #if !defined(GTE_NO_LOGGER) LogAssert(mDegrees.size() > 0, "The input array must have elements."); int32_t lastDegree = -1; for (auto degree : mDegrees) { LogAssert(degree > lastDegree, "Degrees must be increasing."); lastDegree = degree; } #endif mXDomain[0] = std::numeric_limits<Real>::max(); mXDomain[1] = -mXDomain[0]; mWDomain[0] = std::numeric_limits<Real>::max(); mWDomain[1] = -mWDomain[0]; mScale[0] = (Real)0; mScale[1] = (Real)0; mInvTwoWScale = (Real)0; // Powers of x are computed up to twice the powers when // constructing the fitted polynomial. Powers of x are computed // up to the powers for the evaluation of the fitted polynomial. mXPowers.resize(2 * static_cast<size_t>(mDegrees.back()) + 1); mXPowers[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, 2> const* observations, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numObservations, observations, numIndices, indices)) { // Transform the observations to [-1,1]^2 for numerical // robustness. std::vector<std::array<Real, 2>> 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,w0) is |w(x0) - w0|, where w(x) is the fitted polynomial. virtual Real Error(std::array<Real, 2> const& observation) const override { Real w = Evaluate(observation[0]); Real error = std::fabs(w - observation[1]); return error; } virtual void CopyParameters(ApprQuery<Real, std::array<Real, 2>> const* input) override { auto source = dynamic_cast<ApprPolynomialSpecial2 const*>(input); if (source) { *this = *source; } } // Evaluate the polynomial. The domain interval is provided so you can // interpolate (x in domain) or extrapolate (x not in domain). std::array<Real, 2> const& GetXDomain() const { return mXDomain; } Real Evaluate(Real x) const { // Transform x to x' in [-1,1]. x = (Real)-1 + (Real)2 * mScale[0] * (x - mXDomain[0]); // Compute relevant powers of x. int32_t jmax = mDegrees.back(); for (int32_t j = 1, jm1 = 0; j <= jmax; ++j, ++jm1) { mXPowers[j] = mXPowers[jm1] * x; } Real w = (Real)0; int32_t isup = static_cast<int32_t>(mDegrees.size()); for (int32_t i = 0; i < isup; ++i) { Real xp = mXPowers[mDegrees[i]]; w += mParameters[i] * xp; } // Transform w from [-1,1] back to the original space. w = (w + (Real)1) * mInvTwoWScale + mWDomain[0]; return w; } private: // Transform the (x,w) values to (x',w') in [-1,1]^2. void Transform(std::array<Real, 2> const* observations, size_t numIndices, int32_t const* indices, std::vector<std::array<Real, 2>>& transformed) { int32_t numSamples = static_cast<int32_t>(numIndices); transformed.resize(numSamples); std::array<Real, 2> omin = observations[indices[0]]; std::array<Real, 2> omax = omin; std::array<Real, 2> obs; int32_t s, i; for (s = 1; s < numSamples; ++s) { obs = observations[indices[s]]; for (i = 0; i < 2; ++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]; mWDomain[0] = omin[1]; mWDomain[1] = omax[1]; for (i = 0; i < 2; ++i) { mScale[i] = (Real)1 / (omax[i] - omin[i]); } for (s = 0; s < numSamples; ++s) { obs = observations[indices[s]]; for (i = 0; i < 2; ++i) { transformed[s][i] = (Real)-1 + (Real)2 * mScale[i] * (obs[i] - omin[i]); } } mInvTwoWScale = (Real)0.5 / mScale[1]; } // The least-squares fitting algorithm for the transformed data. bool DoLeastSquares(std::vector<std::array<Real, 2>> & transformed) { // Set up a linear system A*X = B, where X are the polynomial // coefficients. int32_t size = static_cast<int32_t>(mDegrees.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 * mDegrees.back(); int32_t row, col; for (int32_t i = 0; i < numSamples; ++i) { // Compute relevant powers of x. Real x = transformed[i][0]; Real w = transformed[i][1]; for (int32_t j = 1, jm1 = 0; j <= twoMaxXDegree; ++j, ++jm1) { mXPowers[j] = mXPowers[jm1] * x; } for (row = 0; row < size; ++row) { // Update the upper-triangular portion of the symmetric // matrix. for (col = row; col < size; ++col) { A(row, col) += mXPowers[static_cast<size_t>(mDegrees[row]) + static_cast<size_t>(mDegrees[col])]; } // Update the right-hand side of the system. B[row] += mXPowers[mDegrees[row]] * 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> mDegrees; std::vector<Real> mParameters; // Support for evaluation. The coefficients were generated for the // samples mapped to [-1,1]^2. The Evaluate() function must transform // x to x' in [-1,1], compute w' in [-1,1], then transform w' to w. std::array<Real, 2> mXDomain, mWDomain; std::array<Real, 2> mScale; Real mInvTwoWScale; // This array is used by Evaluate() to avoid reallocation of the // 'vector' for each call. The member is mutable because, to the // user, the call to Evaluate does not modify the polynomial. mutable std::vector<Real> mXPowers; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegmentSegment.h
.h
26,227
683
// 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 // Compute the closest points for two segments in nD. // // The segments are P[0] + s[0] * (P[1] - P[0]) for 0 <= s[0] <= 1 and // Q[0] + s[1] * (Q[1] - Q[0]) for 0 <= s[1] <= 1. The D[i] are not required // to be unit length. // // The closest point on segment[i] is stored in closest[i] with parameter[i] // storing s[i]. When there are infinitely many choices for the pair of // closest points, only one of them is returned. // // The algorithm is robust even for nearly parallel segments. Effectively, it // uses a conjugate gradient search for the minimum of the squared distance // function, which avoids the numerical problems introduced by divisions in // the case the minimum is located at an interior point of the domain. See the // document // https://www.geometrictools.com/Documentation/DistanceLine3Line3.pdf // for details. #include <Mathematics/DCPQuery.h> #include <Mathematics/Segment.h> namespace gte { template <int32_t N, typename T> class DCPQuery<T, Segment<N, T>, Segment<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<T, 2> parameter; std::array<Vector<N, T>, 2> closest; }; // These two functions are exact for computing Result::sqrDistance // when T is a rational type. Result operator()(Segment<N, T> const& segment0, Segment<N, T> const& segment1) { return operator()(segment0.p[0], segment0.p[1], segment1.p[0], segment1.p[1]); } Result operator()(Vector<N, T> const& P0, Vector<N, T> const& P1, Vector<N, T> const& Q0, Vector<N, T> const& Q1) { Vector<N, T> P1mP0 = P1 - P0; Vector<N, T> Q1mQ0 = Q1 - Q0; Vector<N, T> P0mQ0 = P0 - Q0; T a = Dot(P1mP0, P1mP0); T b = Dot(P1mP0, Q1mQ0); T c = Dot(Q1mQ0, Q1mQ0); T d = Dot(P1mP0, P0mQ0); T e = Dot(Q1mQ0, P0mQ0); T det = a * c - b * b; T s, t, nd, bmd, bte, ctd, bpe, ate, btd; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); if (det > zero) { bte = b * e; ctd = c * d; if (bte <= ctd) // s <= 0 { s = zero; if (e <= zero) // t <= 0 { // region 6 t = zero; nd = -d; if (nd >= a) { s = one; } else if (nd > zero) { s = nd / a; } // else: s is already zero } else if (e < c) // 0 < t < 1 { // region 5 t = e / c; } else // t >= 1 { // region 4 t = one; bmd = b - d; if (bmd >= a) { s = one; } else if (bmd > zero) { s = bmd / a; } // else: s is already zero } } else // s > 0 { s = bte - ctd; if (s >= det) // s >= 1 { // s = 1 s = one; bpe = b + e; if (bpe <= zero) // t <= 0 { // region 8 t = zero; nd = -d; if (nd <= zero) { s = zero; } else if (nd < a) { s = nd / a; } // else: s is already one } else if (bpe < c) // 0 < t < 1 { // region 1 t = bpe / c; } else // t >= 1 { // region 2 t = one; bmd = b - d; if (bmd <= zero) { s = zero; } else if (bmd < a) { s = bmd / a; } // else: s is already one } } else // 0 < s < 1 { ate = a * e; btd = b * d; if (ate <= btd) // t <= 0 { // region 7 t = zero; nd = -d; if (nd <= zero) { s = zero; } else if (nd >= a) { s = one; } else { s = nd / a; } } else // t > 0 { t = ate - btd; if (t >= det) // t >= 1 { // region 3 t = one; bmd = b - d; if (bmd <= zero) { s = zero; } else if (bmd >= a) { s = one; } else { s = bmd / a; } } else // 0 < t < 1 { // region 0 s /= det; t /= det; } } } } } else { // The segments are parallel. The quadratic factors to // R(s,t) = a*(s-(b/a)*t)^2 + 2*d*(s - (b/a)*t) + f // where a*c = b^2, e = b*d/a, f = |P0-Q0|^2, and b is not // zero. R is constant along lines of the form s-(b/a)*t = k // and its occurs on the line a*s - b*t + d = 0. This line // must intersect both the s-axis and the t-axis because 'a' // and 'b' are not zero. Because of parallelism, the line is // also represented by -b*s + c*t - e = 0. // // The code determines an edge of the domain [0,1]^2 that // intersects the minimum line, or if none of the edges // intersect, it determines the closest corner to the minimum // line. The conditionals are designed to test first for // intersection with the t-axis (s = 0) using // -b*s + c*t - e = 0 and then with the s-axis (t = 0) using // a*s - b*t + d = 0. // When s = 0, solve c*t - e = 0 (t = e/c). if (e <= zero) // t <= 0 { // Now solve a*s - b*t + d = 0 for t = 0 (s = -d/a). t = zero; nd = -d; if (nd <= zero) // s <= 0 { // region 6 s = zero; } else if (nd >= a) // s >= 1 { // region 8 s = one; } else // 0 < s < 1 { // region 7 s = nd / a; } } else if (e >= c) // t >= 1 { // Now solve a*s - b*t + d = 0 for t = 1 (s = (b-d)/a). t = one; bmd = b - d; if (bmd <= zero) // s <= 0 { // region 4 s = zero; } else if (bmd >= a) // s >= 1 { // region 2 s = one; } else // 0 < s < 1 { // region 3 s = bmd / a; } } else // 0 < t < 1 { // The point (0,e/c) is on the line and domain, so we have // one point at which R is a minimum. s = zero; t = e / c; } } Result result{}; result.parameter[0] = s; result.parameter[1] = t; result.closest[0] = P0 + s * P1mP0; result.closest[1] = Q0 + t * Q1mQ0; Vector<N, T> diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } // These two functions are exact for computing Result::sqrDistance // when T is a rational type. However, it is generally more robust // than the operator()(...) functions when T is a floating-point type. Result ComputeRobust(Segment<N, T> const& segment0, Segment<N, T> const& segment1) { return ComputeRobust(segment0.p[0], segment0.p[1], segment1.p[0], segment1.p[1]); } Result ComputeRobust(Vector<N, T> const& P0, Vector<N, T> const& P1, Vector<N, T> const& Q0, Vector<N, T> const& Q1) { Result result{}; // The code allows degenerate line segments; that is, P0 and P1 // can be the same point or Q0 and Q1 can be the same point. The // quadratic function for squared distance between the segment is // R(s,t) = a*s^2 - 2*b*s*t + c*t^2 + 2*d*s - 2*e*t + f // for (s,t) in [0,1]^2 where // a = Dot(P1-P0,P1-P0), b = Dot(P1-P0,Q1-Q0), c = Dot(Q1-Q0,Q1-Q0), // d = Dot(P1-P0,P0-Q0), e = Dot(Q1-Q0,P0-Q0), f = Dot(P0-Q0,P0-Q0) Vector<N, T> P1mP0 = P1 - P0; Vector<N, T> Q1mQ0 = Q1 - Q0; Vector<N, T> P0mQ0 = P0 - Q0; T a = Dot(P1mP0, P1mP0); T b = Dot(P1mP0, Q1mQ0); T c = Dot(Q1mQ0, Q1mQ0); T d = Dot(P1mP0, P0mQ0); T e = Dot(Q1mQ0, P0mQ0); // The derivatives dR/ds(i,j) at the four corners of the domain. T f00 = d; T f10 = f00 + a; T f01 = f00 - b; T f11 = f10 - b; // The derivatives dR/dt(i,j) at the four corners of the domain. T g00 = -e; T g10 = g00 - b; T g01 = g00 + c; T g11 = g10 + c; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); if (a > zero && c > zero) { // Compute the solutions to dR/ds(s0,0) = 0 and // dR/ds(s1,1) = 0. The location of sI on the s-axis is // stored in classifyI (I = 0 or 1). If sI <= 0, classifyI // is -1. If sI >= 1, classifyI is 1. If 0 < sI < 1, // classifyI is 0. This information helps determine where to // search for the minimum point (s,t). The fij values are // dR/ds(i,j) for i and j in {0,1}. std::array<T, 2> sValue { GetClampedRoot(a, f00, f10), GetClampedRoot(a, f01, f11) }; std::array<int32_t, 2> classify{}; for (size_t i = 0; i < 2; ++i) { if (sValue[i] <= zero) { classify[i] = -1; } else if (sValue[i] >= one) { classify[i] = +1; } else { classify[i] = 0; } } if (classify[0] == -1 && classify[1] == -1) { // The minimum must occur on s = 0 for 0 <= t <= 1. result.parameter[0] = zero; result.parameter[1] = GetClampedRoot(c, g00, g01); } else if (classify[0] == +1 && classify[1] == +1) { // The minimum must occur on s = 1 for 0 <= t <= 1. result.parameter[0] = one; result.parameter[1] = GetClampedRoot(c, g10, g11); } else { // The line dR/ds = 0 intersects the domain [0,1]^2 in a // nondegenerate segment. Compute the endpoints of that // segment, end[0] and end[1]. The edge[i] flag tells you // on which domain edge end[i] lives: 0 (s=0), 1 (s=1), // 2 (t=0), 3 (t=1). std::array<int32_t, 2> edge{ 0, 0 }; std::array<std::array<T, 2>, 2> end{}; ComputeIntersection(sValue, classify, b, f00, f10, edge, end); // The directional derivative of R along the segment of // intersection is // H(z) = (end[1][1]-end[1][0]) * // dR/dt((1-z)*end[0] + z*end[1]) // for z in [0,1]. The formula uses the fact that // dR/ds = 0 on the segment. Compute the minimum of // H on [0,1]. ComputeMinimumParameters(edge, end, b, c, e, g00, g10, g01, g11, result.parameter); } } else { if (a > zero) { // The Q-segment is degenerate (Q0 and Q1 are the same // point) and the quadratic is R(s,0) = a*s^2 + 2*d*s + f // and has (half) first derivative F(t) = a*s + d. The // closest P-point is interior to the P-segment when // F(0) < 0 and F(1) > 0. result.parameter[0] = GetClampedRoot(a, f00, f10); result.parameter[1] = zero; } else if (c > zero) { // The P-segment is degenerate (P0 and P1 are the same // point) and the quadratic is R(0,t) = c*t^2 - 2*e*t + f // and has (half) first derivative G(t) = c*t - e. The // closest Q-point is interior to the Q-segment when // G(0) < 0 and G(1) > 0. result.parameter[0] = zero; result.parameter[1] = GetClampedRoot(c, g00, g01); } else { // P-segment and Q-segment are degenerate. result.parameter[0] = zero; result.parameter[1] = zero; } } result.closest[0] = (one - result.parameter[0]) * P0 + result.parameter[0] * P1; result.closest[1] = (one - result.parameter[1]) * Q0 + result.parameter[1] * Q1; Vector<N, T> diff = result.closest[0] - result.closest[1]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); return result; } private: // Compute the root of h(z) = h0 + slope*z and clamp it to the interval // [0,1]. It is required that for h1 = h(1), either (h0 < 0 and h1 > 0) // or (h0 > 0 and h1 < 0). static T GetClampedRoot(T const& slope, T const& h0, T const& h1) { // Theoretically, r is in (0,1). However, when the slope is // nearly zero, then so are h0 and h1. Significant numerical // rounding problems can occur when using floating-point // arithmetic. If the rounding causes r to be outside the // interval, clamp it. It is possible that r is in (0,1) and has // rounding errors, but because h0 and h1 are both nearly zero, // the quadratic is nearly constant on (0,1). Any choice of p // should not cause undesirable accuracy problems for the final // distance computation. // // NOTE: You can use bisection to recompute the root or even use // bisection to compute the root and skip the division. This is // generally slower, which might be a problem for high-performance // applications. T const zero = static_cast<T>(0); T r; if (h0 < zero) { T const one = static_cast<T>(1); if (h1 > zero) { r = -h0 / slope; if (r > one) { r = static_cast<T>(0.5); } // The slope is positive and -h0 is positive, so there is // no need to test for a negative value and clamp it. } else { r = one; } } else { r = zero; } return r; } // Compute the intersection of the line dR/ds = 0 with the domain // [0,1]^2. The direction of the line dR/ds is conjugate to (1,0), // so the algorithm for minimization is effectively the conjugate // gradient algorithm for a quadratic function. static void ComputeIntersection(std::array<T, 2> const& sValue, std::array<int32_t, 2> const& classify, T const& b, T const& f00, T const& f10, std::array<int32_t, 2>& edge, std::array<std::array<T, 2>, 2>& end) { // The divisions are theoretically numbers in [0,1]. Numerical // rounding errors might cause the result to be outside the // interval. When this happens, it must be that both numerator // and denominator are nearly zero. The denominator is nearly // zero when the segments are nearly perpendicular. The // numerator is nearly zero when the P-segment is nearly // degenerate (f00 = a is small). The choice of 0.5 should not // cause significant accuracy problems. // // NOTE: You can use bisection to recompute the root or even use // bisection to compute the root and skip the division. This is // generally slower, which might be a problem for high-performance // applications. T const zero = static_cast<T>(0); T const half = static_cast<T>(0.5); T const one = static_cast<T>(1); if (classify[0] < 0) { edge[0] = 0; end[0][0] = zero; end[0][1] = f00 / b; if (end[0][1] < zero || end[0][1] > one) { end[0][1] = half; } if (classify[1] == 0) { edge[1] = 3; end[1][0] = sValue[1]; end[1][1] = one; } else // classify[1] > 0 { edge[1] = 1; end[1][0] = one; end[1][1] = f10 / b; if (end[1][1] < zero || end[1][1] > one) { end[1][1] = half; } } } else if (classify[0] == 0) { edge[0] = 2; end[0][0] = sValue[0]; end[0][1] = zero; if (classify[1] < 0) { edge[1] = 0; end[1][0] = zero; end[1][1] = f00 / b; if (end[1][1] < zero || end[1][1] > one) { end[1][1] = half; } } else if (classify[1] == 0) { edge[1] = 3; end[1][0] = sValue[1]; end[1][1] = one; } else { edge[1] = 1; end[1][0] = one; end[1][1] = f10 / b; if (end[1][1] < zero || end[1][1] > one) { end[1][1] = half; } } } else // classify[0] > 0 { edge[0] = 1; end[0][0] = one; end[0][1] = f10 / b; if (end[0][1] < zero || end[0][1] > one) { end[0][1] = half; } if (classify[1] == 0) { edge[1] = 3; end[1][0] = sValue[1]; end[1][1] = one; } else { edge[1] = 0; end[1][0] = zero; end[1][1] = f00 / b; if (end[1][1] < zero || end[1][1] > one) { end[1][1] = half; } } } } // Compute the location of the minimum of R on the segment of // intersection for the line dR/ds = 0 and the domain [0,1]^2. static void ComputeMinimumParameters(std::array<int32_t, 2> const& edge, std::array<std::array<T, 2>, 2> const& end, T const& b, T const& c, T const& e, T const& g00, T const& g10, T const& g01, T const& g11, std::array<T, 2>& parameter) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T delta = end[1][1] - end[0][1]; T h0 = delta * (-b * end[0][0] + c * end[0][1] - e); if (h0 >= zero) { if (edge[0] == 0) { parameter[0] = zero; parameter[1] = GetClampedRoot(c, g00, g01); } else if (edge[0] == 1) { parameter[0] = one; parameter[1] = GetClampedRoot(c, g10, g11); } else { parameter[0] = end[0][0]; parameter[1] = end[0][1]; } } else { T h1 = delta * (-b * end[1][0] + c * end[1][1] - e); if (h1 <= zero) { if (edge[1] == 0) { parameter[0] = zero; parameter[1] = GetClampedRoot(c, g00, g01); } else if (edge[1] == 1) { parameter[0] = one; parameter[1] = GetClampedRoot(c, g10, g11); } else { parameter[0] = end[1][0]; parameter[1] = end[1][1]; } } else // h0 < 0 and h1 > 0 { T z = std::min(std::max(h0 / (h0 - h1), zero), one); T omz = one - z; parameter[0] = omz * end[0][0] + z * end[1][0]; parameter[1] = omz * end[0][1] + z * end[1][1]; } } } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPSegmentSegment = DCPQuery<T, Segment<N, T>, Segment<N, T>>; template <typename T> using DCPSegment2Segment2 = DCPSegmentSegment<2, T>; template <typename T> using DCPSegment3Segment3 = DCPSegmentSegment<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TSManifoldMesh.h
.h
11,610
335
// 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/HashCombine.h> #include <Mathematics/TetrahedronKey.h> #include <Mathematics/TriangleKey.h> #include <map> #include <memory> #include <unordered_map> namespace gte { class TSManifoldMesh { public: // Triangle data types. class Triangle; typedef std::unique_ptr<Triangle>(*TCreator)(int32_t, int32_t, int32_t); typedef std::unordered_map<TriangleKey<false>, std::unique_ptr<Triangle>, TriangleKey<false>, TriangleKey<false>> TMap; // Tetrahedron data types. class Tetrahedron; typedef std::unique_ptr<Tetrahedron>(*SCreator)(int32_t, int32_t, int32_t, int32_t); typedef std::unordered_map<TetrahedronKey<true>, std::unique_ptr<Tetrahedron>, TetrahedronKey<true>, TetrahedronKey<true>> SMap; // Triangle object. class Triangle { public: virtual ~Triangle() = default; Triangle(int32_t v0, int32_t v1, int32_t v2) : V{ v0, v1, v2 }, T{ nullptr, nullptr } { } // Vertices of the face. std::array<int32_t, 3> V; // Tetrahedra sharing the face. std::array<Tetrahedron*, 2> T; }; // Tetrahedron object. class Tetrahedron { public: virtual ~Tetrahedron() = default; Tetrahedron(int32_t v0, int32_t v1, int32_t v2, int32_t v3) : V{ v0, v1, v2, v3 }, T{ nullptr, nullptr, nullptr, nullptr }, S{ nullptr, nullptr, nullptr, nullptr } { } // Vertices, listed in an order so that each face vertices in // counterclockwise order when viewed from outside the // tetrahedron. std::array<int32_t, 4> V; // Adjacent faces. T[i] points to the triangle face // opposite V[i]. // T[0] points to face (V[1],V[2],V[3]) // T[1] points to face (V[0],V[3],V[2]) // T[2] points to face (V[0],V[1],V[3]) // T[3] points to face (V[0],V[2],V[1]) std::array<Triangle*, 4> T; // Adjacent tetrahedra. S[i] points to the adjacent tetrahedron // sharing face T[i]. std::array<Tetrahedron*, 4> S; }; // Construction and destruction. virtual ~TSManifoldMesh() = default; TSManifoldMesh(TCreator tCreator = nullptr, SCreator sCreator = nullptr) : mTCreator(tCreator ? tCreator : CreateTriangle), mSCreator(sCreator ? sCreator : CreateTetrahedron), mThrowOnNonmanifoldInsertion(true) { } // Support for a deep copy of the mesh. The mTMap and mSMap objects // have dynamically allocated memory for triangles and tetrahedra. 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. TSManifoldMesh(TSManifoldMesh const& mesh) { *this = mesh; } TSManifoldMesh& operator=(TSManifoldMesh const& mesh) { Clear(); mTCreator = mesh.mTCreator; mSCreator = mesh.mSCreator; mThrowOnNonmanifoldInsertion = mesh.mThrowOnNonmanifoldInsertion; for (auto const& element : mesh.mSMap) { // The typecast avoids warnings about not storing the return // value in a named variable. The return value is discarded. (void)Insert(element.first.V[0], element.first.V[1], element.first.V[2], element.first.V[3]); } return *this; } // Member access. inline TMap const& GetTriangles() const { return mTMap; } inline SMap const& GetTetrahedra() const { return mSMap; } // If the insertion of a tetrahedron fails because the mesh would // become nonmanifold, the default behavior is to throw an exception. // You can disable this behavior and continue gracefully without an // exception. bool ThrowOnNonmanifoldInsertion(bool doException) { std::swap(doException, mThrowOnNonmanifoldInsertion); return doException; // return the previous state } // If <v0,v1,v2,v3> is not in the mesh, a Tetrahedron object is // created and returned; otherwise, <v0,v1,v2,v3> is in the mesh and // nullptr is returned. If the insertion leads to a nonmanifold mesh, // the call fails with a nullptr returned. Tetrahedron* Insert(int32_t v0, int32_t v1, int32_t v2, int32_t v3) { TetrahedronKey<true> skey(v0, v1, v2, v3); if (mSMap.find(skey) != mSMap.end()) { // The tetrahedron already exists. Return a null pointer as // a signal to the caller that the insertion failed. return nullptr; } // Add the new tetrahedron. std::unique_ptr<Tetrahedron> newTetra = mSCreator(v0, v1, v2, v3); Tetrahedron* tetra = newTetra.get(); // Add the faces to the mesh if they do not already exist. for (int32_t i = 0; i < 4; ++i) { auto const& opposite = TetrahedronKey<true>::GetOppositeFace()[i]; TriangleKey<false> tkey(tetra->V[opposite[0]], tetra->V[opposite[1]], tetra->V[opposite[2]]); Triangle* face; auto titer = mTMap.find(tkey); if (titer == mTMap.end()) { // This is the first time the face is encountered. std::unique_ptr<Triangle> newFace = mTCreator(tetra->V[opposite[0]], tetra->V[opposite[1]], tetra->V[opposite[2]]); face = newFace.get(); mTMap[tkey] = std::move(newFace); // Update the face and tetrahedron. face->T[0] = tetra; tetra->T[i] = face; } else { // This is the second time the face is encountered. face = titer->second.get(); LogAssert(face != nullptr, "Unexpected condition."); // Update the face. if (face->T[1]) { if (mThrowOnNonmanifoldInsertion) { LogError("Attempt to create nonmanifold mesh."); } else { return nullptr; } } face->T[1] = tetra; // Update the adjacent tetrahedra. auto adjacent = face->T[0]; LogAssert(adjacent != nullptr, "Unexpected condition."); for (int32_t j = 0; j < 4; ++j) { if (adjacent->T[j] == face) { adjacent->S[j] = tetra; break; } } // Update the tetrahedron. tetra->T[i] = face; tetra->S[i] = adjacent; } } mSMap[skey] = std::move(newTetra); return tetra; } // If <v0,v1,v2,v3> is in the mesh, it is removed and 'true' is // returned; otherwise, <v0,v1,v2,v3> is not in the mesh and 'false' // is returned. bool Remove(int32_t v0, int32_t v1, int32_t v2, int32_t v3) { TetrahedronKey<true> skey(v0, v1, v2, v3); auto siter = mSMap.find(skey); if (siter == mSMap.end()) { // The tetrahedron does not exist. return false; } // Get the tetrahedron. Tetrahedron* tetra = siter->second.get(); // Remove the faces and update adjacent tetrahedra if necessary. for (int32_t i = 0; i < 4; ++i) { // Inform the faces the tetrahedron is being deleted. auto face = tetra->T[i]; LogAssert(face != nullptr, "Unexpected condition."); if (face->T[0] == tetra) { // One-tetrahedron faces always have pointer at index // zero. face->T[0] = face->T[1]; face->T[1] = nullptr; } else if (face->T[1] == tetra) { face->T[1] = nullptr; } else { LogError("Unexpected condition."); } // Remove the face if you have the last reference to it. if (!face->T[0] && !face->T[1]) { TriangleKey<false> tkey(face->V[0], face->V[1], face->V[2]); mTMap.erase(tkey); } // Inform adjacent tetrahedra the tetrahedron is being // deleted. auto adjacent = tetra->S[i]; if (adjacent) { for (int32_t j = 0; j < 4; ++j) { if (adjacent->S[j] == tetra) { adjacent->S[j] = nullptr; break; } } } } mSMap.erase(skey); return true; } // Destroy the triangles and tetrahedra to obtain an empty mesh. virtual void Clear() { mTMap.clear(); mSMap.clear(); } // A manifold mesh is closed if each face is shared twice. bool IsClosed() const { for (auto const& element : mTMap) { Triangle* tri = element.second.get(); if (!tri->T[0] || !tri->T[1]) { return false; } } return true; } protected: // The triangle data and default triangle creation. static std::unique_ptr<Triangle> CreateTriangle(int32_t v0, int32_t v1, int32_t v2) { return std::make_unique<Triangle>(v0, v1, v2); } TCreator mTCreator; TMap mTMap; // The tetrahedron data and default tetrahedron creation. static std::unique_ptr<Tetrahedron> CreateTetrahedron(int32_t v0, int32_t v1, int32_t v2, int32_t v3) { return std::make_unique<Tetrahedron>(v0, v1, v2, v3); } SCreator mSCreator; SMap mSMap; bool mThrowOnNonmanifoldInsertion; // default: true }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Hyperplane.h
.h
5,587
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/Matrix.h> #include <Mathematics/SingularValueDecomposition.h> #include <Mathematics/Vector3.h> // The hyperplane is represented as Dot(U, X - P) = 0 where U is a unit-length // normal vector, P is the hyperplane origin, and X is any point on the // hyperplane. The user must ensure that the normal vector is unit length. The // hyperplane constant is c = Dot(U, P) so that Dot(U, X) = c. If P is not // specified when constructing a hyperplane, it is chosen to be the point on // the plane closest to the origin, P = c * U. // // NOTE: You cannot set 'origin' and 'constant' independently. Use the // constructors instead. // // // Construct from normal N and constant c. // Plane3<T> plane(N, c); // plane.origin = c * N // // // Construct from normal N and origin P. // Plane3<T> plane(N, P); // plane.constant = Dot(N, P) // // Plane3<T> plane{}; // N = (0,0,0), P = (0,0,0), c = 0 [invalid] // plane.normal = (0,0,1); // plane.constant = 3; // // If you consume plane now, the origin and constant are inconsistent // // because P = (0,0,0) but Dot(N,P) = 0 != 3 = c. Instead use // plane = Plane3<T>({ 0, 0, 1 }, 3); namespace gte { template <int32_t N, typename T> class Hyperplane { public: // Construction and destruction. The default constructor sets the // normal to (0,...,0,1), the origin to (0,...,0) and the constant to // zero. Hyperplane() : normal{}, origin(Vector<N, T>::Zero()), constant(static_cast<T>(0)) { normal.MakeUnit(N - 1); } Hyperplane(Vector<N, T> const& inNormal, T const& inConstant) : normal(inNormal), origin(inConstant * inNormal), constant(inConstant) { } Hyperplane(Vector<N, T> const& inNormal, Vector<N, T> const& inOrigin) : normal(inNormal), origin(inOrigin), constant(Dot(inNormal, inOrigin)) { } // U is a unit-length vector in the orthogonal complement of the set // {p[1]-p[0],...,p[n-1]-p[0]} and c = Dot(U,p[0]), where the p[i] are // pointson the hyperplane. Hyperplane(std::array<Vector<N, T>, N> const& p) { ComputeFromPoints<N>(p); } // Public member access. Vector<N, T> normal; Vector<N, T> origin; T constant; public: // Comparisons to support sorted containers. bool operator==(Hyperplane const& hyperplane) const { return normal == hyperplane.normal && origin == hyperplane.origin && constant == hyperplane.constant; } bool operator!=(Hyperplane const& hyperplane) const { return !operator==(hyperplane); } bool operator< (Hyperplane const& hyperplane) const { if (normal < hyperplane.normal) { return true; } if (origin > hyperplane.origin) { return false; } if (origin < hyperplane.origin) { return true; } if (origin > hyperplane.origin) { return false; } return constant < hyperplane.constant; } bool operator<=(Hyperplane const& hyperplane) const { return !hyperplane.operator<(*this); } bool operator> (Hyperplane const& hyperplane) const { return hyperplane.operator<(*this); } bool operator>=(Hyperplane const& hyperplane) const { return !operator<(hyperplane); } private: // For use in the Hyperplane(std::array<*>) constructor when N > 3. template <int32_t Dimension = N> typename std::enable_if<Dimension != 3, void>::type ComputeFromPoints(std::array<Vector<Dimension, T>, Dimension> const& p) { Matrix<Dimension, Dimension - 1, T> edge{}; for (int32_t i0 = 0, i1 = 1; i1 < Dimension; i0 = i1++) { edge.SetCol(i0, p[i1] - p[0]); } // Compute the 1-dimensional orthogonal complement of the edges of // the simplex formed by the points p[]. SingularValueDecomposition<T> svd(Dimension, Dimension - 1, 32); svd.Solve(&edge[0], -1); svd.GetUColumn(Dimension - 1, &normal[0]); constant = Dot(normal, p[0]); origin = constant * normal; } // For use in the Hyperplane(std::array<*>) constructor when N == 3. template <int32_t Dimension = N> typename std::enable_if<Dimension == 3, void>::type ComputeFromPoints(std::array<Vector<Dimension, T>, Dimension> const& p) { Vector<Dimension, T> edge0 = p[1] - p[0]; Vector<Dimension, T> edge1 = p[2] - p[0]; normal = UnitCross(edge0, edge1); constant = Dot(normal, p[0]); origin = constant * normal; } }; // Template alias for convenience. template <typename T> using Plane3 = Hyperplane<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ConvexHull2.h
.h
20,066
570
// 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.03 #pragma once // Compute the convex hull of 2D points using a divide-and-conquer algorithm. // This is an O(N log N) algorithm for N input points. The only way to ensure // a correct result for the input vertices is to use an exact predicate for // computing signs of various expressions. The implementation uses interval // arithmetic and rational arithmetic for the predicate. #include <Mathematics/ArbitraryPrecision.h> #include <Mathematics/SWInterval.h> #include <Mathematics/Line.h> #include <Mathematics/Vector2.h> // Uncomment this to assert when an infinite loop is encountered in // ConvexHull2::GetTangent. //#define GTE_THROW_ON_CONVEXHULL2_INFINITE_LOOP namespace gte { // The Real must be 'float' or 'double'. template <typename Real> class ConvexHull2 { public: // Supporting constants and types for rational arithmetic used in // the exact predicate for sign computations. static int32_t constexpr NumWords = std::is_same<Real, float>::value ? 18 : 132; using Rational = BSNumber<UIntegerFP32<NumWords>>; using Interval = SWInterval<Real>; // The class is a functor to support computing the convex hull of // multiple data sets using the same class object. ConvexHull2() : mEpsilon(static_cast<Real>(0)), mDimension(0), mLine(Vector2<Real>::Zero(), Vector2<Real>::Zero()), mRationalPoints{}, mConverted{}, mNumPoints(0), mNumUniquePoints(0), mPoints(nullptr) { static_assert(std::is_floating_point<Real>::value, "The input type must be 'float' or 'double'."); } // The input is the array of points whose convex hull is required. The // epsilon value is used to determine the intrinsic dimensionality of // the vertices (d = 0, 1, or 2). When epsilon is positive, the // determination is fuzzy: points approximately the same point, // approximately on a line, or planar. The return value is 'true' if // and only if the hull construction is successful. bool operator()(int32_t numPoints, Vector2<Real> const* points, Real epsilon) { mEpsilon = std::max(epsilon, static_cast<Real>(0)); mDimension = 0; mLine.origin = Vector2<Real>::Zero(); mLine.direction = Vector2<Real>::Zero(); mNumPoints = numPoints; mNumUniquePoints = 0; mPoints = points; mMerged.clear(); mHull.clear(); if (mNumPoints < 3) { // ConvexHull2 should be called with at least three points. return false; } IntrinsicsVector2<Real> info(mNumPoints, mPoints, mEpsilon); if (info.dimension == 0) { // mDimension is 0 return false; } if (info.dimension == 1) { // The set is (nearly) collinear. mDimension = 1; mLine = Line2<Real>(info.origin, info.direction[0]); return false; } mDimension = 2; // Allocate storage for any rational points that must be // computed in the exact predicate. mRationalPoints.resize(mNumPoints); mConverted.resize(mNumPoints); std::fill(mConverted.begin(), mConverted.end(), 0u); // Sort the points. mHull.resize(mNumPoints); for (int32_t i = 0; i < mNumPoints; ++i) { mHull[i] = i; } std::sort(mHull.begin(), mHull.end(), [points](int32_t i0, int32_t i1) { if (points[i0][0] < points[i1][0]) { return true; } if (points[i0][0] > points[i1][0]) { return false; } return points[i0][1] < points[i1][1]; } ); // Remove duplicates. auto newEnd = std::unique(mHull.begin(), mHull.end(), [points](int32_t i0, int32_t i1) { return points[i0] == points[i1]; } ); mHull.erase(newEnd, mHull.end()); mNumUniquePoints = static_cast<int32_t>(mHull.size()); // Use a divide-and-conquer algorithm. The merge step computes // the convex hull of two convex polygons. mMerged.resize(mNumUniquePoints); int32_t i0 = 0, i1 = mNumUniquePoints - 1; GetHull(i0, i1); int32_t hullSize = i1 - i0 + 1; mHull.resize(hullSize); 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). inline Real GetEpsilon() const { return mEpsilon; } inline int32_t GetDimension() const { return mDimension; } inline Line2<Real> const& GetLine() const { return mLine; } // Member access. inline int32_t GetNumPoints() const { return mNumPoints; } inline int32_t GetNumUniquePoints() const { return mNumUniquePoints; } inline Vector2<Real> const* GetPoints() const { return mPoints; } // The convex hull is a convex polygon whose vertices are listed in // counterclockwise order. inline std::vector<int32_t> const& GetHull() const { return mHull; } private: // Support for divide-and-conquer. void GetHull(int32_t& i0, int32_t& i1) { int32_t numVertices = i1 - i0 + 1; if (numVertices > 1) { // Compute the middle index of input range. int32_t mid = (i0 + i1) / 2; // Compute the hull of subsets (mid-i0+1 >= i1-mid). int32_t j0 = i0, j1 = mid, j2 = mid + 1, j3 = i1; GetHull(j0, j1); GetHull(j2, j3); // Merge the convex hulls into a single convex hull. Merge(j0, j1, j2, j3, i0, i1); } // else: The convex hull is a single point. } void Merge(int32_t j0, int32_t j1, int32_t j2, int32_t j3, int32_t& i0, int32_t& i1) { // Subhull0 is to the left of subhull1 because of the initial // sorting of the points by x-components. We need to find two // mutually visible points, one on the left subhull and one on // the right subhull. int32_t size0 = j1 - j0 + 1; int32_t size1 = j3 - j2 + 1; int32_t i; Vector2<Real> p; // Find the right-most point of the left subhull. Vector2<Real> pmax0 = mPoints[mHull[j0]]; int32_t imax0 = j0; for (i = j0 + 1; i <= j1; ++i) { p = mPoints[mHull[i]]; if (pmax0 < p) { pmax0 = p; imax0 = i; } } // Find the left-most point of the right subhull. Vector2<Real> pmin1 = mPoints[mHull[j2]]; int32_t imin1 = j2; for (i = j2 + 1; i <= j3; ++i) { p = mPoints[mHull[i]]; if (p < pmin1) { pmin1 = p; imin1 = i; } } // Get the lower tangent to hulls (LL = lower-left, // LR = lower-right). int32_t iLL = imax0, iLR = imin1; GetTangent(j0, j1, j2, j3, iLL, iLR); // Get the upper tangent to hulls (UL = upper-left, // UR = upper-right). int32_t iUL = imax0, iUR = imin1; GetTangent(j2, j3, j0, j1, iUR, iUL); // Construct the counterclockwise-ordered merged-hull vertices. int32_t k; int32_t numMerged = 0; i = iUL; for (k = 0; k < size0; ++k) { mMerged[numMerged++] = mHull[i]; if (i == iLL) { break; } i = (i < j1 ? i + 1 : j0); } LogAssert(k < size0, "Unexpected condition."); i = iLR; for (k = 0; k < size1; ++k) { mMerged[numMerged++] = mHull[i]; if (i == iUR) { break; } i = (i < j3 ? i + 1 : j2); } LogAssert(k < size1, "Unexpected condition."); int32_t next = j0; for (k = 0; k < numMerged; ++k) { mHull[next] = mMerged[k]; ++next; } i0 = j0; i1 = next - 1; } void GetTangent(int32_t j0, int32_t j1, int32_t j2, int32_t j3, int32_t& i0, int32_t& i1) { // In theory the loop terminates in a finite number of steps, // but the upper bound for the loop variable is used to trap // problems caused by floating-point roundoff errors that might // lead to an infinite loop. int32_t size0 = j1 - j0 + 1; int32_t size1 = j3 - j2 + 1; int32_t const imax = size0 + size1; int32_t i, iLm1, iRp1; int32_t L0index, L1index, R0index, R1index; for (i = 0; i < imax; i++) { // Get the endpoints of the potential tangent. L1index = mHull[i0]; R0index = mHull[i1]; // Walk along the left hull to find the point of tangency. if (size0 > 1) { iLm1 = (i0 > j0 ? i0 - 1 : j1); L0index = mHull[iLm1]; auto order = ToLineExtended(R0index, L0index, L1index); if (order == Order::NEGATIVE || order == Order::COLLINEAR_RIGHT) { i0 = iLm1; continue; } } // Walk along right hull to find the point of tangency. if (size1 > 1) { iRp1 = (i1 < j3 ? i1 + 1 : j2); R1index = mHull[iRp1]; auto order = ToLineExtended(L1index, R0index, R1index); if (order == Order::NEGATIVE || order == Order::COLLINEAR_LEFT) { i1 = iRp1; continue; } } // The tangent segment has been found. break; } // Detect an "infinite loop" caused by floating point round-off // errors. #if defined(GTE_THROW_ON_CONVEXHULL2_INFINITE_LOOP) LogAssert(i < imax, "Unexpected condition."); #endif } // Memoized access to the rational representation of the points. Vector2<Rational> const& GetRationalPoint(int32_t index) const { if (mConverted[index] == 0) { mConverted[index] = 1; for (int32_t i = 0; i < 2; ++i) { mRationalPoints[index][i] = mPoints[index][i]; } } return mRationalPoints[index]; } // An extended classification of the relationship of a point to a line // segment. For noncollinear points, the return value is // POSITIVE when <P,Q0,Q1> is a counterclockwise triangle // NEGATIVE when <P,Q0,Q1> is a clockwise triangle // For collinear points, the line direction is Q1-Q0. The return // value is // COLLINEAR_LEFT when the line ordering is <P,Q0,Q1> // COLLINEAR_RIGHT when the line ordering is <Q0,Q1,P> // COLLINEAR_CONTAIN when the line ordering is <Q0,P,Q1> enum class Order { Q0_EQUALS_Q1, P_EQUALS_Q0, P_EQUALS_Q1, POSITIVE, NEGATIVE, COLLINEAR_LEFT, COLLINEAR_RIGHT, COLLINEAR_CONTAIN }; Order ToLineExtended(int32_t pIndex, int32_t q0Index, int32_t q1Index) const { Vector2<Real> const& P = mPoints[pIndex]; Vector2<Real> const& Q0 = mPoints[q0Index]; Vector2<Real> const& Q1 = mPoints[q1Index]; if (Q1[0] == Q0[0] && Q1[1] == Q0[1]) { return Order::Q0_EQUALS_Q1; } if (P[0] == Q0[0] && P[1] == Q0[1]) { return Order::P_EQUALS_Q0; } if (P[0] == Q1[0] && P[1] == Q1[1]) { return Order::P_EQUALS_Q1; } // The theoretical classification relies on computing exactly the // sign of the determinant. Numerical roundoff errors can cause // misclassification. Real const zero(0); Interval ip0(P[0]), ip1(P[1]); Interval iq00(Q0[0]), iq01(Q0[1]), iq10(Q1[0]), iq11(Q1[1]); Interval ix0 = iq10 - iq00, iy0 = iq11 - iq01; Interval ix1 = ip0 - iq00, iy1 = ip1 - iq01; Interval ix0y1 = ix0 * iy1; Interval ix1y0 = ix1 * iy0; Interval iDet = ix0y1 - ix1y0; int32_t sign; Vector2<Rational> rDiff0, rDiff1; Rational rDot; bool rDiff0Computed = false; bool rDiff1Computed = false; bool rDotComputed = false; if (iDet[0] > zero) { sign = +1; } else if (iDet[1] < zero) { sign = -1; } else { // The exact sign of the determinant is not known, so compute // the determinant using rational arithmetic. auto const& rP = GetRationalPoint(pIndex); auto const& rQ0 = GetRationalPoint(q0Index); auto const& rQ1 = GetRationalPoint(q1Index); rDiff0 = rQ1 - rQ0; rDiff1 = rP - rQ0; auto rDet = DotPerp(rDiff0, rDiff1); rDiff0Computed = true; rDiff1Computed = true; sign = rDet.GetSign(); } if (sign > 0) { // The points form a counterclockwise triangle <P,Q0,Q1>. return Order::POSITIVE; } else if (sign < 0) { // The points form a clockwise triangle <P,Q1,Q0>. return Order::NEGATIVE; } else { // The points are collinear. P is on the line through Q0 // and Q1. Interval iDot = ix0 * ix1 + iy0 * iy1; if (iDot[0] > zero) { sign = +1; } else if (iDot[1] < zero) { sign = -1; } else { // The exact sign of the dot product is not known, so // compute the dot product using rational arithmetic. auto const& rP = GetRationalPoint(pIndex); auto const& rQ0 = GetRationalPoint(q0Index); auto const& rQ1 = GetRationalPoint(q1Index); if (!rDiff0Computed) { rDiff0 = rQ1 - rQ0; } if (!rDiff1Computed) { rDiff1 = rP - rQ0; } rDot = Dot(rDiff0, rDiff1); rDotComputed = true; sign = rDot.GetSign(); } if (sign < zero) { // The line ordering is <P,Q0,Q1>. return Order::COLLINEAR_LEFT; } Interval iSqrLength = ix0 * ix0 + iy0 * iy0; Interval iTest = iDot - iSqrLength; if (iTest[0] > zero) { sign = +1; } else if (iTest[1] < zero) { sign = -1; } else { // The exact sign of the test is not known, so // compute the test using rational arithmetic. auto const& rP = GetRationalPoint(pIndex); auto const& rQ0 = GetRationalPoint(q0Index); auto const& rQ1 = GetRationalPoint(q1Index); if (!rDiff0Computed) { rDiff0 = rQ1 - rQ0; } if (!rDiff1Computed) { rDiff1 = rP - rQ0; } if (!rDotComputed) { rDot = Dot(rDiff0, rDiff1); } auto rSqrLength = Dot(rDiff0, rDiff0); auto rTest = rDot - rSqrLength; sign = rTest.GetSign(); } if (sign > 0) { // The line ordering is <Q0,Q1,P>. return Order::COLLINEAR_RIGHT; } // The line ordering is <Q0,P,Q1> with P strictly between // Q0 and Q1. return Order::COLLINEAR_CONTAIN; } } // The epsilon value is used for fuzzy determination of intrinsic // dimensionality. If the dimension is 0 or 1, the constructor returns // early. The caller is responsible for retrieving the dimension and // taking an alternate path should the dimension be smaller than 2. // If the dimension is 0, the caller may as well treat all points[] // as a single point, say, points[0]. If the dimension is 1, the // caller can query for the approximating line and project points[] // onto it for further processing. Real mEpsilon; int32_t mDimension; Line2<Real> mLine; // The array of rational points used for the exact predicate. The // mConverted array is used to store 0 or 1, where initially the // values are 0. The first time mComputePoints[i] is encountered, // mConverted[i] is 0. The floating-point vector is converted to // a rational number, after which mConverted[1] is set to 1 to // avoid converting again if the floating-point vector is // encountered in another predicate computation. mutable std::vector<Vector2<Rational>> mRationalPoints; mutable std::vector<uint32_t> mConverted; int32_t mNumPoints; int32_t mNumUniquePoints; Vector2<Real> const* mPoints; std::vector<int32_t> mMerged, mHull; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrRay2Segment2.h
.h
7,669
213
// 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/IntrIntervals.h> #include <Mathematics/IntrLine2Line2.h> #include <Mathematics/Ray.h> #include <Mathematics/Segment.h> namespace gte { template <typename T> class TIQuery<T, Ray2<T>, Segment2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0) { } // The number is 0 (no intersection), 1 (ray and segment intersect // in a single point), or 2 (ray and segment are collinear and // intersect in a segment). bool intersect; int32_t numIntersections; }; Result operator()(Ray2<T> const& ray, Segment2<T> const& segment) { Result result{}; T const zero = static_cast<T>(0); Vector2<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> line0(ray.origin, ray.direction); Line2<T> line1(segOrigin, segDirection); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the ray and // segment. if (llResult.line0Parameter[0] >= zero && std::fabs(llResult.line1Parameter[0]) <= segExtent) { 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 the right-most point of the segment // relative to the ray direction. Vector2<T> diff = segOrigin - ray.origin; T t = Dot(ray.direction, diff) + segExtent; 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>, Segment2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), rayParameter{ static_cast<T>(0), static_cast<T>(0) }, segmentParameter{ static_cast<T>(0), static_cast<T>(0) }, point{ Vector2<T>::Zero(), Vector2<T>::Zero() } { } // The number is 0 (no intersection), 1 (ray and segment intersect // in a single point), or 2 (ray and segment are collinear and // intersect in a segment). bool intersect; int32_t numIntersections; // If numIntersections is 1, the intersection is // point[0] = ray.origin + rayParameter[0] * ray.direction // = segment.center + segmentParameter[0] * segment.direction // If numIntersections is 2, the endpoints of the segment of // intersection are // point[i] = ray.origin + rayParameter[i] * ray.direction // = segment.center + segmentParameter[i] * segment.direction // with rayParameter[0] <= rayParameter[1] and // segmentParameter[0] <= segmentParameter[1]. std::array<T, 2> rayParameter, segmentParameter; std::array<Vector2<T>, 2> point; }; Result operator()(Ray2<T> const& ray, Segment2<T> const& segment) { Result result{}; T const zero = static_cast<T>(0); Vector2<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); FIQuery<T, Line2<T>, Line2<T>> llQuery{}; Line2<T> line0(ray.origin, ray.direction); Line2<T> line1(segOrigin, segDirection); auto llResult = llQuery(line0, line1); if (llResult.numIntersections == 1) { // Test whether the line-line intersection is on the ray and // segment. if (llResult.line0Parameter[0] >= zero && std::fabs(llResult.line1Parameter[0]) <= segExtent) { result.intersect = true; result.numIntersections = 1; result.rayParameter[0] = llResult.line0Parameter[0]; result.segmentParameter[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 segment.origin = // ray.origin + t*ray.direction. Vector2<T> diff = segOrigin - ray.origin; T t = Dot(ray.direction, diff); // Get the ray interval. std::array<T, 2> interval0 = { zero, std::numeric_limits<T>::max() }; // Compute the location of the segment endpoints relative to // the ray. std::array<T, 2> interval1 = { t - segExtent, t + segExtent }; // Compute the intersection of [0,+infinity) and [tmin,tmax]. 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.rayParameter[i] = iiResult.overlap[i]; result.segmentParameter[i] = iiResult.overlap[i] - t; result.point[i] = ray.origin + result.rayParameter[i] * ray.direction; } } 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/IntrSegment3Ellipsoid3.h
.h
6,128
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/IntrIntervals.h> #include <Mathematics/IntrLine3Ellipsoid3.h> #include <Mathematics/Segment.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. 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 ellipsoid equation to obtain a quadratic equation // Q(t) = a2*t^2 + 2*a1*t + a0 = 0, where a2 = D^T*M*D, // a1 = (P1-P0)^T*M*(P0-C) and a0 = (P0-C)^T*M*(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>, Ellipsoid3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Segment3<T> const& segment, Ellipsoid3<T> const& ellipsoid) { Result result{}; Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); Matrix3x3<T> M{}; ellipsoid.GetM(M); T const zero = static_cast<T>(0); Vector3<T> diff = segOrigin - ellipsoid.center; Vector3<T> matDir = M * segDirection; Vector3<T> matDiff = M * diff; T a0 = Dot(diff, matDiff) - static_cast<T>(1); T a1 = Dot(segDirection, matDiff); T a2 = Dot(segDirection, matDir); T discr = a1 * a1 - a0 * a2; if (discr < zero) { // Q(t) has no real-valued roots. The segment does not // intersect the ellipsoid. result.intersect = false; return result; } // Q(-e) = a2*e^2 - 2*a1*e + a0, Q(e) = a2*e^2 + 2*a1*e + a0 T a2e = a2 * segExtent; T tmp0 = a2e * segExtent + a0; // a2*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 ellipsoid. 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 ellipsoid. // Otherwise, Q(-e) > 0 [and Q(e) > 0]. The minimum of Q(t) // occurs at t = -a1/a2. We know that discr >= 0, so Q(t) has a // root on (-e,e) when -a1/2 is in (-e,e). The combined test for // intersection is (Q(-e) > 0 and |a1| < a3*e). result.intersect = (qm > zero && std::fabs(a1) < a2e); return result; } }; template <typename T> class FIQuery<T, Segment3<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()(Segment3<T> const& segment, Ellipsoid3<T> const& ellipsoid) { Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, ellipsoid, 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, Ellipsoid3<T> const& ellipsoid, Result& result) { FIQuery<T, Line3<T>, Ellipsoid3<T>>::DoQuery( segOrigin, segDirection, ellipsoid, result); if (result.intersect) { // The line containing the segment intersects the ellipsoid; // the t-interval is [t0,t1]. The segment intersects the // ellipsoid 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 ellipsoid. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SymmetricEigensolver.h
.h
34,558
830
// 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> #include <Mathematics/RangeIteration.h> #include <algorithm> #include <cstring> #include <vector> // The SymmetricEigensolver class is an implementation of Algorithm 8.2.3 // (Symmetric 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. Algorithm 8.2.1 (Householder // Tridiagonalization) is used to reduce matrix A to tridiagonal T. // Algorithm 8.2.2 (Implicit Symmetric QR Step with Wilkinson Shift) is // used for the iterative reduction from tridiagonal to diagonal. If A is // the original matrix, D is the diagonal matrix of eigenvalues, and Q is // the orthogonal matrix of eigenvectors, then theoretically Q^T*A*Q = D. // Numerically, we have errors E = Q^T*A*Q - D. Algorithm 8.2.3 mentions // that one expects |E| is approximately u*|A|, where |M| denotes the // Frobenius norm of M and where u is the unit roundoff for the // floating-point arithmetic: 2^{-23} for 'float', which is FLT_EPSILON // = 1.192092896e-7f, and 2^{-52} for'double', which is DBL_EPSILON // = 2.2204460492503131e-16. // // The condition |a(i,i+1)| <= epsilon*(|a(i,i) + a(i+1,i+1)|) used to // determine when the reduction decouples to smaller problems is implemented // as: sum = |a(i,i)| + |a(i+1,i+1)|; sum + |a(i,i+1)| == sum. The idea is // that the superdiagonal term is small relative to its diagonal neighbors, // and so it is effectively zero. The unit tests have shown that this // interpretation of decoupling is effective. // // The authors suggest that once you have the tridiagonal matrix, a practical // implementation will store the diagonal and superdiagonal entries in linear // arrays, ignoring the theoretically zero values not in the 3-band. This is // good for cache coherence. The authors also suggest storing the Householder // vectors in the lower-triangular portion of the matrix to save memory. The // implementation uses both suggestions. // // For matrices with randomly generated values in [0,1], the unit tests // produce the following information for N-by-N matrices. // // N |A| |E| |E|/|A| iterations // ------------------------------------------- // 2 1.2332 5.5511e-17 4.5011e-17 1 // 3 2.0024 1.1818e-15 5.9020e-16 5 // 4 2.8708 9.9287e-16 3.4585e-16 7 // 5 2.9040 2.5958e-15 8.9388e-16 9 // 6 4.0427 2.2434e-15 5.5493e-16 12 // 7 5.0276 3.2456e-15 6.4555e-16 15 // 8 5.4468 6.5626e-15 1.2048e-15 15 // 9 6.1510 4.0317e-15 6.5545e-16 17 // 10 6.7523 4.9334e-15 7.3062e-16 21 // 11 7.1322 7.1347e-15 1.0003e-15 22 // 12 7.8324 5.6106e-15 7.1633e-16 24 // 13 8.1073 5.1366e-15 6.3357e-16 25 // 14 8.6257 8.3496e-15 9.6798e-16 29 // 15 9.2603 6.9526e-15 7.5080e-16 31 // 16 9.9853 6.5807e-15 6.5904e-16 32 // 17 10.5388 8.0931e-15 7.6793e-16 35 // 18 11.2377 1.1149e-14 9.9218e-16 38 // 19 11.7105 1.0711e-14 9.1470e-16 42 // 20 12.2227 1.7723e-14 1.4500e-15 42 // 21 12.7411 1.2515e-14 9.8231e-16 47 // 22 13.4462 1.2645e-14 9.4046e-16 50 // 23 13.9541 1.2899e-14 9.2444e-16 47 // 24 14.3298 1.6337e-14 1.1400e-15 53 // 25 14.8050 1.4760e-14 9.9701e-16 54 // 26 15.3914 1.7076e-14 1.1094e-15 57 // 27 15.8430 1.9714e-14 1.2443e-15 60 // 28 16.4771 1.7148e-14 1.0407e-15 60 // 29 16.9909 1.7309e-14 1.0187e-15 60 // 30 17.4456 2.1453e-14 1.2297e-15 64 // 31 17.9909 2.2069e-14 1.2267e-15 68 // // The eigenvalues and |E|/|A| values were compared to those generated by // Mathematica Version 9.0; Wolfram Research, Inc., Champaign IL, 2012. // The results were all comparable with eigenvalues agreeing to a large // number of decimal places. // // Timing on an Intel (R) Core (TM) i7-3930K CPU @ 3.20 GHZ (in seconds): // // N |E|/|A| iters tridiag QR evecs evec[N] comperr // -------------------------------------------------------------- // 512 4.4149e-15 1017 0.180 0.005 1.151 0.848 2.166 // 1024 6.1691e-15 1990 1.775 0.031 11.894 12.759 21.179 // 2048 8.5108e-15 3849 16.592 0.107 119.744 116.56 212.227 // // where iters is the number of QR steps taken, tridiag is the computation // of the Householder reflection vectors, evecs is the composition of // Householder reflections and Givens rotations to obtain the matrix of // eigenvectors, evec[N] is N calls to get the eigenvectors separately, and // comperr is the computation E = Q^T*A*Q - D. The construction of the full // eigenvector matrix is, of course, quite expensive. If you need only a // small number of eigenvectors, use function GetEigenvector(int32_t,Real*). namespace gte { template <typename Real> class SymmetricEigensolver { public: // The solver processes NxN symmetric matrices, where N > 1 ('size' // 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 tridiagonal matrix to a diagonal matrix. The goal // is to compute NxN orthogonal Q and NxN diagonal D for which // Q^T*A*Q = D. SymmetricEigensolver(int32_t size, uint32_t maxIterations) : mSize(0), mMaxIterations(0), mEigenvectorMatrixType(-1) { if (size > 1 && maxIterations > 0) { size_t szSize = static_cast<size_t>(size); mSize = size; mMaxIterations = maxIterations; mMatrix.resize(szSize * szSize); mDiagonal.resize(szSize); mSuperdiagonal.resize(szSize - 1); mGivens.reserve(static_cast<size_t>(maxIterations) * (szSize - 1)); mPermutation.resize(szSize); mVisited.resize(szSize); mPVector.resize(szSize); mVVector.resize(szSize); mWVector.resize(szSize); } } // A copy of the NxN symmetric input is made internally. The order of // the eigenvalues is specified by sortType: -1 (decreasing), 0 (no // sorting), or +1 (increasing). When sorted, the eigenvectors are // ordered accordingly. The return value is the number of iterations // consumed when convergence occurred, 0xFFFFFFFF when convergence did // not occur, or 0 when N <= 1 was passed to the constructor. uint32_t Solve(Real const* input, int32_t sortType) { mEigenvectorMatrixType = -1; if (mSize > 0) { std::copy(input, input + static_cast<size_t>(mSize) * static_cast<size_t>(mSize), mMatrix.begin()); Tridiagonalize(); mGivens.clear(); for (uint32_t j = 0; j < mMaxIterations; ++j) { int32_t imin = -1, imax = -1; for (int32_t i = mSize - 2; i >= 0; --i) { // When a01 is much smaller than its diagonal // neighbors, it is effectively zero. Real a00 = mDiagonal[i]; Real a01 = mSuperdiagonal[i]; Real a11 = mDiagonal[static_cast<size_t>(i) + 1]; Real sum = std::fabs(a00) + std::fabs(a11); if (sum + std::fabs(a01) != sum) { if (imax == -1) { imax = i; } imin = i; } else { // The superdiagonal term is effectively zero // compared to the neighboring diagonal terms. if (imin >= 0) { break; } } } if (imax == -1) { // The algorithm has converged. ComputePermutation(sortType); return j; } // Process the lower-right-most unreduced tridiagonal // block. DoQRImplicitShift(imin, imax); } return 0xFFFFFFFF; } else { return 0; } } // Get the eigenvalues of the matrix passed to Solve(...). The input // 'eigenvalues' must have N elements. void GetEigenvalues(Real* eigenvalues) const { if (eigenvalues && mSize > 0) { if (mPermutation[0] >= 0) { // Sorting was requested. for (int32_t i = 0; i < mSize; ++i) { int32_t p = mPermutation[i]; eigenvalues[i] = mDiagonal[p]; } } else { // Sorting was not requested. size_t numBytes = mSize * sizeof(Real); std::memcpy(eigenvalues, &mDiagonal[0], numBytes); } } } // Accumulate the Householder reflections and Givens rotations to // produce the orthogonal matrix Q for which Q^T*A*Q = D. The input // 'eigenvectors' must have N*N elements. The array is filled in as // if the eigenvector matrix is stored in row-major order. The i-th // eigenvector is // (eigenvectors[i+size*0], ... eigenvectors[i+size*(size - 1)]) // which is the i-th column of 'eigenvectors' as an NxN matrix stored // in row-major order. void GetEigenvectors(Real* eigenvectors) const { mEigenvectorMatrixType = -1; if (eigenvectors && mSize > 0) { // Start with the identity matrix. std::fill(eigenvectors, eigenvectors + static_cast<size_t>(mSize) * static_cast<size_t>(mSize), (Real)0); for (int32_t d = 0; d < mSize; ++d) { eigenvectors[d + mSize * d] = (Real)1; } // Multiply the Householder reflections using backward // accumulation. int32_t r, c; for (int32_t i = mSize - 3, rmin = i + 1; i >= 0; --i, --rmin) { // Copy the v vector and 2/Dot(v,v) from the matrix. Real const* column = &mMatrix[i]; Real twoinvvdv = column[mSize * (i + 1)]; for (r = 0; r < i + 1; ++r) { mVVector[r] = (Real)0; } mVVector[r] = (Real)1; for (++r; r < mSize; ++r) { mVVector[r] = column[mSize * r]; } // Compute the w vector. for (r = 0; r < mSize; ++r) { mWVector[r] = (Real)0; for (c = rmin; c < mSize; ++c) { mWVector[r] += mVVector[c] * eigenvectors[r + mSize * c]; } mWVector[r] *= twoinvvdv; } // Update the matrix, Q <- Q - v*w^T. for (r = rmin; r < mSize; ++r) { for (c = 0; c < mSize; ++c) { eigenvectors[c + mSize * r] -= mVVector[r] * mWVector[c]; } } } // Multiply the Givens rotations. for (auto const& givens : mGivens) { for (r = 0; r < mSize; ++r) { int32_t j = givens.index + mSize * r; Real& q0 = eigenvectors[j]; Real& q1 = eigenvectors[j + 1]; Real prd0 = givens.cs * q0 - givens.sn * q1; Real prd1 = givens.sn * q0 + givens.cs * q1; q0 = prd0; q1 = prd1; } } // The number of Householder reflections is H = mSize - 2. If // H is even, the product of Householder reflections is a // rotation; otherwise, H is odd and the product is a // reflection. The number of Givens rotations does not // influence the type of the product of Householder // reflections. mEigenvectorMatrixType = 1 - (mSize & 1); if (mPermutation[0] >= 0) { // Sorting was requested. std::fill(mVisited.begin(), mVisited.end(), 0); for (int32_t i = 0; i < mSize; ++i) { if (mVisited[i] == 0 && mPermutation[i] != i) { // The item starts a cycle with 2 or more // elements. int32_t start = i, current = i, j, next; for (j = 0; j < mSize; ++j) { mPVector[j] = eigenvectors[i + mSize * j]; } while ((next = mPermutation[current]) != start) { mEigenvectorMatrixType = 1 - mEigenvectorMatrixType; mVisited[current] = 1; for (j = 0; j < mSize; ++j) { eigenvectors[current + mSize * j] = eigenvectors[next + mSize * j]; } current = next; } mVisited[current] = 1; for (j = 0; j < mSize; ++j) { eigenvectors[current + mSize * j] = mPVector[j]; } } } } } } // The eigenvector matrix is a rotation (return +1) or a reflection // (return 0). If the input 'size' to the constructor is 0 or the // input 'eigenvectors' to GetEigenvectors is null, the returned value // is -1. inline int32_t GetEigenvectorMatrixType() const { return mEigenvectorMatrixType; } // Compute a single eigenvector, which amounts to computing column c // of matrix Q. The reflections and rotations are applied // incrementally. This is useful when you want only a small number of // the eigenvectors. void GetEigenvector(int32_t c, Real* eigenvector) const { if (0 <= c && c < mSize) { // y = H*x, then x and y are swapped for the next H Real* x = eigenvector; Real* y = &mPVector[0]; // Start with the Euclidean basis vector. std::memset(x, 0, mSize * sizeof(Real)); if (mPermutation[0] >= 0) { // Sorting was requested. x[mPermutation[c]] = (Real)1; } else { x[c] = (Real)1; } // Apply the Givens rotations. for (auto const& givens : gte::reverse(mGivens)) { Real& xr = x[givens.index]; Real& xrp1 = x[givens.index + 1]; Real tmp0 = givens.cs * xr + givens.sn * xrp1; Real tmp1 = -givens.sn * xr + givens.cs * xrp1; xr = tmp0; xrp1 = tmp1; } // Apply the Householder reflections. for (int32_t i = mSize - 3; i >= 0; --i) { // Get the Householder vector v. Real const* column = &mMatrix[i]; Real twoinvvdv = column[mSize * (i + 1)]; int32_t r; for (r = 0; r <= i; ++r) { y[r] = x[r]; } // Compute s = Dot(x,v) * 2/v^T*v. // // NOTE: MSVS 2019 16+ generates for Real=double, mSize=6: // warning C6385: Reading invalid data from 'x': the // readable size is '_Old_3`mSize*sizeof(Real)' bytes, // but '16' bytes may be read. // This appears to be incorrect. At this point in the // code, r = i + 1. On i-loop entry, r = mSize-2. On // i-loop exit, r = 1. This keeps r in the valid range // for x[]. #if defined(GTE_USE_MSWINDOWS) #pragma warning(disable : 6385) #endif Real s = x[r]; // r = i+1, v[i+1] = 1 // Note that on i-loop entry, r = mSize-2 in which // case r+1 = mSize-1. This keeps index j in the valid // range for x[]. for (int32_t j = r + 1; j < mSize; ++j) { s += x[j] * column[mSize * j]; } s *= twoinvvdv; y[r] = x[r] - s; // v[i+1] = 1 // Compute the remaining components of y. for (++r; r < mSize; ++r) { y[r] = x[r] - s * column[mSize * r]; } std::swap(x, y); #if defined(GTE_USE_MSWINDOWS) #pragma warning(default : 6385) #endif } // The final product is stored in x. if (x != eigenvector) { size_t numBytes = mSize * sizeof(Real); std::memcpy(eigenvector, x, numBytes); } } } Real GetEigenvalue(int32_t c) const { if (mSize > 0) { if (mPermutation[0] >= 0) { // Sorting was requested. return mDiagonal[mPermutation[c]]; } else { // Sorting was not requested. return mDiagonal[c]; } } else { return std::numeric_limits<Real>::max(); } } private: // Tridiagonalize using Householder reflections. On input, mMatrix is // a copy of the input matrix. On output, the upper-triangular part // of mMatrix including the diagonal stores the tridiagonalization. // The lower-triangular part contains 2/Dot(v,v) that are used in // computing eigenvectors and the part below the subdiagonal stores // the essential parts of the Householder vectors v (the elements of // v after the leading 1-valued component). void Tridiagonalize() { int32_t r, c; for (int32_t i = 0, ip1 = 1; i < mSize - 2; ++i, ++ip1) { // Compute the Householder vector. Read the initial vector // from the row of the matrix. Real length = (Real)0; for (r = 0; r < ip1; ++r) { mVVector[r] = (Real)0; } for (r = ip1; r < mSize; ++r) { Real vr = mMatrix[r + static_cast<size_t>(mSize) * i]; mVVector[r] = vr; length += vr * vr; } Real vdv = (Real)1; length = std::sqrt(length); if (length > (Real)0) { Real& v1 = mVVector[ip1]; Real sgn = (v1 >= (Real)0 ? (Real)1 : (Real)-1); Real invDenom = ((Real)1) / (v1 + sgn * length); v1 = (Real)1; for (r = ip1 + 1; r < mSize; ++r) { Real& vr = mVVector[r]; vr *= invDenom; vdv += vr * vr; } } // Compute the rank-1 offsets v*w^T and w*v^T. Real invvdv = (Real)1 / vdv; Real twoinvvdv = invvdv * (Real)2; Real pdvtvdv = (Real)0; for (r = i; r < mSize; ++r) { mPVector[r] = (Real)0; for (c = i; c < r; ++c) { mPVector[r] += mMatrix[r + static_cast<size_t>(mSize) * c] * mVVector[c]; } for (/**/; c < mSize; ++c) { mPVector[r] += mMatrix[c + static_cast<size_t>(mSize) * r] * mVVector[c]; } mPVector[r] *= twoinvvdv; pdvtvdv += mPVector[r] * mVVector[r]; } pdvtvdv *= invvdv; for (r = i; r < mSize; ++r) { mWVector[r] = mPVector[r] - pdvtvdv * mVVector[r]; } // Update the input matrix. for (r = i; r < mSize; ++r) { Real vr = mVVector[r]; Real wr = mWVector[r]; Real offset = vr * wr * (Real)2; mMatrix[r + static_cast<size_t>(mSize) * r] -= offset; for (c = r + 1; c < mSize; ++c) { offset = vr * mWVector[c] + wr * mVVector[c]; mMatrix[c + static_cast<size_t>(mSize) * r] -= offset; } } // Copy the vector to column i of the matrix. The 0-valued // components at indices 0 through i are not stored. The // 1-valued component at index i+1 is also not stored; // instead, the quantity 2/Dot(v,v) is stored for use in // eigenvector construction. That construction must take // into account the implied components that are not stored. mMatrix[i + static_cast<size_t>(mSize) * ip1] = twoinvvdv; for (r = ip1 + 1; r < mSize; ++r) { mMatrix[i + static_cast<size_t>(mSize) * r] = mVVector[r]; } } // Copy the diagonal and subdiagonal entries for cache coherence // in the QR iterations. int32_t k, ksup = mSize - 1, index = 0, delta = mSize + 1; for (k = 0; k < ksup; ++k, index += delta) { mDiagonal[k] = mMatrix[index]; mSuperdiagonal[k] = mMatrix[static_cast<size_t>(index) + 1]; } mDiagonal[k] = mMatrix[index]; } // A helper for generating Givens rotation sine and cosine robustly. void GetSinCos(Real x, Real y, Real& cs, Real& sn) { // Solves sn*x + cs*y = 0 robustly. Real tau; if (y != (Real)0) { if (std::fabs(y) > std::fabs(x)) { tau = -x / y; sn = (Real)1 / std::sqrt((Real)1 + tau * tau); cs = sn * tau; } else { tau = -y / x; cs = (Real)1 / std::sqrt((Real)1 + tau * tau); sn = cs * tau; } } else { cs = (Real)1; sn = (Real)0; } } // The QR step with implicit shift. Generally, the initial T is // unreduced tridiagonal (all subdiagonal entries are nonzero). If a // QR step causes a superdiagonal entry to become zero, the matrix // decouples into a block diagonal matrix with two tridiagonal blocks. // These blocks can be reduced independently of each other, which // allows for parallelization of the algorithm. The inputs imin and // imax identify the subblock of T to be processed. That block has // upper-left element T(imin,imin) and lower-right element // T(imax,imax). void DoQRImplicitShift(int32_t imin, int32_t imax) { // The implicit shift. Compute the eigenvalue u of the // lower-right 2x2 block that is closer to a11. Real a00 = mDiagonal[imax]; Real a01 = mSuperdiagonal[imax]; Real a11 = mDiagonal[static_cast<size_t>(imax) + 1]; Real dif = (a00 - a11) * (Real)0.5; Real sgn = (dif >= (Real)0 ? (Real)1 : (Real)-1); Real a01sqr = a01 * a01; Real u = a11 - a01sqr / (dif + sgn * std::sqrt(dif * dif + a01sqr)); Real x = mDiagonal[imin] - u; Real y = mSuperdiagonal[imin]; Real a12, a22, a23, tmp11, tmp12, tmp21, tmp22, cs, sn; Real a02 = (Real)0; int32_t i0 = imin - 1, i1 = imin, i2 = imin + 1; for (/**/; i1 <= imax; ++i0, ++i1, ++i2) { // Compute the Givens rotation and save it for use in // computing the eigenvectors. GetSinCos(x, y, cs, sn); mGivens.push_back(GivensRotation(i1, cs, sn)); // Update the tridiagonal matrix. This amounts to updating a // 4x4 subblock, // b00 b01 b02 b03 // b01 b11 b12 b13 // b02 b12 b22 b23 // b03 b13 b23 b33 // The four corners (b00, b03, b33) do not change values. The // The interior block {{b11,b12},{b12,b22}} is updated on each // pass. For the first pass, the b0c values are out of range, // so only the values (b13, b23) change. For the last pass, // the br3 values are out of range, so only the values // (b01, b02) change. For passes between first and last, the // values (b01, b02, b13, b23) change. if (i1 > imin) { mSuperdiagonal[i0] = cs * mSuperdiagonal[i0] - sn * a02; } a11 = mDiagonal[i1]; a12 = mSuperdiagonal[i1]; a22 = mDiagonal[i2]; tmp11 = cs * a11 - sn * a12; tmp12 = cs * a12 - sn * a22; tmp21 = sn * a11 + cs * a12; tmp22 = sn * a12 + cs * a22; mDiagonal[i1] = cs * tmp11 - sn * tmp12; mSuperdiagonal[i1] = sn * tmp11 + cs * tmp12; mDiagonal[i2] = sn * tmp21 + cs * tmp22; if (i1 < imax) { a23 = mSuperdiagonal[i2]; a02 = -sn * a23; mSuperdiagonal[i2] = cs * a23; // Update the parameters for the next Givens rotation. x = mSuperdiagonal[i1]; y = a02; } } } // Sort the eigenvalues and compute the corresponding permutation of // the indices of the array storing the eigenvalues. The permutation // is used for reordering the eigenvalues and eigenvectors in the // calls to GetEigenvalues(...) and GetEigenvectors(...). void ComputePermutation(int32_t sortType) { // The number of Householder reflections is H = mSize - 2. If H // is even, the product of Householder reflections is a rotation; // otherwise, H is odd and the product is a reflection. The // number of Givens rotations does not influence the type of the // product of Householder reflections. mEigenvectorMatrixType = 1 - (mSize & 1); if (sortType == 0) { // Set a flag for GetEigenvalues() and GetEigenvectors() to // know that sorted output was not requested. mPermutation[0] = -1; return; } // Compute the permutation induced by sorting. Initially, we // start with the identity permutation I = (0,1,...,N-1). struct SortItem { SortItem() : eigenvalue((Real)0), index(0) { } Real eigenvalue; int32_t index; }; std::vector<SortItem> items(mSize); int32_t i; for (i = 0; i < mSize; ++i) { items[i].eigenvalue = mDiagonal[i]; items[i].index = i; } if (sortType > 0) { std::sort(items.begin(), items.end(), [](SortItem const& item0, SortItem const& item1) { return item0.eigenvalue < item1.eigenvalue; } ); } else { std::sort(items.begin(), items.end(), [](SortItem const& item0, SortItem const& item1) { return item0.eigenvalue > item1.eigenvalue; } ); } i = 0; for (auto const& item : items) { mPermutation[i++] = item.index; } // GetEigenvectors() has nontrivial code for computing the // orthogonal Q from the reflections and rotations. To avoid // complicating the code further when sorting is requested, Q is // computed as in the unsorted case. We then need to swap columns // of Q to be consistent with the sorting of the eigenvalues. To // minimize copying due to column swaps, we use permutation P. // The minimum number of transpositions to obtain P from I is N // minus the number of cycles of P. Each cycle is reordered with // a minimum number of transpositions; that is, the eigenitems are // cyclically swapped, leading to a minimum amount of copying. // For/ example, if there is a cycle i0 -> i1 -> i2 -> i3, then // the copying is // save = eigenitem[i0]; // eigenitem[i1] = eigenitem[i2]; // eigenitem[i2] = eigenitem[i3]; // eigenitem[i3] = save; } // The number N of rows and columns of the matrices to be processed. int32_t mSize; // The maximum number of iterations for reducing the tridiagonal // matrix to a diagonal matrix. uint32_t mMaxIterations; // The internal copy of a matrix passed to the solver. See the // comments about function Tridiagonalize() about what is stored in // the matrix. std::vector<Real> mMatrix; // NxN elements // After the initial tridiagonalization by Householder reflections, we // no longer need the full mMatrix. Copy the diagonal and // superdiagonal entries to linear arrays in order to be cache // friendly. std::vector<Real> mDiagonal; // N elements std::vector<Real> mSuperdiagonal; // N-1 elements // The Givens rotations used to reduce the initial tridiagonal matrix // to a diagonal matrix. A rotation is the identity with the // following replacement entries: R(index,index) = cs, // R(index,index+1) = sn, R(index+1,index) = -sn and // R(index+1,index+1) = cs. If N is the matrix size and K is the // maximum number of iterations, the maximum number of Givens // rotations is K*(N-1). The maximum amount of memory is allocated // to store these. struct GivensRotation { // No default initialization for fast creation of std::vector // of objects of this type. GivensRotation() = default; GivensRotation(int32_t inIndex, Real inCs, Real inSn) : index(inIndex), cs(inCs), sn(inSn) { } int32_t index; Real cs, sn; }; std::vector<GivensRotation> mGivens; // K*(N-1) elements // When sorting is requested, the permutation associated with the sort // is stored in mPermutation. When sorting is not requested, // mPermutation[0] is set to -1. mVisited is used for finding cycles // in the permutation. mEigenvectorMatrixType is +1 if GetEigenvectors // returns a rotation matrix, 0 if GetEigenvectors returns a // reflection matrix or -1 if an input to the constructor or to // GetEigenvectors is invalid. std::vector<int32_t> mPermutation; // N elements mutable std::vector<int32_t> mVisited; // N elements mutable int32_t mEigenvectorMatrixType; // Temporary storage to compute Householder reflections and to // support sorting of eigenvectors. mutable std::vector<Real> mPVector; // N elements mutable std::vector<Real> mVVector; // N elements mutable std::vector<Real> mWVector; // N elements }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/UniqueVerticesSimplices.h
.h
15,793
372
// 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 // UniqueVerticesSimplices allows mesh generation and elimination of duplicate // and/or unused vertices. The vertices have type VertexType, which must have // a less-than comparison predicate because it is used as the key type in // std::map. The IndexType can be any signed or unsigned integer type, not // including 1-byte types or bool. The mesh can be in any dimension D >= 2. In // 2 dimensions, the mesh is a collection of edges. In 3 dimensions, the mesh // is a collection of triangles. Generally, the mesh is a collection of // D-dimensional simplices. The following operations are supported, either for // a mesh topology consisting of indices or of arrays, each array representing // a simplex. // // 1. Generate an indexed simplex representation from an array of simplices, // each simplex represented by D contiguous vertices. Presumably, the // simplices share vertices. The output is an array of unique simplices // (a vertex pool) and an array of D-element arrays of indices into the // pool, each such array representing a simplex. // // 2. Remove duplicate vertices from a vertex pool used by an indexed // simplex representation. A new vertex pool of unique vertices is // generated and the indexed simplices are modified to be indices into // this vertex pool. // // 3. Remove unused vertices from a vertex pool used by an indexed simplex // representation. A new vertex pool of unique vertices is generated and // the indexed simplices are modified to be indices into the new vertex // pool. // // 4. Remove duplicate and unused vertices from a vertex pool, a combination // of the operations in #2 and #3. // // In the Geometric Tools distribution, the class is used for polygon Boolean // operations (D = 2) and for compactifying triangle meshes (D = 3). #include <Mathematics/Logger.h> #include <array> #include <map> #include <set> #include <type_traits> #include <vector> namespace gte { template <typename VertexType, typename IndexType, size_t Dimension> class UniqueVerticesSimplices { public: UniqueVerticesSimplices() { // The index type must be an integral type that does not include // bool. MSVS 2019 16.7.3 does not trigger this static assertion // when IndexType is bool. Instead, it complains about using // .data() for the std::vector<bool> objects and about comparing // bool values to 0 in the LogAssert statements, after which the // compilation terminates. static_assert( std::is_integral<IndexType>::value && !std::is_same<IndexType, bool>::value, "Invalid index type."); } // See #1 in the comments at the beginning of this file. The // preconditions are // 1. inVertices.size() is a positive multiple of D // The postconditions are // 1. outVertices has unique vertices // 2. outIndices.size() = inVertices.size() // 3. 0 <= outIndices[i] < outVertices.size() void GenerateIndexedSimplices( std::vector<VertexType> const& inVertices, std::vector<VertexType>& outVertices, std::vector<IndexType>& outIndices) { LogAssert( inVertices.size() > 0 && inVertices.size() % Dimension == 0, "Invalid number of vertices."); outIndices.resize(inVertices.size()); RemoveDuplicates(inVertices, outVertices, outIndices.data()); } // See #1 in the comments at the beginning of this file. The // preconditions are // 1. inVertices.size() is a positive multiple of Dimension // The postconditions are // 1. outVertices has unique vertices // 2. outSimplices.size() = inVertices.size() / Dimension // 3. 0 <= outSimplices[s][d] < outVertices.size() void GenerateIndexedSimplices( std::vector<VertexType> const& inVertices, std::vector<VertexType>& outVertices, std::vector<std::array<IndexType, Dimension>>& outSimplices) { LogAssert( inVertices.size() > 0 && inVertices.size() % Dimension == 0, "Invalid number of vertices."); outSimplices.resize(inVertices.size() / Dimension); IndexType* outIndices = reinterpret_cast<IndexType*>(outSimplices.data()); RemoveDuplicates(inVertices, outVertices, outIndices); } // See #2 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inIndices.size() is a positive multiple of Dimension // 3. 0 <= inIndices[i] < inVertices.size() // The postconditions are // 1. outVertices has unique vertices // 2. outIndices.size() = inIndices.size() // 3. 0 <= outIndices[i] < outVertices.size() void RemoveDuplicateVertices( std::vector<VertexType> const& inVertices, std::vector<IndexType> const& inIndices, std::vector<VertexType>& outVertices, std::vector<IndexType>& outIndices) { LogAssert( inVertices.size() > 0, "Invalid number of vertices."); LogAssert( inIndices.size() > 0 && inIndices.size() % Dimension == 0, "Invalid number of indices."); IndexType const numVertices = static_cast<IndexType>(inVertices.size()); for (auto index : inIndices) { LogAssert( 0 <= index && index < numVertices, "Invalid index."); } std::vector<IndexType> inToOutMapping(inVertices.size()); RemoveDuplicates(inVertices, outVertices, inToOutMapping.data()); outIndices.resize(inIndices.size()); for (size_t i = 0; i < inIndices.size(); ++i) { outIndices[i] = inToOutMapping[inIndices[i]]; } } // See #2 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inSimplices.size() is positive // 3. 0 <= inSimplices[s][d] < inVertices.size() // The postconditions are // 1. outVertices has unique vertices // 2. outSimplices.size() = inSimplices.size() // 3. 0 <= outSimplices[s][d] < outVertices.size() void RemoveDuplicateVertices( std::vector<VertexType> const& inVertices, std::vector<std::array<IndexType, Dimension>> const& inSimplices, std::vector<VertexType>& outVertices, std::vector<std::array<IndexType, Dimension>>& outSimplices) { LogAssert( inVertices.size() > 0, "Invalid number of vertices."); LogAssert(inSimplices.size() > 0, "Invalid number of simplices."); IndexType const numVertices = static_cast<IndexType>(inVertices.size()); for (auto const& simplex : inSimplices) { for (size_t d = 0; d < Dimension; ++d) { LogAssert( 0 <= simplex[d] && simplex[d] < numVertices, "Invalid index."); } } std::vector<IndexType> inToOutMapping(inVertices.size()); RemoveDuplicates(inVertices, outVertices, inToOutMapping.data()); size_t const numSimplices = inSimplices.size(); outSimplices.resize(numSimplices); for (size_t s = 0; s < numSimplices; ++s) { for (size_t d = 0; d < Dimension; ++d) { outSimplices[s][d] = inToOutMapping[inSimplices[s][d]]; } } } // See #3 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inIndices.size() is a positive multiple of Dimension // 3. 0 <= inIndices[i] < inVertices.size() // The postconditions are // 1. outVertices.size() is positive // 2. outIndices.size() = inIndices.size() // 3. 0 <= outIndices[i] < outVertices.size() // 4. each outVertices[v] occurs at least once in outIndices[] void RemoveUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<IndexType> const& inIndices, std::vector<VertexType>& outVertices, std::vector<IndexType>& outIndices) { LogAssert(inVertices.size() > 0, "Invalid number of vertices."); LogAssert( inIndices.size() > 0 && inIndices.size() % Dimension == 0, "Invalid number of indices."); IndexType const numVertices = static_cast<IndexType>(inVertices.size()); for (auto index : inIndices) { LogAssert( 0 <= index && index < numVertices, "Invalid index."); } outIndices.resize(inIndices.size()); RemoveUnused(inVertices, inIndices.size(), inIndices.data(), outVertices, outIndices.data()); } // See #3 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inSimplices.size() is positive // 3. 0 <= inSimplices[s][d] < inVertices.size() // The postconditions are // 1. outVertices.size() is positive // 2. outSimplices.size() = inSimplices.size() // 3. 0 <= outSimplices[s][d] < outVertices.size() // 4. each outVertices[v] occurs at least once in outSimplices[][] void RemoveUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<std::array<IndexType, Dimension>> const& inSimplices, std::vector<VertexType>& outVertices, std::vector<std::array<IndexType, Dimension>>& outSimplices) { LogAssert( inVertices.size() > 0, "Invalid number of vertices."); LogAssert( inSimplices.size() > 0, "Invalid number of simplices."); IndexType const numVertices = static_cast<IndexType>(inVertices.size()); for (auto const& simplex : inSimplices) { for (size_t d = 0; d < Dimension; ++d) { LogAssert( 0 <= simplex[d] && simplex[d] < numVertices, "Invalid index."); } } outSimplices.resize(inSimplices.size()); size_t const numInIndices = Dimension * inSimplices.size(); IndexType const* inIndices = reinterpret_cast<IndexType const*>(inSimplices.data()); IndexType* outIndices = reinterpret_cast<IndexType*>(outSimplices.data()); RemoveUnused(inVertices, numInIndices, inIndices, outVertices, outIndices); } // See #4 and the preconditions for RemoveDuplicateVertices and for // RemoveUnusedVertices. void RemoveDuplicateAndUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<IndexType> const& inIndices, std::vector<VertexType>& outVertices, std::vector<IndexType>& outIndices) { std::vector<VertexType> tempVertices; std::vector<IndexType> tempIndices; RemoveDuplicateVertices(inVertices, inIndices, tempVertices, tempIndices); RemoveUnusedVertices(tempVertices, tempIndices, outVertices, outIndices); } // See #4 and the preconditions for RemoveDuplicateVertices and for // RemoveUnusedVertices. void RemoveDuplicateAndUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<std::array<IndexType, Dimension>> const& inSimplices, std::vector<VertexType>& outVertices, std::vector<std::array<IndexType, Dimension>>& outSimplices) { std::vector<VertexType> tempVertices; std::vector<std::array<IndexType, Dimension>> tempSimplices; RemoveDuplicateVertices(inVertices, inSimplices, tempVertices, tempSimplices); RemoveUnusedVertices(tempVertices, tempSimplices, outVertices, outSimplices); } private: void RemoveDuplicates( std::vector<VertexType> const& inVertices, std::vector<VertexType>& outVertices, IndexType* inToOutMapping) { // Construct the unique vertices. size_t const numInVertices = inVertices.size(); size_t numOutVertices = 0; std::map<VertexType, IndexType> vmap; for (size_t i = 0; i < numInVertices; ++i) { auto const iter = vmap.find(inVertices[i]); if (iter != vmap.end()) { // The vertex is a duplicate of one inserted earlier into // the map. Its index i will be modified to that of the // first-found vertex. inToOutMapping[i] = iter->second; } else { // The vertex occurs for the first time. vmap.insert(std::make_pair(inVertices[i], static_cast<IndexType>(numOutVertices))); inToOutMapping[i] = static_cast<IndexType>(numOutVertices); ++numOutVertices; } } // Pack the unique vertices into an array. outVertices.resize(numOutVertices); for (auto const& element : vmap) { outVertices[element.second] = element.first; } } void RemoveUnused( std::vector<VertexType> const& inVertices, size_t const numInIndices, IndexType const* inIndices, std::vector<VertexType>& outVertices, IndexType* outIndices) { // Get the unique set of used indices. std::set<IndexType> usedIndices; for (size_t i = 0; i < numInIndices; ++i) { usedIndices.insert(inIndices[i]); } // Locate the used vertices and pack them into an array. outVertices.resize(usedIndices.size()); size_t numOutVertices = 0; std::map<IndexType, IndexType> vmap; for (auto oldIndex : usedIndices) { outVertices[numOutVertices] = inVertices[oldIndex]; vmap.insert(std::make_pair(oldIndex, static_cast<IndexType>(numOutVertices))); ++numOutVertices; } // Reassign the old indices to the new indices. for (size_t i = 0; i < numInIndices; ++i) { outIndices[i] = vmap.find(inIndices[i])->second; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegment2OrientedBox2.h
.h
2,857
79
// 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/DistLine2OrientedBox2.h> #include <Mathematics/DistPointOrientedBox.h> #include <Mathematics/Segment.h> // Compute the distance between a segment and a solid oriented box in 2D. // // The segment is P0 + t * (P1 - P0) for 0 <= t <= 1. The direction D = P1-P0 // is generally not unit length. // // The oriented box has center C, unit-length axis directions U[i] and extents // e[i] for 0 <= i < N. 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 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, Segment2<T>, OrientedBox2<T>> { public: using OrientedQuery = DCPQuery<T, Line2<T>, OrientedBox2<T>>; using Result = typename OrientedQuery::Result; Result operator()(Segment2<T> const& segment, OrientedBox2<T> const& box) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector2<T> direction = segment.p[1] - segment.p[0]; Line2<T> line(segment.p[0], direction); DCPQuery<T, Line2<T>, OrientedBox2<T>> lbQuery{}; auto lbResult = lbQuery(line, box); if (lbResult.parameter >= zero) { if (lbResult.parameter <= one) { result = lbResult; } else { DCPQuery<T, Vector2<T>, OrientedBox2<T>> pbQuery{}; auto pbResult = pbQuery(segment.p[1], box); result.distance = pbResult.distance; result.sqrDistance = pbResult.sqrDistance; result.parameter = one; result.closest[0] = segment.p[1]; result.closest[1] = pbResult.closest[1]; } } else { DCPQuery<T, Vector2<T>, OrientedBox2<T>> pbQuery{}; auto pbResult = pbQuery(segment.p[0], box); result.distance = pbResult.distance; result.sqrDistance = pbResult.sqrDistance; result.parameter = zero; result.closest[0] = segment.p[0]; result.closest[1] = pbResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MinimumAreaBox2.h
.h
27,249
693
// 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.03 #pragma once #include <Mathematics/OrientedBox.h> #include <Mathematics/ConvexHull2.h> // Compute a minimum-area oriented box containing the specified points. The // algorithm uses the rotating calipers method, but with a dual pair of // calipers. For details, see // http://www-cgrl.cs.mcgill.ca/~godfried/research/calipers.html // https://web.archive.org/web/20150330010154/http://cgm.cs.mcgill.ca/~orm/rotcal.html // The box is supported by the convex hull of the points, so the algorithm // is really about computing the minimum-area box containing a convex polygon. // The rotating calipers approach is O(n) in time for n polygon edges. // // A detailed description of the algorithm and implementation is found in // https://www.geometrictools.com/Documentation/MinimumAreaRectangle.pdf // // NOTE: This algorithm guarantees a correct output only when ComputeType is // an exact arithmetic type that supports division. In GTEngine, one such // type is BSRational<UIntegerAP32> (arbitrary precision). Another such type // is BSRational<UIntegerFP32<N>> (fixed precision), where N is chosen large // enough for your input data sets. If you choose ComputeType to be 'float' // or 'double', the output is not guaranteed to be correct. // // See GeometricTools/GTEngine/Samples/Geometrics/MinimumAreaBox2 for an // example of how to use the code. namespace gte { template <typename InputType, typename ComputeType> class MinimumAreaBox2 { public: // The class is a functor to support computing the minimum-area box of // multiple data sets using the same class object. MinimumAreaBox2() : mNumPoints(0), mPoints(nullptr), mSupportIndices{ 0, 0, 0, 0 }, mArea(static_cast<InputType>(0)) { } // The points are arbitrary, so we must compute the convex hull from // them in order to compute the minimum-area box. The input parameters // are necessary for using ConvexHull2. NOTE: ConvexHull2 guarantees // that the hull does not have three consecutive collinear points. OrientedBox2<InputType> operator()(int32_t numPoints, Vector2<InputType> const* points, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value) { InputType const zero = static_cast<InputType>(0); mNumPoints = numPoints; mPoints = points; mHull.clear(); // Get the convex hull of the points. ConvexHull2<InputType> ch2{}; ch2(mNumPoints, mPoints, zero); int32_t dimension = ch2.GetDimension(); OrientedBox2<InputType> minBox{}; if (dimension == 0) { // The points are all the same. minBox.center = mPoints[0]; minBox.axis[0] = Vector2<InputType>::Unit(0); minBox.axis[1] = Vector2<InputType>::Unit(1); minBox.extent[0] = zero; minBox.extent[1] = zero; mHull.resize(1); mHull[0] = 0; return minBox; } InputType const half = static_cast<InputType>(0.5); if (dimension == 1) { // The points lie on a line. Determine the extreme t-values // for the points represented as P = origin + t*direction. We // know that 'origin' is an/ input vertex, so we can start // both t-extremes at zero. Line2<InputType> const& line = ch2.GetLine(); InputType tmin = zero, tmax = zero; int32_t imin = 0, imax = 0; for (int32_t i = 0; i < mNumPoints; ++i) { Vector2<InputType> diff = mPoints[i] - line.origin; InputType t = Dot(diff, line.direction); if (t > tmax) { tmax = t; imax = i; } else if (t < tmin) { tmin = t; imin = i; } } minBox.center = line.origin + half * (tmin + tmax) * line.direction; minBox.extent[0] = half * (tmax - tmin); minBox.extent[1] = zero; minBox.axis[0] = line.direction; minBox.axis[1] = -Perp(line.direction); mHull.resize(2); mHull[0] = imin; mHull[1] = imax; return minBox; } mHull = ch2.GetHull(); Vector2<InputType> const* vertices = ch2.GetPoints(); std::vector<Vector2<ComputeType>> computePoints(mHull.size()); for (size_t i = 0; i < mHull.size(); ++i) { for (int32_t j = 0; j < 2; ++j) { computePoints[i][j] = vertices[mHull[i]][j]; } } RemoveCollinearPoints(computePoints); Box box{}; if (useRotatingCalipers) { box = ComputeBoxForEdgeOrderN(computePoints); } else { box = ComputeBoxForEdgeOrderNSqr(computePoints); } ConvertTo(box, computePoints, minBox); return minBox; } // The points are arbitrary, so the convex hull must be computed from // them to obtain the convex polygon whose minimum width is the // desired output. OrientedBox2<InputType> operator()( std::vector<Vector2<InputType>> const& points, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value) { return operator()(static_cast<int32_t>(points.size()), points.data(), useRotatingCalipers); } // The points already form a counterclockwise, nondegenerate convex // polygon. If the points directly are the convex polygon, pass an // indices object with 0 elements. If the polygon vertices are a // subset of the incoming points, that subset is identified by // numIndices >= 3 and indices having numIndices elements. OrientedBox2<InputType> operator()(int32_t numPoints, Vector2<InputType> const* points, int32_t numIndices, int32_t const* indices, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value) { mHull.clear(); OrientedBox2<InputType> minBox{}; if (numPoints < 3 || !points || (indices && numIndices < 3)) { minBox.center = Vector2<InputType>::Zero(); minBox.axis[0] = Vector2<InputType>::Unit(0); minBox.axis[1] = Vector2<InputType>::Unit(1); minBox.extent = Vector2<InputType>::Zero(); return minBox; } if (indices) { mHull.resize(numIndices); std::copy(indices, indices + numIndices, mHull.begin()); } else { numIndices = numPoints; mHull.resize(numIndices); for (int32_t i = 0; i < numIndices; ++i) { mHull[i] = i; } } std::vector<Vector2<ComputeType>> computePoints(numIndices); for (int32_t i = 0; i < numIndices; ++i) { int32_t h = mHull[i]; computePoints[i][0] = (ComputeType)points[h][0]; computePoints[i][1] = (ComputeType)points[h][1]; } RemoveCollinearPoints(computePoints); Box box{}; if (useRotatingCalipers) { box = ComputeBoxForEdgeOrderN(computePoints); } else { box = ComputeBoxForEdgeOrderNSqr(computePoints); } ConvertTo(box, computePoints, minBox); return minBox; } // The points already form a counterclockwise, nondegenerate convex // polygon. If the points directly are the convex polygon, pass an // indices object with 0 elements. If the polygon vertices are a // subset of the incoming points, that subset is identified by // numIndices >= 3 and indices having numIndices elements. OrientedBox2<InputType> operator()( std::vector<Vector2<InputType>> const& points, std::vector<int32_t> const& indices, bool useRotatingCalipers = !std::is_floating_point<ComputeType>::value) { if (indices.size() > 0) { return operator()(static_cast<int32_t>(points.size()), points.data(), static_cast<int32_t>(indices.size()), indices.data(), useRotatingCalipers); } else { return operator()(points, useRotatingCalipers); } } // Member access. inline int32_t GetNumPoints() const { return mNumPoints; } inline Vector2<InputType> const* GetPoints() const { return mPoints; } inline std::vector<int32_t> const& GetHull() const { return mHull; } inline std::array<int32_t, 4> const& GetSupportIndices() const { return mSupportIndices; } inline InputType GetArea() const { return mArea; } private: // The box axes are U[i] and are usually not unit-length in order to // allow exact arithmetic. The box is supported by mPoints[index[i]], // where i is one of the enumerations above. The box axes are not // necessarily unit length, but they have the same length. They need // to be normalized for conversion back to InputType. struct Box { Box() : U{ Vector2<ComputeType>::Zero(), Vector2<ComputeType>::Zero() }, index{ 0, 0, 0, 0 }, sqrLenU0((ComputeType)0), area((ComputeType)0) { } std::array<Vector2<ComputeType>, 2> U; std::array<int32_t, 4> index; // order: bottom, right, top, left ComputeType sqrLenU0, area; }; // The rotating calipers algorithm has a loop invariant that requires // the convex polygon not to have collinear points. Any such points // must be removed first. The code is also executed for the O(n^2) // algorithm to reduce the number of process edges. void RemoveCollinearPoints(std::vector<Vector2<ComputeType>>& vertices) { std::vector<Vector2<ComputeType>> tmpVertices = vertices; ComputeType const zero = static_cast<ComputeType>(0); int32_t const numVertices = static_cast<int32_t>(vertices.size()); int32_t numNoncollinear = 0; Vector2<ComputeType> ePrev = tmpVertices[0] - tmpVertices.back(); for (int32_t i0 = 0, i1 = 1; i0 < numVertices; ++i0) { Vector2<ComputeType> eNext = tmpVertices[i1] - tmpVertices[i0]; ComputeType dp = DotPerp(ePrev, eNext); if (dp != zero) { vertices[numNoncollinear++] = tmpVertices[i0]; } ePrev = eNext; if (++i1 == numVertices) { i1 = 0; } } vertices.resize(numNoncollinear); } // This is the slow O(n^2) search. Box ComputeBoxForEdgeOrderNSqr(std::vector<Vector2<ComputeType>> const& vertices) { ComputeType const negOne = static_cast<ComputeType>(-1); Box minBox{}; minBox.area = negOne; int32_t const numIndices = static_cast<int32_t>(vertices.size()); for (int32_t i0 = numIndices - 1, i1 = 0; i1 < numIndices; i0 = i1++) { Box box = SmallestBox(i0, i1, vertices); if (minBox.area == negOne || box.area < minBox.area) { minBox = box; } } return minBox; } // The fast O(n) search. Box ComputeBoxForEdgeOrderN(std::vector<Vector2<ComputeType>> const& vertices) { // The inputs are assumed to be the vertices of a convex polygon // that is counterclockwise ordered. The input points must not // contain three consecutive collinear points. // When the bounding box corresponding to a polygon edge is // computed, we mark the edge as visited. If the edge is // encountered later, the algorithm terminates. std::vector<bool> visited(vertices.size()); std::fill(visited.begin(), visited.end(), false); // Start the minimum-area rectangle search with the edge from the // last polygon vertex to the first. When updating the extremes, // we want the bottom-most point on the left edge, the top-most // point on the right edge, the left-most point on the top edge, // and the right-most point on the bottom edge. The polygon edges // starting at these points are then guaranteed not to coincide // with a box edge except when an extreme point is shared by two // box edges (at a corner). Box minBox = SmallestBox((int32_t)vertices.size() - 1, 0, vertices); visited[minBox.index[0]] = true; // Execute the rotating calipers algorithm. Box box = minBox; for (size_t i = 0; i < vertices.size(); ++i) { std::array<std::pair<ComputeType, int32_t>, 4> A{}; int32_t numA{}; if (!ComputeAngles(vertices, box, A, numA)) { // The polygon is a rectangle, so the search is over. break; } // Indirectly sort the A-array. std::array<int32_t, 4> sort = SortAngles(A, numA); // Update the supporting indices (box.index[]) and the box // axis directions (box.U[]). if (!UpdateSupport(A, numA, sort, vertices, visited, box)) { // We have already processed the box polygon edge, so the // search is over. break; } if (box.area < minBox.area) { minBox = box; } } return minBox; } // Compute the smallest box for the polygon edge <V[i0],V[i1]>. Box SmallestBox(int32_t i0, int32_t i1, std::vector<Vector2<ComputeType>> const& vertices) { Box box{}; box.U[0] = vertices[i1] - vertices[i0]; box.U[1] = -Perp(box.U[0]); box.index = { i1, i1, i1, i1 }; box.sqrLenU0 = Dot(box.U[0], box.U[0]); ComputeType const zero = static_cast<ComputeType>(0); Vector2<ComputeType> const& origin = vertices[i1]; std::array<Vector2<ComputeType>, 4> support{}; for (size_t j = 0; j < 4; ++j) { support[j] = { zero, zero }; } int32_t i = 0; for (auto const& vertex : vertices) { Vector2<ComputeType> diff = vertex - origin; Vector2<ComputeType> v = { Dot(box.U[0], diff), Dot(box.U[1], diff) }; // The right-most vertex of the bottom edge is vertices[i1]. // The assumption of no triple of collinear vertices // guarantees that box.index[0] is i1, which is the initial // value assigned at the beginning of this function. // Therefore, there is no need to test for other vertices // farther to the right than vertices[i1]. if (v[0] > support[1][0] || (v[0] == support[1][0] && v[1] > support[1][1])) { // New right maximum OR same right maximum but closer // to top. box.index[1] = i; support[1] = v; } if (v[1] > support[2][1] || (v[1] == support[2][1] && v[0] < support[2][0])) { // New top maximum OR same top maximum but closer // to left. box.index[2] = i; support[2] = v; } if (v[0] < support[3][0] || (v[0] == support[3][0] && v[1] < support[3][1])) { // New left minimum OR same left minimum but closer // to bottom. box.index[3] = i; support[3] = v; } ++i; } // The comment in the loop has the implication that // support[0] = { 0, 0 }, so the scaled height // (support[2][1] - support[0][1]) is simply support[2][1]. ComputeType scaledWidth = support[1][0] - support[3][0]; ComputeType scaledHeight = support[2][1]; box.area = scaledWidth * scaledHeight / box.sqrLenU0; return box; } // Compute (sin(angle))^2 for the polygon edges emanating from the // support vertices of the box. The return value is 'true' if at // least one angle is in [0,pi/2); otherwise, the return value is // 'false' and the original polygon must be a rectangle. bool ComputeAngles(std::vector<Vector2<ComputeType>> const& vertices, Box const& box, std::array<std::pair<ComputeType, int32_t>, 4>& A, int32_t& numA) const { int32_t const numVertices = static_cast<int32_t>(vertices.size()); numA = 0; for (int32_t k0 = 3, k1 = 0; k1 < 4; k0 = k1++) { if (box.index[k0] != box.index[k1]) { // The box edges are ordered in k1 as U[0], U[1], // -U[0], -U[1]. Vector2<ComputeType> D = ((k0 & 2) ? -box.U[k0 & 1] : box.U[k0 & 1]); int32_t j0 = box.index[k0], j1 = j0 + 1; if (j1 == numVertices) { j1 = 0; } Vector2<ComputeType> E = vertices[j1] - vertices[j0]; ComputeType dp = DotPerp(D, E); ComputeType esqrlen = Dot(E, E); ComputeType sinThetaSqr = (dp * dp) / esqrlen; A[numA] = std::make_pair(sinThetaSqr, k0); ++numA; } } return numA > 0; } // Sort the angles indirectly. The sorted indices are returned. This // avoids swapping elements of A[], which can be expensive when // ComputeType is an exact rational type. std::array<int32_t, 4> SortAngles( std::array<std::pair<ComputeType, int32_t>, 4> const& A, int32_t numA) const { std::array<int32_t, 4> sort = { 0, 1, 2, 3 }; if (numA > 1) { if (numA == 2) { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } } else if (numA == 3) { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } if (A[sort[0]].first > A[sort[2]].first) { std::swap(sort[0], sort[2]); } if (A[sort[1]].first > A[sort[2]].first) { std::swap(sort[1], sort[2]); } } else // numA == 4 { if (A[sort[0]].first > A[sort[1]].first) { std::swap(sort[0], sort[1]); } if (A[sort[2]].first > A[sort[3]].first) { std::swap(sort[2], sort[3]); } if (A[sort[0]].first > A[sort[2]].first) { std::swap(sort[0], sort[2]); } if (A[sort[1]].first > A[sort[3]].first) { std::swap(sort[1], sort[3]); } if (A[sort[1]].first > A[sort[2]].first) { std::swap(sort[1], sort[2]); } } } return sort; } bool UpdateSupport(std::array<std::pair<ComputeType, int32_t>, 4> const& A, int32_t numA, std::array<int32_t, 4> const& sort, std::vector<Vector2<ComputeType>> const& vertices, std::vector<bool>& visited, Box& box) { // Replace the support vertices of those edges attaining minimum // angle with the other endpoints of the edges. int32_t const numVertices = static_cast<int32_t>(vertices.size()); auto const& amin = A[sort[0]]; for (int32_t k = 0; k < numA; ++k) { auto const& a = A[sort[k]]; if (a.first == amin.first) { if (++box.index[a.second] == numVertices) { box.index[a.second] = 0; } } } int32_t bottom = box.index[amin.second]; if (visited[bottom]) { // We have already processed this polygon edge. return false; } visited[bottom] = true; // Cycle the vertices so that the bottom support occurs first. std::array<int32_t, 4> nextIndex{}; for (int32_t k = 0; k < 4; ++k) { nextIndex[k] = box.index[(amin.second + k) % 4]; } box.index = nextIndex; // Compute the box axis directions. int32_t j1 = box.index[0], j0 = j1 - 1; if (j0 < 0) { j0 = numVertices - 1; } box.U[0] = vertices[j1] - vertices[j0]; box.U[1] = -Perp(box.U[0]); box.sqrLenU0 = Dot(box.U[0], box.U[0]); // Compute the box area. std::array<Vector2<ComputeType>, 2> diff = { vertices[box.index[1]] - vertices[box.index[3]], vertices[box.index[2]] - vertices[box.index[0]] }; box.area = Dot(box.U[0], diff[0]) * Dot(box.U[1], diff[1]) / box.sqrLenU0; return true; } // Convert the ComputeType box to the InputType box. When the // ComputeType is an exact rational type, the conversions are // performed to avoid precision loss until necessary at the last step. void ConvertTo(Box const& minBox, std::vector<Vector2<ComputeType>> const& computePoints, OrientedBox2<InputType>& itMinBox) { // The sum, difference, and center are all computed exactly. std::array<Vector2<ComputeType>, 2> sum = { computePoints[minBox.index[1]] + computePoints[minBox.index[3]], computePoints[minBox.index[2]] + computePoints[minBox.index[0]] }; std::array<Vector2<ComputeType>, 2> difference = { computePoints[minBox.index[1]] - computePoints[minBox.index[3]], computePoints[minBox.index[2]] - computePoints[minBox.index[0]] }; ComputeType const half = static_cast<ComputeType>(0.5); Vector2<ComputeType> center = half * ( Dot(minBox.U[0], sum[0]) * minBox.U[0] + Dot(minBox.U[1], sum[1]) * minBox.U[1]) / minBox.sqrLenU0; // Calculate the squared extent using ComputeType to avoid loss of // precision before computing a squared root. Vector2<ComputeType> sqrExtent{}; for (int32_t i = 0; i < 2; ++i) { sqrExtent[i] = half * Dot(minBox.U[i], difference[i]); sqrExtent[i] *= sqrExtent[i]; sqrExtent[i] /= minBox.sqrLenU0; } ComputeType const one = static_cast<ComputeType>(1); for (int32_t i = 0; i < 2; ++i) { itMinBox.center[i] = static_cast<InputType>(center[i]); itMinBox.extent[i] = std::sqrt(static_cast<InputType>(sqrExtent[i])); // Before converting to floating-point, factor out the maximum // component using ComputeType to generate rational numbers in // a range that avoids loss of precision during the conversion // and normalization. Vector2<ComputeType> const& axis = minBox.U[i]; ComputeType cmax = std::max(std::fabs(axis[0]), std::fabs(axis[1])); ComputeType invCMax = one / cmax; for (int32_t j = 0; j < 2; ++j) { itMinBox.axis[i][j] = static_cast<InputType>(axis[j] * invCMax); } Normalize(itMinBox.axis[i]); } mSupportIndices = minBox.index; mArea = static_cast<InputType>(minBox.area); } // The input points to be bound. int32_t mNumPoints; Vector2<InputType> const* mPoints; // The indices into mPoints/mComputePoints for the convex hull // vertices. std::vector<int32_t> mHull; // The support indices for the minimum-area box. std::array<int32_t, 4> mSupportIndices; // The area of the minimum-area box. The ComputeType value is exact, // so the only rounding errors occur in the conversion from // ComputeType to InputType (default rounding mode is // round-to-nearest-ties-to-even). InputType mArea; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment3AlignedBox3.h
.h
6,163
166
// 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/IntrLine3AlignedBox3.h> #include <Mathematics/Segment.h> // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the six // faces of the box. The find-intersection queries use Liang-Barsky // clipping. The queries consider the box to be a solid. The algorithms // are described in // https://www.geometrictools.com/Documentation/IntersectionLineBox.pdf namespace gte { template <typename T> class TIQuery<T, Segment3<T>, AlignedBox3<T>> : public TIQuery<T, Line3<T>, AlignedBox3<T>> { public: struct Result : public TIQuery<T, Line3<T>, AlignedBox3<T>>::Result { Result() : TIQuery<T, Line3<T>, AlignedBox3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment3<T> const& segment, AlignedBox3<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly axis[d] = Vector3<T>::Unit(d). Vector3<T> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the segment to a centered form in the aligned-box // coordinate system. Vector3<T> transformedP0 = segment.p[0] - boxCenter; Vector3<T> transformedP1 = segment.p[1] - boxCenter; Segment3<T> transformedSegment(transformedP0, transformedP1); Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; transformedSegment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, boxExtent, result); return result; } protected: void DoQuery(Vector3<T> const& segOrigin, Vector3<T> const& segDirection, T segExtent, Vector3<T> const& boxExtent, Result& result) { for (int32_t i = 0; i < 3; ++i) { if (std::fabs(segOrigin[i]) > boxExtent[i] + segExtent * std::fabs(segDirection[i])) { result.intersect = false; return; } } TIQuery<T, Line3<T>, AlignedBox3<T>>::DoQuery( segOrigin, segDirection, boxExtent, result); } }; template <typename T> class FIQuery<T, Segment3<T>, AlignedBox3<T>> : public FIQuery<T, Line3<T>, AlignedBox3<T>> { public: struct Result : public FIQuery<T, Line3<T>, AlignedBox3<T>>::Result { Result() : FIQuery<T, Line3<T>, AlignedBox3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment3<T> const& segment, AlignedBox3<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly axis[d] = Vector3<T>::Unit(d). Vector3<T> boxCenter{}, boxExtent{}; box.GetCenteredForm(boxCenter, boxExtent); // Transform the segment to a centered form in the aligned-box // coordinate system. Vector3<T> transformedP0 = segment.p[0] - boxCenter; Vector3<T> transformedP1 = segment.p[1] - boxCenter; Segment3<T> transformedSegment(transformedP0, transformedP1); Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; transformedSegment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, boxExtent, result); if (result.intersect) { // The segment origin is in aligned-box coordinates. Transform // it back to the original space. segOrigin += boxCenter; 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, 'output' is default // constructed as if there is no intersection. If an intersection is // found, the 'output' values will be modified accordingly. void DoQuery(Vector3<T> const& segOrigin, Vector3<T> const& segDirection, T segExtent, Vector3<T> const& boxExtent, Result& result) { FIQuery<T, Line3<T>, AlignedBox3<T>>::DoQuery( segOrigin, segDirection, boxExtent, result); if (result.intersect) { // The line containing the segment intersects the box; the // t-interval is [t0,t1]. The segment intersects the box 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 box. result = Result{}; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2AlignedBox2.h
.h
6,046
184
// 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/Line.h> #include <Mathematics/AlignedBox.h> #include <Mathematics/Vector2.h> // The queries consider the box to be a solid. // // The test-intersection queries use the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The find-intersection queries use parametric clipping against the four // edges of the box. namespace gte { template <typename T> class TIQuery<T, Line2<T>, AlignedBox2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Line2<T> const& line, AlignedBox2<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly Axis[d] = Vector2<T>::Unit(d). Vector2<T> boxCenter, boxExtent; box.GetCenteredForm(boxCenter, boxExtent); // Transform the line to the aligned-box coordinate system. Vector2<T> lineOrigin = line.origin - boxCenter; Result result{}; DoQuery(lineOrigin, line.direction, boxExtent, result); return result; } protected: void DoQuery(Vector2<T> const& lineOrigin, Vector2<T> const& lineDirection, Vector2<T> const& boxExtent, Result& result) { T LHS = std::fabs(DotPerp(lineDirection, lineOrigin)); T RHS = boxExtent[0] * std::fabs(lineDirection[1]) + boxExtent[1] * std::fabs(lineDirection[0]); result.intersect = (LHS <= RHS); } }; template <typename T> class FIQuery<T, Line2<T>, AlignedBox2<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()(Line2<T> const& line, AlignedBox2<T> const& box) { // Get the centered form of the aligned box. The axes are // implicitly Axis[d] = Vector2<T>::Unit(d). Vector2<T> boxCenter, boxExtent; box.GetCenteredForm(boxCenter, boxExtent); // Transform the line to the aligned-box coordinate system. Vector2<T> lineOrigin = line.origin - boxCenter; Result result{}; DoQuery(lineOrigin, line.direction, boxExtent, result); for (int32_t i = 0; i < result.numIntersections; ++i) { result.point[i] = line.origin + result.parameter[i] * line.direction; } return result; } protected: void DoQuery(Vector2<T> const& lineOrigin, Vector2<T> const& lineDirection, Vector2<T> const& boxExtent, Result& result) { // The line t-values are in the interval (-infinity,+infinity). // Clip the line against all four planes of an aligned box in // centered form. The result.numPoints is // 0, no intersection // 1, intersect in a single point (t0 is line parameter of point) // 2, intersect in a segment (line parameter interval is [t0,t1]) T t0 = -std::numeric_limits<T>::max(); T t1 = std::numeric_limits<T>::max(); if (Clip(+lineDirection[0], -lineOrigin[0] - boxExtent[0], t0, t1) && Clip(-lineDirection[0], +lineOrigin[0] - boxExtent[0], t0, t1) && Clip(+lineDirection[1], -lineOrigin[1] - boxExtent[1], t0, t1) && Clip(-lineDirection[1], +lineOrigin[1] - boxExtent[1], t0, t1)) { result.intersect = true; if (t1 > t0) { result.numIntersections = 2; result.parameter[0] = t0; result.parameter[1] = t1; } else { result.numIntersections = 1; result.parameter[0] = t0; result.parameter[1] = t0; // Used by derived classes. } return; } result.intersect = false; result.numIntersections = 0; } private: // Test whether the current clipped segment intersects the current // test plane. If the return value is 'true', the segment does // intersect the plane and is clipped; otherwise, the segment is // culled (no intersection with box). static bool Clip(T denom, T numer, T& t0, T& t1) { if (denom > (T)0) { if (numer > denom * t1) { return false; } if (numer > denom * t0) { t0 = numer / denom; } return true; } else if (denom < (T)0) { if (numer > denom * t0) { return false; } if (numer > denom * t1) { t1 = numer / denom; } return true; } else { return numer <= (T)0; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/GVector.h
.h
14,430
519
// 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 <vector> namespace gte { template <typename Real> class GVector { public: // The tuple is length zero (uninitialized). GVector() : mTuple{} { } // The tuple is length 'size' and the elements are uninitialized. GVector(int32_t size) : mTuple{} { SetSize(size); } // For 0 <= d <= size, element d is 1 and all others are zero. If d // is invalid, the zero vector is created. This is a convenience for // creating the standard Euclidean basis vectors; see also // MakeUnit(int32_t,int32_t) and Unit(int32_t,int32_t). GVector(int32_t size, int32_t d) : mTuple{} { SetSize(size); MakeUnit(d); } // The copy constructor, destructor, and assignment operator are // generated by the compiler. // Member access. SetSize(int32_t) does not initialize the tuple. The // first operator[] returns a const reference rather than a Real // value. This supports writing via standard file operations that // require a const pointer to data. void SetSize(int32_t size) { LogAssert(size >= 0, "Invalid size."); mTuple.resize(size); } inline int32_t GetSize() const { return static_cast<int32_t>(mTuple.size()); } inline Real const& operator[](int32_t i) const { return mTuple[i]; } inline Real& operator[](int32_t i) { return mTuple[i]; } // Comparison (for use by STL containers). inline bool operator==(GVector const& vec) const { return mTuple == vec.mTuple; } inline bool operator!=(GVector const& vec) const { return mTuple != vec.mTuple; } inline bool operator< (GVector const& vec) const { return mTuple < vec.mTuple; } inline bool operator<=(GVector const& vec) const { return mTuple <= vec.mTuple; } inline bool operator> (GVector const& vec) const { return mTuple > vec.mTuple; } inline bool operator>=(GVector const& vec) const { return mTuple >= vec.mTuple; } // Special vectors. // All components are 0. void MakeZero() { std::fill(mTuple.begin(), mTuple.end(), (Real)0); } // Component d is 1, all others are zero. void MakeUnit(int32_t d) { std::fill(mTuple.begin(), mTuple.end(), (Real)0); if (0 <= d && d < (int32_t)mTuple.size()) { mTuple[d] = (Real)1; } } static GVector Zero(int32_t size) { GVector<Real> v(size); v.MakeZero(); return v; } static GVector Unit(int32_t size, int32_t d) { GVector<Real> v(size); v.MakeUnit(d); return v; } protected: // This data structure takes advantage of the built-in operator[], // range checking and visualizers in MSVS. std::vector<Real> mTuple; }; // Unary operations. template <typename Real> GVector<Real> operator+(GVector<Real> const& v) { return v; } template <typename Real> GVector<Real> operator-(GVector<Real> const& v) { GVector<Real> result(v.GetSize()); for (int32_t i = 0; i < v.GetSize(); ++i) { result[i] = -v[i]; } return result; } // Linear-algebraic operations. template <typename Real> GVector<Real> operator+(GVector<Real> const& v0, GVector<Real> const& v1) { GVector<Real> result = v0; return result += v1; } template <typename Real> GVector<Real> operator-(GVector<Real> const& v0, GVector<Real> const& v1) { GVector<Real> result = v0; return result -= v1; } template <typename Real> GVector<Real> operator*(GVector<Real> const& v, Real scalar) { GVector<Real> result = v; return result *= scalar; } template <typename Real> GVector<Real> operator*(Real scalar, GVector<Real> const& v) { GVector<Real> result = v; return result *= scalar; } template <typename Real> GVector<Real> operator/(GVector<Real> const& v, Real scalar) { GVector<Real> result = v; return result /= scalar; } template <typename Real> GVector<Real>& operator+=(GVector<Real>& v0, GVector<Real> const& v1) { if (v0.GetSize() == v1.GetSize()) { for (int32_t i = 0; i < v0.GetSize(); ++i) { v0[i] += v1[i]; } return v0; } LogError("Mismatched sizes."); } template <typename Real> GVector<Real>& operator-=(GVector<Real>& v0, GVector<Real> const& v1) { if (v0.GetSize() == v1.GetSize()) { for (int32_t i = 0; i < v0.GetSize(); ++i) { v0[i] -= v1[i]; } return v0; } LogError("Mismatched sizes."); } template <typename Real> GVector<Real>& operator*=(GVector<Real>& v, Real scalar) { for (int32_t i = 0; i < v.GetSize(); ++i) { v[i] *= scalar; } return v; } template <typename Real> GVector<Real>& operator/=(GVector<Real>& v, Real scalar) { if (scalar != (Real)0) { Real invScalar = (Real)1 / scalar; for (int32_t i = 0; i < v.GetSize(); ++i) { v[i] *= invScalar; } return v; } LogError("Division by zero."); } // Geometric operations. The functions with 'robust' set to 'false' use // the standard algorithm for normalizing a vector by computing the length // as a square root of the squared length and dividing by it. The results // can be infinite (or NaN) if the length is zero. When 'robust' is set // to 'true', the algorithm is designed to avoid floating-point overflow // and sets the normalized vector to zero when the length is zero. template <typename Real> Real Dot(GVector<Real> const& v0, GVector<Real> const& v1) { if (v0.GetSize() == v1.GetSize()) { Real dot(0); for (int32_t i = 0; i < v0.GetSize(); ++i) { dot += v0[i] * v1[i]; } return dot; } LogError("Mismatched sizes."); } template <typename Real> Real Length(GVector<Real> const& v, bool robust = false) { if (robust) { Real maxAbsComp = std::fabs(v[0]); for (int32_t i = 1; i < v.GetSize(); ++i) { Real absComp = std::fabs(v[i]); if (absComp > maxAbsComp) { maxAbsComp = absComp; } } Real length; if (maxAbsComp > (Real)0) { GVector<Real> scaled = v / maxAbsComp; length = maxAbsComp * std::sqrt(Dot(scaled, scaled)); } else { length = (Real)0; } return length; } else { return std::sqrt(Dot(v, v)); } } template <typename Real> Real Normalize(GVector<Real>& v, bool robust = false) { if (robust) { Real maxAbsComp = std::fabs(v[0]); for (int32_t i = 1; i < v.GetSize(); ++i) { Real absComp = std::fabs(v[i]); if (absComp > maxAbsComp) { maxAbsComp = absComp; } } Real length; if (maxAbsComp > (Real)0) { v /= maxAbsComp; length = std::sqrt(Dot(v, v)); v /= length; length *= maxAbsComp; } else { length = (Real)0; for (int32_t i = 0; i < v.GetSize(); ++i) { v[i] = (Real)0; } } return length; } else { Real length = std::sqrt(Dot(v, v)); if (length > (Real)0) { v /= length; } else { for (int32_t i = 0; i < v.GetSize(); ++i) { v[i] = (Real)0; } } return length; } } // Gram-Schmidt orthonormalization to generate orthonormal vectors from // the linearly independent inputs. 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, // 1 <= numElements <= N and v[0] through v[numElements-1] must be // initialized. On output, the vectors v[0] through v[numElements-1] // form an orthonormal set. template <typename Real> Real Orthonormalize(int32_t numInputs, GVector<Real>* v, bool robust = false) { if (v && 1 <= numInputs && numInputs <= v[0].GetSize()) { for (int32_t i = 1; i < numInputs; ++i) { if (v[0].GetSize() != v[i].GetSize()) { LogError("Mismatched sizes."); } } Real minLength = Normalize(v[0], robust); for (int32_t i = 1; i < numInputs; ++i) { for (int32_t j = 0; j < i; ++j) { Real dot = Dot(v[i], v[j]); v[i] -= v[j] * dot; } Real length = Normalize(v[i], robust); if (length < minLength) { minLength = length; } } return minLength; } LogError("Invalid input."); } // Compute the axis-aligned bounding box of the vectors. The return value is // 'true' iff the inputs are valid, in which case vmin and vmax have valid // values. template <typename Real> bool ComputeExtremes(int32_t numVectors, GVector<Real> const* v, GVector<Real>& vmin, GVector<Real>& vmax) { if (v && numVectors > 0) { for (int32_t i = 1; i < numVectors; ++i) { if (v[0].GetSize() != v[i].GetSize()) { LogError("Mismatched sizes."); } } int32_t const size = v[0].GetSize(); vmin = v[0]; vmax = vmin; for (int32_t j = 1; j < numVectors; ++j) { GVector<Real> const& vec = v[j]; for (int32_t i = 0; i < size; ++i) { if (vec[i] < vmin[i]) { vmin[i] = vec[i]; } else if (vec[i] > vmax[i]) { vmax[i] = vec[i]; } } } return true; } LogError("Invalid input."); } // Lift n-tuple v to homogeneous (n+1)-tuple (v,last). template <typename Real> GVector<Real> HLift(GVector<Real> const& v, Real last) { int32_t const size = v.GetSize(); GVector<Real> result(size + 1); for (int32_t i = 0; i < size; ++i) { result[i] = v[i]; } result[size] = last; return result; } // Project homogeneous n-tuple v = (u,v[n-1]) to (n-1)-tuple u. template <typename Real> GVector<Real> HProject(GVector<Real> const& v) { int32_t const size = v.GetSize(); if (size > 1) { GVector<Real> result(size - 1); for (int32_t i = 0; i < size - 1; ++i) { result[i] = v[i]; } return result; } else { return GVector<Real>(); } } // Lift n-tuple v = (w0,w1) to (n+1)-tuple u = (w0,u[inject],w1). By // inference, w0 is a (inject)-tuple [nonexistent when inject=0] and w1 // is a (n-inject)-tuple [nonexistent when inject=n]. template <typename Real> GVector<Real> Lift(GVector<Real> const& v, int32_t inject, Real value) { int32_t const size = v.GetSize(); GVector<Real> result(size + 1); int32_t i; for (i = 0; i < inject; ++i) { result[i] = v[i]; } result[i] = value; int32_t j = i; for (++j; i < size; ++i, ++j) { result[j] = v[i]; } return result; } // Project n-tuple v = (w0,v[reject],w1) to (n-1)-tuple u = (w0,w1). By // inference, w0 is a (reject)-tuple [nonexistent when reject=0] and w1 // is a (n-1-reject)-tuple [nonexistent when reject=n-1]. template <typename Real> GVector<Real> Project(GVector<Real> const& v, int32_t reject) { int32_t const size = v.GetSize(); if (size > 1) { GVector<Real> result(size - 1); for (int32_t i = 0, j = 0; i < size - 1; ++i, ++j) { if (j == reject) { ++j; } result[i] = v[j]; } return result; } else { return GVector<Real>(); } } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ExtremalQuery3BSP.h
.h
16,249
431
// 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/ExtremalQuery3.h> #include <Mathematics/RangeIteration.h> #include <Mathematics/VETManifoldMesh.h> #include <stack> #include <queue> namespace gte { template <typename Real> class ExtremalQuery3BSP : public ExtremalQuery3<Real> { public: // Construction. ExtremalQuery3BSP(Polyhedron3<Real> const& polytope) : ExtremalQuery3<Real>(polytope), mTriToNormal{}, mNodes{}, mTreeDepth(0) { // Create the adjacency information for the polytope. VETManifoldMesh mesh; auto const& indices = this->mPolytope.GetIndices(); size_t const numTriangles = indices.size() / 3; for (size_t t = 0; t < numTriangles; ++t) { std::array<int32_t, 3> V = { 0, 0, 0 }; for (size_t j = 0; j < 3; ++j) { V[j] = indices[3 * t + j]; } auto triangle = mesh.Insert(V[0], V[1], V[2]); mTriToNormal.insert(std::make_pair(triangle, static_cast<int32_t>(t))); } // Create the set of unique arcs which are used to create the BSP // tree. std::multiset<SphericalArc> arcs; CreateSphericalArcs(mesh, arcs); // Create the BSP tree to be used in the extremal query. CreateBSPTree(arcs); } // Disallow copying and assignment. ExtremalQuery3BSP(ExtremalQuery3BSP const&) = delete; ExtremalQuery3BSP& operator=(ExtremalQuery3BSP const&) = delete; // Compute the extreme vertices in the specified direction and return // the indices of the vertices in the polyhedron vertex array. virtual void GetExtremeVertices(Vector3<Real> const& direction, int32_t& positiveDirection, int32_t& negativeDirection) override { // Do a nonrecursive depth-first search of the BSP tree to // determine spherical polygon contains the incoming direction D. // Index 0 is the root of the BSP tree. int32_t current = 0; while (current >= 0) { SphericalArc& node = mNodes[current]; int32_t sign = gte::isign(Dot(direction, node.normal)); if (sign >= 0) { current = node.posChild; if (current == -1) { // At a leaf node. positiveDirection = node.posVertex; } } else { current = node.negChild; if (current == -1) { // At a leaf node. positiveDirection = node.negVertex; } } } // Do a nonrecursive depth-first search of the BSP tree to // determine spherical polygon contains the reverse incoming // direction -D. current = 0; // the root of the BSP tree while (current >= 0) { SphericalArc& node = mNodes[current]; int32_t sign = gte::isign(Dot(direction, node.normal)); if (sign <= 0) { current = node.posChild; if (current == -1) { // At a leaf node. negativeDirection = node.posVertex; } } else { current = node.negChild; if (current == -1) { // At a leaf node. negativeDirection = node.negVertex; } } } } // Tree statistics. inline int32_t GetNumNodes() const { return static_cast<int32_t>(mNodes.size()); } inline int32_t GetTreeDepth() const { return mTreeDepth; } private: class SphericalArc { public: // Construction. SphericalArc() : nIndex{ -1, -1 }, separation(0), normal(Vector3<Real>::Zero()), posVertex(-1), negVertex(-1), posChild(-1), negChild(-1) { } // The arcs are stored in a multiset ordered by increasing // separation. The multiset will be traversed in reverse order. // This heuristic is designed to create BSP trees whose top-most // nodes can eliminate as many arcs as possible during an extremal // query. bool operator<(SphericalArc const& arc) const { return separation < arc.separation; } // Indices N[] into the face normal array for the endpoints of the // arc. std::array<int32_t, 2> nIndex; // The number of arcs in the path from normal N[0] to normal N[1]. // For spherical polygon edges, the number is 1. The number is 2 // or larger for bisector arcs of the spherical polygon. int32_t separation; // The normal is Cross(FaceNormal[N[0]],FaceNormal[N[1]]). Vector3<Real> normal; // Indices into the vertex array for the extremal points for the // two regions sharing the arc. As the arc is traversed from // normal N[0] to normal N[1], PosVertex is the index for the // extreme vertex to the left of the arc and NegVertex is the // index for the extreme vertex to the right of the arc. int32_t posVertex, negVertex; // Support for BSP trees stored as contiguous nodes in an array. int32_t posChild, negChild; }; typedef VETManifoldMesh::Triangle Triangle; void SortAdjacentTriangles(int32_t vIndex, std::unordered_set<Triangle*> const& tAdj, std::vector<Triangle*>& tAdjSorted) { // Copy the set of adjacent triangles into a vector container. int32_t const numTriangles = static_cast<int32_t>(tAdj.size()); tAdjSorted.resize(tAdj.size()); // Traverse the triangles adjacent to vertex V using edge-triangle // adjacency information to produce a sorted array of adjacent // triangles. Triangle* tri = *tAdj.begin(); for (int32_t i = 0; i < numTriangles; ++i) { for (int32_t prev = 2, curr = 0; curr < 3; prev = curr++) { if (tri->V[curr] == vIndex) { tAdjSorted[i] = tri; tri = tri->T[prev]; break; } } } } void CreateSphericalArcs(VETManifoldMesh& mesh, std::multiset<SphericalArc>& arcs) { int32_t const prev[3] = { 2, 0, 1 }; int32_t const next[3] = { 1, 2, 0 }; for (auto const& element : mesh.GetEdges()) { auto const& edge = element.second; // VS 2019 16.8.1 generates LNT1006 "Local variable is not // initialized." Incorrect, because the default constructor // initializes all the members. SphericalArc arc; arc.nIndex[0] = mTriToNormal[edge->T[0]]; arc.nIndex[1] = mTriToNormal[edge->T[1]]; arc.separation = 1; arc.normal = Cross(this->mFaceNormals[arc.nIndex[0]], this->mFaceNormals[arc.nIndex[1]]); Triangle* adj = edge->T[0]; int32_t j; for (j = 0; j < 3; ++j) { if (adj->V[j] != edge->V[0] && adj->V[j] != edge->V[1]) { arc.posVertex = adj->V[prev[j]]; arc.negVertex = adj->V[next[j]]; break; } } LogAssert(j < 3, "Unexpected condition."); arcs.insert(arc); } CreateSphericalBisectors(mesh, arcs); } void CreateSphericalBisectors(VETManifoldMesh& mesh, std::multiset<SphericalArc>& arcs) { std::queue<std::pair<int32_t, int32_t>> queue; for (auto const& element : mesh.GetVertices()) { // Sort the normals into a counterclockwise spherical polygon // when viewed from outside the sphere. auto const& vertex = element.second; int32_t const vIndex = vertex->V; std::vector<Triangle*> tAdjSorted; SortAdjacentTriangles(vIndex, vertex->TAdjacent, tAdjSorted); int32_t const numTriangles = static_cast<int32_t>(vertex->TAdjacent.size()); queue.push(std::make_pair(0, numTriangles)); while (!queue.empty()) { std::pair<int32_t, int32_t> item = queue.front(); queue.pop(); int32_t i0 = item.first, i1 = item.second; int32_t separation = i1 - i0; if (separation > 1 && separation != numTriangles - 1) { if (i1 < numTriangles) { // VS 2019 16.8.1 generates LNT1006 "Local // variable is not initialized." Incorrect, // because the default constructor initializes // all the members. SphericalArc arc; arc.nIndex[0] = mTriToNormal[tAdjSorted[i0]]; arc.nIndex[1] = mTriToNormal[tAdjSorted[i1]]; arc.separation = separation; arc.normal = Cross(this->mFaceNormals[arc.nIndex[0]], this->mFaceNormals[arc.nIndex[1]]); arc.posVertex = vIndex; arc.negVertex = vIndex; arcs.insert(arc); } int32_t imid = (i0 + i1 + 1) / 2; if (imid != i1) { queue.push(std::make_pair(i0, imid)); queue.push(std::make_pair(imid, i1)); } } } } } void CreateBSPTree(std::multiset<SphericalArc>& arcs) { // The tree has at least a root. mTreeDepth = 1; for (auto const& arc : gte::reverse(arcs)) { InsertArc(arc); } // The leaf nodes are not counted in the traversal of InsertArc. // The depth must be incremented to account for leaves. ++mTreeDepth; } void InsertArc(SphericalArc const& arc) { // The incoming arc is stored at the end of the nodes array. if (mNodes.size() > 0) { // Do a nonrecursive depth-first search of the current BSP // tree to place the incoming arc. Index 0 is the root of the // BSP tree. std::stack<int32_t> candidates; candidates.push(0); while (!candidates.empty()) { int32_t current = candidates.top(); candidates.pop(); SphericalArc* node = &mNodes[current]; int32_t sign0; if (arc.nIndex[0] == node->nIndex[0] || arc.nIndex[0] == node->nIndex[1]) { sign0 = 0; } else { Real dot = Dot(this->mFaceNormals[arc.nIndex[0]], node->normal); sign0 = gte::isign(dot); } int32_t sign1; if (arc.nIndex[1] == node->nIndex[0] || arc.nIndex[1] == node->nIndex[1]) { sign1 = 0; } else { Real dot = Dot(this->mFaceNormals[arc.nIndex[1]], node->normal); sign1 = gte::isign(dot); } int32_t doTest = 0; if (sign0 * sign1 < 0) { // The new arc straddles the current arc, so propagate // it to both child nodes. doTest = 3; } else if (sign0 > 0 || sign1 > 0) { // The new arc is on the positive side of the current // arc. doTest = 1; } else if (sign0 < 0 || sign1 < 0) { // The new arc is on the negative side of the current // arc. doTest = 2; } // else: sign0 = sign1 = 0, in which case no propagation // is needed because the current BSP node will handle the // correct partitioning of the arcs during extremal // queries. int32_t depth; if (doTest & 1) { if (node->posChild != -1) { candidates.push(node->posChild); depth = static_cast<int32_t>(candidates.size()); if (depth > mTreeDepth) { mTreeDepth = depth; } } else { node->posChild = static_cast<int32_t>(mNodes.size()); mNodes.push_back(arc); // The push_back can cause a reallocation, so the // current pointer must be refreshed. node = &mNodes[current]; } } if (doTest & 2) { if (node->negChild != -1) { candidates.push(node->negChild); depth = static_cast<int32_t>(candidates.size()); if (depth > mTreeDepth) { mTreeDepth = depth; } } else { node->negChild = static_cast<int32_t>(mNodes.size()); mNodes.push_back(arc); } } } } else { // root node mNodes.push_back(arc); } } // Lookup table for indexing into mFaceNormals. std::map<Triangle*, int32_t> mTriToNormal; // Fixed-size storage for the BSP nodes. std::vector<SphericalArc> mNodes; int32_t mTreeDepth; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ContPointInPolygon2.h
.h
6,792
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/Vector2.h> // Given a polygon as an order list of vertices (x[i],y[i]) for 0 <= i < N // and a test point (xt,yt), return 'true' if (xt,yt) is in the polygon and // 'false' if it is not. All queries require that the number of vertices // satisfies N >= 3. namespace gte { template <typename Real> class PointInPolygon2 { public: // The class object stores a copy of 'points', so be careful about // the persistence of 'points' when you have created a // PointInPolygon2 object. PointInPolygon2(int32_t numPoints, Vector2<Real> const* points) : mNumPoints(numPoints), mPoints(points) { } // Simple polygons (ray-intersection counting). bool Contains(Vector2<Real> const& p) const { bool inside = false; for (int32_t i = 0, j = mNumPoints - 1; i < mNumPoints; j = i++) { Vector2<Real> const& U0 = mPoints[i]; Vector2<Real> const& U1 = mPoints[j]; Real rhs, lhs; if (p[1] < U1[1]) // U1 above ray { if (U0[1] <= p[1]) // U0 on or below ray { lhs = (p[1] - U0[1]) * (U1[0] - U0[0]); rhs = (p[0] - U0[0]) * (U1[1] - U0[1]); if (lhs > rhs) { inside = !inside; } } } else if (p[1] < U0[1]) // U1 on or below ray, U0 above ray { lhs = (p[1] - U0[1]) * (U1[0] - U0[0]); rhs = (p[0] - U0[0]) * (U1[1] - U0[1]); if (lhs < rhs) { inside = !inside; } } } return inside; } // Algorithms for convex polygons. The input polygons must have // vertices in counterclockwise order. // O(N) algorithm (which-side-of-edge tests) bool ContainsConvexOrderN(Vector2<Real> const& p) const { for (int32_t i1 = 0, i0 = mNumPoints - 1; i1 < mNumPoints; i0 = i1++) { Real nx = mPoints[i1][1] - mPoints[i0][1]; Real ny = mPoints[i0][0] - mPoints[i1][0]; Real dx = p[0] - mPoints[i0][0]; Real dy = p[1] - mPoints[i0][1]; if (nx * dx + ny * dy > (Real)0) { return false; } } return true; } // O(log N) algorithm (bisection and recursion, like BSP tree) bool ContainsConvexOrderLogN(Vector2<Real> const& p) const { return SubContainsPoint(p, 0, 0); } // The polygon must have exactly four vertices. This method is like // the O(log N) and uses three which-side-of-segment test instead of // four which-side-of-edge tests. If the polygon does not have four // vertices, the function returns false. bool ContainsQuadrilateral(Vector2<Real> const& p) const { if (mNumPoints != 4) { return false; } Real nx = mPoints[2][1] - mPoints[0][1]; Real ny = mPoints[0][0] - mPoints[2][0]; Real dx = p[0] - mPoints[0][0]; Real dy = p[1] - mPoints[0][1]; if (nx * dx + ny * dy > (Real)0) { // P potentially in <V0,V1,V2> nx = mPoints[1][1] - mPoints[0][1]; ny = mPoints[0][0] - mPoints[1][0]; if (nx * dx + ny * dy > (Real)0.0) { return false; } nx = mPoints[2][1] - mPoints[1][1]; ny = mPoints[1][0] - mPoints[2][0]; dx = p[0] - mPoints[1][0]; dy = p[1] - mPoints[1][1]; if (nx * dx + ny * dy > (Real)0) { return false; } } else { // P potentially in <V0,V2,V3> nx = mPoints[0][1] - mPoints[3][1]; ny = mPoints[3][0] - mPoints[0][0]; if (nx * dx + ny * dy > (Real)0) { return false; } nx = mPoints[3][1] - mPoints[2][1]; ny = mPoints[2][0] - mPoints[3][0]; dx = p[0] - mPoints[3][0]; dy = p[1] - mPoints[3][1]; if (nx * dx + ny * dy > (Real)0) { return false; } } return true; } private: // For recursion in ContainsConvexOrderLogN. bool SubContainsPoint(Vector2<Real> const& p, int32_t i0, int32_t i1) const { Real nx, ny, dx, dy; int32_t diff = i1 - i0; if (diff == 1 || (diff < 0 && diff + mNumPoints == 1)) { nx = mPoints[i1][1] - mPoints[i0][1]; ny = mPoints[i0][0] - mPoints[i1][0]; dx = p[0] - mPoints[i0][0]; dy = p[1] - mPoints[i0][1]; return nx * dx + ny * dy <= (Real)0; } // Bisect the index range. int32_t mid; if (i0 < i1) { mid = (i0 + i1) >> 1; } else { mid = (i0 + i1 + mNumPoints) >> 1; if (mid >= mNumPoints) { mid -= mNumPoints; } } // Determine which side of the splitting line contains the point. nx = mPoints[mid][1] - mPoints[i0][1]; ny = mPoints[i0][0] - mPoints[mid][0]; dx = p[0] - mPoints[i0][0]; dy = p[1] - mPoints[i0][1]; if (nx * dx + ny * dy > (Real)0) { // P potentially in <V(i0),V(i0+1),...,V(mid-1),V(mid)> return SubContainsPoint(p, i0, mid); } else { // P potentially in <V(mid),V(mid+1),...,V(i1-1),V(i1)> return SubContainsPoint(p, mid, i1); } } int32_t mNumPoints; Vector2<Real> const* mPoints; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Logger.h
.h
1,861
40
// 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 <stdexcept> #include <string> // Generate exceptions about unexpected conditions. The messages can be // intercepted in a 'catch' block and processed as desired. The 'exception' // in the macros is one of the standard exceptions provided by C++. You can // also derive your own exception class from those provided by C++ and pass // those via the macros. // The report uses the current source file, function and line on which the // macro is expanded. #define GTE_ASSERT(condition, exception, message) \ if (!(condition)) { throw exception(std::string(__FILE__) + "(" + std::string(__FUNCTION__) + "," + std::to_string(__LINE__) + "): " + message + "\n"); } #define GTE_ERROR(exception, message) \ { throw exception(std::string(__FILE__) + "(" + std::string(__FUNCTION__) + "," + std::to_string(__LINE__) + "): " + message + "\n"); } // The report uses the specified source file, function and line. The file // and function are type 'char const*' and the line is type 'int32_t'. #define GTE_ASSERT_INDIRECT(condition, exception, file, function, line, message) \ if (!(condition)) { throw exception(std::string(file) + "(" + std::string(function) + "," + std::to_string(line) + "): " + message + "\n"); } #define GTE_ERROR_INDIRECT(exception, file, function, line, message) \ { throw exception(std::string(file) + "(" + std::string(function) + "," + std::to_string(line) + "): " + message + "\n"); } #define LogAssert(condition, message) \ GTE_ASSERT(condition, std::runtime_error, message) #define LogError(message) \ GTE_ERROR(std::runtime_error, message);
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ConstrainedDelaunay2.h
.h
51,749
1,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/Delaunay2.h> // Compute the Delaunay triangulation of the input point and then insert // edges that are constrained to be in the triangulation. For each such // edge, a retriangulation of the triangle strip containing the edge is // required. NOTE: If two constrained edges overlap at a point that is // an interior point of each edge, the second insertion will interfere // with the retriangulation of the first edge. Although the code here // will do what is requested, a pair of such edges usually indicates the // upstream process that generated the edges is not doing what it should. namespace gte { // The variadic template declaration supports the class // ConstrainedDelaunay2<InputType, ComputeType>, which is deprecated and // will be removed in a future release. The declaration also supports the // replacement class ConstrainedDelaunay2<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 ConstrainedDelaunay2 {}; } namespace gte { // The code has LogAssert statements that throw exceptions when triggered. // For a correct algorithm using exact arithmetic, these should not occur. // When using floating-point arithmetic, it is possible that rounding errors // lead to a malformed triangulation. It is strongly recommended that you // choose ComputeType to be a rational type. No divisions are required, // either in Delaunay2 or ConstrainedDelaunay2, so you may choose the type // to be BSNumber<UInteger> rather than BSRational<UInteger>. However, if // you choose ComputeType to be 'float' or 'double', you should call the // Insert(...) function in a try-catch block and take appropriate action. // // The worst-case choices of N for ComputeType of type BSNumber or BSRational // with integer storage UIntegerFP32<N> are listed in the next table. The // expression requiring the most bits is in the last else-block of ComputePSD. // We recommend using only BSNumber, because no divisions are performed in the // insertion computations. // // input type | compute type | ComputePSD | Delaunay | N // -----------+--------------+------------+----------+------ // float | BSNumber | 70 | 35 | 70 // double | BSNumber | 525 | 263 | 525 // float | BSRational | 555 | 573 | 573 // double | BSRational | 4197 | 4329 | 4329 // // The recommended ComputeType is BSNumber<UIntegerFP32<70>> for the // InputType 'float' and BSNumber<UIntegerFP32<526>> for the InputType // 'double' (525 rounded up to 526 for the bits array size to be a // multiple of 8 bytes.) template <typename InputType, typename ComputeType> class // [[deprecated("Use ConstrainedDelaunay2<InputType> instead.")]] ConstrainedDelaunay2<InputType, ComputeType> : public Delaunay2<InputType, ComputeType> { public: // The class is a functor to support computing the constrained // Delaunay triangulation of multiple data sets using the same class // object. virtual ~ConstrainedDelaunay2() = default; ConstrainedDelaunay2() : Delaunay2<InputType, ComputeType>() { } // This operator computes the Delaunay triangulation only. Read the // Delaunay2 constructor comments about 'vertices' and 'epsilon'. For // ComputeType chosen to be a rational type, pass zero for epsilon. bool operator()(int32_t numVertices, Vector2<InputType> const* vertices, InputType epsilon) { return Delaunay2<InputType, ComputeType>::operator()(numVertices, vertices, epsilon); } // The 'edge' is the constrained edge to be inserted into the // triangulation. If that edge is already in the triangulation, the // function returns without any retriangulation and 'partitionedEdge' // contains the input 'edge'. If 'edge' is coincident with 1 or more // edges already in the triangulation, 'edge' is partitioned into // subedges which are then inserted. It is also possible that 'edge' // does not overlap already existing edges in the triangulation but // has interior points that are vertices in the triangulation; in // this case, 'edge' is partitioned and the subedges are inserted. // In either case, 'partitionEdge' is an ordered list of indices // into the triangulation vertices that are on the edge. It is // guaranteed that partitionedEdge.front() = edge[0] and // partitionedEdge.back() = edge[1]. void Insert(std::array<int32_t, 2> edge, std::vector<int32_t>& partitionedEdge) { LogAssert( edge[0] != edge[1] && 0 <= edge[0] && edge[0] < this->mNumVertices && 0 <= edge[1] && edge[1] < this->mNumVertices, "Invalid edge."); // The partitionedEdge vector stores the endpoints of the incoming // edge if that edge does not contain interior points that are // vertices of the Delaunay triangulation. If the edge contains // one or more vertices in its interior, the edge is partitioned // into subedges, each subedge having vertex endpoints but no // interior point is a vertex. The partition is stored in the // partitionedEdge vector. std::vector<std::array<int32_t, 2>> partition; // When using exact arithmetic, a while(!edgeConsumed) loop // suffices. When using floating-point arithmetic (which you // should not do for CDT), guard against an infinite loop. bool edgeConsumed = false; size_t const numTriangles = this->mGraph.GetTriangles().size(); size_t t; for (t = 0; t < numTriangles && !edgeConsumed; ++t) { EdgeKey<false> ekey(edge[0], edge[1]); if (this->mGraph.GetEdges().find(ekey) != this->mGraph.GetEdges().end()) { // The edge already exists in the triangulation. mInsertedEdges.insert(ekey); partition.push_back(edge); break; } // Get the link edges for the vertex edge[0]. These edges are // opposite the link vertex. std::vector<std::array<int32_t, 2>> linkEdges; GetLinkEdges(edge[0], linkEdges); // Determine which link triangle contains the to-be-inserted // edge. for (auto const& linkEdge : linkEdges) { // Compute on which side of the to-be-inserted edge the // link vertices live. The triangles are not degenerate, // so it is not possible for sign0 = sign1 = 0. int32_t v0 = linkEdge[0]; int32_t v1 = linkEdge[1]; int32_t sign0 = this->mQuery.ToLine(v0, edge[0], edge[1]); int32_t sign1 = this->mQuery.ToLine(v1, edge[0], edge[1]); if (sign0 >= 0 && sign1 <= 0) { if (sign0 > 0) { if (sign1 < 0) { // The triangle <edge[0], v0, v1> strictly // contains the to-be-inserted edge. Gather // the triangles in the triangle strip // containing the edge. edgeConsumed = ProcessTriangleStrip(edge, v0, v1, partition); } else // sign1 == 0 && sign0 > 0 { // The to-be-inserted edge is coincident with // the triangle edge <edge[0], v1>, and it is // guaranteed that the vertex at v1 is an // interior point of <edge[0],edge[1]> because // we previously tested whether edge[] is in // the triangulation. edgeConsumed = ProcessCoincidentEdge(edge, v1, partition); } } else // sign0 == 0 && sign1 < 0 { // The to-be-inserted edge is coincident with // the triangle edge <edge[0], v0>, and it is // guaranteed that the vertex at v0 is an // interior point of <edge[0],edge[1]> because // we previously tested whether edge[] is in // the triangulation. edgeConsumed = ProcessCoincidentEdge(edge, v0, partition); } break; } } } // If the following assertion is triggered, ComputeType was chosen // to be 'float' or 'double'. Floating-point rounding errors led to // misclassification of signs. The linkEdges-loop exited without // ever calling the ProcessTriangleStrip or ProcessCoincidentEdge // functions. LogAssert(partition.size() > 0, CDTMessage()); partitionedEdge.resize(partition.size() + 1); for (size_t i = 0; i < partition.size(); ++i) { partitionedEdge[i] = partition[i][0]; } partitionedEdge.back() = partition.back()[1]; } // All edges inserted via the Insert(...) call are stored for use // by the caller. If any edge passed to Insert(...) is partitioned // into subedges, the subedges are stored but not the original edge. std::set<EdgeKey<false>> const& GetInsertedEdges() const { return mInsertedEdges; } // The interface functions to the base class Delaunay2 are valid, so // access to any Delaunay information is allowed. Perhaps the most // important member function is GetGraph() that returns a reference // to the ETManifoldMesh that represents the constrained Delaunay // triangulation. NOTE: If you want access to the compact arrays // via GetIndices(t, indices[]) or GetAdjacencies(t, adjacents[]), // you must first call UpdateIndicesAdjacencies() to ensure that the // compact arrays are synchonized with the Delaunay graph. private: using Vertex = VETManifoldMesh::Vertex; using Edge = VETManifoldMesh::Edge; using Triangle = VETManifoldMesh::Triangle; // For a vertex at index v, return the edges of the adjacent triangles, // each triangle having v as a vertex and the returned edge is // opposite v. void GetLinkEdges(int32_t v, std::vector<std::array<int32_t, 2>>& linkEdges) { auto const& vmap = this->mGraph.GetVertices(); auto viter = vmap.find(v); LogAssert(viter != vmap.end(), "Failed to find vertex in graph."); auto vertex = viter->second.get(); LogAssert(vertex != nullptr, "Unexpected condition."); for (auto const& linkTri : vertex->TAdjacent) { size_t j; for (j = 0; j < 3; ++j) { if (linkTri->V[j] == vertex->V) { linkEdges.push_back({ linkTri->V[(j + 1) % 3], linkTri->V[(j + 2) % 3] }); break; } } LogAssert(j < 3, "Unexpected condition."); } } // The return value is 'true' if the edge did not have to be // subdivided because it has an interior point that is a vertex. // The return value is 'false' if it does have such a point, in // which case edge[0] is updated to the index of that vertex. The // caller must process the new edge. bool ProcessTriangleStrip(std::array<int32_t, 2>& edge, int32_t v0, int32_t v1, std::vector<std::array<int32_t, 2>>& partitionedEdge) { bool edgeConsumed = true; std::array<int32_t, 2> localEdge = edge; // Locate and store the triangles in the triangle strip containing // the edge. std::vector<TriangleKey<true>> tristrip; tristrip.emplace_back(localEdge[0], v0, v1); auto const& tmap = this->mGraph.GetTriangles(); auto titer = tmap.find(TriangleKey<true>(localEdge[0], v0, v1)); LogAssert(titer != tmap.end(), CDTMessage()); auto tri = titer->second.get(); LogAssert(tri, CDTMessage()); // Keep track of the right and left polylines that bound the // triangle strip. These polylines can have coincident edges. // In particular, this happens when the current triangle in the // strip shares an edge with a previous triangle in the strip // and the previous triangle is not the immediate predecessor // to the current triangle. std::vector<int32_t> rightPolygon, leftPolygon; rightPolygon.push_back(localEdge[0]); rightPolygon.push_back(v0); leftPolygon.push_back(localEdge[0]); leftPolygon.push_back(v1); // When using exact arithmetic, a for(;;) loop suffices. When // using floating-point arithmetic (which you should really not // do for CDT), guard against an infinite loop. size_t const numTriangles = tmap.size(); size_t t; for (t = 0; t < numTriangles; ++t) { // The current triangle is tri and has edge <v0,v1>. Get // the triangle adj that is adjacent to tri via this edge. auto adj = tri->GetAdjacentOfEdge(v0, v1); LogAssert(adj, CDTMessage()); tristrip.emplace_back(adj->V[0], adj->V[1], adj->V[2]); // Get the vertex of adj that is opposite edge <v0,v1>. int32_t vOpposite = 0; bool found = adj->GetOppositeVertexOfEdge(v0, v1, vOpposite); LogAssert(found, CDTMessage()); if (vOpposite == localEdge[1]) { // The triangle strip containing the edge is complete. break; } // The next triangle in the strip depends on whether the // opposite vertex is left-of the edge, right-of the edge // or on the edge. int32_t querySign = this->mQuery.ToLine(vOpposite, localEdge[0], localEdge[1]); if (querySign > 0) { tri = adj; v0 = vOpposite; rightPolygon.push_back(v0); } else if (querySign < 0) { tri = adj; v1 = vOpposite; leftPolygon.push_back(v1); } else { // The to-be-inserted edge contains an interior point that // is also a vertex in the triangulation. The edge must be // subdivided. The first subedge is in a triangle strip // that is processed by code below that is outside the // loop. The second subedge must be processed by the // caller. localEdge[1] = vOpposite; edge[0] = vOpposite; edgeConsumed = false; break; } } LogAssert(t < numTriangles, CDTMessage()); // Insert the final endpoint of the to-be-inserted edge. rightPolygon.push_back(localEdge[1]); leftPolygon.push_back(localEdge[1]); // The retriangulation depends on counterclockwise ordering of // the boundary right and left polygons. The right polygon is // already counterclockwise ordered. The left polygon is // clockwise ordered, so reverse it. std::reverse(leftPolygon.begin(), leftPolygon.end()); // Update the inserted edges. mInsertedEdges.insert(EdgeKey<false>(localEdge[0], localEdge[1])); partitionedEdge.push_back(localEdge); // Remove the triangle strip from the full triangulation. This // must occur before the retriangulation which inserts new // triangles into the full triangulation. for (auto const& tkey : tristrip) { this->mGraph.Remove(tkey.V[0], tkey.V[1], tkey.V[2]); } // Retriangulate the tristrip region. Retriangulate(leftPolygon); Retriangulate(rightPolygon); return edgeConsumed; } // Process a to-be-inserted edge that is coincident with an already // existing triangulation edge. bool ProcessCoincidentEdge(std::array<int32_t, 2>& edge, int32_t v, std::vector<std::array<int32_t, 2>>& partitionedEdge) { mInsertedEdges.insert(EdgeKey<false>(edge[0], v)); partitionedEdge.push_back({ edge[0], v }); edge[0] = v; bool edgeConsumed = (v == edge[1]); return edgeConsumed; } // Retriangulate the polygon via a bisection-like method that finds // vertices closest to the current polygon base edge. The function // is naturally recursive, but simulated recursion is used to avoid // a large program stack by instead using the heap. void Retriangulate(std::vector<int32_t> const& polygon) { std::vector<std::array<size_t, 2>> stack(polygon.size()); int32_t top = -1; stack[++top] = { 0, polygon.size() - 1 }; while (top != -1) { std::array<size_t, 2> i = stack[top--]; if (i[1] > i[0] + 1) { // Get the vertex indices for the specified i-values. int32_t v0 = polygon[i[0]]; int32_t v1 = polygon[i[1]]; // Select isplit in the index range [i[0]+1,i[1]-1] so // that the vertex at index polygon[isplit] attains the // minimum distance to the edge with vertices at the // indices polygon[i[0]] and polygon[i[1]]. size_t isplit = SelectSplit(polygon, i[0], i[1]); int32_t vsplit = polygon[isplit]; // Insert the triangle into the Delaunay graph. this->mGraph.Insert(v0, vsplit, v1); stack[++top] = { i[0], isplit }; stack[++top] = { isplit, i[1] }; } } } // Determine the polygon vertex with index strictly between i0 and i1 // that minimizes the pseudosquared distance from that vertex to the // line segment whose endpoints are at indices i0 and i1. size_t SelectSplit(std::vector<int32_t> const& polygon, size_t i0, size_t i1) { size_t i2; if (i1 == i0 + 2) { // This is the only candidate. i2 = i0 + 1; } else // i1 - i0 > 2 { // Select the index i2 in [i0+1,i1-1] for which the distance // from the vertex v2 at i2 to the edge <v0,v1> is minimized. // To allow exact arithmetic, use a pseudosquared distance // that avoids divisions and square roots. i2 = i0 + 1; int32_t v0 = polygon[i0]; int32_t v1 = polygon[i1]; int32_t v2 = polygon[i2]; // Precompute some common values that are used in all calls // to ComputePSD. Vector2<ComputeType> const& ctv0 = this->mComputeVertices[v0]; Vector2<ComputeType> const& ctv1 = this->mComputeVertices[v1]; Vector2<ComputeType> V1mV0 = ctv1 - ctv0; ComputeType sqrlen10 = Dot(V1mV0, V1mV0); // Locate the minimum pseudosquared distance. ComputeType minpsd = ComputePSD(v0, v1, v2, V1mV0, sqrlen10); for (size_t i = i2 + 1; i < i1; ++i) { v2 = polygon[i]; ComputeType psd = ComputePSD(v0, v1, v2, V1mV0, sqrlen10); if (psd < minpsd) { minpsd = psd; i2 = i; } } } return i2; } // Compute a pseudosquared distance from the vertex at v2 to the edge // <v0,v1>. The result is exact for rational arithmetic and does not // involve division. This allows ComputeType to be BSNumber<UInteger> // rather than BSRational<UInteger>, which leads to better // performance. ComputeType ComputePSD(int32_t v0, int32_t v1, int32_t v2, Vector2<ComputeType> const& V1mV0, ComputeType const& sqrlen10) { ComputeType const zero = static_cast<ComputeType>(0); Vector2<ComputeType> const& ctv0 = this->mComputeVertices[v0]; Vector2<ComputeType> const& ctv1 = this->mComputeVertices[v1]; Vector2<ComputeType> const& ctv2 = this->mComputeVertices[v2]; Vector2<ComputeType> V2mV0 = ctv2 - ctv0; ComputeType dot1020 = Dot(V1mV0, V2mV0); ComputeType psd; if (dot1020 <= zero) { ComputeType sqrlen20 = Dot(V2mV0, V2mV0); psd = sqrlen10 * sqrlen20; } else { Vector2<ComputeType> V2mV1 = ctv2 - ctv1; ComputeType dot1021 = Dot(V1mV0, V2mV1); if (dot1021 >= zero) { ComputeType sqrlen21 = Dot(V2mV1, V2mV1); psd = sqrlen10 * sqrlen21; } else { ComputeType sqrlen20 = Dot(V2mV0, V2mV0); psd = sqrlen10 * sqrlen20 - dot1020 * dot1020; } } return psd; } // All edges inserted via the Insert(...) call are stored for use // by the caller. If any edge passed to Insert(...) is partitioned // into subedges, the subedges are inserted into this member. std::set<EdgeKey<false>> mInsertedEdges; private: // All LogAssert statements other than the first one in the Insert // call possibly can occur when ComputeType is chosen to be 'float' // or 'double' rather than an arbitrary-precision type. This function // encapsulates a message that is included in the logging and in the // thrown exception explaining that floating-point rounding errors // are most likely the problem and that you should consider using // arbitrary precision for the ComputeType. template <typename Dummy = ComputeType> static typename std::enable_if<!is_arbitrary_precision<Dummy>::value, std::string>::type CDTMessage() { return R"( ComputeType is a floating-point type. The assertions can be triggered because of rounding errors. Repeat the call to operator() using ComputeType the type BSNumber<UIntegerAP32>. If no assertion is triggered, the problem was most likely due to rounding errors. If an assertion is triggered, please file a bug report and provide the input dataset to the operator()(...) function. )"; } template <typename Dummy = ComputeType> static typename std::enable_if<is_arbitrary_precision<Dummy>::value, std::string>::type CDTMessage() { return R"( The failed assertion is unexpected when using arbitrary-precision arithmetic. Please file a bug report and provide the input dataset to the operator()(...) function. )"; } }; } 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 ConstrainedDelaunay2<T> : public Delaunay2<T> { public: // The class is a functor to support computing the constrained // Delaunay triangulation of multiple data sets using the same class // object. virtual ~ConstrainedDelaunay2() = default; ConstrainedDelaunay2() : Delaunay2<T>(), mInsertedEdges{}, mCRPool(maxNumCRPool) { } // This operator computes the Delaunay triangulation only. Edges are // inserted later. bool operator()(std::vector<Vector2<T>> const& vertices) { return Delaunay2<T>::operator()(vertices); } bool operator()(size_t numVertices, Vector2<T> const* vertices) { return Delaunay2<T>::operator()(numVertices, vertices); } // The 'edge' is the constrained edge to be inserted into the // triangulation. If that edge is already in the triangulation, the // function returns without any retriangulation and 'partitionedEdge' // contains the input 'edge'. If 'edge' is coincident with 1 or more // edges already in the triangulation, 'edge' is partitioned into // subedges which are then inserted. It is also possible that 'edge' // does not overlap already existing edges in the triangulation but // has interior points that are vertices in the triangulation; in // this case, 'edge' is partitioned and the subedges are inserted. // In either case, 'partitionEdge' is an ordered list of indices // into the triangulation vertices that are on the edge. It is // guaranteed that partitionedEdge.front() = edge[0] and // partitionedEdge.back() = edge[1]. void Insert(std::array<int32_t, 2> edge, std::vector<int32_t>& partitionedEdge) { LogAssert( edge[0] != edge[1] && 0 <= edge[0] && edge[0] < static_cast<int32_t>(this->GetNumVertices()) && 0 <= edge[1] && edge[1] < static_cast<int32_t>(this->GetNumVertices()), "Invalid edge."); // The partitionedEdge vector stores the endpoints of the incoming // edge if that edge does not contain interior points that are // vertices of the Delaunay triangulation. If the edge contains // one or more vertices in its interior, the edge is partitioned // into subedges, each subedge having vertex endpoints but no // interior point is a vertex. The partition is stored in the // partitionedEdge vector. std::vector<std::array<int32_t, 2>> partition; // When using exact arithmetic, a while(!edgeConsumed) loop // suffices. Just in case the code has a bug, guard against an // infinite loop. bool edgeConsumed = false; size_t const numTriangles = this->mGraph.GetTriangles().size(); size_t t; for (t = 0; t < numTriangles && !edgeConsumed; ++t) { EdgeKey<false> ekey(edge[0], edge[1]); if (this->mGraph.GetEdges().find(ekey) != this->mGraph.GetEdges().end()) { // The edge already exists in the triangulation. mInsertedEdges.insert(ekey); partition.push_back(edge); break; } // Get the link edges for the vertex edge[0]. These edges are // opposite the link vertex. std::vector<std::array<int32_t, 2>> linkEdges; GetLinkEdges(edge[0], linkEdges); // Determine which link triangle contains the to-be-inserted // edge. for (auto const& linkEdge : linkEdges) { // Compute on which side of the to-be-inserted edge the // link vertices live. The triangles are not degenerate, // so it is not possible for sign0 = sign1 = 0. size_t e0Index = static_cast<size_t>(edge[0]); size_t e1Index = static_cast<size_t>(edge[1]); size_t v0Index = static_cast<size_t>(linkEdge[0]); size_t v1Index = static_cast<size_t>(linkEdge[1]); int32_t sign0 = ToLine(v0Index, e0Index, e1Index); int32_t sign1 = ToLine(v1Index, e0Index, e1Index); if (sign0 >= 0 && sign1 <= 0) { if (sign0 > 0) { if (sign1 < 0) { // The triangle <edge[0], v0, v1> strictly // contains the to-be-inserted edge. Gather // the triangles in the triangle strip // containing the edge. edgeConsumed = ProcessTriangleStrip(edge, v0Index, v1Index, partition); } else // sign1 == 0 && sign0 > 0 { // The to-be-inserted edge is coincident with // the triangle edge <edge[0], v1>, and it is // guaranteed that the vertex at v1 is an // interior point of <edge[0],edge[1]> because // we previously tested whether edge[] is in // the triangulation. edgeConsumed = ProcessCoincidentEdge(edge, v1Index, partition); } } else // sign0 == 0 && sign1 < 0 { // The to-be-inserted edge is coincident with // the triangle edge <edge[0], v0>, and it is // guaranteed that the vertex at v0 is an // interior point of <edge[0],edge[1]> because // we previously tested whether edge[] is in // the triangulation. edgeConsumed = ProcessCoincidentEdge(edge, v0Index, partition); } break; } } } // If the following assertion is triggered, ComputeType was chosen // to be 'float' or 'double'. Floating-point rounding errors led to // misclassification of signs. The linkEdges-loop exited without // ever calling the ProcessTriangleStrip or ProcessCoincidentEdge // functions. LogAssert(partition.size() > 0, CDTMessage()); partitionedEdge.resize(partition.size() + 1); for (size_t i = 0; i < partition.size(); ++i) { partitionedEdge[i] = partition[i][0]; } partitionedEdge.back() = partition.back()[1]; } // All edges inserted via the Insert(...) call are stored for use // by the caller. If any edge passed to Insert(...) is partitioned // into subedges, the subedges are stored but not the original edge. using EdgeKeySet = std::unordered_set<EdgeKey<false>, EdgeKey<false>, EdgeKey<false>>; EdgeKeySet const& GetInsertedEdges() const { return mInsertedEdges; } // The interface functions to the base class Delaunay2 are valid, so // access to any Delaunay information is allowed. Perhaps the most // important member function is GetGraph() that returns a reference // to the ETManifoldMesh that represents the constrained Delaunay // triangulation. NOTE: If you want access to the compact arrays // via GetIndices(t, indices[]) or GetAdjacencies(t, adjacents[]), // you must first call UpdateIndicesAdjacencies() to ensure that the // compact arrays are synchonized with the Delaunay graph. private: // The type of the read-only input vertices[] when converted for // rational arithmetic. using InputRational = typename Delaunay2<T>::InputRational; // The compute type used for exact sign classification. static int32_t constexpr ComputeNumWords = std::is_same<T, float>::value ? 70 : 526; using ComputeRational = BSNumber<UIntegerFP32<ComputeNumWords>>; // Convenient renaming. using Vertex = VETManifoldMesh::Vertex; using Edge = VETManifoldMesh::Edge; using Triangle = VETManifoldMesh::Triangle; // For a vertex at index v, return the edges of the adjacent triangles, // each triangle having v as a vertex and the returned edge is // opposite v. void GetLinkEdges(int32_t v, std::vector<std::array<int32_t, 2>>& linkEdges) { auto const& vmap = this->mGraph.GetVertices(); auto viter = vmap.find(v); LogAssert(viter != vmap.end(), "Failed to find vertex in graph."); auto vertex = viter->second.get(); LogAssert(vertex != nullptr, "Unexpected condition."); for (auto const& linkTri : vertex->TAdjacent) { size_t j; for (j = 0; j < 3; ++j) { if (linkTri->V[j] == vertex->V) { linkEdges.push_back({ linkTri->V[(j + 1) % 3], linkTri->V[(j + 2) % 3] }); break; } } LogAssert(j < 3, "Unexpected condition."); } } // Given a line with origin V0 and direction <V0,V1> and a query // point P, ToLine returns // +1, P on right of line // -1, P on left of line // 0, P on the line int32_t ToLine(size_t pIndex, size_t v0Index, size_t v1Index) const { // The expression tree has 13 nodes consisting of 6 input // leaves and 7 compute nodes. // Use interval arithmetic to determine the sign if possible. auto const& inP = this->mVertices[pIndex]; Vector2<T> const& inV0 = this->mVertices[v0Index]; Vector2<T> const& inV1 = this->mVertices[v1Index]; auto x0 = SWInterval<T>::Sub(inP[0], inV0[0]); auto y0 = SWInterval<T>::Sub(inP[1], inV0[1]); auto x1 = SWInterval<T>::Sub(inV1[0], inV0[0]); auto y1 = SWInterval<T>::Sub(inV1[1], inV0[1]); auto x0y1 = x0 * y1; auto x1y0 = x1 * y0; auto det = x0y1 - x1y0; 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 = this->mIRVertices[pIndex]; auto const& irV0 = this->mIRVertices[v0Index]; auto const& irV1 = this->mIRVertices[v1Index]; auto const& crP0 = Copy(irP[0], mCRPool[0]); auto const& crP1 = Copy(irP[1], mCRPool[1]); auto const& crV00 = Copy(irV0[0], mCRPool[2]); auto const& crV01 = Copy(irV0[1], mCRPool[3]); auto const& crV10 = Copy(irV1[0], mCRPool[4]); auto const& crV11 = Copy(irV1[1], mCRPool[5]); auto& crX0 = mCRPool[6]; auto& crY0 = mCRPool[7]; auto& crX1 = mCRPool[8]; auto& crY1 = mCRPool[9]; auto& crX0Y1 = mCRPool[10]; auto& crX1Y0 = mCRPool[11]; auto& crDet = mCRPool[12]; // Evaluate the expression tree. crX0 = crP0 - crV00; crY0 = crP1 - crV01; crX1 = crV10 - crV00; crY1 = crV11 - crV01; crX0Y1 = crX0 * crY1; crX1Y0 = crX1 * crY0; crDet = crX0Y1 - crX1Y0; return crDet.GetSign(); } // The return value is 'true' if the edge did not have to be // subdivided because it has an interior point that is a vertex. // The return value is 'false' if it does have such a point, in // which case edge[0] is updated to the index of that vertex. The // caller must process the new edge. bool ProcessTriangleStrip(std::array<int32_t, 2>& edge, size_t v0Index, size_t v1Index, std::vector<std::array<int32_t, 2>>& partitionedEdge) { int32_t v0 = static_cast<int32_t>(v0Index); int32_t v1 = static_cast<int32_t>(v1Index); bool edgeConsumed = true; std::array<int32_t, 2> localEdge = edge; // Locate and store the triangles in the triangle strip containing // the edge. ETManifoldMesh tristrip; tristrip.Insert(localEdge[0], v0, v1); auto const& tmap = this->mGraph.GetTriangles(); auto titer = tmap.find(TriangleKey<true>(localEdge[0], v0, v1)); LogAssert(titer != tmap.end(), CDTMessage()); auto tri = titer->second.get(); LogAssert(tri, CDTMessage()); // Keep track of the right and left polylines that bound the // triangle strip. These polylines can have coincident edges. // In particular, this happens when the current triangle in the // strip shares an edge with a previous triangle in the strip // and the previous triangle is not the immediate predecessor // to the current triangle. std::vector<int32_t> rightPolygon, leftPolygon; rightPolygon.push_back(localEdge[0]); rightPolygon.push_back(v0); leftPolygon.push_back(localEdge[0]); leftPolygon.push_back(v1); // When using exact arithmetic, a for(;;) loop suffices. When // using floating-point arithmetic (which you should really not // do for CDT), guard against an infinite loop. size_t const numTriangles = tmap.size(); size_t t; for (t = 0; t < numTriangles; ++t) { // The current triangle is tri and has edge <v0,v1>. Get // the triangle adj that is adjacent to tri via this edge. auto adj = tri->GetAdjacentOfEdge(v0, v1); LogAssert(adj, CDTMessage()); tristrip.Insert(adj->V[0], adj->V[1], adj->V[2]); // Get the vertex of adj that is opposite edge <v0,v1>. int32_t vOpposite = 0; bool found = adj->GetOppositeVertexOfEdge(v0, v1, vOpposite); LogAssert(found, CDTMessage()); if (vOpposite == localEdge[1]) { // The triangle strip containing the edge is complete. break; } // The next triangle in the strip depends on whether the // opposite vertex is left-of the edge, right-of the edge // or on the edge. int32_t querySign = ToLine(static_cast<size_t>(vOpposite), static_cast<size_t>(localEdge[0]), static_cast<size_t>(localEdge[1])); if (querySign > 0) { tri = adj; v0 = vOpposite; rightPolygon.push_back(v0); } else if (querySign < 0) { tri = adj; v1 = vOpposite; leftPolygon.push_back(v1); } else { // The to-be-inserted edge contains an interior point that // is also a vertex in the triangulation. The edge must be // subdivided. The first subedge is in a triangle strip // that is processed by code below that is outside the // loop. The second subedge must be processed by the // caller. localEdge[1] = vOpposite; edge[0] = vOpposite; edgeConsumed = false; break; } } LogAssert(t < numTriangles, CDTMessage()); // Insert the final endpoint of the to-be-inserted edge. rightPolygon.push_back(localEdge[1]); leftPolygon.push_back(localEdge[1]); // The retriangulation depends on counterclockwise ordering of // the boundary right and left polygons. The right polygon is // already counterclockwise ordered. The left polygon is // clockwise ordered, so reverse it. std::reverse(leftPolygon.begin(), leftPolygon.end()); // Update the inserted edges. mInsertedEdges.insert(EdgeKey<false>(localEdge[0], localEdge[1])); partitionedEdge.push_back(localEdge); // Remove the triangle strip from the full triangulation. This // must occur before the retriangulation which inserts new // triangles into the full triangulation. for (auto const& element : tristrip.GetTriangles()) { auto const& tkey = element.first; this->mGraph.Remove(tkey.V[0], tkey.V[1], tkey.V[2]); } // Retriangulate the tristrip region. Retriangulate(leftPolygon); Retriangulate(rightPolygon); return edgeConsumed; } // Process a to-be-inserted edge that is coincident with an already // existing triangulation edge. bool ProcessCoincidentEdge(std::array<int32_t, 2>& edge, size_t vIndex, std::vector<std::array<int32_t, 2>>& partitionedEdge) { int32_t v = static_cast<int32_t>(vIndex); mInsertedEdges.insert(EdgeKey<false>(edge[0], v)); partitionedEdge.push_back({ edge[0], v }); edge[0] = v; bool edgeConsumed = (v == edge[1]); return edgeConsumed; } // Retriangulate the polygon via a bisection-like method that finds // vertices closest to the current polygon base edge. The function // is naturally recursive, but simulated recursion is used to avoid // a large program stack by instead using the heap. void Retriangulate(std::vector<int32_t> const& polygon) { std::vector<std::array<size_t, 2>> stack(polygon.size()); size_t top = std::numeric_limits<size_t>::max(); stack[++top] = { 0, polygon.size() - 1 }; while (top != std::numeric_limits<size_t>::max()) { std::array<size_t, 2> i = stack[top--]; if (i[1] > i[0] + 1) { // Get the vertex indices for the specified i-values. int32_t v0 = polygon[i[0]]; int32_t v1 = polygon[i[1]]; // Select isplit in the index range [i[0]+1,i[1]-1] so // that the vertex at index polygon[isplit] attains the // minimum distance to the edge with vertices at the // indices polygon[i[0]] and polygon[i[1]]. size_t isplit = SelectSplit(polygon, i[0], i[1]); int32_t vsplit = polygon[isplit]; // Insert the triangle into the Delaunay graph. this->mGraph.Insert(v0, vsplit, v1); stack[++top] = { i[0], isplit }; stack[++top] = { isplit, i[1] }; } } } static ComputeRational const& Copy(InputRational const& source, ComputeRational& target) { target.SetSign(source.GetSign()); target.SetBiasedExponent(source.GetBiasedExponent()); target.GetUInteger().CopyFrom(source.GetUInteger()); return target; } // Determine the polygon vertex with index strictly between i0 and i1 // that minimizes the pseudosquared distance from that vertex to the // line segment whose endpoints are at indices i0 and i1. size_t SelectSplit(std::vector<int32_t> const& polygon, size_t i0, size_t i1) { size_t i2; if (i1 == i0 + 2) { // This is the only candidate. i2 = i0 + 1; } else // i1 - i0 > 2 { // Select the index i2 in [i0+1,i1-1] for which the distance // from the vertex v2 at i2 to the edge <v0,v1> is minimized. // To allow exact arithmetic, use a pseudosquared distance // that avoids divisions and square roots. i2 = i0 + 1; size_t v0 = static_cast<size_t>(polygon[i0]); size_t v1 = static_cast<size_t>(polygon[i1]); size_t v2 = static_cast<size_t>(polygon[i2]); // Precompute some common values that are used in all calls // to ComputePSD. auto const& irV0 = this->mIRVertices[v0]; auto const& irV1 = this->mIRVertices[v1]; auto const& irV2 = this->mIRVertices[v2]; auto const& crV0x = Copy(irV0[0], mCRPool[0]); auto const& crV0y = Copy(irV0[1], mCRPool[1]); auto const& crV1x = Copy(irV1[0], mCRPool[2]); auto const& crV1y = Copy(irV1[1], mCRPool[3]); auto const& crV2x = Copy(irV2[0], mCRPool[4]); auto const& crV2y = Copy(irV2[1], mCRPool[5]); auto& crV1mV0x = mCRPool[6]; auto& crV1mV0y = mCRPool[7]; auto& crSqrLen10 = mCRPool[8]; auto& crPSD = mCRPool[9]; auto& crMinPSD = mCRPool[10]; crV1mV0x = crV1x - crV0x; crV1mV0y = crV1y - crV0y; crSqrLen10 = crV1mV0x * crV1mV0x + crV1mV0y * crV1mV0y; // Locate the minimum pseudosquared distance. ComputePSD(crV0x, crV0y, crV1x, crV1y, crV2x, crV2y, crV1mV0x, crV1mV0y, crSqrLen10, crMinPSD); for (size_t i = i2 + 1; i < i1; ++i) { v2 = polygon[i]; auto const& irNextV2 = this->mIRVertices[v2]; this->Copy(irNextV2[0], mCRPool[4]); this->Copy(irNextV2[1], mCRPool[5]); ComputePSD(crV0x, crV0y, crV1x, crV1y, crV2x, crV2y, crV1mV0x, crV1mV0y, crSqrLen10, crPSD); if (crPSD < crMinPSD) { crMinPSD = crPSD; i2 = i; } } } return i2; } // Compute a pseudosquared distance from the vertex at v2 to the edge // <v0,v1>. The result is exact for rational arithmetic and does not // involve division. This allows ComputeType to be BSNumber<UInteger> // rather than BSRational<UInteger>, which leads to better // performance. void ComputePSD( ComputeRational const& crV0x, ComputeRational const& crV0y, ComputeRational const& crV1x, ComputeRational const& crV1y, ComputeRational const& crV2x, ComputeRational const& crV2y, ComputeRational const& crV1mV0x, ComputeRational const& crV1mV0y, ComputeRational const& crSqrLen10, ComputeRational& crPSD) { auto& crV2mV0x = mCRPool[11]; auto& crV2mV0y = mCRPool[12]; auto& crV2mV1x = mCRPool[13]; auto& crV2mV1y = mCRPool[14]; auto& crDot1020 = mCRPool[15]; auto& crSqrLen20 = mCRPool[16]; auto& crDot1021 = mCRPool[17]; auto& crSqrLen21 = mCRPool[18]; crV2mV0x = crV2x - crV0x; crV2mV0y = crV2y - crV0y; crDot1020 = crV1mV0x * crV2mV0x + crV1mV0y * crV2mV0y; if (crDot1020.GetSign() <= 0) { crSqrLen20 = crV2mV0x * crV2mV0x + crV2mV0y * crV2mV0y; crPSD = crSqrLen10 * crSqrLen20; } else { crV2mV1x = crV2x - crV1x; crV2mV1y = crV2y - crV1y; crDot1021 = crV1mV0x * crV2mV1x + crV1mV0y * crV2mV1y; if (crDot1021.GetSign() >= 0) { crSqrLen21 = crV2mV1x * crV2mV1x + crV2mV1y * crV2mV1y; crPSD = crSqrLen10 * crSqrLen21; } else { crSqrLen20 = crV2mV0x * crV2mV0x + crV2mV0y * crV2mV0y; crPSD = crSqrLen10 * crSqrLen20 - crDot1020 * crDot1020; } } } static std::string CDTMessage() { return R"( The failed assertion is unexpected when using arbitrary-precision arithmetic. Please file a bug report and provide the input dataset to the operator()(...) function. )"; } // All edges inserted via the Insert(...) call are stored for use // by the caller. If any edge passed to Insert(...) is partitioned // into subedges, the subedges are inserted into this member. EdgeKeySet mInsertedEdges; // Sufficient storage for the expression trees related to computing // the exact pseudosquared distances in SelectSplit and ComputePSD. static size_t constexpr maxNumCRPool = 19; mutable std::vector<ComputeRational> mCRPool; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FastGaussianBlur3.h
.h
8,119
190
// 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> // The algorithms here are based on solving the linear heat equation using // finite differences in scale, not in time. The following document has // a brief summary of the concept, // https://www.geometrictools.com/Documentation/FastGaussianBlur.pdf // The idea is to represent the blurred image as f(x,s) in terms of position // x and scale s. Gaussian blurring is accomplished by using the input image // I(x,s0) as the initial image (of scale s0 > 0) for the partial differential // equation // s*df/ds = s^2*Laplacian(f) // where the Laplacian operator is // Laplacian = (d/dx)^2, dimension 1 // Laplacian = (d/dx)^2+(d/dy)^2, dimension 2 // Laplacian = (d/dx)^2+(d/dy)^2+(d/dz)^2, dimension 3 // // The term s*df/ds is approximated by // s*df(x,s)/ds = (f(x,b*s)-f(x,s))/ln(b) // for b > 1, but close to 1, where ln(b) is the natural logarithm of b. If // you take the limit of the right-hand side as b approaches 1, you get the // left-hand side. // // The term s^2*((d/dx)^2)f is approximated by // s^2*((d/dx)^2)f = (f(x+h*s,s)-2*f(x,s)+f(x-h*s,s))/h^2 // for h > 0, but close to zero. // // Equating the approximations for the left-hand side and the right-hand side // of the partial differential equation leads to the numerical method used in // this code. // // For iterative application of these functions, the caller is responsible // for constructing a geometric sequence of scales, // s0, s1 = s0*b, s2 = s1*b = s0*b^2, ... // where the base b satisfies 1 < b < exp(0.5*d) where d is the dimension of // the image. The upper bound on b guarantees stability of the finite // difference method used to approximate the partial differential equation. // The method assumes a pixel size of h = 1. namespace gte { // The image type must be one of int16_t, int32_t, float or double. The // computations are performed using double. The input and output images // must both have xBound*yBound*zBound elements and be stored in // lexicographical order. The indexing is i = x+xBound*(y+yBound*z). template <typename T> class FastGaussianBlur3 { public: void Execute(int32_t xBound, int32_t yBound, int32_t zBound, T const* input, T* output, double scale, double logBase) { mXBound = xBound; mYBound = yBound; mZBound = zBound; mInput = input; mOutput = output; int32_t xBoundM1 = xBound - 1, yBoundM1 = yBound - 1, zBoundM1 = zBound - 1; for (int32_t z = 0; z < zBound; ++z) { double rzps = static_cast<double>(z) + scale; double rzms = static_cast<double>(z) - scale; int32_t zp1 = static_cast<int32_t>(std::floor(rzps)); int32_t zm1 = static_cast<int32_t>(std::ceil(rzms)); for (int32_t y = 0; y < yBound; ++y) { double ryps = static_cast<double>(y) + scale; double ryms = static_cast<double>(y) - scale; int32_t yp1 = static_cast<int32_t>(std::floor(ryps)); int32_t ym1 = static_cast<int32_t>(std::ceil(ryms)); for (int32_t x = 0; x < xBound; ++x) { double rxps = static_cast<double>(x) + scale; double rxms = static_cast<double>(x) - scale; int32_t xp1 = static_cast<int32_t>(std::floor(rxps)); int32_t xm1 = static_cast<int32_t>(std::ceil(rxms)); double center = Input(x, y, z); double xsum = -2.0 * center, ysum = xsum, zsum = xsum; // x portion of second central difference if (xp1 >= xBoundM1) // use boundary value { xsum += Input(xBoundM1, y, z); } else // linearly interpolate { double imgXp1 = Input(xp1, y, z); double imgXp2 = Input(xp1 + 1, y, z); double delta = rxps - static_cast<double>(xp1); xsum += imgXp1 + delta * (imgXp2 - imgXp1); } if (xm1 <= 0) // use boundary value { xsum += Input(0, y, z); } else // linearly interpolate { double imgXm1 = Input(xm1, y, z); double imgXm2 = Input(xm1 - 1, y, z); double delta = rxms - static_cast<double>(xm1); xsum += imgXm1 + delta * (imgXm1 - imgXm2); } // y portion of second central difference if (yp1 >= yBoundM1) // use boundary value { ysum += Input(x, yBoundM1, z); } else // linearly interpolate { double imgYp1 = Input(x, yp1, z); double imgYp2 = Input(x, yp1 + 1, z); double delta = ryps - static_cast<double>(yp1); ysum += imgYp1 + delta * (imgYp2 - imgYp1); } if (ym1 <= 0) // use boundary value { ysum += Input(x, 0, z); } else // linearly interpolate { double imgYm1 = Input(x, ym1, z); double imgYm2 = Input(x, ym1 - 1, z); double delta = ryms - static_cast<double>(ym1); ysum += imgYm1 + delta * (imgYm1 - imgYm2); } // z portion of second central difference if (zp1 >= zBoundM1) // use boundary value { zsum += Input(x, y, zBoundM1); } else // linearly interpolate { double imgZp1 = Input(x, y, zp1); double imgZp2 = Input(x, y, zp1 + 1); double delta = rzps - static_cast<double>(zp1); zsum += imgZp1 + delta * (imgZp2 - imgZp1); } if (zm1 <= 0) // use boundary value { zsum += Input(x, y, 0); } else // linearly interpolate { double imgZm1 = Input(x, y, zm1); double imgZm2 = Input(x, y, zm1 - 1); double delta = rzms - static_cast<double>(zm1); zsum += imgZm1 + delta * (imgZm1 - imgZm2); } Output(x, y, z) = static_cast<T>(center + logBase * (xsum + ysum + zsum)); } } } } private: inline double Input(int32_t x, int32_t y, int32_t z) const { return static_cast<double>(mInput[x + mXBound * (y + mYBound * z)]); } inline T& Output(int32_t x, int32_t y, int32_t z) { return mOutput[x + mXBound * (y + mYBound * z)]; } int32_t mXBound, mYBound, mZBound; T const* mInput; T* mOutput; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BandedMatrix.h
.h
17,426
524
// 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> #include <Mathematics/LexicoArray2.h> #include <vector> namespace gte { template <typename Real> class BandedMatrix { public: // Construction and destruction. BandedMatrix(int32_t size, int32_t numLBands, int32_t numUBands) : mSize(size), mDBand{}, mLBands{}, mUBands{}, mZero((Real)0) { if (size > 0 && 0 <= numLBands && numLBands < size && 0 <= numUBands && numUBands < size) { mDBand.resize(size); std::fill(mDBand.begin(), mDBand.end(), (Real)0); if (numLBands > 0) { mLBands.resize(numLBands); int32_t numElements = size - 1; for (auto& band : mLBands) { band.resize(numElements--); std::fill(band.begin(), band.end(), (Real)0); } } if (numUBands > 0) { mUBands.resize(numUBands); int32_t numElements = size - 1; for (auto& band : mUBands) { band.resize(numElements--); std::fill(band.begin(), band.end(), (Real)0); } } } else { // Invalid argument to BandedMatrix constructor. mSize = 0; } } ~BandedMatrix() { } // Member access. inline int32_t GetSize() const { return mSize; } inline std::vector<Real>& GetDBand() { return mDBand; } inline std::vector<Real> const& GetDBand() const { return mDBand; } inline std::vector<std::vector<Real>>& GetLBands() { return mLBands; } inline std::vector<std::vector<Real>> const& GetLBands() const { return mLBands; } inline std::vector<std::vector<Real>>& GetUBands() { return mUBands; } inline std::vector<std::vector<Real>> const& GetUBands() const { return mUBands; } Real& operator()(int32_t r, int32_t c) { if (0 <= r && r < mSize && 0 <= c && c < mSize) { int32_t band = c - r; if (band > 0) { int32_t const numUBands = static_cast<int32_t>(mUBands.size()); if (--band < numUBands && r < mSize - 1 - band) { return mUBands[band][r]; } } else if (band < 0) { band = -band; int32_t const numLBands = static_cast<int32_t>(mLBands.size()); if (--band < numLBands && c < mSize - 1 - band) { return mLBands[band][c]; } } else { return mDBand[r]; } } // else invalid index // Set the value to zero in case someone unknowingly modified mZero on a // previous call to operator(int32_t,int32_t). mZero = (Real)0; return mZero; } Real const& operator()(int32_t r, int32_t c) const { if (0 <= r && r < mSize && 0 <= c && c < mSize) { int32_t band = c - r; if (band > 0) { int32_t const numUBands = static_cast<int32_t>(mUBands.size()); if (--band < numUBands && r < mSize - 1 - band) { return mUBands[band][r]; } } else if (band < 0) { band = -band; int32_t const numLBands = static_cast<int32_t>(mLBands.size()); if (--band < numLBands && c < mSize - 1 - band) { return mLBands[band][c]; } } else { return mDBand[r]; } } // else invalid index // Set the value to zero in case someone unknowingly modified // mZero on a previous call to operator(int32_t,int32_t). mZero = (Real)0; return mZero; } // Factor the square banded matrix A into A = L*L^T, where L is a // lower-triangular matrix (L^T is an upper-triangular matrix). This // is an LU decomposition that allows for stable inversion of A to // solve A*X = B. The return value is 'true' iff the factorizing is // successful (L is invertible). If successful, A contains the // Cholesky factorization: L in the lower-triangular part of A and // L^T in the upper-triangular part of A. bool CholeskyFactor() { if (mDBand.size() == 0 || mLBands.size() != mUBands.size()) { // Invalid number of bands. return false; } int32_t const sizeM1 = mSize - 1; int32_t const numBands = static_cast<int32_t>(mLBands.size()); int32_t k, kMax; for (int32_t i = 0; i < mSize; ++i) { int32_t jMin = i - numBands; if (jMin < 0) { jMin = 0; } int32_t j; for (j = jMin; j < i; ++j) { kMax = j + numBands; if (kMax > sizeM1) { kMax = sizeM1; } for (k = i; k <= kMax; ++k) { operator()(k, i) -= operator()(i, j) * operator()(k, j); } } kMax = j + numBands; if (kMax > sizeM1) { kMax = sizeM1; } for (k = 0; k < i; ++k) { operator()(k, i) = operator()(i, k); } Real diagonal = operator()(i, i); if (diagonal <= (Real)0) { return false; } Real invSqrt = ((Real)1) / std::sqrt(diagonal); for (k = i; k <= kMax; ++k) { operator()(k, i) *= invSqrt; } } return true; } // Solve the linear system A*X = B, where A is an NxN banded matrix // and B is an Nx1 vector. The unknown X is also Nx1. The input to // this function is B. The output X is computed and stored in B. The // return value is 'true' iff the system has a solution. The matrix A // and the vector B are both modified by this function. If // successful, A contains the Cholesky factorization: L in the // lower-triangular part of A and L^T in the upper-triangular part // of A. bool SolveSystem(Real* bVector) { return CholeskyFactor() && SolveLower(bVector) && SolveUpper(bVector); } // Solve the linear system A*X = B, where A is an NxN banded matrix // and B is an NxM matrix. The unknown X is also NxM. The input to // this function is B. The output X is computed and stored in B. The // return value is 'true' iff the system has a solution. The matrix A // and the vector B are both modified by this function. If // successful, A contains the Cholesky factorization: L in the // lower-triangular part of A and L^T in the upper-triangular part // of A. // // 'bMatrix' must have the storage order specified by the template // parameter. template <bool RowMajor> bool SolveSystem(Real* bMatrix, int32_t numBColumns) { return CholeskyFactor() && SolveLower<RowMajor>(bMatrix, numBColumns) && SolveUpper<RowMajor>(bMatrix, numBColumns); } // Compute the inverse of the banded matrix. The return value is // 'true' when the matrix is invertible, in which case the 'inverse' // output is valid. The return value is 'false' when the matrix is // not invertible, in which case 'inverse' is invalid and should not // be used. The input matrix 'inverse' must be the same size as // 'this'. // // 'bMatrix' must have the storage order specified by the template // parameter. template <bool RowMajor> bool ComputeInverse(Real* inverse) const { LexicoArray2<RowMajor, Real> invA(mSize, mSize, inverse); BandedMatrix<Real> tmpA = *this; for (int32_t row = 0; row < mSize; ++row) { for (int32_t col = 0; col < mSize; ++col) { if (row != col) { invA(row, col) = (Real)0; } else { invA(row, row) = (Real)1; } } } // Forward elimination. for (int32_t row = 0; row < mSize; ++row) { // The pivot must be nonzero in order to proceed. Real diag = tmpA(row, row); if (diag == (Real)0) { return false; } Real invDiag = ((Real)1) / diag; tmpA(row, row) = (Real)1; // Multiply the row to be consistent with diagonal term of 1. int32_t colMin = row + 1; int32_t colMax = colMin + static_cast<int32_t>(mUBands.size()); if (colMax > mSize) { colMax = mSize; } int32_t c; for (c = colMin; c < colMax; ++c) { tmpA(row, c) *= invDiag; } for (c = 0; c <= row; ++c) { invA(row, c) *= invDiag; } // Reduce the remaining rows. int32_t rowMin = row + 1; int32_t rowMax = rowMin + static_cast<int32_t>(mLBands.size()); if (rowMax > mSize) { rowMax = mSize; } for (int32_t r = rowMin; r < rowMax; ++r) { Real mult = tmpA(r, row); tmpA(r, row) = (Real)0; for (c = colMin; c < colMax; ++c) { tmpA(r, c) -= mult * tmpA(row, c); } for (c = 0; c <= row; ++c) { invA(r, c) -= mult * invA(row, c); } } } // Backward elimination. for (int32_t row = mSize - 1; row >= 1; --row) { int32_t rowMax = row - 1; int32_t rowMin = row - static_cast<int32_t>(mUBands.size()); if (rowMin < 0) { rowMin = 0; } for (int32_t r = rowMax; r >= rowMin; --r) { Real mult = tmpA(r, row); tmpA(r, row) = (Real)0; for (int32_t c = 0; c < mSize; ++c) { invA(r, c) -= mult * invA(row, c); } } } return true; } private: // The linear system is L*U*X = B, where A = L*U and U = L^T, Reduce // this to U*X = L^{-1}*B. The return value is 'true' iff the // operation is successful. bool SolveLower(Real* dataVector) const { int32_t const size = static_cast<int32_t>(mDBand.size()); for (int32_t r = 0; r < size; ++r) { Real lowerRR = operator()(r, r); if (lowerRR > (Real)0) { for (int32_t c = 0; c < r; ++c) { Real lowerRC = operator()(r, c); dataVector[r] -= lowerRC * dataVector[c]; } dataVector[r] /= lowerRR; } else { return false; } } return true; } // The linear system is U*X = L^{-1}*B. Reduce this to // X = U^{-1}*L^{-1}*B. The return value is 'true' iff the operation // is successful. bool SolveUpper(Real* dataVector) const { int32_t const size = static_cast<int32_t>(mDBand.size()); for (int32_t r = size - 1; r >= 0; --r) { Real upperRR = operator()(r, r); if (upperRR > (Real)0) { for (int32_t c = r + 1; c < size; ++c) { Real upperRC = operator()(r, c); dataVector[r] -= upperRC * dataVector[c]; } dataVector[r] /= upperRR; } else { return false; } } return true; } // The linear system is L*U*X = B, where A = L*U and U = L^T, Reduce // this to U*X = L^{-1}*B. The return value is 'true' iff the // operation is successful. See the comments for // SolveSystem(Real*,int32_t) about the storage for dataMatrix. template <bool RowMajor> bool SolveLower(Real* dataMatrix, int32_t numColumns) const { LexicoArray2<RowMajor, Real> data(mSize, numColumns, dataMatrix); for (int32_t r = 0; r < mSize; ++r) { Real lowerRR = operator()(r, r); if (lowerRR > (Real)0) { for (int32_t c = 0; c < r; ++c) { Real lowerRC = operator()(r, c); for (int32_t bCol = 0; bCol < numColumns; ++bCol) { data(r, bCol) -= lowerRC * data(c, bCol); } } Real inverse = ((Real)1) / lowerRR; for (int32_t bCol = 0; bCol < numColumns; ++bCol) { data(r, bCol) *= inverse; } } else { return false; } } return true; } // The linear system is U*X = L^{-1}*B. Reduce this to // X = U^{-1}*L^{-1}*B. The return value is 'true' iff the operation // is successful. See the comments for SolveSystem(Real*,int32_t) about // the storage for dataMatrix. template <bool RowMajor> bool SolveUpper(Real* dataMatrix, int32_t numColumns) const { LexicoArray2<RowMajor, Real> data(mSize, numColumns, dataMatrix); for (int32_t r = mSize - 1; r >= 0; --r) { Real upperRR = operator()(r, r); if (upperRR > (Real)0) { for (int32_t c = r + 1; c < mSize; ++c) { Real upperRC = operator()(r, c); for (int32_t bCol = 0; bCol < numColumns; ++bCol) { data(r, bCol) -= upperRC * data(c, bCol); } } Real inverse = ((Real)1) / upperRR; for (int32_t bCol = 0; bCol < numColumns; ++bCol) { data(r, bCol) *= inverse; } } else { return false; } } return true; } int32_t mSize; std::vector<Real> mDBand; std::vector<std::vector<Real>> mLBands, mUBands; // For return by operator()(int32_t,int32_t) for valid indices not in the // bands, in which case the matrix entries are zero, mutable Real mZero; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointHyperplane.h
.h
1,712
55
// 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/Hyperplane.h> // Compute the distance between a point and a line (N = 2), between a point // and a plane (N = 3) or generally between a point and a hyperplane (N >= 2). // // The plane is defined by Dot(N, X - P) = 0, where P is the plane origin and // N is a unit-length normal for the plane. // // TODO: Modify to support non-unit-length N. namespace gte { template <int32_t N, typename T> class DCPQuery<T, Vector<N, T>, Hyperplane<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), signedDistance(static_cast<T>(0)), closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { static_assert( N >= 2, "Invalid dimension."); } T distance, signedDistance; std::array<Vector<N, T>, 2> closest; }; Result operator()(Vector<N, T> const& point, Hyperplane<N, T> const& plane) { Result result{}; result.signedDistance = Dot(plane.normal, point) - plane.constant; result.distance = std::fabs(result.signedDistance); result.closest[0] = point; result.closest[1] = point - result.signedDistance * plane.normal; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRay2OrientedBox2.h
.h
2,102
62
// 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/DistLine2OrientedBox2.h> #include <Mathematics/DistPointOrientedBox.h> #include <Mathematics/Ray.h> // Compute the distance between a ray and a solid oriented box in 2D. // // The ray is P + t * D for t >= 0, 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 0 <= i < N. 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 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, Ray2<T>, OrientedBox2<T>> { public: using OrientedQuery = DCPQuery<T, Line2<T>, OrientedBox2<T>>; using Result = typename OrientedQuery::Result; Result operator()(Ray2<T> const& ray, OrientedBox2<T> const& box) { Result result{}; Line2<T> line(ray.origin, ray.direction); OrientedQuery lbQuery{}; auto lbResult = lbQuery(line, box); T const zero = static_cast<T>(0); if (lbResult.parameter >= zero) { result = lbResult; } else { DCPQuery<T, Vector2<T>, OrientedBox2<T>> pbQuery{}; auto pbResult = pbQuery(ray.origin, box); result.distance = pbResult.distance; result.sqrDistance = pbResult.sqrDistance; result.parameter = zero; result.closest[0] = ray.origin; result.closest[1] = pbResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRay2AlignedBox2.h
.h
2,049
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/DistLine2AlignedBox2.h> #include <Mathematics/DistPointAlignedBox.h> #include <Mathematics/Ray.h> // Compute the distance between a ray and a solid aligned box in 2D. // // 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, Ray2<T>, AlignedBox2<T>> { public: using AlignedQuery = DCPQuery<T, Line2<T>, AlignedBox2<T>>; using Result = typename AlignedQuery::Result; Result operator()(Ray2<T> const& ray, AlignedBox2<T> const& box) { Result result{}; Line2<T> line(ray.origin, ray.direction); AlignedQuery lbQuery{}; auto lbResult = lbQuery(line, box); T const zero = static_cast<T>(0); if (lbResult.parameter >= zero) { result = lbResult; } else { DCPQuery<T, Vector2<T>, AlignedBox2<T>> pbQuery{}; auto pbResult = pbQuery(ray.origin, box); result.distance = pbResult.distance; result.sqrDistance = pbResult.sqrDistance; result.parameter = zero; result.closest[0] = ray.origin; result.closest[1] = pbResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Sector2.h
.h
3,909
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/Vector2.h> // A solid sector is the intersection of a disk and a 2D cone. The disk // has center C, radius R, and contains points X for which |X-C| <= R. The // 2D cone has vertex C, unit-length axis direction D, angle A in (0,pi) // measured from D, and contains points X for which // Dot(D,(X-C)/|X-C|) >= cos(A). Sector points X satisfy both inequality // constraints. namespace gte { template <typename Real> class Sector2 { public: // Construction and destruction. The default constructor sets the // vertex to (0,0), radius to 1, axis direction to (1,0), and angle // to pi, all of which define a disk. Sector2() : vertex(Vector2<Real>::Zero()), radius((Real)1), direction(Vector2<Real>::Unit(0)), angle((Real)GTE_C_PI), cosAngle((Real)-1), sinAngle((Real)0) { } Sector2(Vector2<Real> const& inVertex, Real inRadius, Vector2<Real> const& inDirection, Real inAngle) : vertex(inVertex), radius(inRadius), direction(inDirection) { SetAngle(inAngle); } // Set the angle and cos(angle) simultaneously. void SetAngle(Real inAngle) { angle = inAngle; cosAngle = std::cos(angle); sinAngle = std::sin(angle); } // Test whether P is in the sector. bool Contains(Vector2<Real> const& p) const { Vector2<Real> diff = p - vertex; Real length = Length(diff); return length <= radius && Dot(direction, diff) >= length * cosAngle; } // The cosine and sine of the angle are used in queries, so all o // angle, cos(angle), and sin(angle) are stored. If you set 'angle' // via the public members, you must set all to be consistent. You // can also call SetAngle(...) to ensure consistency. Vector2<Real> vertex; Real radius; Vector2<Real> direction; Real angle, cosAngle, sinAngle; public: // Comparisons to support sorted containers. bool operator==(Sector2 const& sector) const { return vertex == sector.vertex && radius == sector.radius && direction == sector.direction && angle == sector.angle; } bool operator!=(Sector2 const& sector) const { return !operator==(sector); } bool operator< (Sector2 const& sector) const { if (vertex < sector.vertex) { return true; } if (vertex > sector.vertex) { return false; } if (radius < sector.radius) { return true; } if (radius > sector.radius) { return false; } if (direction < sector.direction) { return true; } if (direction > sector.direction) { return false; } return angle < sector.angle; } bool operator<=(Sector2 const& sector) const { return !sector.operator<(*this); } bool operator> (Sector2 const& sector) const { return sector.operator<(*this); } bool operator>=(Sector2 const& sector) const { return !operator<(sector); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/GenerateMeshUV.h
.h
27,754
662
// 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> #include <Mathematics/ETManifoldMesh.h> #include <cstdint> #include <cstring> #include <functional> #include <set> #include <thread> // This class is an implementation of the barycentric mapping algorithm // described in Section 5.3 of the book // Polygon Mesh Processing // Mario Botsch, Leif Kobbelt, Mark Pauly, Pierre Alliez, Bruno Levy // AK Peters, Ltd., Natick MA, 2010 // It uses the mean value weights described in Section 5.3.1 to allow the mesh // geometry to influence the texture coordinate generation, and it uses // Gauss-Seidel iteration to solve the sparse linear system. The authors' // advice is that the Gauss-Seidel approach works well for at most about 5000 // vertices, presumably the convergence rate degrading as the number of // vertices increases. // // The algorithm implemented here has an additional preprocessing step that // computes a topological distance transform of the vertices. The boundary // texture coordinates are propagated inward by updating the vertices in // topological distance order, leading to fast convergence for large numbers // of vertices. namespace gte { template <typename Real> class GenerateMeshUV { public: // Construction and destruction. Set the number of threads to 0 when // you want the code to run in the main thread of the applications. // Set the number of threads to a positive number when you want the // code to run multithreaded on the CPU. Derived classes that use the // GPU ignore the number of threads, setting the constructor input to // std::numeric_limits<uint32_t>::max(). Provide a callback when you // want to monitor each iteration of the uv-solver. The input to the // progress callback is the current iteration; it starts at 1 and // increases to the numIterations input to the operator() member // function. GenerateMeshUV(uint32_t numThreads, std::function<void(uint32_t)> const* progress = nullptr) : mNumThreads(numThreads), mProgress(progress), mNumVertices(0), mVertices(nullptr), mTCoords(nullptr), mNumBoundaryEdges(0), mBoundaryStart(0) { } virtual ~GenerateMeshUV() = default; // The incoming mesh must be edge-triangle manifold and have rectangle // topology (simply connected, closed polyline boundary). The arrays // 'vertices' and 'tcoords' must both have 'numVertices' elements. // Set 'useSquareTopology' to true for the generated coordinates to // live in the uv-square [0,1]^2. Set it to false for the generated // coordinates to live in a convex polygon that inscribes the uv-disk // of center (1/2,1/2) and radius 1/2. void operator()(uint32_t numIterations, bool useSquareTopology, int32_t numVertices, Vector3<Real> const* vertices, int32_t numIndices, int32_t const* indices, Vector2<Real>* tcoords) { // Ensure that numIterations is even, which avoids having a memory // copy from the temporary ping-pong buffer to 'tcoords'. if (numIterations & 1) { ++numIterations; } mNumVertices = numVertices; mVertices = vertices; mTCoords = tcoords; // The linear system solver has a first pass to initialize the // texture coordinates to ensure the Gauss-Seidel iteration // converges rapidly. This requires the texture coordinates all // start as (-1,-1). for (int32_t i = 0; i < numVertices; ++i) { mTCoords[i][0] = (Real)-1; mTCoords[i][1] = (Real)-1; } // Create the manifold mesh data structure. mGraph.Clear(); int32_t const numTriangles = numIndices / 3; for (int32_t t = 0; t < numTriangles; ++t) { int32_t v0 = *indices++; int32_t v1 = *indices++; int32_t v2 = *indices++; mGraph.Insert(v0, v1, v2); } TopologicalVertexDistanceTransform(); if (useSquareTopology) { AssignBoundaryTextureCoordinatesSquare(); } else { AssignBoundaryTextureCoordinatesDisk(); } ComputeMeanValueWeights(); SolveSystem(numIterations); } protected: // A CPU-based implementation is provided by this class. The derived // classes using the GPU override this function. virtual void SolveSystemInternal(uint32_t numIterations) { if (mNumThreads > 1) { SolveSystemCPUMultiple(numIterations); } else { SolveSystemCPUSingle(numIterations); } } // Constructor inputs. uint32_t mNumThreads; std::function<void(uint32_t)> const* mProgress; // Convenience members that store the input parameters to operator(). int32_t mNumVertices; Vector3<Real> const* mVertices; Vector2<Real>* mTCoords; // The edge-triangle manifold graph, where each edge is shared by at // most two triangles. ETManifoldMesh mGraph; // The mVertexInfo array stores -1 for the interior vertices. For a // boundary edge <v0,v1> that is counterclockwise, // mVertexInfo[v0] = v1, which gives us an orded boundary polyline. std::vector<int32_t> mVertexInfo; int32_t mNumBoundaryEdges, mBoundaryStart; typedef ETManifoldMesh::Edge Edge; std::set<Edge*> mInteriorEdges; // The vertex graph required to set up a sparse linear system of // equations to determine the texture coordinates. struct Vertex { // The topological distance from the boundary of the mesh. int32_t distance; // The value range0 is the index into mVertexGraphData for the // first adjacent vertex. The value range1 is the number of // adjacent vertices. int32_t range0, range1; // Unused on the CPU. The padding is necessary for the HLSL and // GLSL programs in GPUGenerateMeshUV.h. int32_t padding; }; std::vector<Vertex> mVertexGraph; std::vector<std::pair<int32_t, Real>> mVertexGraphData; // The vertices are listed in the order determined by a topological // distance transform. Boundary vertices have 'distance' 0. Any // vertices that are not boundary vertices but are edge-adjacent to // boundary vertices have 'distance' 1. Neighbors of those have // distance '2', and so on. The mOrderedVertices array stores // distance-0 vertices first, distance-1 vertices second, and so on. std::vector<int32_t> mOrderedVertices; private: void TopologicalVertexDistanceTransform() { // Initialize the graph information. mVertexInfo.resize(mNumVertices); std::fill(mVertexInfo.begin(), mVertexInfo.end(), -1); mVertexGraph.resize(mNumVertices); mVertexGraphData.resize(2 * mGraph.GetEdges().size()); std::pair<int32_t, Real> initialData = std::make_pair(-1, (Real)-1); std::fill(mVertexGraphData.begin(), mVertexGraphData.end(), initialData); mOrderedVertices.resize(mNumVertices); mInteriorEdges.clear(); mNumBoundaryEdges = 0; mBoundaryStart = std::numeric_limits<int32_t>::max(); // Count the number of adjacent vertices for each vertex. For // data sets with a large number of vertices, this is a // preprocessing step to avoid a dynamic data structure that has // a large number of std:map objects that take a very long time // to destroy when a debugger is attached to the executable. // Instead, we allocate a single array that stores all the // adjacency information. It is also necessary to bundle the // data this way for a GPU version of the algorithm. std::vector<int32_t> numAdjacencies(mNumVertices); std::fill(numAdjacencies.begin(), numAdjacencies.end(), 0); for (auto const& element : mGraph.GetEdges()) { ++numAdjacencies[element.first.V[0]]; ++numAdjacencies[element.first.V[1]]; if (element.second->T[1]) { // This is an interior edge. mInteriorEdges.insert(element.second.get()); } else { // This is a boundary edge. Determine the ordering of the // vertex indices to make the edge counterclockwise. ++mNumBoundaryEdges; int32_t v0 = element.second->V[0], v1 = element.second->V[1]; auto tri = element.second->T[0]; int32_t i; for (i = 0; i < 3; ++i) { int32_t v2 = tri->V[i]; if (v2 != v0 && v2 != v1) { // The vertex is opposite the boundary edge. v0 = tri->V[(i + 1) % 3]; v1 = tri->V[(i + 2) % 3]; mVertexInfo[v0] = v1; mBoundaryStart = std::min(mBoundaryStart, v0); break; } } } } // Set the range data for each vertex. for (int32_t vIndex = 0, aIndex = 0; vIndex < mNumVertices; ++vIndex) { int32_t numAdjacent = numAdjacencies[vIndex]; mVertexGraph[vIndex].range0 = aIndex; mVertexGraph[vIndex].range1 = numAdjacent; aIndex += numAdjacent; mVertexGraph[vIndex].padding = 0; } // Compute a topological distance transform of the vertices. std::set<int32_t> currFront; for (auto const& element : mGraph.GetEdges()) { int32_t v0 = element.second->V[0], v1 = element.second->V[1]; for (int32_t i = 0; i < 2; ++i) { if (mVertexInfo[v0] == -1) { mVertexGraph[v0].distance = -1; } else { mVertexGraph[v0].distance = 0; currFront.insert(v0); } // Insert v1 into the first available slot of the // adjacency array. int32_t range0 = mVertexGraph[v0].range0; int32_t range1 = mVertexGraph[v0].range1; for (int32_t j = 0; j < range1; ++j) { std::pair<int32_t, Real>& data = mVertexGraphData[static_cast<size_t>(range0) + j]; if (data.second == (Real)-1) { data.first = v1; data.second = (Real)0; break; } } std::swap(v0, v1); } } // Use a breadth-first search to propagate the distance // information. int32_t nextDistance = 1; size_t numFrontVertices = currFront.size(); std::copy(currFront.begin(), currFront.end(), mOrderedVertices.begin()); while (currFront.size() > 0) { std::set<int32_t> nextFront; for (auto v : currFront) { int32_t range0 = mVertexGraph[v].range0; int32_t range1 = mVertexGraph[v].range1; auto* current = &mVertexGraphData[range0]; for (int32_t j = 0; j < range1; ++j, ++current) { int32_t a = current->first; if (mVertexGraph[a].distance == -1) { mVertexGraph[a].distance = nextDistance; nextFront.insert(a); } } } std::copy(nextFront.begin(), nextFront.end(), mOrderedVertices.begin() + numFrontVertices); numFrontVertices += nextFront.size(); currFront = std::move(nextFront); ++nextDistance; } } void AssignBoundaryTextureCoordinatesSquare() { // Map the boundary of the mesh to the unit square [0,1]^2. The // selection of square vertices is such that the relative // distances between boundary vertices and the relative distances // between polygon vertices is preserved, except that the four // corners of the square are required to have boundary points // mapped to them. The first boundary point has an implied // distance of zero. The value distance[i] is the length of the // boundary polyline from vertex 0 to vertex i+1. std::vector<Real> distance(mNumBoundaryEdges); Real total = (Real)0; int32_t v0 = mBoundaryStart, v1, i; for (i = 0; i < mNumBoundaryEdges; ++i) { v1 = mVertexInfo[v0]; total += Length(mVertices[v1] - mVertices[v0]); distance[i] = total; v0 = v1; } Real invTotal = (Real)1 / total; for (auto& d : distance) { d *= invTotal; } auto begin = distance.begin(), end = distance.end(); int32_t endYMin = (int32_t)(std::lower_bound(begin, end, (Real)0.25) - begin); int32_t endXMax = (int32_t)(std::lower_bound(begin, end, (Real)0.50) - begin); int32_t endYMax = (int32_t)(std::lower_bound(begin, end, (Real)0.75) - begin); int32_t endXMin = (int32_t)distance.size() - 1; // The first polygon vertex is (0,0). The remaining vertices are // chosen counterclockwise around the square. v0 = mBoundaryStart; mTCoords[v0][0] = (Real)0; mTCoords[v0][1] = (Real)0; for (i = 0; i < endYMin; ++i) { v1 = mVertexInfo[v0]; mTCoords[v1][0] = distance[i] * (Real)4; mTCoords[v1][1] = (Real)0; v0 = v1; } v1 = mVertexInfo[v0]; mTCoords[v1][0] = (Real)1; mTCoords[v1][1] = (Real)0; v0 = v1; for (++i; i < endXMax; ++i) { v1 = mVertexInfo[v0]; mTCoords[v1][0] = (Real)1; mTCoords[v1][1] = distance[i] * (Real)4 - (Real)1; v0 = v1; } v1 = mVertexInfo[v0]; mTCoords[v1][0] = (Real)1; mTCoords[v1][1] = (Real)1; v0 = v1; for (++i; i < endYMax; ++i) { v1 = mVertexInfo[v0]; mTCoords[v1][0] = (Real)3 - distance[i] * (Real)4; mTCoords[v1][1] = (Real)1; v0 = v1; } v1 = mVertexInfo[v0]; mTCoords[v1][0] = (Real)0; mTCoords[v1][1] = (Real)1; v0 = v1; for (++i; i < endXMin; ++i) { v1 = mVertexInfo[v0]; mTCoords[v1][0] = (Real)0; mTCoords[v1][1] = (Real)4 - distance[i] * (Real)4; v0 = v1; } } void AssignBoundaryTextureCoordinatesDisk() { // Map the boundary of the mesh to a convex polygon. The selection // of convex polygon vertices is such that the relative distances // between boundary vertices and the relative distances between // polygon vertices is preserved. The first boundary point has an // implied distance of zero. The value distance[i] is the length // of the boundary polyline from vertex 0 to vertex i+1. std::vector<Real> distance(mNumBoundaryEdges); Real total = (Real)0; int32_t v0 = mBoundaryStart; for (int32_t i = 0; i < mNumBoundaryEdges; ++i) { int32_t v1 = mVertexInfo[v0]; total += Length(mVertices[v1] - mVertices[v0]); distance[i] = total; v0 = v1; } // The convex polygon lives in [0,1]^2 and inscribes a circle with // center (1/2,1/2) and radius 1/2. The polygon center is not // necessarily the circle center! This is the case when a // boundary edge has length larger than half the total length of // the boundary polyline; we do not expect such data for our // meshes. The first polygon vertex is (1/2,0). The remaining // vertices are chosen counterclockwise around the polygon. Real multiplier = (Real)GTE_C_TWO_PI / total; v0 = mBoundaryStart; mTCoords[v0][0] = (Real)1; mTCoords[v0][1] = (Real)0.5; for (int32_t i = 1, im1 = 0; i < mNumBoundaryEdges; ++i, ++im1) { int32_t v1 = mVertexInfo[v0]; Real angle = multiplier * distance[im1]; mTCoords[v1][0] = (std::cos(angle) + (Real)1) * (Real)0.5; mTCoords[v1][1] = (std::sin(angle) + (Real)1) * (Real)0.5; v0 = v1; } } void ComputeMeanValueWeights() { for (auto const& edge : mInteriorEdges) { int32_t v0 = edge->V[0], v1 = edge->V[1]; for (int32_t i = 0; i < 2; ++i) { // Compute the direction from X0 to X1 and compute the // length of the edge (X0,X1). Vector3<Real> X0 = mVertices[v0]; Vector3<Real> X1 = mVertices[v1]; Vector3<Real> X1mX0 = X1 - X0; Real x1mx0length = Normalize(X1mX0); Real weight; if (x1mx0length > (Real)0) { // Compute the weight for X0 associated with X1. weight = (Real)0; for (int32_t j = 0; j < 2; ++j) { // Find the vertex of triangle T[j] opposite edge // <X0,X1>. auto tri = edge->T[j]; int32_t k; for (k = 0; k < 3; ++k) { int32_t v2 = tri->V[k]; if (v2 != v0 && v2 != v1) { Vector3<Real> X2 = mVertices[v2]; Vector3<Real> X2mX0 = X2 - X0; Real x2mx0Length = Normalize(X2mX0); if (x2mx0Length > (Real)0) { Real dot = Dot(X2mX0, X1mX0); Real cs = std::min(std::max(dot, (Real)-1), (Real)1); Real angle = std::acos(cs); weight += std::tan(angle * (Real)0.5); } else { weight += (Real)1; } break; } } } weight /= x1mx0length; } else { weight = (Real)1; } int32_t range0 = mVertexGraph[v0].range0; int32_t range1 = mVertexGraph[v0].range1; for (int32_t j = 0; j < range1; ++j) { std::pair<int32_t, Real>& data = mVertexGraphData[static_cast<size_t>(range0) + j]; if (data.first == v1) { data.second = weight; } } std::swap(v0, v1); } } } void SolveSystem(uint32_t numIterations) { // On the first pass, average only neighbors whose texture // coordinates have been computed. This is a good initial guess // for the linear system and leads to relatively fast convergence // of the Gauss-Seidel iterates. Real zero = (Real)0; for (int32_t i = mNumBoundaryEdges; i < mNumVertices; ++i) { int32_t v0 = mOrderedVertices[i]; int32_t range0 = mVertexGraph[v0].range0; int32_t range1 = mVertexGraph[v0].range1; auto const* current = &mVertexGraphData[range0]; Vector2<Real> tcoord{ zero, zero }; Real weight, weightSum = zero; for (int32_t j = 0; j < range1; ++j, ++current) { int32_t v1 = current->first; if (mTCoords[v1][0] != -1.0f) { weight = current->second; weightSum += weight; tcoord += weight * mTCoords[v1]; } } tcoord /= weightSum; mTCoords[v0] = tcoord; } SolveSystemInternal(numIterations); } void SolveSystemCPUSingle(uint32_t numIterations) { // Use ping-pong buffers for the texture coordinates. std::vector<Vector2<Real>> tcoords(mNumVertices); size_t numBytes = mNumVertices * sizeof(Vector2<Real>); std::memcpy(&tcoords[0], mTCoords, numBytes); Vector2<Real>* inTCoords = mTCoords; Vector2<Real>* outTCoords = &tcoords[0]; // The value numIterations is even, so we always swap an even // number of times. This ensures that on exit from the loop, // outTCoords is tcoords. for (uint32_t i = 1; i <= numIterations; ++i) { if (mProgress) { (*mProgress)(i); } for (int32_t j = mNumBoundaryEdges; j < mNumVertices; ++j) { int32_t v0 = mOrderedVertices[j]; int32_t range0 = mVertexGraph[v0].range0; int32_t range1 = mVertexGraph[v0].range1; auto const* current = &mVertexGraphData[range0]; Vector2<Real> tcoord{ (Real)0, (Real)0 }; Real weight, weightSum = (Real)0; for (int32_t k = 0; k < range1; ++k, ++current) { int32_t v1 = current->first; weight = current->second; weightSum += weight; tcoord += weight * inTCoords[v1]; } tcoord /= weightSum; outTCoords[v0] = tcoord; } std::swap(inTCoords, outTCoords); } } void SolveSystemCPUMultiple(uint32_t numIterations) { // Use ping-pong buffers for the texture coordinates. std::vector<Vector2<Real>> tcoords(mNumVertices); size_t numBytes = mNumVertices * sizeof(Vector2<Real>); std::memcpy(&tcoords[0], mTCoords, numBytes); Vector2<Real>* inTCoords = mTCoords; Vector2<Real>* outTCoords = &tcoords[0]; // Partition the data for multiple threads. int32_t numV = mNumVertices - mNumBoundaryEdges; int32_t numVPerThread = numV / mNumThreads; std::vector<int32_t> vmin(mNumThreads), vmax(mNumThreads); for (uint32_t t = 0; t < mNumThreads; ++t) { vmin[t] = mNumBoundaryEdges + t * numVPerThread; vmax[t] = vmin[t] + numVPerThread - 1; } vmax[mNumThreads - 1] = mNumVertices - 1; // The value numIterations is even, so we always swap an even // number of times. This ensures that on exit from the loop, // outTCoords is tcoords. for (uint32_t i = 1; i <= numIterations; ++i) { if (mProgress) { (*mProgress)(i); } // Execute Gauss-Seidel iterations in multiple threads. std::vector<std::thread> process(mNumThreads); for (uint32_t t = 0; t < mNumThreads; ++t) { process[t] = std::thread([this, t, &vmin, &vmax, inTCoords, outTCoords]() { for (int32_t j = vmin[t]; j <= vmax[t]; ++j) { int32_t v0 = mOrderedVertices[j]; int32_t range0 = mVertexGraph[v0].range0; int32_t range1 = mVertexGraph[v0].range1; auto const* current = &mVertexGraphData[range0]; Vector2<Real> tcoord{ (Real)0, (Real)0 }; Real weight, weightSum = (Real)0; for (int32_t k = 0; k < range1; ++k, ++current) { int32_t v1 = current->first; weight = current->second; weightSum += weight; tcoord += weight * inTCoords[v1]; } tcoord /= weightSum; outTCoords[v0] = tcoord; } }); } // Wait for all threads to finish. for (uint32_t t = 0; t < mNumThreads; ++t) { process[t].join(); } std::swap(inTCoords, outTCoords); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprOrthogonalLine2.h
.h
4,227
118
// 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/Line.h> #include <Mathematics/SymmetricEigensolver2x2.h> #include <Mathematics/Vector2.h> // Least-squares fit of a line to (x,y) data by using distance measurements // orthogonal to the proposed line. The return value is 'true' if and only // if the fit is unique (always successful, 'true' when a minimum eigenvalue // is unique). The mParameters value is a line with (P,D) = // (origin,direction). The error for S = (x0,y0) is (S-P)^T*(I - D*D^T)*(S-P). namespace gte { template <typename Real> class ApprOrthogonalLine2 : public ApprQuery<Real, Vector2<Real>> { public: // Initialize the model parameters to zero. ApprOrthogonalLine2() : mParameters(Vector2<Real>::Zero(), 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++]; } mean /= (Real)numIndices; 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]; } // 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); // The line direction is the eigenvector in the direction // of largest variance of the points. mParameters.origin = mean; mParameters.direction = evec[1]; // The fitted line is unique when the maximum eigenvalue // has multiplicity 1. return eval[0] < eval[1]; } } mParameters = Line2<Real>(Vector2<Real>::Zero(), Vector2<Real>::Zero()); return false; } // Get the parameters for the best fit. Line2<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.origin; Real sqrlen = Dot(diff, diff); Real dot = Dot(diff, mParameters.direction); Real error = std::fabs(sqrlen - dot * dot); return error; } virtual void CopyParameters(ApprQuery<Real, Vector2<Real>> const* input) override { auto source = dynamic_cast<ApprOrthogonalLine2<Real> const*>(input); if (source) { *this = *source; } } private: Line2<Real> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RootsBisection2.h
.h
4,350
111
// 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/RootsBisection1.h> // Estimate a root to continuous functions F(x,y) and G(x,y) define on a // rectangle [xMin,xMax]x[yMin,yMax]. The requirements are that for each // y' in [yMin,yMax], A(x) = F(x,y') satisfies A(xMin) * A(xMax) < 0, // which guarantees A(x) has a root. Also, for each x' in [xMin,xMax], // B(y) = G(x',y) satisfies B(yMin) * B(yMax) < 0, which guarantees B(y) // has a root. Bisection is performed in the x-direction for A(x). Let // x' be the root. Bisection is then performed in the y-direction for // B(y). Let y' be the root. The function value is A(x') = F(x',y'). // This effectively is a bisection of C(x) = F(x,h(x)) along the curve // where G(x,h(x)) = 0. namespace gte { template <typename Real> class RootsBisection2 { public: // Use this constructor when Real is a floating-point type. template <typename Dummy = Real> RootsBisection2(uint32_t xMaxIterations, uint32_t yMaxIterations, typename std::enable_if<!is_arbitrary_precision<Dummy>::value>::type* = nullptr) : mXBisector(xMaxIterations), mYBisector(yMaxIterations), mXRoot(0), mYRoot(0), mFAtRoot(0), mGAtRoot(0), mNoGuaranteeForRootBound(false) { static_assert(!is_arbitrary_precision<Real>::value, "Template parameter is not a floating-point type."); } // Use this constructor when Real is an arbitrary-precision type. template <typename Dummy = Real> RootsBisection2(uint32_t precision, uint32_t xMaxIterations, uint32_t yMaxIterations, typename std::enable_if<is_arbitrary_precision<Dummy>::value>::type* = nullptr) : mXBisector(precision, xMaxIterations), mYBisector(precision, yMaxIterations), mXRoot(0), mYRoot(0), mFAtRoot(0), mGAtRoot(0), mNoGuaranteeForRootBound(false) { static_assert(is_arbitrary_precision<Real>::value, "Template parameter is not an arbitrary-precision type."); } // Disallow copy and move semantics. RootsBisection2(RootsBisection2 const&) = delete; RootsBisection2(RootsBisection2&&) = delete; RootsBisection2& operator=(RootsBisection2 const&) = delete; RootsBisection2& operator=(RootsBisection2&&) = delete; uint32_t operator()( std::function<Real(Real const&, Real const&)> F, std::function<Real(Real const&, Real const&)> G, Real const& xMin, Real const& xMax, Real const& yMin, Real const& yMax, Real& xRoot, Real& yRoot, Real& fAtRoot, Real& gAtRoot) { // XFunction(x) = F(x,y), where G(x,y) = 0. auto XFunction = [this, &F, &G, &yMin, &yMax](Real const& x) { // YFunction(y) = G(x,y) auto YFunction = [&G, &x](Real const& y) { return G(x, y); }; // Bisect in the y-variable to find the root of YFunction(y). uint32_t numYIterations = mYBisector(YFunction, yMin, yMax, mYRoot, mGAtRoot); mNoGuaranteeForRootBound = (numYIterations == 0); return F(x, mYRoot); }; // Bisect in the x-variable to find the root of XFunction(x). uint32_t numXIterations = mXBisector(XFunction, xMin, xMax, mXRoot, mFAtRoot); mNoGuaranteeForRootBound = (numXIterations == 0); xRoot = mXRoot; yRoot = mYRoot; fAtRoot = mFAtRoot; gAtRoot = mGAtRoot; return numXIterations; } inline bool NoGuaranteeForRootBound() const { return mNoGuaranteeForRootBound; } private: RootsBisection1<Real> mXBisector, mYBisector; Real mXRoot, mYRoot, mFAtRoot, mGAtRoot; bool mNoGuaranteeForRootBound; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RigidBody.h
.h
23,429
667
// 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.06 #pragma once #include <Mathematics/Matrix3x3.h> #include <Mathematics/Rotation.h> #include <Mathematics/LinearSystem.h> #include <functional> #include <memory> // The classes in this file support an implementation of collision response // for acceleration-based constrained motion using impulse functions. The // description is in Chapter 6 of "Game Physics, 2nd edition". For a // description of the construction of impulse forces, see // https://www.geometrictools.com/Documentation/ComputingImpulsiveForces.pdf namespace gte { // The rigid body state is stored in a separate structure so that // the Force and Torque functionals can be passed a single object // to avoid a large number of parameters that would otherwise have // to be passed to the functionals. This makes the Runge-Kutta ODE // solver easier to read. The RigidBody<T> class provides wrappers // around the state accessors to avoid exposing a public state member. template <typename T> class RigidBodyState { public: RigidBodyState() : mMass(static_cast<T>(0)), mInvMass(static_cast<T>(0)), mBodyInertia(Matrix3x3<T>::Zero()), mBodyInverseInertia(Matrix3x3<T>::Zero()), mPosition(Vector3<T>::Zero()), mQOrientation(Quaternion<T>::Identity()), mLinearMomentum(Vector3<T>::Zero()), mAngularMomentum(Vector3<T>::Zero()), mWorldInertia(Matrix3x3<T>::Zero()), mWorldInverseInertia(Matrix3x3<T>::Zero()), mROrientation(Matrix3x3<T>::Identity()), mLinearVelocity(Vector3<T>::Zero()), mAngularVelocity(Vector3<T>::Zero()), mQAngularVelocity{} { } // Set the mass to a positive number for movable bodies. Set the mass // to zero for immovable objects. A body is immovable in the physics // simulation, but you can position and orient the immovable body // manually, typically during the creation of the physics objects. void SetMass(T mass) { T const zero = static_cast<T>(0); if (mass > zero) { mMass = mass; mInvMass = static_cast<T>(1) / mass; } else { mMass = zero; mInvMass = zero; } } // Set the body inertia to a positive definite matrix for movable // bodies. Set the body inertia to the zero matrix for immovable // objects, but you can position and orient the immovable body // manually, typically during the creation of the physics objects. void SetBodyInertia(Matrix3x3<T> const& bodyInertia) { Matrix3x3<T> const zero = Matrix3x3<T>::Zero(); if (bodyInertia != zero) { mBodyInertia = bodyInertia; mBodyInverseInertia = Inverse(bodyInertia); UpdateWorldInertialQuantities(); } else { mBodyInertia = zero; mBodyInverseInertia = zero; mWorldInertia = zero; mWorldInverseInertia = zero; } } inline bool IsMovable() const { return mMass > static_cast<T>(0); } inline bool IsImmovable() const { return mMass == static_cast<T>(0); } inline void SetPosition(Vector3<T> const& position) { mPosition = position; } void SetQOrientation(Quaternion<T> const& qOrientation, bool normalize = false) { mQOrientation = qOrientation; if (normalize) { Normalize(mQOrientation); } mROrientation = Rotation<3, T>(qOrientation); if (IsMovable()) { UpdateWorldInertialQuantities(); } } void SetLinearMomentum(Vector3<T> const& linearMomentum) { if (IsMovable()) { mLinearMomentum = linearMomentum; mLinearVelocity = mInvMass * linearMomentum; } } void SetAngularMomentum(Vector3<T> const& angularMomentum) { if (IsMovable()) { mAngularMomentum = angularMomentum; mAngularVelocity = mWorldInverseInertia * angularMomentum; mQAngularVelocity[0] = mAngularVelocity[0]; mQAngularVelocity[1] = mAngularVelocity[1]; mQAngularVelocity[2] = mAngularVelocity[2]; mQAngularVelocity[3] = static_cast<T>(0); } } void SetROrientation(Matrix3x3<T> const& rOrientation) { mROrientation = rOrientation; mQOrientation = Rotation<3, T>(rOrientation); if (IsMovable()) { UpdateWorldInertialQuantities(); } } void SetLinearVelocity(Vector3<T> const& linearVelocity) { if (IsMovable()) { mLinearVelocity = linearVelocity; mLinearMomentum = mMass * linearVelocity; } } void SetAngularVelocity(Vector3<T> const& angularVelocity) { if (IsMovable()) { mAngularVelocity = angularVelocity; mAngularMomentum = mWorldInertia * angularVelocity; mQAngularVelocity[0] = mAngularVelocity[0]; mQAngularVelocity[1] = mAngularVelocity[1]; mQAngularVelocity[2] = mAngularVelocity[2]; mQAngularVelocity[3] = static_cast<T>(0); } } inline T const& GetMass() const { return mMass; } inline T const& GetInverseMass() const { return mInvMass; } inline Matrix3x3<T> const& GetBodyInertia() const { return mBodyInertia; } inline Matrix3x3<T> const& GetBodyInverseInertia() const { return mBodyInverseInertia; } inline Matrix3x3<T> const& GetWorldInertia() const { return mWorldInertia; } inline Matrix3x3<T> const& GetWorldInverseInertia() const { return mWorldInverseInertia; } inline Vector3<T> const& GetPosition() const { return mPosition; } inline Quaternion<T> const& GetQOrientation() const { return mQOrientation; } inline Vector3<T> const& GetLinearMomentum() const { return mLinearMomentum; } inline Vector3<T> const& GetAngularMomentum() const { return mAngularMomentum; } inline Matrix3x3<T> const& GetROrientation() const { return mROrientation; } inline Vector3<T> const& GetLinearVelocity() const { return mLinearVelocity; } inline Vector3<T> const& GetAngularVelocity() const { return mAngularVelocity; } inline Quaternion<T> const& GetQAngularVelocity() const { return mQAngularVelocity; } private: void UpdateWorldInertialQuantities() { mWorldInertia = MultiplyABT( mROrientation * mBodyInertia, mROrientation); mWorldInverseInertia = MultiplyABT( mROrientation * mBodyInverseInertia, mROrientation); } // Constant quantities during the simulation. T mMass; T mInvMass; Matrix3x3<T> mBodyInertia; Matrix3x3<T> mBodyInverseInertia; // State variables in the differential equations of motion. Vector3<T> mPosition; Quaternion<T> mQOrientation; Vector3<T> mLinearMomentum; Vector3<T> mAngularMomentum; // Quantities derived from the state variables. Matrix3x3<T> mWorldInertia; Matrix3x3<T> mWorldInverseInertia; Matrix3x3<T> mROrientation; Vector3<T> mLinearVelocity; Vector3<T> mAngularVelocity; Quaternion<T> mQAngularVelocity; }; template <typename T> class RigidBody { public: // The rigid body state is initialized to zero values. Set the members // before starting the simulation. For immovable objects, set mass to // zero. RigidBody() : Force{}, Torque{}, mState{} { } virtual ~RigidBody() = default; // Set the mass to a positive number for movable bodies. Set the mass // to zero for immovable objects. A body is immovable in the physics // simulation, but you can position and orient the immovable body // manually, typically during the creation of the physics objects. inline void SetMass(T mass) { mState.SetMass(mass); } // Set the body inertia to a positive definite matrix for movable // bodies. Set the body inertia to the zero matrix for immovable // objects, but you can position and orient the immovable body // manually, typically during the creation of the physics objects. inline void SetBodyInertia(Matrix3x3<T> const& bodyInertia) { mState.SetBodyInertia(bodyInertia); } inline bool IsMovable() const { return mState.IsMovable(); } inline bool IsImmovable() const { return mState.IsImmovable(); } inline void SetPosition(Vector3<T> const& position) { mState.SetPosition(position); } inline void SetQOrientation(Quaternion<T> const& qOrientation, bool normalize = false) { mState.SetQOrientation(qOrientation, normalize); } inline void SetLinearMomentum(Vector3<T> const& linearMomentum) { mState.SetLinearMomentum(linearMomentum); } inline void SetAngularMomentum(Vector3<T> const& angularMomentum) { mState.SetAngularMomentum(angularMomentum); } inline void SetROrientation(Matrix3x3<T> const& rOrientation) { mState.SetROrientation(rOrientation); } inline void SetLinearVelocity(Vector3<T> const& linearVelocity) { mState.SetLinearVelocity(linearVelocity); } inline void SetAngularVelocity(Vector3<T> const& angularVelocity) { mState.SetAngularVelocity(angularVelocity); } inline T const& GetMass() const { return mState.GetMass(); } inline T const& GetInverseMass() const { return mState.GetInverseMass(); } inline Matrix3x3<T> const& GetBodyInertia() const { return mState.GetBodyInertia(); } inline Matrix3x3<T> const& GetBodyInverseInertia() const { return mState.GetBodyInverseInertia(); } inline Matrix3x3<T> const& GetWorldInertia() const { return mState.GetWorldInertia(); } inline Matrix3x3<T> const& GetWorldInverseInertia() const { return mState.GetWorldInverseInertia(); } inline Vector3<T> const& GetPosition() const { return mState.GetPosition(); } inline Quaternion<T> const& GetQOrientation() const { return mState.GetQOrientation(); } inline Vector3<T> const& GetLinearMomentum() const { return mState.GetLinearMomentum(); } inline Vector3<T> const& GetAngularMomentum() const { return mState.GetAngularMomentum(); } inline Matrix3x3<T> const& GetROrientation() const { return mState.GetROrientation(); } inline Vector3<T> const& GetLinearVelocity() const { return mState.GetLinearVelocity(); } inline Vector3<T> const& GetAngularVelocity() const { return mState.GetAngularVelocity();; } inline Quaternion<T> const& GetQAngularVelocity() const { return mState.GetQAngularVelocity(); } // Force and torque functions. The first input (type T) is the // simulation time. The second input is rigid body state. These // functions must be set before starting the simulation. using Function = std::function<Vector3<T>(T, RigidBodyState<T> const&)>; Function Force; Function Torque; // Runge-Kutta fourth-order differential equation solver void Update(T const& t, T const& dt) { // TODO: When GTE_MAT_VEC is not defined (i.e. use vec-mat), // test to see whether dq/dt = 0.5 * w * q (mat-vec convention) // needs to become a different equation. T const half = static_cast<T>(0.5); T const two = static_cast<T>(2); T const six = static_cast<T>(6); T halfDT = half * dt; T sixthDT = dt / six; T TpHalfDT = t + halfDT; T TpDT = t + dt; RigidBodyState<T> newState{}; newState.SetMass(GetMass()); newState.SetBodyInertia(GetBodyInertia()); // A1 = G(T,S0), B1 = S0 + (DT/2)*A1 Vector3<T> A1DXDT = GetLinearVelocity(); Quaternion<T> W = GetQAngularVelocity(); Quaternion<T> A1DQDT = half * W * GetQOrientation(); Vector3<T> A1DPDT = Force(t, mState); Vector3<T> A1DLDT = Torque(t, mState); newState.SetPosition(GetPosition() + halfDT * A1DXDT); newState.SetQOrientation(GetQOrientation() + halfDT * A1DQDT, true); newState.SetLinearMomentum(GetLinearMomentum() + halfDT * A1DPDT); newState.SetAngularMomentum(GetAngularMomentum() + halfDT * A1DLDT); // A2 = G(T+DT/2,B1), B2 = S0 + (DT/2)*A2 Vector3<T> A2DXDT = newState.GetLinearVelocity(); W = newState.GetQAngularVelocity(); Quaternion<T> A2DQDT = half * W * newState.GetQOrientation(); Vector3<T> A2DPDT = Force(TpHalfDT, newState); Vector3<T> A2DLDT = Torque(TpHalfDT, newState); newState.SetPosition(GetPosition() + halfDT * A2DXDT); newState.SetQOrientation(GetQOrientation() + halfDT * A2DQDT, true); newState.SetLinearMomentum(GetLinearMomentum() + halfDT * A2DPDT); newState.SetAngularMomentum(GetAngularMomentum() + halfDT * A2DLDT); // A3 = G(T+DT/2,B2), B3 = S0 + DT*A3 Vector3<T> A3DXDT = newState.GetLinearVelocity(); W = newState.GetQAngularVelocity(); Quaternion<T> A3DQDT = half * W * newState.GetQOrientation(); Vector3<T> A3DPDT = Force(TpHalfDT, newState); Vector3<T> A3DLDT = Torque(TpHalfDT, newState); newState.SetPosition(GetPosition() + dt * A3DXDT); newState.SetQOrientation(GetQOrientation() + dt * A3DQDT, true); newState.SetLinearMomentum(GetLinearMomentum() + dt * A3DPDT); newState.SetAngularMomentum(GetAngularMomentum() + dt * A3DLDT); // A4 = G(T+DT,B3), S1 = S0 + (DT/6)*(A1+2*(A2+A3)+A4) Vector3<T> A4DXDT = newState.GetLinearVelocity(); W = newState.GetQAngularVelocity(); Quaternion<T> A4DQDT = half * W * newState.GetQOrientation(); Vector3<T> A4DPDT = Force(TpDT, newState); Vector3<T> A4DLDT = Torque(TpDT, newState); SetPosition(GetPosition() + sixthDT * (A1DXDT + two * (A2DXDT + A3DXDT) + A4DXDT)); SetQOrientation(GetQOrientation() + sixthDT * (A1DQDT + two * (A2DQDT + A3DQDT) + A4DQDT), true); SetLinearMomentum(GetLinearMomentum() + sixthDT * (A1DPDT + two * (A2DPDT + A3DPDT) + A4DPDT)); SetAngularMomentum(GetAngularMomentum() + sixthDT * (A1DLDT + two * (A2DLDT + A3DLDT) + A4DLDT)); } private: RigidBodyState<T> mState; }; // The rigid body contact stores basic information. The class can be // extended by derivation to allow for additional information that is // specific to a simulation. template <typename T> class RigidBodyContact { public: RigidBodyContact() : A{}, B{}, P(Vector3<T>::Zero()), N(Vector3<T>::Zero()), restitution(static_cast<T>(0)) { } virtual ~RigidBodyContact() = default; // Call ApplyImpulse for each rigid body in your simulation at the // the current simulation time. After all such calls are made, // then iterate over all your rigid bodies and call their // Update(time, deltaTime) functions. virtual void ApplyImpulse() { // The positions of the centers of mass. auto const& XA = A->GetPosition(); auto const& XB = B->GetPosition(); // The location of the contact points relative to the centers of // mass. auto rA = P - XA; auto rB = P - XB; // The preimpulse linear velocities of the centers of mass. auto const& linvelANeg = A->GetLinearVelocity(); auto const& linvelBNeg = B->GetLinearVelocity(); // The preimpulse angular velocities about the centers of mass. auto const& angvelANeg = A->GetAngularVelocity(); auto const& angvelBNeg = B->GetAngularVelocity(); // The preimpulse velocities of P0. auto velANeg = linvelANeg + Cross(angvelANeg, rA); auto velBNeg = linvelBNeg + Cross(angvelBNeg, rB); auto velDiffNeg = velANeg - velBNeg; // The preimpulse linear momenta of the centers of mass. auto const& linmomANeg = A->GetLinearMomentum(); auto const& linmomBNeg = B->GetLinearMomentum(); // The preimpulse angular momenta about the centers of mass. auto const& angmomANeg = A->GetAngularMomentum(); auto const& angmomBNeg = B->GetAngularMomentum(); // The inverse masses, inverse world inertia tensors and quadratic // forms associated with these tensors. T sumInvMasses = A->GetInverseMass() + B->GetInverseMass(); auto const& invJA = A->GetWorldInverseInertia(); auto const& invJB = B->GetWorldInverseInertia(); T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector3<T> T0 = velDiffNeg - Dot(N, velDiffNeg) * N; Normalize(T0); if (T0 != Vector3<T>::Zero()) { // T0 is tangent at P, unit length and perpendicular to N. Vector3<T> T1 = Cross(N, T0); auto rAxN = Cross(rA, N); auto rAxT0 = Cross(rA, T0); auto rAxT1 = Cross(rA, T1); auto rBxN = Cross(rB, N); auto rBxT0 = Cross(rB, T0); auto rBxT1 = Cross(rB, T1); // The matrix constructed here is positive definite. This // ensures the linear system always has a solution, so the // bool return value from LinearSystem<T>::Solve is // ignored. Matrix3x3<T> sysMatrix{}; sysMatrix(0, 0) = sumInvMasses + Dot(rAxN, invJA * rAxN) + Dot(rBxN, invJB * rBxN); sysMatrix(1, 1) = sumInvMasses + Dot(rAxT0, invJA * rAxT0) + Dot(rBxT0, invJB * rBxT0); sysMatrix(2, 2) = sumInvMasses + Dot(rAxT1, invJA * rAxT1) + Dot(rBxT1, invJB * rBxT1); sysMatrix(0, 1) = Dot(rAxN, invJA * rAxT0) + Dot(rBxN, invJB * rBxT0); sysMatrix(0, 2) = Dot(rAxN, invJA * rAxT1) + Dot(rBxN, invJB * rBxT1); sysMatrix(1, 2) = Dot(rAxT0, invJA * rAxT1) + Dot(rBxT0, invJB * rBxT1); sysMatrix(1, 0) = sysMatrix(0, 1); sysMatrix(2, 0) = sysMatrix(0, 2); sysMatrix(2, 1) = sysMatrix(1, 2); Vector3<T> sysInput{}; sysInput[0] = -(one + restitution) * Dot(N, velDiffNeg); sysInput[1] = zero; sysInput[2] = zero; Vector3<T> sysOutput{}; (void)LinearSystem<T>::Solve(sysMatrix, sysInput, sysOutput); // Apply the impulsive force to the bodies to change linear and // angular momentum. auto impulse = sysOutput[0] * N + sysOutput[1] * T0 + sysOutput[2] * T1; A->SetLinearMomentum(linmomANeg + impulse); B->SetLinearMomentum(linmomBNeg - impulse); A->SetAngularMomentum(angmomANeg + Cross(rA, impulse)); B->SetAngularMomentum(angmomBNeg - Cross(rB, impulse)); } else { // Fall back to the impulse force f*N0 when the relative // velocity at the contact P0 is parallel to N0. auto rAxN = Cross(rA, N); auto rBxN = Cross(rB, N); T quadformA = Dot(rAxN, invJA * rAxN); T quadformB = Dot(rBxN, invJB * rBxN); // The magnitude of the impulse force. T numer = -(one + restitution) * Dot(N, velDiffNeg); T denom = sumInvMasses + quadformA + quadformB; T f = numer / denom; // Apply the impulsive force to the bodies to change linear and // angular momentum. auto impulse = f * N; A->SetLinearMomentum(linmomANeg + impulse); B->SetLinearMomentum(linmomBNeg - impulse); A->SetAngularMomentum(angmomANeg + Cross(rA, impulse)); B->SetAngularMomentum(angmomBNeg - Cross(rB, impulse)); } } // Body A has the vertex in a vertex-face contact or edge-edge // contact. std::shared_ptr<RigidBody<T>> A; // Body B has the face in a vertex-face contact, and the normal N // is for that face. If there is instead an edge-edge contact, the // normal N is the cross product of the edges. std::shared_ptr<RigidBody<T>> B; // The intersection point at contact. Vector3<T> P; // The outward unit-length normal to the face at the contact // point. Vector3<T> N; // The coefficient of restitution which is in [0,1]. This allows for // the loss of kinetic energy at a contact point. T restitution; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox2Circle2.h
.h
3,620
103
// 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/IntrAlignedBox2Circle2.h> #include <Mathematics/DistPointOrientedBox.h> // The find-intersection query is based on the document // https://www.geometrictools.com/Documentation/IntersectionMovingCircleRectangle.pdf namespace gte { template <typename T> class TIQuery<T, OrientedBox2<T>, Circle2<T>> { public: // The intersection query considers the box and circle to be solids; // that is, the circle object includes the region inside the circular // boundary and the box object includes the region inside the // rectangular boundary. If the circle object and rectangle object // overlap, the objects intersect. struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(OrientedBox2<T> const& box, Circle2<T> const& circle) { DCPQuery<T, Vector2<T>, OrientedBox2<T>> pbQuery; auto pbResult = pbQuery(circle.center, box); Result result{}; result.intersect = (pbResult.sqrDistance <= circle.radius * circle.radius); return result; } }; template <typename T> class FIQuery<T, OrientedBox2<T>, Circle2<T>> : public FIQuery<T, AlignedBox2<T>, Circle2<T>> { public: // See the base class for the definition of 'struct Result'. typename FIQuery<T, AlignedBox2<T>, Circle2<T>>::Result operator()(OrientedBox2<T> const& box, Vector2<T> const& boxVelocity, Circle2<T> const& circle, Vector2<T> const& circleVelocity) { // Transform the oriented box to an axis-aligned box centered at // the origin and transform the circle accordingly. Compute the // velocity of the circle relative to the box. T const zero(0), one(1), minusOne(-1); Vector2<T> cdiff = circle.center - box.center; Vector2<T> vdiff = circleVelocity - boxVelocity; Vector2<T> C, V; for (int32_t i = 0; i < 2; ++i) { C[i] = Dot(cdiff, box.axis[i]); V[i] = Dot(vdiff, box.axis[i]); } // Change signs on components, if necessary, to transform C to the // first quadrant. Adjust the velocity accordingly. std::array<T, 2> sign{ (T)0, (T)0 }; for (int32_t i = 0; i < 2; ++i) { if (C[i] >= zero) { sign[i] = one; } else { C[i] = -C[i]; V[i] = -V[i]; sign[i] = minusOne; } } typename FIQuery<T, AlignedBox2<T>, Circle2<T>>::Result result{}; this->DoQuery(box.extent, C, circle.radius, V, result); if (result.intersectionType != 0) { // Transform back to the original coordinate system. result.contactPoint = box.center + (sign[0] * result.contactPoint[0]) * box.axis[0] + (sign[1] * result.contactPoint[1]) * box.axis[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrHalfspace3Ellipsoid3.h
.h
1,676
54
// 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/Halfspace.h> #include <Mathematics/Hyperellipsoid.h> #include <Mathematics/Matrix3x3.h> // Queries for intersection of objects with halfspaces. These are useful for // containment testing, object culling, and clipping. namespace gte { template <typename T> class TIQuery<T, Halfspace3<T>, Ellipsoid3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Halfspace3<T> const& halfspace, Ellipsoid3<T> const& ellipsoid) { // Project the ellipsoid onto the normal line. The plane of the // halfspace occurs at the origin (zero) of the normal line. Result result{}; Matrix3x3<T> MInverse; ellipsoid.GetMInverse(MInverse); T discr = Dot(halfspace.normal, MInverse * halfspace.normal); T extent = std::sqrt(std::max(discr, (T)0)); T center = Dot(halfspace.normal, ellipsoid.center) - halfspace.constant; T tmax = center + extent; // The ellipsoid and halfspace intersect when the projection // interval maximum is nonnegative. result.intersect = (tmax >= (T)0); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrSegment3Plane3.h
.h
3,261
114
// 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/IntrLine3Plane3.h> #include <Mathematics/Segment.h> namespace gte { template <typename T> class TIQuery<T, Segment3<T>, Plane3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Segment3<T> const& segment, Plane3<T> const& plane) { Result result{}; // Compute the (signed) distance from the segment endpoints to the // plane. DCPQuery<T, Vector3<T>, Plane3<T>> vpQuery{}; T sdistance0 = vpQuery(segment.p[0], plane).signedDistance; if (sdistance0 == (T)0) { // Endpoint p[0] is on the plane. result.intersect = true; return result; } T sdistance1 = vpQuery(segment.p[1], plane).signedDistance; if (sdistance1 == (T)0) { // Endpoint p[1] is on the plane. result.intersect = true; return result; } // Test whether the segment transversely intersects the plane. result.intersect = (sdistance0 * sdistance1 < (T)0); return result; } }; template <typename T> class FIQuery<T, Segment3<T>, Plane3<T>> : public FIQuery<T, Line3<T>, Plane3<T>> { public: struct Result : public FIQuery<T, Line3<T>, Plane3<T>>::Result { Result() : FIQuery<T, Line3<T>, Plane3<T>>::Result{} { } // No additional information to compute. }; Result operator()(Segment3<T> const& segment, Plane3<T> const& plane) { Vector3<T> segOrigin{}, segDirection{}; T segExtent{}; segment.GetCenteredForm(segOrigin, segDirection, segExtent); Result result{}; DoQuery(segOrigin, segDirection, segExtent, plane, result); if (result.intersect) { result.point = segOrigin + result.parameter * segDirection; } return result; } protected: void DoQuery(Vector3<T> const& segOrigin, Vector3<T> const& segDirection, T segExtent, Plane3<T> const& plane, Result& result) { FIQuery<T, Line3<T>, Plane3<T>>::DoQuery(segOrigin, segDirection, plane, result); if (result.intersect) { // The line intersects the plane in a point that might not be // on the segment. if (std::fabs(result.parameter) > segExtent) { result.intersect = false; result.numIntersections = 0; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprHeightLine2.h
.h
3,817
109
// 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/Vector2.h> // Least-squares fit of a line to height data (x,f(x)). The line is of the // form: (y - yAvr) = a*(x - xAvr), where (xAvr,yAvr) is the average of the // sample points. The return value of Fit is 'true' if and only if the fit is // successful (the input points are not degenerate to a single point). The // mParameters values are ((xAvr,yAvr),(a,-1)) on success and ((0,0),(0,0)) on // failure. The error for (x0,y0) is [a*(x0-xAvr)-(y0-yAvr)]^2. namespace gte { template <typename Real> class ApprHeightLine2 : public ApprQuery<Real, Vector2<Real>> { public: // Initialize the model parameters to zero. ApprHeightLine2() { mParameters.first = Vector2<Real>::Zero(); mParameters.second = 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++]; } mean /= (Real)numIndices; if (std::isfinite(mean[0]) && std::isfinite(mean[1])) { // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (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]; } // Decompose the covariance matrix. if (covar00 > (Real)0) { mParameters.first = mean; mParameters.second[0] = covar01 / covar00; mParameters.second[1] = (Real)-1; return true; } } } mParameters.first = Vector2<Real>::Zero(); mParameters.second = Vector2<Real>::Zero(); return false; } // Get the parameters for the best fit. std::pair<Vector2<Real>, Vector2<Real>> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return 2; } virtual Real Error(Vector2<Real> const& point) const override { Real d = Dot(point - mParameters.first, mParameters.second); Real error = d * d; return error; } virtual void CopyParameters(ApprQuery<Real, Vector2<Real>> const* input) override { auto source = dynamic_cast<ApprHeightLine2<Real> const*>(input); if (source) { *this = *source; } } private: std::pair<Vector2<Real>, Vector2<Real>> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPoint3ConvexPolyhedron3.h
.h
7,178
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/DCPQuery.h> #include <Mathematics/LCPSolver.h> #include <Mathematics/ConvexPolyhedron3.h> #include <memory> // Compute the distance between a point and a convex polyhedron in 3D. The // algorithm is based on using an LCP solver for the convex quadratic // programming problem. For details, see // https://www.geometrictools.com/Documentation/ConvexQuadraticProgramming.pdf namespace gte { template <typename T> class DCPQuery<T, Vector3<T>, ConvexPolyhedron3<T>> { public: // Construction. If you have no knowledge of the number of faces // for the convex polyhedra you plan on applying the query to, pass // 'numTriangles' of zero. This is a request to the operator() // function to create the LCP solver for each query, and this // requires memory allocation and deallocation per query. If you // plan on applying the query multiple/ times to a single polyhedron, // even if the vertices of the polyhedron are modified for each query, // then pass 'numTriangles' to be the number of triangle faces for // that polyhedron. This lets the operator() function know to create // the LCP solver once at construction time, thus avoiding the memory // management costs during the query. DCPQuery(int32_t numTriangles = 0) { if (numTriangles > 0) { int32_t const n = numTriangles + 3; mLCP = std::make_unique<LCPSolver<T>>(n); mMaxLCPIterations = mLCP->GetMaxIterations(); } else { mMaxLCPIterations = 0; } } struct Result { Result() : queryIsSuccessful(false), distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{ Vector3<T>::Zero(), Vector3<T>::Zero() }, numLCPIterations(0) { } bool queryIsSuccessful; // These members are valid only when queryIsSuccessful is true; // otherwise, they are all set to zero. T distance, sqrDistance; std::array<Vector3<T>, 2> closest; // The number of iterations used by LCPSolver regardless of // whether the query is successful. int32_t numLCPIterations; }; // Default maximum iterations is 144 (n = 12, maxIterations = n*n). // If the solver fails to converge, try increasing the maximum number // of iterations. void SetMaxLCPIterations(int32_t maxLCPIterations) { mMaxLCPIterations = maxLCPIterations; if (mLCP) { mLCP->SetMaxIterations(mMaxLCPIterations); } } Result operator()(Vector3<T> const& point, ConvexPolyhedron3<T> const& polyhedron) { Result result{}; int32_t const numTriangles = static_cast<int32_t>(polyhedron.planes.size()); if (numTriangles == 0) { // The polyhedron planes and aligned box need to be created. result.queryIsSuccessful = false; for (int32_t i = 0; i < 3; ++i) { result.closest[0][i] = (T)0; result.closest[1][i] = (T)0; } result.distance = (T)0; result.sqrDistance = (T)0; result.numLCPIterations = 0; return result; } int32_t const n = numTriangles + 3; // Translate the point and convex polyhedron so that the // polyhedron is in the first octant. The translation is not // explicit; rather, the q and M for the LCP are initialized using // the translation information. Vector4<T> hmin = HLift(polyhedron.alignedBox.min, (T)1); std::vector<T> q(n); for (int32_t r = 0; r < 3; ++r) { q[r] = polyhedron.alignedBox.min[r] - point[r]; } for (int32_t r = 3, t = 0; r < n; ++r, ++t) { q[r] = -Dot(polyhedron.planes[t], hmin); } std::vector<T> M(static_cast<size_t>(n) * static_cast<size_t>(n)); M[0] = (T)1; M[1] = (T)0; M[2] = (T)0; M[n] = (T)0; M[static_cast<size_t>(n) + 1] = (T)1; M[static_cast<size_t>(n) + 2] = (T)0; M[2 * static_cast<size_t>(n)] = (T)0; M[2 * static_cast<size_t>(n) + 1] = (T)0; M[2 * static_cast<size_t>(n) + 2] = (T)1; for (int32_t t = 0, c = 3; t < numTriangles; ++t, ++c) { Vector3<T> normal = HProject(polyhedron.planes[t]); for (int32_t r = 0; r < 3; ++r) { M[c + static_cast<size_t>(n) * r] = normal[r]; M[r + static_cast<size_t>(n) * c] = -normal[r]; } } for (int32_t r = 3; r < n; ++r) { for (int32_t c = 3; c < n; ++c) { M[c + static_cast<size_t>(n) * r] = (T)0; } } bool needsLCP = (mLCP == nullptr); if (needsLCP) { mLCP = std::make_unique<LCPSolver<T>>(n); if (mMaxLCPIterations > 0) { mLCP->SetMaxIterations(mMaxLCPIterations); } } std::vector<T> w(n), z(n); if (mLCP->Solve(q, M, w, z)) { result.queryIsSuccessful = true; result.closest[0] = point; for (int32_t i = 0; i < 3; ++i) { result.closest[1][i] = z[i] + polyhedron.alignedBox.min[i]; } Vector3<T> diff = result.closest[1] - result.closest[0]; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); } else { // If you reach this case, the maximum number of iterations // was not specified to be large enough or there is a problem // due to floating-point rounding errors. If you believe the // latter is true, file a bug report. result.queryIsSuccessful = false; } result.numLCPIterations = mLCP->GetNumIterations(); if (needsLCP) { mLCP = nullptr; } return result; } private: int32_t mMaxLCPIterations; std::unique_ptr<LCPSolver<T>> mLCP; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprGreatCircle3.h
.h
5,433
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/Matrix3x3.h> #include <Mathematics/SymmetricEigensolver3x3.h> namespace gte { // Least-squares fit of a great circle to unit-length vectors (x,y,z) by // using distance measurements orthogonal (and measured along great // circles) to the proposed great circle. The inputs akPoint[] are unit // length. The returned value is unit length, call it N. The fitted // great circle is defined by Dot(N,X) = 0, where X is a unit-length // vector on the great circle. template <typename Real> class ApprGreatCircle3 { public: void operator()(int32_t numPoints, Vector3<Real> const* points, Vector3<Real>& normal) const { // Compute the covariance matrix of the vectors. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (Real)0; for (int32_t i = 0; i < numPoints; i++) { Vector3<Real> diff = points[i]; 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]; } Real invNumPoints = (Real)1 / static_cast<Real>(numPoints); covar00 *= invNumPoints; covar01 *= invNumPoints; covar02 *= invNumPoints; covar11 *= invNumPoints; covar12 *= invNumPoints; covar22 *= invNumPoints; // Solve the eigensystem. 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); normal = evec[0]; } }; // In addition to the least-squares fit of a great circle, the input // vectors are projected onto that circle. The sector of smallest angle // (possibly obtuse) that contains the points is computed. The endpoints // of the arc of the sector are returned. The returned endpoints A0 and // A1 are perpendicular to the returned normal N. Moreover, when you view // the arc by looking at the plane of the great circle with a view // direction of -N, the arc is traversed counterclockwise starting at A0 // and ending at A1. template <typename Real> class ApprGreatArc3 { public: void operator()(int32_t numPoints, Vector3<Real> const* points, Vector3<Real>& normal, Vector3<Real>& arcEnd0, Vector3<Real>& arcEnd1) const { // Get the least-squares great circle for the vectors. The circle // is on the plane Dot(N,X) = 0. Generate a basis from N. Vector3<Real> basis[3]; // { N, U, V } ApprGreatCircle3<Real>()(numPoints, points, basis[0]); ComputeOrthogonalComplement(1, basis); // The vectors are X[i] = u[i]*U + v[i]*V + w[i]*N. The // projections are // P[i] = (u[i]*U + v[i]*V)/sqrt(u[i]*u[i] + v[i]*v[i]) // The great circle is parameterized by // C(t) = cos(t)*U + sin(t)*V // Compute the angles t in [-pi,pi] for the projections onto the // great circle. It is not necesarily to normalize (u[i],v[i]), // instead computing t = atan2(v[i],u[i]). The items[] represents // (u, v, angle). std::vector<std::array<Real, 3>> items(numPoints); for (int32_t i = 0; i < numPoints; ++i) { items[i][0] = Dot(basis[1], points[i]); items[i][1] = Dot(basis[2], points[i]); items[i][2] = std::atan2(items[i][1], items[i][0]); } std::sort(items.begin(), items.end(), [](std::array<Real, 3> const& item0, std::array<Real, 3> const& item1) { return item0[2] < item1[2]; } ); // Locate the pair of consecutive angles whose difference is a // maximum. Effectively, we are constructing a cone of minimum // angle that contains the unit-length vectors. int32_t numPointsM1 = numPoints - 1; Real maxDiff = (Real)GTE_C_TWO_PI + items[0][2] - items[numPointsM1][2]; int32_t end0 = 0, end1 = numPointsM1; for (int32_t i0 = 0, i1 = 1; i0 < numPointsM1; i0 = i1++) { Real diff = items[i1][2] - items[i0][2]; if (diff > maxDiff) { maxDiff = diff; end0 = i1; end1 = i0; } } normal = basis[0]; arcEnd0 = items[end0][0] * basis[1] + items[end0][1] * basis[2]; arcEnd1 = items[end1][0] * basis[1] + items[end1][1] * basis[2]; Normalize(arcEnd0); Normalize(arcEnd1); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NURBSSurface.h
.h
9,182
245
// 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/ParametricSurface.h> #include <Mathematics/Vector.h> namespace gte { template <int32_t N, typename Real> class NURBSSurface : public ParametricSurface<N, Real> { 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 // row-major order, attribute[i0 + numControls0*i1]. As a 2D array, // this corresponds to attribute2D[i1][i0]. NURBSSurface(BasisFunctionInput<Real> const& input0, BasisFunctionInput<Real> const& input1, Vector<N, Real> const* controls, Real const* weights) : ParametricSurface<N, Real>((Real)0, (Real)1, (Real)0, (Real)1, true) { BasisFunctionInput<Real> const* input[2] = { &input0, &input1 }; for (int32_t i = 0; i < 2; ++i) { mNumControls[i] = input[i]->numControls; mBasisFunction[i].Create(*input[i]); } // The mBasisFunction stores the domain but so does // ParametricSurface. this->mUMin = mBasisFunction[0].GetMinDomain(); this->mUMax = mBasisFunction[0].GetMaxDomain(); this->mVMin = mBasisFunction[1].GetMinDomain(); this->mVMax = mBasisFunction[1].GetMaxDomain(); // 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]; 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); } this->mConstructed = true; } // Member access. The index 'dim' must be in {0,1}. inline BasisFunction<Real> const& GetBasisFunction(int32_t dim) const { return mBasisFunction[dim]; } 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(); } void SetControl(int32_t i0, int32_t i1, Vector<N, Real> const& control) { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { mControls[i0 + static_cast<size_t>(mNumControls[0]) * i1] = control; } } Vector<N, Real> const& GetControl(int32_t i0, int32_t i1) const { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { return mControls[i0 + static_cast<size_t>(mNumControls[0]) * i1]; } else { return mControls[0]; } } void SetWeight(int32_t i0, int32_t i1, Real weight) { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { mWeights[i0 + static_cast<size_t>(mNumControls[0]) * i1] = weight; } } Real const& GetWeight(int32_t i0, int32_t i1) const { if (0 <= i0 && i0 < GetNumControls(0) && 0 <= i1 && i1 < GetNumControls(1)) { return mWeights[i0 + static_cast<size_t>(mNumControls[0]) * i1]; } else { return mWeights[0]; } } // 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. virtual void Evaluate(Real u, Real v, uint32_t order, Vector<N, Real>* jet) const override { uint32_t const supOrder = ParametricSurface<N, Real>::SUP_ORDER; if (!this->mConstructed || order >= supOrder) { // Return a zero-valued jet for invalid state. for (uint32_t i = 0; i < supOrder; ++i) { jet[i].MakeZero(); } return; } int32_t iumin, iumax, ivmin, ivmax; mBasisFunction[0].Evaluate(u, order, iumin, iumax); mBasisFunction[1].Evaluate(v, order, ivmin, ivmax); // Compute position. Vector<N, Real> X; Real w; Compute(0, 0, iumin, iumax, ivmin, ivmax, X, w); Real invW = (Real)1 / w; jet[0] = invW * X; if (order >= 1) { // Compute first-order derivatives. Vector<N, Real> XDerU; Real wDerU; Compute(1, 0, iumin, iumax, ivmin, ivmax, XDerU, wDerU); jet[1] = invW * (XDerU - wDerU * jet[0]); Vector<N, Real> XDerV; Real wDerV; Compute(0, 1, iumin, iumax, ivmin, ivmax, XDerV, wDerV); jet[2] = invW * (XDerV - wDerV * jet[0]); if (order >= 2) { // Compute second-order derivatives. Vector<N, Real> XDerUU; Real wDerUU; Compute(2, 0, iumin, iumax, ivmin, ivmax, XDerUU, wDerUU); jet[3] = invW * (XDerUU - (Real)2 * wDerU * jet[1] - wDerUU * jet[0]); Vector<N, Real> XDerUV; Real wDerUV; Compute(1, 1, iumin, iumax, ivmin, ivmax, XDerUV, wDerUV); jet[4] = invW * (XDerUV - wDerU * jet[2] - wDerV * jet[1] - wDerUV * jet[0]); Vector<N, Real> XDerVV; Real wDerVV; Compute(0, 2, iumin, iumax, ivmin, ivmax, XDerVV, wDerVV); jet[5] = invW * (XDerVV - (Real)2 * wDerV * jet[2] - wDerVV * jet[0]); } } } protected: // Support for Evaluate(...). void Compute(uint32_t uOrder, uint32_t vOrder, int32_t iumin, int32_t iumax, int32_t ivmin, int32_t ivmax, Vector<N, Real>& X, Real& w) 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]; X.MakeZero(); w = (Real)0; for (int32_t iv = ivmin; iv <= ivmax; ++iv) { Real tmpv = mBasisFunction[1].GetValue(vOrder, iv); 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; Real tmp = tmpu * tmpv * mWeights[index]; X += tmp * mControls[index]; w += tmp; } } } std::array<BasisFunction<Real>, 2> mBasisFunction; std::array<int32_t, 2> mNumControls; std::vector<Vector<N, Real>> mControls; std::vector<Real> mWeights; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPoint3Cylinder3.h
.h
4,346
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.01.06 #pragma once #include <Mathematics/DCPQuery.h> #include <Mathematics/Cylinder3.h> #include <Mathematics/Vector3.h> // The queries consider the cylinder to be a solid. namespace gte { template <typename T> class DCPQuery<T, Vector3<T>, Cylinder3<T>> { public: // The input point is stored in the member closest[0]. The cylinder // point closest to it is stored in the member closest[1]. struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<Vector3<T>, 2> closest; }; Result operator()(Vector3<T> const& point, Cylinder3<T> const& cylinder) { Result result; // Convert the point to the cylinder coordinate system. In this // system, the point believes (0,0,0) is the cylinder axis origin // and (0,0,1) is the cylinder axis direction. std::array<Vector3<T>, 3> basis{}; basis[0] = cylinder.axis.direction; ComputeOrthogonalComplement(1, basis.data()); Vector3<T> delta = point - cylinder.axis.origin; Vector3<T> P { Dot(basis[1], delta), Dot(basis[2], delta), Dot(basis[0], delta) }; if (cylinder.height == std::numeric_limits<T>::max()) { DoQueryInfiniteCylinder(P, cylinder.radius, result); } else { DoQueryFiniteCylinder(P, cylinder.radius, cylinder.height, result); } // Convert the closest point from the cylinder coordinate system // to the original coordinate system. result.closest[0] = point; result.closest[1] = cylinder.axis.origin + result.closest[1][0] * basis[1] + result.closest[1][1] * basis[2] + result.closest[1][2] * basis[0]; return result; } private: void DoQueryInfiniteCylinder(Vector3<T> const& P, T const& radius, Result& result) { T sqrRadius = radius * radius; T sqrDistance = P[0] * P[0] + P[1] * P[1]; if (sqrDistance >= sqrRadius) { // The point is outside the cylinder or on the cylinder wall. T distance = std::sqrt(sqrDistance); result.distance = distance - radius; result.sqrDistance = result.distance * result.distance; T temp = radius / distance; result.closest[1][0] = P[0] * temp; result.closest[1][1] = P[1] * temp; result.closest[1][2] = P[2]; } else { // The point is inside the cylinder. result.distance = (T)0; result.sqrDistance = (T)0; result.closest[1] = P; } } void DoQueryFiniteCylinder(Vector3<T> const& P, T const& radius, T const& height, Result& result) { DoQueryInfiniteCylinder(P, radius, result); // Clamp the infinite cylinder's closest point to the finite // cylinder. if (result.closest[1][2] > height) { result.closest[1][2] = height; Vector3<T> diff = result.closest[1] - P; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); } else if (result.closest[1][2] < -height) { result.closest[1][2] = -height; Vector3<T> diff = result.closest[1] - P; result.sqrDistance = Dot(diff, diff); result.distance = std::sqrt(result.sqrDistance); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ConformalMapGenus0.h
.h
16,224
415
// 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/ETManifoldMesh.h> #include <Mathematics/LinearSystem.h> #include <Mathematics/Polynomial1.h> #include <Mathematics/Vector2.h> #include <Mathematics/Vector3.h> // Conformally map a 2-dimensional manifold mesh with the topology of a sphere // to a sphere. The algorithm is an implementation of the one in the paper // S.Haker, S.Angenent, A.Tannenbaum, R.Kikinis, G.Sapiro, and M.Halle. // Conformal surface parameterization for texture mapping, // IEEE Transactions on Visualization and Computer Graphics, // Volume 6, Number 2, pages 181–189, 2000 // The paper is available at https://ieeexplore.ieee.org/document/856998 but // is not freely downloadable. namespace gte { template <typename Real> class ConformalMapGenus0 { public: // The input mesh should be a closed, manifold surface that has the // topology of a sphere (genus 0 surface). ConformalMapGenus0() : mPlaneCoordinates{}, mMinPlaneCoordinate(Vector2<Real>::Zero()), mMaxPlaneCoordinate(Vector2<Real>::Zero()), mSphereCoordinates{}, mSphereRadius(0.0f) { } ~ConformalMapGenus0() { } // The returned 'bool' value is 'true' whenever the conjugate gradient // algorithm converged. Even if it did not, the results might still // be acceptable. bool operator()(int32_t numPositions, Vector3<Real> const* positions, int32_t numTriangles, int32_t const* indices, int32_t punctureTriangle) { bool converged = true; mPlaneCoordinates.resize(numPositions); mSphereCoordinates.resize(numPositions); // Construct a triangle-edge representation of mesh. ETManifoldMesh graph; int32_t const* currentIndex = indices; int32_t t; for (t = 0; t < numTriangles; ++t) { int32_t v0 = *currentIndex++; int32_t v1 = *currentIndex++; int32_t v2 = *currentIndex++; graph.Insert(v0, v1, v2); } auto const& emap = graph.GetEdges(); // Construct the nondiagonal entries of the sparse matrix A. typename LinearSystem<Real>::SparseMatrix A; int32_t v0, v1, v2, i; Vector3<Real> E0, E1; Real value; for (auto const& element : emap) { v0 = element.first.V[0]; v1 = element.first.V[1]; value = (Real)0; for (int32_t j = 0; j < 2; ++j) { auto triangle = element.second->T[j]; for (i = 0; i < 3; ++i) { v2 = triangle->V[i]; if (v2 != v0 && v2 != v1) { E0 = positions[v0] - positions[v2]; E1 = positions[v1] - positions[v2]; value += Dot(E0, E1) / Length(Cross(E0, E1)); } } } value *= -(Real)0.5; std::array<int32_t, 2> lookup = { v0, v1 }; A[lookup] = value; } // Construct the diagonal entries of the sparse matrix A. std::vector<Real> tmp(numPositions, (Real)0); for (auto const& element : A) { tmp[element.first[0]] -= element.second; tmp[element.first[1]] -= element.second; } for (i = 0; i < numPositions; ++i) { std::array<int32_t, 2> lookup = { i, i }; A[lookup] = tmp[i]; } LogAssert(static_cast<size_t>(numPositions) + emap.size() == A.size(), "Mismatched sizes."); // Construct the sparse column vector B. currentIndex = &indices[3 * punctureTriangle]; v0 = *currentIndex++; v1 = *currentIndex++; v2 = *currentIndex++; Vector3<Real> V0 = positions[v0]; Vector3<Real> V1 = positions[v1]; Vector3<Real> V2 = positions[v2]; Vector3<Real> E10 = V1 - V0; Vector3<Real> E20 = V2 - V0; Vector3<Real> E12 = V1 - V2; Vector3<Real> normal = Cross(E20, E10); Real len10 = Length(E10); Real invLen10 = (Real)1 / len10; Real twoArea = Length(normal); Real invLenNormal = (Real)1 / twoArea; Real invProd = invLen10 * invLenNormal; Real re0 = -invLen10; Real im0 = invProd * Dot(E12, E10); Real re1 = invLen10; Real im1 = invProd * Dot(E20, E10); Real re2 = (Real)0; Real im2 = -len10 * invLenNormal; // Solve the sparse system for the real parts. uint32_t const maxIterations = 1024; Real const tolerance = 1e-06f; std::fill(tmp.begin(), tmp.end(), (Real)0); tmp[v0] = re0; tmp[v1] = re1; tmp[v2] = re2; std::vector<Real> result(numPositions); uint32_t iterations = LinearSystem<Real>().SolveSymmetricCG( numPositions, A, tmp.data(), result.data(), maxIterations, tolerance); if (iterations >= maxIterations) { converged = false; } for (i = 0; i < numPositions; ++i) { mPlaneCoordinates[i][0] = result[i]; } // Solve the sparse system for the imaginary parts. std::fill(tmp.begin(), tmp.end(), (Real)0); tmp[v0] = -im0; tmp[v1] = -im1; tmp[v2] = -im2; iterations = LinearSystem<Real>().SolveSymmetricCG(numPositions, A, tmp.data(), result.data(), maxIterations, tolerance); if (iterations >= maxIterations) { converged = false; } for (i = 0; i < numPositions; ++i) { mPlaneCoordinates[i][1] = result[i]; } // Scale to [-1,1]^2 for numerical conditioning in later steps. Real fmin = mPlaneCoordinates[0][0], fmax = fmin; for (i = 0; i < numPositions; i++) { if (mPlaneCoordinates[i][0] < fmin) { fmin = mPlaneCoordinates[i][0]; } else if (mPlaneCoordinates[i][0] > fmax) { fmax = mPlaneCoordinates[i][0]; } if (mPlaneCoordinates[i][1] < fmin) { fmin = mPlaneCoordinates[i][1]; } else if (mPlaneCoordinates[i][1] > fmax) { fmax = mPlaneCoordinates[i][1]; } } Real halfRange = (Real)0.5 * (fmax - fmin); Real invHalfRange = (Real)1 / halfRange; for (i = 0; i < numPositions; ++i) { mPlaneCoordinates[i][0] = (Real)-1 + invHalfRange * (mPlaneCoordinates[i][0] - fmin); mPlaneCoordinates[i][1] = (Real)-1 + invHalfRange * (mPlaneCoordinates[i][1] - fmin); } // Map the plane coordinates to the sphere using inverse // stereographic projection. The main issue is selecting a // translation in (x,y) and a radius of the projection sphere. // Both factors strongly influence the final result. // Use the average as the south pole. The points tend to be // clustered approximately in the middle of the conformally // mapped punctured triangle, so the average is a good choice // to place the pole. Vector2<Real> origin{ (Real)0, (Real)0 }; for (i = 0; i < numPositions; ++i) { origin += mPlaneCoordinates[i]; } origin /= (Real)numPositions; for (i = 0; i < numPositions; ++i) { mPlaneCoordinates[i] -= origin; } mMinPlaneCoordinate = mPlaneCoordinates[0]; mMaxPlaneCoordinate = mPlaneCoordinates[0]; for (i = 1; i < numPositions; ++i) { if (mPlaneCoordinates[i][0] < mMinPlaneCoordinate[0]) { mMinPlaneCoordinate[0] = mPlaneCoordinates[i][0]; } else if (mPlaneCoordinates[i][0] > mMaxPlaneCoordinate[0]) { mMaxPlaneCoordinate[0] = mPlaneCoordinates[i][0]; } if (mPlaneCoordinates[i][1] < mMinPlaneCoordinate[1]) { mMinPlaneCoordinate[1] = mPlaneCoordinates[i][1]; } else if (mPlaneCoordinates[i][1] > mMaxPlaneCoordinate[1]) { mMaxPlaneCoordinate[1] = mPlaneCoordinates[i][1]; } } // Select the radius of the sphere so that the projected punctured // triangle has an area whose fraction of total spherical area is // the same fraction as the area of the punctured triangle to the // total area of the original triangle mesh. Real twoTotalArea = (Real)0; currentIndex = indices; for (t = 0; t < numTriangles; ++t) { V0 = positions[*currentIndex++]; V1 = positions[*currentIndex++]; V2 = positions[*currentIndex++]; E0 = V1 - V0; E1 = V2 - V0; twoTotalArea += Length(Cross(E0, E1)); } ComputeSphereRadius(v0, v1, v2, twoArea / twoTotalArea); Real sqrSphereRadius = mSphereRadius * mSphereRadius; // Inverse stereographic projection to obtain sphere coordinates. // The sphere is centered at the origin and has radius 1. for (i = 0; i < numPositions; i++) { Real rSqr = Dot(mPlaneCoordinates[i], mPlaneCoordinates[i]); Real mult = (Real)1 / (rSqr + sqrSphereRadius); Real x = (Real)2 * mult * sqrSphereRadius * mPlaneCoordinates[i][0]; Real y = (Real)2 * mult * sqrSphereRadius * mPlaneCoordinates[i][1]; Real z = mult * mSphereRadius * (rSqr - sqrSphereRadius); mSphereCoordinates[i] = Vector3<Real>{ x, y, z } / mSphereRadius; } return converged; } // Conformal mapping of mesh to plane. The array of coordinates has a // one-to-one correspondence with the input vertex array. inline std::vector<Vector2<Real>> const& GetPlaneCoordinates() const { return mPlaneCoordinates; } inline Vector2<Real> const& GetMinPlaneCoordinate() const { return mMinPlaneCoordinate; } inline Vector2<Real> const& GetMaxPlaneCoordinate() const { return mMaxPlaneCoordinate; } // Conformal mapping of mesh to sphere (centered at origin). The array // of coordinates has a one-to-one correspondence with the input vertex // array. inline std::vector<Vector3<Real>> const& GetSphereCoordinates() const { return mSphereCoordinates; } inline Real GetSphereRadius() const { return mSphereRadius; } private: void ComputeSphereRadius(int32_t v0, int32_t v1, int32_t v2, Real areaFraction) { Vector2<Real> V0 = mPlaneCoordinates[v0]; Vector2<Real> V1 = mPlaneCoordinates[v1]; Vector2<Real> V2 = mPlaneCoordinates[v2]; Real r0Sqr = Dot(V0, V0); Real r1Sqr = Dot(V1, V1); Real r2Sqr = Dot(V2, V2); Real diffR10 = r1Sqr - r0Sqr; Real diffR20 = r2Sqr - r0Sqr; Real diffX10 = V1[0] - V0[0]; Real diffY10 = V1[1] - V0[1]; Real diffX20 = V2[0] - V0[0]; Real diffY20 = V2[1] - V0[1]; Real diffRX10 = V1[0] * r0Sqr - V0[0] * r1Sqr; Real diffRY10 = V1[1] * r0Sqr - V0[1] * r1Sqr; Real diffRX20 = V2[0] * r0Sqr - V0[0] * r2Sqr; Real diffRY20 = V2[1] * r0Sqr - V0[1] * r2Sqr; Real c0 = diffR20 * diffRY10 - diffR10 * diffRY20; Real c1 = diffR20 * diffY10 - diffR10 * diffY20; Real d0 = diffR10 * diffRX20 - diffR20 * diffRX10; Real d1 = diffR10 * diffX20 - diffR20 * diffX10; Real e0 = diffRX10 * diffRY20 - diffRX20 * diffRY10; Real e1 = diffRX10 * diffY20 - diffRX20 * diffY10; Real e2 = diffX10 * diffY20 - diffX20 * diffY10; Polynomial1<Real> poly0(6); poly0[0] = (Real)0; poly0[1] = (Real)0; poly0[2] = e0 * e0; poly0[3] = c0 * c0 + d0 * d0 + (Real)2 * e0 * e1; poly0[4] = (Real)2 * (c0 * c1 + d0 * d1 + e0 * e1) + e1 * e1; poly0[5] = c1 * c1 + d1 * d1 + (Real)2 * e1 * e2; poly0[6] = e2 * e2; Polynomial1<Real> qpoly0(1), qpoly1(1), qpoly2(1); qpoly0[0] = r0Sqr; qpoly0[1] = (Real)1; qpoly1[0] = r1Sqr; qpoly1[1] = (Real)1; qpoly2[0] = r2Sqr; qpoly2[1] = (Real)1; Real tmp = areaFraction * static_cast<Real>(GTE_C_PI); Real amp = tmp * tmp; Polynomial1<Real> poly1 = amp * qpoly0; poly1 = poly1 * qpoly0; poly1 = poly1 * qpoly0; poly1 = poly1 * qpoly0; poly1 = poly1 * qpoly1; poly1 = poly1 * qpoly1; poly1 = poly1 * qpoly2; poly1 = poly1 * qpoly2; Polynomial1<Real> poly2 = poly1 - poly0; LogAssert(poly2.GetDegree() <= 8, "Expecting degree no larger than 8."); // Bound a root near zero and apply bisection to find t. Real tmin = (Real)0, fmin = poly2(tmin); Real tmax = (Real)1, fmax = poly2(tmax); LogAssert(fmin > (Real)0 && fmax < (Real)0, "Expecting opposite-signed extremes."); // Determine the number of iterations to get 'digits' of accuracy. int32_t const digits = 6; Real tmp0 = std::log(tmax - tmin); Real tmp1 = (Real)digits * static_cast<Real>(GTE_C_LN_10); Real arg = (tmp0 + tmp1) * static_cast<Real>(GTE_C_INV_LN_2); int32_t maxIterations = static_cast<int32_t>(arg + (Real)0.5); Real tmid = (Real)0, fmid; for (int32_t i = 0; i < maxIterations; ++i) { tmid = (Real)0.5 * (tmin + tmax); fmid = poly2(tmid); Real product = fmid * fmin; if (product < (Real)0) { tmax = tmid; fmax = fmid; } else { tmin = tmid; fmin = fmid; } } mSphereRadius = std::sqrt(tmid); } // Conformal mapping to a plane. The plane's (px,py) points // correspond to the mesh's (mx,my,mz) points. std::vector<Vector2<Real>> mPlaneCoordinates; Vector2<Real> mMinPlaneCoordinate, mMaxPlaneCoordinate; // Conformal mapping to a sphere. The sphere's (sx,sy,sz) points // correspond to the mesh's (mx,my,mz) points. std::vector<Vector3<Real>> mSphereCoordinates; Real mSphereRadius; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Cone.h
.h
19,394
506
// 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/Logger.h> #include <Mathematics/Math.h> #include <Mathematics/Ray.h> #include <Mathematics/Vector2.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/UniqueVerticesSimplices.h> // An infinite cone is defined by a vertex V, a unit-length direction D and an // angle A with 0 < A < pi/2. A point X is on the cone when // Dot(D, X - V) = |X - V| * cos(A) // A solid cone includes points on the cone and in the region that contains // the cone ray V + h * D for h >= 0. It is defined by // Dot(D, X - V) >= |X - V| * cos(A) // The height of any point Y in space relative to the cone is defined by // h = Dot(D, Y - V), which is the signed length of the projection of X - V // onto the cone axis. Observe that we have restricted the cone definition to // an acute angle A, so |X - V| * cos(A) >= 0; therefore, points on or inside // the cone have nonnegative heights: Dot(D, X - V) >= 0. I will refer to the // infinite solid cone as the "positive cone," which means that the non-vertex // points inside the cone have positive heights. Although rare in computer // graphics, one might also want to consider the "negative cone," which is // defined by // -Dot(D, X - V) <= -|X - V| * cos(A) // The non-vertex points inside this cone have negative heights. // // For many of the geometric queries involving cones, we can avoid the square // root computation implied by |X - V|. The positive cone is defined by // Dot(D, X - V)^2 >= |X - V|^2 * cos(A)^2, // which is a quadratic inequality, but the squaring of the terms leads to an // inequality that includes points X in the negative cone. When using the // quadratic inequality for the positive cone, we need to include also the // constraint Dot(D, X - V) >= 0. // // I define four different types of cones. They all involve V, D and A. The // differences are based on restrictions to the heights of the cone points. // The height range is defined to be the interval of possible heights, say, // [hmin,hmax] with 0 <= hmin < hmax <= +infinity. // 1. infinite cone: hmin = 0, hmax = +infinity // 2. infinite truncated cone: hmin > 0, hmax = +infinity // 3. finite cone: hmin >= 0, hmax < +infinity // 4. frustum of a cone: hmin > 0, hmax < +infinity // The infinite truncated cone is truncated for h-minimum; the radius of the // disk at h-minimum is rmin = hmin * tan(A). The finite cone is truncated for // h-maximum; the radius of the disk at h-maximum is rmax = hmax * tan(A). // The frustum of a cone is truncated both for h-minimum and h-maximum. // // A technical problem when creating a data structure to represent a cone is // deciding how to represent +infinity in the height range. When the template // type T is 'float' or 'double', we could represent it as // std::numeric_limits<T>::infinity(). The geometric queries must be // structured properly to conform to the semantics associated with the // floating-point infinity. We could also use the largest finite // floating-point number, std::numeric_limits<T>::max(). Either choice is // problematic when instead T is an arbitrary precision type that does not // have a representation for infinity; this is the case for the types // BSNumber<T> and BSRational<T>, where T is UIntegerAP or UIntegerFP<N>. // // The introduction of representations of infinities for the arbitrary // precision types would require modifying the arithmetic operations to test // whether the number is finite or infinite. This leads to a greater // computational cost for all queries, even when those queries do not require // manipulating infinities. In the case of a cone, the height manipulations // are nearly always for comparisons of heights. I choose to represent // +infinity by setting the maxHeight member to -1. The member functions // IsFinite() and IsInfinite() compare maxHeight to -1 and report the correct // state. // // My choice of representation has the main consequence that comparisons // between heights requires extra logic. This can make geometric queries // cumbersome to implement. For example, the point-in-cone test using the // quadratic inequality is shown in the pseudocode // Vector point = <some point>; // Cone cone = <some cone>; // Vector delta = point - cone.V; // T h = Dot(cone.D, delta); // bool pointInCone = // cone.hmin <= h && // h <= cone.hmax && // h * h >= Dot(delta, delta) * cone.cosAngleSqr; // In the event the cone is infinite and we choose cone.hmax = -1 to // represent this, the test 'h <= cone.hmax' must be revised, // bool pointInCone = // cone.hmin <= h && // (cone.hmax == -1 ? true : (h <= cone.hmax)) && // h * h >= Dot(delta, delta) * cone.cosAngleSqr; // To encapsulate the comparisons against height extremes, use the member // function HeightInRange(h); that is // bool pointInCone = // cone.HeightInRange(h) && // h * h >= Dot(delta, delta) * cone.cosAngleSqr; // The modification is not that complicated here, but consider a more // sophisticated query such as determining the interval of intersection // of two height intervals [h0,h1] and [cone.hmin,cone.hmax]. The file // IntrIntervals.h provides implementations for computing the // intersection of two intervals, where either or both intervals are // semi-infinite. namespace gte { template <int32_t N, typename T> class Cone { public: // Create an infinite cone with // vertex = (0,...,0) // axis = (0,...,0,1) // angle = pi/4 // minimum height = 0 // maximum height = +infinity Cone() { ray.origin.MakeZero(); ray.direction.MakeUnit(N - 1); SetAngle((T)GTE_C_QUARTER_PI); MakeInfiniteCone(); } // Create an infinite cone with the specified vertex, axis direction, // angle and with heights // minimum height = 0 // maximum height = +infinity Cone(Ray<N, T> const& inRay, T const& inAngle) : ray(inRay) { SetAngle(inAngle); MakeInfiniteCone(); } // Create an infinite truncated cone with the specified vertex, axis // direction, angle and positive minimum height. The maximum height // is +infinity. If you specify a minimum height of 0, you get the // equivalent of calling the constructor for an infinite cone. Cone(Ray<N, T> const& inRay, T const& inAngle, T const& inMinHeight) : ray(inRay) { SetAngle(inAngle); MakeInfiniteTruncatedCone(inMinHeight); } // Create a finite cone or a frustum of a cone with all parameters // specified. If you specify a minimum height of 0, you get a finite // cone. If you specify a positive minimum height, you get a frustum // of a cone. Cone(Ray<N, T> const& inRay, T inAngle, T inMinHeight, T inMaxHeight) : ray(inRay) { SetAngle(inAngle); MakeConeFrustum(inMinHeight, inMaxHeight); } // The angle must be in (0,pi/2). The function sets 'angle' and // computes 'cosAngle', 'sinAngle', 'tanAngle', 'cosAngleSqr', // 'sinAngleSqr' and 'invSinAngle'. void SetAngle(T const& inAngle) { LogAssert((T)0 < inAngle && inAngle < (T)GTE_C_HALF_PI, "Invalid angle."); angle = inAngle; cosAngle = std::cos(angle); sinAngle = std::sin(angle); tanAngle = std::tan(angle); cosAngleSqr = cosAngle * cosAngle; sinAngleSqr = sinAngle * sinAngle; invSinAngle = (T)1 / sinAngle; } // Set the heights to obtain one of the four types of cones. Be aware // that an infinite cone has maxHeight set to -1. Be careful not to // use maxHeight without understanding this interpretation. void MakeInfiniteCone() { mMinHeight = (T)0; mMaxHeight = (T)-1; } void MakeInfiniteTruncatedCone(T const& inMinHeight) { LogAssert(inMinHeight >= (T)0, "Invalid minimum height."); mMinHeight = inMinHeight; mMaxHeight = (T)-1; } void MakeFiniteCone(T const& inMaxHeight) { LogAssert(inMaxHeight > (T)0, "Invalid maximum height."); mMinHeight = (T)0; mMaxHeight = inMaxHeight; } void MakeConeFrustum(T const& inMinHeight, T const& inMaxHeight) { LogAssert(inMinHeight >= (T)0 && inMaxHeight > inMinHeight, "Invalid minimum or maximum height."); mMinHeight = inMinHeight; mMaxHeight = inMaxHeight; } // Get the height extremes. For an infinite cone, maxHeight is set // to -1. For a finite cone, maxHeight is set to a positive number. // Be careful not to use maxHeight without understanding this // interpretation. inline T GetMinHeight() const { return mMinHeight; } inline T GetMaxHeight() const { return mMaxHeight; } inline bool HeightInRange(T const& h) const { return mMinHeight <= h && (mMaxHeight != (T)-1 ? h <= mMaxHeight : true); } inline bool HeightLessThanMin(T const& h) const { return h < mMinHeight; } inline bool HeightGreaterThanMax(T const& h) const { return (mMaxHeight != (T)-1 ? h > mMaxHeight : false); } inline bool IsFinite() const { return mMaxHeight != (T)-1; } inline bool IsInfinite() const { return mMaxHeight == (T)-1; } // The cone axis direction (ray.direction) must be unit length. Ray<N, T> ray; // The angle must be in (0,pi/2). The other members are derived from // angle to avoid calling trigonometric functions in geometric queries // (for speed). You may set the angle and compute these by calling // SetAngle(inAngle). T angle; T cosAngle, sinAngle, tanAngle; T cosAngleSqr, sinAngleSqr, invSinAngle; private: // The heights must satisfy 0 <= minHeight < maxHeight <= +infinity. // For an infinite cone, maxHeight is set to -1. For a finite cone, // maxHeight is set to a positive number. Be careful not to use // maxHeight without understanding this interpretation. T mMinHeight, mMaxHeight; public: // Comparisons to support sorted containers. These based only on // 'ray', 'angle', 'minHeight' and 'maxHeight'. bool operator==(Cone const& cone) const { return ray == cone.ray && angle == cone.angle && mMinHeight == cone.mMinHeight && mMaxHeight == cone.mMaxHeight; } bool operator!=(Cone const& cone) const { return !operator==(cone); } bool operator< (Cone const& cone) const { if (ray < cone.ray) { return true; } if (ray > cone.ray) { return false; } if (angle < cone.angle) { return true; } if (angle > cone.angle) { return false; } if (mMinHeight < cone.mMinHeight) { return true; } if (mMinHeight > cone.mMinHeight) { return false; } return mMaxHeight < cone.mMaxHeight; } bool operator<=(Cone const& cone) const { return !cone.operator<(*this); } bool operator> (Cone const& cone) const { return cone.operator<(*this); } bool operator>=(Cone const& cone) const { return !operator<(cone); } public: // Support for visualization. template <int32_t Dummy = N> typename std::enable_if<(Dummy == 3), void>::type CreateMesh(size_t numMinVertices, bool inscribed, std::vector<Vector<3, T>>& vertices, std::vector<int32_t>& indices) { LogAssert(IsFinite(), "Meshes can be generated only for finite cones."); T hMin = GetMinHeight(); T hMax = GetMaxHeight(); T rMin = hMin * tanAngle; T rMax = hMax * tanAngle; T tNumExtra = static_cast<T>(0.5) * rMax/ rMin - static_cast<T>(1); size_t numExtra = 0; if (tNumExtra > static_cast<T>(0)) { numExtra = static_cast<size_t>(std::ceil(tNumExtra)); } size_t numMaxVertices = 2 * numMinVertices * (1 + numExtra); vertices.clear(); indices.clear(); std::vector<Vector<2, T>> polygonMin, polygonMax; if (inscribed) { GenerateInscribed(numMinVertices, rMin, polygonMin); GenerateInscribed(numMaxVertices, rMax, polygonMax); } else { GenerateCircumscribed(numMinVertices, rMin, polygonMin); GenerateCircumscribed(numMaxVertices, rMax, polygonMax); } if (hMin > static_cast<T>(0)) { CreateConeFrustumMesh(numMinVertices, numMaxVertices, numExtra, hMin, hMax, polygonMin, polygonMax, vertices, indices); } else { // TODO: // CreateFiniteTruncatedConeMesh(numMaxVertices, numExtra, // hMax, polygonMax, vertices, indices); } // Transform to the coordinate system of the cone. std::array<Vector<3, T>, 3> basis{}; basis[0] = ray.direction; ComputeOrthogonalComplement(1, basis.data()); Matrix<3, 3, T> rotate{}; rotate.SetCol(0, basis[1]); rotate.SetCol(1, basis[2]); rotate.SetCol(2, basis[0]); for (size_t i = 0; i < vertices.size(); ++i) { vertices[i] = rotate * vertices[i] + ray.origin; } } private: template <int32_t Dummy = N> static typename std::enable_if<(Dummy == 3), void>::type GenerateInscribed(size_t numVertices, T const& radius, std::vector<Vector<2, T>>& polygon) { T theta = static_cast<T>(GTE_C_TWO_PI) / static_cast<T>(numVertices); polygon.resize(numVertices + 1); for (size_t i = 0; i < numVertices; ++i) { T angle = static_cast<T>(i) * theta; polygon[i][0] = radius * std::cos(angle); polygon[i][1] = radius * std::sin(angle); } polygon.back() = polygon[0]; } template <int32_t Dummy = N> static typename std::enable_if<(Dummy == 3), void>::type GenerateCircumscribed(size_t numVertices, T const& radius, std::vector<Vector<2, T>>& polygon) { T theta = static_cast<T>(GTE_C_TWO_PI) / static_cast<T>(numVertices); std::vector<Vector<2, T>> inscribed(numVertices + 1); for (size_t i = 0; i < numVertices; ++i) { T angle = static_cast<T>(i) * theta; inscribed[i][0] = radius * std::cos(angle); inscribed[i][1] = radius * std::sin(angle); } inscribed.back() = inscribed[0]; T divisor = static_cast<T>(1) + std::cos(theta); polygon.resize(numVertices + 1); for (size_t i = 0, ip1 = 1; i < numVertices; ++i, ++ip1) { polygon[i] = (inscribed[i] + inscribed[ip1]) / divisor; } polygon.back() = polygon[0]; } template <int32_t Dummy = N> static typename std::enable_if<(Dummy == 3), void>::type CreateConeFrustumMesh(size_t numMinVertices, size_t numMaxVertices, size_t numExtra, T const& hMin, T const& hMax, std::vector<Vector<2, T>> const& polygonMin, std::vector<Vector<2, T>> const& polygonMax, std::vector<Vector<3, T>>& vertices, std::vector<int32_t>& indices) { std::vector<Vector<3, T>> vertexPool; Vector<3, T> V0, V1, V2; for (size_t i0 = 0, i1 = 1; i0 < numMinVertices; i0 = i1++) { size_t j0 = 2 * (numExtra + 1) * i0; V0 = HLift(polygonMin[i0], hMin); for (size_t k0 = 0, k1 = 1; k0 <= numExtra; k0 = k1++) { V1 = HLift(polygonMax[j0 + k1], hMax); V2 = HLift(polygonMax[j0 + k0], hMax); vertexPool.push_back(V0); vertexPool.push_back(V1); vertexPool.push_back(V2); } size_t j1 = 2 * (numExtra + 1) * i1; V0 = HLift(polygonMin[i1], hMin); for (size_t k0 = 0, k1 = 1; k0 <= numExtra; k0 = k1++) { V1 = HLift(polygonMax[j1 - k0], hMax); V2 = HLift(polygonMax[j1 - k1], hMax); vertexPool.push_back(V0); vertexPool.push_back(V1); vertexPool.push_back(V2); } size_t jmid = j0 + (numExtra + 1); V0 = HLift(polygonMax[jmid], hMax); V1 = HLift(polygonMin[i0], hMin); V2 = HLift(polygonMin[i1], hMin); vertexPool.push_back(V0); vertexPool.push_back(V1); vertexPool.push_back(V2); } V0 = { static_cast<T>(0), static_cast<T>(0), hMin }; for (size_t i0 = 0, i1 = 1; i0 < numMinVertices; i0 = i1++) { V1 = HLift(polygonMin[i1], hMin); V2 = HLift(polygonMin[i0], hMin); vertexPool.push_back(V0); vertexPool.push_back(V1); vertexPool.push_back(V2); } V0 = { static_cast<T>(0), static_cast<T>(0), hMax }; for (size_t i0 = 0, i1 = 1; i0 < numMaxVertices; i0 = i1++) { V1 = HLift(polygonMax[i0], hMax); V2 = HLift(polygonMax[i1], hMax); vertexPool.push_back(V0); vertexPool.push_back(V1); vertexPool.push_back(V2); } UniqueVerticesSimplices<Vector<3, T>, int32_t, 3> uvs; uvs.GenerateIndexedSimplices(vertexPool, vertices, indices); } }; // Template alias for convenience. template <typename T> using Cone3 = Cone<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/BSplineSurfaceFit.h
.h
9,808
244
// 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/BandedMatrix.h> #include <Mathematics/BasisFunction.h> #include <Mathematics/Vector3.h> // The algorithm implemented here is based on the document // https://www.geometrictools.com/Documentation/BSplineSurfaceLeastSquaresFit.pdf namespace gte { template <typename Real> class BSplineSurfaceFit { public: // Construction. The preconditions for calling the constructor are // 1 <= degree0 && degree0 + 1 < numControls0 <= numSamples0 // 1 <= degree1 && degree1 + 1 < numControls1 <= numSamples1 // The sample data must be in row-major order. The control data is // also stored in row-major order. BSplineSurfaceFit(int32_t degree0, int32_t numControls0, int32_t numSamples0, int32_t degree1, int32_t numControls1, int32_t numSamples1, Vector3<Real> const* sampleData) : mSampleData(sampleData), mControlData(static_cast<size_t>(numControls0) * static_cast<size_t>(numControls1)) { LogAssert(1 <= degree0 && degree0 + 1 < numControls0, "Invalid degree."); LogAssert(numControls0 <= numSamples0, "Invalid number of controls."); LogAssert(1 <= degree1 && degree1 + 1 < numControls1, "Invalid degree."); LogAssert(numControls1 <= numSamples1, "Invalid number of controls."); LogAssert(sampleData, "Invalid sample data."); mDegree[0] = degree0; mNumSamples[0] = numSamples0; mNumControls[0] = numControls0; mDegree[1] = degree1; mNumSamples[1] = numSamples1; mNumControls[1] = numControls1; BasisFunctionInput<Real> input; Real tMultiplier[2]; int32_t dim; for (dim = 0; dim < 2; ++dim) { input.numControls = mNumControls[dim]; input.degree = mDegree[dim]; input.uniform = true; input.periodic = false; input.numUniqueKnots = mNumControls[dim] - mDegree[dim] + 1; input.uniqueKnots.resize(input.numUniqueKnots); input.uniqueKnots[0].t = (Real)0; input.uniqueKnots[0].multiplicity = mDegree[dim] + 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 = mDegree[dim] + 1; mBasis[dim].Create(input); tMultiplier[dim] = ((Real)1) / ((Real)mNumSamples[dim] - (Real)1); } // Fit the data points with a B-spline surface using a // least-squares error metric. The problem is of the form // A0^T*A0*Q*A1^T*A1 = A0^T*P*A1, where A0^T*A0 and A1^T*A1 are // banded matrices, P contains the sample data, and Q is the // unknown matrix of control points. Real t; int32_t i0, i1, i2, imin, imax; // Construct the matrices A0^T*A0 and A1^T*A1. BandedMatrix<Real> ATAMat[2] = { BandedMatrix<Real>(mNumControls[0], mDegree[0] + 1, mDegree[0] + 1), BandedMatrix<Real>(mNumControls[1], mDegree[1] + 1, mDegree[1] + 1) }; for (dim = 0; dim < 2; ++dim) { for (i0 = 0; i0 < mNumControls[dim]; ++i0) { for (i1 = 0; i1 < i0; ++i1) { ATAMat[dim](i0, i1) = ATAMat[dim](i1, i0); } int32_t i1Max = i0 + mDegree[dim]; if (i1Max >= mNumControls[dim]) { i1Max = mNumControls[dim] - 1; } for (i1 = i0; i1 <= i1Max; ++i1) { Real value = (Real)0; for (i2 = 0; i2 < mNumSamples[dim]; ++i2) { t = tMultiplier[dim] * (Real)i2; mBasis[dim].Evaluate(t, 0, imin, imax); if (imin <= i0 && i0 <= imax && imin <= i1 && i1 <= imax) { Real b0 = mBasis[dim].GetValue(0, i0); Real b1 = mBasis[dim].GetValue(0, i1); value += b0 * b1; } } ATAMat[dim](i0, i1) = value; } } } // Construct the matrices A0^T and A1^T. A[d]^T has // mNumControls[d] rows and mNumSamples[d] columns. Array2<Real> ATMat[2]; for (dim = 0; dim < 2; dim++) { ATMat[dim] = Array2<Real>(mNumSamples[dim], mNumControls[dim]); size_t numBytes = static_cast<size_t>(mNumControls[dim]) * static_cast<size_t>(mNumSamples[dim]) * sizeof(Real); std::memset(ATMat[dim][0], 0, numBytes); for (i0 = 0; i0 < mNumControls[dim]; ++i0) { for (i1 = 0; i1 < mNumSamples[dim]; ++i1) { t = tMultiplier[dim] * (Real)i1; mBasis[dim].Evaluate(t, 0, imin, imax); if (imin <= i0 && i0 <= imax) { ATMat[dim][i0][i1] = mBasis[dim].GetValue(0, i0); } } } } // Compute X0 = (A0^T*A0)^{-1}*A0^T and X1 = (A1^T*A1)^{-1}*A1^T // by solving the linear systems A0^T*A0*X0 = A0^T and // A1^T*A1*X1 = A1^T. for (dim = 0; dim < 2; ++dim) { bool solved = ATAMat[dim].template SolveSystem<true>(ATMat[dim][0], mNumSamples[dim]); LogAssert(solved, "Failed to solve linear system in BSplineSurfaceFit constructor."); } // The control points for the fitted surface are stored in the matrix // Q = X0*P*X1^T, where P is the matrix of sample data. for (i1 = 0; i1 < mNumControls[1]; ++i1) { for (i0 = 0; i0 < mNumControls[0]; ++i0) { Vector3<Real> sum = Vector3<Real>::Zero(); for (int32_t j1 = 0; j1 < mNumSamples[1]; ++j1) { Real x1Value = ATMat[1][i1][j1]; for (int32_t j0 = 0; j0 < mNumSamples[0]; ++j0) { Real x0Value = ATMat[0][i0][j0]; Vector3<Real> sample = mSampleData[j0 + mNumSamples[0] * j1]; sum += (x0Value * x1Value) * sample; } } mControlData[i0 + static_cast<size_t>(mNumControls[0]) * i1] = sum; } } } // Access to input sample information. inline int32_t GetNumSamples(int32_t dimension) const { return mNumSamples[dimension]; } inline Vector3<Real> const* GetSampleData() const { return mSampleData; } // Access to output control point and surface information. inline int32_t GetDegree(int32_t dimension) const { return mDegree[dimension]; } inline int32_t GetNumControls(int32_t dimension) const { return mNumControls[dimension]; } inline Vector3<Real> const* GetControlData() const { return &mControlData[0]; } inline BasisFunction<Real> const& GetBasis(int32_t dimension) const { return mBasis[dimension]; } // Evaluation of the B-spline surface. It is defined for // 0 <= u <= 1 and 0 <= v <= 1. If a parameter value is outside // [0,1], it is clamped to [0,1]. Vector3<Real> GetPosition(Real u, Real v) const { int32_t iumin, iumax, ivmin, ivmax; mBasis[0].Evaluate(u, 0, iumin, iumax); mBasis[1].Evaluate(v, 0, ivmin, ivmax); Vector3<Real> position = Vector3<Real>::Zero(); for (int32_t iv = ivmin; iv <= ivmax; ++iv) { Real value1 = mBasis[1].GetValue(0, iv); for (int32_t iu = iumin; iu <= iumax; ++iu) { Real value0 = mBasis[0].GetValue(0, iu); Vector3<Real> control = mControlData[iu + static_cast<size_t>(mNumControls[0]) * iv]; position += (value0 * value1) * control; } } return position; } private: // Input sample information. int32_t mNumSamples[2]; Vector3<Real> const* mSampleData; // The fitted B-spline surface, open and with uniform knots. int32_t mDegree[2]; int32_t mNumControls[2]; std::vector<Vector3<Real>> mControlData; BasisFunction<Real> mBasis[2]; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrTriangle3Cylinder3.h
.h
20,504
488
// 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/Triangle.h> #include <Mathematics/Cylinder3.h> #include <Mathematics/Vector2.h> #include <Mathematics/Vector3.h> // An algorithm for the test-intersection query between a triangle and a // finite cylinder is described in // https://www.geometrictools.com/Documentation/IntersectionTriangleCylinder.pdf // The code here is an implementation of that algorithm. The comments include // references to Figure 1 of the PDF. namespace gte { template <typename T> class TIQuery<T, Triangle3<T>, Cylinder3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Triangle3<T> const& triangle, Cylinder3<T> const& cylinder) { Result result{}; // Get a right-handed orthonormal basis from the cylinder axis // direction. std::array<Vector3<T>, 3> basis{}; // {U2,U0,U1} basis[0] = cylinder.axis.direction; ComputeOrthogonalComplement(1, basis.data()); // Compute coordinates of the triangle vertices in the coordinate // system {C;U0,U1,U2}, where C is the cylinder center and U2 is // the cylinder direction. The basis {U0,U1,U2} is orthonormal and // right-handed. std::array<Vector3<T>, 3> P{}; for (size_t i = 0; i < 3; ++i) { Vector3<T> delta = triangle.v[i] - cylinder.axis.origin; P[i][0] = Dot(basis[1], delta); // x[i] P[i][1] = Dot(basis[2], delta); // y[i] P[i][2] = Dot(basis[0], delta); // z[i] } // Sort the triangle vertices so that z[0] <= z[1] <= z[2]. size_t j0{}, j1{}, j2{}; if (P[0][2] < P[1][2]) { if (P[2][2] < P[0][2]) { j0 = 2; j1 = 0; j2 = 1; } else if (P[2][2] < P[1][2]) { j0 = 0; j1 = 2; j2 = 1; } else { j0 = 0; j1 = 1; j2 = 2; } } else { if (P[2][2] < P[1][2]) { j0 = 2; j1 = 1; j2 = 0; } else if (P[2][2] < P[0][2]) { j0 = 1; j1 = 2; j2 = 0; } else { j0 = 1; j1 = 0; j2 = 2; } } std::array<T, 3> z = { P[j0][2], P[j1][2], P[j2][2] }; // Maintain the xy-components and z-components separately. The // z-components are used for clipping against bottom and top // planes of the cylinder. The xy-components are used for // disk-containment tests x * x + y * y <= r * r. // Attempt an early exit by testing whether the triangle is // strictly outside the cylinder slab -h/2 < z < h/2. T const hhalf = static_cast<T>(0.5) * cylinder.height; if (z[2] < -hhalf) { // The triangle is strictly below the bottom-disk plane of // the cylinder. See case 0a of Figure 1 in the PDF. result.intersect = false; return result; } if (z[0] > hhalf) { // The triangle is strictly above the top-disk plane of the // cylinder. See case 0b of Figure 1 in the PDF. result.intersect = false; return result; } // Project the triangle vertices onto the xy-plane. std::array<Vector2<T>, 3> Q { Vector2<T>{ P[j0][0], P[j0][1] }, Vector2<T>{ P[j1][0], P[j1][1] }, Vector2<T>{ P[j2][0], P[j2][1] } }; // Attempt an early exit when the triangle does not have to be // clipped. T const& radius = cylinder.radius; if (-hhalf <= z[0] && z[2] <= hhalf) { // The triangle is between the planes of the top-disk and // the bottom disk of the cylinder. Determine whether the // projection of the triangle onto a plane perpendicular // to the cylinder axis overlaps the disk of projection // of the cylinder onto the same plane. See case 3a of // Figure 1 of the PDF. result.intersect = DiskOverlapsPolygon(3, Q.data(), radius); return result; } // Clip against |z| <= h/2. At this point we know that z2 >= -h/2 // and z0 <= h/2 with either z0 < -h/2 or z2 > h/2 or both. The // test-intersection query involves testing for overlap between // the xy-projection of the clipped triangle and the xy-projection // of the cylinder (a disk in the projection plane). The code // below computes the vertices of the projection of the clipped // triangle. The t-values of the triangle-edge parameterizations // satisfy 0 <= t <= 1. if (z[0] < -hhalf) { if (z[2] > hhalf) { if (z[1] >= hhalf) { // Cases 4a and 4b of Figure 1 in the PDF. // // The edge <V0,V1> is parameterized by V0+t*(V1-V0). // On the bottom of the slab, // -h/2 = z0 + t * (z1 - z0) // t = (-h/2 - z0) / (z1 - z0) = numerNeg0 / denom10 // and on the tob of the slab, // +h/2 = z0 + t * (z1 - z0) // t = (+h/2 - z0) / (z1 - z0) = numerPos0 / denom10 // // The edge <V0,V2> is parameterized by V0+t*(V2-V0). // On the bottom of the slab, // -h/2 = z0 + t * (z2 - z0) // t = (-h/2 - z0) / (z2 - z0) = numerNeg0 / denom20 // and on the tob of the slab, // +h/2 = z0 + t * (z2 - z0) // t = (+h/2 - z0) / (z2 - z0) = numerPos0 / denom20 T numerNeg0 = -hhalf - z[0]; T numerPos0 = +hhalf - z[0]; T denom10 = z[1] - z[0]; T denom20 = z[2] - z[0]; Vector2<T> dir20 = (Q[2] - Q[0]) / denom20; Vector2<T> dir10 = (Q[1] - Q[0]) / denom10; std::array<Vector2<T>, 4> polygon { Q[0] + numerNeg0 * dir20, Q[0] + numerNeg0 * dir10, Q[0] + numerPos0 * dir10, Q[0] + numerPos0 * dir20 }; result.intersect = DiskOverlapsPolygon(4, polygon.data(), radius); } else if (z[1] <= -hhalf) { // Cases 4c and 4d of Figure 1 of the PDF. // // The edge <V2,V0> is parameterized by V0+t*(V2-V0). // On the bottom of the slab, // -h/2 = z2 + t * (z0 - z2) // t = (-h/2 - z2) / (z0 - z2) = numerNeg2 / denom02 // and on the tob of the slab, // +h/2 = z2 + t * (z0 - z2) // t = (+h/2 - z2) / (z0 - z2) = numerPos2 / denom02 // // The edge <V2,V1> is parameterized by V2+t*(V1-V2). // On the bottom of the slab, // -h/2 = z2 + t * (z1 - z2) // t = (-h/2 - z2) / (z1 - z2) = numerNeg2 / denom12 // and on the top of the slab, // +h/2 = z2 + t * (z1 - z2) // t = (+h/2 - z2) / (z1 - z2) = numerPos2 / denom12 T numerNeg2 = -hhalf - z[2]; T numerPos2 = +hhalf - z[2]; T denom02 = z[0] - z[2]; T denom12 = z[1] - z[2]; Vector2<T> dir02 = (Q[0] - Q[2]) / denom02; Vector2<T> dir12 = (Q[1] - Q[2]) / denom12; std::array<Vector2<T>, 4> polygon { Q[2] + numerNeg2 * dir02, Q[2] + numerNeg2 * dir12, Q[2] + numerPos2 * dir12, Q[2] + numerPos2 * dir02 }; result.intersect = DiskOverlapsPolygon(4, polygon.data(), radius); } else // -hhalf < z[1] < hhalf { // Case 5 of Figure 1 of the PDF. // // The edge <V0,V2> is parameterized by V0+t*(V2-V0). // On the bottom of the slab, // -h/2 = z0 + t * (z2 - z0) // t = (-h/2 - z0) / (z2 - z0) = numerNeg0 / denom20 // and on the tob of the slab, // +h/2 = z0 + t * (z2 - z0) // t = (+h/2 - z0) / (z2 - z0) = numerPos0 / denom20 // // The edge <V1,V0> is parameterized by V1+t*(V0-V1). // On the bottom of the slab, // -h/2 = z1 + t * (z0 - z1) // t = (-h/2 - z1) / (z0 - z1) = numerNeg1 / denom01 // // The edge <V1,V2> is parameterized by V1+t*(V2-V1). // On the top of the slab, // +h/2 = z1 + t * (z2 - z1) // t = (+h/2 - z1) / (z2 - z1) = numerPos1 / denom21 T numerNeg0 = -hhalf - z[0]; T numerPos0 = +hhalf - z[0]; T numerNeg1 = -hhalf - z[1]; T numerPos1 = +hhalf - z[1]; T denom20 = z[2] - z[0]; T denom01 = z[0] - z[1]; T denom21 = z[2] - z[1]; Vector2<T> dir20 = (Q[2] - Q[0]) / denom20; Vector2<T> dir01 = (Q[0] - Q[1]) / denom01; Vector2<T> dir21 = (Q[2] - Q[1]) / denom21; std::array<Vector2<T>, 5> polygon { Q[0] + numerNeg0 * dir20, Q[1] + numerNeg1 * dir01, Q[1], Q[1] + numerPos1 * dir21, Q[0] + numerPos0 * dir20 }; result.intersect = DiskOverlapsPolygon(5, polygon.data(), radius); } } else if (z[2] > -hhalf) { if (z[1] <= -hhalf) { // Cases 3b and 3c of Figure 1 of the PDF. // // The edge <V2,V0> is parameterized by V2+t*(V0-V2). // On the bottom of the slab, // -h/2 = z2 + t * (z0 - z2) // t = (-h/2 - z2) / (z0 - z2) = numerNeg2 / denom02 // // The edge <V2,V1> is parameterized by V2+t*(V1-V2). // On the bottom of the slab, // -h/2 = z2 + t * (z1 - z2) // t = (-h/2 - z2) / (z1 - z2) = numerNeg2 / denom12 T numerNeg2 = -hhalf - z[2]; T denom02 = z[0] - z[2]; T denom12 = z[1] - z[2]; Vector2<T> dir02 = (Q[0] - Q[2]) / denom02; Vector2<T> dir12 = (Q[1] - Q[2]) / denom12; std::array<Vector2<T>, 3> polygon { Q[2], Q[2] + numerNeg2 * dir02, Q[2] + numerNeg2 * dir12 }; result.intersect = DiskOverlapsPolygon(3, polygon.data(), radius); } else // z[1] > -hhalf { // Case 4e of Figure 1 of the PDF. // // The edge <V0,V1> is parameterized by V0+t*(V1-V0). // On the bottom of the slab, // -h/2 = z0 + t * (z1 - z0) // t = (-h/2 - z0) / (z1 - z0) = numerNeg0 / denom10 // // The edge <V0,V2> is parameterized by V0+t*(V2-V0). // On the bottom of the slab, // -h/2 = z0 + t * (z2 - z0) // t = (-h/2 - z0) / (z2 - z0) = numerNeg0 / denom20 T numerNeg0 = -hhalf - z[0]; T denom10 = z[1] - z[0]; T denom20 = z[2] - z[0]; Vector2<T> dir20 = (Q[2] - Q[0]) / denom20; Vector2<T> dir10 = (Q[1] - Q[0]) / denom10; std::array<Vector2<T>, 4> polygon { Q[0] + numerNeg0 * dir20, Q[0] + numerNeg0 * dir10, Q[1], Q[2] }; result.intersect = DiskOverlapsPolygon(4, polygon.data(), radius); } } else // z[2] == -hhalf { if (z[1] < -hhalf) { // Case 1a of Figure 1 of the PDF. result.intersect = DiskOverlapsPoint(Q[2], radius); } else { // Case 2a of Figure 1 of the PDF. result.intersect = DiskOverlapsSegment(Q[1], Q[2], radius); } } } else if (z[0] < hhalf) { if (z[1] >= hhalf) { // Cases 3d and 3e of Figure 1 of the PDF. // // The edge <V0,V1> is parameterized by V0+t*(V1-V0). // On the top of the slab, // +h/2 = z0 + t * (z1 - z0) // t = (+h/2 - z0) / (z1 - z0) = numerPos0 / denom10 // // The edge <V0,V2> is parameterized by V0+t*(V2-V0). // On the top of the slab, // +h/2 = z0 + t * (z2 - z0) // t = (+h/2 - z0) / (z2 - z0) = numerPos0 / denom20 T numerPos0 = +hhalf - z[0]; T denom10 = z[1] - z[0]; T denom20 = z[2] - z[0]; Vector2<T> dir10 = (Q[1] - Q[0]) / denom10; Vector2<T> dir20 = (Q[2] - Q[0]) / denom20; std::array<Vector2<T>, 3> polygon { Q[0], Q[0] + numerPos0 * dir10, Q[0] + numerPos0 * dir20 }; result.intersect = DiskOverlapsPolygon(3, polygon.data(), radius); } else // z[1] < hhalf { // Case 4f of Figure 1 of the PDF. // // The edge <V2,V0> is parameterized by V2+t*(V0-V2). // On the top of the slab, // +h/2 = z2 + t * (z0 - z2) // t = (+h/2 - z2) / (z0 - z2) = numerPos2 / denom02 // // The edge <V2,V1> is parameterized by V2+t*(V1-V2). // On the top of the slab, // +h/2 = z2 + t * (z1 - z2) // t = (+h/2 - z2) / (z1 - z2) = numerPos2 / denom12 T numerPos2 = +hhalf - z[2]; T denom02 = z[0] - z[2]; T denom12 = z[1] - z[2]; Vector2<T> dir02 = (Q[0] - Q[2]) / denom02; Vector2<T> dir12 = (Q[1] - Q[2]) / denom12; std::array<Vector2<T>, 4> polygon { Q[0], Q[1], Q[2] + numerPos2 * dir12, Q[2] + numerPos2 * dir02 }; result.intersect = DiskOverlapsPolygon(4, polygon.data(), radius); } } else // z[0] == hhalf { if (z[1] > hhalf) { // Case 1b of Figure 1 of the PDF. result.intersect = DiskOverlapsPoint(Q[0], radius); } else { // Case 2b of Figure 1 of the PDF. result.intersect = DiskOverlapsSegment(Q[0], Q[1], radius); } } return result; } private: // Support for the static test query. bool DiskOverlapsPoint(Vector2<T> const& Q, T const& radius) const { return Dot(Q, Q) <= radius * radius; } bool DiskOverlapsSegment(Vector2<T> const& Q0, Vector2<T> const& Q1, T const& radius) const { T sqrRadius = radius * radius; Vector2<T> direction = Q0 - Q1; T dot = Dot(Q0, direction); if (dot <= static_cast<T>(0)) { return Dot(Q0, Q0) <= sqrRadius; } T sqrLength = Dot(direction, direction); if (dot >= sqrLength) { return Dot(Q1, Q1) <= sqrRadius; } dot = DotPerp(direction, Q0); return dot * dot <= sqrLength * sqrRadius; } bool DiskOverlapsPolygon(size_t numVertices, Vector2<T> const* Q, T const& radius) const { // Test whether the polygon contains (0,0). T const zero = static_cast<T>(0); size_t positive = 0, negative = 0; size_t i0, i1; for (i0 = numVertices - 1, i1 = 0; i1 < numVertices; i0 = i1++) { T dot = DotPerp(Q[i0], Q[i0] - Q[i1]); if (dot > zero) { ++positive; } else if (dot < zero) { ++negative; } } if (positive == 0 || negative == 0) { // The polygon contains (0,0), so the disk and polygon // overlap. return true; } // Test whether any edge is overlapped by the polygon. for (i0 = numVertices - 1, i1 = 0; i1 < numVertices; i0 = i1++) { if (DiskOverlapsSegment(Q[i0], Q[i1], radius)) { return true; } } return false; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpAkimaNonuniform1.h
.h
3,538
113
// 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 IntpAkimaNonuniform1 : public IntpAkima1<Real> { public: // Construction. The interpolator is for arbitrarily spaced x-values. // The input arrays must have 'quantity' elements and the X[] array // must store increasing values: X[i + 1] > X[i] for all i. IntpAkimaNonuniform1(int32_t quantity, Real const* X, Real const* F) : IntpAkima1<Real>(quantity, F), mX(X) { LogAssert(X != nullptr, "Invalid input."); for (int32_t j0 = 0, j1 = 1; j1 < quantity; ++j0, ++j1) { LogAssert(X[j1] > X[j0], "Invalid input."); } // Compute slopes. 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) { Real dx = X[ip1] - X[i]; Real df = F[ip1] - F[i]; slope[ip2] = df / dx; } 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. for (i = 0, ip1 = 1; i < quantity - 1; ++i, ++ip1) { auto& poly = this->mPoly[i]; Real F0 = F[i]; Real F1 = F[ip1]; Real FDer0 = FDer[i]; Real FDer1 = FDer[ip1]; Real df = F1 - F0; Real dx = X[ip1] - X[i]; Real dx2 = dx * dx; Real dx3 = dx2 * dx; poly[0] = F0; poly[1] = FDer0; poly[2] = ((Real)3 * df - dx * (FDer1 + (Real)2 * FDer0)) / dx2; poly[3] = (dx * (FDer0 + FDer1) - (Real)2 * df) / dx3; } } virtual ~IntpAkimaNonuniform1() = default; // Member access. Real const* GetX() const { return mX; } virtual Real GetXMin() const override { return mX[0]; } virtual Real GetXMax() const override { return mX[this->mQuantity - 1]; } protected: virtual void Lookup(Real x, int32_t& index, Real& dx) const override { // The caller has ensured that mXMin <= x <= mXMax. for (index = 0; index + 1 < this->mQuantity; ++index) { if (x < mX[index + 1]) { dx = x - mX[index]; return; } } --index; dx = x - mX[index]; } Real const* mX; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLineLine.h
.h
2,962
93
// 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> // Compute the distance between two lines in nD. // // The lines are P[i] + s[i] * D[i], where D[i] is not required to be unit // length. // // The closest point on line[i] is stored in closest[i] with parameter[i] // storing s[i]. 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, Line<N, T>, Line<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<T, 2> parameter; std::array<Vector<N, T>, 2> closest; }; Result operator()(Line<N, T> const& line0, Line<N, T> const& line1) { Result result{}; T const zero = static_cast<T>(0); Vector<N, T> diff = line0.origin - line1.origin; T a00 = Dot(line0.direction, line0.direction); T a01 = -Dot(line0.direction, line1.direction); T a11 = Dot(line1.direction, line1.direction); T b0 = Dot(line0.direction, diff); T det = std::max(a00 * a11 - a01 * a01, zero); T s0{}, s1{}; if (det > zero) { // The lines are not parallel. T b1 = -Dot(line1.direction, diff); s0 = (a01 * b1 - a11 * b0) / det; s1 = (a01 * b0 - a00 * b1) / det; } else { // The lines are parallel. Select any pair of closest points. s0 = -b0 / a00; s1 = zero; } result.parameter[0] = s0; result.parameter[1] = s1; result.closest[0] = line0.origin + s0 * line0.direction; result.closest[1] = line1.origin + s1 * line1.direction; 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 DCPLineLine = DCPQuery<T, Line<N, T>, Line<N, T>>; template <typename T> using DCPLine2Line2 = DCPLineLine<2, T>; template <typename T> using DCPLine3Line3 = DCPLineLine<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistOrientedBox3OrientedBox3.h
.h
4,544
121
// 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/DistRectangle3OrientedBox3.h> // Compute the distance between two solid oriented boxes in 3D. // // Each 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 of the first oriented box is stored in closest[0]. The // closest point of the second oriented 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, OrientedBox3<T>, OrientedBox3<T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{} { } T distance, sqrDistance; std::array<Vector3<T>, 2> closest; }; Result operator()(OrientedBox3<T> const& box0, OrientedBox3<T> const& box1) { Result result{}; DCPQuery<T, Rectangle3<T>, OrientedBox3<T>> rbQuery{}; typename DCPQuery<T, Rectangle3<T>, OrientedBox3<T>>::Result rbOutput{}; Rectangle3<T> rectangle{}; T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; // Compare faces of box0 to box1. for (int32_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++) { rectangle.axis[0] = box0.axis[i0]; rectangle.axis[1] = box0.axis[i1]; rectangle.extent[0] = box0.extent[i0]; rectangle.extent[1] = box0.extent[i1]; Vector3<T> scaledAxis = box0.extent[i2] * box0.axis[i2]; rectangle.center = box0.center + scaledAxis; rbOutput = rbQuery(rectangle, box1); if (result.sqrDistance == invalid || rbOutput.sqrDistance < result.sqrDistance) { result.distance = rbOutput.distance; result.sqrDistance = rbOutput.sqrDistance; result.closest = rbOutput.closest; } rectangle.center = box0.center - scaledAxis; rbOutput = rbQuery(rectangle, box1); if (result.sqrDistance == invalid || rbOutput.sqrDistance < result.sqrDistance) { result.distance = rbOutput.distance; result.sqrDistance = rbOutput.sqrDistance; result.closest = rbOutput.closest; } } // Compare faces of box1 to box0. for (int32_t i0 = 2, i1 = 0, i2 = 1; i1 < 3; i2 = i0, i0 = i1++) { rectangle.axis[0] = box1.axis[i0]; rectangle.axis[1] = box1.axis[i1]; rectangle.extent[0] = box1.extent[i0]; rectangle.extent[1] = box1.extent[i1]; Vector3<T> scaledAxis = box1.extent[i2] * box1.axis[i2]; rectangle.center = box1.center + scaledAxis; rbOutput = rbQuery(rectangle, box0); if (result.sqrDistance == invalid || rbOutput.sqrDistance < result.sqrDistance) { result.distance = rbOutput.distance; result.sqrDistance = rbOutput.sqrDistance; result.closest[0] = rbOutput.closest[1]; result.closest[1] = rbOutput.closest[0]; } rectangle.center = box1.center - scaledAxis; rbOutput = rbQuery(rectangle, box0); if (result.sqrDistance == invalid || rbOutput.sqrDistance < result.sqrDistance) { result.distance = rbOutput.distance; result.sqrDistance = rbOutput.sqrDistance; result.closest[0] = rbOutput.closest[1]; result.closest[1] = rbOutput.closest[0]; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ImageUtility2.h
.h
59,818
1,487
// 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/Image2.h> #include <cmath> #include <functional> #include <limits> // Image utilities for Image2<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 and d1 rows. The input image must have zeros on its // boundaries x = 0, x = d0-1, y = 0 and y = d1-1. The 0-valued pixels are // considered to be background. The 1-valued pixels 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. Dilation and // erosion functions do not have the requirement that the boundary pixels of // the binary image inputs be zero. namespace gte { class ImageUtility2 { public: // Compute the 4-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 GetComponents4(Image2<int32_t>& image, std::vector<std::vector<size_t>>& components) { std::array<int32_t, 4> neighbors; image.GetNeighborhood(neighbors); GetComponents(4, &neighbors[0], image, components); } // Compute the 8-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 GetComponents8(Image2<int32_t>& image, std::vector<std::vector<size_t>>& components) { std::array<int32_t, 8> neighbors; image.GetNeighborhood(neighbors); GetComponents(8, &neighbors[0], image, components); } // Compute a dilation with a structuring element consisting of the // 4-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. static void Dilate4(Image2<int32_t> const& input, Image2<int32_t>& output) { std::array<std::array<int32_t, 2>, 4> neighbors; input.GetNeighborhood(neighbors); Dilate(input, 4, &neighbors[0], output); } // Compute a dilation with a structuring element consisting of the // 8-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. static void Dilate8(Image2<int32_t> const& input, Image2<int32_t>& output) { std::array<std::array<int32_t, 2>, 8> neighbors; input.GetNeighborhood(neighbors); Dilate(input, 8, &neighbors[0], output); } // Compute a dilation with a structing element consisting of neighbors // specified by offsets relative to the pixel. The input image is // binary with 0 for background and 1 for foreground. The output // image must be an object different from the input image. static void Dilate(Image2<int32_t> const& input, int32_t numNeighbors, std::array<int32_t, 2> const* neighbors, Image2<int32_t>& output) { LogAssert(&output != &input, "Input and output must be different."); output = input; // If the pixel at (x,y) is 1, then the pixels at (x+dx,y+dy) are // set to 1 where (dx,dy) is in the 'neighbors' array. Boundary // testing is used to avoid accessing out-of-range pixels. int32_t const dim0 = input.GetDimension(0); int32_t const dim1 = input.GetDimension(1); for (int32_t y = 0; y < dim1; ++y) { for (int32_t x = 0; x < dim0; ++x) { if (input(x, y) == 1) { for (int32_t j = 0; j < numNeighbors; ++j) { int32_t xNbr = x + neighbors[j][0]; int32_t yNbr = y + neighbors[j][1]; if (0 <= xNbr && xNbr < dim0 && 0 <= yNbr && yNbr < dim1) { output(xNbr, yNbr) = 1; } } } } } } // Compute an erosion with a structuring element consisting of the // 4-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. If zeroExterior is // true, the image exterior is assumed to be 0, so 1-valued boundary // pixels are set to 0; otherwise, boundary pixels are set to 0 only // when they have neighboring image pixels that are 0. static void Erode4(Image2<int32_t> const& input, bool zeroExterior, Image2<int32_t>& output) { std::array<std::array<int32_t, 2>, 4> neighbors; input.GetNeighborhood(neighbors); Erode(input, zeroExterior, 4, &neighbors[0], output); } // Compute an erosion with a structuring element consisting of the // 8-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. If zeroExterior is // true, the image exterior is assumed to be 0, so 1-valued boundary // pixels are set to 0; otherwise, boundary pixels are set to 0 only // when they have neighboring image pixels that are 0. static void Erode8(Image2<int32_t> const& input, bool zeroExterior, Image2<int32_t>& output) { std::array<std::array<int32_t, 2>, 8> neighbors; input.GetNeighborhood(neighbors); Erode(input, zeroExterior, 8, &neighbors[0], output); } // Compute an erosion with a structuring element consisting of // neighbors specified by offsets relative to the pixel. The input // image is binary with 0 for background and 1 for foreground. The // output image must be an object different from the input image. If // zeroExterior is true, the image exterior is assumed to be 0, so // 1-valued boundary pixels are set to 0; otherwise, boundary pixels // are set to 0 only when they have neighboring image pixels that // are 0. static void Erode(Image2<int32_t> const& input, bool zeroExterior, int32_t numNeighbors, std::array<int32_t, 2> const* neighbors, Image2<int32_t>& output) { LogAssert(&output != &input, "Input and output must be different."); output = input; // If the pixel at (x,y) is 1, it is changed to 0 when at least // one neighbor (x+dx,y+dy) is 0, where (dx,dy) is in the // 'neighbors' array. int32_t const dim0 = input.GetDimension(0); int32_t const dim1 = input.GetDimension(1); for (int32_t y = 0; y < dim1; ++y) { for (int32_t x = 0; x < dim0; ++x) { if (input(x, y) == 1) { for (int32_t j = 0; j < numNeighbors; ++j) { int32_t xNbr = x + neighbors[j][0]; int32_t yNbr = y + neighbors[j][1]; if (0 <= xNbr && xNbr < dim0 && 0 <= yNbr && yNbr < dim1) { if (input(xNbr, yNbr) == 0) { output(x, y) = 0; break; } } else if (zeroExterior) { output(x, y) = 0; break; } } } } } } // Compute an opening with a structuring element consisting of the // 4-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. If zeroExterior is // true, the image exterior is assumed to consist of 0-valued pixels; // otherwise, the image exterior is assumed to consist of 1-valued // pixels. static void Open4(Image2<int32_t> const& input, bool zeroExterior, Image2<int32_t>& output) { Image2<int32_t> temp(input.GetDimension(0), input.GetDimension(1)); Erode4(input, zeroExterior, temp); Dilate4(temp, output); } // Compute an opening with a structuring element consisting of the // 8-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. If zeroExterior is // true, the image exterior is assumed to consist of 0-valued pixels; // otherwise, the image exterior is assumed to consist of 1-valued // pixels. static void Open8(Image2<int32_t> const& input, bool zeroExterior, Image2<int32_t>& output) { Image2<int32_t> temp(input.GetDimension(0), input.GetDimension(1)); Erode8(input, zeroExterior, temp); Dilate8(temp, output); } // Compute an opening with a structuring element consisting of // neighbors specified by offsets relative to the pixel. The input // image is binary with 0 for background and 1 for foreground. The // output image must be an object different from the input image. If // zeroExterior is true, the image exterior is assumed to consist of // 0-valued pixels; otherwise, the image exterior is assumed to // consist of 1-valued pixels. static void Open(Image2<int32_t> const& input, bool zeroExterior, int32_t numNeighbors, std::array<int32_t, 2> const* neighbors, Image2<int32_t>& output) { Image2<int32_t> temp(input.GetDimension(0), input.GetDimension(1)); Erode(input, zeroExterior, numNeighbors, neighbors, temp); Dilate(temp, numNeighbors, neighbors, output); } // Compute a closing with a structuring element consisting of the // 4-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. If zeroExterior is // true, the image exterior is assumed to consist of 0-valued pixels; // otherwise, the image exterior is assumed to consist of 1-valued // pixels. static void Close4(Image2<int32_t> const& input, bool zeroExterior, Image2<int32_t>& output) { Image2<int32_t> temp(input.GetDimension(0), input.GetDimension(1)); Dilate4(input, temp); Erode4(temp, zeroExterior, output); } // Compute a closing with a structuring element consisting of the // 8-connected neighbors of each pixel. The input image is binary // with 0 for background and 1 for foreground. The output image must // be an object different from the input image. If zeroExterior is // true, the image exterior is assumed to consist of 0-valued pixels; // otherwise, the image exterior is assumed to consist of 1-valued // pixels. static void Close8(Image2<int32_t> const& input, bool zeroExterior, Image2<int32_t>& output) { Image2<int32_t> temp(input.GetDimension(0), input.GetDimension(1)); Dilate8(input, temp); Erode8(temp, zeroExterior, output); } // Compute a closing with a structuring element consisting of // neighbors specified by offsets relative to the pixel. The input // image is binary with 0 for background and 1 for foreground. The // output image must be an object different from the input image. If // zeroExterior is true, the image exterior is assumed to consist of // 0-valued pixels; otherwise, the image exterior is assumed to // consist of 1-valued pixels. static void Close(Image2<int32_t> const& input, bool zeroExterior, int32_t numNeighbors, std::array<int32_t, 2> const* neighbors, Image2<int32_t>& output) { Image2<int32_t> temp(input.GetDimension(0), input.GetDimension(1)); Dilate(input, numNeighbors, neighbors, temp); Erode(temp, zeroExterior, numNeighbors, neighbors, output); } // Locate a pixel and walk around the edge of a component. The input // (x,y) is where the search starts for a nonzero pixel. If (x,y) is // outside the component, the walk is around the outside the // component. If the component has a hole and (x,y) is inside that // hole, the walk is around the boundary surrounding the hole. The // function returns 'true' on a success walk. The return value is // 'false' when no boundary was found from the starting (x,y). static bool ExtractBoundary(int32_t x, int32_t y, Image2<int32_t>& image, std::vector<size_t>& boundary) { // Find a first boundary pixel. size_t const numPixels = image.GetNumPixels(); size_t i; for (i = image.GetIndex(x, y); i < numPixels; ++i) { if (image[i]) { break; } } if (i == numPixels) { // No boundary pixel found. return false; } std::array<int32_t, 8> const dx = { -1, 0, +1, +1, +1, 0, -1, -1 }; std::array<int32_t, 8> const dy = { -1, -1, -1, 0, +1, +1, +1, 0 }; // Create a new point list that contains the first boundary point. boundary.push_back(i); // The direction from background 0 to boundary pixel 1 is // (dx[7],dy[7]). std::array<int32_t, 2> coord = image.GetCoordinates(i); int32_t x0 = coord[0], y0 = coord[1]; int32_t cx = x0, cy = y0; int32_t nx = x0 - 1, ny = y0, dir = 7; // Traverse the boundary in clockwise order. Mark visited pixels // as 2. image(cx, cy) = 2; bool notDone = true; while (notDone) { int32_t j, nbr; for (j = 0, nbr = dir; j < 8; ++j, nbr = (nbr + 1) % 8) { nx = cx + dx[nbr]; ny = cy + dy[nbr]; if (image(nx, ny)) // next boundary pixel found { break; } } if (j == 8) { // (cx,cy) is isolated notDone = false; continue; } if (nx == x0 && ny == y0) { // boundary traversal completed notDone = false; continue; } // (nx,ny) is next boundary point, add point to list. Note // that the index for the pixel is computed for the original // image, not for the larger temporary image. boundary.push_back(image.GetIndex(nx, ny)); // Mark visited pixels as 2. image(nx, ny) = 2; // Start search for next point. cx = nx; cy = ny; dir = (j + 5 + dir) % 8; } return true; } // Use a depth-first search for filling a 4-connected region. This is // nonrecursive, simulated by using a heap-allocated "stack". The // input (x,y) is the seed point that starts the fill. template <typename PixelType> static void FloodFill4(Image2<PixelType>& image, int32_t x, int32_t y, PixelType foreColor, PixelType backColor) { // Test for a valid seed. int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); if (x < 0 || x >= dim0 || y < 0 || y >= dim1) { // 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 numPixels = image.GetNumPixels(); std::vector<int32_t> xStack(numPixels), yStack(numPixels); // 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; 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]; // Fill the pixel. image(x, y) = foreColor; int32_t xp1 = x + 1; if (xp1 < dim0 && image(xp1, y) == backColor) { // Push pixel with background color. ++top; xStack[top] = xp1; yStack[top] = y; continue; } int32_t xm1 = x - 1; if (0 <= xm1 && image(xm1, y) == backColor) { // Push pixel with background color. ++top; xStack[top] = xm1; yStack[top] = y; continue; } int32_t yp1 = y + 1; if (yp1 < dim1 && image(x, yp1) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = yp1; continue; } int32_t ym1 = y - 1; if (0 <= ym1 && image(x, ym1) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = ym1; continue; } // Done in all directions, pop and return to search other // directions of predecessor. --top; } } // Compute the L1-distance transform of the binary image. The function // returns the maximum distance and a point at which the maximum // distance is attained. static void GetL1Distance(Image2<int32_t>& image, int32_t& maxDistance, int32_t& xMax, int32_t& yMax) { int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); int32_t const dim0m1 = dim0 - 1; int32_t const dim1m1 = dim1 - 1; // Use a grass-fire approach, computing distance from boundary to // interior one pass at a time. bool changeMade = true; int32_t distance; for (distance = 1, xMax = 0, yMax = 0; changeMade; ++distance) { changeMade = false; int32_t distanceP1 = distance + 1; for (int32_t y = 1; y < dim1m1; ++y) { for (int32_t x = 1; x < dim0m1; ++x) { if (image(x, y) == distance) { if (image(x - 1, y) >= distance && image(x + 1, y) >= distance && image(x, y - 1) >= distance && image(x, y + 1) >= distance) { image(x, y) = distanceP1; xMax = x; yMax = y; changeMade = true; } } } } } maxDistance = --distance; } // Compute the L2-distance transform of the binary image. The maximum // distance should not be larger than 100, so you have to ensure this // is the case for the input image. The function returns the maximum // distance and a point at which the maximum distance is attained. // Comments about the algorithm are in the source file. static void GetL2Distance(Image2<int32_t> const& image, float& maxDistance, int32_t& xMax, int32_t& yMax, Image2<float>& transform) { // This program calculates the Euclidean distance transform of a // binary input image. The adaptive algorithm is guaranteed to // give exact distances for all distances < 100. The algorithm // was provided John Gauch at University of Kansas. The following // is a quote: /// // The basic idea is similar to a EDT described recently in PAMI // by Laymarie from McGill. By keeping the dx and dy offset to // the nearest edge (feature) point in the image, we can search to // see which dx dy is closest to a given point by examining a set // of neighbors. The Laymarie method (and Borgfors) look at a // fixed 3x3 or 5x5 neighborhood and call it a day. What we did // was calculate (painfully) what neighborhoods you need to look // at to guarentee that the exact distance is obtained. Thus, // you will see in the code, that we L2Check the current distance // and depending on what we have so far, we extend the search // region. Since our algorithm for L2Checking the exactness of // each neighborhood is on the order N^4, we have only gone to // N=100. In theory, you could make this large enough to get all // distances exact. We have implemented the algorithm to get all // distances < 100 to be exact. int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); int32_t const dim0m1 = dim0 - 1; int32_t const dim1m1 = dim1 - 1; int32_t x, y, distance; // Create and initialize intermediate images. Image2<int32_t> xNear(dim0, dim1); Image2<int32_t> yNear(dim0, dim1); Image2<int32_t> dist(dim0, dim1); for (y = 0; y < dim1; ++y) { for (x = 0; x < dim0; ++x) { if (image(x, y) != 0) { xNear(x, y) = 0; yNear(x, y) = 0; dist(x, y) = std::numeric_limits<int32_t>::max(); } else { xNear(x, y) = x; yNear(x, y) = y; dist(x, y) = 0; } } } int32_t const K1 = 1; int32_t const K2 = 169; // 13^2 int32_t const K3 = 961; // 31^2 int32_t const K4 = 2401; // 49^2 int32_t const K5 = 5184; // 72^2 // Pass in the ++ direction. for (y = 0; y < dim1; ++y) { for (x = 0; x < dim0; ++x) { distance = dist(x, y); if (distance > K1) { L2Check(x, y, -1, 0, xNear, yNear, dist); L2Check(x, y, -1, -1, xNear, yNear, dist); L2Check(x, y, 0, -1, xNear, yNear, dist); } if (distance > K2) { L2Check(x, y, -2, -1, xNear, yNear, dist); L2Check(x, y, -1, -2, xNear, yNear, dist); } if (distance > K3) { L2Check(x, y, -3, -1, xNear, yNear, dist); L2Check(x, y, -3, -2, xNear, yNear, dist); L2Check(x, y, -2, -3, xNear, yNear, dist); L2Check(x, y, -1, -3, xNear, yNear, dist); } if (distance > K4) { L2Check(x, y, -4, -1, xNear, yNear, dist); L2Check(x, y, -4, -3, xNear, yNear, dist); L2Check(x, y, -3, -4, xNear, yNear, dist); L2Check(x, y, -1, -4, xNear, yNear, dist); } if (distance > K5) { L2Check(x, y, -5, -1, xNear, yNear, dist); L2Check(x, y, -5, -2, xNear, yNear, dist); L2Check(x, y, -5, -3, xNear, yNear, dist); L2Check(x, y, -5, -4, xNear, yNear, dist); L2Check(x, y, -4, -5, xNear, yNear, dist); L2Check(x, y, -2, -5, xNear, yNear, dist); L2Check(x, y, -3, -5, xNear, yNear, dist); L2Check(x, y, -1, -5, xNear, yNear, dist); } } } // Pass in -- direction. for (y = dim1m1; y >= 0; --y) { for (x = dim0m1; x >= 0; --x) { distance = dist(x, y); if (distance > K1) { L2Check(x, y, 1, 0, xNear, yNear, dist); L2Check(x, y, 1, 1, xNear, yNear, dist); L2Check(x, y, 0, 1, xNear, yNear, dist); } if (distance > K2) { L2Check(x, y, 2, 1, xNear, yNear, dist); L2Check(x, y, 1, 2, xNear, yNear, dist); } if (distance > K3) { L2Check(x, y, 3, 1, xNear, yNear, dist); L2Check(x, y, 3, 2, xNear, yNear, dist); L2Check(x, y, 2, 3, xNear, yNear, dist); L2Check(x, y, 1, 3, xNear, yNear, dist); } if (distance > K4) { L2Check(x, y, 4, 1, xNear, yNear, dist); L2Check(x, y, 4, 3, xNear, yNear, dist); L2Check(x, y, 3, 4, xNear, yNear, dist); L2Check(x, y, 1, 4, xNear, yNear, dist); } if (distance > K5) { L2Check(x, y, 5, 1, xNear, yNear, dist); L2Check(x, y, 5, 2, xNear, yNear, dist); L2Check(x, y, 5, 3, xNear, yNear, dist); L2Check(x, y, 5, 4, xNear, yNear, dist); L2Check(x, y, 4, 5, xNear, yNear, dist); L2Check(x, y, 2, 5, xNear, yNear, dist); L2Check(x, y, 3, 5, xNear, yNear, dist); L2Check(x, y, 1, 5, xNear, yNear, dist); } } } // Pass in the +- direction. for (y = dim1m1; y >= 0; --y) { for (x = 0; x < dim0; ++x) { distance = dist(x, y); if (distance > K1) { L2Check(x, y, -1, 0, xNear, yNear, dist); L2Check(x, y, -1, 1, xNear, yNear, dist); L2Check(x, y, 0, 1, xNear, yNear, dist); } if (distance > K2) { L2Check(x, y, -2, 1, xNear, yNear, dist); L2Check(x, y, -1, 2, xNear, yNear, dist); } if (distance > K3) { L2Check(x, y, -3, 1, xNear, yNear, dist); L2Check(x, y, -3, 2, xNear, yNear, dist); L2Check(x, y, -2, 3, xNear, yNear, dist); L2Check(x, y, -1, 3, xNear, yNear, dist); } if (distance > K4) { L2Check(x, y, -4, 1, xNear, yNear, dist); L2Check(x, y, -4, 3, xNear, yNear, dist); L2Check(x, y, -3, 4, xNear, yNear, dist); L2Check(x, y, -1, 4, xNear, yNear, dist); } if (distance > K5) { L2Check(x, y, -5, 1, xNear, yNear, dist); L2Check(x, y, -5, 2, xNear, yNear, dist); L2Check(x, y, -5, 3, xNear, yNear, dist); L2Check(x, y, -5, 4, xNear, yNear, dist); L2Check(x, y, -4, 5, xNear, yNear, dist); L2Check(x, y, -2, 5, xNear, yNear, dist); L2Check(x, y, -3, 5, xNear, yNear, dist); L2Check(x, y, -1, 5, xNear, yNear, dist); } } } // Pass in the -+ direction. for (y = 0; y < dim1; ++y) { for (x = dim0m1; x >= 0; --x) { distance = dist(x, y); if (distance > K1) { L2Check(x, y, 1, 0, xNear, yNear, dist); L2Check(x, y, 1, -1, xNear, yNear, dist); L2Check(x, y, 0, -1, xNear, yNear, dist); } if (distance > K2) { L2Check(x, y, 2, -1, xNear, yNear, dist); L2Check(x, y, 1, -2, xNear, yNear, dist); } if (distance > K3) { L2Check(x, y, 3, -1, xNear, yNear, dist); L2Check(x, y, 3, -2, xNear, yNear, dist); L2Check(x, y, 2, -3, xNear, yNear, dist); L2Check(x, y, 1, -3, xNear, yNear, dist); } if (distance > K4) { L2Check(x, y, 4, -1, xNear, yNear, dist); L2Check(x, y, 4, -3, xNear, yNear, dist); L2Check(x, y, 3, -4, xNear, yNear, dist); L2Check(x, y, 1, -4, xNear, yNear, dist); } if (distance > K5) { L2Check(x, y, 5, -1, xNear, yNear, dist); L2Check(x, y, 5, -2, xNear, yNear, dist); L2Check(x, y, 5, -3, xNear, yNear, dist); L2Check(x, y, 5, -4, xNear, yNear, dist); L2Check(x, y, 4, -5, xNear, yNear, dist); L2Check(x, y, 2, -5, xNear, yNear, dist); L2Check(x, y, 3, -5, xNear, yNear, dist); L2Check(x, y, 1, -5, xNear, yNear, dist); } } } xMax = 0; yMax = 0; maxDistance = 0.0f; for (y = 0; y < dim1; ++y) { for (x = 0; x < dim0; ++x) { float fdistance = std::sqrt((float)dist(x, y)); if (fdistance > maxDistance) { maxDistance = fdistance; xMax = x; yMax = y; } transform(x, y) = fdistance; } } } // Compute a skeleton of a binary image. Boundary pixels are trimmed // from the object one layer at a time based on their adjacency to // interior pixels. At each step the connectivity and cycles of the // object are preserved. The skeleton overwrites the contents of the // input image. static void GetSkeleton(Image2<int32_t>& image) { int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); // Trim pixels, mark interior as 4. bool notDone = true; while (notDone) { if (MarkInterior(image, 4, Interior4)) { // No interior pixels, trimmed set is at most 2-pixels // thick. notDone = false; continue; } if (ClearInteriorAdjacent(image, 4)) { // All remaining interior pixels are either articulation // points or part of blobs whose boundary pixels are all // articulation points. An example of the latter case is // shown below. The background pixels are marked with '.' // rather than '0' for readability. The interior pixels // are marked with '4' and the boundary pixels are marked // with '1'. // // ......... // .....1... // ..1.1.1.. // .1.141... // ..14441.. // ..1441.1. // .1.11.1.. // ..1..1... // ......... // // This is a pathological problem where there are many // small holes (0-pixel with north, south, west, and east // neighbors all 1-pixels) that your application can try // to avoid by an initial pass over the image to fill in // such holes. Of course, you do have problems with // checkerboard patterns... notDone = false; continue; } } // Trim pixels, mark interior as 3. notDone = true; while (notDone) { if (MarkInterior(image, 3, Interior3)) { // No interior pixels, trimmed set is at most 2-pixels // thick. notDone = false; continue; } if (ClearInteriorAdjacent(image, 3)) { // All remaining 3-values can be safely removed since they // are not articulation points and the removal will not // cause new holes. for (int32_t y = 0; y < dim1; ++y) { for (int32_t x = 0; x < dim0; ++x) { if (image(x, y) == 3 && !IsArticulation(image, x, y)) { image(x, y) = 0; } } } notDone = false; continue; } } // Trim pixels, mark interior as 2. notDone = true; while (notDone) { if (MarkInterior(image, 2, Interior2)) { // No interior pixels, trimmed set is at most 1-pixel // thick. Call it a skeleton. notDone = false; continue; } if (ClearInteriorAdjacent(image, 2)) { // Removes 2-values that are not articulation points. for (int32_t y = 0; y < dim1; ++y) { for (int32_t x = 0; x < dim0; ++x) { if (image(x, y) == 2 && !IsArticulation(image, x, y)) { image(x, y) = 0; } } } notDone = false; continue; } } // Make the skeleton a binary image. size_t const numPixels = image.GetNumPixels(); for (size_t i = 0; i < numPixels; ++i) { if (image[i] != 0) { image[i] = 1; } } } // In the remaining public member functions, the callback represents // the action you want applied to each pixel as it is visited. // Visit pixels in a (2*thick+1)x(2*thick+1) square centered at (x,y). static void DrawThickPixel(int32_t x, int32_t y, int32_t thick, std::function<void(int32_t, int32_t)> const& callback) { for (int32_t dy = -thick; dy <= thick; ++dy) { for (int32_t dx = -thick; dx <= thick; ++dx) { callback(x + dx, y + dy); } } } // Visit pixels using Bresenham's line drawing algorithm. static void DrawLine(int32_t x0, int32_t y0, int32_t x1, int32_t y1, std::function<void(int32_t, int32_t)> const& callback) { // Starting point of line. int32_t x = x0, y = y0; // Direction of line. int32_t dx = x1 - x0, dy = y1 - y0; // 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)); // Decision parameters for pixel selection. if (dx < 0) { dx = -dx; } if (dy < 0) { dy = -dy; } int32_t ax = 2 * dx, ay = 2 * dy; int32_t decX, decY; // Determine largest direction component, single-step related // variable. int32_t maxValue = dx, var = 0; if (dy > maxValue) { var = 1; } // Traverse Bresenham line. switch (var) { case 0: // Single-step in x-direction. decY = ay - dx; for (/**/; /**/; x += sx, decY += ay) { callback(x, y); // Take Bresenham step. if (x == x1) { break; } if (decY >= 0) { decY -= ax; y += sy; } } break; case 1: // Single-step in y-direction. decX = ax - dy; for (/**/; /**/; y += sy, decX += ax) { callback(x, y); // Take Bresenham step. if (y == y1) { break; } if (decX >= 0) { decX -= ay; x += sx; } } break; } } // Visit pixels using Bresenham's circle drawing algorithm. Set // 'solid' to false for drawing only the circle. Set 'solid' to true // to draw all pixels on and inside the circle. static void DrawCircle(int32_t xCenter, int32_t yCenter, int32_t radius, bool solid, std::function<void(int32_t, int32_t)> const& callback) { int32_t x, y, dec; if (solid) { int32_t xValue, yMin, yMax, i; for (x = 0, y = radius, dec = 3 - 2 * radius; x <= y; ++x) { xValue = xCenter + x; yMin = yCenter - y; yMax = yCenter + y; for (i = yMin; i <= yMax; ++i) { callback(xValue, i); } xValue = xCenter - x; for (i = yMin; i <= yMax; ++i) { callback(xValue, i); } xValue = xCenter + y; yMin = yCenter - x; yMax = yCenter + x; for (i = yMin; i <= yMax; ++i) { callback(xValue, i); } xValue = xCenter - y; for (i = yMin; i <= yMax; ++i) { callback(xValue, i); } if (dec >= 0) { dec += -4 * (y--) + 4; } dec += 4 * x + 6; } } else { for (x = 0, y = radius, dec = 3 - 2 * radius; x <= y; ++x) { callback(xCenter + x, yCenter + y); callback(xCenter + x, yCenter - y); callback(xCenter - x, yCenter + y); callback(xCenter - x, yCenter - y); callback(xCenter + y, yCenter + x); callback(xCenter + y, yCenter - x); callback(xCenter - y, yCenter + x); callback(xCenter - y, yCenter - x); if (dec >= 0) { dec += -4 * (y--) + 4; } dec += 4 * x + 6; } } } // Visit pixels in a rectangle of the specified dimensions. Set // 'solid' to false for drawing only the rectangle. Set 'solid' to // true to draw all pixels on and inside the rectangle. static void DrawRectangle(int32_t xMin, int32_t yMin, int32_t xMax, int32_t yMax, bool solid, std::function<void(int32_t, int32_t)> const& callback) { int32_t x, y; if (solid) { for (y = yMin; y <= yMax; ++y) { for (x = xMin; x <= xMax; ++x) { callback(x, y); } } } else { for (x = xMin; x <= xMax; ++x) { callback(x, yMin); callback(x, yMax); } for (y = yMin + 1; y <= yMax - 1; ++y) { callback(xMin, y); callback(xMax, y); } } } // Visit the pixels using Bresenham's algorithm for the axis-aligned // ellipse ((x-xc)/a)^2 + ((y-yc)/b)^2 = 1, where xCenter is xc, // yCenter is yc, xExtent is a, and yExtent is b. static void DrawEllipse(int32_t xCenter, int32_t yCenter, int32_t xExtent, int32_t yExtent, std::function<void(int32_t, int32_t)> const& callback) { int32_t xExtSqr = xExtent * xExtent, yExtSqr = yExtent * yExtent; int32_t x, y, dec; x = 0; y = yExtent; dec = 2 * yExtSqr + xExtSqr * (1 - 2 * yExtent); for (/**/; yExtSqr * x <= xExtSqr * y; ++x) { callback(xCenter + x, yCenter + y); callback(xCenter - x, yCenter + y); callback(xCenter + x, yCenter - y); callback(xCenter - x, yCenter - y); if (dec >= 0) { dec += 4 * xExtSqr * (1 - y); --y; } dec += yExtSqr * (4 * x + 6); } if (y == 0 && x < xExtent) { // The discretization caused us to reach the y-axis before the // x-values reached the ellipse vertices. Draw a solid line // along the x-axis to those vertices. for (/**/; x <= xExtent; ++x) { callback(xCenter + x, yCenter); callback(xCenter - x, yCenter); } return; } x = xExtent; y = 0; dec = 2 * xExtSqr + yExtSqr * (1 - 2 * xExtent); for (/**/; xExtSqr * y <= yExtSqr * x; ++y) { callback(xCenter + x, yCenter + y); callback(xCenter - x, yCenter + y); callback(xCenter + x, yCenter - y); callback(xCenter - x, yCenter - y); if (dec >= 0) { dec += 4 * yExtSqr * (1 - x); --x; } dec += xExtSqr * (4 * y + 6); } if (x == 0 && y < yExtent) { // The discretization caused us to reach the x-axis before the // y-values reached the ellipse vertices. Draw a solid line // along the y-axis to those vertices. for (/**/; y <= yExtent; ++y) { callback(xCenter, yCenter + y); callback(xCenter, yCenter - y); } } } // Use a depth-first search for filling a 4-connected region. This is // nonrecursive, simulated by using a heap-allocated "stack". The // input (x,y) is the seed point that starts the fill. The x-value is // in {0..xSize-1} and the y-value is in {0..ySize-1}. template <typename PixelType> static void DrawFloodFill4(int32_t x, int32_t y, int32_t xSize, int32_t ySize, PixelType foreColor, PixelType backColor, std::function<void(int32_t, int32_t, PixelType)> const& setCallback, std::function<PixelType(int32_t, int32_t)> const& getCallback) { // Test for a valid seed. if (x < 0 || x >= xSize || y < 0 || y >= ySize) { // The seed point is outside the image domain, so nothing to // fill. return; } // Allocate the maximum amount of space needed for the stack. An // empty stack has top == -1. int32_t const numPixels = xSize * ySize; std::vector<int32_t> xStack(numPixels), yStack(numPixels); // 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; 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]; // Fill the pixel. setCallback(x, y, foreColor); int32_t xp1 = x + 1; if (xp1 < xSize && getCallback(xp1, y) == backColor) { // Push pixel with background color. ++top; xStack[top] = xp1; yStack[top] = y; continue; } int32_t xm1 = x - 1; if (0 <= xm1 && getCallback(xm1, y) == backColor) { // Push pixel with background color. ++top; xStack[top] = xm1; yStack[top] = y; continue; } int32_t yp1 = y + 1; if (yp1 < ySize && getCallback(x, yp1) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = yp1; continue; } int32_t ym1 = y - 1; if (0 <= ym1 && getCallback(x, ym1) == backColor) { // Push pixel with background color. ++top; xStack[top] = x; yStack[top] = ym1; continue; } // Done in all directions, pop and return to search other // directions of the predecessor. --top; } } private: // Connected component labeling using depth-first search. static void GetComponents(int32_t numNeighbors, int32_t const* delta, Image2<int32_t>& image, std::vector<std::vector<size_t>>& components) { size_t const numPixels = image.GetNumPixels(); std::vector<int32_t> numElements(numPixels); std::vector<size_t> vstack(numPixels); size_t i, numComponents = 0; int32_t label = 2; for (i = 0; i < numPixels; ++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 < numPixels; ++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]; } } } } // Support for GetL2Distance. static void L2Check(int32_t x, int32_t y, int32_t dx, int32_t dy, Image2<int32_t>& xNear, Image2<int32_t>& yNear, Image2<int32_t>& dist) { int32_t const dim0 = dist.GetDimension(0); int32_t const dim1 = dist.GetDimension(1); int32_t xp = x + dx, yp = y + dy; if (0 <= xp && xp < dim0 && 0 <= yp && yp < dim1) { if (dist(xp, yp) < dist(x, y)) { int32_t dx0 = xNear(xp, yp) - x; int32_t dy0 = yNear(xp, yp) - y; int32_t newDist = dx0 * dx0 + dy0 * dy0; if (newDist < dist(x, y)) { xNear(x, y) = xNear(xp, yp); yNear(x, y) = yNear(xp, yp); dist(x, y) = newDist; } } } } // Support for GetSkeleton. static bool Interior2(Image2<int32_t>& image, int32_t x, int32_t y) { bool b1 = (image(x, y - 1) != 0); bool b3 = (image(x + 1, y) != 0); bool b5 = (image(x, y + 1) != 0); bool b7 = (image(x - 1, y) != 0); return (b1 && b3) || (b3 && b5) || (b5 && b7) || (b7 && b1); } static bool Interior3(Image2<int32_t>& image, int32_t x, int32_t y) { int32_t numNeighbors = 0; if (image(x - 1, y) != 0) { ++numNeighbors; } if (image(x + 1, y) != 0) { ++numNeighbors; } if (image(x, y - 1) != 0) { ++numNeighbors; } if (image(x, y + 1) != 0) { ++numNeighbors; } return numNeighbors == 3; } static bool Interior4(Image2<int32_t>& image, int32_t x, int32_t y) { return image(x - 1, y) != 0 && image(x + 1, y) != 0 && image(x, y - 1) != 0 && image(x, y + 1) != 0; } static bool MarkInterior(Image2<int32_t>& image, int32_t value, bool (*function)(Image2<int32_t>&, int32_t, int32_t)) { int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); bool noInterior = true; for (int32_t y = 0; y < dim1; ++y) { for (int32_t x = 0; x < dim0; ++x) { if (image(x, y) > 0) { if (function(image, x, y)) { image(x, y) = value; noInterior = false; } else { image(x, y) = 1; } } } } return noInterior; } static bool IsArticulation(Image2<int32_t>& image, int32_t x, int32_t y) { static std::array<int32_t, 256> const articulation = { 0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0, 0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0, 0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0, 0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0, 0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0, 0,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0, 0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0, 1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0, 0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,1,0,0,1,1,0,0,1,1,0,0, 1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0, 0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0 }; // Converts 8 neighbors of pixel (x,y) to an 8-bit value, // bit = 1 iff pixel is set. int32_t byteMask = 0; if (image(x - 1, y - 1) != 0) { byteMask |= 0x01; } if (image(x, y - 1) != 0) { byteMask |= 0x02; } if (image(x + 1, y - 1) != 0) { byteMask |= 0x04; } if (image(x + 1, y) != 0) { byteMask |= 0x08; } if (image(x + 1, y + 1) != 0) { byteMask |= 0x10; } if (image(x, y + 1) != 0) { byteMask |= 0x20; } if (image(x - 1, y + 1) != 0) { byteMask |= 0x40; } if (image(x - 1, y) != 0) { byteMask |= 0x80; } return articulation[byteMask] == 1; } static bool ClearInteriorAdjacent(Image2<int32_t>& image, int32_t value) { int32_t const dim0 = image.GetDimension(0); int32_t const dim1 = image.GetDimension(1); bool noRemoval = true; for (int32_t y = 0; y < dim1; ++y) { for (int32_t x = 0; x < dim0; ++x) { if (image(x, y) == 1) { bool interiorAdjacent = image(x - 1, y - 1) == value || image(x, y - 1) == value || image(x + 1, y - 1) == value || image(x + 1, y) == value || image(x + 1, y + 1) == value || image(x, y + 1) == value || image(x - 1, y + 1) == value || image(x - 1, y) == value; if (interiorAdjacent && !IsArticulation(image, x, y)) { image(x, y) = 0; noRemoval = false; } } } } return noRemoval; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IsPlanarGraph.h
.h
19,040
494
// 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 <array> #include <map> #include <set> #include <vector> // Test whether an undirected graph is planar. The input positions must be // unique and the input edges must be unique, so the number of positions is // at least 2 and the number of edges is at least one. The elements of the // edges array must be indices in {0,..,positions.size()-1}. // // A sort-and-sweep algorithm is used to determine edge-edge intersections. // If none of the intersections occur at edge-interior points, the graph is // planar. See Game Physics (2nd edition), Section 6.2.2: Culling with // Axis-Aligned Bounding Boxes for such an algorithm. The operator() // returns 'true' when the graph is planar. If it returns 'false', the // 'invalidIntersections' set contains pairs of edges that intersect at an // edge-interior point (that by definition is not a graph vertex). Each set // element is a pair of indices into the 'edges' array; the indices are // ordered so that element[0] < element[1]. The Real type must be chosen // to guarantee exact computation of edge-edge intersections. namespace gte { template <typename Real> class IsPlanarGraph { public: IsPlanarGraph() : mZero(0), mOne(1) { } enum { IPG_IS_PLANAR_GRAPH = 0, IPG_INVALID_INPUT_SIZES = 1, IPG_DUPLICATED_POSITIONS = 2, IPG_DUPLICATED_EDGES = 4, IPG_DEGENERATE_EDGES = 8, IPG_EDGES_WITH_INVALID_VERTICES = 16, IPG_INVALID_INTERSECTIONS = 32 }; // The function returns a combination of the IPG_* flags listed in the // previous enumeration. A combined value of 0 indicates the input // forms a planar graph. If the combined value is not zero, you may // examine the flags for the failure conditions and use the Get* // member accessors to obtain specific information about the failure. // If the positions.size() < 2 or edges.size() == 0, the // IPG_INVALID_INPUT_SIZES flag is set. int32_t operator()(std::vector<std::array<Real, 2>> const& positions, std::vector<std::array<int32_t, 2>> const& edges) { mDuplicatedPositions.clear(); mDuplicatedEdges.clear(); mDegenerateEdges.clear(); mEdgesWithInvalidVertices.clear(); mInvalidIntersections.clear(); int32_t flags = IsValidTopology(positions, edges); if (flags == IPG_INVALID_INPUT_SIZES) { return flags; } std::set<OrderedEdge> overlappingRectangles; ComputeOverlappingRectangles(positions, edges, overlappingRectangles); for (auto key : overlappingRectangles) { // Get the endpoints of the line segments for the edges whose // bounding rectangles overlapped. Determine whether the line // segments intersect. If they do, determine how they // intersect. std::array<int32_t, 2> e0 = edges[key.V[0]]; std::array<int32_t, 2> e1 = edges[key.V[1]]; std::array<Real, 2> const& p0 = positions[e0[0]]; std::array<Real, 2> const& p1 = positions[e0[1]]; std::array<Real, 2> const& q0 = positions[e1[0]]; std::array<Real, 2> const& q1 = positions[e1[1]]; if (InvalidSegmentIntersection(p0, p1, q0, q1)) { mInvalidIntersections.push_back(key); } } if (mInvalidIntersections.size() > 0) { flags |= IPG_INVALID_INTERSECTIONS; } return flags; } // A pair of indices (v0,v1) into the positions array is stored as // (min(v0,v1), max(v0,v1)). This supports sorted containers of // edges. struct OrderedEdge { OrderedEdge(int32_t v0 = -1, int32_t v1 = -1) { if (v0 < v1) { // v0 is minimum V[0] = v0; V[1] = v1; } else { // v1 is minimum V[0] = v1; V[1] = v0; } } bool operator<(OrderedEdge const& edge) const { // Lexicographical ordering used by std::array<int32_t,2>. return V < edge.V; } std::array<int32_t, 2> V; }; inline std::vector<std::vector<int32_t>> const& GetDuplicatedPositions() const { return mDuplicatedPositions; } inline std::vector<std::vector<int32_t>> const& GetDuplicatedEdges() const { return mDuplicatedEdges; } inline std::vector<int32_t> const& GetDegenerateEdges() const { return mDegenerateEdges; } inline std::vector<int32_t> const& GetEdgesWithInvalidVertices() const { return mEdgesWithInvalidVertices; } inline std::vector<typename IsPlanarGraph<Real>::OrderedEdge> const& GetInvalidIntersections() const { return mInvalidIntersections; } private: class Endpoint { public: Endpoint() : value(static_cast<Real>(0)), type(0), index(0) { } Real value; // endpoint value int32_t type; // '0' if interval min, '1' if interval max. int32_t index; // index of interval containing this endpoint // Comparison operator for sorting. bool operator<(Endpoint const& endpoint) const { if (value < endpoint.value) { return true; } if (value > endpoint.value) { return false; } return type < endpoint.type; } }; int32_t IsValidTopology(std::vector<std::array<Real, 2>> const& positions, std::vector<std::array<int32_t, 2>> const& edges) { int32_t const numPositions = static_cast<int32_t>(positions.size()); int32_t const numEdges = static_cast<int32_t>(edges.size()); if (numPositions < 2 || numEdges == 0) { // The graph must have at least one edge. return IPG_INVALID_INPUT_SIZES; } // The positions must be unique. int32_t flags = IPG_IS_PLANAR_GRAPH; std::map<std::array<Real, 2>, std::vector<int32_t>> uniquePositions; for (int32_t i = 0; i < numPositions; ++i) { std::array<Real, 2> p = positions[i]; auto iter = uniquePositions.find(p); if (iter == uniquePositions.end()) { std::vector<int32_t> indices; indices.push_back(i); uniquePositions.insert(std::make_pair(p, indices)); } else { iter->second.push_back(i); } } if (uniquePositions.size() < positions.size()) { // At least two positions are duplicated. for (auto const& element : uniquePositions) { if (element.second.size() > 1) { mDuplicatedPositions.push_back(element.second); } } flags |= IPG_DUPLICATED_POSITIONS; } // The edges must be unique. std::map<OrderedEdge, std::vector<int32_t>> uniqueEdges; for (int32_t i = 0; i < numEdges; ++i) { OrderedEdge key(edges[i][0], edges[i][1]); auto iter = uniqueEdges.find(key); if (iter == uniqueEdges.end()) { std::vector<int32_t> indices; indices.push_back(i); uniqueEdges.insert(std::make_pair(key, indices)); } else { iter->second.push_back(i); } } if (uniqueEdges.size() < edges.size()) { // At least two edges are duplicated, possibly even a pair of // edges (v0,v1) and (v1,v0) which is not allowed because the // graph is undirected. for (auto const& element : uniqueEdges) { if (element.second.size() > 1) { mDuplicatedEdges.push_back(element.second); } } flags |= IPG_DUPLICATED_EDGES; } // The edges are represented as pairs of indices into the // 'positions' array. The indices for a single edge must be // different (no edges allowed from a vertex to itself) and all // indices must be valid. At the same time, keep track of unique // edges. for (int32_t i = 0; i < numEdges; ++i) { std::array<int32_t, 2> e = edges[i]; if (e[0] == e[1]) { // The edge is degenerate, originating and terminating at // the same vertex. mDegenerateEdges.push_back(i); flags |= IPG_DEGENERATE_EDGES; } if (e[0] < 0 || e[0] >= numPositions || e[1] < 0 || e[1] >= numPositions) { // The edge has an index that references a nonexistent // vertex. mEdgesWithInvalidVertices.push_back(i); flags |= IPG_EDGES_WITH_INVALID_VERTICES; } } return flags; } void ComputeOverlappingRectangles(std::vector<std::array<Real, 2>> const& positions, std::vector<std::array<int32_t, 2>> const& edges, std::set<OrderedEdge>& overlappingRectangles) const { // Compute axis-aligned bounding rectangles for the edges. int32_t const numEdges = static_cast<int32_t>(edges.size()); std::vector<std::array<Real, 2>> emin(numEdges); std::vector<std::array<Real, 2>> emax(numEdges); for (int32_t i = 0; i < numEdges; ++i) { std::array<int32_t, 2> e = edges[i]; std::array<Real, 2> const& p0 = positions[e[0]]; std::array<Real, 2> const& p1 = positions[e[1]]; for (int32_t j = 0; j < 2; ++j) { if (p0[j] < p1[j]) { emin[i][j] = p0[j]; emax[i][j] = p1[j]; } else { emin[i][j] = p1[j]; emax[i][j] = p0[j]; } } } // Get the rectangle endpoints. int32_t const numEndpoints = 2 * numEdges; std::vector<Endpoint> xEndpoints(numEndpoints); std::vector<Endpoint> yEndpoints(numEndpoints); for (int32_t i = 0, j = 0; i < numEdges; ++i) { xEndpoints[j].type = 0; xEndpoints[j].value = emin[i][0]; xEndpoints[j].index = i; yEndpoints[j].type = 0; yEndpoints[j].value = emin[i][1]; yEndpoints[j].index = i; ++j; xEndpoints[j].type = 1; xEndpoints[j].value = emax[i][0]; xEndpoints[j].index = i; yEndpoints[j].type = 1; yEndpoints[j].value = emax[i][1]; yEndpoints[j].index = i; ++j; } // Sort the rectangle endpoints. std::sort(xEndpoints.begin(), xEndpoints.end()); std::sort(yEndpoints.begin(), yEndpoints.end()); // Sweep through the endpoints to determine overlapping // x-intervals. Use an active set of rectangles to reduce the // complexity of the algorithm. std::set<int32_t> active; for (int32_t i = 0; i < numEndpoints; ++i) { Endpoint const& endpoint = xEndpoints[i]; int32_t index = endpoint.index; if (endpoint.type == 0) // an interval 'begin' value { // In the 1D problem, the current interval overlaps with // all the active intervals. In 2D this we also need to // check for y-overlap. for (auto activeIndex : active) { // Rectangles activeIndex and index overlap in the // x-dimension. Test for overlap in the y-dimension. std::array<Real, 2> const& r0min = emin[activeIndex]; std::array<Real, 2> const& r0max = emax[activeIndex]; std::array<Real, 2> const& r1min = emin[index]; std::array<Real, 2> const& r1max = emax[index]; if (r0max[1] >= r1min[1] && r0min[1] <= r1max[1]) { if (activeIndex < index) { overlappingRectangles.insert(OrderedEdge(activeIndex, index)); } else { overlappingRectangles.insert(OrderedEdge(index, activeIndex)); } } } active.insert(index); } else // an interval 'end' value { active.erase(index); } } } bool InvalidSegmentIntersection( std::array<Real, 2> const& p0, std::array<Real, 2> const& p1, std::array<Real, 2> const& q0, std::array<Real, 2> const& q1) const { // We must solve the two linear equations // p0 + t0 * (p1 - p0) = q0 + t1 * (q1 - q0) // for the unknown variables t0 and t1. These may be written as // t0 * (p1 - p0) - t1 * (q1 - q0) = q0 - p0 // If denom = Dot(p1 - p0, Perp(q1 - q0)) is not zero, then // t0 = Dot(q0 - p0, Perp(q1 - q0)) / denom = numer0 / denom // t1 = Dot(q0 - p0, Perp(p1 - p0)) / denom = numer1 / denom // For an invalid intersection, we need (t0,t1) with: // ((0 < t0 < 1) and (0 <= t1 <= 1)) or ((0 <= t0 <= 1) and // (0 < t1 < 1). std::array<Real, 2> p1mp0, q1mq0, q0mp0; for (int32_t j = 0; j < 2; ++j) { p1mp0[j] = p1[j] - p0[j]; q1mq0[j] = q1[j] - q0[j]; q0mp0[j] = q0[j] - p0[j]; } Real denom = p1mp0[0] * q1mq0[1] - p1mp0[1] * q1mq0[0]; Real numer0 = q0mp0[0] * q1mq0[1] - q0mp0[1] * q1mq0[0]; Real numer1 = q0mp0[0] * p1mp0[1] - q0mp0[1] * p1mp0[0]; if (denom != mZero) { // The lines of the segments are not parallel. if (denom > mZero) { if (mZero <= numer0 && numer0 <= denom && mZero <= numer1 && numer1 <= denom) { // The segments intersect. return (numer0 != mZero && numer0 != denom) || (numer1 != mZero && numer1 != denom); } else { return false; } } else // denom < mZero { if (mZero >= numer0 && numer0 >= denom && mZero >= numer1 && numer1 >= denom) { // The segments intersect. return (numer0 != mZero && numer0 != denom) || (numer1 != mZero && numer1 != denom); } else { return false; } } } else { // The lines of the segments are parallel. if (numer0 != mZero || numer1 != mZero) { // The lines of the segments are separated. return false; } else { // The segments lie on the same line. Compute the // parameter intervals for the segments in terms of the // t0-parameter and determine their overlap (if any). std::array<Real, 2> q1mp0; for (int32_t j = 0; j < 2; ++j) { q1mp0[j] = q1[j] - p0[j]; } Real sqrLenP1mP0 = p1mp0[0] * p1mp0[0] + p1mp0[1] * p1mp0[1]; Real value0 = q0mp0[0] * p1mp0[0] + q0mp0[1] * p1mp0[1]; Real value1 = q1mp0[0] * p1mp0[0] + q1mp0[1] * p1mp0[1]; if ((value0 >= sqrLenP1mP0 && value1 >= sqrLenP1mP0) || (value0 <= mZero && value1 <= mZero)) { // If the segments intersect, they must do so at // endpoints of the segments. return false; } else { // The segments overlap in a positive-length interval. return true; } } } } std::vector<std::vector<int32_t>> mDuplicatedPositions; std::vector<std::vector<int32_t>> mDuplicatedEdges; std::vector<int32_t> mDegenerateEdges; std::vector<int32_t> mEdgesWithInvalidVertices; std::vector<OrderedEdge> mInvalidIntersections; Real mZero, mOne; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SeparatePoints2.h
.h
7,172
205
// 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/ConvexHull2.h> // Separate two point sets, if possible, by computing a line for which the // point sets lie on opposite sides. The algorithm computes the convex hull // of the point sets, then uses the method of separating axes to determine // whether the two convex polygons are disjoint. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf namespace gte { template <typename Real, typename ComputeType> class SeparatePoints2 { public: // The return value is 'true' if and only if there is a separation. // If 'true', the returned line is a separating line. The code // assumes that each point set has at least 3 noncollinear points. bool operator()(int32_t numPoints0, Vector2<Real> const* points0, int32_t numPoints1, Vector2<Real> const* points1, Line2<Real>& separatingLine) const { // Construct convex hull of point set 0. ConvexHull2<Real> ch0; ch0(numPoints0, points0, (Real)0); if (ch0.GetDimension() != 2) { return false; } // Construct convex hull of point set 1. ConvexHull2<Real> ch1; ch1(numPoints1, points1, (Real)0); if (ch1.GetDimension() != 2) { return false; } int32_t numEdges0 = static_cast<int32_t>(ch0.GetHull().size()); int32_t const* edges0 = &ch0.GetHull()[0]; int32_t numEdges1 = static_cast<int32_t>(ch1.GetHull().size()); int32_t const* edges1 = &ch1.GetHull()[0]; // Test edges of hull 0 for possible separation of points. int32_t j0, j1, i0, i1, side0, side1; Vector2<Real> lineNormal; Real lineConstant; for (j1 = 0, j0 = numEdges0 - 1; j1 < numEdges0; j0 = j1++) { // Look up edge (assert: i0 != i1 ). i0 = edges0[j0]; i1 = edges0[j1]; // Compute potential separating line // (assert: (xNor,yNor) != (0,0)). separatingLine.origin = points0[i0]; separatingLine.direction = points0[i1] - points0[i0]; Normalize(separatingLine.direction); lineNormal = Perp(separatingLine.direction); lineConstant = Dot(lineNormal, separatingLine.origin); // Determine whether hull 1 is on same side of line. side1 = OnSameSide(lineNormal, lineConstant, numEdges1, edges1, points1); if (side1) { // Determine on which side of line hull 0 lies. side0 = WhichSide(lineNormal, lineConstant, numEdges0, edges0, points0); if (side0 * side1 <= 0) // Line separates hulls. { return true; } } } // Test edges of hull 1 for possible separation of points. for (j1 = 0, j0 = numEdges1 - 1; j1 < numEdges1; j0 = j1++) { // Look up edge (assert: i0 != i1 ). i0 = edges1[j0]; i1 = edges1[j1]; // Compute perpendicular to edge // (assert: (xNor,yNor) != (0,0)). separatingLine.origin = points1[i0]; separatingLine.direction = points1[i1] - points1[i0]; Normalize(separatingLine.direction); lineNormal = Perp(separatingLine.direction); lineConstant = Dot(lineNormal, separatingLine.origin); // Determine whether hull 0 is on same side of line. side0 = OnSameSide(lineNormal, lineConstant, numEdges0, edges0, points0); if (side0) { // Determine on which side of line hull 1 lies. side1 = WhichSide(lineNormal, lineConstant, numEdges1, edges1, points1); if (side0 * side1 <= 0) // Line separates hulls. { return true; } } } return false; } private: int32_t OnSameSide(Vector2<Real> const& lineNormal, Real lineConstant, int32_t numEdges, int32_t const* edges, Vector2<Real> const* points) const { // Test whether all points on same side of line Dot(N,X) = c. Real c0; int32_t posSide = 0, negSide = 0; for (int32_t i1 = 0, i0 = numEdges - 1; i1 < numEdges; i0 = i1++) { c0 = Dot(lineNormal, points[edges[i0]]); if (c0 > lineConstant) { ++posSide; } else if (c0 < lineConstant) { ++negSide; } if (posSide && negSide) { // Line splits point set. return 0; } c0 = Dot(lineNormal, points[edges[i1]]); if (c0 > lineConstant) { ++posSide; } else if (c0 < lineConstant) { ++negSide; } if (posSide && negSide) { // Line splits point set. return 0; } } return (posSide ? +1 : -1); } int32_t WhichSide(Vector2<Real> const& lineNormal, Real lineConstant, int32_t numEdges, int32_t const* edges, Vector2<Real> const* points) const { // Establish which side of line hull is on. Real c0; for (int32_t i1 = 0, i0 = numEdges - 1; i1 < numEdges; i0 = i1++) { c0 = Dot(lineNormal, points[edges[i0]]); if (c0 > lineConstant) { // Hull on positive side. return +1; } if (c0 < lineConstant) { // Hull on negative side. return -1; } c0 = Dot(lineNormal, points[edges[i1]]); if (c0 > lineConstant) { // Hull on positive side. return +1; } if (c0 < lineConstant) { // Hull on negative side. return -1; } } // Hull is effectively collinear. return 0; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprCone3EllipseAndPoints.h
.h
15,919
448
// 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.02.25 #pragma once #include <Mathematics/Logger.h> #include <Mathematics/ApprGaussian3.h> #include <Mathematics/ApprEllipse2.h> #include <Mathematics/Cone.h> #include <Mathematics/Ellipse3.h> #include <Mathematics/Hyperplane.h> #include <Mathematics/Minimize1.h> #include <Mathematics/OBBTreeOfPoints.h> // An infinite single-sided cone is fit to a 3D ellipse that is known to be // the intersection of a plane with the cone. The ellipse itself is not // enough information, producing the cone vertex and cone direction as a // function of the cone angle. Additional points on the cone are required // to determine the cone angle. The algorithm description is // https://www.geometrictools.com/Documentation/FitConeToEllipseAndPoints.pdf namespace gte { template <typename T> class ApprCone3EllipseAndPoints { public: // The ellipse must be the intersection of a plane with the cone. // In an application, typically the ellipse is estimated from point // samples of the intersection which are then fitted with the // ellipse. // // The default control parameters appear to be reasonable for // applications, but they are exposed to the caller for tuning. struct Control { Control() : penalty(static_cast<T>(1)), maxSubdivisions(8), maxBisections(64), epsilon(static_cast<T>(1e-08)), tolerance(static_cast<T>(1e-04)), padding(static_cast<T>(1e-03)) { } bool ValidParameters() const { T const zero = static_cast<T>(0); return penalty > zero && maxSubdivisions > 0 && maxBisections > 0 && epsilon > zero && tolerance > zero && padding > zero; } // The least-squares error function is updated with the // penalty value for a points[i] that is below the plane // supporting the cone; that is, when the dot product // Dot(coneDirection, points[i] - coneVertex) < 0. T penalty; // Parameters for Minimizer1<T>. int32_t maxSubdivisions; int32_t maxBisections = 64; T epsilon = static_cast<T>(1e-08); T tolerance = static_cast<T>(1e-04); // Search for the minimum on [0 + padding, pi/2 - padding] to // avoid divisions by zero of the least-squares error function // at the endpoints of [0,pi/2]. T padding; }; static Cone3<T> Fit(Ellipse3<T> const& ellipse, std::vector<Vector3<T>> const& points, Control control = Control{}) { LogAssert( control.ValidParameters(), "Invalid control parameter."); T sigma0{}, sigma1{}; auto F = [&ellipse, &points, &sigma0, &sigma1, &control](T const& theta) { T const zero = static_cast<T>(0); auto cone = ComputeCone(theta, sigma0, sigma1, ellipse); T error = zero; for (auto const& point : points) { auto diff = point - cone.ray.origin; auto dot = Dot(cone.ray.direction, diff); if (dot >= zero) { auto sqrLen = Dot(diff, diff); auto quad = dot * dot - cone.cosAngleSqr * sqrLen; auto term = quad * quad; error += term; } else { error += control.penalty; } } error = std::sqrt(error) / static_cast<T>(points.size()); return error; }; T const one = static_cast<T>(1); Minimize1<T> minimizer(F, control.maxSubdivisions, control.maxBisections, control.epsilon, control.tolerance); T t0 = static_cast<T>(control.padding); T t1 = static_cast<T>(GTE_C_HALF_PI) - control.padding; T tmin{}, fmin{}; T minError = -one; Cone3<T> minCone{}; sigma0 = one; sigma1 = one; minimizer.GetMinimum(t0, t1, tmin, fmin); if (t0 < tmin && tmin < t1) { if (minError == -one || fmin < minError) { minError = fmin; minCone = ComputeCone(tmin, sigma0, sigma1, ellipse); } } sigma0 = one; sigma1 = -one; minimizer.GetMinimum(t0, t1, tmin, fmin); if (t0 < tmin && tmin < t1) { if (minError == -one || fmin < minError) { minError = fmin; minCone = ComputeCone(tmin, sigma0, sigma1, ellipse); } } sigma0 = -one; sigma1 = one; minimizer.GetMinimum(t0, t1, tmin, fmin); if (t0 < tmin && tmin < t1) { if (minError == -one || fmin < minError) { minError = fmin; minCone = ComputeCone(tmin, sigma0, sigma1, ellipse); } } sigma0 = -one; sigma1 = -one; minimizer.GetMinimum(t0, t1, tmin, fmin); if (t0 < tmin && tmin < t1) { if (minError == -one || fmin < minError) { minError = fmin; minCone = ComputeCone(tmin, sigma0, sigma1, ellipse); } } LogAssert( minError != -one, "Failed to find fitted cone."); return minCone; } private: static Cone3<T> ComputeCone(T theta, T sigma0, T sigma1, Ellipse3<T> const& ellipse) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); auto const& C = ellipse.center; auto const& N = ellipse.normal; auto const& U = ellipse.axis[0]; auto const& a = ellipse.extent[0]; auto const& b = ellipse.extent[1]; auto bDivA = b / a; auto eSqr = std::max(zero, one - bDivA * bDivA); auto omesqr = one - eSqr; auto e = std::sqrt(eSqr); auto snTheta = std::sin(theta); auto csTheta = std::cos(theta); auto snPhi = sigma0 * e * csTheta; auto snPhiSqr = snPhi * snPhi; auto csPhi = sigma1 * std::sqrt(std::max(zero, one - snPhiSqr)); auto h = a * omesqr * csTheta / (snTheta * std::fabs(csPhi)); auto D = csPhi * N + snPhi * U; auto snThetaSqr = snTheta * snTheta; auto csThetaSqr = csTheta * csTheta; auto Q = C - ((h * snPhi * snThetaSqr) / (csThetaSqr - snPhiSqr)) * U; auto K = Q - h * D; Cone3<T> cone{}; cone.MakeInfiniteCone(); cone.SetAngle(theta); cone.ray.origin = K; cone.ray.direction = D; return cone; } }; // If the points contain only elliptical cross sections of intersection of // planes with the cone, extract the ellipses so that one of them can be // used as input to ApprCone3EllipseAndPoints. template <typename T> class ApprCone3ExtractEllipses { public: ApprCone3ExtractEllipses() : mBoxExtentEpsilon(static_cast<T>(0)), mCosAngleEpsilon(static_cast<T>(0)), mOBBTree{}, mPlanes{}, mIndices{}, mBoxes{}, mEllipses{} { } // The boxExtentEpsilon determines when a box is deemed "flat." // The cosAngleEpsilon is used to decide when two flat boxes are // in the same plane. void Extract(std::vector<Vector3<T>> const& points, T boxExtentEpsilon, T cosAngleEpsilon, std::vector<Ellipse3<T>>& ellipses) { T const zero = static_cast<T>(0); mBoxExtentEpsilon = std::max(boxExtentEpsilon, zero); mCosAngleEpsilon = std::max(cosAngleEpsilon, zero); mOBBTree.clear(); mPlanes.clear(); mIndices.clear(); mBoxes.clear(); mEllipses.clear(); CreateOBBTree(points); LocatePlanes(0); AssociatePointsWithPlanes(points); mEllipses.resize(mIndices.size()); for (size_t i = 0; i < mIndices.size(); ++i) { mEllipses[i] = ComputeEllipse(points, mIndices[i]); } ellipses = mEllipses; } // Access the ellipses extracted from the input points. inline std::vector<Ellipse3<T>> const& GetEllipses() const { return mEllipses; } // Accessors for informational purposes. inline std::vector<typename OBBTreeForPoints<T>::Node> const& GetOBBTree() const { return mOBBTree; } inline std::vector<Plane3<T>> const& GetPlanes() const { return mPlanes; } inline std::vector<std::vector<int32_t>> const& GetIndices() const { return mIndices; } inline std::vector<OrientedBox3<T>> const& GetBoxes() const { return mBoxes; } private: void CreateOBBTree(std::vector<Vector3<T>> const& points) { uint32_t const numPoints = static_cast<uint32_t>(points.size()); char const* rawPoints = reinterpret_cast<char const*>(points.data()); size_t const stride = sizeof(points[0]); OBBTreeForPoints<T> creator(numPoints, rawPoints, stride); mOBBTree = creator.GetTree(); } void LocatePlanes(size_t nodeIndex) { auto const& node = mOBBTree[nodeIndex]; if (node.maxIndex >= node.minIndex + 2) { for (int32_t j = 0; j < 3; ++j) { if (node.box.extent[j] <= mBoxExtentEpsilon) { mBoxes.push_back(node.box); Plane3<T> plane(node.box.axis[j], node.box.center); ProcessPlane(plane); return; } } } if (node.leftChild != std::numeric_limits<uint32_t>::max()) { LocatePlanes(node.leftChild); } if (node.rightChild != std::numeric_limits<uint32_t>::max()) { LocatePlanes(node.rightChild); } } void ProcessPlane(Plane3<T> const& plane) { T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const epsilon = mCosAngleEpsilon; T const oneMinusEpsilon = one - epsilon; for (size_t i = 0; i < mPlanes.size(); ++i) { T cosAngle = Dot(plane.normal, mPlanes[i].normal); T absDiff{}; if (cosAngle > zero) { absDiff = std::fabs(plane.constant - mPlanes[i].constant); if (cosAngle >= oneMinusEpsilon && absDiff <= epsilon) { // The planes are effectively the same. return; } } else { cosAngle = -cosAngle; absDiff = std::fabs(plane.constant + mPlanes[i].constant); if (cosAngle >= oneMinusEpsilon && absDiff <= epsilon) { // The planes are effectively the same. return; } } } mPlanes.push_back(plane); } void AssociatePointsWithPlanes(std::vector<Vector3<T>> const& points) { mIndices.resize(mPlanes.size()); for (size_t i = 0; i < points.size(); ++i) { auto const& point = points[i]; T minDistance = std::numeric_limits<T>::max(); size_t minJ = std::numeric_limits<size_t>::max(); for (size_t j = 0; j < mPlanes.size(); ++j) { auto const& plane = mPlanes[j]; auto diff = point - plane.origin; T distance = std::fabs(Dot(plane.normal, diff)); if (distance < minDistance) { minDistance = distance; minJ = j; } } mIndices[minJ].push_back(static_cast<int32_t>(i)); } } Ellipse3<T> ComputeEllipse(std::vector<Vector3<T>> const& points, std::vector<int32_t> const& indices) { // Fit the points with a 3D Gaussian distribution. The eigenvalues // are computed in nondecreasing order, which means the smallest // eigenvalue corresponds to the normal vector gbox.axis[0] of the // plane of the points. Use gbox.axis[1] and gbox.axis[2] as the // spanners of the plane of the point. ApprGaussian3<T> gfitter{}; gfitter.FitIndexed(points.size(), points.data(), indices.size(), indices.data()); auto const& gbox = gfitter.GetParameters(); // Project the points onto the plane as 2-tuples. std::vector<Vector2<T>> projections(indices.size()); for (size_t i = 0; i < indices.size(); ++i) { Vector3<T> diff = points[indices[i]] - gbox.center; projections[i][0] = Dot(gbox.axis[1], diff); projections[i][1] = Dot(gbox.axis[2], diff); } // Fit the projected points with a 2D ellipse. ApprEllipse2<T> efitter{}; size_t const numIterations = 1024; bool const useEllipseForInitialGuess = false; Ellipse2<T> ellipse2{}; efitter(projections, numIterations, useEllipseForInitialGuess, ellipse2); // Lift the 2D ellipse to a 3D ellipse. Ellipse3<T> ellipse3{}; ellipse3.center = gbox.center + ellipse2.center[0] * gbox.axis[1] + ellipse2.center[1] * gbox.axis[2]; ellipse3.normal = gbox.axis[0]; ellipse3.axis[0] = ellipse2.axis[0][0] * gbox.axis[1] + ellipse2.axis[0][1] * gbox.axis[2]; ellipse3.axis[1] = ellipse2.axis[1][0] * gbox.axis[1] + ellipse2.axis[1][1] * gbox.axis[2]; ellipse3.extent = ellipse2.extent; return ellipse3; } T mBoxExtentEpsilon, mCosAngleEpsilon; std::vector<typename OBBTreeForPoints<T>::Node> mOBBTree; std::vector<Plane3<T>> mPlanes; std::vector<std::vector<int32_t>> mIndices; std::vector<OrientedBox3<T>> mBoxes; std::vector<Ellipse3<T>> mEllipses; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/TanEstimate.h
.h
5,511
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 tan(x). The polynomial p(x) of // degree D has only odd-power terms, is required to have linear term x, // and p(pi/4) = tan(pi/4) = 1. It minimizes the quantity // maximum{|tan(x) - p(x)| : x in [-pi/4,pi/4]} over all polynomials of // degree D subject to the constraints mentioned. namespace gte { template <typename Real> class TanEstimate { public: // The input constraint is x in [-pi/4,pi/4]. For example, // float x; // in [-pi/4,pi/4] // float result = TanEstimate<float>::Degree<3>(x); template <int32_t D> inline static Real Degree(Real x) { return Evaluate(degree<D>(), x); } // The input x can be any real number. Range reduction is used to // generate a value y in [-pi/2,pi/2]. If |y| <= pi/4, then the // polynomial is evaluated. If y in (pi/4,pi/2), set z = y - pi/4 // and use the identity // tan(y) = tan(z + pi/4) = [1 + tan(z)]/[1 - tan(z)] // Be careful when evaluating at y nearly pi/2, because tan(y) // becomes infinite. For example, // float x; // x any real number // float result = TanEstimate<float>::DegreeRR<3>(x); template <int32_t D> inline static Real DegreeRR(Real x) { Real y; Reduce(x, y); if (std::fabs(y) <= (Real)GTE_C_QUARTER_PI) { return Degree<D>(y); } else if (y > (Real)GTE_C_QUARTER_PI) { Real poly = Degree<D>(y - (Real)GTE_C_QUARTER_PI); return ((Real)1 + poly) / ((Real)1 - poly); } else { Real poly = Degree<D>(y + (Real)GTE_C_QUARTER_PI); return -((Real)1 - poly) / ((Real)1 + poly); } } private: // Metaprogramming and private implementation to allow specialization // of a template member function. template <int32_t D> struct degree {}; inline static Real Evaluate(degree<3>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_TAN_DEG3_C1; poly = (Real)GTE_C_TAN_DEG3_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<5>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_TAN_DEG5_C2; poly = (Real)GTE_C_TAN_DEG5_C1 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG5_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<7>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_TAN_DEG7_C3; poly = (Real)GTE_C_TAN_DEG7_C2 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG7_C1 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG7_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<9>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_TAN_DEG9_C4; poly = (Real)GTE_C_TAN_DEG9_C3 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG9_C2 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG9_C1 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG9_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<11>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_TAN_DEG11_C5; poly = (Real)GTE_C_TAN_DEG11_C4 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG11_C3 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG11_C2 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG11_C1 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG11_C0 + poly * xsqr; poly = poly * x; return poly; } inline static Real Evaluate(degree<13>, Real x) { Real xsqr = x * x; Real poly; poly = (Real)GTE_C_TAN_DEG13_C6; poly = (Real)GTE_C_TAN_DEG13_C5 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG13_C4 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG13_C3 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG13_C2 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG13_C1 + poly * xsqr; poly = (Real)GTE_C_TAN_DEG13_C0 + poly * xsqr; poly = poly * x; return poly; } // Support for range reduction. inline static void Reduce(Real x, Real& y) { // Map x to y in [-pi,pi], x = pi*quotient + remainder. y = std::fmod(x, (Real)GTE_C_PI); // Map y to [-pi/2,pi/2] with tan(y) = tan(x). if (y > (Real)GTE_C_HALF_PI) { y -= (Real)GTE_C_PI; } else if (y < (Real)-GTE_C_HALF_PI) { y += (Real)GTE_C_PI; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SeparatePoints3.h
.h
8,299
223
// 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/ConvexHull3.h> #include <Mathematics/Hyperplane.h> // Separate two point sets, if possible, by computing a plane for which the // point sets lie on opposite sides. The algorithm computes the convex hull // of the point sets, then uses the method of separating axes to determine // whether the two convex polyhedra are disjoint. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf namespace gte { template <typename Real, typename ComputeType> class SeparatePoints3 { public: // The return value is 'true' if and only if there is a separation. // If 'true', the returned plane is a separating plane. The code // assumes that each point set has at least 4 noncoplanar points. bool operator()(size_t numPoints0, Vector3<Real> const* points0, size_t numPoints1, Vector3<Real> const* points1, Plane3<Real>& separatingPlane) const { // Construct convex hull of point set 0. ConvexHull3<Real> ch0; ch0(numPoints0, points0, 0); if (ch0.GetDimension() != 3) { return false; } // Construct convex hull of point set 1. ConvexHull3<Real> ch1; ch1(numPoints1, points1, 0); if (ch1.GetDimension() != 3) { return false; } auto const& hull0 = ch0.GetHull(); auto const& hull1 = ch1.GetHull(); size_t numTriangles0 = hull0.size() / 3; size_t numTriangles1 = hull1.size() / 3; // Test faces of hull 0 for possible separation of points. size_t i, i0, i1, i2; int32_t side0, side1; Vector3<Real> diff0, diff1; for (i = 0; i < numTriangles0; ++i) { // Look up face (assert: i0 != i1 && i0 != i2 && i1 != i2). i0 = hull0[3 * i]; i1 = hull0[3 * i + 1]; i2 = hull0[3 * i + 2]; // Compute potential separating plane // (assert: normal != (0,0,0)). separatingPlane = Plane3<Real>({ points0[i0], points0[i1], points0[i2] }); // Determine whether hull 1 is on same side of plane. side1 = OnSameSide(separatingPlane, numTriangles1, hull1.data(), points1); if (side1) { // Determine on which side of plane hull 0 lies. side0 = WhichSide(separatingPlane, numTriangles0, hull0.data(), points0); if (side0 * side1 <= 0) // Plane separates hulls. { return true; } } } // Test faces of hull 1 for possible separation of points. for (i = 0; i < numTriangles1; ++i) { // Look up edge (assert: i0 != i1 && i0 != i2 && i1 != i2). i0 = hull1[3 * i]; i1 = hull1[3 * i + 1]; i2 = hull1[3 * i + 2]; // Compute perpendicular to face // (assert: normal != (0,0,0)). separatingPlane = Plane3<Real>({ points1[i0], points1[i1], points1[i2] }); // Determine whether hull 0 is on same side of plane. side0 = OnSameSide(separatingPlane, numTriangles0, hull0.data(), points0); if (side0) { // Determine on which side of plane hull 1 lies. side1 = WhichSide(separatingPlane, numTriangles1, hull1.data(), points1); if (side0 * side1 <= 0) // Plane separates hulls. { return true; } } } // Build edge set for hull 0. std::set<std::pair<size_t, size_t>> edgeSet0; for (i = 0; i < numTriangles0; ++i) { // Look up face (assert: i0 != i1 && i0 != i2 && i1 != i2). i0 = hull0[3 * i]; i1 = hull0[3 * i + 1]; i2 = hull0[3 * i + 2]; edgeSet0.insert(std::make_pair(i0, i1)); edgeSet0.insert(std::make_pair(i0, i2)); edgeSet0.insert(std::make_pair(i1, i2)); } // Build edge list for hull 1. std::set<std::pair<size_t, size_t>> edgeSet1; for (i = 0; i < numTriangles1; ++i) { // Look up face (assert: i0 != i1 && i0 != i2 && i1 != i2). i0 = hull1[3 * i]; i1 = hull1[3 * i + 1]; i2 = hull1[3 * i + 2]; edgeSet1.insert(std::make_pair(i0, i1)); edgeSet1.insert(std::make_pair(i0, i2)); edgeSet1.insert(std::make_pair(i1, i2)); } // Test planes whose normals are cross products of two edges, one // from each hull. for (auto const& e0 : edgeSet0) { // Get edge. diff0 = points0[e0.second] - points0[e0.first]; for (auto const& e1 : edgeSet1) { diff1 = points1[e1.second] - points1[e1.first]; // Compute potential separating plane. separatingPlane.normal = UnitCross(diff0, diff1); separatingPlane.constant = Dot(separatingPlane.normal, points0[e0.first]); // Determine if hull 0 is on same side of plane. side0 = OnSameSide(separatingPlane, numTriangles0, hull0.data(), points0); side1 = OnSameSide(separatingPlane, numTriangles1, hull1.data(), points1); if (side0 * side1 < 0) // Plane separates hulls. { return true; } } } return false; } private: int32_t OnSameSide(Plane3<Real> const& plane, size_t numTriangles, size_t const* indices, Vector3<Real> const* points) const { // Test whether all points on same side of plane Dot(N,X) = c. size_t posSide = 0, negSide = 0; for (size_t t = 0; t < numTriangles; ++t) { for (size_t i = 0; i < 3; ++i) { size_t v = indices[3 * t + i]; Real c0 = Dot(plane.normal, points[v]); if (c0 > plane.constant) { ++posSide; } else if (c0 < plane.constant) { ++negSide; } if (posSide && negSide) { // Plane splits point set. return 0; } } } return (posSide ? +1 : -1); } int32_t WhichSide(Plane3<Real> const& plane, size_t numTriangles, size_t const* indices, Vector3<Real> const* points) const { // Establish which side of plane hull is on. for (size_t t = 0; t < numTriangles; ++t) { for (size_t i = 0; i < 3; ++i) { size_t v = indices[3 * t + i]; Real c0 = Dot(plane.normal, points[v]); if (c0 > plane.constant) { // Positive side. return +1; } if (c0 < plane.constant) { // Negative side. return -1; } } } // Hull is effectively collinear. return 0; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrLine2Arc2.h
.h
2,634
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/IntrLine2Circle2.h> #include <Mathematics/Arc2.h> // The queries consider the arc to be a 1-dimensional object. namespace gte { template <typename T> class TIQuery<T, Line2<T>, Arc2<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Line2<T> const& line, Arc2<T> const& arc) { Result result{}; FIQuery<T, Line2<T>, Arc2<T>> laQuery; auto laResult = laQuery(line, arc); result.intersect = laResult.intersect; return result; } }; template <typename T> class FIQuery<T, Line2<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()(Line2<T> const& line, Arc2<T> const& arc) { Result result{}; FIQuery<T, Line2<T>, Circle2<T>> lcQuery; Circle2<T> circle(arc.center, arc.radius); auto lcResult = lcQuery(line, circle); if (lcResult.intersect) { // Test whether line-circle intersections are on the arc. result.numIntersections = 0; for (int32_t i = 0; i < lcResult.numIntersections; ++i) { if (arc.Contains(lcResult.point[i])) { result.intersect = true; result.parameter[result.numIntersections] = lcResult.parameter[i]; result.point[result.numIntersections] = lcResult.point[i]; ++result.numIntersections; } } } else { result.intersect = false; result.numIntersections = 0; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprPolynomial4.h
.h
11,165
281
// 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/Array2.h> #include <Mathematics/GMatrix.h> #include <array> // The samples are (x[i],y[i],z[i],w[i]) for 0 <= i < S. Think of w as a // function of x, y, and z, say w = f(x,y,z). The function fits the samples // with a polynomial of degree d0 in x, degree d1 in y, and degree d2 in z, // say // w = sum_{i=0}^{d0} sum_{j=0}^{d1} sum_{k=0}^{d2} c[i][j][k]*x^i*y^j*z^k // The method is a least-squares fitting algorithm. The mParameters stores // c[i][j][k] = mParameters[i+(d0+1)*(j+(d1+1)*k)] for a total of // (d0+1)*(d1+1)*(d2+1) coefficients. The observation type is // std::array<Real,4>, which represents a tuple (x,y,z,w). // // WARNING. The fitting algorithm for polynomial terms // (1,x,x^2,...,x^d0), (1,y,y^2,...,y^d1), (1,z,z^2,...,z^d2) // is known to be nonrobust for large degrees and for large magnitude data. // One alternative is to use orthogonal polynomials // (f[0](x),...,f[d0](x)), (g[0](y),...,g[d1](y)), (h[0](z),...,h[d2](z)) // and apply the least-squares algorithm to these. Another alternative is to // transform // (x',y',z',w') = ((x-xcen)/rng, (y-ycen)/rng, (z-zcen)/rng, w/rng) // where xmin = min(x[i]), xmax = max(x[i]), xcen = (xmin+xmax)/2, // ymin = min(y[i]), ymax = max(y[i]), ycen = (ymin+ymax)/2, zmin = min(z[i]), // zmax = max(z[i]), zcen = (zmin+zmax)/2, and // rng = max(xmax-xmin,ymax-ymin,zmax-zmin). Fit the (x',y',z',w') points, // w' = sum_{i=0}^{d0} sum_{j=0}^{d1} sum_{k=0}^{d2} c'[i][j][k] * // (x')^i*(y')^j*(z')^k // The original polynomial is evaluated as // w = rng * sum_{i=0}^{d0} sum_{j=0}^{d1} sum_{k=0}^{d2} c'[i][j][k] * // ((x-xcen)/rng)^i * ((y-ycen)/rng)^j * ((z-zcen)/rng)^k namespace gte { template <typename Real> class ApprPolynomial4 : public ApprQuery<Real, std::array<Real, 4>> { public: // Initialize the model parameters to zero. ApprPolynomial4(int32_t xDegree, int32_t yDegree, int32_t zDegree) : mXDegree(xDegree), mYDegree(yDegree), mZDegree(zDegree), mXDegreeP1(xDegree + 1), mYDegreeP1(yDegree + 1), mZDegreeP1(zDegree + 1), mSize(mXDegreeP1* mYDegreeP1* mZDegreeP1), mParameters(mSize, (Real)0), mYZCoefficient(static_cast<size_t>(mYDegreeP1) * static_cast<size_t>(mZDegreeP1), (Real)0), mZCoefficient(mZDegreeP1, (Real)0) { 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]; } // 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)) { int32_t s, i0, j0, k0, n0, i1, j1, k1, n1; // Compute the powers of x, y, and z. int32_t numSamples = static_cast<int32_t>(numIndices); int32_t twoXDegree = 2 * mXDegree; int32_t twoYDegree = 2 * mYDegree; int32_t twoZDegree = 2 * mZDegree; Array2<Real> xPower(static_cast<size_t>(twoXDegree) + 1, numSamples); Array2<Real> yPower(static_cast<size_t>(twoYDegree) + 1, numSamples); Array2<Real> zPower(static_cast<size_t>(twoZDegree) + 1, numSamples); for (s = 0; s < numSamples; ++s) { Real x = observations[indices[s]][0]; Real y = observations[indices[s]][1]; Real z = observations[indices[s]][2]; mXDomain[0] = std::min(x, mXDomain[0]); mXDomain[1] = std::max(x, mXDomain[1]); mYDomain[0] = std::min(y, mYDomain[0]); mYDomain[1] = std::max(y, mYDomain[1]); mZDomain[0] = std::min(z, mZDomain[0]); mZDomain[1] = std::max(z, mZDomain[1]); xPower[s][0] = (Real)1; for (i0 = 1; i0 <= twoXDegree; ++i0) { xPower[s][i0] = x * xPower[s][i0 - 1]; } yPower[s][0] = (Real)1; for (j0 = 1; j0 <= twoYDegree; ++j0) { yPower[s][j0] = y * yPower[s][j0 - 1]; } zPower[s][0] = (Real)1; for (k0 = 1; k0 <= twoZDegree; ++k0) { zPower[s][k0] = z * zPower[s][k0 - 1]; } } // Matrix A is the Vandermonde matrix and vector B is the // right-hand side of the linear system A*X = B. GMatrix<Real> A(mSize, mSize); GVector<Real> B(mSize); for (k0 = 0; k0 <= mZDegree; ++k0) { for (j0 = 0; j0 <= mYDegree; ++j0) { for (i0 = 0; i0 <= mXDegree; ++i0) { Real sum = (Real)0; n0 = i0 + mXDegreeP1 * (j0 + mYDegreeP1 * k0); for (s = 0; s < numSamples; ++s) { Real w = observations[indices[s]][3]; sum += w * xPower[s][i0] * yPower[s][j0] * zPower[s][k0]; } B[n0] = sum; for (k1 = 0; k1 <= mZDegree; ++k1) { for (j1 = 0; j1 <= mYDegree; ++j1) { for (i1 = 0; i1 <= mXDegree; ++i1) { sum = (Real)0; n1 = i1 + mXDegreeP1 * (j1 + mYDegreeP1 * k1); for (s = 0; s < numSamples; ++s) { sum += xPower[s][i0 + i1] * yPower[s][j0 + j1] * zPower[s][k0 + k1]; } A(n0, n1) = sum; } } } } } } // Solve for the polynomial coefficients. GVector<Real> coefficients = Inverse(A) * B; bool hasNonzero = false; for (int32_t i = 0; i < mSize; ++i) { mParameters[i] = coefficients[i]; if (coefficients[i] != (Real)0) { hasNonzero = true; } } return hasNonzero; } 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 static_cast<size_t>(mSize); } // 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<ApprPolynomial4 const*>(input); if (source) { *this = *source; } } // Evaluate the polynomial. The domain intervals are 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 { int32_t i0, i1, i2; Real w; for (i2 = 0; i2 <= mZDegree; ++i2) { for (i1 = 0; i1 <= mYDegree; ++i1) { i0 = mXDegree; w = mParameters[i0 + static_cast<size_t>(mXDegreeP1) * (i1 + static_cast<size_t>(mYDegreeP1) * i2)]; while (--i0 >= 0) { w = mParameters[i0 + static_cast<size_t>(mXDegreeP1) * (i1 + static_cast<size_t>(mYDegreeP1) * i2)] + w * x; } mYZCoefficient[i1 + static_cast<size_t>(mYDegree) * i2] = w; } } for (i2 = 0; i2 <= mZDegree; ++i2) { i1 = mYDegree; w = mYZCoefficient[i1 + static_cast<size_t>(mYDegreeP1) * i2]; while (--i1 >= 0) { w = mParameters[i1 + static_cast<size_t>(mYDegreeP1) * i2] + w * y; } mZCoefficient[i2] = w; } i2 = mZDegree; w = mZCoefficient[i2]; while (--i2 >= 0) { w = mZCoefficient[i2] + w * z; } return w; } private: int32_t mXDegree, mYDegree, mZDegree; int32_t mXDegreeP1, mYDegreeP1, mZDegreeP1, mSize; std::array<Real, 2> mXDomain, mYDomain, mZDomain; std::vector<Real> mParameters; // These arrays are used by Evaluate() to avoid reallocation of the // 'vector's for each call. The member is mutable because, to the // user, the call to Evaluate does not modify the polynomial. mutable std::vector<Real> mYZCoefficient; mutable std::vector<Real> mZCoefficient; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NURBSSphere.h
.h
20,928
460
// 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/NURBSSurface.h> #include <Mathematics/Vector3.h> #include <functional> // 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. // NURBSEighthSphereDegree4 implements Section 3.1.2 (triangular domain) // NURBSHalfSphereDegree3 implements Section 3.2 (rectangular domain) // NURBSFullSphereDegree3 implements Section 2.3 (rectangular domain) // TODO: The class NURBSSurface currently assumes a rectangular domain. // Once support is added for triangular domains, make that new class a // base class of the sphere-representing NURBS. This will allow sharing // of the NURBS basis functions and evaluation framework. namespace gte { template <typename Real> class NURBSEighthSphereDegree4 { public: // Construction. The eigth sphere is x^2 + y^2 + z^2 = 1 for x >= 0, // y >= 0 and z >= 0. NURBSEighthSphereDegree4() { Real const sqrt2 = std::sqrt((Real)2); Real const sqrt3 = std::sqrt((Real)3); Real const a0 = (sqrt3 - (Real)1) / sqrt3; Real const a1 = (sqrt3 + (Real)1) / ((Real)2 * sqrt3); Real const a2 = (Real)1 - ((Real)5 - sqrt2) * ((Real)7 - sqrt3) / (Real)46; Real const b0 = (Real)4 * sqrt3 * (sqrt3 - (Real)1); Real const b1 = (Real)3 * sqrt2; Real const b2 = (Real)4; Real const b3 = sqrt2 * ((Real)3 + (Real)2 * sqrt2 - sqrt3) / sqrt3; mControls[0][0] = { (Real)0, (Real)0, (Real)1 }; // P004 mControls[0][1] = { (Real)0, a0, (Real)1 }; // P013 mControls[0][2] = { (Real)0, a1, a1 }; // P022 mControls[0][3] = { (Real)0, (Real)1, a0 }; // P031 mControls[0][4] = { (Real)0, (Real)1, (Real)0 }; // P040 mControls[1][0] = { a0, (Real)0, (Real)1 }; // P103 mControls[1][1] = { a2, a2, (Real)1 }; // P112 mControls[1][2] = { a2, (Real)1, a2 }; // P121 mControls[1][3] = { a0, (Real)1, (Real)0 }; // P130 mControls[1][4] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[2][0] = { a1, (Real)0, a1 }; // P202 mControls[2][1] = { (Real)1, a2, a2 }; // P211 mControls[2][2] = { a1, a1, (Real)0 }; // P220 mControls[2][3] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[2][4] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[3][0] = { (Real)1, (Real)0, a0 }; // P301 mControls[3][1] = { (Real)1, a0, (Real)0 }; // P310 mControls[3][2] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[3][3] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[3][4] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[4][0] = { (Real)1, (Real)0, (Real)0 }; // P400 mControls[4][1] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[4][2] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[4][3] = { (Real)0, (Real)0, (Real)0 }; // unused mControls[4][4] = { (Real)0, (Real)0, (Real)0 }; // unused mWeights[0][0] = b0; // w004 mWeights[0][1] = b1; // w013 mWeights[0][2] = b2; // w022 mWeights[0][3] = b1; // w031 mWeights[0][4] = b0; // w040 mWeights[1][0] = b1; // w103 mWeights[1][1] = b3; // w112 mWeights[1][2] = b3; // w121 mWeights[1][3] = b1; // w130 mWeights[1][4] = (Real)0; // unused mWeights[2][0] = b2; // w202 mWeights[2][1] = b3; // w211 mWeights[2][2] = b2; // w220 mWeights[2][3] = (Real)0; // unused mWeights[2][4] = (Real)0; // unused mWeights[3][0] = b1; // w301 mWeights[3][1] = b1; // w310 mWeights[3][2] = (Real)0; // unused mWeights[3][3] = (Real)0; // unused mWeights[3][4] = (Real)0; // unused mWeights[4][0] = b0; // w400 mWeights[4][1] = (Real)0; // unused mWeights[4][2] = (Real)0; // unused mWeights[4][3] = (Real)0; // unused mWeights[4][4] = (Real)0; // unused } // 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. void Evaluate(Real u, Real v, uint32_t maxOrder, Vector<3, Real> values[6]) const { // TODO: Some of the polynomials are used in other polynomials. // Optimize the code by eliminating the redundant computations. Real w = (Real)1 - u - v; Real uu = u * u, uv = u * v, uw = u * w, vv = v * v, vw = v * w, ww = w * w; // Compute the order-0 polynomials. Only the elements to be used // are filled in. The other terms are uninitialized but never // used. Real B[5][5]; B[0][0] = ww * ww; B[0][1] = (Real)4 * vw * ww; B[0][2] = (Real)6 * vv * ww; B[0][3] = (Real)4 * vv * vw; B[0][4] = vv * vv; B[1][0] = (Real)4 * uw * ww; B[1][1] = (Real)12 * uv * ww; B[1][2] = (Real)12 * uv * vw; B[1][3] = (Real)4 * uv * vv; B[2][0] = (Real)6 * uu * ww; B[2][1] = (Real)12 * uu * vw; B[2][2] = (Real)6 * uu * vv; B[3][0] = (Real)4 * uu * uw; B[3][1] = (Real)4 * uu * uv; B[4][0] = uu * uu; // Compute the NURBS position. Vector<3, Real> N{ (Real)0, (Real)0, (Real)0 }; Real D(0); for (int32_t j1 = 0; j1 <= 4; ++j1) { for (int32_t j0 = 0; j0 <= 4 - j1; ++j0) { Real product = mWeights[j1][j0] * B[j1][j0]; N += product * mControls[j1][j0]; D += product; } } values[0] = N / D; if (maxOrder >= 1) { // Compute the order-1 polynomials. Only the elements to be // used are filled in. The other terms are uninitialized but // never used. Real WmU = w - u; Real WmTwoU = WmU - u; Real WmThreeU = WmTwoU - u; Real TwoWmU = w + WmU; Real ThreeWmU = w + TwoWmU; Real WmV = w - v; Real WmTwoV = WmV - v; Real WmThreeV = WmTwoV - v; Real TwoWmV = w + WmV; Real ThreeWmV = w + TwoWmV; Real Dsqr = D * D; Real Bu[5][5]; Bu[0][0] = (Real)-4 * ww * w; Bu[0][1] = (Real)-12 * v * ww; Bu[0][2] = (Real)-12 * vv * w; Bu[0][3] = (Real)-4 * v * vv; Bu[0][4] = (Real)0; Bu[1][0] = (Real)4 * ww * WmThreeU; Bu[1][1] = (Real)12 * vw * WmTwoU; Bu[1][2] = (Real)12 * vv * WmU; Bu[1][3] = (Real)4 * vv; Bu[2][0] = (Real)12 * uw * WmU; Bu[2][1] = (Real)12 * uv * TwoWmU; Bu[2][2] = (Real)12 * u * vv; Bu[3][0] = (Real)4 * uu * ThreeWmU; Bu[3][1] = (Real)12 * uu * v; Bu[4][0] = (Real)4 * uu * u; Real Bv[5][5]; Bv[0][0] = (Real)-4 * ww * w; Bv[0][1] = (Real)4 * ww * WmThreeV; Bv[0][2] = (Real)12 * vw * WmV; Bv[0][3] = (Real)4 * vv * ThreeWmV; Bv[0][4] = (Real)4 * vv * v; Bv[1][0] = (Real)-12 * u * ww; Bv[1][1] = (Real)12 * uw * WmTwoV; Bv[1][2] = (Real)12 * uv * TwoWmV; Bv[1][3] = (Real)12 * u * vv; Bv[2][0] = (Real)-12 * uu * w; Bv[2][1] = (Real)12 * uu * WmV; Bv[2][2] = (Real)12 * uu * v; Bv[3][0] = (Real)-4 * uu * u; Bv[3][1] = (Real)4 * uu * u; Bv[4][0] = (Real)0; Vector<3, Real> Nu{ (Real)0, (Real)0, (Real)0 }; Vector<3, Real> Nv{ (Real)0, (Real)0, (Real)0 }; Real Du(0), Dv(0); for (int32_t j1 = 0; j1 <= 4; ++j1) { for (int32_t j0 = 0; j0 <= 4 - j1; ++j0) { Real product = mWeights[j1][j0] * Bu[j1][j0]; Nu += product * mControls[j1][j0]; Du += product; product = mWeights[j1][j0] * Bv[j1][j0]; Nv += product * mControls[j1][j0]; Dv += product; } } Vector<3, Real> numerDU = D * Nu - Du * N; Vector<3, Real> numerDV = D * Nv - Dv * N; values[1] = numerDU / Dsqr; values[2] = numerDV / Dsqr; if (maxOrder >= 2) { // Compute the order-2 polynomials. Only the elements to // be used are filled in. The other terms are // uninitialized but never used. Real Dcub = Dsqr * D; Real Buu[5][5]; Buu[0][0] = (Real)12 * ww; Buu[0][1] = (Real)24 * vw; Buu[0][2] = (Real)12 * vv; Buu[0][3] = (Real)0; Buu[0][4] = (Real)0; Buu[1][0] = (Real)-24 * w * WmU; Buu[1][1] = (Real)-24 * v * TwoWmU; Buu[1][2] = (Real)-24 * vv; Buu[1][3] = (Real)0; Buu[2][0] = (Real)12 * (ww - (Real)4 * uw + uu); Buu[2][1] = (Real)24 * v * WmTwoU; Buu[2][2] = (Real)12 * vv; Buu[3][0] = (Real)24 * u * WmU; Buu[3][1] = (Real)24 * uv; Buu[4][0] = (Real)12 * uu; Real Buv[5][5]; Buv[0][0] = (Real)12 * ww; Buv[0][1] = (Real)-12 * w * WmTwoV; Buv[0][2] = (Real)-12 * v * TwoWmV; Buv[0][3] = (Real)-12 * vv; Buv[0][4] = (Real)0; Buv[1][0] = (Real)-12 * w * WmTwoU; Buv[1][1] = (Real)12 * (ww + (Real)2 * (uv - uw - vw)); Buv[1][2] = (Real)12 * v * ((Real)2 * WmU - v); Buv[1][3] = (Real)12 * vv; Buv[2][0] = (Real)-12 * u * TwoWmU; Buv[2][1] = (Real)12 * u * ((Real)2 * WmV - u); Buv[2][2] = (Real)24 * uv; Buv[3][0] = (Real)-12 * uu; Buv[3][1] = (Real)12 * uu; Buv[4][0] = (Real)0; Real Bvv[5][5]; Bvv[0][0] = (Real)12 * ww; Bvv[0][1] = (Real)-24 * w * WmV; Bvv[0][2] = (Real)12 * (ww - (Real)4 * vw + vv); Bvv[0][3] = (Real)24 * v * WmV; Bvv[0][4] = (Real)12 * vv; Bvv[1][0] = (Real)24 * uw; Bvv[1][1] = (Real)-24 * u * TwoWmV; Bvv[1][2] = (Real)24 * u * WmTwoV; Bvv[1][3] = (Real)24 * uv; Bvv[2][0] = (Real)12 * uu; Bvv[2][1] = (Real)-24 * uu; Bvv[2][2] = (Real)12 * uu; Bvv[3][0] = (Real)0; Bvv[3][1] = (Real)0; Bvv[4][0] = (Real)0; Vector<3, Real> Nuu{ (Real)0, (Real)0, (Real)0 }; Vector<3, Real> Nuv{ (Real)0, (Real)0, (Real)0 }; Vector<3, Real> Nvv{ (Real)0, (Real)0, (Real)0 }; Real Duu(0), Duv(0), Dvv(0); for (int32_t j1 = 0; j1 <= 4; ++j1) { for (int32_t j0 = 0; j0 <= 4 - j1; ++j0) { Real product = mWeights[j1][j0] * Buu[j1][j0]; Nuu += product * mControls[j1][j0]; Duu += product; product = mWeights[j1][j0] * Buv[j1][j0]; Nuv += product * mControls[j1][j0]; Duv += product; product = mWeights[j1][j0] * Bvv[j1][j0]; Nvv += product * mControls[j1][j0]; Dvv += product; } } Vector<3, Real> termDuu = D * (D * Nuu - Duu * N); Vector<3, Real> termDuv = D * (D * Nuv - Duv * N - Du * Nv - Dv * Nu); Vector<3, Real> termDvv = D * (D * Nvv - Dvv * N); values[3] = (D * termDuu - (Real)2 * Du * numerDU) / Dcub; values[4] = (D * termDuv + (Real)2 * Du * Dv * N) / Dcub; values[5] = (D * termDvv - (Real)2 * Dv * numerDV) / Dcub; } } } private: // For simplicity of the implementation, 2-dimensional arrays // of size 5-by-5 are used. Only array[r][c] is used where // 0 <= r <= 4 and 0 <= c < 4 - r. Vector3<Real> mControls[5][5]; Real mWeights[5][5]; }; template <typename Real> class NURBSHalfSphereDegree3 : public NURBSSurface<3, Real> { public: NURBSHalfSphereDegree3() : NURBSSurface<3, Real>(BasisFunctionInput<Real>(4, 3), BasisFunctionInput<Real>(4, 3), nullptr, nullptr) { // weight[j][i] is mWeights[i + 4 * j], 0 <= i < 4, 0 <= j < 4 Real const oneThird = (Real)1 / (Real)3; Real const oneNinth = (Real)1 / (Real)9; 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] = oneNinth; this->mWeights[6] = oneNinth; this->mWeights[7] = oneThird; this->mWeights[8] = oneThird; this->mWeights[9] = oneNinth; this->mWeights[10] = oneNinth; this->mWeights[11] = oneThird; this->mWeights[12] = (Real)1; this->mWeights[13] = oneThird; this->mWeights[14] = oneThird; this->mWeights[15] = (Real)1; // control[j][i] is mControls[i + 4 * j], 0 <= i < 4, 0 <= j < 4 this->mControls[0] = { (Real)0, (Real)0, (Real)1 }; this->mControls[1] = { (Real)0, (Real)0, (Real)1 }; this->mControls[2] = { (Real)0, (Real)0, (Real)1 }; this->mControls[3] = { (Real)0, (Real)0, (Real)1 }; this->mControls[4] = { (Real)2, (Real)0, (Real)1 }; this->mControls[5] = { (Real)2, (Real)4, (Real)1 }; this->mControls[6] = { (Real)-2, (Real)4, (Real)1 }; this->mControls[7] = { (Real)-2, (Real)0, (Real)1 }; this->mControls[8] = { (Real)2, (Real)0, (Real)-1 }; this->mControls[9] = { (Real)2, (Real)4, (Real)-1 }; this->mControls[10] = { (Real)-2, (Real)4, (Real)-1 }; this->mControls[11] = { (Real)-2, (Real)0, (Real)-1 }; this->mControls[12] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[13] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[14] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[15] = { (Real)0, (Real)0, (Real)-1 }; } }; template <typename Real> class NURBSFullSphereDegree3 : public NURBSSurface<3, Real> { public: NURBSFullSphereDegree3() : NURBSSurface<3, Real>(BasisFunctionInput<Real>(4, 3), CreateBasisFunctionInputV(), nullptr, nullptr) { // weight[j][i] is mWeights[i + 4 * j], 0 <= i < 4, 0 <= j < 7 Real const oneThird = (Real)1 / (Real)3; Real const oneNinth = (Real)1 / (Real)9; this->mWeights[0] = (Real)1; this->mWeights[4] = oneThird; this->mWeights[8] = oneThird; this->mWeights[12] = (Real)1; this->mWeights[16] = oneThird; this->mWeights[20] = oneThird; this->mWeights[24] = (Real)1; this->mWeights[1] = oneThird; this->mWeights[5] = oneNinth; this->mWeights[9] = oneNinth; this->mWeights[13] = oneThird; this->mWeights[17] = oneNinth; this->mWeights[21] = oneNinth; this->mWeights[25] = oneThird; this->mWeights[2] = oneThird; this->mWeights[6] = oneNinth; this->mWeights[10] = oneNinth; this->mWeights[14] = oneThird; this->mWeights[18] = oneNinth; this->mWeights[22] = oneNinth; this->mWeights[26] = oneThird; this->mWeights[3] = (Real)1; this->mWeights[7] = oneThird; this->mWeights[11] = oneThird; this->mWeights[15] = (Real)1; this->mWeights[19] = oneThird; this->mWeights[23] = oneThird; this->mWeights[27] = (Real)1; // control[j][i] is mControls[i + 4 * j], 0 <= i < 4, 0 <= j < 7 this->mControls[0] = { (Real)0, (Real)0, (Real)1 }; this->mControls[4] = { (Real)0, (Real)0, (Real)1 }; this->mControls[8] = { (Real)0, (Real)0, (Real)1 }; this->mControls[12] = { (Real)0, (Real)0, (Real)1 }; this->mControls[16] = { (Real)0, (Real)0, (Real)1 }; this->mControls[20] = { (Real)0, (Real)0, (Real)1 }; this->mControls[24] = { (Real)0, (Real)0, (Real)1 }; this->mControls[1] = { (Real)2, (Real)0, (Real)1 }; this->mControls[5] = { (Real)2, (Real)4, (Real)1 }; this->mControls[9] = { (Real)-2, (Real)4, (Real)1 }; this->mControls[13] = { (Real)-2, (Real)0, (Real)1 }; this->mControls[17] = { (Real)-2, (Real)-4, (Real)1 }; this->mControls[21] = { (Real)2, (Real)-4, (Real)1 }; this->mControls[25] = { (Real)2, (Real)0, (Real)1 }; this->mControls[2] = { (Real)2, (Real)0, (Real)-1 }; this->mControls[6] = { (Real)2, (Real)4, (Real)-1 }; this->mControls[10] = { (Real)-2, (Real)4, (Real)-1 }; this->mControls[14] = { (Real)-2, (Real)0, (Real)-1 }; this->mControls[18] = { (Real)-2, (Real)-4, (Real)-1 }; this->mControls[22] = { (Real)2, (Real)-4, (Real)-1 }; this->mControls[26] = { (Real)2, (Real)0, (Real)-1 }; this->mControls[3] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[7] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[11] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[15] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[19] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[23] = { (Real)0, (Real)0, (Real)-1 }; this->mControls[27] = { (Real)0, (Real)0, (Real)-1 }; } private: static BasisFunctionInput<Real> CreateBasisFunctionInputV() { 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/AdaptiveSkeletonClimbing3.h
.h
100,234
2,897
// 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/Array2.h> #include <Mathematics/Math.h> #include <Mathematics/TriangleKey.h> #include <map> #include <memory> #include <ostream> #include <set> // Extract level surfaces using an adaptive approach to reduce the triangle // count. The implementation is for the algorithm described in the paper // Multiresolution Isosurface Extraction with Adaptive Skeleton Climbing // Tim Poston, Tien-Tsin Wong and Pheng-Ann Heng // Computer Graphics forum, volume 17, issue 3, September 1998 // pages 137-147 // https://onlinelibrary.wiley.com/doi/abs/10.1111/1467-8659.00261 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 AdaptiveSkeletonClimbing3 { public: // Construction and destruction. The input image is assumed to // contain (2^N+1)-by-(2^N+1)-by-(2^N+1) elements where N >= 0. // The organization is lexicographic order for (x,y,z). When // 'fixBoundary' is set to 'true', image boundary voxels are not // allowed to merge with any other voxels. This forces highest // level of detail on the boundary. The idea is that an image too // large to process by itself can be partitioned into smaller // subimages and the adaptive skeleton climbing applied to each // subimage. By forcing highest resolution on the boundary, // adjacent subimages will not have any cracking problems. AdaptiveSkeletonClimbing3(int32_t N, T const* inputVoxels, bool fixBoundary = false) : mTwoPowerN(1 << N), mSize(mTwoPowerN + 1), mSizeSqr(mSize * mSize), mInputVoxels(inputVoxels), mLevel((Real)0), mFixBoundary(fixBoundary), mXMerge(mSize, mSize), mYMerge(mSize, mSize), mZMerge(mSize, mSize) { static_assert(std::is_integral<T>::value && sizeof(T) <= 4, "Type T must be int{8,16,32}_t or uint{8,16,32}_t."); if (N <= 0 || mInputVoxels == nullptr) { LogError("Invalid input."); } for (int32_t i = 0; i < mSize; ++i) { for (int32_t j = 0; j < mSize; ++j) { mXMerge[i][j] = std::make_shared<LinearMergeTree>(N); mYMerge[i][j] = std::make_shared<LinearMergeTree>(N); mZMerge[i][j] = std::make_shared<LinearMergeTree>(N); } } } // TODO: Refactor this class to have base class SurfaceExtractor. typedef std::array<Real, 3> Vertex; typedef std::array<int32_t, 2> Edge; typedef TriangleKey<true> Triangle; void Extract(Real level, int32_t depth, std::vector<Vertex>& vertices, std::vector<Triangle>& triangles) { std::vector<Vertex> localVertices; std::vector<Triangle> localTriangles; mBoxes.clear(); mLevel = level; Merge(depth); Tessellate(localVertices, localTriangles); vertices = std::move(localVertices); triangles = std::move(localTriangles); } 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; } } void OrientTriangles(std::vector<Vertex>& 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]); } } } } void ComputeNormals(std::vector<Vertex> 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; } } } } // Support for debugging. void PrintBoxes(std::ostream& output) { output << mBoxes.size() << std::endl; for (size_t i = 0; i < mBoxes.size(); ++i) { OctBox const& box = mBoxes[i]; output << "box " << i << ": "; output << "x0 = " << box.x0 << ", "; output << "y0 = " << box.y0 << ", "; output << "z0 = " << box.z0 << ", "; output << "dx = " << box.dx << ", "; output << "dy = " << box.dy << ", "; output << "dz = " << box.dz << std::endl; } } private: // Helper classes for the skeleton climbing. struct OctBox { OctBox(int32_t inX0, int32_t inY0, int32_t inZ0, int32_t inDX, int32_t inDY, int32_t inDZ, int32_t inLX, int32_t inLY, int32_t inLZ) : x0(inX0), y0(inY0), z0(inZ0), x1(inX0 + inDX), y1(inY0 + inDY), z1(inZ0 + inDZ), dx(inDX), dy(inDY), dz(inDZ), LX(inLX), LY(inLY), LZ(inLZ) { } int32_t x0, y0, z0, x1, y1, z1, dx, dy, dz, LX, LY, LZ; }; struct MergeBox { MergeBox(int32_t stride) : xStride(stride), yStride(stride), zStride(stride), valid(true) { } int32_t xStride, yStride, zStride; bool valid; }; class LinearMergeTree { public: LinearMergeTree(int32_t N) : mTwoPowerN(1 << N), mNodes(2 * static_cast<size_t>(mTwoPowerN) - 1), mZeroBases(2 * static_cast<size_t>(mTwoPowerN) - 1) { } enum { CFG_NONE = 0, CFG_INCR = 1, CFG_DECR = 2, CFG_MULT = 3, CFG_ROOT_MASK = 3, CFG_EDGE = 4, CFG_ZERO_SUBEDGE = 8 }; bool IsNone(int32_t i) const { return (mNodes[i] & CFG_ROOT_MASK) == CFG_NONE; } int32_t GetRootType(int32_t i) const { return mNodes[i] & CFG_ROOT_MASK; } int32_t GetZeroBase(int32_t i) const { return mZeroBases[i]; } void SetEdge(int32_t i) { mNodes[i] |= CFG_EDGE; // Inform all predecessors whether they have a zero subedge. if (mZeroBases[i] >= 0) { while (i > 0) { i = (i - 1) / 2; mNodes[i] |= CFG_ZERO_SUBEDGE; } } } bool IsZeroEdge(int32_t i) const { return mNodes[i] == (CFG_EDGE | CFG_INCR) || mNodes[i] == (CFG_EDGE | CFG_DECR); } bool HasZeroSubedge(int32_t i) const { return (mNodes[i] & CFG_ZERO_SUBEDGE) != 0; } void SetLevel(Real level, T const* data, int32_t offset, int32_t stride) { // Assert: The 'level' is not an image value. Because T is // an integer type, choose 'level' to be a Real-valued number // that does not represent an integer. // Determine the sign changes between pairs of consecutive // samples. int32_t firstLeaf = mTwoPowerN - 1; for (int32_t i = 0, leaf = firstLeaf; i < mTwoPowerN; ++i, ++leaf) { int32_t base = offset + stride * i; Real value0 = static_cast<Real>(data[base]); Real value1 = static_cast<Real>(data[base + stride]); if (value0 > level) { if (value1 > level) { mNodes[leaf] = CFG_NONE; mZeroBases[leaf] = -1; } else { mNodes[leaf] = CFG_DECR; mZeroBases[leaf] = i; } } else // value0 < level { if (value1 > level) { mNodes[leaf] = CFG_INCR; mZeroBases[leaf] = i; } else { mNodes[leaf] = CFG_NONE; mZeroBases[leaf] = -1; } } } // Propagate the sign change information up the binary tree. for (int32_t i = firstLeaf - 1; i >= 0; --i) { int32_t twoIp1 = 2 * i + 1, twoIp2 = twoIp1 + 1; int32_t value0 = mNodes[twoIp1]; int32_t value1 = mNodes[twoIp2]; int32_t combine = (value0 | value1); mNodes[i] = combine; if (combine == CFG_INCR) { if (value0 == CFG_INCR) { mZeroBases[i] = mZeroBases[twoIp1]; } else { mZeroBases[i] = mZeroBases[twoIp2]; } } else if (combine == CFG_DECR) { if (value0 == CFG_DECR) { mZeroBases[i] = mZeroBases[twoIp1]; } else { mZeroBases[i] = mZeroBases[twoIp2]; } } else { mZeroBases[i] = -1; } } } private: int32_t mTwoPowerN; std::vector<int32_t> mNodes; std::vector<int32_t> mZeroBases; }; class VETable { public: VETable() : mVertices(18) { } bool IsValidVertex(int32_t i) const { return mVertices[i].valid; } int32_t GetNumVertices() const { return static_cast<int32_t>(mVertices.size()); } Vertex const& GetVertex(int32_t i) const { return mVertices[i].position; } void Insert(int32_t i, Real x, Real y, Real z) { TVertex& vertex = mVertices[i]; vertex.position = Vertex{ x, y, z }; vertex.valid = true; } void Insert(Vertex const& position) { mVertices.push_back(TVertex(position)); } void InsertEdge(int32_t v0, int32_t v1) { TVertex& vertex0 = mVertices[v0]; TVertex& vertex1 = mVertices[v1]; vertex0.adjacent[vertex0.adjQuantity] = v1; ++vertex0.adjQuantity; vertex1.adjacent[vertex1.adjQuantity] = v0; ++vertex1.adjQuantity; } void RemoveTrianglesEC(std::vector<Vertex>& positions, std::vector<Triangle>& triangles) { // Ear-clip the wireframe to get the triangles. Triangle triangle; while (RemoveEC(triangle)) { int32_t v0 = static_cast<int32_t>(positions.size()); int32_t v1 = v0 + 1; int32_t v2 = v1 + 1; // Bypassing the constructor to avoid a warning in the // release build by gcc 7.5.0 on Ubuntu 18.04.5 LTS: // "assuming signed overflow does not occur when assuming // that (X + c) >= X is always true." The correct // constructor case is used because v0 < v1 < v2. Triangle tkey; tkey.V[0] = v0; tkey.V[1] = v1; tkey.V[2] = v2; triangles.push_back(tkey); positions.push_back(mVertices[triangle.V[0]].position); positions.push_back(mVertices[triangle.V[1]].position); positions.push_back(mVertices[triangle.V[2]].position); } } void RemoveTrianglesSE(std::vector<Vertex>& positions, std::vector<Triangle>& triangles) { // Compute centroid of vertices. Vertex centroid = { (Real)0, (Real)0, (Real)0 }; int32_t const vmax = static_cast<int32_t>(mVertices.size()); int32_t i, j, quantity = 0; for (i = 0; i < vmax; i++) { TVertex const& vertex = mVertices[i]; if (vertex.valid) { for (j = 0; j < 3; ++j) { centroid[j] += vertex.position[j]; } ++quantity; } } for (j = 0; j < 3; ++j) { centroid[j] /= static_cast<Real>(quantity); } int32_t v0 = static_cast<int32_t>(positions.size()); positions.push_back(centroid); int32_t i1 = 18; int32_t v1 = v0 + 1; positions.push_back(mVertices[i1].position); int32_t i2 = mVertices[i1].adjacent[1], v2; for (i = 0; i < quantity - 1; ++i) { v2 = v1 + 1; positions.push_back(mVertices[i2].position); // Bypassing the constructor to avoid a warning in the // release build by gcc 7.5.0 on Ubuntu 18.04.5 LTS: // "assuming signed overflow does not occur when assuming // that (X + c) >= X is always true." The correct // constructor case is used because v0 < v1 < v2. Triangle tkey; tkey.V[0] = v0; tkey.V[1] = v1; tkey.V[2] = v2; triangles.push_back(tkey); if (mVertices[i2].adjacent[1] != i1) { i1 = i2; i2 = mVertices[i2].adjacent[1]; } else { i1 = i2; i2 = mVertices[i2].adjacent[0]; } v1 = v2; } v2 = v0 + 1; // Unlike the previous two constructor calls, it is not // guaranteed that v0 < v1. triangles.push_back(Triangle(v0, v1, v2)); } protected: void RemoveVertex(int32_t i) { TVertex& vertex0 = mVertices[i]; int32_t a0 = vertex0.adjacent[0]; int32_t a1 = vertex0.adjacent[1]; TVertex& adjVertex0 = mVertices[a0]; TVertex& adjVertex1 = mVertices[a1]; int32_t j; for (j = 0; j < adjVertex0.adjQuantity; j++) { if (adjVertex0.adjacent[j] == i) { adjVertex0.adjacent[j] = a1; break; } } for (j = 0; j < adjVertex1.adjQuantity; j++) { if (adjVertex1.adjacent[j] == i) { adjVertex1.adjacent[j] = a0; break; } } vertex0.valid = false; if (adjVertex0.adjQuantity == 2) { if (adjVertex0.adjacent[0] == adjVertex0.adjacent[1]) { adjVertex0.valid = false; } } if (adjVertex1.adjQuantity == 2) { if (adjVertex1.adjacent[0] == adjVertex1.adjacent[1]) { adjVertex1.valid = false; } } } // ear clipping bool RemoveEC(Triangle& triangle) { int32_t numVertices = static_cast<int32_t>(mVertices.size()); for (int32_t i = 0; i < numVertices; ++i) { TVertex const& vertex = mVertices[i]; if (vertex.valid && vertex.adjQuantity == 2) { triangle.V[0] = i; triangle.V[1] = vertex.adjacent[0]; triangle.V[2] = vertex.adjacent[1]; RemoveVertex(i); return true; } } return false; } class TVertex { public: TVertex() : position{ (Real)0, (Real)0, (Real)0 }, adjQuantity(0), adjacent{ 0, 0, 0, 0 }, valid(false) { } TVertex(Vertex const& inPosition) : position(inPosition), adjQuantity(0), adjacent{ 0, 0, 0, 0 }, valid(true) { } Vertex position; int32_t adjQuantity; std::array<int32_t, 4> adjacent; bool valid; }; std::vector<TVertex> mVertices; }; private: // Support for merging monoboxes. void Merge(int32_t depth) { int32_t x, y, z, offset, stride; for (y = 0; y < mSize; ++y) { for (z = 0; z < mSize; ++z) { offset = mSize * (y + mSize * z); stride = 1; mXMerge[y][z]->SetLevel(mLevel, mInputVoxels, offset, stride); } } for (x = 0; x < mSize; ++x) { for (z = 0; z < mSize; ++z) { offset = x + mSizeSqr * z; stride = mSize; mYMerge[x][z]->SetLevel(mLevel, mInputVoxels, offset, stride); } } for (x = 0; x < mSize; ++x) { for (y = 0; y < mSize; ++y) { offset = x + mSize * y; stride = mSizeSqr; mZMerge[x][y]->SetLevel(mLevel, mInputVoxels, offset, stride); } } Merge(0, 0, 0, 0, 0, 0, 0, mTwoPowerN, depth); } bool Merge(int32_t v, int32_t LX, int32_t LY, int32_t LZ, int32_t x0, int32_t y0, int32_t z0, int32_t stride, int32_t depth) { if (stride > 1) // internal nodes { int32_t hStride = stride / 2; int32_t vBase = 8 * v; int32_t v000 = vBase + 1; int32_t v100 = vBase + 2; int32_t v010 = vBase + 3; int32_t v110 = vBase + 4; int32_t v001 = vBase + 5; int32_t v101 = vBase + 6; int32_t v011 = vBase + 7; int32_t v111 = vBase + 8; int32_t LX0 = 2 * LX + 1, LX1 = LX0 + 1; int32_t LY0 = 2 * LY + 1, LY1 = LY0 + 1; int32_t LZ0 = 2 * LZ + 1, LZ1 = LZ0 + 1; int32_t x1 = x0 + hStride, y1 = y0 + hStride, z1 = z0 + hStride; int32_t dm1 = depth - 1; bool m000 = Merge(v000, LX0, LY0, LZ0, x0, y0, z0, hStride, dm1); bool m100 = Merge(v100, LX1, LY0, LZ0, x1, y0, z0, hStride, dm1); bool m010 = Merge(v010, LX0, LY1, LZ0, x0, y1, z0, hStride, dm1); bool m110 = Merge(v110, LX1, LY1, LZ0, x1, y1, z0, hStride, dm1); bool m001 = Merge(v001, LX0, LY0, LZ1, x0, y0, z1, hStride, dm1); bool m101 = Merge(v101, LX1, LY0, LZ1, x1, y0, z1, hStride, dm1); bool m011 = Merge(v011, LX0, LY1, LZ1, x0, y1, z1, hStride, dm1); bool m111 = Merge(v111, LX1, LY1, LZ1, x1, y1, z1, hStride, dm1); MergeBox r000(hStride), r100(hStride), r010(hStride), r110(hStride); MergeBox r001(hStride), r101(hStride), r011(hStride), r111(hStride); if (depth <= 0) { if (m000 && m001) { DoZMerge(r000, r001, x0, y0, LZ); } if (m100 && m101) { DoZMerge(r100, r101, x1, y0, LZ); } if (m010 && m011) { DoZMerge(r010, r011, x0, y1, LZ); } if (m110 && m111) { DoZMerge(r110, r111, x1, y1, LZ); } if (m000 && m010) { DoYMerge(r000, r010, x0, LY, z0); } if (m100 && m110) { DoYMerge(r100, r110, x1, LY, z0); } if (m001 && m011) { DoYMerge(r001, r011, x0, LY, z1); } if (m101 && m111) { DoYMerge(r101, r111, x1, LY, z1); } if (m000 && m100) { DoXMerge(r000, r100, LX, y0, z0); } if (m010 && m110) { DoXMerge(r010, r110, LX, y1, z0); } if (m001 && m101) { DoXMerge(r001, r101, LX, y0, z1); } if (m011 && m111) { DoXMerge(r011, r111, LX, y1, z1); } } if (depth <= 1) { if (r000.valid) { if (r000.xStride == stride) { if (r000.yStride == stride) { if (r000.zStride == stride) { return true; } else { AddBox(x0, y0, z0, stride, stride, hStride, LX, LY, LZ0); } } else { if (r000.zStride == stride) { AddBox(x0, y0, z0, stride, hStride, stride, LX, LY0, LZ); } else { AddBox(x0, y0, z0, stride, hStride, hStride, LX, LY0, LZ0); } } } else { if (r000.yStride == stride) { if (r000.zStride == stride) { AddBox(x0, y0, z0, hStride, stride, stride, LX0, LY, LZ); } else { AddBox(x0, y0, z0, hStride, stride, hStride, LX0, LY, LZ0); } } else { if (r000.zStride == stride) { AddBox(x0, y0, z0, hStride, hStride, stride, LX0, LY0, LZ); } else if (m000) { AddBox(x0, y0, z0, hStride, hStride, hStride, LX0, LY0, LZ0); } } } } if (r100.valid) { if (r100.yStride == stride) { if (r100.zStride == stride) { AddBox(x1, y0, z0, hStride, stride, stride, LX1, LY, LZ); } else { AddBox(x1, y0, z0, hStride, stride, hStride, LX1, LY, LZ0); } } else { if (r100.zStride == stride) { AddBox(x1, y0, z0, hStride, hStride, stride, LX1, LY0, LZ); } else if (m100) { AddBox(x1, y0, z0, hStride, hStride, hStride, LX1, LY0, LZ0); } } } if (r010.valid) { if (r010.xStride == stride) { if (r010.zStride == stride) { AddBox(x0, y1, z0, stride, hStride, stride, LX, LY1, LZ); } else { AddBox(x0, y1, z0, stride, hStride, hStride, LX, LY1, LZ0); } } else { if (r010.zStride == stride) { AddBox(x0, y1, z0, hStride, hStride, stride, LX0, LY1, LZ); } else if (m010) { AddBox(x0, y1, z0, hStride, hStride, hStride, LX0, LY1, LZ0); } } } if (r001.valid) { if (r001.xStride == stride) { if (r001.yStride == stride) { AddBox(x0, y0, z1, stride, stride, hStride, LX, LY, LZ1); } else { AddBox(x0, y0, z1, stride, hStride, hStride, LX, LY0, LZ1); } } else { if (r001.yStride == stride) { AddBox(x0, y0, z1, hStride, stride, hStride, LX0, LY, LZ1); } else if (m001) { AddBox(x0, y0, z1, hStride, hStride, hStride, LX0, LY0, LZ1); } } } if (r110.valid) { if (r110.zStride == stride) { AddBox(x1, y1, z0, hStride, hStride, stride, LX1, LY1, LZ); } else if (m110) { AddBox(x1, y1, z0, hStride, hStride, hStride, LX1, LY1, LZ0); } } if (r101.valid) { if (r101.yStride == stride) { AddBox(x1, y0, z1, hStride, stride, hStride, LX1, LY, LZ1); } else if (m101) { AddBox(x1, y0, z1, hStride, hStride, hStride, LX1, LY0, LZ1); } } if (r011.valid) { if (r011.xStride == stride) { AddBox(x0, y1, z1, stride, hStride, hStride, LX, LY1, LZ1); } else if (m011) { AddBox(x0, y1, z1, hStride, hStride, hStride, LX0, LY1, LZ1); } } if (r111.valid && m111) { AddBox(x1, y1, z1, hStride, hStride, hStride, LX1, LY1, LZ1); } } return false; } else // leaf nodes { if (mFixBoundary) { // Do not allow boundary voxels to merge with any other // voxels. AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } // A leaf box is mergeable with neighbors as long as all its // faces have 0 or 2 sign changes on the edges. That is, a // face may not have sign changes on all four edges. If it // does, the resulting box for tessellating is 1x1x1 and is // handled separately from boxes of larger dimensions. // xmin face int32_t z1 = z0 + 1; int32_t rt0 = mYMerge[x0][z0]->GetRootType(LY); int32_t rt1 = mYMerge[x0][z1]->GetRootType(LY); if ((rt0 | rt1) == LinearMergeTree::CFG_MULT) { AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } // xmax face int32_t x1 = x0 + 1; rt0 = mYMerge[x1][z0]->GetRootType(LY); rt1 = mYMerge[x1][z1]->GetRootType(LY); if ((rt0 | rt1) == LinearMergeTree::CFG_MULT) { AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } // ymin face rt0 = mZMerge[x0][y0]->GetRootType(LZ); rt1 = mZMerge[x1][y0]->GetRootType(LZ); if ((rt0 | rt1) == LinearMergeTree::CFG_MULT) { AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } // ymax face int32_t y1 = y0 + 1; rt0 = mZMerge[x0][y1]->GetRootType(LZ); rt1 = mZMerge[x1][y1]->GetRootType(LZ); if ((rt0 | rt1) == LinearMergeTree::CFG_MULT) { AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } // zmin face rt0 = mXMerge[y0][z0]->GetRootType(LX); rt1 = mXMerge[y1][z0]->GetRootType(LX); if ((rt0 | rt1) == LinearMergeTree::CFG_MULT) { AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } // zmax face rt0 = mXMerge[y0][z1]->GetRootType(LX); rt1 = mXMerge[y1][z1]->GetRootType(LX); if ((rt0 | rt1) == LinearMergeTree::CFG_MULT) { AddBox(x0, y0, z0, 1, 1, 1, LX, LY, LZ); return false; } return true; } } bool DoXMerge(MergeBox& r0, MergeBox& r1, int32_t LX, int32_t y0, int32_t z0) { if (!r0.valid || !r1.valid || r0.yStride != r1.yStride || r0.zStride != r1.zStride) { return false; } // Boxes are potentially x-mergeable. int32_t y1 = y0 + r0.yStride, z1 = z0 + r0.zStride; int32_t incr = 0, decr = 0; for (int32_t y = y0; y <= y1; ++y) { for (int32_t z = z0; z <= z1; ++z) { switch (mXMerge[y][z]->GetRootType(LX)) { case LinearMergeTree::CFG_MULT: return false; case LinearMergeTree::CFG_INCR: ++incr; break; case LinearMergeTree::CFG_DECR: ++decr; break; } } } if (incr != 0 && decr != 0) { return false; } // Strongly mono, x-merge the boxes. r0.xStride *= 2; r1.valid = false; return true; } bool DoYMerge(MergeBox& r0, MergeBox& r1, int32_t x0, int32_t LY, int32_t z0) { if (!r0.valid || !r1.valid || r0.xStride != r1.xStride || r0.zStride != r1.zStride) { return false; } // Boxes are potentially y-mergeable. int32_t x1 = x0 + r0.xStride, z1 = z0 + r0.zStride; int32_t incr = 0, decr = 0; for (int32_t x = x0; x <= x1; ++x) { for (int32_t z = z0; z <= z1; ++z) { switch (mYMerge[x][z]->GetRootType(LY)) { case LinearMergeTree::CFG_MULT: return false; case LinearMergeTree::CFG_INCR: ++incr; break; case LinearMergeTree::CFG_DECR: ++decr; break; } } } if (incr != 0 && decr != 0) { return false; } // Strongly mono, y-merge the boxes. r0.yStride *= 2; r1.valid = false; return true; } bool DoZMerge(MergeBox& r0, MergeBox& r1, int32_t x0, int32_t y0, int32_t LZ) { if (!r0.valid || !r1.valid || r0.xStride != r1.xStride || r0.yStride != r1.yStride) { return false; } // Boxes are potentially z-mergeable. int32_t x1 = x0 + r0.xStride, y1 = y0 + r0.yStride; int32_t incr = 0, decr = 0; for (int32_t x = x0; x <= x1; ++x) { for (int32_t y = y0; y <= y1; ++y) { switch (mZMerge[x][y]->GetRootType(LZ)) { case LinearMergeTree::CFG_MULT: return false; case LinearMergeTree::CFG_INCR: ++incr; break; case LinearMergeTree::CFG_DECR: ++decr; break; } } } if (incr != 0 && decr != 0) { return false; } // Strongly mono, z-merge the boxes. r0.zStride *= 2; r1.valid = false; return true; } void AddBox(int32_t x0, int32_t y0, int32_t z0, int32_t dx, int32_t dy, int32_t dz, int32_t LX, int32_t LY, int32_t LZ) { OctBox box(x0, y0, z0, dx, dy, dz, LX, LY, LZ); mBoxes.push_back(box); // Mark box edges in linear merge trees. This information will be // used later for extraction. mXMerge[box.y0][box.z0]->SetEdge(box.LX); mXMerge[box.y0][box.z1]->SetEdge(box.LX); mXMerge[box.y1][box.z0]->SetEdge(box.LX); mXMerge[box.y1][box.z1]->SetEdge(box.LX); mYMerge[box.x0][box.z0]->SetEdge(box.LY); mYMerge[box.x0][box.z1]->SetEdge(box.LY); mYMerge[box.x1][box.z0]->SetEdge(box.LY); mYMerge[box.x1][box.z1]->SetEdge(box.LY); mZMerge[box.x0][box.y0]->SetEdge(box.LZ); mZMerge[box.x0][box.y1]->SetEdge(box.LZ); mZMerge[box.x1][box.y0]->SetEdge(box.LZ); mZMerge[box.x1][box.y1]->SetEdge(box.LZ); } // Support for tessellating monoboxes. void Tessellate(std::vector<Vertex>& positions, std::vector<Triangle>& triangles) { for (size_t i = 0; i < mBoxes.size(); ++i) { OctBox const& box = mBoxes[i]; // Get vertices on edges of box. VETable table; uint32_t type; GetVertices(box, type, table); if (type == 0) { continue; } // Add wireframe edges to table, add face-vertices if // necessary. if (box.dx > 1 || box.dy > 1 || box.dz > 1) { // Box is larger than voxel, each face has at most one // edge. GetXMinEdgesM(box, type, table); GetXMaxEdgesM(box, type, table); GetYMinEdgesM(box, type, table); GetYMaxEdgesM(box, type, table); GetZMinEdgesM(box, type, table); GetZMaxEdgesM(box, type, table); if (table.GetNumVertices() > 18) { table.RemoveTrianglesSE(positions, triangles); } else { table.RemoveTrianglesEC(positions, triangles); } } else { // The box is a 1x1x1 voxel. Do the full edge analysis // but no splitting is required. GetXMinEdgesS(box, type, table); GetXMaxEdgesS(box, type, table); GetYMinEdgesS(box, type, table); GetYMaxEdgesS(box, type, table); GetZMinEdgesS(box, type, table); GetZMaxEdgesS(box, type, table); table.RemoveTrianglesEC(positions, triangles); } } } Real GetXInterp(int32_t x, int32_t y, int32_t z) const { int32_t index = x + mSize * (y + mSize * z); Real f0 = static_cast<Real>(mInputVoxels[index]); ++index; Real f1 = static_cast<Real>(mInputVoxels[index]); return static_cast<Real>(x) + (mLevel - f0) / (f1 - f0); } Real GetYInterp(int32_t x, int32_t y, int32_t z) const { int32_t index = x + mSize * (y + mSize * z); Real f0 = static_cast<Real>(mInputVoxels[index]); index += mSize; Real f1 = static_cast<Real>(mInputVoxels[index]); return static_cast<Real>(y) + (mLevel - f0) / (f1 - f0); } Real GetZInterp(int32_t x, int32_t y, int32_t z) const { int32_t index = x + mSize * (y + mSize * z); Real f0 = static_cast<Real>(mInputVoxels[index]); index += mSizeSqr; Real f1 = static_cast<Real>(mInputVoxels[index]); return static_cast<Real>(z) + (mLevel - f0) / (f1 - f0); } void GetVertices(OctBox const& box, uint32_t& type, VETable& table) { int32_t root; type = 0; // xmin-ymin edge root = mZMerge[box.x0][box.y0]->GetZeroBase(box.LZ); if (root != -1) { type |= EB_XMIN_YMIN; table.Insert(EI_XMIN_YMIN, static_cast<float>(box.x0), static_cast<float>(box.y0), GetZInterp(box.x0, box.y0, root)); } // xmin-ymax edge root = mZMerge[box.x0][box.y1]->GetZeroBase(box.LZ); if (root != -1) { type |= EB_XMIN_YMAX; table.Insert(EI_XMIN_YMAX, static_cast<float>(box.x0), static_cast<float>(box.y1), GetZInterp(box.x0, box.y1, root)); } // xmax-ymin edge root = mZMerge[box.x1][box.y0]->GetZeroBase(box.LZ); if (root != -1) { type |= EB_XMAX_YMIN; table.Insert(EI_XMAX_YMIN, static_cast<float>(box.x1), static_cast<float>(box.y0), GetZInterp(box.x1, box.y0, root)); } // xmax-ymax edge root = mZMerge[box.x1][box.y1]->GetZeroBase(box.LZ); if (root != -1) { type |= EB_XMAX_YMAX; table.Insert(EI_XMAX_YMAX, static_cast<float>(box.x1), static_cast<float>(box.y1), GetZInterp(box.x1, box.y1, root)); } // xmin-zmin edge root = mYMerge[box.x0][box.z0]->GetZeroBase(box.LY); if (root != -1) { type |= EB_XMIN_ZMIN; table.Insert(EI_XMIN_ZMIN, static_cast<float>(box.x0), GetYInterp(box.x0, root, box.z0), static_cast<float>(box.z0)); } // xmin-zmax edge root = mYMerge[box.x0][box.z1]->GetZeroBase(box.LY); if (root != -1) { type |= EB_XMIN_ZMAX; table.Insert(EI_XMIN_ZMAX, static_cast<float>(box.x0), GetYInterp(box.x0, root, box.z1), static_cast<float>(box.z1)); } // xmax-zmin edge root = mYMerge[box.x1][box.z0]->GetZeroBase(box.LY); if (root != -1) { type |= EB_XMAX_ZMIN; table.Insert(EI_XMAX_ZMIN, static_cast<float>(box.x1), GetYInterp(box.x1, root, box.z0), static_cast<float>(box.z0)); } // xmax-zmax edge root = mYMerge[box.x1][box.z1]->GetZeroBase(box.LY); if (root != -1) { type |= EB_XMAX_ZMAX; table.Insert(EI_XMAX_ZMAX, static_cast<float>(box.x1), GetYInterp(box.x1, root, box.z1), static_cast<float>(box.z1)); } // ymin-zmin edge root = mXMerge[box.y0][box.z0]->GetZeroBase(box.LX); if (root != -1) { type |= EB_YMIN_ZMIN; table.Insert(EI_YMIN_ZMIN, GetXInterp(root, box.y0, box.z0), static_cast<float>(box.y0), static_cast<float>(box.z0)); } // ymin-zmax edge root = mXMerge[box.y0][box.z1]->GetZeroBase(box.LX); if (root != -1) { type |= EB_YMIN_ZMAX; table.Insert(EI_YMIN_ZMAX, GetXInterp(root, box.y0, box.z1), static_cast<float>(box.y0), static_cast<float>(box.z1)); } // ymax-zmin edge root = mXMerge[box.y1][box.z0]->GetZeroBase(box.LX); if (root != -1) { type |= EB_YMAX_ZMIN; table.Insert(EI_YMAX_ZMIN, GetXInterp(root, box.y1, box.z0), static_cast<float>(box.y1), static_cast<float>(box.z0)); } // ymax-zmax edge root = mXMerge[box.y1][box.z1]->GetZeroBase(box.LX); if (root != -1) { type |= EB_YMAX_ZMAX; table.Insert(EI_YMAX_ZMAX, GetXInterp(root, box.y1, box.z1), static_cast<float>(box.y1), static_cast<float>(box.z1)); } } // Edge extraction for single boxes (1x1x1). void GetXMinEdgesS(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_YMIN) { faceType |= 0x01; } if (type & EB_XMIN_YMAX) { faceType |= 0x02; } if (type & EB_XMIN_ZMIN) { faceType |= 0x04; } if (type & EB_XMIN_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: return; case 3: table.InsertEdge(EI_XMIN_YMIN, EI_XMIN_YMAX); break; case 5: table.InsertEdge(EI_XMIN_YMIN, EI_XMIN_ZMIN); break; case 6: table.InsertEdge(EI_XMIN_YMAX, EI_XMIN_ZMIN); break; case 9: table.InsertEdge(EI_XMIN_YMIN, EI_XMIN_ZMAX); break; case 10: table.InsertEdge(EI_XMIN_YMAX, EI_XMIN_ZMAX); break; case 12: table.InsertEdge(EI_XMIN_ZMIN, EI_XMIN_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = box.x0 + mSize * (box.y0 + mSize * box.z0); // F(x,y,z) int64_t f00 = static_cast<int64_t>(mInputVoxels[i]); i += mSize; // F(x,y+1,z) int64_t f10 = static_cast<int64_t>(mInputVoxels[i]); i += mSizeSqr; // F(x,y+1,z+1) int64_t f11 = static_cast<int64_t>(mInputVoxels[i]); i -= mSize; // F(x,y,z+1) int64_t f01 = static_cast<int64_t>(mInputVoxels[i]); int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.InsertEdge(EI_XMIN_YMIN, EI_XMIN_ZMIN); table.InsertEdge(EI_XMIN_YMAX, EI_XMIN_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.InsertEdge(EI_XMIN_YMIN, EI_XMIN_ZMAX); table.InsertEdge(EI_XMIN_YMAX, EI_XMIN_ZMIN); } else { // Plus-sign configuration, add branch point to // tessellation. table.Insert(FI_XMIN, table.GetVertex(EI_XMIN_ZMIN)[0], table.GetVertex(EI_XMIN_ZMIN)[1], table.GetVertex(EI_XMIN_YMIN)[2]); // Add edges sharing the branch point. table.InsertEdge(EI_XMIN_YMIN, FI_XMIN); table.InsertEdge(EI_XMIN_YMAX, FI_XMIN); table.InsertEdge(EI_XMIN_ZMIN, FI_XMIN); table.InsertEdge(EI_XMIN_ZMAX, FI_XMIN); } break; } default: LogError("The level value cannot be an exact integer."); } } void GetXMaxEdgesS(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMAX_YMIN) { faceType |= 0x01; } if (type & EB_XMAX_YMAX) { faceType |= 0x02; } if (type & EB_XMAX_ZMIN) { faceType |= 0x04; } if (type & EB_XMAX_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: return; case 3: table.InsertEdge(EI_XMAX_YMIN, EI_XMAX_YMAX); break; case 5: table.InsertEdge(EI_XMAX_YMIN, EI_XMAX_ZMIN); break; case 6: table.InsertEdge(EI_XMAX_YMAX, EI_XMAX_ZMIN); break; case 9: table.InsertEdge(EI_XMAX_YMIN, EI_XMAX_ZMAX); break; case 10: table.InsertEdge(EI_XMAX_YMAX, EI_XMAX_ZMAX); break; case 12: table.InsertEdge(EI_XMAX_ZMIN, EI_XMAX_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = box.x1 + mSize * (box.y0 + mSize * box.z0); // F(x,y,z) int64_t f00 = static_cast<int64_t>(mInputVoxels[i]); i += mSize; // F(x,y+1,z) int64_t f10 = static_cast<int64_t>(mInputVoxels[i]); i += mSizeSqr; // F(x,y+1,z+1) int64_t f11 = static_cast<int64_t>(mInputVoxels[i]); i -= mSize; // F(x,y,z+1) int64_t f01 = static_cast<int64_t>(mInputVoxels[i]); int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.InsertEdge(EI_XMAX_YMIN, EI_XMAX_ZMIN); table.InsertEdge(EI_XMAX_YMAX, EI_XMAX_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.InsertEdge(EI_XMAX_YMIN, EI_XMAX_ZMAX); table.InsertEdge(EI_XMAX_YMAX, EI_XMAX_ZMIN); } else { // Plus-sign configuration, add branch point to // tessellation. table.Insert(FI_XMAX, table.GetVertex(EI_XMAX_ZMIN)[0], table.GetVertex(EI_XMAX_ZMIN)[1], table.GetVertex(EI_XMAX_YMIN)[2]); // Add edges sharing the branch point. table.InsertEdge(EI_XMAX_YMIN, FI_XMAX); table.InsertEdge(EI_XMAX_YMAX, FI_XMAX); table.InsertEdge(EI_XMAX_ZMIN, FI_XMAX); table.InsertEdge(EI_XMAX_ZMAX, FI_XMAX); } break; } default: LogError("The level value cannot be an exact integer."); } } void GetYMinEdgesS(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_YMIN) { faceType |= 0x01; } if (type & EB_XMAX_YMIN) { faceType |= 0x02; } if (type & EB_YMIN_ZMIN) { faceType |= 0x04; } if (type & EB_YMIN_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: return; case 3: table.InsertEdge(EI_XMIN_YMIN, EI_XMAX_YMIN); break; case 5: table.InsertEdge(EI_XMIN_YMIN, EI_YMIN_ZMIN); break; case 6: table.InsertEdge(EI_XMAX_YMIN, EI_YMIN_ZMIN); break; case 9: table.InsertEdge(EI_XMIN_YMIN, EI_YMIN_ZMAX); break; case 10: table.InsertEdge(EI_XMAX_YMIN, EI_YMIN_ZMAX); break; case 12: table.InsertEdge(EI_YMIN_ZMIN, EI_YMIN_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = box.x0 + mSize * (box.y0 + mSize * box.z0); // F(x,y,z) int64_t f00 = static_cast<int64_t>(mInputVoxels[i]); ++i; // F(x+1,y,z) int64_t f10 = static_cast<int64_t>(mInputVoxels[i]); i += mSizeSqr; // F(x+1,y,z+1) int64_t f11 = static_cast<int64_t>(mInputVoxels[i]); --i; // F(x,y,z+1) int64_t f01 = static_cast<int64_t>(mInputVoxels[i]); int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.InsertEdge(EI_XMIN_YMIN, EI_YMIN_ZMIN); table.InsertEdge(EI_XMAX_YMIN, EI_YMIN_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.InsertEdge(EI_XMIN_YMIN, EI_YMIN_ZMAX); table.InsertEdge(EI_XMAX_YMIN, EI_YMIN_ZMIN); } else { // Plus-sign configuration, add branch point to // tessellation. table.Insert(FI_YMIN, table.GetVertex(EI_YMIN_ZMIN)[0], table.GetVertex(EI_XMIN_YMIN)[1], table.GetVertex(EI_XMIN_YMIN)[2]); // Add edges sharing the branch point. table.InsertEdge(EI_XMIN_YMIN, FI_YMIN); table.InsertEdge(EI_XMAX_YMIN, FI_YMIN); table.InsertEdge(EI_YMIN_ZMIN, FI_YMIN); table.InsertEdge(EI_YMIN_ZMAX, FI_YMIN); } break; } default: LogError("The level value cannot be an exact integer."); } } void GetYMaxEdgesS(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_YMAX) { faceType |= 0x01; } if (type & EB_XMAX_YMAX) { faceType |= 0x02; } if (type & EB_YMAX_ZMIN) { faceType |= 0x04; } if (type & EB_YMAX_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: return; case 3: table.InsertEdge(EI_XMIN_YMAX, EI_XMAX_YMAX); break; case 5: table.InsertEdge(EI_XMIN_YMAX, EI_YMAX_ZMIN); break; case 6: table.InsertEdge(EI_XMAX_YMAX, EI_YMAX_ZMIN); break; case 9: table.InsertEdge(EI_XMIN_YMAX, EI_YMAX_ZMAX); break; case 10: table.InsertEdge(EI_XMAX_YMAX, EI_YMAX_ZMAX); break; case 12: table.InsertEdge(EI_YMAX_ZMIN, EI_YMAX_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = box.x0 + mSize * (box.y1 + mSize * box.z0); // F(x,y,z) int64_t f00 = static_cast<int64_t>(mInputVoxels[i]); ++i; // F(x+1,y,z) int64_t f10 = static_cast<int64_t>(mInputVoxels[i]); i += mSizeSqr; // F(x+1,y,z+1) int64_t f11 = static_cast<int64_t>(mInputVoxels[i]); --i; // F(x,y,z+1) int64_t f01 = static_cast<int64_t>(mInputVoxels[i]); int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.InsertEdge(EI_XMIN_YMAX, EI_YMAX_ZMIN); table.InsertEdge(EI_XMAX_YMAX, EI_YMAX_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.InsertEdge(EI_XMIN_YMAX, EI_YMAX_ZMAX); table.InsertEdge(EI_XMAX_YMAX, EI_YMAX_ZMIN); } else { // Plus-sign configuration, add branch point to // tessellation. table.Insert(FI_YMAX, table.GetVertex(EI_YMAX_ZMIN)[0], table.GetVertex(EI_XMIN_YMAX)[1], table.GetVertex(EI_XMIN_YMAX)[2]); // Add edges sharing the branch point. table.InsertEdge(EI_XMIN_YMAX, FI_YMAX); table.InsertEdge(EI_XMAX_YMAX, FI_YMAX); table.InsertEdge(EI_YMAX_ZMIN, FI_YMAX); table.InsertEdge(EI_YMAX_ZMAX, FI_YMAX); } break; } default: LogError("The level value cannot be an exact integer."); } } void GetZMinEdgesS(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_ZMIN) { faceType |= 0x01; } if (type & EB_XMAX_ZMIN) { faceType |= 0x02; } if (type & EB_YMIN_ZMIN) { faceType |= 0x04; } if (type & EB_YMAX_ZMIN) { faceType |= 0x08; } switch (faceType) { case 0: return; case 3: table.InsertEdge(EI_XMIN_ZMIN, EI_XMAX_ZMIN); break; case 5: table.InsertEdge(EI_XMIN_ZMIN, EI_YMIN_ZMIN); break; case 6: table.InsertEdge(EI_XMAX_ZMIN, EI_YMIN_ZMIN); break; case 9: table.InsertEdge(EI_XMIN_ZMIN, EI_YMAX_ZMIN); break; case 10: table.InsertEdge(EI_XMAX_ZMIN, EI_YMAX_ZMIN); break; case 12: table.InsertEdge(EI_YMIN_ZMIN, EI_YMAX_ZMIN); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = box.x0 + mSize * (box.y0 + mSize * box.z0); // F(x,y,z) int64_t f00 = static_cast<int64_t>(mInputVoxels[i]); ++i; // F(x+1,y,z) int64_t f10 = static_cast<int64_t>(mInputVoxels[i]); i += mSize; // F(x+1,y+1,z) int64_t f11 = static_cast<int64_t>(mInputVoxels[i]); --i; // F(x,y+1,z) int64_t f01 = static_cast<int64_t>(mInputVoxels[i]); int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.InsertEdge(EI_XMIN_ZMIN, EI_YMIN_ZMIN); table.InsertEdge(EI_XMAX_ZMIN, EI_YMAX_ZMIN); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.InsertEdge(EI_XMIN_ZMIN, EI_YMAX_ZMIN); table.InsertEdge(EI_XMAX_ZMIN, EI_YMIN_ZMIN); } else { // Plus-sign configuration, add branch point to // tessellation. table.Insert(FI_ZMIN, table.GetVertex(EI_YMIN_ZMIN)[0], table.GetVertex(EI_XMIN_ZMIN)[1], table.GetVertex(EI_XMIN_ZMIN)[2]); // Add edges sharing the branch point. table.InsertEdge(EI_XMIN_ZMIN, FI_ZMIN); table.InsertEdge(EI_XMAX_ZMIN, FI_ZMIN); table.InsertEdge(EI_YMIN_ZMIN, FI_ZMIN); table.InsertEdge(EI_YMAX_ZMIN, FI_ZMIN); } break; } default: LogError("The level value cannot be an exact integer."); } } void GetZMaxEdgesS(const OctBox& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_ZMAX) { faceType |= 0x01; } if (type & EB_XMAX_ZMAX) { faceType |= 0x02; } if (type & EB_YMIN_ZMAX) { faceType |= 0x04; } if (type & EB_YMAX_ZMAX) { faceType |= 0x08; } switch (faceType) { case 0: return; case 3: table.InsertEdge(EI_XMIN_ZMAX, EI_XMAX_ZMAX); break; case 5: table.InsertEdge(EI_XMIN_ZMAX, EI_YMIN_ZMAX); break; case 6: table.InsertEdge(EI_XMAX_ZMAX, EI_YMIN_ZMAX); break; case 9: table.InsertEdge(EI_XMIN_ZMAX, EI_YMAX_ZMAX); break; case 10: table.InsertEdge(EI_XMAX_ZMAX, EI_YMAX_ZMAX); break; case 12: table.InsertEdge(EI_YMIN_ZMAX, EI_YMAX_ZMAX); break; case 15: { // Four vertices, one per edge, need to disambiguate. int32_t i = box.x0 + mSize * (box.y0 + mSize * box.z1); // F(x,y,z) int64_t f00 = static_cast<int64_t>(mInputVoxels[i]); i++; // F(x+1,y,z) int64_t f10 = static_cast<int64_t>(mInputVoxels[i]); i += mSize; // F(x+1,y+1,z) int64_t f11 = static_cast<int64_t>(mInputVoxels[i]); i--; // F(x,y+1,z) int64_t f01 = static_cast<int64_t>(mInputVoxels[i]); int64_t det = f00 * f11 - f01 * f10; if (det > 0) { // Disjoint hyperbolic segments, pair <P0,P2>, <P1,P3>. table.InsertEdge(EI_XMIN_ZMAX, EI_YMIN_ZMAX); table.InsertEdge(EI_XMAX_ZMAX, EI_YMAX_ZMAX); } else if (det < 0) { // Disjoint hyperbolic segments, pair <P0,P3>, <P1,P2>. table.InsertEdge(EI_XMIN_ZMAX, EI_YMAX_ZMAX); table.InsertEdge(EI_XMAX_ZMAX, EI_YMIN_ZMAX); } else { // Plus-sign configuration, add branch point to // tessellation. table.Insert(FI_ZMAX, table.GetVertex(EI_YMIN_ZMAX)[0], table.GetVertex(EI_XMIN_ZMAX)[1], table.GetVertex(EI_XMIN_ZMAX)[2]); // Add edges sharing the branch point. table.InsertEdge(EI_XMIN_ZMAX, FI_ZMAX); table.InsertEdge(EI_XMAX_ZMAX, FI_ZMAX); table.InsertEdge(EI_YMIN_ZMAX, FI_ZMAX); table.InsertEdge(EI_YMAX_ZMAX, FI_ZMAX); } break; } default: LogError("The level value cannot be an exact integer."); } } // Edge extraction for merged boxes. class Sort0 { public: bool operator()(Vertex const& arg0, Vertex const& arg1) const { if (arg0[0] < arg1[0]) { return true; } if (arg0[0] > arg1[0]) { return false; } if (arg0[1] < arg1[1]) { return true; } if (arg0[1] > arg1[1]) { return false; } return arg0[2] < arg1[2]; } }; class Sort1 { public: bool operator()(Vertex const& arg0, Vertex const& arg1) const { if (arg0[2] < arg1[2]) { return true; } if (arg0[2] > arg1[2]) { return false; } if (arg0[0] < arg1[0]) { return true; } if (arg0[0] > arg1[0]) { return false; } return arg0[1] < arg1[1]; } }; class Sort2 { public: bool operator()(Vertex const& arg0, Vertex const& arg1) const { if (arg0[1] < arg1[1]) { return true; } if (arg0[1] > arg1[1]) { return false; } if (arg0[2] < arg1[2]) { return true; } if (arg0[2] > arg1[2]) { return false; } return arg0[0] < arg1[0]; } }; void GetZMinEdgesM(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_ZMIN) { faceType |= 0x01; } if (type & EB_XMAX_ZMIN) { faceType |= 0x02; } if (type & EB_YMIN_ZMIN) { faceType |= 0x04; } if (type & EB_YMAX_ZMIN) { faceType |= 0x08; } int32_t end0 = 0, end1 = 0; switch (faceType) { case 0: return; case 3: end0 = EI_XMIN_ZMIN; end1 = EI_XMAX_ZMIN; break; case 5: end0 = EI_XMIN_ZMIN; end1 = EI_YMIN_ZMIN; break; case 6: end0 = EI_YMIN_ZMIN; end1 = EI_XMAX_ZMIN; break; case 9: end0 = EI_XMIN_ZMIN; end1 = EI_YMAX_ZMIN; break; case 10: end0 = EI_YMAX_ZMIN; end1 = EI_XMAX_ZMIN; break; case 12: end0 = EI_YMIN_ZMIN; end1 = EI_YMAX_ZMIN; break; default: LogError("The level value cannot be an exact integer."); } std::set<Vertex, Sort0> vSet; for (int32_t x = box.x0 + 1; x < box.x1; ++x) { auto const& merge = mYMerge[x][box.z0]; if (merge->IsZeroEdge(box.LY) || merge->HasZeroSubedge(box.LY)) { int32_t root = merge->GetZeroBase(box.LY); vSet.insert(Vertex{ static_cast<Real>(x), GetYInterp(x, root, box.z0), static_cast<Real>(box.z0) }); } } for (int32_t y = box.y0 + 1; y < box.y1; ++y) { auto const& merge = mXMerge[y][box.z0]; if (merge->IsZeroEdge(box.LX) || merge->HasZeroSubedge(box.LX)) { int32_t root = merge->GetZeroBase(box.LX); vSet.insert(Vertex{ GetXInterp(root, y, box.z0), static_cast<Real>(y), static_cast<Real>(box.z0) }); } } // Add subdivision. if (vSet.size() == 0) { table.InsertEdge(end0, end1); return; } Real v0x = std::floor((*vSet.begin())[0]); Real v1x = std::floor((*vSet.rbegin())[0]); Real e0x = std::floor(table.GetVertex(end0)[0]); Real e1x = std::floor(table.GetVertex(end1)[0]); if (e1x <= v0x && v1x <= e0x) { std::swap(end0, end1); } // Add vertices. int32_t v0 = table.GetNumVertices(), v1 = v0; for (auto const& position : vSet) { table.Insert(position); } // Add edges. table.InsertEdge(end0, v1); ++v1; int32_t const imax = static_cast<int32_t>(vSet.size()); for (int32_t i = 1; i < imax; ++i, ++v0, ++v1) { table.InsertEdge(v0, v1); } table.InsertEdge(v0, end1); } void GetZMaxEdgesM(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_ZMAX) { faceType |= 0x01; } if (type & EB_XMAX_ZMAX) { faceType |= 0x02; } if (type & EB_YMIN_ZMAX) { faceType |= 0x04; } if (type & EB_YMAX_ZMAX) { faceType |= 0x08; } int32_t end0 = 0, end1 = 0; switch (faceType) { case 0: return; case 3: end0 = EI_XMIN_ZMAX; end1 = EI_XMAX_ZMAX; break; case 5: end0 = EI_XMIN_ZMAX; end1 = EI_YMIN_ZMAX; break; case 6: end0 = EI_YMIN_ZMAX; end1 = EI_XMAX_ZMAX; break; case 9: end0 = EI_XMIN_ZMAX; end1 = EI_YMAX_ZMAX; break; case 10: end0 = EI_YMAX_ZMAX; end1 = EI_XMAX_ZMAX; break; case 12: end0 = EI_YMIN_ZMAX; end1 = EI_YMAX_ZMAX; break; default: LogError("The level value cannot be an exact integer."); } std::set<Vertex, Sort0> vSet; for (int32_t x = box.x0 + 1; x < box.x1; ++x) { auto const& merge = mYMerge[x][box.z1]; if (merge->IsZeroEdge(box.LY) || merge->HasZeroSubedge(box.LY)) { int32_t root = merge->GetZeroBase(box.LY); vSet.insert(Vertex{ static_cast<Real>(x), GetYInterp(x, root, box.z1), static_cast<Real>(box.z1) }); } } for (int32_t y = box.y0 + 1; y < box.y1; ++y) { auto const& merge = mXMerge[y][box.z1]; if (merge->IsZeroEdge(box.LX) || merge->HasZeroSubedge(box.LX)) { int32_t root = merge->GetZeroBase(box.LX); vSet.insert(Vertex{ GetXInterp(root, y, box.z1), static_cast<Real>(y), static_cast<Real>(box.z1) }); } } // Add subdivision. int32_t v0 = table.GetNumVertices(), v1 = v0; if (vSet.size() == 0) { table.InsertEdge(end0, end1); return; } Real v0x = std::floor((*vSet.begin())[0]); Real v1x = std::floor((*vSet.rbegin())[0]); Real e0x = std::floor(table.GetVertex(end0)[0]); Real e1x = std::floor(table.GetVertex(end1)[0]); if (e1x <= v0x && v1x <= e0x) { std::swap(end0, end1); } // Add vertices. for (auto const& position : vSet) { table.Insert(position); } // Add edges. table.InsertEdge(end0, v1); ++v1; int32_t const imax = static_cast<int32_t>(vSet.size()); for (int32_t i = 1; i < imax; ++i, ++v0, ++v1) { table.InsertEdge(v0, v1); } table.InsertEdge(v0, end1); } void GetYMinEdgesM(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_YMIN) { faceType |= 0x01; } if (type & EB_XMAX_YMIN) { faceType |= 0x02; } if (type & EB_YMIN_ZMIN) { faceType |= 0x04; } if (type & EB_YMIN_ZMAX) { faceType |= 0x08; } int32_t end0 = 0, end1 = 0; switch (faceType) { case 0: return; case 3: end0 = EI_XMIN_YMIN; end1 = EI_XMAX_YMIN; break; case 5: end0 = EI_XMIN_YMIN; end1 = EI_YMIN_ZMIN; break; case 6: end0 = EI_YMIN_ZMIN; end1 = EI_XMAX_YMIN; break; case 9: end0 = EI_XMIN_YMIN; end1 = EI_YMIN_ZMAX; break; case 10: end0 = EI_YMIN_ZMAX; end1 = EI_XMAX_YMIN; break; case 12: end0 = EI_YMIN_ZMIN; end1 = EI_YMIN_ZMAX; break; default: LogError("The level value cannot be an exact integer."); } std::set<Vertex, Sort1> vSet; for (int32_t x = box.x0 + 1; x < box.x1; ++x) { auto const& merge = mZMerge[x][box.y0]; if (merge->IsZeroEdge(box.LZ) || merge->HasZeroSubedge(box.LZ)) { int32_t root = merge->GetZeroBase(box.LZ); vSet.insert(Vertex{ static_cast<Real>(x), static_cast<Real>(box.y0), GetZInterp(x, box.y0, root) }); } } for (int32_t z = box.z0 + 1; z < box.z1; ++z) { auto const& merge = mXMerge[box.y0][z]; if (merge->IsZeroEdge(box.LX) || merge->HasZeroSubedge(box.LX)) { int32_t root = merge->GetZeroBase(box.LX); vSet.insert(Vertex{ GetXInterp(root, box.y0, z), static_cast<Real>(box.y0), static_cast<Real>(z) }); } } // Add subdivision. int32_t v0 = table.GetNumVertices(), v1 = v0; if (vSet.size() == 0) { table.InsertEdge(end0, end1); return; } Real v0z = std::floor((*vSet.begin())[2]); Real v1z = std::floor((*vSet.rbegin())[2]); Real e0z = std::floor(table.GetVertex(end0)[2]); Real e1z = std::floor(table.GetVertex(end1)[2]); if (e1z <= v0z && v1z <= e0z) { std::swap(end0, end1); } // Add vertices. for (auto const& position : vSet) { table.Insert(position); } // Add edges. table.InsertEdge(end0, v1); ++v1; int32_t const imax = static_cast<int32_t>(vSet.size()); for (int32_t i = 1; i < imax; ++i, ++v0, ++v1) { table.InsertEdge(v0, v1); } table.InsertEdge(v0, end1); } void GetYMaxEdgesM(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_YMAX) { faceType |= 0x01; } if (type & EB_XMAX_YMAX) { faceType |= 0x02; } if (type & EB_YMAX_ZMIN) { faceType |= 0x04; } if (type & EB_YMAX_ZMAX) { faceType |= 0x08; } int32_t end0 = 0, end1 = 0; switch (faceType) { case 0: return; case 3: end0 = EI_XMIN_YMAX; end1 = EI_XMAX_YMAX; break; case 5: end0 = EI_XMIN_YMAX; end1 = EI_YMAX_ZMIN; break; case 6: end0 = EI_YMAX_ZMIN; end1 = EI_XMAX_YMAX; break; case 9: end0 = EI_XMIN_YMAX; end1 = EI_YMAX_ZMAX; break; case 10: end0 = EI_YMAX_ZMAX; end1 = EI_XMAX_YMAX; break; case 12: end0 = EI_YMAX_ZMIN; end1 = EI_YMAX_ZMAX; break; default: LogError("The level value cannot be an exact integer."); } std::set<Vertex, Sort1> vSet; for (int32_t x = box.x0 + 1; x < box.x1; ++x) { auto const& merge = mZMerge[x][box.y1]; if (merge->IsZeroEdge(box.LZ) || merge->HasZeroSubedge(box.LZ)) { int32_t root = merge->GetZeroBase(box.LZ); vSet.insert(Vertex{ static_cast<Real>(x), static_cast<Real>(box.y1), GetZInterp(x, box.y1, root) }); } } for (int32_t z = box.z0 + 1; z < box.z1; ++z) { auto const& merge = mXMerge[box.y1][z]; if (merge->IsZeroEdge(box.LX) || merge->HasZeroSubedge(box.LX)) { int32_t root = merge->GetZeroBase(box.LX); vSet.insert(Vertex{ GetXInterp(root, box.y1, z), static_cast<Real>(box.y1), static_cast<Real>(z) }); } } // Add subdivision. if (vSet.size() == 0) { table.InsertEdge(end0, end1); return; } Real v0z = std::floor((*vSet.begin())[2]); Real v1z = std::floor((*vSet.rbegin())[2]); Real e0z = std::floor(table.GetVertex(end0)[2]); Real e1z = std::floor(table.GetVertex(end1)[2]); if (e1z <= v0z && v1z <= e0z) { std::swap(end0, end1); } // Add vertices. int32_t v0 = table.GetNumVertices(), v1 = v0; for (auto const& position : vSet) { table.Insert(position); } // Add edges. table.InsertEdge(end0, v1); ++v1; int32_t const imax = static_cast<int32_t>(vSet.size()); for (int32_t i = 1; i < imax; ++i, ++v0, ++v1) { table.InsertEdge(v0, v1); } table.InsertEdge(v0, end1); } void GetXMinEdgesM(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMIN_YMIN) { faceType |= 0x01; } if (type & EB_XMIN_YMAX) { faceType |= 0x02; } if (type & EB_XMIN_ZMIN) { faceType |= 0x04; } if (type & EB_XMIN_ZMAX) { faceType |= 0x08; } int32_t end0 = 0, end1 = 0; switch (faceType) { case 0: return; case 3: end0 = EI_XMIN_YMIN; end1 = EI_XMIN_YMAX; break; case 5: end0 = EI_XMIN_YMIN; end1 = EI_XMIN_ZMIN; break; case 6: end0 = EI_XMIN_ZMIN; end1 = EI_XMIN_YMAX; break; case 9: end0 = EI_XMIN_YMIN; end1 = EI_XMIN_ZMAX; break; case 10: end0 = EI_XMIN_ZMAX; end1 = EI_XMIN_YMAX; break; case 12: end0 = EI_XMIN_ZMIN; end1 = EI_XMIN_ZMAX; break; default: LogError("The level value cannot be an exact integer."); } std::set<Vertex, Sort2> vSet; for (int32_t z = box.z0 + 1; z < box.z1; ++z) { auto const& merge = mYMerge[box.x0][z]; if (merge->IsZeroEdge(box.LY) || merge->HasZeroSubedge(box.LY)) { int32_t root = merge->GetZeroBase(box.LY); vSet.insert(Vertex{ static_cast<Real>(box.x0), GetYInterp(box.x0, root, z), static_cast<Real>(z) }); } } for (int32_t y = box.y0 + 1; y < box.y1; ++y) { auto const& merge = mZMerge[box.x0][y]; if (merge->IsZeroEdge(box.LZ) || merge->HasZeroSubedge(box.LZ)) { int32_t root = merge->GetZeroBase(box.LZ); vSet.insert(Vertex{ static_cast<Real>(box.x0), static_cast<Real>(y), GetZInterp(box.x0, y, root) }); } } // Add subdivision. int32_t v0 = table.GetNumVertices(), v1 = v0; if (vSet.size() == 0) { table.InsertEdge(end0, end1); return; } Real v0y = std::floor((*vSet.begin())[1]); Real v1y = std::floor((*vSet.rbegin())[1]); Real e0y = std::floor(table.GetVertex(end0)[1]); Real e1y = std::floor(table.GetVertex(end1)[1]); if (e1y <= v0y && v1y <= e0y) { std::swap(end0, end1); } // Add vertices. for (auto const& position : vSet) { table.Insert(position); } // Add edges. table.InsertEdge(end0, v1); ++v1; int32_t const imax = static_cast<int32_t>(vSet.size()); for (int32_t i = 1; i < imax; ++i, ++v0, ++v1) { table.InsertEdge(v0, v1); } table.InsertEdge(v0, end1); } void GetXMaxEdgesM(OctBox const& box, uint32_t type, VETable& table) { uint32_t faceType = 0; if (type & EB_XMAX_YMIN) { faceType |= 0x01; } if (type & EB_XMAX_YMAX) { faceType |= 0x02; } if (type & EB_XMAX_ZMIN) { faceType |= 0x04; } if (type & EB_XMAX_ZMAX) { faceType |= 0x08; } int32_t end0 = 0, end1 = 0; switch (faceType) { case 0: return; case 3: end0 = EI_XMAX_YMIN; end1 = EI_XMAX_YMAX; break; case 5: end0 = EI_XMAX_YMIN; end1 = EI_XMAX_ZMIN; break; case 6: end0 = EI_XMAX_ZMIN; end1 = EI_XMAX_YMAX; break; case 9: end0 = EI_XMAX_YMIN; end1 = EI_XMAX_ZMAX; break; case 10: end0 = EI_XMAX_ZMAX; end1 = EI_XMAX_YMAX; break; case 12: end0 = EI_XMAX_ZMIN; end1 = EI_XMAX_ZMAX; break; default: LogError("The level value cannot be an exact integer."); } std::set<Vertex, Sort2> vSet; for (int32_t z = box.z0 + 1; z < box.z1; ++z) { auto const& merge = mYMerge[box.x1][z]; if (merge->IsZeroEdge(box.LY) || merge->HasZeroSubedge(box.LY)) { int32_t root = merge->GetZeroBase(box.LY); vSet.insert(Vertex{ static_cast<Real>(box.x1), GetYInterp(box.x1, root, z), static_cast<Real>(z) }); } } for (int32_t y = box.y0 + 1; y < box.y1; y++) { auto const& merge = mZMerge[box.x1][y]; if (merge->IsZeroEdge(box.LZ) || merge->HasZeroSubedge(box.LZ)) { int32_t root = merge->GetZeroBase(box.LZ); vSet.insert(Vertex{ static_cast<Real>(box.x1), static_cast<Real>(y), GetZInterp(box.x1, y, root) }); } } // Add subdivision. if (vSet.size() == 0) { table.InsertEdge(end0, end1); return; } Real v0y = std::floor((*vSet.begin())[1]); Real v1y = std::floor((*vSet.rbegin())[1]); Real e0y = std::floor(table.GetVertex(end0)[1]); Real e1y = std::floor(table.GetVertex(end1)[1]); if (e1y <= v0y && v1y <= e0y) { std::swap(end0, end1); } // Add vertices. int32_t v0 = table.GetNumVertices(), v1 = v0; for (auto const& position : vSet) { table.Insert(position); } // Add edges. table.InsertEdge(end0, v1); ++v1; int32_t const imax = static_cast<int32_t>(vSet.size()); for (int32_t i = 1; i < imax; ++i, ++v0, ++v1) { table.InsertEdge(v0, v1); } table.InsertEdge(v0, end1); } // Support for normal vector calculations. Vertex GetGradient(Vertex const& position) const { Vertex vzero = { (Real)0, (Real)0, (Real)0 }; int32_t x = static_cast<int32_t>(position[0]); if (x < 0 || x >= mTwoPowerN) { return vzero; } int32_t y = static_cast<int32_t>(position[1]); if (y < 0 || y >= mTwoPowerN) { return vzero; } int32_t z = static_cast<int32_t>(position[2]); if (z < 0 || z >= mTwoPowerN) { return vzero; } int32_t i000 = x + mSize * (y + mSize * z); int32_t i100 = i000 + 1; int32_t i010 = i000 + mSize; int32_t i110 = i100 + mSize; int32_t i001 = i000 + mSizeSqr; int32_t i101 = i100 + mSizeSqr; int32_t i011 = i010 + mSizeSqr; int32_t i111 = i110 + mSizeSqr; Real f000 = static_cast<Real>(mInputVoxels[i000]); Real f100 = static_cast<Real>(mInputVoxels[i100]); Real f010 = static_cast<Real>(mInputVoxels[i010]); Real f110 = static_cast<Real>(mInputVoxels[i110]); Real f001 = static_cast<Real>(mInputVoxels[i001]); Real f101 = static_cast<Real>(mInputVoxels[i101]); Real f011 = static_cast<Real>(mInputVoxels[i011]); Real f111 = static_cast<Real>(mInputVoxels[i111]); Real fx = position[0] - static_cast<Real>(x); Real fy = position[1] - static_cast<Real>(y); Real fz = position[2] - static_cast<Real>(z); Real oneMinusX = (Real)1 - fx; Real oneMinusY = (Real)1 - fy; Real oneMinusZ = (Real)1 - fz; Real tmp0, tmp1; Vertex gradient; tmp0 = oneMinusY * (f100 - f000) + fy * (f110 - f010); tmp1 = oneMinusY * (f101 - f001) + fy * (f111 - f011); gradient[0] = oneMinusZ * tmp0 + fz * tmp1; tmp0 = oneMinusX * (f010 - f000) + fx * (f110 - f100); tmp1 = oneMinusX * (f011 - f001) + fx * (f111 - f101); gradient[1] = oneMinusZ * tmp0 + fz * tmp1; tmp0 = oneMinusX * (f001 - f000) + fx * (f101 - f100); tmp1 = oneMinusX * (f011 - f010) + fx * (f111 - f110); gradient[2] = oneMinusY * tmp0 + oneMinusY * tmp1; return gradient; } enum { EI_XMIN_YMIN = 0, EI_XMIN_YMAX = 1, EI_XMAX_YMIN = 2, EI_XMAX_YMAX = 3, EI_XMIN_ZMIN = 4, EI_XMIN_ZMAX = 5, EI_XMAX_ZMIN = 6, EI_XMAX_ZMAX = 7, EI_YMIN_ZMIN = 8, EI_YMIN_ZMAX = 9, EI_YMAX_ZMIN = 10, EI_YMAX_ZMAX = 11, FI_XMIN = 12, FI_XMAX = 13, FI_YMIN = 14, FI_YMAX = 15, FI_ZMIN = 16, FI_ZMAX = 17, I_QUANTITY = 18, EB_XMIN_YMIN = 1 << EI_XMIN_YMIN, EB_XMIN_YMAX = 1 << EI_XMIN_YMAX, EB_XMAX_YMIN = 1 << EI_XMAX_YMIN, EB_XMAX_YMAX = 1 << EI_XMAX_YMAX, EB_XMIN_ZMIN = 1 << EI_XMIN_ZMIN, EB_XMIN_ZMAX = 1 << EI_XMIN_ZMAX, EB_XMAX_ZMIN = 1 << EI_XMAX_ZMIN, EB_XMAX_ZMAX = 1 << EI_XMAX_ZMAX, EB_YMIN_ZMIN = 1 << EI_YMIN_ZMIN, EB_YMIN_ZMAX = 1 << EI_YMIN_ZMAX, EB_YMAX_ZMIN = 1 << EI_YMAX_ZMIN, EB_YMAX_ZMAX = 1 << EI_YMAX_ZMAX, FB_XMIN = 1 << FI_XMIN, FB_XMAX = 1 << FI_XMAX, FB_YMIN = 1 << FI_YMIN, FB_YMAX = 1 << FI_YMAX, FB_ZMIN = 1 << FI_ZMIN, FB_ZMAX = 1 << FI_ZMAX }; // image data int32_t mTwoPowerN, mSize, mSizeSqr; T const* mInputVoxels; Real mLevel; bool mFixBoundary; // Trees for linear merging. Array2<std::shared_ptr<LinearMergeTree>> mXMerge, mYMerge, mZMerge; // monoboxes std::vector<OctBox> mBoxes; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Integration.h
.h
8,447
218
// 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/RootsPolynomial.h> #include <array> #include <functional> namespace gte { template <typename Real> class Integration { public: // A simple algorithm, but slow to converge as the number of samples // is increased. The 'numSamples' needs to be two or larger. static Real TrapezoidRule(int32_t numSamples, Real a, Real b, std::function<Real(Real)> const& integrand) { Real h = (b - a) / ((Real)numSamples - (Real)1); Real result = (Real)0.5 * (integrand(a) + integrand(b)); for (int32_t i = 1; i <= numSamples - 2; ++i) { result += integrand(a + i * h); } result *= h; return result; } // The trapezoid rule is used to generate initial estimates, but then // Richardson extrapolation is used to improve the estimates. This is // preferred over TrapezoidRule. The 'order' must be positive. static Real Romberg(int32_t order, Real a, Real b, std::function<Real(Real)> const& integrand) { Real const half = (Real)0.5; std::vector<std::array<Real, 2>> rom(order); Real h = b - a; rom[0][0] = half * h * (integrand(a) + integrand(b)); for (int32_t i0 = 2, p0 = 1; i0 <= order; ++i0, p0 *= 2, h *= half) { // Approximations via the trapezoid rule. Real sum = (Real)0; int32_t i1; for (i1 = 1; i1 <= p0; ++i1) { sum += integrand(a + h * (i1 - half)); } // Richardson extrapolation. rom[0][1] = half * (rom[0][0] + h * sum); for (int32_t i2 = 1, i2m1 = 0, p2 = 4; i2 < i0; ++i2, ++i2m1, p2 *= 4) { rom[i2][1] = (p2 * rom[i2m1][1] - rom[i2m1][0]) / (static_cast<size_t>(p2) - 1); } for (i1 = 0; i1 < i0; ++i1) { rom[i1][0] = rom[i1][1]; } } Real result = rom[static_cast<size_t>(order) - 1][0]; return result; } // Gaussian quadrature estimates the integral of a function f(x) // defined on [-1,1] using // integral_{-1}^{1} f(t) dt = sum_{i=0}^{n-1} c[i]*f(r[i]) // where r[i] are the roots to the Legendre polynomial p(t) of degree // n and // c[i] = integral_{-1}^{1} prod_{j=0,j!=i} (t-r[j]/(r[i]-r[j]) dt // To integrate over [a,b], a transformation to [-1,1] is applied // internally: x - ((b-a)*t + (b+a))/2. The Legendre polynomials are // generated by // P[0](x) = 1, P[1](x) = x, // P[k](x) = ((2*k-1)*x*P[k-1](x) - (k-1)*P[k-2](x))/k, k >= 2 // Implementing the polynomial generation is simple, and computing the // roots requires a numerical method for finding polynomial roots. // The challenging task is to develop an efficient algorithm for // computing the coefficients c[i] for a specified degree. The // 'degree' must be two or larger. static void ComputeQuadratureInfo(int32_t degree, std::vector<Real>& roots, std::vector<Real>& coefficients) { Real const zero = (Real)0; Real const one = (Real)1; Real const half = (Real)0.5; std::vector<std::vector<Real>> poly(static_cast<size_t>(degree) + 1); poly[0].resize(1); poly[0][0] = one; poly[1].resize(2); poly[1][0] = zero; poly[1][1] = one; for (int32_t n = 2, nm1 = 1, nm2 = 0, np1 = 3; n <= degree; ++n, ++nm1, ++nm2, ++np1) { Real mult0 = (Real)nm1 / (Real)n; Real mult1 = ((Real)2 * (Real)n - (Real)1) / (Real)n; poly[n].resize(np1); poly[n][0] = -mult0 * poly[nm2][0]; for (int32_t i = 1, im1 = 0; i <= nm2; ++i, ++im1) { poly[n][i] = mult1 * poly[nm1][im1] - mult0 * poly[nm2][i]; } poly[n][nm1] = mult1 * poly[nm1][nm2]; poly[n][n] = mult1 * poly[nm1][nm1]; } roots.resize(degree); RootsPolynomial<Real>::Find(degree, &poly[degree][0], 2048, &roots[0]); coefficients.resize(roots.size()); size_t n = roots.size() - 1; std::vector<Real> subroots(n); for (size_t i = 0; i < roots.size(); ++i) { Real denominator = (Real)1; for (size_t j = 0, k = 0; j < roots.size(); ++j) { if (j != i) { subroots[k++] = roots[j]; denominator *= roots[i] - roots[j]; } } std::array<Real, 2> delta = { -one - subroots.back(), +one - subroots.back() }; std::vector<std::array<Real, 2>> weights(n); weights[0][0] = half * delta[0] * delta[0]; weights[0][1] = half * delta[1] * delta[1]; for (size_t k = 1; k < n; ++k) { Real dk = (Real)k; Real mult = -dk / (dk + (Real)2); weights[k][0] = mult * delta[0] * weights[k - 1][0]; weights[k][1] = mult * delta[1] * weights[k - 1][1]; } struct Info { int32_t numBits; std::array<Real, 2> product; }; int32_t numElements = (1 << static_cast<uint32_t>(n - 1)); std::vector<Info> info(numElements); info[0].numBits = 0; info[0].product[0] = one; info[0].product[1] = one; for (int32_t ipow = 1, r = 0; ipow < numElements; ipow <<= 1, ++r) { info[ipow].numBits = 1; info[ipow].product[0] = -one - subroots[r]; info[ipow].product[1] = +one - subroots[r]; for (int32_t m = 1, j = ipow + 1; m < ipow; ++m, ++j) { info[j].numBits = info[m].numBits + 1; info[j].product[0] = info[ipow].product[0] * info[m].product[0]; info[j].product[1] = info[ipow].product[1] * info[m].product[1]; } } std::vector<std::array<Real, 2>> sum(n); std::array<Real, 2> zero2 = { zero, zero }; std::fill(sum.begin(), sum.end(), zero2); for (size_t k = 0; k < info.size(); ++k) { sum[info[k].numBits][0] += info[k].product[0]; sum[info[k].numBits][1] += info[k].product[1]; } std::array<Real, 2> total = zero2; for (size_t k = 0; k < n; ++k) { total[0] += weights[n - 1 - k][0] * sum[k][0]; total[1] += weights[n - 1 - k][1] * sum[k][1]; } coefficients[i] = (total[1] - total[0]) / denominator; } } static Real GaussianQuadrature(std::vector<Real> const& roots, std::vector<Real>const& coefficients, Real a, Real b, std::function<Real(Real)> const& integrand) { Real const half = (Real)0.5; Real radius = half * (b - a); Real center = half * (b + a); Real result = (Real)0; for (size_t i = 0; i < roots.size(); ++i) { result += coefficients[i] * integrand(radius * roots[i] + center); } result *= radius; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrCapsule3Capsule3.h
.h
1,095
42
// 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/DistSegmentSegment.h> #include <Mathematics/Capsule.h> namespace gte { template <typename T> class TIQuery<T, Capsule3<T>, Capsule3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Capsule3<T> const& capsule0, Capsule3<T> const& capsule1) { Result result{}; DCPQuery<T, Segment3<T>, Segment3<T>> ssQuery; auto ssResult = ssQuery(capsule0.segment, capsule1.segment); T rSum = capsule0.radius + capsule1.radius; result.intersect = (ssResult.distance <= rSum); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprPolynomial2.h
.h
6,198
179
// 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/Array2.h> #include <Mathematics/GMatrix.h> #include <array> // The samples are (x[i],w[i]) for 0 <= i < S. Think of w as a function of // x, say w = f(x). The function fits the samples with a polynomial of // degree d, say w = sum_{i=0}^d c[i]*x^i. The method is a least-squares // fitting algorithm. The mParameters stores the coefficients c[i] for // 0 <= i <= d. The observation type is std::array<Real,2>, which represents // a pair (x,w). // // WARNING. The fitting algorithm for polynomial terms // (1,x,x^2,...,x^d) // is known to be nonrobust for large degrees and for large magnitude data. // One alternative is to use orthogonal polynomials // (f[0](x),...,f[d](x)) // and apply the least-squares algorithm to these. Another alternative is to // transform // (x',w') = ((x-xcen)/rng, w/rng) // where xmin = min(x[i]), xmax = max(x[i]), xcen = (xmin+xmax)/2, and // rng = xmax-xmin. Fit the (x',w') points, // w' = sum_{i=0}^d c'[i]*(x')^i. // The original polynomial is evaluated as // w = rng*sum_{i=0}^d c'[i]*((x-xcen)/rng)^i namespace gte { template <typename Real> class ApprPolynomial2 : public ApprQuery<Real, std::array<Real, 2>> { public: // Initialize the model parameters to zero. ApprPolynomial2(int32_t degree) : mDegree(degree), mSize(degree + 1), mParameters(mSize, (Real)0) { mXDomain[0] = std::numeric_limits<Real>::max(); mXDomain[1] = -mXDomain[0]; } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numObservations, std::array<Real, 2> const* observations, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numObservations, observations, numIndices, indices)) { int32_t s, i0, i1; // Compute the powers of x. int32_t numSamples = static_cast<int32_t>(numIndices); int32_t twoDegree = 2 * mDegree; Array2<Real> xPower(static_cast<size_t>(twoDegree) + 1, numSamples); for (s = 0; s < numSamples; ++s) { Real x = observations[indices[s]][0]; mXDomain[0] = std::min(x, mXDomain[0]); mXDomain[1] = std::max(x, mXDomain[1]); xPower[s][0] = (Real)1; for (i0 = 1; i0 <= twoDegree; ++i0) { xPower[s][i0] = x * xPower[s][i0 - 1]; } } // Matrix A is the Vandermonde matrix and vector B is the // right-hand side of the linear system A*X = B. GMatrix<Real> A(mSize, mSize); GVector<Real> B(mSize); for (i0 = 0; i0 <= mDegree; ++i0) { Real sum = (Real)0; for (s = 0; s < numSamples; ++s) { Real w = observations[indices[s]][1]; sum += w * xPower[s][i0]; } B[i0] = sum; for (i1 = 0; i1 <= mDegree; ++i1) { sum = (Real)0; for (s = 0; s < numSamples; ++s) { sum += xPower[s][i0 + i1]; } A(i0, i1) = sum; } } // Solve for the polynomial coefficients. GVector<Real> coefficients = Inverse(A) * B; bool hasNonzero = false; for (int32_t i = 0; i < mSize; ++i) { mParameters[i] = coefficients[i]; if (coefficients[i] != (Real)0) { hasNonzero = true; } } return hasNonzero; } 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 static_cast<size_t>(mSize); } // Compute the model error for the specified observation for the // current model parameters. The returned value for observation // (x0,w0) is |w(x0) - w0|, where w(x) is the fitted polynomial. virtual Real Error(std::array<Real, 2> const& observation) const override { Real w = Evaluate(observation[0]); Real error = std::fabs(w - observation[1]); return error; } virtual void CopyParameters(ApprQuery<Real, std::array<Real, 2>> const* input) override { auto source = dynamic_cast<ApprPolynomial2 const*>(input); if (source) { *this = *source; } } // Evaluate the polynomial. The domain interval is provided so you can // interpolate (x in domain) or extrapolate (x not in domain). std::array<Real, 2> const& GetXDomain() const { return mXDomain; } Real Evaluate(Real x) const { int32_t i = mDegree; Real w = mParameters[i]; while (--i >= 0) { w = mParameters[i] + w * x; } return w; } private: int32_t mDegree, mSize; std::array<Real, 2> mXDomain; std::vector<Real> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrPlane3OrientedBox3.h
.h
1,274
47
// 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/DistPointHyperplane.h> #include <Mathematics/OrientedBox.h> namespace gte { template <typename T> class TIQuery<T, Plane3<T>, OrientedBox3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Plane3<T> const& plane, OrientedBox3<T> const& box) { Result result{}; T radius = std::fabs(box.extent[0] * Dot(plane.normal, box.axis[0])) + std::fabs(box.extent[1] * Dot(plane.normal, box.axis[1])) + std::fabs(box.extent[2] * Dot(plane.normal, box.axis[2])); DCPQuery<T, Vector3<T>, Plane3<T>> ppQuery; auto ppResult = ppQuery(box.center, plane); result.intersect = (ppResult.distance <= radius); return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrHalfspace3Triangle3.h
.h
8,720
244
// 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/Halfspace.h> #include <Mathematics/Triangle.h> // Queries for intersection of objects with halfspaces. These are useful for // containment testing, object culling, and clipping. namespace gte { template <typename T> class TIQuery<T, Halfspace3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Halfspace3<T> const& halfspace, Triangle3<T> const& triangle) { Result result{}; // Project the triangle vertices onto the normal line. The plane // of the halfspace occurs at the origin (zero) of the normal // line. std::array<T, 3> s{}; for (int32_t i = 0; i < 3; ++i) { s[i] = Dot(halfspace.normal, triangle.v[i]) - halfspace.constant; } // The triangle and halfspace intersect when the projection // interval maximum is nonnegative. result.intersect = (std::max(std::max(s[0], s[1]), s[2]) >= (T)0); return result; } }; template <typename T> class FIQuery<T, Halfspace3<T>, Triangle3<T>> { public: struct Result { Result() : intersect(false), numPoints(0), point{ Vector3<T>::Zero(), Vector3<T>::Zero(), Vector3<T>::Zero(), Vector3<T>::Zero() } { } bool intersect; // The triangle is clipped against the plane defining the // halfspace. The 'numPoints' is either 0 (no intersection), // 1 (point), 2 (segment), 3 (triangle), or 4 (quadrilateral). int32_t numPoints; std::array<Vector3<T>, 4> point; }; Result operator()(Halfspace3<T> const& halfspace, Triangle3<T> const& triangle) { Result result{}; // Determine on which side of the plane the vertices lie. The // table of possibilities is listed next with n = numNegative, // p = numPositive, and z = numZero. // // n p z intersection // --------------------------------- // 0 3 0 triangle (original) // 0 2 1 triangle (original) // 0 1 2 triangle (original) // 0 0 3 triangle (original) // 1 2 0 quad (2 edges clipped) // 1 1 1 triangle (1 edge clipped) // 1 0 2 edge // 2 1 0 triangle (2 edges clipped) // 2 0 1 vertex // 3 0 0 none std::array<T, 3> s{}; int32_t numPositive = 0, numNegative = 0, numZero = 0; for (int32_t i = 0; i < 3; ++i) { s[i] = Dot(halfspace.normal, triangle.v[i]) - halfspace.constant; if (s[i] > (T)0) { ++numPositive; } else if (s[i] < (T)0) { ++numNegative; } else { ++numZero; } } if (numNegative == 0) { // The triangle is in the halfspace. result.intersect = true; result.numPoints = 3; result.point[0] = triangle.v[0]; result.point[1] = triangle.v[1]; result.point[2] = triangle.v[2]; } else if (numNegative == 1) { result.intersect = true; if (numPositive == 2) { // The portion of the triangle in the halfspace is a // quadrilateral. result.numPoints = 4; for (int32_t i0 = 0; i0 < 3; ++i0) { if (s[i0] < (T)0) { int32_t i1 = (i0 + 1) % 3, i2 = (i0 + 2) % 3; result.point[0] = triangle.v[i1]; result.point[1] = triangle.v[i2]; T t2 = s[i2] / (s[i2] - s[i0]); T t0 = s[i0] / (s[i0] - s[i1]); result.point[2] = triangle.v[i2] + t2 * (triangle.v[i0] - triangle.v[i2]); result.point[3] = triangle.v[i0] + t0 * (triangle.v[i1] - triangle.v[i0]); break; } } } else if (numPositive == 1) { // The portion of the triangle in the halfspace is a // triangle with one vertex on the plane. result.numPoints = 3; for (int32_t i0 = 0; i0 < 3; ++i0) { if (s[i0] == (T)0) { int32_t i1 = (i0 + 1) % 3, i2 = (i0 + 2) % 3; result.point[0] = triangle.v[i0]; T t1 = s[i1] / (s[i1] - s[i2]); Vector3<T> p = triangle.v[i1] + t1 * (triangle.v[i2] - triangle.v[i1]); if (s[i1] > (T)0) { result.point[1] = triangle.v[i1]; result.point[2] = p; } else { result.point[1] = p; result.point[2] = triangle.v[i2]; } break; } } } else { // Only an edge of the triangle is in the halfspace. result.numPoints = 0; for (int32_t i = 0; i < 3; ++i) { if (s[i] == (T)0) { result.point[result.numPoints++] = triangle.v[i]; } } } } else if (numNegative == 2) { result.intersect = true; if (numPositive == 1) { // The portion of the triangle in the halfspace is a // triangle. result.numPoints = 3; for (int32_t i0 = 0; i0 < 3; ++i0) { if (s[i0] > (T)0) { int32_t i1 = (i0 + 1) % 3, i2 = (i0 + 2) % 3; result.point[0] = triangle.v[i0]; T t0 = s[i0] / (s[i0] - s[i1]); T t2 = s[i2] / (s[i2] - s[i0]); result.point[1] = triangle.v[i0] + t0 * (triangle.v[i1] - triangle.v[i0]); result.point[2] = triangle.v[i2] + t2 * (triangle.v[i0] - triangle.v[i2]); break; } } } else { // Only a vertex of the triangle is in the halfspace. result.numPoints = 1; for (int32_t i = 0; i < 3; ++i) { if (s[i] == (T)0) { result.point[0] = triangle.v[i]; break; } } } } else // numNegative == 3 { // The triangle is outside the halfspace. (numNegative == 3) result.intersect = false; result.numPoints = 0; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FastGaussianBlur1.h
.h
4,050
101
// 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> // The algorithms here are based on solving the linear heat equation using // finite differences in scale, not in time. The following document has // a brief summary of the concept, // https://www.geometrictools.com/Documentation/FastGaussianBlur.pdf // The idea is to represent the blurred image as f(x,s) in terms of position // x and scale s. Gaussian blurring is accomplished by using the input image // I(x,s0) as the initial image (of scale s0 > 0) for the partial differential // equation // s*df/ds = s^2*Laplacian(f) // where the Laplacian operator is // Laplacian = (d/dx)^2, dimension 1 // Laplacian = (d/dx)^2+(d/dy)^2, dimension 2 // Laplacian = (d/dx)^2+(d/dy)^2+(d/dz)^2, dimension 3 // // The term s*df/ds is approximated by // s*df(x,s)/ds = (f(x,b*s)-f(x,s))/ln(b) // for b > 1, but close to 1, where ln(b) is the natural logarithm of b. If // you take the limit of the right-hand side as b approaches 1, you get the // left-hand side. // // The term s^2*((d/dx)^2)f is approximated by // s^2*((d/dx)^2)f = (f(x+h*s,s)-2*f(x,s)+f(x-h*s,s))/h^2 // for h > 0, but close to zero. // // Equating the approximations for the left-hand side and the right-hand side // of the partial differential equation leads to the numerical method used in // this code. // // For iterative application of these functions, the caller is responsible // for constructing a geometric sequence of scales, // s0, s1 = s0*b, s2 = s1*b = s0*b^2, ... // where the base b satisfies 1 < b < exp(0.5*d) where d is the dimension of // the image. The upper bound on b guarantees stability of the finite // difference method used to approximate the partial differential equation. // The method assumes a pixel size of h = 1. namespace gte { // The image type must be one of int16_t, int32_t, float or double. The // computations are performed using double. The input and output images // must both have xBound elements. template <typename T> class FastGaussianBlur1 { public: void Execute(int32_t xBound, T const* input, T* output, double scale, double logBase) { int32_t xBoundM1 = xBound - 1; for (int32_t x = 0; x < xBound; ++x) { double rxps = static_cast<double>(x) + scale; double rxms = static_cast<double>(x) - scale; int32_t xp1 = static_cast<int32_t>(std::floor(rxps)); int32_t xm1 = static_cast<int32_t>(std::ceil(rxms)); double center = static_cast<double>(input[x]); double xsum = -2.0 * center; if (xp1 >= xBoundM1) // use boundary value { xsum += static_cast<double>(input[xBoundM1]); } else // linearly interpolate { double imgXp1 = static_cast<double>(input[xp1]); double imgXp2 = static_cast<double>(input[xp1 + 1]); double delta = rxps - static_cast<double>(xp1); xsum += imgXp1 + delta * (imgXp2 - imgXp1); } if (xm1 <= 0) // use boundary value { xsum += static_cast<double>(input[0]); } else // linearly interpolate { double imgXm1 = static_cast<double>(input[xm1]); double imgXm2 = static_cast<double>(input[xm1 - 1]); double delta = rxms - static_cast<double>(xm1); xsum += imgXm1 + delta * (imgXm1 - imgXm2); } output[x] = static_cast<T>(center + logBase * xsum); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpTricubic3.h
.h
16,434
529
// 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. Exact interpolation is achieved by setting catmullRom // to 'true', giving you the Catmull-Rom blending matrix. If a smooth // interpolation is desired, set catmullRom to 'false' to obtain B-spline // blending. namespace gte { template <typename Real> class IntpTricubic3 { public: // Construction. IntpTricubic3(int32_t xBound, int32_t yBound, int32_t zBound, Real xMin, Real xSpacing, Real yMin, Real ySpacing, Real zMin, Real zSpacing, Real const* F, bool catmullRom) : 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 4x4x4 block of data points are needed to construct // the tricubic interpolation. LogAssert(xBound >= 4 && yBound >= 4 && zBound >= 4 && 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; if (catmullRom) { mBlend[0][0] = (Real)0; mBlend[0][1] = (Real)-0.5; mBlend[0][2] = (Real)1; mBlend[0][3] = (Real)-0.5; mBlend[1][0] = (Real)1; mBlend[1][1] = (Real)0; mBlend[1][2] = (Real)-2.5; mBlend[1][3] = (Real)1.5; mBlend[2][0] = (Real)0; mBlend[2][1] = (Real)0.5; mBlend[2][2] = (Real)2; mBlend[2][3] = (Real)-1.5; mBlend[3][0] = (Real)0; mBlend[3][1] = (Real)0; mBlend[3][2] = (Real)-0.5; mBlend[3][3] = (Real)0.5; } else { mBlend[0][0] = (Real)1 / (Real)6; mBlend[0][1] = (Real)-3 / (Real)6; mBlend[0][2] = (Real)3 / (Real)6; mBlend[0][3] = (Real)-1 / (Real)6;; mBlend[1][0] = (Real)4 / (Real)6; mBlend[1][1] = (Real)0 / (Real)6; mBlend[1][2] = (Real)-6 / (Real)6; mBlend[1][3] = (Real)3 / (Real)6; mBlend[2][0] = (Real)1 / (Real)6; mBlend[2][1] = (Real)3 / (Real)6; mBlend[2][2] = (Real)3 / (Real)6; mBlend[2][3] = (Real)-3 / (Real)6; mBlend[3][0] = (Real)0 / (Real)6; mBlend[3][1] = (Real)0 / (Real)6; mBlend[3][2] = (Real)0 / (Real)6; mBlend[3][3] = (Real)1 / (Real)6; } } // 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, 4> U; U[0] = (Real)1; U[1] = xIndex - ix; U[2] = U[1] * U[1]; U[3] = U[1] * U[2]; std::array<Real, 4> V; V[0] = (Real)1; V[1] = yIndex - iy; V[2] = V[1] * V[1]; V[3] = V[1] * V[2]; std::array<Real, 4> W; W[0] = (Real)1; W[1] = zIndex - iz; W[2] = W[1] * W[1]; W[3] = W[1] * W[2]; // Compute P = M*U, Q = M*V, R = M*W. std::array<Real, 4> P, Q, R; for (int32_t row = 0; row < 4; ++row) { P[row] = (Real)0; Q[row] = (Real)0; R[row] = (Real)0; for (int32_t col = 0; col < 4; ++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 4x4x4 // subimage containing (x,y,z). --ix; --iy; --iz; Real result = (Real)0; for (int32_t slice = 0; slice < 4; ++slice) { int32_t zClamp = iz + slice; if (zClamp < 0) { zClamp = 0; } else if (zClamp > mZBound - 1) { zClamp = mZBound - 1; } for (int32_t row = 0; row < 4; ++row) { int32_t yClamp = iy + row; if (yClamp < 0) { yClamp = 0; } else if (yClamp > mYBound - 1) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 4; ++col) { int32_t xClamp = ix + col; if (xClamp < 0) { xClamp = 0; } else if (xClamp > mXBound - 1) { 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, 4> U; Real dx, xMult; switch (xOrder) { case 0: dx = xIndex - ix; U[0] = (Real)1; U[1] = dx; U[2] = dx * U[1]; U[3] = dx * U[2]; xMult = (Real)1; break; case 1: dx = xIndex - ix; U[0] = (Real)0; U[1] = (Real)1; U[2] = (Real)2 * dx; U[3] = (Real)3 * dx * dx; xMult = mInvXSpacing; break; case 2: dx = xIndex - ix; U[0] = (Real)0; U[1] = (Real)0; U[2] = (Real)2; U[3] = (Real)6 * dx; xMult = mInvXSpacing * mInvXSpacing; break; case 3: U[0] = (Real)0; U[1] = (Real)0; U[2] = (Real)0; U[3] = (Real)6; xMult = mInvXSpacing * mInvXSpacing * mInvXSpacing; break; default: return (Real)0; } std::array<Real, 4> V; Real dy, yMult; switch (yOrder) { case 0: dy = yIndex - iy; V[0] = (Real)1; V[1] = dy; V[2] = dy * V[1]; V[3] = dy * V[2]; yMult = (Real)1; break; case 1: dy = yIndex - iy; V[0] = (Real)0; V[1] = (Real)1; V[2] = (Real)2 * dy; V[3] = (Real)3 * dy * dy; yMult = mInvYSpacing; break; case 2: dy = yIndex - iy; V[0] = (Real)0; V[1] = (Real)0; V[2] = (Real)2; V[3] = (Real)6 * dy; yMult = mInvYSpacing * mInvYSpacing; break; case 3: V[0] = (Real)0; V[1] = (Real)0; V[2] = (Real)0; V[3] = (Real)6; yMult = mInvYSpacing * mInvYSpacing * mInvYSpacing; break; default: return (Real)0; } std::array<Real, 4> W; Real dz, zMult; switch (zOrder) { case 0: dz = zIndex - iz; W[0] = (Real)1; W[1] = dz; W[2] = dz * W[1]; W[3] = dz * W[2]; zMult = (Real)1; break; case 1: dz = zIndex - iz; W[0] = (Real)0; W[1] = (Real)1; W[2] = (Real)2 * dz; W[3] = (Real)3 * dz * dz; zMult = mInvZSpacing; break; case 2: dz = zIndex - iz; W[0] = (Real)0; W[1] = (Real)0; W[2] = (Real)2; W[3] = (Real)6 * dz; zMult = mInvZSpacing * mInvZSpacing; break; case 3: W[0] = (Real)0; W[1] = (Real)0; W[2] = (Real)0; W[3] = (Real)6; zMult = mInvZSpacing * mInvZSpacing * mInvZSpacing; break; default: return (Real)0; } // Compute P = M*U, Q = M*V, and R = M*W. std::array<Real, 4> P, Q, R; for (int32_t row = 0; row < 4; ++row) { P[row] = (Real)0; Q[row] = (Real)0; R[row] = (Real)0; for (int32_t col = 0; col < 4; ++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 4x4x4 // subimage containing (x,y,z). --ix; --iy; --iz; Real result = (Real)0; for (int32_t slice = 0; slice < 4; ++slice) { int32_t zClamp = iz + slice; if (zClamp < 0) { zClamp = 0; } else if (zClamp > mZBound - 1) { zClamp = mZBound - 1; } for (int32_t row = 0; row < 4; ++row) { int32_t yClamp = iy + row; if (yClamp < 0) { yClamp = 0; } else if (yClamp > mYBound - 1) { yClamp = mYBound - 1; } for (int32_t col = 0; col < 4; ++col) { int32_t xClamp = ix + col; if (xClamp < 0) { xClamp = 0; } else if (xClamp > mXBound - 1) { 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, 4>, 4> mBlend; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/FastMarch3.h
.h
23,130
610
// 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/FastMarch.h> #include <Mathematics/Math.h> // The topic of fast marching methods are discussed in the book // Level Set Methods and Fast Marching Methods: // Evolving Interfaces in Computational Geometry, Fluid Mechanics, // Computer Vision, and Materials Science // J.A. Sethian, // Cambridge University Press, 1999 namespace gte { template <typename Real> class FastMarch3 : public FastMarch<Real> { public: // Construction and destruction. FastMarch3(size_t xBound, size_t yBound, size_t zBound, Real xSpacing, Real ySpacing, Real zSpacing, std::vector<size_t> const& seeds, std::vector<Real> const& speeds) : FastMarch<Real>(xBound * yBound * zBound, seeds, speeds) { Initialize(xBound, yBound, zBound, xSpacing, ySpacing, zSpacing); } FastMarch3(size_t xBound, size_t yBound, size_t zBound, Real xSpacing, Real ySpacing, Real zSpacing, std::vector<size_t> const& seeds, Real speed) : FastMarch<Real>(xBound * yBound * zBound, seeds, speed) { Initialize(xBound, yBound, zBound, xSpacing, ySpacing, zSpacing); } virtual ~FastMarch3() { } // Member access. inline size_t GetXBound() const { return mXBound; } inline size_t GetYBound() const { return mYBound; } inline size_t GetZBound() const { return mZBound; } inline Real GetXSpacing() const { return mXSpacing; } inline Real GetYSpacing() const { return mYSpacing; } inline Real GetZSpacing() const { return mZSpacing; } inline size_t Index(size_t x, size_t y, size_t z) const { return x + mXBound * (y + mYBound * z); } // Voxel classification. virtual void GetBoundary(std::vector<size_t>& boundary) const override { for (size_t i = 0; i < this->mQuantity; ++i) { if (this->IsValid(i) && !this->IsTrial(i)) { if (this->IsTrial(i - 1) || this->IsTrial(i + 1) || this->IsTrial(i - mXBound) || this->IsTrial(i + mXBound) || this->IsTrial(i - mXYBound) || this->IsTrial(i + mXYBound)) { boundary.push_back(i); } } } } virtual bool IsBoundary(size_t i) const override { if (this->IsValid(i) && !this->IsTrial(i)) { if (this->IsTrial(i - 1) || this->IsTrial(i + 1) || this->IsTrial(i - mXBound) || this->IsTrial(i + mXBound) || this->IsTrial(i - mXYBound) || this->IsTrial(i + mXYBound)) { return true; } } return false; } // Run one step of the fast marching algorithm. virtual void Iterate() override { // Remove the minimum trial value from the heap. size_t i; Real value; this->mHeap.Remove(i, value); // Promote the trial value to a known value. The value was // negative but is now nonnegative (the heap stores only // nonnegative numbers). this->mTrials[i] = nullptr; // All trial pixels must be updated. All far neighbors must // become trial pixels. size_t iM1 = i - 1; if (this->IsTrial(iM1)) { ComputeTime(iM1); this->mHeap.Update(this->mTrials[iM1], this->mTimes[iM1]); } else if (this->IsFar(iM1)) { ComputeTime(iM1); this->mTrials[iM1] = this->mHeap.Insert(iM1, this->mTimes[iM1]); } size_t iP1 = i + 1; if (this->IsTrial(iP1)) { ComputeTime(iP1); this->mHeap.Update(this->mTrials[iP1], this->mTimes[iP1]); } else if (this->IsFar(iP1)) { ComputeTime(iP1); this->mTrials[iP1] = this->mHeap.Insert(iP1, this->mTimes[iP1]); } size_t iMXB = i - mXBound; if (this->IsTrial(iMXB)) { ComputeTime(iMXB); this->mHeap.Update(this->mTrials[iMXB], this->mTimes[iMXB]); } else if (this->IsFar(iMXB)) { ComputeTime(iMXB); this->mTrials[iMXB] = this->mHeap.Insert(iMXB, this->mTimes[iMXB]); } size_t iPXB = i + mXBound; if (this->IsTrial(iPXB)) { ComputeTime(iPXB); this->mHeap.Update(this->mTrials[iPXB], this->mTimes[iPXB]); } else if (this->IsFar(iPXB)) { ComputeTime(iPXB); this->mTrials[iPXB] = this->mHeap.Insert(iPXB, this->mTimes[iPXB]); } size_t iMXYB = i - mXYBound; if (this->IsTrial(iMXYB)) { ComputeTime(iMXYB); this->mHeap.Update(this->mTrials[iMXYB], this->mTimes[iMXYB]); } else if (this->IsFar(iMXYB)) { ComputeTime(iMXYB); this->mTrials[iMXYB] = this->mHeap.Insert(iMXYB, this->mTimes[iMXYB]); } size_t iPXYB = i + mXYBound; if (this->IsTrial(iPXYB)) { ComputeTime(iPXYB); this->mHeap.Update(this->mTrials[iPXYB], this->mTimes[iPXYB]); } else if (this->IsFar(iPXYB)) { ComputeTime(iPXYB); this->mTrials[iPXYB] = this->mHeap.Insert(iPXYB, this->mTimes[iPXYB]); } } protected: // Called by the constructors. void Initialize(size_t xBound, size_t yBound, size_t zBound, Real xSpacing, Real ySpacing, Real zSpacing) { mXBound = xBound; mYBound = yBound; mZBound = zBound; mXYBound = xBound * yBound; mXBoundM1 = mXBound - 1; mYBoundM1 = mYBound - 1; mZBoundM1 = mZBound - 1; mXSpacing = xSpacing; mYSpacing = ySpacing; mZSpacing = zSpacing; mInvXSpacing = (Real)1 / xSpacing; mInvYSpacing = (Real)1 / ySpacing; mInvZSpacing = (Real)1 / zSpacing; // Boundary pixels are marked as zero speed to allow us to avoid // having to process the boundary pixels separately during the // iteration. size_t x, y, z, i; // vertex (0,0,0) i = Index(0, 0, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (xmax,0,0) i = Index(mXBoundM1, 0, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (0,ymax,0) i = Index(0, mYBoundM1, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (xmax,ymax,0) i = Index(mXBoundM1, mYBoundM1, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (0,0,zmax) i = Index(0, 0, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (xmax,0,zmax) i = Index(mXBoundM1, 0, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (0,ymax,zmax) i = Index(0, mYBoundM1, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // vertex (xmax,ymax,zmax) i = Index(mXBoundM1, mYBoundM1, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); // edges (x,0,0) and (x,ymax,0) for (x = 0; x < mXBound; ++x) { i = Index(x, 0, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); i = Index(x, mYBoundM1, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); } // edges (0,y,0) and (xmax,y,0) for (y = 0; y < mYBound; ++y) { i = Index(0, y, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); i = Index(mXBoundM1, y, 0); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); } // edges (x,0,zmax) and (x,ymax,zmax) for (x = 0; x < mXBound; ++x) { i = Index(x, 0, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); i = Index(x, mYBoundM1, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); } // edges (0,y,zmax) and (xmax,y,zmax) for (y = 0; y < mYBound; ++y) { i = Index(0, y, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); i = Index(mXBoundM1, y, mZBoundM1); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); } // edges (0,0,z) and (xmax,0,z) for (z = 0; z < mZBound; ++z) { i = Index(0, 0, z); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); i = Index(mXBoundM1, 0, z); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); } // edges (0,ymax,z) and (xmax,ymax,z) for (z = 0; z < mZBound; ++z) { i = Index(0, mYBoundM1, z); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); i = Index(mXBoundM1, mYBoundM1, z); this->mInvSpeeds[i] = std::numeric_limits<Real>::max(); this->mTimes[i] = -std::numeric_limits<Real>::max(); } // Compute the first batch of trial pixels. These are pixels a grid // distance of one away from the seed pixels. for (z = 1; z < mZBoundM1; ++z) { for (y = 1; y < mYBoundM1; ++y) { for (x = 1; x < mXBoundM1; ++x) { i = Index(x, y, z); if (this->IsFar(i)) { if ((this->IsValid(i - 1) && !this->IsTrial(i - 1)) || (this->IsValid(i + 1) && !this->IsTrial(i + 1)) || (this->IsValid(i - mXBound) && !this->IsTrial(i - mXBound)) || (this->IsValid(i + mXBound) && !this->IsTrial(i + mXBound)) || (this->IsValid(i - mXYBound) && !this->IsTrial(i - mXYBound)) || (this->IsValid(i + mXYBound) && !this->IsTrial(i + mXYBound))) { ComputeTime(i); this->mTrials[i] = this->mHeap.Insert(i, this->mTimes[i]); } } } } } } // Called by Iterate(). void ComputeTime(size_t i) { bool hasXTerm; Real xConst; if (this->IsValid(i - 1)) { hasXTerm = true; xConst = this->mTimes[i - 1]; if (this->IsValid(i + 1)) { if (this->mTimes[i + 1] < xConst) { xConst = this->mTimes[i + 1]; } } } else if (this->IsValid(i + 1)) { hasXTerm = true; xConst = this->mTimes[i + 1]; } else { hasXTerm = false; xConst = (Real)0; } bool hasYTerm; Real yConst; if (this->IsValid(i - mXBound)) { hasYTerm = true; yConst = this->mTimes[i - mXBound]; if (this->IsValid(i + mXBound)) { if (this->mTimes[i + mXBound] < yConst) { yConst = this->mTimes[i + mXBound]; } } } else if (this->IsValid(i + mXBound)) { hasYTerm = true; yConst = this->mTimes[i + mXBound]; } else { hasYTerm = false; yConst = (Real)0; } bool hasZTerm; Real zConst; if (this->IsValid(i - mXYBound)) { hasZTerm = true; zConst = this->mTimes[i - mXYBound]; if (this->IsValid(i + mXYBound)) { if (this->mTimes[i + mXYBound] < zConst) { zConst = this->mTimes[i + mXYBound]; } } } else if (this->IsValid(i + mXYBound)) { hasZTerm = true; zConst = this->mTimes[i + mXYBound]; } else { hasZTerm = false; zConst = (Real)0; } Real sum, diff, discr; if (hasXTerm) { if (hasYTerm) { if (hasZTerm) { // xyz sum = xConst + yConst + zConst; discr = (Real)3 * this->mInvSpeeds[i] * this->mInvSpeeds[i]; diff = xConst - yConst; discr -= diff * diff; diff = xConst - zConst; discr -= diff * diff; diff = yConst - zConst; discr -= diff * diff; if (discr >= (Real)0) { // The quadratic equation has a real-valued // solution. Choose the largest positive root for // the crossing time. this->mTimes[i] = (sum + std::sqrt(discr)) / (Real)3; } else { // The quadratic equation does not have a // real-valued solution. This can happen when the // speed is so large that the time gradient has // very small length, which means that the time // has not changed significantly from the // neighbors to the current pixel. Just choose // the maximum time of the neighbors. (Is there a // better choice?) this->mTimes[i] = xConst; if (yConst > this->mTimes[i]) { this->mTimes[i] = yConst; } if (zConst > this->mTimes[i]) { this->mTimes[i] = zConst; } } } else { // xy sum = xConst + yConst; diff = xConst - yConst; discr = (Real)2 * this->mInvSpeeds[i] * this->mInvSpeeds[i] - diff * diff; if (discr >= (Real)0) { // The quadratic equation has a real-valued // solution. Choose the largest positive root for // the crossing time. this->mTimes[i] = (Real)0.5 * (sum + std::sqrt(discr)); } else { // The quadratic equation does not have a // real-valued solution. This can happen when the // speed is so large that the time gradient has // very small length, which means that the time // has not changed significantly from the // neighbors to the current pixel. Just choose // the maximum time of the neighbors. (Is there a // better choice?) this->mTimes[i] = (diff >= (Real)0 ? xConst : yConst); } } } else { if (hasZTerm) { // xz sum = xConst + zConst; diff = xConst - zConst; discr = (Real)2 * this->mInvSpeeds[i] * this->mInvSpeeds[i] - diff * diff; if (discr >= (Real)0) { // The quadratic equation has a real-valued // solution. Choose the largest positive root for // the crossing time. this->mTimes[i] = (Real)0.5 * (sum + std::sqrt(discr)); } else { // The quadratic equation does not have a // real-valued solution. This can happen when the // speed is so large that the time gradient has // very small length, which means that the time // has not changed significantly from the // neighbors to the current pixel. Just choose // the maximum time of the neighbors. (Is there a // better choice?) this->mTimes[i] = (diff >= (Real)0 ? xConst : zConst); } } else { // x this->mTimes[i] = this->mInvSpeeds[i] + xConst; } } } else { if (hasYTerm) { if (hasZTerm) { // yz sum = yConst + zConst; diff = yConst - zConst; discr = (Real)2 * this->mInvSpeeds[i] * this->mInvSpeeds[i] - diff * diff; if (discr >= (Real)0) { // The quadratic equation has a real-valued // solution. Choose the largest positive root for // the crossing time. this->mTimes[i] = (Real)0.5 * (sum + std::sqrt(discr)); } else { // The quadratic equation does not have a // real-valued solution. This can happen when the // speed is so large that the time gradient has // very small length, which means that the time // has not changed significantly from the // neighbors to the current pixel. Just choose // the maximum time of the neighbors. (Is there a // better choice?) this->mTimes[i] = (diff >= (Real)0 ? yConst : zConst); } } else { // y this->mTimes[i] = this->mInvSpeeds[i] + yConst; } } else { if (hasZTerm) { // z this->mTimes[i] = this->mInvSpeeds[i] + zConst; } else { // Assert: The pixel must have at least one valid // neighbor. } } } } size_t mXBound, mYBound, mZBound, mXYBound; size_t mXBoundM1, mYBoundM1, mZBoundM1; Real mXSpacing, mYSpacing, mZSpacing; Real mInvXSpacing, mInvYSpacing, mInvZSpacing; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointCanonicalBox.h
.h
2,653
81
// 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/CanonicalBox.h> // Compute the distance from a point to a solid canonical box in nD. // // The canonical box has center at the origin and is aligned with the // coordinate axes. The extents are E = (e[0],e[1],...,e[n-1]). A box // point is Y = (y[0],y[1],...,y[n-1]) with |y[i]| <= e[i] for all i. // // The input point P 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>, CanonicalBox<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<Vector<N, T>, 2> closest; }; Result operator()(Vector<N, T> const& point, CanonicalBox<N, T> const& box) { Result result{}; result.closest[0] = point; result.closest[1] = point; result.sqrDistance = static_cast<T>(0); for (int32_t i = 0; i < N; ++i) { if (point[i] < -box.extent[i]) { T delta = result.closest[1][i] + box.extent[i]; result.sqrDistance += delta * delta; result.closest[1][i] = -box.extent[i]; } else if (point[i] > box.extent[i]) { T delta = result.closest[1][i] - box.extent[i]; result.sqrDistance += delta * delta; result.closest[1][i] = box.extent[i]; } } result.distance = std::sqrt(result.sqrDistance); return result; } }; // Template aliases for convenience. template <int32_t N, typename T> using DCPPointCanonicalBox = DCPQuery<T, Vector<N, T>, CanonicalBox<N, T>>; template <typename T> using DCPPoint2CanonicalBox2 = DCPPointCanonicalBox<2, T>; template <typename T> using DCPPoint3CanonicalBox3 = DCPPointCanonicalBox<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/PdeFilter1.h
.h
9,243
291
// 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/PdeFilter.h> #include <array> #include <limits> #include <vector> namespace gte { template <typename Real> class PdeFilter1 : public PdeFilter<Real> { public: // Abstract base class. PdeFilter1(int32_t xBound, Real xSpacing, Real const* data, int32_t const* mask, Real borderValue, typename PdeFilter<Real>::ScaleType scaleType) : PdeFilter<Real>(xBound, data, borderValue, scaleType), mXBound(xBound), mXSpacing(xSpacing), mInvDx((Real)1 / xSpacing), mHalfInvDx((Real)0.5 * mInvDx), mInvDxDx(mInvDx * mInvDx), mUm(0), mUz(0), mUp(0), mSrc(0), mDst(1), mMask(static_cast<size_t>(xBound) + 2), mHasMask(mask != nullptr) { // The mBuffer[] are ping-pong buffers for filtering. for (int32_t i = 0; i < 2; ++i) { mBuffer[i].resize(static_cast<size_t>(xBound) + 2); } for (int32_t x = 0, xp = 1, i = 0; x < mXBound; ++x, ++xp, ++i) { mBuffer[mSrc][xp] = this->mOffset + (data[i] - this->mMin) * this->mScale; mBuffer[mDst][xp] = (Real)0; mMask[xp] = (mHasMask ? mask[i] : 1); } // Assign values to the 1-pixel image border. if (this->mBorderValue != std::numeric_limits<Real>::max()) { AssignDirichletImageBorder(); } else { AssignNeumannImageBorder(); } // To handle masks that do not cover the entire image, assign // values to those pixels that are 8-neighbors of the mask pixels. if (mHasMask) { if (this->mBorderValue != std::numeric_limits<Real>::max()) { AssignDirichletMaskBorder(); } else { AssignNeumannMaskBorder(); } } } virtual ~PdeFilter1() { } // Member access. The internal 1D images for "data" and "mask" are // copies of the inputs to the constructor but padded with a 1-pixel // thick border to support filtering on the image boundary. These // images are of size (xbound+2). The correct lookups into the padded // arrays are handled internally. inline int32_t GetXBound() const { return mXBound; } inline Real GetXSpacing() const { return mXSpacing; } // Pixel access and derivative estimation. The lookups into the // padded data are handled correctly. The estimation involves only // the 3-tuple neighborhood of (x), where 0 <= x < xbound. TODO: If // larger neighborhoods are desired at a later date, the padding and // associated code must be adjusted accordingly. Real GetU(int32_t x) const { auto const& F = mBuffer[mSrc]; return F[static_cast<size_t>(x) + 1]; } Real GetUx(int32_t x) const { auto const& F = mBuffer[mSrc]; return mHalfInvDx * (F[static_cast<size_t>(x) + 2] - F[x]); } Real GetUxx(int32_t x) const { auto const& F = mBuffer[mSrc]; return mInvDxDx * (F[static_cast<size_t>(x) + 2] - (Real)2 * F[static_cast<size_t>(x) + 1] + F[x]); } int32_t GetMask(int32_t x) const { return mMask[static_cast<size_t>(x) + 1]; } protected: // Assign values to the 1-pixel image border. void AssignDirichletImageBorder() { int32_t xBp1 = mXBound + 1; // vertex (0,0) mBuffer[mSrc][0] = this->mBorderValue; mBuffer[mDst][0] = this->mBorderValue; if (mHasMask) { mMask[0] = 0; } // vertex (xmax,0) mBuffer[mSrc][xBp1] = this->mBorderValue; mBuffer[mDst][xBp1] = this->mBorderValue; if (mHasMask) { mMask[xBp1] = 0; } } void AssignNeumannImageBorder() { int32_t xBp1 = mXBound + 1; Real duplicate; // vertex (0,0) duplicate = mBuffer[mSrc][1]; mBuffer[mSrc][0] = duplicate; mBuffer[mDst][0] = duplicate; if (mHasMask) { mMask[0] = 0; } // vertex (xmax,0) duplicate = mBuffer[mSrc][mXBound]; mBuffer[mSrc][xBp1] = duplicate; mBuffer[mDst][xBp1] = duplicate; if (mHasMask) { mMask[xBp1] = 0; } } // Assign values to the 1-pixel mask border. void AssignDirichletMaskBorder() { for (int32_t x = 1; x <= mXBound; ++x) { if (mMask[x]) { continue; } for (int32_t i0 = 0, j0 = x - 1; i0 < 3; ++i0, ++j0) { if (mMask[j0]) { mBuffer[mSrc][x] = this->mBorderValue; mBuffer[mDst][x] = this->mBorderValue; break; } } } } void AssignNeumannMaskBorder() { // Recompute the values just outside the masked region. This // guarantees that derivative estimations use the current values // around the boundary. for (int32_t x = 1; x <= mXBound; ++x) { if (mMask[x]) { continue; } int32_t count = 0; Real average = (Real)0; for (int32_t i0 = 0, j0 = x - 1; i0 < 3; ++i0, ++j0) { if (mMask[j0]) { average += mBuffer[mSrc][j0]; ++count; } } if (count > 0) { average /= (Real)count; mBuffer[mSrc][x] = average; mBuffer[mDst][x] = average; } } } // This function recomputes the boundary values when Neumann // conditions are used. If a derived class overrides this, it must // call the base-class OnPreUpdate first. virtual void OnPreUpdate() override { if (mHasMask && this->mBorderValue == std::numeric_limits<Real>::max()) { // Neumann boundary conditions are in use, so recompute the // mask/ border. AssignNeumannMaskBorder(); } // else: No mask has been specified or Dirichlet boundary // conditions are in use. Nothing to do. } // Iterate over all the pixels and call OnUpdate(x) for each pixel // that is not masked out. virtual void OnUpdate() override { for (int32_t x = 1; x <= mXBound; ++x) { if (!mHasMask || mMask[x]) { OnUpdate(x); } } } // If a derived class overrides this, it must call the base-class // OnPostUpdate last. The base-class function swaps the buffers for // the next pass. virtual void OnPostUpdate() override { std::swap(mSrc, mDst); } // The per-pixel processing depends on the PDE algorithm. The (x) // must be in padded coordinates: 1 <= x <= xbound. virtual void OnUpdate(int32_t x) = 0; // Copy source data to temporary storage. void LookUp3(int32_t x) { auto const& F = mBuffer[mSrc]; mUm = F[static_cast<size_t>(x) - 1]; mUz = F[x]; mUp = F[static_cast<size_t>(x) + 1]; } // Image parameters. int32_t mXBound; Real mXSpacing; // dx Real mInvDx; // 1/dx Real mHalfInvDx; // 1/(2*dx) Real mInvDxDx; // 1/(dx*dx) // Temporary storage for 3-tuple neighborhood. In the notation mUx, // the x index is in {m,z,p}, referring to subtract 1 (m), no change // (z), or add 1 (p) to the appropriate index. Real mUm, mUz, mUp; // Successive iterations toggle between two buffers. std::array<std::vector<Real>, 2> mBuffer; int32_t mSrc, mDst; std::vector<int32_t> mMask; bool mHasMask; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/PdeFilter3.h
.h
33,034
952
// 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/PdeFilter.h> #include <Mathematics/Array3.h> #include <array> #include <limits> namespace gte { template <typename Real> class PdeFilter3 : public PdeFilter<Real> { public: // Abstract base class. PdeFilter3(int32_t xBound, int32_t yBound, int32_t zBound, Real xSpacing, Real ySpacing, Real zSpacing, Real const* data, int32_t const* mask, Real borderValue, typename PdeFilter<Real>::ScaleType scaleType) : PdeFilter<Real>(xBound * yBound * zBound, data, borderValue, scaleType), mXBound(xBound), mYBound(yBound), mZBound(zBound), mXSpacing(xSpacing), mYSpacing(ySpacing), mZSpacing(zSpacing), mInvDx((Real)1 / xSpacing), mInvDy((Real)1 / ySpacing), mInvDz((Real)1 / zSpacing), mHalfInvDx((Real)0.5 * mInvDx), mHalfInvDy((Real)0.5 * mInvDy), mHalfInvDz((Real)0.5 * mInvDz), mInvDxDx(mInvDx * mInvDx), mFourthInvDxDy(mHalfInvDx * mHalfInvDy), mFourthInvDxDz(mHalfInvDx * mHalfInvDz), mInvDyDy(mInvDy * mInvDy), mFourthInvDyDz(mHalfInvDy * mHalfInvDz), mInvDzDz(mInvDz * mInvDz), mUmmm(0), mUzmm(0), mUpmm(0), mUmzm(0), mUzzm(0), mUpzm(0), mUmpm(0), mUzpm(0), mUppm(0), mUmmz(0), mUzmz(0), mUpmz(0), mUmzz(0), mUzzz(0), mUpzz(0), mUmpz(0), mUzpz(0), mUppz(0), mUmmp(0), mUzmp(0), mUpmp(0), mUmzp(0), mUzzp(0), mUpzp(0), mUmpp(0), mUzpp(0), mUppp(0), mSrc(0), mDst(1), mMask(static_cast<size_t>(xBound) + 2, static_cast<size_t>(yBound) + 2, static_cast<size_t>(zBound) + 2), mHasMask(mask != nullptr) { for (int32_t i = 0; i < 2; ++i) { mBuffer[i] = Array3<Real>(static_cast<size_t>(xBound) + 2, static_cast<size_t>(yBound) + 2, static_cast<size_t>(zBound) + 2); } // The mBuffer[] are ping-pong buffers for filtering. for (int32_t z = 0, zp = 1, i = 0; z < mZBound; ++z, ++zp) { for (int32_t y = 0, yp = 1; y < mYBound; ++y, ++yp) { for (int32_t x = 0, xp = 1; x < mXBound; ++x, ++xp, ++i) { mBuffer[mSrc][zp][yp][xp] = this->mOffset + (data[i] - this->mMin) * this->mScale; mBuffer[mDst][zp][yp][xp] = (Real)0; mMask[zp][yp][xp] = (mHasMask ? mask[i] : 1); } } } // Assign values to the 1-voxel thick border. if (this->mBorderValue != std::numeric_limits<Real>::max()) { AssignDirichletImageBorder(); } else { AssignNeumannImageBorder(); } // To handle masks that do not cover the entire image, assign // values to those voxels that are 26-neighbors of the mask // voxels. if (mHasMask) { if (this->mBorderValue != std::numeric_limits<Real>::max()) { AssignDirichletMaskBorder(); } else { AssignNeumannMaskBorder(); } } } virtual ~PdeFilter3() { } // Member access. The internal 2D images for "data" and "mask" are // copies of the inputs to the constructor but padded with a 1-voxel // thick border to support filtering on the image boundary. These // images are of size (xbound+2)-by-(ybound+2)-by-(zbound+2). The // correct lookups into the padded arrays are handled internally. inline int32_t GetXBound() const { return mXBound; } inline int32_t GetYBound() const { return mYBound; } inline int32_t GetZBound() const { return mZBound; } inline Real GetXSpacing() const { return mXSpacing; } inline Real GetYSpacing() const { return mYSpacing; } inline Real GetZSpacing() const { return mZSpacing; } // Voxel access and derivative estimation. The lookups into the // padded data are handled correctly. The estimation involves only // the 3-by-3-by-3 neighborhood of (x,y,z), where 0 <= x < xbound, // 0 <= y < ybound and 0 <= z < zbound. TODO: If larger neighborhoods // are desired at a later date, the padding and associated code must // be adjusted accordingly. Real GetU(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, yp1 = y + 1, zp1 = z + 1; return F[zp1][yp1][xp1]; } Real GetUx(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp2 = x + 2, yp1 = y + 1, zp1 = z + 1; return mHalfInvDx * (F[zp1][yp1][xp2] - F[zp1][yp1][x]); } Real GetUy(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, yp2 = y + 2, zp1 = z + 1; return mHalfInvDy * (F[zp1][yp2][xp1] - F[zp1][y][xp1]); } Real GetUz(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, yp1 = y + 1, zp2 = z + 2; return mHalfInvDz * (F[zp2][yp1][xp1] - F[z][yp1][xp1]); } Real GetUxx(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, xp2 = x + 2, yp1 = y + 1, zp1 = z + 1; return mInvDxDx * (F[zp1][yp1][xp2] - (Real)2 * F[zp1][yp1][xp1] + F[zp1][yp1][x]); } Real GetUxy(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp2 = x + 2, yp2 = y + 2, zp1 = z + 1; return mFourthInvDxDy * (F[zp1][y][x] - F[zp1][y][xp2] + F[zp1][yp2][xp2] - F[zp1][yp2][x]); } Real GetUxz(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp2 = x + 2, yp1 = y + 1, zp2 = z + 2; return mFourthInvDxDz * (F[z][yp1][x] - F[z][yp1][xp2] + F[zp2][yp1][xp2] - F[zp2][yp1][x]); } Real GetUyy(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, yp1 = y + 1, yp2 = y + 2, zp1 = z + 1; return mInvDyDy * (F[zp1][yp2][xp1] - (Real)2 * F[zp1][yp1][xp1] + F[zp1][y][xp1]); } Real GetUyz(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, yp2 = y + 2, zp2 = z + 2; return mFourthInvDyDz * (F[z][y][xp1] - F[z][yp2][xp1] + F[zp2][yp2][xp1] - F[zp2][y][xp1]); } Real GetUzz(int32_t x, int32_t y, int32_t z) const { auto const& F = mBuffer[mSrc]; int32_t xp1 = x + 1, yp1 = y + 1, zp1 = z + 1, zp2 = z + 2; return mInvDzDz * (F[zp2][yp1][xp1] - (Real)2 * F[zp1][yp1][xp1] + F[z][yp1][xp1]); } int32_t GetMask(int32_t x, int32_t y, int32_t z) const { int32_t xp1 = x + 1, yp1 = y + 1, zp1 = z + 1; return mMask[zp1][yp1][xp1]; } protected: // Assign values to the 1-voxel image border. void AssignDirichletImageBorder() { int32_t xBp1 = mXBound + 1, yBp1 = mYBound + 1, zBp1 = mZBound + 1; int32_t x, y, z; // vertex (0,0,0) mBuffer[mSrc][0][0][0] = this->mBorderValue; mBuffer[mDst][0][0][0] = this->mBorderValue; if (mHasMask) { mMask[0][0][0] = 0; } // vertex (xmax,0,0) mBuffer[mSrc][0][0][xBp1] = this->mBorderValue; mBuffer[mDst][0][0][xBp1] = this->mBorderValue; if (mHasMask) { mMask[0][0][xBp1] = 0; } // vertex (0,ymax,0) mBuffer[mSrc][0][yBp1][0] = this->mBorderValue; mBuffer[mDst][0][yBp1][0] = this->mBorderValue; if (mHasMask) { mMask[0][yBp1][0] = 0; } // vertex (xmax,ymax,0) mBuffer[mSrc][0][yBp1][xBp1] = this->mBorderValue; mBuffer[mDst][0][yBp1][xBp1] = this->mBorderValue; if (mHasMask) { mMask[0][yBp1][xBp1] = 0; } // vertex (0,0,zmax) mBuffer[mSrc][zBp1][0][0] = this->mBorderValue; mBuffer[mDst][zBp1][0][0] = this->mBorderValue; if (mHasMask) { mMask[zBp1][0][0] = 0; } // vertex (xmax,0,zmax) mBuffer[mSrc][zBp1][0][xBp1] = this->mBorderValue; mBuffer[mDst][zBp1][0][xBp1] = this->mBorderValue; if (mHasMask) { mMask[zBp1][0][xBp1] = 0; } // vertex (0,ymax,zmax) mBuffer[mSrc][zBp1][yBp1][0] = this->mBorderValue; mBuffer[mDst][zBp1][yBp1][0] = this->mBorderValue; if (mHasMask) { mMask[zBp1][yBp1][0] = 0; } // vertex (xmax,ymax,zmax) mBuffer[mSrc][zBp1][yBp1][xBp1] = this->mBorderValue; mBuffer[mDst][zBp1][yBp1][xBp1] = this->mBorderValue; if (mHasMask) { mMask[zBp1][yBp1][xBp1] = 0; } // edges (x,0,0) and (x,ymax,0) for (x = 1; x <= mXBound; ++x) { mBuffer[mSrc][0][0][x] = this->mBorderValue; mBuffer[mDst][0][0][x] = this->mBorderValue; if (mHasMask) { mMask[0][0][x] = 0; } mBuffer[mSrc][0][yBp1][x] = this->mBorderValue; mBuffer[mDst][0][yBp1][x] = this->mBorderValue; if (mHasMask) { mMask[0][yBp1][x] = 0; } } // edges (0,y,0) and (xmax,y,0) for (y = 1; y <= mYBound; ++y) { mBuffer[mSrc][0][y][0] = this->mBorderValue; mBuffer[mDst][0][y][0] = this->mBorderValue; if (mHasMask) { mMask[0][y][0] = 0; } mBuffer[mSrc][0][y][xBp1] = this->mBorderValue; mBuffer[mDst][0][y][xBp1] = this->mBorderValue; if (mHasMask) { mMask[0][y][xBp1] = 0; } } // edges (x,0,zmax) and (x,ymax,zmax) for (x = 1; x <= mXBound; ++x) { mBuffer[mSrc][zBp1][0][x] = this->mBorderValue; mBuffer[mDst][zBp1][0][x] = this->mBorderValue; if (mHasMask) { mMask[zBp1][0][x] = 0; } mBuffer[mSrc][zBp1][yBp1][x] = this->mBorderValue; mBuffer[mDst][zBp1][yBp1][x] = this->mBorderValue; if (mHasMask) { mMask[zBp1][yBp1][x] = 0; } } // edges (0,y,zmax) and (xmax,y,zmax) for (y = 1; y <= mYBound; ++y) { mBuffer[mSrc][zBp1][y][0] = this->mBorderValue; mBuffer[mDst][zBp1][y][0] = this->mBorderValue; if (mHasMask) { mMask[zBp1][y][0] = 0; } mBuffer[mSrc][zBp1][y][xBp1] = this->mBorderValue; mBuffer[mDst][zBp1][y][xBp1] = this->mBorderValue; if (mHasMask) { mMask[zBp1][y][xBp1] = 0; } } // edges (0,0,z) and (xmax,0,z) for (z = 1; z <= mZBound; ++z) { mBuffer[mSrc][z][0][0] = this->mBorderValue; mBuffer[mDst][z][0][0] = this->mBorderValue; if (mHasMask) { mMask[z][0][0] = 0; } mBuffer[mSrc][z][0][xBp1] = this->mBorderValue; mBuffer[mDst][z][0][xBp1] = this->mBorderValue; if (mHasMask) { mMask[z][0][xBp1] = 0; } } // edges (0,ymax,z) and (xmax,ymax,z) for (z = 1; z <= mZBound; ++z) { mBuffer[mSrc][z][yBp1][0] = this->mBorderValue; mBuffer[mDst][z][yBp1][0] = this->mBorderValue; if (mHasMask) { mMask[z][yBp1][0] = 0; } mBuffer[mSrc][z][yBp1][xBp1] = this->mBorderValue; mBuffer[mDst][z][yBp1][xBp1] = this->mBorderValue; if (mHasMask) { mMask[z][yBp1][xBp1] = 0; } } // faces (x,y,0) and (x,y,zmax) for (y = 1; y <= mYBound; ++y) { for (x = 1; x <= mXBound; ++x) { mBuffer[mSrc][0][y][x] = this->mBorderValue; mBuffer[mDst][0][y][x] = this->mBorderValue; if (mHasMask) { mMask[0][y][x] = 0; } mBuffer[mSrc][zBp1][y][x] = this->mBorderValue; mBuffer[mDst][zBp1][y][x] = this->mBorderValue; if (mHasMask) { mMask[zBp1][y][x] = 0; } } } // faces (x,0,z) and (x,ymax,z) for (z = 1; z <= mZBound; ++z) { for (x = 1; x <= mXBound; ++x) { mBuffer[mSrc][z][0][x] = this->mBorderValue; mBuffer[mDst][z][0][x] = this->mBorderValue; if (mHasMask) { mMask[z][0][x] = 0; } mBuffer[mSrc][z][yBp1][x] = this->mBorderValue; mBuffer[mDst][z][yBp1][x] = this->mBorderValue; if (mHasMask) { mMask[z][yBp1][x] = 0; } } } // faces (0,y,z) and (xmax,y,z) for (z = 1; z <= mZBound; ++z) { for (y = 1; y <= mYBound; ++y) { mBuffer[mSrc][z][y][0] = this->mBorderValue; mBuffer[mDst][z][y][0] = this->mBorderValue; if (mHasMask) { mMask[z][y][0] = 0; } mBuffer[mSrc][z][y][xBp1] = this->mBorderValue; mBuffer[mDst][z][y][xBp1] = this->mBorderValue; if (mHasMask) { mMask[z][y][xBp1] = 0; } } } } void AssignNeumannImageBorder() { int32_t xBp1 = mXBound + 1, yBp1 = mYBound + 1, zBp1 = mZBound + 1; int32_t x, y, z; Real duplicate; // vertex (0,0,0) duplicate = mBuffer[mSrc][1][1][1]; mBuffer[mSrc][0][0][0] = duplicate; mBuffer[mDst][0][0][0] = duplicate; if (mHasMask) { mMask[0][0][0] = 0; } // vertex (xmax,0,0) duplicate = mBuffer[mSrc][1][1][mXBound]; mBuffer[mSrc][0][0][xBp1] = duplicate; mBuffer[mDst][0][0][xBp1] = duplicate; if (mHasMask) { mMask[0][0][xBp1] = 0; } // vertex (0,ymax,0) duplicate = mBuffer[mSrc][1][mYBound][1]; mBuffer[mSrc][0][yBp1][0] = duplicate; mBuffer[mDst][0][yBp1][0] = duplicate; if (mHasMask) { mMask[0][yBp1][0] = 0; } // vertex (xmax,ymax,0) duplicate = mBuffer[mSrc][1][mYBound][mXBound]; mBuffer[mSrc][0][yBp1][xBp1] = duplicate; mBuffer[mDst][0][yBp1][xBp1] = duplicate; if (mHasMask) { mMask[0][yBp1][xBp1] = 0; } // vertex (0,0,zmax) duplicate = mBuffer[mSrc][mZBound][1][1]; mBuffer[mSrc][zBp1][0][0] = duplicate; mBuffer[mDst][zBp1][0][0] = duplicate; if (mHasMask) { mMask[zBp1][0][0] = 0; } // vertex (xmax,0,zmax) duplicate = mBuffer[mSrc][mZBound][1][mXBound]; mBuffer[mSrc][zBp1][0][xBp1] = duplicate; mBuffer[mDst][zBp1][0][xBp1] = duplicate; if (mHasMask) { mMask[zBp1][0][xBp1] = 0; } // vertex (0,ymax,zmax) duplicate = mBuffer[mSrc][mZBound][mYBound][1]; mBuffer[mSrc][zBp1][yBp1][0] = duplicate; mBuffer[mDst][zBp1][yBp1][0] = duplicate; if (mHasMask) { mMask[zBp1][yBp1][0] = 0; } // vertex (xmax,ymax,zmax) duplicate = mBuffer[mSrc][mZBound][mYBound][mXBound]; mBuffer[mSrc][zBp1][yBp1][xBp1] = duplicate; mBuffer[mDst][zBp1][yBp1][xBp1] = duplicate; if (mHasMask) { mMask[zBp1][yBp1][xBp1] = 0; } // edges (x,0,0) and (x,ymax,0) for (x = 1; x <= mXBound; ++x) { duplicate = mBuffer[mSrc][1][1][x]; mBuffer[mSrc][0][0][x] = duplicate; mBuffer[mDst][0][0][x] = duplicate; if (mHasMask) { mMask[0][0][x] = 0; } duplicate = mBuffer[mSrc][1][mYBound][x]; mBuffer[mSrc][0][yBp1][x] = duplicate; mBuffer[mDst][0][yBp1][x] = duplicate; if (mHasMask) { mMask[0][yBp1][x] = 0; } } // edges (0,y,0) and (xmax,y,0) for (y = 1; y <= mYBound; ++y) { duplicate = mBuffer[mSrc][1][y][1]; mBuffer[mSrc][0][y][0] = duplicate; mBuffer[mDst][0][y][0] = duplicate; if (mHasMask) { mMask[0][y][0] = 0; } duplicate = mBuffer[mSrc][1][y][mXBound]; mBuffer[mSrc][0][y][xBp1] = duplicate; mBuffer[mDst][0][y][xBp1] = duplicate; if (mHasMask) { mMask[0][y][xBp1] = 0; } } // edges (x,0,zmax) and (x,ymax,zmax) for (x = 1; x <= mXBound; ++x) { duplicate = mBuffer[mSrc][mZBound][1][x]; mBuffer[mSrc][zBp1][0][x] = duplicate; mBuffer[mDst][zBp1][0][x] = duplicate; if (mHasMask) { mMask[zBp1][0][x] = 0; } duplicate = mBuffer[mSrc][mZBound][mYBound][x]; mBuffer[mSrc][zBp1][yBp1][x] = duplicate; mBuffer[mDst][zBp1][yBp1][x] = duplicate; if (mHasMask) { mMask[zBp1][yBp1][x] = 0; } } // edges (0,y,zmax) and (xmax,y,zmax) for (y = 1; y <= mYBound; ++y) { duplicate = mBuffer[mSrc][mZBound][y][1]; mBuffer[mSrc][zBp1][y][0] = duplicate; mBuffer[mDst][zBp1][y][0] = duplicate; if (mHasMask) { mMask[zBp1][y][0] = 0; } duplicate = mBuffer[mSrc][mZBound][y][mXBound]; mBuffer[mSrc][zBp1][y][xBp1] = duplicate; mBuffer[mDst][zBp1][y][xBp1] = duplicate; if (mHasMask) { mMask[zBp1][y][xBp1] = 0; } } // edges (0,0,z) and (xmax,0,z) for (z = 1; z <= mZBound; ++z) { duplicate = mBuffer[mSrc][z][1][1]; mBuffer[mSrc][z][0][0] = duplicate; mBuffer[mDst][z][0][0] = duplicate; if (mHasMask) { mMask[z][0][0] = 0; } duplicate = mBuffer[mSrc][z][1][mXBound]; mBuffer[mSrc][z][0][xBp1] = duplicate; mBuffer[mDst][z][0][xBp1] = duplicate; if (mHasMask) { mMask[z][0][xBp1] = 0; } } // edges (0,ymax,z) and (xmax,ymax,z) for (z = 1; z <= mZBound; ++z) { duplicate = mBuffer[mSrc][z][mYBound][1]; mBuffer[mSrc][z][yBp1][0] = duplicate; mBuffer[mDst][z][yBp1][0] = duplicate; if (mHasMask) { mMask[z][yBp1][0] = 0; } duplicate = mBuffer[mSrc][z][mYBound][mXBound]; mBuffer[mSrc][z][yBp1][xBp1] = duplicate; mBuffer[mDst][z][yBp1][xBp1] = duplicate; if (mHasMask) { mMask[z][yBp1][xBp1] = 0; } } // faces (x,y,0) and (x,y,zmax) for (y = 1; y <= mYBound; ++y) { for (x = 1; x <= mXBound; ++x) { duplicate = mBuffer[mSrc][1][y][x]; mBuffer[mSrc][0][y][x] = duplicate; mBuffer[mDst][0][y][x] = duplicate; if (mHasMask) { mMask[0][y][x] = 0; } duplicate = mBuffer[mSrc][mZBound][y][x]; mBuffer[mSrc][zBp1][y][x] = duplicate; mBuffer[mDst][zBp1][y][x] = duplicate; if (mHasMask) { mMask[zBp1][y][x] = 0; } } } // faces (x,0,z) and (x,ymax,z) for (z = 1; z <= mZBound; ++z) { for (x = 1; x <= mXBound; ++x) { duplicate = mBuffer[mSrc][z][1][x]; mBuffer[mSrc][z][0][x] = duplicate; mBuffer[mDst][z][0][x] = duplicate; if (mHasMask) { mMask[z][0][x] = 0; } duplicate = mBuffer[mSrc][z][mYBound][x]; mBuffer[mSrc][z][yBp1][x] = duplicate; mBuffer[mDst][z][yBp1][x] = duplicate; if (mHasMask) { mMask[z][yBp1][x] = 0; } } } // faces (0,y,z) and (xmax,y,z) for (z = 1; z <= mZBound; ++z) { for (y = 1; y <= mYBound; ++y) { duplicate = mBuffer[mSrc][z][y][1]; mBuffer[mSrc][z][y][0] = duplicate; mBuffer[mDst][z][y][0] = duplicate; if (mHasMask) { mMask[z][y][0] = 0; } duplicate = mBuffer[mSrc][z][y][mXBound]; mBuffer[mSrc][z][y][xBp1] = duplicate; mBuffer[mDst][z][y][xBp1] = duplicate; if (mHasMask) { mMask[z][y][xBp1] = 0; } } } } // Assign values to the 1-voxel mask border. void AssignDirichletMaskBorder() { for (int32_t z = 1; z <= mZBound; ++z) { for (int32_t y = 1; y <= mYBound; ++y) { for (int32_t x = 1; x <= mXBound; ++x) { if (mMask[z][y][x]) { continue; } bool found = false; for (int32_t i2 = 0, j2 = z - 1; i2 < 3 && !found; ++i2, ++j2) { for (int32_t i1 = 0, j1 = y - 1; i1 < 3 && !found; ++i1, ++j1) { for (int32_t i0 = 0, j0 = x - 1; i0 < 3; ++i0, ++j0) { if (mMask[j2][j1][j0]) { mBuffer[mSrc][z][y][x] = this->mBorderValue; mBuffer[mDst][z][y][x] = this->mBorderValue; found = true; break; } } } } } } } } void AssignNeumannMaskBorder() { // Recompute the values just outside the masked region. This // guarantees that derivative estimations use the current values // around the boundary. for (int32_t z = 1; z <= mZBound; ++z) { for (int32_t y = 1; y <= mYBound; ++y) { for (int32_t x = 1; x <= mXBound; ++x) { if (mMask[z][y][x]) { continue; } int32_t count = 0; Real average = (Real)0; for (int32_t i2 = 0, j2 = z - 1; i2 < 3; ++i2, ++j2) { for (int32_t i1 = 0, j1 = y - 1; i1 < 3; ++i1, ++j1) { for (int32_t i0 = 0, j0 = x - 1; i0 < 3; ++i0, ++j0) { if (mMask[j2][j1][j0]) { average += mBuffer[mSrc][j2][j1][j0]; count++; } } } } if (count > 0) { average /= (Real)count; mBuffer[mSrc][z][y][x] = average; mBuffer[mDst][z][y][x] = average; } } } } } // This function recomputes the boundary values when Neumann // conditions are used. If a derived class overrides this, it must // call the base-class OnPreUpdate first. virtual void OnPreUpdate() override { if (mHasMask && this->mBorderValue == std::numeric_limits<Real>::max()) { // Neumann boundary conditions are in use, so recompute the // mask border. AssignNeumannMaskBorder(); } // else: No mask has been specified or Dirichlet boundary // conditions are in use. Nothing to do. } // Iterate over all the pixels and call OnUpdate(x,y,z) for each voxel // that is not masked out. virtual void OnUpdate() override { for (int32_t z = 1; z <= mZBound; ++z) { for (int32_t y = 1; y <= mYBound; ++y) { for (int32_t x = 1; x <= mXBound; ++x) { if (!mHasMask || mMask[z][y][x]) { OnUpdateSingle(x, y, z); } } } } } // If a derived class overrides this, it must call the base-class // OnPostUpdate last. The base-class function swaps the buffers for // the next pass. virtual void OnPostUpdate() override { std::swap(mSrc, mDst); } // The per-pixel processing depends on the PDE algorithm. The (x,y,z) // must be in padded coordinates: 1 <= x <= xbound, 1 <= y <= ybound // and 1 <= z <= zbound. virtual void OnUpdateSingle(int32_t x, int32_t y, int32_t z) = 0; // Copy source data to temporary storage. void LookUp7(int32_t x, int32_t y, int32_t z) { auto const& F = mBuffer[mSrc]; int32_t xm = x - 1, xp = x + 1; int32_t ym = y - 1, yp = y + 1; int32_t zm = z - 1, zp = z + 1; mUzzm = F[zm][y][x]; mUzmz = F[z][ym][x]; mUmzz = F[z][y][xm]; mUzzz = F[z][y][x]; mUpzz = F[z][y][xp]; mUzpz = F[z][yp][x]; mUzzp = F[zp][y][x]; } void LookUp27(int32_t x, int32_t y, int32_t z) { auto const& F = mBuffer[mSrc]; int32_t xm = x - 1, xp = x + 1; int32_t ym = y - 1, yp = y + 1; int32_t zm = z - 1, zp = z + 1; mUmmm = F[zm][ym][xm]; mUzmm = F[zm][ym][x]; mUpmm = F[zm][ym][xp]; mUmzm = F[zm][y][xm]; mUzzm = F[zm][y][x]; mUpzm = F[zm][y][xp]; mUmpm = F[zm][yp][xm]; mUzpm = F[zm][yp][x]; mUppm = F[zm][yp][xp]; mUmmz = F[z][ym][xm]; mUzmz = F[z][ym][x]; mUpmz = F[z][ym][xp]; mUmzz = F[z][y][xm]; mUzzz = F[z][y][x]; mUpzz = F[z][y][xp]; mUmpz = F[z][yp][xm]; mUzpz = F[z][yp][x]; mUppz = F[z][yp][xp]; mUmmp = F[zp][ym][xm]; mUzmp = F[zp][ym][x]; mUpmp = F[zp][ym][xp]; mUmzp = F[zp][y][xm]; mUzzp = F[zp][y][x]; mUpzp = F[zp][y][xp]; mUmpp = F[zp][yp][xm]; mUzpp = F[zp][yp][x]; mUppp = F[zp][yp][xp]; } // Image parameters. int32_t mXBound, mYBound, mZBound; Real mXSpacing; // dx Real mYSpacing; // dy Real mZSpacing; // dz Real mInvDx; // 1/dx Real mInvDy; // 1/dy Real mInvDz; // 1/dz Real mHalfInvDx; // 1/(2*dx) Real mHalfInvDy; // 1/(2*dy) Real mHalfInvDz; // 1/(2*dz) Real mInvDxDx; // 1/(dx*dx) Real mFourthInvDxDy; // 1/(4*dx*dy) Real mFourthInvDxDz; // 1/(4*dx*dz) Real mInvDyDy; // 1/(dy*dy) Real mFourthInvDyDz; // 1/(4*dy*dz) Real mInvDzDz; // 1/(dz*dz) // Temporary storage for 3x3x3 neighborhood. In the notation mUxyz, // the x, y and z indices are in {m,z,p}, referring to subtract 1 (m), // no change (z), or add 1 (p) to the appropriate index. Real mUmmm, mUzmm, mUpmm; Real mUmzm, mUzzm, mUpzm; Real mUmpm, mUzpm, mUppm; Real mUmmz, mUzmz, mUpmz; Real mUmzz, mUzzz, mUpzz; Real mUmpz, mUzpz, mUppz; Real mUmmp, mUzmp, mUpmp; Real mUmzp, mUzzp, mUpzp; Real mUmpp, mUzpp, mUppp; // Successive iterations toggle between two buffers. std::array<Array3<Real>, 2> mBuffer; int32_t mSrc, mDst; Array3<int32_t> mMask; bool mHasMask; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Projection.h
.h
6,599
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 <Mathematics/Hyperellipsoid.h> #include <Mathematics/Hyperplane.h> #include <Mathematics/Line.h> #include <Mathematics/Matrix2x2.h> #include <Mathematics/Matrix3x3.h> // The algorithm for the perspective projection of an ellipsoid onto a // plane is described in // https://www.geometrictools.com/Documentation/PerspectiveProjectionEllipsoid.pdf namespace gte { // Orthogonally project an ellipse onto a line. The projection interval // is [smin,smax] and corresponds to the line segment P + s * D, where // smin <= s <= smax. template <typename Real> void Project(Ellipse2<Real> const& ellipse, Line2<Real> const& line, Real& smin, Real& smax) { // Center of projection interval. Real center = Dot(line.direction, ellipse.center - line.origin); // Radius of projection interval. Real tmp[2] = { ellipse.extent[0] * Dot(line.direction, ellipse.axis[0]), ellipse.extent[1] * Dot(line.direction, ellipse.axis[1]) }; Real rSqr = tmp[0] * tmp[0] + tmp[1] * tmp[1]; Real radius = std::sqrt(rSqr); smin = center - radius; smax = center + radius; } // Orthogonally project an ellipsoid onto a line. The projection interval // is [smin,smax] and corresponds to the line segment P + s * D, where // smin <= s <= smax. template <typename Real> void Project(Ellipsoid3<Real> const& ellipsoid, Line3<Real> const& line, Real& smin, Real& smax) { // Center of projection interval. Real center = Dot(line.direction, ellipsoid.center - line.origin); // Radius of projection interval. Real tmp[3] = { ellipsoid.extent[0] * Dot(line.direction, ellipsoid.axis[0]), ellipsoid.extent[1] * Dot(line.direction, ellipsoid.axis[1]), ellipsoid.extent[2] * Dot(line.direction, ellipsoid.axis[2]) }; Real rSqr = tmp[0] * tmp[0] + tmp[1] * tmp[1] + tmp[2] * tmp[2]; Real radius = std::sqrt(rSqr); smin = center - radius; smax = center + radius; } // Perspectively project an ellipsoid onto a plane. // // The ellipsoid has center C, axes A[i] and extents e[i] for 0 <= i <= 2. // // The eyepoint is E. // // The view plane is Dot(N,X) = d, where N is a unit-length normal vector. // Choose U and V so that {U,V,N} is a right-handed orthonormal set; that // is, the vectors are unit length, mutually perpendicular and // N = Cross(U,V). N must be directed away from E in the sense that the // point K on the plane closest to E is K = E + n * N with n > 0. When // using a view frustum, n is the 'near' distance (from the eyepoint to // the view plane). The plane equation is then // 0 = Dot(N,X-K) = Dot(N,X) - Dot(N,E) - n = d - Dot(N,E) - n // so that n = d - Dot(N,E). // // The ellipsoid must be between the eyepoint and the view plane in the // sense that all rays from the eyepoint that intersect the ellipsoid must // also intersect the view plane. The precondition test is to project the // ellipsoid onto the line E + s * N to obtain interval [smin,smax] where // smin > 0. The function Project(ellipsoid, line, smin, smax) defined // previously in this file can be used to verify the precondition. If the // precondition is satisfied, the projection is an ellipse in the plane. // If the precondition is not satisfied, the projection is a conic section // that is not an ellipse or it is the empty set. // // The output is the equation of the ellipse in 2D. The projected ellipse // coordinates Y = (y0,y1) are the view plane coordinates of the actual 3D // ellipse points X = K + y0 * U + y1 * V = K + J * Y, where J is a 3x2 // matrix whose columns are U and V. // Use this query when you have a single plane and a single ellipsoid to // project onto the plane. template <typename Real> void PerspectiveProject(Ellipsoid3<Real> const& ellipsoid, Vector3<Real> const& E, Plane3<Real> const& plane, Ellipse2<Real>& ellipse) { std::array<Vector3<Real>, 3> basis{}; basis[0] = plane.normal; ComputeOrthogonalComplement(1, basis.data()); auto const& N = plane.normal; auto const& U = basis[1]; auto const& V = basis[2]; Real n = plane.constant - Dot(N, E); PerspectiveProject(ellipsoid, E, N, U, V, n, ellipse); } // Use this query when you have a single plane and multiple ellipsoids to // project onto the plane. The vectors U and V and the near value n are // precomputed. template <typename Real> void PerspectiveProject(Ellipsoid3<Real> const& ellipsoid, Vector3<Real> const& E, Vector3<Real> const& N, Vector3<Real> const& U, Vector3<Real> const& V, Real const& n, Ellipse2<Real>& ellipse) { Real const two = static_cast<Real>(2); Real const four = static_cast<Real>(4); // Compute the coefficients for the ellipsoid represented by the // quadratic equation X^T*A*X + B^T*X + C = 0. Matrix3x3<Real> A{}; Vector3<Real> B{}; Real C{}; ellipsoid.ToCoefficients(A, B, C); // Compute the matrix M; see PerspectiveProjectionEllipsoid.pdf for // the mathematical details. Vector3<Real> AE = A * E; Real qformEAE = Dot(E, AE); Real dotBE = Dot(B, E); Real quadE = four * (qformEAE + dotBE + C); Vector3<Real> Bp2AE = B + two * AE; Matrix3x3<Real> M = OuterProduct(Bp2AE, Bp2AE) - quadE * A; // Compute the coefficients for the projected ellipse. Vector3<Real> MU = M * U; Vector3<Real> MV = M * V; Vector3<Real> MN = M * N; Real twoN = two * n; Matrix2x2<Real> AOut; Vector2<Real> BOut; Real COut; AOut(0, 0) = Dot(U, MU); AOut(0, 1) = Dot(U, MV); AOut(1, 0) = AOut(0, 1); AOut(1, 1) = Dot(V, MV); BOut[0] = twoN * (Dot(U, MN)); BOut[1] = twoN * (Dot(V, MN)); COut = n * n * Dot(N, MN); // Extract the ellipse center, axis directions and extents. ellipse.FromCoefficients(AOut, BOut, COut); } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SymmetricEigensolver3x3.h
.h
28,983
727
// 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 <array> #include <cmath> #include <limits> // The document // https://www.geometrictools.com/Documentation/RobustEigenSymmetric3x3.pdf // describes algorithms for solving the eigensystem associated with a 3x3 // symmetric real-valued matrix. The iterative algorithm is implemented // by class SymmmetricEigensolver3x3. The noniterative algorithm is // implemented by class NISymmetricEigensolver3x3. The code does not use // GTEngine objects. namespace gte { template <typename T> class SortEigenstuff { public: void operator()(int32_t sortType, bool isRotation, std::array<T, 3>& eval, std::array<std::array<T, 3>, 3>& evec) { if (sortType != 0) { // Sort the eigenvalues to eval[0] <= eval[1] <= eval[2]. std::array<size_t, 3> index{}; if (eval[0] < eval[1]) { if (eval[2] < eval[0]) { // even permutation index[0] = 2; index[1] = 0; index[2] = 1; } else if (eval[2] < eval[1]) { // odd permutation index[0] = 0; index[1] = 2; index[2] = 1; isRotation = !isRotation; } else { // even permutation index[0] = 0; index[1] = 1; index[2] = 2; } } else { if (eval[2] < eval[1]) { // odd permutation index[0] = 2; index[1] = 1; index[2] = 0; isRotation = !isRotation; } else if (eval[2] < eval[0]) { // even permutation index[0] = 1; index[1] = 2; index[2] = 0; } else { // odd permutation index[0] = 1; index[1] = 0; index[2] = 2; isRotation = !isRotation; } } if (sortType == -1) { // The request is for eval[0] >= eval[1] >= eval[2]. This // requires an odd permutation, (i0,i1,i2) -> (i2,i1,i0). std::swap(index[0], index[2]); isRotation = !isRotation; } std::array<T, 3> unorderedEVal = eval; std::array<std::array<T, 3>, 3> unorderedEVec = evec; for (size_t j = 0; j < 3; ++j) { size_t i = index[j]; eval[j] = unorderedEVal[i]; evec[j] = unorderedEVec[i]; } } // Ensure the ordered eigenvectors form a right-handed basis. if (!isRotation) { for (size_t j = 0; j < 3; ++j) { evec[2][j] = -evec[2][j]; } } } }; template <typename T> class SymmetricEigensolver3x3 { public: // The input matrix must be symmetric, so only the unique elements // must be specified: a00, a01, a02, a11, a12, and a22. // // If 'aggressive' is 'true', the iterations occur until a // superdiagonal entry is exactly zero. If 'aggressive' is 'false', // the iterations occur until a superdiagonal entry is effectively // zero compared to the/ sum of magnitudes of its diagonal neighbors. // Generally, the nonaggressive convergence is acceptable. // // The order of the eigenvalues is specified by sortType: // -1 (decreasing), 0 (no sorting) or +1 (increasing). When sorted, // the eigenvectors are ordered accordingly, and // {evec[0], evec[1], evec[2]} is guaranteed to/ be a right-handed // orthonormal set. The return value is the number of iterations // used by the algorithm. int32_t operator()(T const& a00, T const& a01, T const& a02, T const& a11, T const& a12, T const& a22, bool aggressive, int32_t sortType, std::array<T, 3>& eval, std::array<std::array<T, 3>, 3>& evec) const { // Compute the Householder reflection H0 and B = H0*A*H0, where // b02 = 0. H0 = {{c,s,0},{s,-c,0},{0,0,1}} with each inner // triple a row of H0. T const zero = static_cast<T>(0); T const one = static_cast<T>(1); T const half = static_cast<T>(0.5); bool isRotation = false; T c = zero, s = zero; GetCosSin(a12, -a02, c, s); T term0 = c * a00 + s * a01; T term1 = c * a01 + s * a11; T term2 = s * a00 - c * a01; T term3 = s * a01 - c * a11; T b00 = c * term0 + s * term1; T b01 = s * term0 - c * term1; //T b02 = c * a02 + s * a12; // 0 T b11 = s * term2 - c * term3; T b12 = s * a02 - c * a12; T b22 = a22; // Maintain Q as the product of the reflections. Initially, // Q = H0. Updates by Givens reflections G are Q <- Q * G. The // columns of the final Q are the estimates for the eigenvectors. std::array<std::array<T, 3>, 3> Q = { { { c, s, zero }, { s, -c, zero }, { zero, zero, one } } }; // The smallest subnormal number is 2^{-alpha}. The value alpha is // 149 for 'float' and 1074 for 'double'. int32_t constexpr alpha = std::numeric_limits<T>::digits - std::numeric_limits<T>::min_exponent; int32_t i = 0, imax = 0, power = 0; T c2 = zero, s2 = zero; if (std::fabs(b12) <= std::fabs(b01)) { // It is known that |currentB12| < 2^{-i/2} * |initialB12|. // Compute imax so that 0 is the closest floating-point number // to 2^{-imax/2} * |initialB12|. (void)std::frexp(b12, &power); imax = 2 * (power + alpha + 1); for (i = 0; i < imax; ++i) { // Compute the Givens reflection // G = {{c,0,-s},{s,0,c},{0,1,0}} where each inner triple // is a row of G. GetCosSin(half * (b00 - b11), b01, c2, s2); s = std::sqrt(half * (one - c2)); c = half * s2 / s; // Update Q <- Q * G. for (size_t r = 0; r < 3; ++r) { term0 = c * Q[r][0] + s * Q[r][1]; term1 = Q[r][2]; term2 = c * Q[r][1] - s * Q[r][0]; Q[r][0] = term0; Q[r][1] = term1; Q[r][2] = term2; } isRotation = !isRotation; // Update B <- Q^T * B * Q, ensuring that b02 is zero and // |b12| has strictly decreased. term0 = c * b00 + s * b01; term1 = c * b01 + s * b11; term2 = s * b00 - c * b01; term3 = s * b01 - c * b11; //b02 = s * c * (b11 - b00) + (c * c - s * s) * b01; // 0 b00 = c * term0 + s * term1; b01 = s * b12; b11 = b22; b12 = c * b12; b22 = s * term2 - c * term3; if (Converged(aggressive, b00, b11, b01)) { // Compute the Householder reflection // H1 = {{c,s,0},{s,-c,0},{0,0,1}} where each inner // triple is a row of H1. GetCosSin(half * (b00 - b11), b01, c2, s2); s = std::sqrt(half * (one - c2)); c = half * s2 / s; // Update Q <- Q * H1. for (size_t r = 0; r < 3; ++r) { term0 = c * Q[r][0] + s * Q[r][1]; term1 = s * Q[r][0] - c * Q[r][1]; Q[r][0] = term0; Q[r][1] = term1; } isRotation = !isRotation; // Compute the diagonal estimate D = Q^T * B * Q. term0 = c * b00 + s * b01; term1 = c * b01 + s * b11; term2 = s * b00 - c * b01; term3 = s * b01 - c * b11; b00 = c * term0 + s * term1; b11 = s * term2 - c * term3; break; } } } else { // It is known that |currentB01| < 2^{-i/2} * |initialB01|. // Compute imax so that 0 is the closest floating-point number // to 2^{-imax/2} * |initialB01|. (void)std::frexp(b01, &power); imax = 2 * (power + alpha + 1); for (i = 0; i < imax; ++i) { // Compute the Givens reflection // G = {{0,1,0},{c,0,-s},{s,0,c}} where each inner triple // is a row of G. GetCosSin(half * (b11 - b22), b12, c2, s2); s = std::sqrt(half * (one - c2)); c = half * s2 / s; // Update Q <- Q * G. for (size_t r = 0; r < 3; ++r) { term0 = c * Q[r][1] + s * Q[r][2]; term1 = Q[r][0]; term2 = c * Q[r][2] - s * Q[r][1]; Q[r][0] = term0; Q[r][1] = term1; Q[r][2] = term2; } isRotation = !isRotation; // Update B <- Q^T * B * Q, ensuring that b02 is zero and // |b01| has strictly decreased. term0 = c * b11 + s * b12; term1 = c * b12 + s * b22; term2 = s * b11 - c * b12; term3 = s * b12 - c * b22; //b02 = s * c * (b22 - b11) + (c * c - s * s) * b12; // 0 b22 = s * term2 - c * term3; b12 = -s * b01; b11 = b00; b01 = c * b01; b00 = c * term0 + s * term1; if (Converged(aggressive, b11, b22, b12)) { // Compute the Householder reflection // H1 = {{1,0,0},{0,c,s},{0,s,-c}} where each inner // triple is a row of H1. GetCosSin(half * (b11 - b22), b12, c2, s2); s = std::sqrt(half * (one - c2)); c = half * s2 / s; // Update Q <- Q * H1. for (size_t r = 0; r < 3; ++r) { term0 = c * Q[r][1] + s * Q[r][2]; term1 = s * Q[r][1] - c * Q[r][2]; Q[r][1] = term0; Q[r][2] = term1; } isRotation = !isRotation; // Compute the diagonal estimate D = Q^T * B * Q. term0 = c * b11 + s * b12; term1 = c * b12 + s * b22; term2 = s * b11 - c * b12; term3 = s * b12 - c * b22; b11 = c * term0 + s * term1; b22 = s * term2 - c * term3; break; } } } eval = { b00, b11, b22 }; for (size_t row = 0; row < 3; ++row) { for (size_t col = 0; col < 3; ++col) { evec[row][col] = Q[col][row]; } } SortEigenstuff<T>()(sortType, isRotation, eval, evec); return i; } private: // Normalize (u,v) to (c,s) with c <= 0 when (u,v) is not (0,0). // If (u,v) = (0,0), the function returns (c,s) = (-1,0). When used // to generate a Householder reflection, it does not matter whether // (c,s) or (-c,-s) is returned. When generating a Givens reflection, // c = cos(2*theta) and s = sin(2*theta). Having a negative cosine // for the double-angle term ensures that the single-angle terms // c = cos(theta) and s = sin(theta) satisfy |c| < 1/sqrt(2) < |s|. static void GetCosSin(T const& u, T const& v, T& c, T& s) { T const zero = static_cast<T>(0); T length = std::sqrt(u * u + v * v); if (length > zero) { c = u / length; s = v / length; if (c > zero) { c = -c; s = -s; } } else { c = static_cast<T>(-1); s = zero; } } static bool Converged(bool aggressive, T const& diagonal0, T const& diagonal1, T const& superdiagonal) { if (aggressive) { // Test whether the superdiagonal term is zero. return superdiagonal == static_cast<T>(0); } else { // Test whether the superdiagonal term is effectively zero // compared to its diagonal neighbors. T sum = std::fabs(diagonal0) + std::fabs(diagonal1); return sum + std::fabs(superdiagonal) == sum; } } }; template <typename T> class NISymmetricEigensolver3x3 { public: // The input matrix must be symmetric, so only the unique elements // must be specified: a00, a01, a02, a11, a12, and a22. The // eigenvalues are sorted in ascending order: eval0 <= eval1 <= eval2. void operator()(T a00, T a01, T a02, T a11, T a12, T a22, int32_t sortType, std::array<T, 3>& eval, std::array<std::array<T, 3>, 3>& evec) const { // Precondition the matrix by factoring out the maximum absolute // value of the components. This guards against floating-point // overflow when computing the eigenvalues. T max0 = std::max(std::fabs(a00), std::fabs(a01)); T max1 = std::max(std::fabs(a02), std::fabs(a11)); T max2 = std::max(std::fabs(a12), std::fabs(a22)); T maxAbsElement = std::max(std::max(max0, max1), max2); if (maxAbsElement == (T)0) { // A is the zero matrix. eval[0] = (T)0; eval[1] = (T)0; eval[2] = (T)0; evec[0] = { (T)1, (T)0, (T)0 }; evec[1] = { (T)0, (T)1, (T)0 }; evec[2] = { (T)0, (T)0, (T)1 }; return; } T invMaxAbsElement = (T)1 / maxAbsElement; a00 *= invMaxAbsElement; a01 *= invMaxAbsElement; a02 *= invMaxAbsElement; a11 *= invMaxAbsElement; a12 *= invMaxAbsElement; a22 *= invMaxAbsElement; T norm = a01 * a01 + a02 * a02 + a12 * a12; if (norm > (T)0) { // Compute the eigenvalues of A. // In the PDF mentioned previously, B = (A - q*I)/p, where // q = tr(A)/3 with tr(A) the trace of A (sum of the diagonal // entries of A) and where p = sqrt(tr((A - q*I)^2)/6). T q = (a00 + a11 + a22) / (T)3; // The matrix A - q*I is represented by the following, where // b00, b11 and b22 are computed after these comments, // +- -+ // | b00 a01 a02 | // | a01 b11 a12 | // | a02 a12 b22 | // +- -+ T b00 = a00 - q; T b11 = a11 - q; T b22 = a22 - q; // The is the variable p mentioned in the PDF. T p = std::sqrt((b00 * b00 + b11 * b11 + b22 * b22 + norm * (T)2) / (T)6); // We need det(B) = det((A - q*I)/p) = det(A - q*I)/p^3. The // value det(A - q*I) is computed using a cofactor expansion // by the first row of A - q*I. The cofactors are c00, c01 // and c02 and the determinant is b00*c00 - a01*c01 + a02*c02. // The det(B) is then computed finally by the division // with p^3. T c00 = b11 * b22 - a12 * a12; T c01 = a01 * b22 - a12 * a02; T c02 = a01 * a12 - b11 * a02; T det = (b00 * c00 - a01 * c01 + a02 * c02) / (p * p * p); // The halfDet value is cos(3*theta) mentioned in the PDF. The // acos(z) function requires |z| <= 1, but will fail silently // and return NaN if the input is larger than 1 in magnitude. // To avoid this problem due to rounding errors, the halfDet // value is clamped to [-1,1]. T halfDet = det * (T)0.5; halfDet = std::min(std::max(halfDet, (T)-1), (T)1); // The eigenvalues of B are ordered as // beta0 <= beta1 <= beta2. The number of digits in // twoThirdsPi is chosen so that, whether float or double, // the floating-point number is the closest to theoretical // 2*pi/3. T angle = std::acos(halfDet) / (T)3; T const twoThirdsPi = (T)2.09439510239319549; T beta2 = std::cos(angle) * (T)2; T beta0 = std::cos(angle + twoThirdsPi) * (T)2; T beta1 = -(beta0 + beta2); // The eigenvalues of A are ordered as // alpha0 <= alpha1 <= alpha2. eval[0] = q + p * beta0; eval[1] = q + p * beta1; eval[2] = q + p * beta2; // Compute the eigenvectors so that the set // {evec[0], evec[1], evec[2]} is right handed and // orthonormal. if (halfDet >= (T)0) { ComputeEigenvector0(a00, a01, a02, a11, a12, a22, eval[2], evec[2]); ComputeEigenvector1(a00, a01, a02, a11, a12, a22, evec[2], eval[1], evec[1]); evec[0] = Cross(evec[1], evec[2]); } else { ComputeEigenvector0(a00, a01, a02, a11, a12, a22, eval[0], evec[0]); ComputeEigenvector1(a00, a01, a02, a11, a12, a22, evec[0], eval[1], evec[1]); evec[2] = Cross(evec[0], evec[1]); } } else { // The matrix is diagonal. eval[0] = a00; eval[1] = a11; eval[2] = a22; evec[0] = { (T)1, (T)0, (T)0 }; evec[1] = { (T)0, (T)1, (T)0 }; evec[2] = { (T)0, (T)0, (T)1 }; } // The preconditioning scaled the matrix A, which scales the // eigenvalues. Revert the scaling. eval[0] *= maxAbsElement; eval[1] *= maxAbsElement; eval[2] *= maxAbsElement; SortEigenstuff<T>()(sortType, true, eval, evec); } private: static std::array<T, 3> Multiply(T s, std::array<T, 3> const& U) { std::array<T, 3> product = { s * U[0], s * U[1], s * U[2] }; return product; } static std::array<T, 3> Subtract(std::array<T, 3> const& U, std::array<T, 3> const& V) { std::array<T, 3> difference = { U[0] - V[0], U[1] - V[1], U[2] - V[2] }; return difference; } static std::array<T, 3> Divide(std::array<T, 3> const& U, T s) { T invS = (T)1 / s; std::array<T, 3> division = { U[0] * invS, U[1] * invS, U[2] * invS }; return division; } 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; } 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; } void ComputeOrthogonalComplement(std::array<T, 3> const& W, std::array<T, 3>& U, std::array<T, 3>& V) const { // Robustly compute a right-handed orthonormal set { U, V, W }. // The vector W is guaranteed to be unit-length, in which case // there is no need to worry about a division by zero when // computing invLength. T invLength; if (std::fabs(W[0]) > std::fabs(W[1])) { // The component of maximum absolute value is either W[0] // or W[2]. invLength = (T)1 / std::sqrt(W[0] * W[0] + W[2] * W[2]); U = { -W[2] * invLength, (T)0, +W[0] * invLength }; } else { // The component of maximum absolute value is either W[1] // or W[2]. invLength = (T)1 / std::sqrt(W[1] * W[1] + W[2] * W[2]); U = { (T)0, +W[2] * invLength, -W[1] * invLength }; } V = Cross(W, U); } void ComputeEigenvector0(T a00, T a01, T a02, T a11, T a12, T a22, T eval0, std::array<T, 3>& evec0) const { // Compute a unit-length eigenvector for eigenvalue[i0]. The // matrix is rank 2, so two of the rows are linearly independent. // For a robust computation of the eigenvector, select the two // rows whose cross product has largest length of all pairs of // rows. std::array<T, 3> row0 = { a00 - eval0, a01, a02 }; std::array<T, 3> row1 = { a01, a11 - eval0, a12 }; std::array<T, 3> row2 = { a02, a12, a22 - eval0 }; std::array<T, 3> r0xr1 = Cross(row0, row1); std::array<T, 3> r0xr2 = Cross(row0, row2); std::array<T, 3> r1xr2 = Cross(row1, row2); T d0 = Dot(r0xr1, r0xr1); T d1 = Dot(r0xr2, r0xr2); T d2 = Dot(r1xr2, r1xr2); T dmax = d0; int32_t imax = 0; if (d1 > dmax) { dmax = d1; imax = 1; } if (d2 > dmax) { imax = 2; } if (imax == 0) { evec0 = Divide(r0xr1, std::sqrt(d0)); } else if (imax == 1) { evec0 = Divide(r0xr2, std::sqrt(d1)); } else { evec0 = Divide(r1xr2, std::sqrt(d2)); } } void ComputeEigenvector1(T a00, T a01, T a02, T a11, T a12, T a22, std::array<T, 3> const& evec0, T eval1, std::array<T, 3>& evec1) const { // Robustly compute a right-handed orthonormal set // { U, V, evec0 }. std::array<T, 3> U, V; ComputeOrthogonalComplement(evec0, U, V); // Let e be eval1 and let E be a corresponding eigenvector which // is a solution to the linear system (A - e*I)*E = 0. The matrix // (A - e*I) is 3x3, not invertible (so infinitely many // solutions), and has rank 2 when eval1 and eval are different. // It has rank 1 when eval1 and eval2 are equal. Numerically, it // is difficult to compute robustly the rank of a matrix. Instead, // the 3x3 linear system is reduced to a 2x2 system as follows. // Define the 3x2 matrix J = [U V] whose columns are the U and V // computed previously. Define the 2x1 vector X = J*E. The 2x2 // system is 0 = M * X = (J^T * (A - e*I) * J) * X where J^T is // the transpose of J and M = J^T * (A - e*I) * J is a 2x2 matrix. // The system may be written as // +- -++- -+ +- -+ // | U^T*A*U - e U^T*A*V || x0 | = e * | x0 | // | V^T*A*U V^T*A*V - e || x1 | | x1 | // +- -++ -+ +- -+ // where X has row entries x0 and x1. std::array<T, 3> AU = { a00 * U[0] + a01 * U[1] + a02 * U[2], a01 * U[0] + a11 * U[1] + a12 * U[2], a02 * U[0] + a12 * U[1] + a22 * U[2] }; std::array<T, 3> AV = { a00 * V[0] + a01 * V[1] + a02 * V[2], a01 * V[0] + a11 * V[1] + a12 * V[2], a02 * V[0] + a12 * V[1] + a22 * V[2] }; T m00 = U[0] * AU[0] + U[1] * AU[1] + U[2] * AU[2] - eval1; T m01 = U[0] * AV[0] + U[1] * AV[1] + U[2] * AV[2]; T m11 = V[0] * AV[0] + V[1] * AV[1] + V[2] * AV[2] - eval1; // For robustness, choose the largest-length row of M to compute // the eigenvector. The 2-tuple of coefficients of U and V in the // assignments to eigenvector[1] lies on a circle, and U and V are // unit length and perpendicular, so eigenvector[1] is unit length // (within numerical tolerance). T absM00 = std::fabs(m00); T absM01 = std::fabs(m01); T absM11 = std::fabs(m11); T maxAbsComp; if (absM00 >= absM11) { maxAbsComp = std::max(absM00, absM01); if (maxAbsComp > (T)0) { if (absM00 >= absM01) { m01 /= m00; m00 = (T)1 / std::sqrt((T)1 + m01 * m01); m01 *= m00; } else { m00 /= m01; m01 = (T)1 / std::sqrt((T)1 + m00 * m00); m00 *= m01; } evec1 = Subtract(Multiply(m01, U), Multiply(m00, V)); } else { evec1 = U; } } else { maxAbsComp = std::max(absM11, absM01); if (maxAbsComp > (T)0) { if (absM11 >= absM01) { m01 /= m11; m11 = (T)1 / std::sqrt((T)1 + m01 * m01); m01 *= m11; } else { m11 /= m01; m01 = (T)1 / std::sqrt((T)1 + m11 * m11); m11 *= m01; } evec1 = Subtract(Multiply(m11, U), Multiply(m01, V)); } else { evec1 = U; } } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Timer.h
.h
1,764
62
// 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> #include <chrono> namespace gte { class Timer { public: // Construction of a high-resolution timer (64-bit). Timer() { Reset(); } // Get the current time relative to the initial time. int64_t GetNanoseconds() const { auto currentTime = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::nanoseconds>( currentTime - mInitialTime).count(); } int64_t GetMicroseconds() const { auto currentTime = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::microseconds>( currentTime - mInitialTime).count(); } int64_t GetMilliseconds() const { auto currentTime = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>( currentTime - mInitialTime).count(); } double GetSeconds() const { int64_t msecs = GetMilliseconds(); return static_cast<double>(msecs) / 1000.0; } // Reset so that the current time is the initial time. void Reset() { mInitialTime = std::chrono::high_resolution_clock::now(); } private: std::chrono::high_resolution_clock::time_point mInitialTime; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/UniqueVerticesTriangles.h
.h
14,609
342
// 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/Logger.h> #include <algorithm> #include <array> #include <map> #include <set> #include <vector> // UniqueVerticesTriangles is a helper class that provides support for several // mesh generation and mesh reduction operations. The vertices have type // VertexType, which must have a less-than comparison predicate because // duplicate vertices are eliminated in the operations. // // 1. Generate an indexed triangle representation from an array of // triples of VertexType. Each triple represents the vertices of // a triangle. Presumably, the triangles share vertices. The output // is an array of unique VertexType objects (a vertex pool) and an // array of triples of indices into the pool, each triple // representing a triangle. // // 2. Remove duplicate vertices from a vertex pool used by an indexed // triangle representation. A new vertex pool of unique vertices is // generated and the indexed triangles are modified to be indices into // this vertex pool. // // 3. Remove unused vertices from a vertex pool used by an indexed triangle // representation. A new vertex pool of unique vertices is generated and // the indexed triangles are modified to be indices into the new vertex // pool. // // 4. Remove duplicate and unused vertices from a vertex pool, a combination // of the operations in #2 and #3. // Uncomment this preprocessor symbol to validate the preconditions of the // inputs of the class member functions. #define GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES namespace gte { template <typename VertexType> class // [[deprecated("Use UniqueVerticesSimplices<VertexType,IndexType,3> instead.")]] UniqueVerticesTriangles { public: // The class has no state, so the constructors, destructors, copy // semantics and move semantics are all the defaults generated by the // compiler. // See #1 in the comments at the beginning of this file. The // preconditions are // 1. inVertices.size() is a positive multiple of 3 // The postconditions are // 1. outVertices has unique vertices // 2. outIndices.size() = inVertices.size() // 3. 0 <= outIndices[i] < outVertices.size() void GenerateIndexedTriangles( std::vector<VertexType> const& inVertices, std::vector<VertexType>& outVertices, std::vector<int32_t>& outIndices) { #if defined(GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES) LogAssert(inVertices.size() > 0 && inVertices.size() % 3 == 0, "Invalid number of vertices."); #endif outIndices.resize(inVertices.size()); RemoveDuplicates(inVertices, outVertices, outIndices.data()); } // See #1 in the comments at the beginning of this file. The // preconditions are // 1. inVertices.size() is a positive multiple of 3 // The postconditions are // 1. outVertices has unique vertices // 2. outTriangles.size() = inVertices.size() / 3 // 3. 0 <= outTriangles[i][j] < outVertices.size() void GenerateIndexedTriangles( std::vector<VertexType> const& inVertices, std::vector<VertexType>& outVertices, std::vector<std::array<int32_t, 3>>& outTriangles) { #if defined(GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES) LogAssert(inVertices.size() > 0 && inVertices.size() % 3 == 0, "Invalid number of vertices."); #endif outTriangles.resize(inVertices.size() / 3); int32_t* outIndices = reinterpret_cast<int32_t*>(outTriangles.data()); RemoveDuplicates(inVertices, outVertices, outIndices); } // See #2 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inIndices.size() is a positive multiple of 3 // 3. 0 <= inIndices[i] < inVertices.size() // The postconditions are // 1. outVertices has unique vertices // 2. outIndices.size() = inIndices.size() // 3. 0 <= outIndices[i] < outVertices.size() void RemoveDuplicateVertices( std::vector<VertexType> const& inVertices, std::vector<int32_t> const& inIndices, std::vector<VertexType>& outVertices, std::vector<int32_t>& outIndices) { #if defined(GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES) LogAssert(inVertices.size() > 0, "Invalid number of vertices."); LogAssert(inIndices.size() > 0 && inIndices.size() % 3 == 0, "Invalid number of indices."); int32_t const numVertices = static_cast<int32_t>(inVertices.size()); for (auto index : inIndices) { LogAssert(0 <= index && index < numVertices, "Invalid index."); } #endif std::vector<int32_t> inToOutMapping(inVertices.size()); RemoveDuplicates(inVertices, outVertices, inToOutMapping.data()); outIndices.resize(inIndices.size()); for (size_t i = 0; i < inIndices.size(); ++i) { outIndices[i] = inToOutMapping[inIndices[i]]; } } // See #2 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inTriangles.size() is positive // 3. 0 <= inTriangles[i][j] < inVertices.size() // The postconditions are // 1. outVertices has unique vertices // 2. outTriangles.size() = inTriangles.size() // 3. 0 <= outTriangles[i][j] < outVertices.size() void RemoveDuplicateVertices( std::vector<VertexType> const& inVertices, std::vector<std::array<int32_t, 3>> const& inTriangles, std::vector<VertexType>& outVertices, std::vector<std::array<int32_t, 3>>& outTriangles) { #if defined(GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES) LogAssert(inVertices.size() > 0, "Invalid number of vertices."); LogAssert(inTriangles.size() > 0, "Invalid number of triangles."); int32_t const numVertices = static_cast<int32_t>(inVertices.size()); for (auto const& triangle : inTriangles) { for (size_t j = 0; j < 3; ++j) { LogAssert(0 <= triangle[j] && triangle[j] < numVertices, "Invalid index."); } } #endif std::vector<int32_t> inToOutMapping(inVertices.size()); RemoveDuplicates(inVertices, outVertices, inToOutMapping.data()); size_t const numTriangles = inTriangles.size(); outTriangles.resize(numTriangles); for (size_t t = 0; t < numTriangles; ++t) { for (size_t j = 0; j < 3; ++j) { outTriangles[t][j] = inToOutMapping[inTriangles[t][j]]; } } } // See #3 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inIndices.size() is a positive multiple of 3 // 3. 0 <= inIndices[i] < inVertices.size() // The postconditions are // 1. outVertices.size() is positive // 2. outIndices.size() = inIndices.size() // 3. 0 <= outIndices[i] < outVertices.size() // 4. each outVertices[j] occurs at least once in outIndices void RemoveUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<int32_t> const& inIndices, std::vector<VertexType>& outVertices, std::vector<int32_t>& outIndices) { #if defined(GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES) LogAssert(inVertices.size() > 0, "Invalid number of vertices."); LogAssert(inIndices.size() > 0 && inIndices.size() % 3 == 0, "Invalid number of indices."); int32_t const numVertices = static_cast<int32_t>(inVertices.size()); for (auto index : inIndices) { LogAssert(0 <= index && index < numVertices, "Invalid index."); } #endif outIndices.resize(inIndices.size()); RemoveUnused(inVertices, inIndices.size(), inIndices.data(), outVertices, outIndices.data()); } // See #3 in the comments at the beginning of the file. The // preconditions are // 1. inVertices.size() is positive // 2. inTriangles.size() is positive // 3. 0 <= outTriangles[i][j] < inVertices.size() // The postconditions are // 1. outVertices.size() is positive // 2. outTriangles.size() = inTriangles.size() // 3. 0 <= outTriangles[i][j] < outVertices.size() // 4. each outVertices[j] occurs at least once in outTriangles void RemoveUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<std::array<int32_t, 3>> const& inTriangles, std::vector<VertexType> & outVertices, std::vector<std::array<int32_t, 3>> & outTriangles) { #if defined(GTL_VALIDATE_UNIQUE_VERTICES_TRIANGLES) LogAssert(inVertices.size() > 0, "Invalid number of vertices."); LogAssert(inTriangles.size() > 0, "Invalid number of triangles."); int32_t const numVertices = static_cast<int32_t>(inVertices.size()); for (auto const& triangle : inTriangles) { for (size_t j = 0; j < 3; ++j) { LogAssert(0 <= triangle[j] && triangle[j] < numVertices, "Invalid index."); } } #endif outTriangles.resize(inTriangles.size()); size_t const numInIndices = 3 * inTriangles.size(); int32_t const* inIndices = reinterpret_cast<int32_t const*>(inTriangles.data()); int32_t* outIndices = reinterpret_cast<int32_t*>(outTriangles.data()); RemoveUnused(inVertices, numInIndices, inIndices, outVertices, outIndices); } // See #4 and the preconditions for RemoveDuplicateVertices and for // RemoveUnusedVertices. void RemoveDuplicateAndUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<int32_t> const& inIndices, std::vector<VertexType>& outVertices, std::vector<int32_t>& outIndices) { std::vector<VertexType> tempVertices; std::vector<int32_t> tempIndices; RemoveDuplicateVertices(inVertices, inIndices, tempVertices, tempIndices); RemoveUnusedVertices(tempVertices, tempIndices, outVertices, outIndices); } // See #4 and the preconditions for RemoveDuplicateVertices and for // RemoveUnusedVertices. void RemoveDuplicateAndUnusedVertices( std::vector<VertexType> const& inVertices, std::vector<std::array<int32_t, 3>> const& inTriangles, std::vector<VertexType>& outVertices, std::vector<std::array<int32_t, 3>>& outTriangles) { std::vector<VertexType> tempVertices; std::vector<std::array<int32_t, 3>> tempTriangles; RemoveDuplicateVertices(inVertices, inTriangles, tempVertices, tempTriangles); RemoveUnusedVertices(tempVertices, tempTriangles, outVertices, outTriangles); } private: void RemoveDuplicates( std::vector<VertexType> const& inVertices, std::vector<VertexType>& outVertices, int32_t* inToOutMapping) { // Construct the unique vertices. size_t const numInVertices = inVertices.size(); size_t numOutVertices = 0; std::map<VertexType, int32_t> vmap; for (size_t i = 0; i < numInVertices; ++i, ++inToOutMapping) { auto const iter = vmap.find(inVertices[i]); if (iter != vmap.end()) { // The vertex is a duplicate of one inserted earlier into // the map. Its index i will be modified to that of the // first-found vertex. *inToOutMapping = iter->second; } else { // The vertex occurs for the first time. vmap.insert(std::make_pair(inVertices[i], static_cast<int32_t>(numOutVertices))); *inToOutMapping = static_cast<int32_t>(numOutVertices); ++numOutVertices; } } // Pack the unique vertices into an array. outVertices.resize(numOutVertices); for (auto const& element : vmap) { outVertices[element.second] = element.first; } } void RemoveUnused( std::vector<VertexType> const& inVertices, size_t const numInIndices, int32_t const* inIndices, std::vector<VertexType>& outVertices, int32_t* outIndices) { std::set<int32_t> usedIndices; for (size_t i = 0; i < numInIndices; ++i) { usedIndices.insert(inIndices[i]); } // Locate the used vertices and pack them into an array. outVertices.resize(usedIndices.size()); size_t numOutVertices = 0; std::map<int32_t, int32_t> vmap; for (auto oldIndex : usedIndices) { outVertices[numOutVertices] = inVertices[oldIndex]; vmap.insert(std::make_pair(oldIndex, static_cast<int32_t>(numOutVertices))); ++numOutVertices; } // Reassign the old indices to the new indices. for (size_t i = 0; i < numInIndices; ++i) { outIndices[i] = vmap.find(inIndices[i])->second; } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/EulerAngles.h
.h
2,175
71
// 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 Euler angle data structure for representing rotations. See the // document // https://www.geometrictools.com/Documentation/EulerAngles.pdf namespace gte { // Factorization into Euler angles is not necessarily unique. Let the // integer indices for the axes be (N0,N1,N2), which must be in the set // {(0,1,2),(0,2,1),(1,0,2),(1,2,0),(2,0,1),(2,1,0), // (0,1,0),(0,2,0),(1,0,1),(1,2,1),(2,0,2),(2,1,2)} // Let the corresponding angles be (angleN0,angleN1,angleN2). If the // result is NOT_UNIQUE_SUM, then the multiple solutions occur because // angleN2+angleN0 is constant. If the result is NOT_UNIQUE_DIF, then // the multiple solutions occur because angleN2-angleN0 is constant. // In either type of nonuniqueness, the function returns angleN0=0. enum class EulerResult { // The solution is invalid (incorrect axis indices). INVALID, // The solution is unique. UNIQUE, // The solution is not unique. A sum of angles is constant. NOT_UNIQUE_SUM, // The solution is not unique. A difference of angles is constant. NOT_UNIQUE_DIF }; template <typename Real> class EulerAngles { public: EulerAngles() : axis{0, 0, 0}, angle{ (Real)0, (Real)0, (Real)0 }, result(EulerResult::INVALID) { } EulerAngles(int32_t i0, int32_t i1, int32_t i2, Real a0, Real a1, Real a2) : axis{ i0, i1, i2 }, angle{ a0, a1, a2 }, result(EulerResult::UNIQUE) { } std::array<int32_t, 3> axis; std::array<Real, 3> angle; // This member is set during conversions from rotation matrices, // quaternions, or axis-angles. EulerResult result; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/SurfaceExtractorMC.h
.h
13,294
334
// 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/MarchingCubes.h> #include <Mathematics/Image3.h> #include <Mathematics/UniqueVerticesSimplices.h> #include <Mathematics/Vector3.h> namespace gte { template <typename Real> class SurfaceExtractorMC : public MarchingCubes { public: // Construction and destruction. virtual ~SurfaceExtractorMC() { } SurfaceExtractorMC(Image3<Real> const& image) : mImage(image) { } // Object copies are not allowed. SurfaceExtractorMC() = delete; SurfaceExtractorMC(SurfaceExtractorMC const&) = delete; SurfaceExtractorMC const& operator=(SurfaceExtractorMC const&) = delete; struct Mesh { // All members are set to zeros. Mesh() { std::array<Real, 3> zero = { (Real)0, (Real)0, (Real)0 }; std::fill(vertices.begin(), vertices.end(), zero); } Topology topology; std::array<Vector3<Real>, MAX_VERTICES> vertices; }; // Extract the triangle mesh approximating F = 0 for a single voxel. // The input function values must be stored as // F[0] = function(0,0,0), F[4] = function(0,0,1), // F[1] = function(1,0,0), F[5] = function(1,0,1), // F[2] = function(0,1,0), F[6] = function(0,1,1), // F[3] = function(1,1,0), F[7] = function(1,1,1). // Thus, F[k] = function(k & 1, (k & 2) >> 1, (k & 4) >> 2). // The return value is 'true' iff the F[] values are all nonzero. // If they are not, the returned 'mesh' has no vertices and no // triangles--as if F[] had all positive or all negative values. bool Extract(std::array<Real, 8> const& F, Mesh& mesh) const { int32_t entry = 0; for (int32_t i = 0, mask = 1; i < 8; ++i, mask <<= 1) { if (F[i] < (Real)0) { entry |= mask; } else if (F[i] == (Real)0) { return false; } } mesh.topology = GetTable(entry); for (int32_t i = 0; i < mesh.topology.numVertices; ++i) { int32_t j0 = mesh.topology.vpair[i][0]; int32_t j1 = mesh.topology.vpair[i][1]; Real corner0[3]; corner0[0] = static_cast<Real>(j0 & 1); corner0[1] = static_cast<Real>((j0 & 2) >> 1); corner0[2] = static_cast<Real>((j0 & 4) >> 2); Real corner1[3]; corner1[0] = static_cast<Real>(j1 & 1); corner1[1] = static_cast<Real>((j1 & 2) >> 1); corner1[2] = static_cast<Real>((j1 & 4) >> 2); Real invDenom = ((Real)1) / (F[j0] - F[j1]); for (int32_t k = 0; k < 3; ++k) { Real numer = F[j0] * corner1[k] - F[j1] * corner0[k]; mesh.vertices[i][k] = numer * invDenom; } } return true; } // Extract the triangle mesh approximating F = 0 for all the voxels in // a 3D image. The input image must be stored in a 1-dimensional // array with lexicographical order; that is, image[i] corresponds to // voxel location (x,y,z) where i = x + bound0 * (y + bound1 * z). // The output 'indices' consists indices.size()/3 triangles, each a // triple of indices into 'vertices' bool Extract(Real level, std::vector<Vector3<Real>>& vertices, std::vector<int32_t>& indices) const { vertices.clear(); indices.clear(); for (int32_t z = 0; z + 1 < mImage.GetDimension(2); ++z) { for (int32_t y = 0; y + 1 < mImage.GetDimension(1); ++y) { for (int32_t x = 0; x + 1 < mImage.GetDimension(0); ++x) { std::array<size_t, 8> corners; mImage.GetCorners(x, y, z, corners); std::array<Real, 8> F; for (int32_t k = 0; k < 8; ++k) { F[k] = mImage[corners[k]] - level; } Mesh mesh; if (Extract(F, mesh)) { int32_t vbase = static_cast<int32_t>(vertices.size()); for (int32_t i = 0; i < mesh.topology.numVertices; ++i) { Vector3<Real> position = mesh.vertices[i]; position[0] += static_cast<Real>(x); position[1] += static_cast<Real>(y); position[2] += static_cast<Real>(z); vertices.push_back(position); } for (int32_t i = 0; i < mesh.topology.numTriangles; ++i) { for (int32_t j = 0; j < 3; ++j) { indices.push_back(vbase + mesh.topology.itriple[i][j]); } } } else { vertices.clear(); indices.clear(); return false; } } } } return true; } // The extraction has duplicate vertices on edges shared by voxels. // This function will eliminate the duplication. void MakeUnique(std::vector<Vector3<Real>>& vertices, std::vector<int32_t>& indices) const { std::vector<Vector3<Real>> outVertices; std::vector<int32_t> outIndices; UniqueVerticesSimplices<Vector3<Real>, int32_t, 3> uvt; uvt.RemoveDuplicateVertices(vertices, indices, outVertices, outIndices); vertices = std::move(outVertices); indices = std::move(outIndices); } // The extraction does not use any topological information about the // level surface. 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 if you // build a table of vertex, edge, and face adjacencies, but the // resulting data structure is somewhat expensive to process to // reorient triangles. void OrientTriangles(std::vector<Vector3<Real>> const& vertices, std::vector<int32_t>& indices, bool sameDir) const { int32_t const numTriangles = static_cast<int32_t>(indices.size() / 3); int32_t* triangle = indices.data(); for (int32_t t = 0; t < numTriangles; ++t, triangle += 3) { // Get triangle vertices. Vector3<Real> v0 = vertices[triangle[0]]; Vector3<Real> v1 = vertices[triangle[1]]; Vector3<Real> v2 = vertices[triangle[2]]; // Construct triangle normal based on current orientation. Vector3<Real> edge1 = v1 - v0; Vector3<Real> edge2 = v2 - v0; Vector3<Real> normal = Cross(edge1, edge2); // Get the image gradient at the vertices. Vector3<Real> gradient0 = GetGradient(v0); Vector3<Real> gradient1 = GetGradient(v1); Vector3<Real> gradient2 = GetGradient(v2); // Compute the average gradient. Vector3<Real> gradientAvr = (gradient0 + gradient1 + gradient2) / (Real)3; // Compute the dot product of normal and average gradient. Real dot = Dot(gradientAvr, normal); // Choose triangle orientation based on gradient direction. if (sameDir) { if (dot < (Real)0) { // Wrong orientation, reorder it. std::swap(triangle[1], triangle[2]); } } else { if (dot > (Real)0) { // Wrong orientation, reorder it. std::swap(triangle[1], triangle[2]); } } } } // Compute vertex normals for the mesh. void ComputeNormals(std::vector<Vector3<Real>> const& vertices, std::vector<int32_t> const& indices, std::vector<Vector3<Real>>& normals) const { // Maintain a running sum of triangle normals at each vertex. int32_t const numVertices = static_cast<int32_t>(vertices.size()); normals.resize(numVertices); Vector3<Real> zero = Vector3<Real>::Zero(); std::fill(normals.begin(), normals.end(), zero); int32_t const numTriangles = static_cast<int32_t>(indices.size() / 3); int32_t const* current = indices.data(); for (int32_t i = 0; i < numTriangles; ++i) { int32_t i0 = *current++; int32_t i1 = *current++; int32_t i2 = *current++; Vector3<Real> v0 = vertices[i0]; Vector3<Real> v1 = vertices[i1]; Vector3<Real> v2 = vertices[i2]; // Construct triangle normal. Vector3<Real> edge1 = v1 - v0; Vector3<Real> edge2 = v2 - v0; Vector3<Real> normal = Cross(edge1, edge2); // Maintain the sum of normals at each vertex. normals[i0] += normal; normals[i1] += normal; normals[i2] += normal; } // 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) { Normalize(normal); } } protected: Vector3<Real> GetGradient(Vector3<Real> position) const { int32_t x = static_cast<int32_t>(std::floor(position[0])); if (x < 0 || x >= mImage.GetDimension(0) - 1) { return Vector3<Real>::Zero(); } int32_t y = static_cast<int32_t>(std::floor(position[1])); if (y < 0 || y >= mImage.GetDimension(1) - 1) { return Vector3<Real>::Zero(); } int32_t z = static_cast<int32_t>(std::floor(position[2])); if (z < 0 || z >= mImage.GetDimension(2) - 1) { return Vector3<Real>::Zero(); } position[0] -= static_cast<Real>(x); position[1] -= static_cast<Real>(y); position[2] -= static_cast<Real>(z); Real oneMX = (Real)1 - position[0]; Real oneMY = (Real)1 - position[1]; Real oneMZ = (Real)1 - position[2]; // Get image values at corners of voxel. std::array<size_t, 8> corners; mImage.GetCorners(x, y, z, corners); Real f000 = mImage[corners[0]]; Real f100 = mImage[corners[1]]; Real f010 = mImage[corners[2]]; Real f110 = mImage[corners[3]]; Real f001 = mImage[corners[4]]; Real f101 = mImage[corners[5]]; Real f011 = mImage[corners[6]]; Real f111 = mImage[corners[7]]; Vector3<Real> gradient; Real tmp0 = oneMY * (f100 - f000) + position[1] * (f110 - f010); Real tmp1 = oneMY * (f101 - f001) + position[1] * (f111 - f011); gradient[0] = oneMZ * tmp0 + position[2] * tmp1; tmp0 = oneMX * (f010 - f000) + position[0] * (f110 - f100); tmp1 = oneMX * (f011 - f001) + position[0] * (f111 - f101); gradient[1] = oneMZ * tmp0 + position[2] * tmp1; tmp0 = oneMX * (f001 - f000) + position[0] * (f101 - f100); tmp1 = oneMX * (f011 - f010) + position[0] * (f111 - f110); gradient[2] = oneMY * tmp0 + position[1] * tmp1; return gradient; } Image3<Real> const& mImage; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntpLinearNonuniform2.h
.h
2,517
73
// 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/Vector2.h> // Linear interpolation of a network of triangles whose vertices are of the // form (x,y,f(x,y)). The function samples are F[i] and represent // f(x[i],y[i]), where i is the index of the input vertex (x[i],y[i]) to // Delaunay2. // // The TriangleMesh interface must support the following: // bool GetIndices(int32_t, std::array<int32_t, 3>&) const; // bool GetBarycentrics(int32_t, Vector2<Real> const&, // std::array<Real, 3>&) const; // int32_t GetContainingTriangle(Vector2<Real> const&) const; namespace gte { template <typename Real, typename TriangleMesh> class IntpLinearNonuniform2 { public: // Construction. IntpLinearNonuniform2(TriangleMesh const& mesh, Real const* F) : mMesh(&mesh), mF(F) { LogAssert(mF != nullptr, "Invalid input."); } // Linear interpolation. The return value is 'true' if and only if // the input point P is in the convex hull of the input vertices, in // which case the interpolation is valid. bool operator()(Vector2<Real> const& P, Real& F) const { int32_t t = mMesh->GetContainingTriangle(P); if (t == -1) { // The point is outside the triangulation. return false; } // Get the barycentric coordinates of P with respect to the triangle, // P = b0*V0 + b1*V1 + b2*V2, where b0 + b1 + b2 = 1. std::array<Real, 3> bary; if (!mMesh->GetBarycentrics(t, P, bary)) { // TODO: Throw an exception or allow this as valid behavior? // P is in a needle-like or degenerate triangle. return false; } // The result is a barycentric combination of function values. std::array<int32_t, 3> indices{ 0, 0, 0 }; mMesh->GetIndices(t, indices); F = bary[0] * mF[indices[0]] + bary[1] * mF[indices[1]] + bary[2] * mF[indices[2]]; return true; } private: TriangleMesh const* mMesh; Real const* mF; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MassSpringVolume.h
.h
11,174
283
// 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> namespace gte { template <int32_t N, typename Real> class MassSpringVolume : public ParticleSystem<N, Real> { public: // Construction and destruction. This class represents an SxRxC array // of masses lying on in a volume and connected by an array of // springs. The masses are indexed by mass[s][r][c] for 0 <= s < S, // 0 <= r < R and 0 <= c < C. The mass at interior position X[s][r][c] // is connected by springs to the masses at positions X[s][r-1][c], // X[s][r+1][c], X[s][r][c-1], X[s][r][c+1], X[s-1][r][c] and // X[s+1][r][c]. Boundary masses have springs connecting them to the // obvious neighbors ("face" mass has 5 neighbors, "edge" mass has 4 // neighbors, "corner" mass has 3 neighbors). The masses are arranged // in lexicographical order: position[c+C*(r+R*s)] = X[s][r][c] for // 0 <= s < S, 0 <= r < R, and 0 <= c < C. The other arrays are // stored similarly. virtual ~MassSpringVolume() = default; MassSpringVolume(int32_t numSlices, int32_t numRows, int32_t numCols, Real step) : ParticleSystem<N, Real>(numSlices* numRows* numCols, step), mNumSlices(numSlices), mNumRows(numRows), mNumCols(numCols), mConstantS(static_cast<size_t>(numSlices) * static_cast<size_t>(numRows) * static_cast<size_t>(numCols)), mLengthS(static_cast<size_t>(numSlices)* static_cast<size_t>(numRows)* static_cast<size_t>(numCols)), mConstantR(static_cast<size_t>(numSlices)* static_cast<size_t>(numRows)* static_cast<size_t>(numCols)), mLengthR(static_cast<size_t>(numSlices)* static_cast<size_t>(numRows)* static_cast<size_t>(numCols)), mConstantC(static_cast<size_t>(numSlices)* static_cast<size_t>(numRows)* static_cast<size_t>(numCols)), mLengthC(static_cast<size_t>(numSlices)* static_cast<size_t>(numRows)* static_cast<size_t>(numCols)) { std::fill(mConstantS.begin(), mConstantS.end(), (Real)0); std::fill(mLengthS.begin(), mLengthS.end(), (Real)0); std::fill(mConstantR.begin(), mConstantR.end(), (Real)0); std::fill(mLengthR.begin(), mLengthR.end(), (Real)0); std::fill(mConstantC.begin(), mConstantC.end(), (Real)0); std::fill(mLengthC.begin(), mLengthC.end(), (Real)0); } // Member access. inline int32_t GetNumSlices() const { return mNumSlices; } inline int32_t GetNumRows() const { return mNumRows; } inline int32_t GetNumCols() const { return mNumCols; } inline void SetMass(int32_t s, int32_t r, int32_t c, Real mass) { ParticleSystem<N, Real>::SetMass(GetIndex(s, r, c), mass); } inline void SetPosition(int32_t s, int32_t r, int32_t c, Vector<N, Real> const& position) { ParticleSystem<N, Real>::SetPosition(GetIndex(s, r, c), position); } inline void SetVelocity(int32_t s, int32_t r, int32_t c, Vector<N, Real> const& velocity) { ParticleSystem<N, Real>::SetVelocity(GetIndex(s, r, c), velocity); } Real const& GetMass(int32_t s, int32_t r, int32_t c) const { return ParticleSystem<N, Real>::GetMass(GetIndex(s, r, c)); } inline Vector<N, Real> const& GetPosition(int32_t s, int32_t r, int32_t c) const { return ParticleSystem<N, Real>::GetPosition(GetIndex(s, r, c)); } inline Vector<N, Real> const& GetVelocity(int32_t s, int32_t r, int32_t c) const { return ParticleSystem<N, Real>::GetVelocity(GetIndex(s, r, c)); } // Each interior mass at (s,r,c) has 6 adjacent springs. Face masses // have only 5 neighbors, edge masses have only 4 neighbors, and corner // masses have only 3 neighbors. Each mass provides access to 3 adjacent // springs at (s,r,c+1), (s,r+1,c), and (s+1,r,c). The face, edge, and // corner masses provide access to only an appropriate subset of these. // The caller is responsible for ensuring the validity of the (s,r,c) // inputs. // to (s+1,r,c) inline void SetConstantS(int32_t s, int32_t r, int32_t c, Real constant) { mConstantS[GetIndex(s, r, c)] = constant; } // to (s+1,r,c) inline void SetLengthS(int32_t s, int32_t r, int32_t c, Real length) { mLengthS[GetIndex(s, r, c)] = length; } // to (s,r+1,c) inline void SetConstantR(int32_t s, int32_t r, int32_t c, Real constant) { mConstantR[GetIndex(s, r, c)] = constant; } // to (s,r+1,c) inline void SetLengthR(int32_t s, int32_t r, int32_t c, Real length) { mLengthR[GetIndex(s, r, c)] = length; } // to (s,r,c+1) inline void SetConstantC(int32_t s, int32_t r, int32_t c, Real constant) { mConstantC[GetIndex(s, r, c)] = constant; } // spring to (s,r,c+1) inline void SetLengthC(int32_t s, int32_t r, int32_t c, Real length) { mLengthC[GetIndex(s, r, c)] = length; } inline Real const& GetConstantS(int32_t s, int32_t r, int32_t c) const { return mConstantS[GetIndex(s, r, c)]; } inline Real const& GetLengthS(int32_t s, int32_t r, int32_t c) const { return mLengthS[GetIndex(s, r, c)]; } inline Real const& GetConstantR(int32_t s, int32_t r, int32_t c) const { return mConstantR[GetIndex(s, r, c)]; } inline Real const& GetLengthR(int32_t s, int32_t r, int32_t c) const { return mLengthR[GetIndex(s, r, c)]; } inline Real const& GetConstantC(int32_t s, int32_t r, int32_t c) const { return mConstantC[GetIndex(s, r, c)]; } inline Real const& GetLengthC(int32_t s, int32_t r, int32_t c) const { return mLengthC[GetIndex(s, r, c)]; } // 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. // The face, edge, and corner points of the volume of masses must // be handled separately, because each has fewer than eight // springs attached to it. Vector<N, Real> acceleration = ExternalAcceleration(i, time, position, velocity); Vector<N, Real> diff, force; Real ratio; int32_t s, r, c, prev, next; GetCoordinates(i, s, r, c); if (s > 0) { prev = i - mNumRows * mNumCols; // index to previous s-neighbor diff = position[prev] - position[i]; ratio = GetLengthS(s - 1, r, c) / Length(diff); force = GetConstantS(s - 1, r, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (s < mNumSlices - 1) { next = i + mNumRows * mNumCols; // index to next s-neighbor diff = position[next] - position[i]; ratio = GetLengthS(s, r, c) / Length(diff); force = GetConstantS(s, r, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (r > 0) { prev = i - mNumCols; // index to previous r-neighbor diff = position[prev] - position[i]; ratio = GetLengthR(s, r - 1, c) / Length(diff); force = GetConstantR(s, r - 1, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (r < mNumRows - 1) { next = i + mNumCols; // index to next r-neighbor diff = position[next] - position[i]; ratio = GetLengthR(s, r, c) / Length(diff); force = GetConstantR(s, r, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (c > 0) { prev = i - 1; // index to previous c-neighbor diff = position[prev] - position[i]; ratio = GetLengthC(s, r, c - 1) / Length(diff); force = GetConstantC(s, r, c - 1) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } if (c < mNumCols - 1) { next = i + 1; // index to next c-neighbor diff = position[next] - position[i]; ratio = GetLengthC(s, r, c) / Length(diff); force = GetConstantC(s, r, c) * ((Real)1 - ratio) * diff; acceleration += this->mInvMass[i] * force; } return acceleration; } inline int32_t GetIndex(int32_t s, int32_t r, int32_t c) const { return c + mNumCols * (r + mNumRows * s); } void GetCoordinates(int32_t i, int32_t& s, int32_t& r, int32_t& c) const { c = i % mNumCols; i = (i - c) / mNumCols; r = i % mNumRows; s = i / mNumRows; } int32_t mNumSlices, mNumRows, mNumCols; std::vector<Real> mConstantS, mLengthS; std::vector<Real> mConstantR, mLengthR; std::vector<Real> mConstantC, mLengthC; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistRay3Triangle3.h
.h
2,153
63
// 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/DistLine3Triangle3.h> #include <Mathematics/DistPointTriangle.h> #include <Mathematics/Ray.h> // Compute the distance between a ray and a triangle in 3D. // // The ray is P + t * D for t >= 0, where D is not required to be unit length. // // 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 closest point on the ray is stored in closest[0] with parameter t. The // closest point on the triangle is closest[1] with barycentric coordinates // (b[0],b[1],b[2]). 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>, Triangle3<T>> { public: using LTQuery = DCPQuery<T, Line3<T>, Triangle3<T>>; using Result = typename LTQuery::Result; Result operator()(Ray3<T> const& ray, Triangle3<T> const& triangle) { Result result{}; T const zero = static_cast<T>(0); Line3<T> line(ray.origin, ray.direction); LTQuery ltQuery{}; auto ltResult = ltQuery(line, triangle); if (ltResult.parameter >= zero) { result = ltResult; } else { DCPQuery<T, Vector3<T>, Triangle3<T>> ptQuery{}; auto ptResult = ptQuery(ray.origin, triangle); result.distance = ptResult.distance; result.sqrDistance = ptResult.sqrDistance; result.parameter = zero; result.barycentric = ptResult.barycentric; result.closest[0] = ray.origin; result.closest[1] = ptResult.closest[1]; } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/RemezAlgorithm.h
.h
17,835
531
// 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 <functional> namespace gte { template <typename T> class RemezAlgorithm { public: using Function = std::function<T(T const&)>; RemezAlgorithm() : mF{}, mFDer{}, mXMin(0), mXMax(0), mDegree(0), mMaxRemezIterations(0), mMaxBisectionIterations(0), mMaxBracketIterations(0), mPCoefficients{}, mEstimatedMaxError(0), mXNodes{}, mErrors{}, mFValues{}, mUCoefficients{}, mVCoefficients{}, mPartition{} { } size_t Execute(Function const& F, Function const& FDer, T const& xMin, T const& xMax, size_t degree, size_t maxRemezIterations, size_t maxBisectionIterations, size_t maxBracketIterations) { LogAssert(xMin < xMax&& degree > 0 && maxRemezIterations > 0 && maxBisectionIterations > 0 && maxBracketIterations, "Invalid argument."); mF = F; mFDer = FDer; mXMin = xMin; mXMax = xMax; mDegree = degree; mMaxRemezIterations = maxRemezIterations; mMaxBisectionIterations = maxBisectionIterations; mMaxBracketIterations = maxBracketIterations; mPCoefficients.resize(mDegree + 1); mEstimatedMaxError = static_cast<T>(0); mXNodes.resize(mDegree + 2); mErrors.resize(mDegree + 2); mFValues.resize(mDegree + 2); mUCoefficients.resize(mDegree + 1); mVCoefficients.resize(mDegree + 1); mEstimatedMaxError = static_cast<T>(0); mPartition.resize(mDegree + 3); ComputeInitialXNodes(); size_t iteration; for (iteration = 0; iteration < mMaxRemezIterations; ++iteration) { ComputeFAtXNodes(); ComputeUCoefficients(); ComputeVCoefficients(); ComputeEstimatedError(); ComputePCoefficients(); if (IsOscillatory()) { ComputePartition(); ComputeXExtremes(); } else { iteration = std::numeric_limits<size_t>::max(); break; } } return iteration; } // The output of the algorithm. inline std::vector<T> const& GetCoefficients() const { return mPCoefficients; } inline T GetEstimatedMaxError() const { return mEstimatedMaxError; } inline std::vector<T> const& GetXNodes() const { return mXNodes; } inline std::vector<T> const& GetErrors() const { return mErrors; } private: void ComputeInitialXNodes() { // Get the Chebyshev nodes for the interval [-1,1]. size_t const numNodes = mXNodes.size(); T const halfPiDivN = static_cast<T>(GTE_C_HALF_PI / numNodes); std::vector<T> cosAngles(numNodes); for (size_t i = 0, j = 2 * numNodes - 1; i < numNodes; ++i, j -= 2) { T angle = static_cast<T>(j) * halfPiDivN; cosAngles[i] = std::cos(angle); } if (numNodes & 1) { // Avoid the rounding errors when the angle is pi/2, where // cos(pi/2) is theoretically zero. cosAngles[numNodes / 2] = static_cast<T>(0); } // Transform the nodes to the interval [xMin, xMax]. T const half(0.5); T const center = half * (mXMax + mXMin); T const radius = half * (mXMax - mXMin); for (size_t i = 0; i < mXNodes.size(); ++i) { mXNodes[i] = center + radius * cosAngles[i]; } } void ComputeFAtXNodes() { for (size_t i = 0; i < mXNodes.size(); ++i) { mFValues[i] = mF(mXNodes[i]); } } // Compute polynomial u(x) for which u(x[i]) = F(x[i]). void ComputeUCoefficients() { for (size_t i = 0; i < mUCoefficients.size(); ++i) { mUCoefficients[i] = mFValues[i]; for (size_t j = 0; j < i; ++j) { mUCoefficients[i] -= mUCoefficients[j]; mUCoefficients[i] /= mXNodes[i] - mXNodes[j]; } } } // Compute polynomial v(x) for which v(x[i]) = (-1)^i. void ComputeVCoefficients() { T sign(1); for (size_t i = 0; i < mVCoefficients.size(); ++i) { mVCoefficients[i] = sign; for (size_t j = 0; j < i; ++j) { mVCoefficients[i] -= mVCoefficients[j]; mVCoefficients[i] /= mXNodes[i] - mXNodes[j]; } sign = -sign; } } void ComputeEstimatedError() { T const powNegOne = static_cast<T>((mDegree & 1) ? -1 : +1); T const& xBack = mXNodes.back(); T const& fBack = mFValues.back(); T uBack = EvaluateU(xBack); T vBack = EvaluateV(xBack); mEstimatedMaxError = (uBack - fBack) / (vBack + powNegOne); } void ComputePCoefficients() { // Compute the P-polynomial symbolically as a Newton polynomial // in order to obtain the coefficients from the t-powers. size_t const numCoefficients = mUCoefficients.size(); std::vector<T> constant(numCoefficients); for (size_t i = 0; i < numCoefficients; ++i) { constant[i] = mUCoefficients[i] - mEstimatedMaxError * mVCoefficients[i]; } T const one(1); size_t index = numCoefficients - 1; Polynomial1<T> poly{ constant[index--] }; for (size_t i = 1; i < numCoefficients; ++i, --index) { Polynomial1<T> linear{ -mXNodes[index], one }; poly = constant[index] + linear * poly; } for (size_t i = 0; i < numCoefficients; ++i) { mPCoefficients[i] = poly[static_cast<uint32_t>(i)]; } } bool IsOscillatory() { // Compute the errors |F(x)-P(x)| for the current nodes and // verify they are oscillatory. for (size_t i = 0; i < mXNodes.size(); ++i) { mErrors[i] = mF(mXNodes[i]) - EvaluateP(mXNodes[i]); } T const zero(0); for (size_t i0 = 0, i1 = 1; i1 < mXNodes.size(); i0 = i1++) { if ((mErrors[i0] > zero && mErrors[i1] > zero) || (mErrors[i0] < zero && mErrors[i1] < zero)) { // The process terminates when the errors are not // oscillatory. return false; } } return true; } void ComputePartition() { // Define E(x) = F(x) - P(x). Use bisection to compute the roots // of E(x). The algorithm partitions [xMin, xMax] into degree+2 // subintervals, each subinterval with E(x) positive or with E(x) // negative. Later, the local extrema on the subintervals are // computed using a quadratic-fit line-search algorithm. The // extreme locations become the next set of x-nodes. T const zero(0), half(0.5); mPartition.front() = mXMin; mPartition.back() = mXMax; for (size_t i0 = 0, i1 = 1; i1 < mXNodes.size(); i0 = i1++) { T x0 = mXNodes[i0], x1 = mXNodes[i1], xMid(0), eMid(0); int32_t sign0 = (mErrors[i0] > zero ? 1 : -1); int32_t sign1 = (mErrors[i1] > zero ? 1 : -1); int32_t signMid; size_t iteration; for (iteration = 0; iteration < mMaxBisectionIterations; ++iteration) { xMid = half * (x0 + x1); if (xMid == x0 || xMid == x1) { // We are at the limit of floating-point precision for // the average of endpoints. break; } // Update the correct endpoint to the midpoint. eMid = mF(xMid) - EvaluateP(xMid); signMid = (eMid > zero ? 1 : (eMid < zero ? -1 : 0)); if (signMid == sign0) { x0 = xMid; } else if (signMid == sign1) { x1 = xMid; } else { // Found a root (numerically rounded to zero). break; } } // It is possible that the maximum number of bisections was // applied without convergence. Use the last computed xMid // as the root. mPartition[i1] = xMid; } } // Use a quadratic-fit line-search (QFLS) to find the local extrema. void ComputeXExtremes() { T const zero(0), half(0.5); T const w0 = static_cast<T>(0.6); T const w1 = static_cast<T>(0.4); T x0, xm, x1, e0, em, e1; std::vector<T> nextXNodes(mXNodes.size()); // The interval [xMin,mPartition[1]] might not have an interior // local extrema. If the QFLS does not produce a bracket, use // the average (x0+x1)/2 as the local extreme location. x0 = mPartition[0]; x1 = mPartition[1]; xm = w0 * x0 + w1 * x1; e0 = -std::fabs(mF(x0) - EvaluateP(x0)); e1 = zero; em = -std::fabs(mF(xm) - EvaluateP(xm)); if (em < e0 && em < e1) { nextXNodes[0] = GetXExtreme(x0, e0, xm, em, x1, e1); } else { nextXNodes[0] = half * (x0 + x1); } // These subintervals have interior local extrema. for (size_t i0 = 1, i1 = 2; i0 < mDegree + 1; i0 = i1++) { nextXNodes[i0] = GetXExtreme(mPartition[i0], mPartition[i1]); } // The interval [mPartition[deg+1],xMax] might not have an // interior local extrema. If the QFLS does not produce a // bracket, use xMax as the local extreme location. x0 = mPartition[mDegree + 1]; x1 = mPartition[mDegree + 2]; xm = w0 * x0 + w1 * x1; e0 = zero; e1 = -std::fabs(mF(x1) - EvaluateP(x1)); em = -std::fabs(mF(xm) - EvaluateP(xm)); if (em < e0 && em < e1) { nextXNodes[mDegree + 1] = GetXExtreme(x0, e0, xm, em, x1, e1); } else { nextXNodes[mDegree + 1] = half * (x0 + x1); } mXNodes = nextXNodes; } // Let E(x) = -|F(x) - P(x)|. This function is called when // {(x0,E(x0)), (xm,E(xm)), (x1,E(x1)} brackets a minimum of E(x). T GetXExtreme(T x0, T e0, T xm, T em, T x1, T e1) { T const zero(0), half(0.5); for (size_t iteration = 0; iteration < mMaxBracketIterations; ++iteration) { // Compute the vertex of the interpolating parabola. T difXmX1 = xm - x0; T difX1X0 = x1 - x0; T difX0Xm = x0 - xm; T sumXmX1 = xm + x1; T sumX1X0 = x1 + x0; T sumX0Xm = x0 + xm; T tmp0 = difXmX1 * e0; T tmpm = difX1X0 * em; T tmp1 = difX0Xm * e1; T numer = sumXmX1 * tmp0 + sumX1X0 * tmpm + sumX0Xm * tmp1; T denom = tmp0 + tmpm + tmp1; if (denom == zero) { return xm; } T xv = half * numer / denom; if (xv <= x0 || xv >= x1) { return xv; } T ev = -std::fabs(mF(xv) - EvaluateP(xv)); if (xv < xm) { if (ev < em) { x1 = xm; e1 = em; xm = xv; em = ev; } else { x0 = xv; e0 = ev; } } else if (xv > xm) { if (ev < em) { x0 = xm; e0 = em; xm = xv; em = ev; } else { x1 = xv; e1 = ev; } } else { return xv; } } return xm; } T GetXExtreme(T x0, T x1) { T const zero(0); T eder0 = mFDer(x0) - EvaluatePDer(x0); T eder1 = mFDer(x1) - EvaluatePDer(x1); int32_t signEDer0 = (eder0 > zero ? 1 : (eder0 < zero ? -1 : 0)); int32_t signEDer1 = (eder1 > zero ? 1 : (eder1 < zero ? -1 : 0)); LogAssert(signEDer0 * signEDer1 == -1, "Opposite signs required."); T const half(0.5); T xmid(0), ederMid(0); int32_t signEMid = 0; for (size_t i = 0; i < mMaxBisectionIterations; ++i) { xmid = half * (x0 + x1); if (xmid == x0 || xmid == x1) { return xmid; } ederMid = mFDer(xmid) - EvaluatePDer(xmid); signEMid = (ederMid > zero ? 1 : (ederMid < zero ? -1 : 0)); if (signEMid == signEDer0) { x0 = xmid; } else if (signEMid == signEDer1) { x1 = xmid; } else { break; } } return xmid; } // Evaluate u(x) = // u[0]+(x-xn[0])*(u[1]+(x-xn[1])*(u[2]+...+(x-xn[n-1])*u[n-1])) T EvaluateU(T const& x) { size_t index = mUCoefficients.size() - 1; T result = mUCoefficients[index--]; for (size_t i = 1; i < mUCoefficients.size(); ++i, --index) { result = mUCoefficients[index] + (x - mXNodes[index]) * result; } return result; } // Evaluate v(x) = // v[0]+(x-xn[0])*(v[1]+(x-xn[1])*(v[2]+...+(x-xn[n-1])*v[n-1])) T EvaluateV(T const& x) { size_t index = mVCoefficients.size() - 1; T result = mVCoefficients[index--]; for (size_t i = 1; i < mVCoefficients.size(); ++i, --index) { result = mVCoefficients[index] + (x - mXNodes[index]) * result; } return result; } // Evaluate p(x) = sum_{i=0}^{n} p[i] * x^i. T EvaluateP(T const& x) { size_t index = mPCoefficients.size() - 1; T result = mPCoefficients[index--]; for (size_t i = 1; i < mPCoefficients.size(); ++i, --index) { result = mPCoefficients[index] + x * result; } return result; } T EvaluatePDer(T const& x) { size_t index = mPCoefficients.size() - 1; T result = static_cast<T>(index) * mPCoefficients[index]; --index; for (size_t i = 2; i < mPCoefficients.size(); ++i, --index) { result = static_cast<T>(index) * mPCoefficients[index] + x * result; } return result; } // Inputs to Execute(...). Function mF; Function mFDer; T mXMin; T mXMax; size_t mDegree; size_t mMaxRemezIterations; size_t mMaxBisectionIterations; size_t mMaxBracketIterations; // Outputs from Execute(...). std::vector<T> mPCoefficients; T mEstimatedMaxError; std::vector<T> mXNodes; std::vector<T> mErrors; // Members used in the intermediate computations. std::vector<T> mFValues; std::vector<T> mUCoefficients; std::vector<T> mVCoefficients; std::vector<T> mPartition; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/UIntegerALU32.h
.h
22,385
573
// 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 <algorithm> // Support for unsigned integer arithmetic in BSNumber and BSRational. The // Curiously Recurring Template Paradigm is used to allow the UInteger // types to share code without introducing virtual functions. namespace gte { template <typename UInteger> class UIntegerALU32 { public: // Comparisons. These are not generic. They rely on their being // called when the two BSNumber arguments to BSNumber::operatorX() // are of the form 1.u*2^p and 1.v*2^p. The comparisons apply to // 1.u and 1.v as unsigned integers with their leading 1-bits aligned. bool operator==(UInteger const& number) const { UInteger const& self = *(UInteger const*)this; int32_t numBits = self.GetNumBits(); if (numBits != number.GetNumBits()) { return false; } if (numBits > 0) { auto const& bits = self.GetBits(); auto const& nBits = number.GetBits(); int32_t const last = self.GetSize() - 1; for (int32_t i = last; i >= 0; --i) { if (bits[i] != nBits[i]) { return false; } } } return true; } bool operator!=(UInteger const& number) const { return !operator==(number); } bool operator< (UInteger const& number) const { UInteger const& self = *(UInteger const*)this; int32_t nNumBits = number.GetNumBits(); auto const& nBits = number.GetBits(); int32_t numBits = self.GetNumBits(); if (numBits > 0 && nNumBits > 0) { // The numbers must be compared as if they are left-aligned // with each other. We got here because we had // self = 1.u * 2^p and number = 1.v * 2^p. Although they // have the same exponent, it is possible that // 'self < number' but 'numBits(1u) > numBits(1v)'. Compare // the bits one 32-bit block at a time. auto const& bits = self.GetBits(); int32_t bitIndex0 = numBits - 1; int32_t bitIndex1 = nNumBits - 1; int32_t block0 = bitIndex0 / 32; int32_t block1 = bitIndex1 / 32; int32_t numBlockBits0 = 1 + (bitIndex0 % 32); int32_t numBlockBits1 = 1 + (bitIndex1 % 32); uint64_t n0shift = bits[block0]; uint64_t n1shift = nBits[block1]; while (block0 >= 0 && block1 >= 0) { // Shift the bits in the leading blocks to the high-order bit. uint32_t value0 = (uint32_t)((n0shift << (32 - numBlockBits0)) & 0x00000000FFFFFFFFull); uint32_t value1 = (uint32_t)((n1shift << (32 - numBlockBits1)) & 0x00000000FFFFFFFFull); // Shift bits in the next block (if any) to fill the current // block. if (--block0 >= 0) { n0shift = bits[block0]; value0 |= (uint32_t)((n0shift >> numBlockBits0) & 0x00000000FFFFFFFFull); } if (--block1 >= 0) { n1shift = nBits[block1]; value1 |= (uint32_t)((n1shift >> numBlockBits1) & 0x00000000FFFFFFFFull); } if (value0 < value1) { return true; } if (value0 > value1) { return false; } } return block0 < block1; } else { // One or both numbers are zero. The only time 'less than' is // 'true' is when 'number' is positive. return nNumBits > 0; } } bool operator<=(UInteger const& number) const { return operator<(number) || operator==(number); } bool operator> (UInteger const& number) const { return !operator<=(number); } bool operator>=(UInteger const& number) const { return !operator<(number); } // Arithmetic operations. These are performed in-place; that is, the // result is stored in 'this' object. The goal is to reduce the // number of object copies, much like the goal is for std::move. The // Sub function requires the inputs to satisfy n0 > n1. void Add(UInteger const& n0, UInteger const& n1) { UInteger& self = *(UInteger*)this; int32_t n0NumBits = n0.GetNumBits(); int32_t n1NumBits = n1.GetNumBits(); // Add the numbers considered as positive integers. Set the last // block to zero in case no carry-out occurs. int32_t numBits = std::max(n0NumBits, n1NumBits) + 1; self.SetNumBits(numBits); self.SetBack(0); // Get the input array sizes. int32_t numElements0 = n0.GetSize(); int32_t numElements1 = n1.GetSize(); // Order the inputs so that the first has the most blocks. auto const& u0 = (numElements0 >= numElements1 ? n0.GetBits() : n1.GetBits()); auto const& u1 = (numElements0 >= numElements1 ? n1.GetBits() : n0.GetBits()); auto numElements = std::minmax(numElements0, numElements1); // Add the u1-blocks to u0-blocks. auto& bits = self.GetBits(); uint64_t carry = 0, sum; int32_t i; for (i = 0; i < numElements.first; ++i) { sum = u0[i] + (u1[i] + carry); bits[i] = (uint32_t)(sum & 0x00000000FFFFFFFFull); carry = (sum >> 32); } // We have no more u1-blocks. Propagate the carry-out, if there is // one, or copy the remaining blocks if there is not. if (carry > 0) { for (/**/; i < numElements.second; ++i) { sum = u0[i] + carry; bits[i] = (uint32_t)(sum & 0x00000000FFFFFFFFull); carry = (sum >> 32); } if (carry > 0) { #if defined(GTE_USE_MSWINDOWS) #pragma warning(disable : 28020) #endif bits[i] = (uint32_t)(carry & 0x00000000FFFFFFFFull); #if defined(GTE_USE_MSWINDOWS) #pragma warning(default : 28020) #endif } } else { for (/**/; i < numElements.second; ++i) { bits[i] = u0[i]; } } // Reduce the number of bits if there was not a carry-out. uint32_t firstBitIndex = (numBits - 1) % 32; uint32_t mask = (1 << firstBitIndex); if ((mask & self.GetBack()) == 0) { self.SetNumBits(--numBits); } } void Sub(UInteger const& n0, UInteger const& n1) { UInteger& self = *(UInteger*)this; int32_t n0NumBits = n0.GetNumBits(); auto const& n0Bits = n0.GetBits(); auto const& n1Bits = n1.GetBits(); // Subtract the numbers considered as positive integers. We know // that n0 > n1, so create a number n2 that has the same number of // bits as n0 and use two's-complement to generate -n2, and then // add n0 and -n2. The result is nonnegative, so we do not need // to apply two's complement to a negative result to extract the // sign and absolute value. // Get the input array sizes. We know // numElements0 >= numElements1. int32_t numElements0 = n0.GetSize(); int32_t numElements1 = n1.GetSize(); // Create the two's-complement number n2. We know // n2.GetNumElements() is the same as numElements0. UInteger n2{}; n2.SetNumBits(n0NumBits); auto& n2Bits = n2.GetBits(); int32_t i; for (i = 0; i < numElements1; ++i) { n2Bits[i] = ~n1Bits[i]; } for (/**/; i < numElements0; ++i) { n2Bits[i] = ~0u; } // Now add 1 to the bit-negated result to obtain -n1. uint64_t carry = 1, sum; for (i = 0; i < numElements0; ++i) { sum = n2Bits[i] + carry; n2Bits[i] = (uint32_t)(sum & 0x00000000FFFFFFFFull); carry = (sum >> 32); } // Add the numbers as positive integers. Set the last block to // zero in case no carry-out occurs. self.SetNumBits(n0NumBits + 1); self.SetBack(0); // Add the n0-blocks to n2-blocks. auto & bits = self.GetBits(); for (i = 0, carry = 0; i < numElements0; ++i) { sum = n2Bits[i] + (n0Bits[i] + carry); bits[i] = (uint32_t)(sum & 0x00000000FFFFFFFFull); carry = (sum >> 32); } // Strip off the bits introduced by two's-complement. int32_t block; for (block = numElements0 - 1; block >= 0; --block) { if (bits[block] > 0) { break; } } if (block >= 0) { self.SetNumBits(32 * block + BitHacks::GetLeadingBit(bits[block]) + 1); } else { // This block originally did not exist, only the if-block did. // During some testing for the RAEGC book, a crash occurred // where it appeared the block was needed. I added this block // to fix the problem, but had forgotten the precondition that // n0 > n1. Consequently, I did not look carefully at the // inputs and call stack to determine how this could have // happened. Trap this problem and analyze the call stack and // inputs that lead to this case if it happens again. The call // stack is started by BSNumber::SubIgnoreSign(...). self.SetNumBits(0); LogError("The difference of the number is zero, which violates the precondition n0 > n1."); } } void Mul(UInteger const& n0, UInteger const& n1) { UInteger& self = *(UInteger*)this; int32_t n0NumBits = n0.GetNumBits(); int32_t n1NumBits = n1.GetNumBits(); auto const& n0Bits = n0.GetBits(); auto const& n1Bits = n1.GetBits(); // The number of bits is at most this, possibly one bit smaller. int32_t numBits = n0NumBits + n1NumBits; self.SetNumBits(numBits); auto& bits = self.GetBits(); // Product of a single-block number with a multiple-block number. UInteger product{}; product.SetNumBits(numBits); auto& pBits = product.GetBits(); // Get the array sizes. int32_t const numElements0 = n0.GetSize(); int32_t const numElements1 = n1.GetSize(); int32_t const numElements = self.GetSize(); // Compute the product v = u0*u1. int32_t i0, i1, i2; uint64_t term, sum; // The case i0 == 0 is handled separately to initialize the // accumulator with u0[0]*v. This avoids having to fill the bytes // of 'bits' with zeros outside the double loop, something that // can be a performance issue when 'numBits' is large. uint64_t block0 = n0Bits[0]; uint64_t carry = 0; for (i1 = 0; i1 < numElements1; ++i1) { term = block0 * n1Bits[i1] + carry; bits[i1] = (uint32_t)(term & 0x00000000FFFFFFFFull); carry = (term >> 32); } if (i1 < numElements) { bits[i1] = (uint32_t)(carry & 0x00000000FFFFFFFFull); } for (i0 = 1; i0 < numElements0; ++i0) { // Compute the product p = u0[i0]*u1. block0 = n0Bits[i0]; carry = 0; for (i1 = 0, i2 = i0; i1 < numElements1; ++i1, ++i2) { term = block0 * n1Bits[i1] + carry; pBits[i2] = (uint32_t)(term & 0x00000000FFFFFFFFull); carry = (term >> 32); } if (i2 < numElements) { pBits[i2] = (uint32_t)(carry & 0x00000000FFFFFFFFull); } // Add p to the accumulator v. carry = 0; for (i1 = 0, i2 = i0; i1 < numElements1; ++i1, ++i2) { sum = pBits[i2] + (bits[i2] + carry); bits[i2] = (uint32_t)(sum & 0x00000000FFFFFFFFull); carry = (sum >> 32); } if (i2 < numElements) { sum = pBits[i2] + carry; bits[i2] = (uint32_t)(sum & 0x00000000FFFFFFFFull); } } // Reduce the number of bits if there was not a carry-out. uint32_t firstBitIndex = (numBits - 1) % 32; uint32_t mask = (1 << firstBitIndex); if ((mask & self.GetBack()) == 0) { self.SetNumBits(--numBits); } } // The shift is performed in-place; that is, the result is stored in // 'this' object. void ShiftLeft(UInteger const& number, int32_t shift) { UInteger& self = *(UInteger*)this; int32_t nNumBits = number.GetNumBits(); auto const& nBits = number.GetBits(); // Shift the 'number' considered as an odd positive integer. self.SetNumBits(nNumBits + shift); // Set the low-order bits to zero. auto& bits = self.GetBits(); int32_t const shiftBlock = shift / 32; for (int32_t i = 0; i < shiftBlock; ++i) { bits[i] = 0; } // Get the location of the low-order 1-bit within the result. int32_t const numInElements = number.GetSize(); int32_t const lshift = shift % 32; int32_t i, j; if (lshift > 0) { // The trailing 1-bits for source and target are at different // relative indices. Each shifted source block straddles a // boundary between two target blocks, so we must extract the // subblocks and copy accordingly. int32_t const rshift = 32 - lshift; uint32_t prev = 0, curr; for (i = shiftBlock, j = 0; j < numInElements; ++i, ++j) { curr = nBits[j]; bits[i] = (curr << lshift) | (prev >> rshift); prev = curr; } if (i < self.GetSize()) { // The leading 1-bit of the source is at a relative index // such that when you add the shift amount, that bit // occurs in a new block. #if defined(GTE_USE_MSWINDOWS) #pragma warning(disable : 28020) #endif bits[i] = (prev >> rshift); #if defined(GTE_USE_MSWINDOWS) #pragma warning(default : 28020) #endif } } else { // The trailing 1-bits for source and target are at the same // relative index. The shift reduces to a block copy. for (i = shiftBlock, j = 0; j < numInElements; ++i, ++j) { bits[i] = nBits[j]; } } } // The 'number' is even and positive. It is shifted right to become // an odd number and the return value is the amount shifted. The // operation is performed in-place; that is, the result is stored in // 'this' object. int32_t ShiftRightToOdd(UInteger const& number) { UInteger& self = *(UInteger*)this; auto const& nBits = number.GetBits(); // Get the leading 1-bit. int32_t const numElements = number.GetSize(); int32_t const numM1 = numElements - 1; int32_t firstBitIndex = 32 * numM1 + BitHacks::GetLeadingBit(nBits[numM1]); // Get the trailing 1-bit. int32_t lastBitIndex = -1; for (int32_t block = 0; block < numElements; ++block) { uint32_t value = nBits[block]; if (value > 0) { lastBitIndex = 32 * block + BitHacks::GetTrailingBit(value); break; } } // The right-shifted result. self.SetNumBits(firstBitIndex - lastBitIndex + 1); auto& bits = self.GetBits(); int32_t const numBlocks = self.GetSize(); // Get the location of the low-order 1-bit within the result. int32_t const shiftBlock = lastBitIndex / 32; int32_t rshift = lastBitIndex % 32; if (rshift > 0) { int32_t const lshift = 32 - rshift; int32_t i, j = shiftBlock; uint32_t curr = nBits[j++]; for (i = 0; j < numElements; ++i, ++j) { uint32_t next = nBits[j]; bits[i] = (curr >> rshift) | (next << lshift); curr = next; } if (i < numBlocks) { bits[i] = (curr >> rshift); } } else { for (int32_t i = 0, j = shiftBlock; i < numBlocks; ++i, ++j) { bits[i] = nBits[j]; } } return rshift + 32 * shiftBlock; } // Add 1 to 'this', useful for rounding modes in conversions of // BSNumber and BSRational. The operation is performed in-place; // that is, the result is stored in 'this' object. The return value // is the amount shifted after the addition in order to obtain an // odd integer. int32_t RoundUp() { UInteger const& self = *(UInteger const*)this; UInteger rounded{}; rounded.Add(self, UInteger(1u)); return ShiftRightToOdd(rounded); } // Get a block of numRequested bits starting with the leading 1-bit of // the nonzero number. The returned number has the prefix stored in // the high-order bits. Additional bits are copied and used by the // caller for rounding. This function supports conversions from // 'float' and 'double'. The input 'numRequested' is smaller than 64. uint64_t GetPrefix(int32_t numRequested) const { UInteger const& self = *(UInteger const*)this; auto const& bits = self.GetBits(); // Copy to 'prefix' the leading 32-bit block that is nonzero. int32_t bitIndex = self.GetNumBits() - 1; int32_t blockIndex = bitIndex / 32; uint64_t prefix = bits[blockIndex]; // Get the number of bits in the block starting with the leading // 1-bit. int32_t firstBitIndex = bitIndex % 32; int32_t numBlockBits = firstBitIndex + 1; // Shift the leading 1-bit to bit-63 of prefix. We have consumed // numBlockBits, which might not be the entire budget. int32_t targetIndex = 63; int32_t shift = targetIndex - firstBitIndex; prefix <<= static_cast<uint32_t>(shift); numRequested -= numBlockBits; targetIndex -= numBlockBits; if (numRequested > 0 && --blockIndex >= 0) { // More bits are available. Copy and shift the entire 32-bit // next block and OR it into the 'prefix'. For 'float', we // will have consumed the entire budget. For 'double', we // might have to get bits from a third block. uint64_t nextBlock = bits[blockIndex]; shift = targetIndex - 31; // Shift amount is positive. nextBlock <<= static_cast<uint32_t>(shift); prefix |= nextBlock; numRequested -= 32; targetIndex -= 32; if (numRequested > 0 && --blockIndex >= 0) { // We know that targetIndex > 0; only 'double' allows us // to get here, so numRequested is at most 53. We also // know that targetIndex < 32 because we started with 63 // and subtracted at least 32 from it. Thus, the shift // amount is positive. nextBlock = bits[blockIndex]; shift = 31 - targetIndex; nextBlock >>= static_cast<uint32_t>(shift); prefix |= nextBlock; } } return prefix; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistSegment3OrientedBox3.h
.h
2,816
78
// 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/DistLine3OrientedBox3.h> #include <Mathematics/DistPointOrientedBox.h> #include <Mathematics/Segment.h> // Compute the distance between a segment and a solid orienteded 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 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 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>, OrientedBox3<T>> { public: using LBQuery = DCPQuery<T, Line3<T>, OrientedBox3<T>>; using Result = typename LBQuery::Result; Result operator()(Segment3<T> const& segment, OrientedBox3<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>, OrientedBox3<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>, OrientedBox3<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/Polygon2.h
.h
9,763
271
// 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/IntrSegment2Segment2.h> #include <set> #include <vector> // The Polygon2 object represents a simple polygon: No duplicate vertices, // closed (each vertex is shared by exactly two edges), and no // self-intersections at interior edge points. The 'vertexPool' array can // contain more points than needed to define the polygon, which allows the // vertex pool to have multiple polygons associated with it. Thus, the // programmer must ensure that the vertex pool persists as long as any // Polygon2 objects exist that depend on the pool. The number of polygon // vertices is 'numIndices' and must be 3 or larger. The 'indices' array // refers to the points in 'vertexPool' that are part of the polygon and must // have 'numIndices' unique elements. The edges of the polygon are pairs of // indices into 'vertexPool', // edge[0] = (indices[0], indices[1]) // : // edge[numIndices-2] = (indices[numIndices-2], indices[numIndices-1]) // edge[numIndices-1] = (indices[numIndices-1], indices[0]) // The programmer should ensure the polygon is simple. The geometric // queries are valid regardless of whether the polygon is oriented clockwise // or counterclockwise. // // NOTE: Comparison operators are not provided. The semantics of equal // polygons is complicated and (at the moment) not useful. The vertex pools // can be different and indices do not match, but the vertices they reference // can match. Even with a shared vertex pool, the indices can be "rotated", // leading to the same polygon abstractly but the data structures do not // match. namespace gte { template <typename Real> class Polygon2 { public: // Construction. The constructor succeeds when 'numIndices' >= 3 and // 'vertexPool' and 'indices' are not null; we cannot test whether you // have a valid number of elements in the input arrays. A copy is // made of 'indices', but the 'vertexPool' is not copied. If the // constructor fails, the internal vertex pointer is set to null, the // index array has no elements, and the orientation is set to // clockwise. Polygon2(Vector2<Real> const* vertexPool, int32_t numIndices, int32_t const* indices, bool counterClockwise) : mVertexPool(vertexPool), mCounterClockwise(counterClockwise) { if (numIndices >= 3 && vertexPool && indices) { for (int32_t i = 0; i < numIndices; ++i) { mVertices.insert(indices[i]); } if (numIndices == static_cast<int32_t>(mVertices.size())) { mIndices.resize(numIndices); std::copy(indices, indices + numIndices, mIndices.begin()); return; } // At least one duplicated vertex was encountered, so the // polygon is not simple. Fail the constructor call. mVertices.clear(); } // Invalid input to the Polygon2 constructor. mVertexPool = nullptr; mCounterClockwise = false; } // To validate construction, create an object as shown: // Polygon2<Real> polygon(parameters); // if (!polygon) { <constructor failed, handle accordingly>; } inline operator bool() const { return mVertexPool != nullptr; } // Member access. inline Vector2<Real> const* GetVertexPool() const { return mVertexPool; } inline std::set<int32_t> const& GetVertices() const { return mVertices; } inline std::vector<int32_t> const& GetIndices() const { return mIndices; } inline bool CounterClockwise() const { return mCounterClockwise; } // Geometric queries. Vector2<Real> ComputeVertexAverage() const { Vector2<Real> average = Vector2<Real>::Zero(); if (mVertexPool) { for (int32_t index : mVertices) { average += mVertexPool[index]; } average /= static_cast<Real>(mVertices.size()); } return average; } Real ComputePerimeterLength() const { Real length(0); if (mVertexPool) { Vector2<Real> v0 = mVertexPool[mIndices.back()]; for (int32_t index : mIndices) { Vector2<Real> v1 = mVertexPool[index]; length += Length(v1 - v0); v0 = v1; } } return length; } Real ComputeArea() const { Real area(0); if (mVertexPool) { size_t const numIndices = mIndices.size(); Vector2<Real> v0 = mVertexPool[mIndices[numIndices - 2]]; Vector2<Real> v1 = mVertexPool[mIndices[numIndices - 1]]; for (int32_t index : mIndices) { Vector2<Real> v2 = mVertexPool[index]; area += v1[0] * (v2[1] - v0[1]); v0 = v1; v1 = v2; } area *= (Real)0.5; } return std::fabs(area); } // Simple polygons have no self-intersections at interior points // of edges. The test is an exhaustive all-pairs intersection // test for edges, which is inefficient for polygons with a large // number of vertices. TODO: Provide an efficient algorithm that // uses the algorithm of class RectangleManager.h. bool IsSimple() const { if (!mVertexPool) { return false; } // For mVertexPool to be nonnull, the number of indices is // guaranteed to be at least 3. int32_t const numIndices = static_cast<int32_t>(mIndices.size()); if (numIndices == 3) { // The polygon is a triangle. return true; } return IsSimpleInternal(); } // Convex polygons are simple polygons where the angles between // consecutive edges are less than or equal to pi radians. bool IsConvex() const { if (!mVertexPool) { return false; } // For mVertexPool to be nonnull, the number of indices is // guaranteed to be at least 3. int32_t const numIndices = static_cast<int32_t>(mIndices.size()); if (numIndices == 3) { // The polygon is a triangle. return true; } return IsSimpleInternal() && IsConvexInternal(); } private: // These calls have preconditions that mVertexPool is not null and // mIndices.size() > 3. The heart of the algorithms are implemented // here. bool IsSimpleInternal() const { Segment2<Real> seg0, seg1; TIQuery<Real, Segment2<Real>, Segment2<Real>> query; typename TIQuery<Real, Segment2<Real>, Segment2<Real>>::Result result; int32_t const numIndices = static_cast<int32_t>(mIndices.size()); for (int32_t i0 = 0; i0 < numIndices; ++i0) { int32_t i0p1 = (i0 + 1) % numIndices; seg0.p[0] = mVertexPool[mIndices[i0]]; seg0.p[1] = mVertexPool[mIndices[i0p1]]; int32_t i1min = (i0 + 2) % numIndices; int32_t i1max = (i0 - 2 + numIndices) % numIndices; for (int32_t i1 = i1min; i1 <= i1max; ++i1) { int32_t i1p1 = (i1 + 1) % numIndices; seg1.p[0] = mVertexPool[mIndices[i1]]; seg1.p[1] = mVertexPool[mIndices[i1p1]]; result = query(seg0, seg1); if (result.intersect) { return false; } } } return true; } bool IsConvexInternal() const { Real sign = (mCounterClockwise ? (Real)1 : (Real)-1); int32_t const numIndices = static_cast<int32_t>(mIndices.size()); for (int32_t i = 0; i < numIndices; ++i) { int32_t iPrev = (i + numIndices - 1) % numIndices; int32_t iNext = (i + 1) % numIndices; Vector2<Real> vPrev = mVertexPool[mIndices[iPrev]]; Vector2<Real> vCurr = mVertexPool[mIndices[i]]; Vector2<Real> vNext = mVertexPool[mIndices[iNext]]; Vector2<Real> edge0 = vCurr - vPrev; Vector2<Real> edge1 = vNext - vCurr; Real test = sign * DotPerp(edge0, edge1); if (test < (Real)0) { return false; } } return true; } Vector2<Real> const* mVertexPool; std::set<int32_t> mVertices; std::vector<int32_t> mIndices; bool mCounterClockwise; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MinHeap.h
.h
15,679
423
// 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> // A min-heap is a binary tree whose nodes have weights and with the // constraint that the weight of a parent node is less than or equal to the // weights of its children. This data structure may be used as a priority // queue. If the std::priority_queue interface suffices for your needs, use // that instead. However, for some geometric algorithms, that interface is // insufficient for optimal performance. For example, if you have a polyline // vertices that you want to decimate, each vertex's weight depends on its // neighbors' locations. If the minimum-weight vertex is removed from the // min-heap, the neighboring vertex weights must be updated--something that // is O(1) time when you store the vertices as a doubly linked list. The // neighbors are already in the min-heap, so modifying their weights without // removing then from--and then reinserting into--the min-heap requires they // must be moved to their proper places to restore the invariant of the // min-heap. With std::priority_queue, you have no direct access to the // modified vertices, forcing you to search for those vertices, remove them, // update their weights, and re-insert them. The min-heap implementation here // does support the update without removal and reinsertion. // // The ValueType represents the weight and it must support comparisons // "<" and "<=". Additional information can be stored in the min-heap for // convenient access; this is stored as the KeyType. In the (open) polyline // decimation example, the KeyType is a structure that stores indices to // a vertex and its neighbors. The following code illustrates the creation // and use of the min-heap. The Weight() function is whatever you choose to // guide which vertices are removed first from the polyline. // // struct Vertex { int32_t previous, current, next; }; // int32_t numVertices = <number of polyline vertices>; // std::vector<Vector<N, Real>> positions(numVertices); // <assign all positions[*]>; // MinHeap<Vertex, Real> minHeap(numVertices); // std::vector<MinHeap<Vertex, Real>::Record*> records(numVertices); // for (int32_t i = 0; i < numVertices; ++i) // { // Vertex vertex; // vertex.previous = (i + numVertices - 1) % numVertices; // vertex.current = i; // vertex.next = (i + 1) % numVertices; // records[i] = minHeap.Insert(vertex, Weight(positions, vertex)); // } // // while (minHeap.GetNumElements() >= 2) // { // Vertex vertex; // Real weight; // minHeap.Remove(vertex, weight); // <consume the 'vertex' according to your application's needs>; // // // Remove 'vertex' from the doubly linked list. // Vertex& vp = records[vertex.previous]->key; // Vertex& vc = records[vertex.current]->key; // Vertex& vn = records[vertex.next]->key; // vp.next = vc.next; // vn.previous = vc.previous; // // // Update the neighbors' weights in the min-heap. // minHeap.Update(records[vertex.previous], Weight(positions, vp)); // minHeap.Update(records[vertex.next], Weight(positions, vn)); // } namespace gte { template <typename KeyType, typename ValueType> class MinHeap { public: struct Record { Record() : key{}, value{}, index(-1) { } KeyType key; ValueType value; int32_t index; }; // Construction. The record 'value' members are uninitialized for // native types chosen for ValueType. If ValueType is of class type, // then the default constructor is used to set the 'value' members. MinHeap(int32_t maxElements = 0) { Reset(maxElements); } MinHeap(MinHeap const& minHeap) { *this = minHeap; } // Assignment. MinHeap& operator=(MinHeap const& minHeap) { mNumElements = minHeap.mNumElements; mRecords = minHeap.mRecords; mPointers.resize(minHeap.mPointers.size()); for (auto& record : mRecords) { mPointers[record.index] = &record; } return *this; } // Clear the min-heap so that it has the specified max elements, // mNumElements is zero, and mPointers are set to the natural ordering // of mRecords. void Reset(int32_t maxElements) { mNumElements = 0; if (maxElements > 0) { mRecords.resize(maxElements); mPointers.resize(maxElements); for (int32_t i = 0; i < maxElements; ++i) { mPointers[i] = &mRecords[i]; mPointers[i]->index = i; } } else { mRecords.clear(); mPointers.clear(); } } // Get the remaining number of elements in the min-heap. This number // is in the range {0..maxElements}. inline int32_t GetNumElements() const { return mNumElements; } // Get the root of the min-heap. The return value is 'true' whenever // the min-heap is not empty. This function reads the root but does // not remove the element from the min-heap. bool GetMinimum(KeyType& key, ValueType& value) const { if (mNumElements > 0) { key = mPointers[0]->key; value = mPointers[0]->value; return true; } else { return false; } } // Insert into the min-heap the 'value' that corresponds to the 'key'. // The return value is a pointer to the heap record that stores a copy // of 'value', and the pointer value is constant for the life of the // min-heap. If you must update a member of the min-heap, say, as // illustrated in the polyline decimation example, pass the pointer to // Update: // auto* valueRecord = minHeap.Insert(key, value); // <do whatever>; // minHeap.Update(valueRecord, newValue). Record* Insert(KeyType const& key, ValueType const& value) { // Return immediately when the heap is full. if (mNumElements == static_cast<int32_t>(mRecords.size())) { return nullptr; } // Store the input information in the last heap record, which is // the last leaf in the tree. int32_t child = mNumElements++; Record* record = mPointers[child]; record->key = key; record->value = value; // Propagate the information toward the root of the tree until it // reaches its correct position, thus restoring the tree to a // valid heap. while (child > 0) { int32_t parent = (child - 1) / 2; if (mPointers[parent]->value <= value) { // The parent has a value smaller than or equal to the // child's value, so we now have a valid heap. break; } // The parent has a larger value than the child's value. Swap // the parent and child: // Move the parent into the child's slot. mPointers[child] = mPointers[parent]; mPointers[child]->index = child; // Move the child into the parent's slot. mPointers[parent] = record; mPointers[parent]->index = parent; child = parent; } return mPointers[child]; } // Remove the root of the heap and return its 'key' and 'value // members. The root contains the minimum value of all heap elements. // The return value is 'true' whenever the min-heap was not empty // before the Remove call. bool Remove(KeyType& key, ValueType& value) { // Return immediately when the heap is empty. if (mNumElements == 0) { return false; } // Get the information from the root of the heap. Record* root = mPointers[0]; key = root->key; value = root->value; // Restore the tree to a heap. Abstractly, record is the new root // of the heap. It is moved down the tree via parent-child swaps // until it is in a location that restores the tree to a heap. int32_t last = --mNumElements; Record* record = mPointers[last]; int32_t parent = 0, child = 1; while (child <= last) { if (child < last) { // Select the child with smallest value to be the one that // is swapped with the parent, if necessary. int32_t childP1 = child + 1; if (mPointers[childP1]->value < mPointers[child]->value) { child = childP1; } } if (record->value <= mPointers[child]->value) { // The tree is now a heap. break; } // Move the child into the parent's slot. mPointers[parent] = mPointers[child]; mPointers[parent]->index = parent; parent = child; child = 2 * child + 1; } // The previous 'last' record was moved to the root and propagated // down the tree to its final resting place, restoring the tree to // a heap. The slot mPointers[parent] is that resting place. mPointers[parent] = record; mPointers[parent]->index = parent; // The old root record must not be lost. Attach it to the slot // that contained the old last record. mPointers[last] = root; mPointers[last]->index = last; return true; } // The value of a heap record must be modified through this function // call. The side effect is that the heap is updated accordingly to // restore the data structure to a min-heap. The input 'record' // should be a pointer returned by Insert(value); see the comments for // the Insert() function. void Update(Record* record, ValueType const& value) { // Return immediately on invalid record. if (!record) { return; } int32_t parent, child, childP1, maxChild; if (record->value < value) { record->value = value; // The new value is larger than the old value. Propagate it // toward the leaves. parent = record->index; child = 2 * parent + 1; while (child < mNumElements) { // At least one child exists. Locate the one of maximum // value. childP1 = child + 1; if (childP1 < mNumElements) { // Two children exist. if (mPointers[child]->value <= mPointers[childP1]->value) { maxChild = child; } else { maxChild = childP1; } } else { // One child exists. maxChild = child; } if (value <= mPointers[maxChild]->value) { // The new value is in the correct place to restore // the tree to a heap. break; } // The child has a larger value than the parent's value. // Swap the parent and child: // Move the child into the parent's slot. mPointers[parent] = mPointers[maxChild]; mPointers[parent]->index = parent; // Move the parent into the child's slot. mPointers[maxChild] = record; mPointers[maxChild]->index = maxChild; parent = maxChild; child = 2 * parent + 1; } } else if (value < record->value) { record->value = value; // The new weight is smaller than the old weight. Propagate // it toward the root. child = record->index; while (child > 0) { // A parent exists. parent = (child - 1) / 2; if (mPointers[parent]->value <= value) { // The new value is in the correct place to restore // the tree to a heap. break; } // The parent has a smaller value than the child's value. // Swap the child and parent. // Move the parent into the child's slot. mPointers[child] = mPointers[parent]; mPointers[child]->index = child; // Move the child into the parent's slot. mPointers[parent] = record; mPointers[parent]->index = parent; child = parent; } } } // Support for debugging. The functions test whether the data // structure is a valid min-heap. bool IsValid() const { for (int32_t child = 0; child < mNumElements; ++child) { int32_t parent = (child - 1) / 2; if (parent > 0) { if (mPointers[child]->value < mPointers[parent]->value) { return false; } if (mPointers[parent]->index != parent) { return false; } } } return true; } private: // A 2-level storage system is used. The pointers have two roles. // Firstly, they are unique to each inserted value in order to support // the Update() capability of the min-heap. Secondly, they avoid // potentially expensive copying of Record objects as sorting occurs // in the heap. int32_t mNumElements; std::vector<Record> mRecords; std::vector<Record*> mPointers; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistLineSegment.h
.h
4,300
125
// 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/Segment.h> // Compute the distance between a line and a segment in nD. // // The segment is Q[0] + s[0] * (Q[1] - Q[0]) for 0 <= s[0] <= 1. The // direction D[0] = Q[1] - Q[0] is generally not unit length. // // The line is P[1] + s[1] * D[1], where D[i] is not required to be unit // length. // // The closest point on the segment is stored in closest[0] with parameter[0] // storing s[0]. The closest point on the line is stoed in closest[1] with // parameter[1] storing s[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, Line<N, T>, Segment<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), parameter{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<T, 2> parameter; std::array<Vector<N, T>, 2> closest; }; Result operator()(Line<N, T> const& line, Segment<N, T> const& segment) { Result result{}; T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector<N, T> segDirection = segment.p[1] - segment.p[0]; Vector<N, T> diff = line.origin - segment.p[0]; T a00 = Dot(line.direction, line.direction); T a01 = -Dot(line.direction, segDirection); T a11 = Dot(segDirection, segDirection); T b0 = Dot(line.direction, diff); T det = std::max(a00 * a11 - a01 * a01, zero); T s0{}, s1{}; if (det > zero) { // The line and segment are not parallel. T b1 = -Dot(segDirection, diff); s1 = a01 * b0 - a00 * b1; if (s1 >= zero) { if (s1 <= det) { // Two interior points are closest, one on the line // and one on the segment. s0 = (a01 * b1 - a11 * b0) / det; s1 /= det; } else { // The endpoint Q1 of the segment and an interior // point of the line are closest. s0 = -(a01 + b0) / a00; s1 = one; } } else { // The endpoint Q0 of the segment and an interior point // of the line are closest. s0 = -b0 / a00; s1 = zero; } } else { // The line and segment are parallel. Select the pair of // closest points where the closest segment point is the // endpoint Q0. s0 = -b0 / a00; s1 = zero; } result.parameter[0] = s0; result.parameter[1] = s1; result.closest[0] = line.origin + s0 * line.direction; result.closest[1] = segment.p[0] + s1 * segDirection; 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 DCPLineSegment = DCPQuery<T, Line<N, T>, Segment<N, T>>; template <typename T> using DCPLine2Segment2 = DCPLineSegment<2, T>; template <typename T> using DCPLine3Segment3 = DCPLineSegment<3, T>; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistTriangle3CanonicalBox3.h
.h
5,063
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.01.06 #pragma once #include <Mathematics/DistPlane3CanonicalBox3.h> #include <Mathematics/DistSegment3CanonicalBox3.h> #include <Mathematics/Triangle.h> // Compute the distance between a solid triangle and a solid canonical box // 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 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 triangle closest is stored in closest[0] with // barycentric coordinates (b[0],b[1],b[2]). 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, Triangle3<T>, CanonicalBox3<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) }, closest{ Vector3<T>::Zero(), Vector3<T>::Zero() } { } T distance, sqrDistance; std::array<T, 3> barycentric; std::array<Vector3<T>, 2> closest; }; Result operator()(Triangle3<T> const& triangle, CanonicalBox3<T> const& box) { Result result{}; Vector3<T> E10 = triangle.v[1] - triangle.v[0]; Vector3<T> E20 = triangle.v[2] - triangle.v[0]; Vector3<T> K = Cross(E10, E20); T sqrLength = Dot(K, K); Vector3<T> N = K; Normalize(N); using PBQuery = DCPQuery<T, Plane3<T>, CanonicalBox3<T>>; PBQuery pbQuery{}; Plane3<T> plane(N, triangle.v[0]); auto pbOutput = pbQuery(plane, box); // closest[0] = b[0] * V[0] + b[1] * V[1] + b[2] * V[2] // = V[0] + b[1] * (V[1] - V[0]) + b[2] * (V[2] - V[0]); // delta = closest[0] - V[0] = b[1] * E10 + b[2] * E20 T const zero = static_cast<T>(0); T const one = static_cast<T>(1); Vector3<T> delta = pbOutput.closest[0] - triangle.v[0]; Vector3<T> KxDelta = Cross(K, delta); result.barycentric[1] = Dot(E20, KxDelta) / sqrLength; result.barycentric[2] = -Dot(E10, KxDelta) / sqrLength; result.barycentric[0] = one - result.barycentric[1] - result.barycentric[2]; if (zero <= result.barycentric[0] && result.barycentric[0] <= one && zero <= result.barycentric[1] && result.barycentric[1] <= one && zero <= result.barycentric[2] && result.barycentric[2] <= one) { result.distance = pbOutput.distance; result.sqrDistance = pbOutput.sqrDistance; result.closest = pbOutput.closest; } else { // The closest plane point is outside the triangle, although // it is possible there are points inside the triangle that // also are closest points to the box. Regardless, locate a // point on an edge of the triangle that is closest to the // box. using SBQuery = DCPQuery<T, Segment3<T>, CanonicalBox3<T>>; SBQuery sbQuery{}; typename SBQuery::Result sbOutput{}; Segment3<T> segment{}; T const invalid = static_cast<T>(-1); result.distance = invalid; result.sqrDistance = invalid; // Compare edges of the triangle to the box. 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]; sbOutput = sbQuery(segment, box); if (result.sqrDistance == invalid || sbOutput.sqrDistance < result.sqrDistance) { result.distance = sbOutput.distance; result.sqrDistance = sbOutput.sqrDistance; result.barycentric[i0] = one - sbOutput.parameter; result.barycentric[i1] = sbOutput.parameter; result.barycentric[i2] = zero; result.closest = sbOutput.closest; } } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ExtremalQuery3.h
.h
2,254
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/Polyhedron3.h> namespace gte { template <typename Real> class ExtremalQuery3 { public: // Abstract base class. virtual ~ExtremalQuery3() = default; // Disallow copying and assignment. ExtremalQuery3(ExtremalQuery3 const&) = delete; ExtremalQuery3& operator=(ExtremalQuery3 const&) = delete; // Member access. inline Polyhedron3<Real> const& GetPolytope() const { return mPolytope; } inline std::vector<Vector3<Real>> const& GetFaceNormals() const { return mFaceNormals; } // Compute the extreme vertices in the specified direction and return // the indices of the vertices in the polyhedron vertex array. virtual void GetExtremeVertices(Vector3<Real> const& direction, int32_t& positiveDirection, int32_t& negativeDirection) = 0; protected: // The caller must ensure that the input polyhedron is convex. ExtremalQuery3(Polyhedron3<Real> const& polytope) : mPolytope(polytope), mFaceNormals{} { // Create the face normals. auto vertexPool = mPolytope.GetVertices(); auto const& indices = mPolytope.GetIndices(); size_t const numTriangles = indices.size() / 3; mFaceNormals.resize(numTriangles); for (size_t t = 0; t < numTriangles; ++t) { Vector3<Real> v0 = vertexPool[indices[3 * t + 0]]; Vector3<Real> v1 = vertexPool[indices[3 * t + 1]]; Vector3<Real> v2 = vertexPool[indices[3 * t + 2]]; Vector3<Real> edge1 = v1 - v0; Vector3<Real> edge2 = v2 - v0; mFaceNormals[t] = UnitCross(edge1, edge2); } } Polyhedron3<Real> const& mPolytope; std::vector<Vector3<Real>> mFaceNormals; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrCircle2Arc2.h
.h
2,676
83
// 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, Circle2<T>, Arc2<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), point{ Vector2<T>::Zero(), Vector2<T>::Zero() }, arc(Vector2<T>::Zero(), (T)0, Vector2<T>::Zero(), Vector2<T>::Zero()) { } bool intersect; // The number of intersections is 0, 1, 2 or maxInt = // std::numeric_limits<int32_t>::max(). When 1, the arc and circle // intersect in a single point. When 2, the arc is not on the // circle and they intersect in two points. When maxInt, the // arc is on the circle. int32_t numIntersections; // Valid only when numIntersections = 1 or 2. std::array<Vector2<T>, 2> point; // Valid only when numIntersections = maxInt. Arc2<T> arc; }; Result operator()(Circle2<T> const& circle, Arc2<T> const& arc) { Result result{}; Circle2<T> circleOfArc(arc.center, arc.radius); FIQuery<T, Circle2<T>, Circle2<T>> ccQuery; auto ccResult = ccQuery(circle, circleOfArc); if (!ccResult.intersect) { result.intersect = false; result.numIntersections = 0; return result; } if (ccResult.numIntersections == std::numeric_limits<int32_t>::max()) { // The arc is on the circle. result.intersect = true; result.numIntersections = std::numeric_limits<int32_t>::max(); result.arc = arc; return result; } // Test whether circle-circle intersection points are on the arc. for (int32_t i = 0; i < ccResult.numIntersections; ++i) { result.numIntersections = 0; if (arc.Contains(ccResult.point[i])) { result.point[result.numIntersections++] = ccResult.point[i]; result.intersect = true; } } return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox3OrientedBox3.h
.h
12,583
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.02.06 #pragma once #include <Mathematics/TIQuery.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 an object0 face normal N0 // and an object1 face normal N1 are nearly parallel. In this case, you may // skip the edge-edge directions, which is equivalent to projecting the // objects 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 object, 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 axes 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 object0, then (i0,-1) is // returned. If the axis is a face normal N[i1], then (-1,i1) is returned. If // the axis is a cross product of edges, Cross(N[i0],N[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, OrientedBox3<T>, OrientedBox3<T>> { public: struct Result { Result() : intersect(false), separating{ 0, 0 } { } bool intersect; std::array<int32_t, 2> separating; }; Result operator()(OrientedBox3<T> const& box0, OrientedBox3<T> const& box1, T epsilon = static_cast<T>(0)) { Result result{}; // Convenience variables. Vector3<T> const& C0 = box0.center; Vector3<T> const* A0 = &box0.axis[0]; Vector3<T> const& E0 = box0.extent; 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 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{}; // Dot(D, A0[i]) std::array<T, 3> dotDA0{}; // 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] = Dot(A0[0], A1[i]); absDot01[0][i] = std::fabs(dot01[0][i]); if (absDot01[0][i] > cutoff) { existsParallelPair = true; } } dotDA0[0] = Dot(D, A0[0]); r = std::fabs(dotDA0[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] = Dot(A0[1], A1[i]); absDot01[1][i] = std::fabs(dot01[1][i]); if (absDot01[1][i] > cutoff) { existsParallelPair = true; } } dotDA0[1] = Dot(D, A0[1]); r = std::fabs(dotDA0[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] = Dot(A0[2], A1[i]); absDot01[2][i] = std::fabs(dot01[2][i]); if (absDot01[2][i] > cutoff) { existsParallelPair = true; } } dotDA0[2] = Dot(D, A0[2]); r = std::fabs(dotDA0[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(dotDA0[2] * dot01[1][0] - dotDA0[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(dotDA0[2] * dot01[1][1] - dotDA0[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(dotDA0[2] * dot01[1][2] - dotDA0[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(dotDA0[0] * dot01[2][0] - dotDA0[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(dotDA0[0] * dot01[2][1] - dotDA0[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(dotDA0[0] * dot01[2][2] - dotDA0[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(dotDA0[1] * dot01[0][0] - dotDA0[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(dotDA0[1] * dot01[0][1] - dotDA0[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(dotDA0[1] * dot01[0][2] - dotDA0[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/SurfaceExtractorTetrahedra.h
.h
38,584
996
// 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/SurfaceExtractor.h> #include <set> // The level set extraction algorithm implemented here is described // in the document // https://www.geometrictools.com/Documentation/ExtractLevelSurfaces.pdf 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 SurfaceExtractorTetrahedra : public SurfaceExtractor<T, Real> { public: // Convenience type definitions. typedef typename SurfaceExtractor<T, Real>::Vertex Vertex; typedef typename SurfaceExtractor<T, Real>::Triangle Triangle; // 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. SurfaceExtractorTetrahedra(int32_t xBound, int32_t yBound, int32_t zBound, T const* inputVoxels) : SurfaceExtractor<T, Real>(xBound, yBound, zBound, inputVoxels), mNextVertex(0) { } // Extract level surfaces and return rational vertices. Use the // base-class Extract if you want real-valued vertices. virtual void Extract(T level, std::vector<Vertex>& vertices, std::vector<Triangle>& triangles) override { // Adjust the image so that the level set is F(x,y,z) = 0. int64_t levelI64 = static_cast<int64_t>(level); for (size_t i = 0; i < this->mVoxels.size(); ++i) { int64_t inputI64 = static_cast<int64_t>(this->mInputVoxels[i]); this->mVoxels[i] = inputI64 - levelI64; } mVMap.clear(); mESet.clear(); mTSet.clear(); mNextVertex = 0; vertices.clear(); triangles.clear(); for (int32_t z = 0, zp = 1; zp < this->mZBound; ++z, ++zp) { int32_t zParity = (z & 1); for (int32_t y = 0, yp = 1; yp < this->mYBound; ++y, ++yp) { int32_t yParity = (y & 1); for (int32_t x = 0, xp = 1; xp < this->mXBound; ++x, ++xp) { int32_t xParity = (x & 1); int32_t i000 = x + this->mXBound * (y + this->mYBound * z); int32_t i100 = i000 + 1; int32_t i010 = i000 + this->mXBound; int32_t i110 = i010 + 1; int32_t i001 = i000 + this->mXYBound; int32_t i101 = i001 + 1; int32_t i011 = i001 + this->mXBound; int32_t i111 = i011 + 1; int64_t f000 = static_cast<int64_t>(this->mVoxels[i000]); int64_t f100 = static_cast<int64_t>(this->mVoxels[i100]); int64_t f010 = static_cast<int64_t>(this->mVoxels[i010]); int64_t f110 = static_cast<int64_t>(this->mVoxels[i110]); int64_t f001 = static_cast<int64_t>(this->mVoxels[i001]); int64_t f101 = static_cast<int64_t>(this->mVoxels[i101]); int64_t f011 = static_cast<int64_t>(this->mVoxels[i011]); int64_t f111 = static_cast<int64_t>(this->mVoxels[i111]); if (xParity ^ yParity ^ zParity) { // 1205 ProcessTetrahedron( xp, y, z, f100, xp, yp, z, f110, x, y, z, f000, xp, y, zp, f101); // 3027 ProcessTetrahedron( x, yp, z, f010, x, y, z, f000, xp, yp, z, f110, x, yp, zp, f011); // 4750 ProcessTetrahedron( x, y, zp, f001, x, yp, zp, f011, xp, y, zp, f101, x, y, z, f000); // 6572 ProcessTetrahedron( xp, yp, zp, f111, xp, y, zp, f101, x, yp, zp, f011, xp, yp, z, f110); // 0752 ProcessTetrahedron( x, y, z, f000, x, yp, zp, f011, xp, y, zp, f101, xp, yp, z, f110); } else { // 0134 ProcessTetrahedron( x, y, z, f000, xp, y, z, f100, x, yp, z, f010, x, y, zp, f001); // 2316 ProcessTetrahedron( xp, yp, z, f110, x, yp, z, f010, xp, y, z, f100, xp, yp, zp, f111); // 5461 ProcessTetrahedron( xp, y, zp, f101, x, y, zp, f001, xp, yp, zp, f111, xp, y, z, f100); // 7643 ProcessTetrahedron( x, yp, zp, f011, xp, yp, zp, f111, x, y, zp, f001, x, yp, z, f010); // 6314 ProcessTetrahedron( xp, yp, zp, f111, x, yp, z, f010, xp, y, z, f100, x, y, zp, f001); } } } } // Pack vertices into an array. vertices.resize(mVMap.size()); for (auto const& element : mVMap) { vertices[element.second] = element.first; } // Pack edges into an array (computed, but not reported to // caller). std::vector<Edge> edges(mESet.size()); size_t i = 0; for (auto const& element : mESet) { edges[i++] = element; } // Pack triangles into an array. triangles.resize(mTSet.size()); i = 0; for (auto const& element : mTSet) { triangles[i++] = element; } } protected: struct Edge { Edge() = default; Edge(int32_t v0, int32_t v1) { if (v0 < v1) { v[0] = v0; v[1] = v1; } else { v[0] = v1; v[1] = v0; } } bool operator==(Edge const& other) const { return v[0] == other.v[0] && v[1] == other.v[1]; } bool operator<(Edge const& other) const { for (int32_t i = 0; i < 2; ++i) { if (v[i] < other.v[i]) { return true; } if (v[i] > other.v[i]) { return false; } } return false; } std::array<int32_t, 2> v; }; virtual std::array<Real, 3> GetGradient(std::array<Real, 3> const& pos) override { std::array<Real, 3> const zero{ (Real)0, (Real)0, (Real)0 }; int32_t x = static_cast<int32_t>(pos[0]); if (x < 0 || x + 1 >= this->mXBound) { return zero; } int32_t y = static_cast<int32_t>(pos[1]); if (y < 0 || y + 1 >= this->mYBound) { return zero; } int32_t z = static_cast<int32_t>(pos[2]); if (z < 0 || z + 1 >= this->mZBound) { return zero; } // Get image values at corners of voxel. int32_t i000 = x + this->mXBound * (y + this->mYBound * z); int32_t i100 = i000 + 1; int32_t i010 = i000 + this->mXBound; int32_t i110 = i010 + 1; int32_t i001 = i000 + this->mXYBound; int32_t i101 = i001 + 1; int32_t i011 = i001 + this->mXBound; int32_t i111 = i011 + 1; Real f000 = static_cast<Real>(this->mVoxels[i000]); Real f100 = static_cast<Real>(this->mVoxels[i100]); Real f010 = static_cast<Real>(this->mVoxels[i010]); Real f110 = static_cast<Real>(this->mVoxels[i110]); Real f001 = static_cast<Real>(this->mVoxels[i001]); Real f101 = static_cast<Real>(this->mVoxels[i101]); Real f011 = static_cast<Real>(this->mVoxels[i011]); Real f111 = static_cast<Real>(this->mVoxels[i111]); Real dx = pos[0] - static_cast<Real>(x); Real dy = pos[1] - static_cast<Real>(y); Real dz = pos[2] - static_cast<Real>(z); std::array<Real, 3> grad; if ((x & 1) ^ (y & 1) ^ (z & 1)) { if (dx - dy - dz >= (Real)0) { // 1205 grad[0] = +f100 - f000; grad[1] = -f100 + f110; grad[2] = -f100 + f101; } else if (dx - dy + dz <= (Real)0) { // 3027 grad[0] = -f010 + f110; grad[1] = +f010 - f000; grad[2] = -f010 + f011; } else if (dx + dy - dz <= (Real)0) { // 4750 grad[0] = -f001 + f101; grad[1] = -f001 + f011; grad[2] = +f001 - f000; } else if (dx + dy + dz >= (Real)0) { // 6572 grad[0] = +f111 - f011; grad[1] = +f111 - f101; grad[2] = +f111 - f110; } else { // 0752 grad[0] = (Real)0.5 * (-f000 - f011 + f101 + f110); grad[1] = (Real)0.5 * (-f000 + f011 - f101 + f110); grad[2] = (Real)0.5 * (-f000 + f011 + f101 - f110); } } else { if (dx + dy + dz <= (Real)1) { // 0134 grad[0] = -f000 + f100; grad[1] = -f000 + f010; grad[2] = -f000 + f001; } else if (dx + dy - dz >= (Real)1) { // 2316 grad[0] = +f110 - f010; grad[1] = +f110 - f100; grad[2] = -f110 + f111; } else if (dx - dy + dz >= (Real)1) { // 5461 grad[0] = +f101 - f001; grad[1] = -f101 + f111; grad[2] = +f101 - f100; } else if (-dx + dy + dz >= (Real)1) { // 7643 grad[0] = -f011 + f111; grad[1] = +f011 - f001; grad[2] = +f011 - f010; } else { // 6314 grad[0] = (Real)0.5 * (f111 - f010 + f100 - f001); grad[1] = (Real)0.5 * (f111 + f010 - f100 - f001); grad[2] = (Real)0.5 * (f111 - f010 - f100 + f001); } } return grad; } int32_t AddVertex(Vertex const& v) { auto iter = mVMap.find(v); if (iter != mVMap.end()) { // Vertex already in map, just return its unique index. return iter->second; } else { // Vertex not in map, insert it and assign it a unique index. int32_t i = mNextVertex++; mVMap.insert(std::make_pair(v, i)); return i; } } void AddEdge(Vertex const& v0, Vertex const& v1) { int32_t i0 = AddVertex(v0); int32_t i1 = AddVertex(v1); mESet.insert(Edge(i0, i1)); } void AddTriangle(Vertex const& v0, Vertex const& v1, Vertex const& v2) { int32_t i0 = AddVertex(v0); int32_t i1 = AddVertex(v1); int32_t i2 = AddVertex(v2); // Nothing to do if triangle already exists. Triangle triangle(i0, i1, i2); if (mTSet.find(triangle) != mTSet.end()) { return; } // Prevent double-sided triangles. std::swap(triangle.v[1], triangle.v[2]); if (mTSet.find(triangle) != mTSet.end()) { return; } mESet.insert(Edge(i0, i1)); mESet.insert(Edge(i1, i2)); mESet.insert(Edge(i2, i0)); mTSet.insert(triangle); } // Support for extraction with linear interpolation. void ProcessTetrahedron( int64_t x0, int64_t y0, int64_t z0, int64_t f0, int64_t x1, int64_t y1, int64_t z1, int64_t f1, int64_t x2, int64_t y2, int64_t z2, int64_t f2, int64_t x3, int64_t y3, int64_t z3, int64_t f3) { int64_t xn0, yn0, zn0, d0; int64_t xn1, yn1, zn1, d1; int64_t xn2, yn2, zn2, d2; int64_t xn3, yn3, zn3, d3; if (f0 != 0) { // convert to case +*** if (f0 < 0) { f0 = -f0; f1 = -f1; f2 = -f2; f3 = -f3; } if (f1 > 0) { if (f2 > 0) { if (f3 > 0) { // ++++ return; } else if (f3 < 0) { // +++- d0 = f0 - f3; xn0 = f0 * x3 - f3 * x0; yn0 = f0 * y3 - f3 * y0; zn0 = f0 * z3 - f3 * z0; d1 = f1 - f3; xn1 = f1 * x3 - f3 * x1; yn1 = f1 * y3 - f3 * y1; zn1 = f1 * z3 - f3 * z1; d2 = f2 - f3; xn2 = f2 * x3 - f3 * x2; yn2 = f2 * y3 - f3 * y2; zn2 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else { // +++0 AddVertex( Vertex(x3, 1, y3, 1, z3, 1)); } } else if (f2 < 0) { d0 = f0 - f2; xn0 = f0 * x2 - f2 * x0; yn0 = f0 * y2 - f2 * y0; zn0 = f0 * z2 - f2 * z0; d1 = f1 - f2; xn1 = f1 * x2 - f2 * x1; yn1 = f1 * y2 - f2 * y1; zn1 = f1 * z2 - f2 * z1; if (f3 > 0) { // ++-+ d2 = f3 - f2; xn2 = f3 * x2 - f2 * x3; yn2 = f3 * y2 - f2 * y3; zn2 = f3 * z2 - f2 * z3; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else if (f3 < 0) { // ++-- d2 = f0 - f3; xn2 = f0 * x3 - f3 * x0; yn2 = f0 * y3 - f3 * y0; zn2 = f0 * z3 - f3 * z0; d3 = f1 - f3; xn3 = f1 * x3 - f3 * x1; yn3 = f1 * y3 - f3 * y1; zn3 = f1 * z3 - f3 * z1; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); AddTriangle( Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn3, d3, yn3, d3, zn3, d3), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else { // ++-0 AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x3, 1, y3, 1, z3, 1)); } } else { if (f3 > 0) { // ++0+ AddVertex( Vertex(x2, 1, y2, 1, z2, 1)); } else if (f3 < 0) { // ++0- d0 = f0 - f3; xn0 = f0 * x3 - f3 * x0; yn0 = f0 * y3 - f3 * y0; zn0 = f0 * z3 - f3 * z0; d1 = f1 - f3; xn1 = f1 * x3 - f3 * x1; yn1 = f1 * y3 - f3 * y1; zn1 = f1 * z3 - f3 * z1; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x2, 1, y2, 1, z2, 1)); } else { // ++00 AddEdge( Vertex(x2, 1, y2, 1, z2, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } } else if (f1 < 0) { if (f2 > 0) { d0 = f0 - f1; xn0 = f0 * x1 - f1 * x0; yn0 = f0 * y1 - f1 * y0; zn0 = f0 * z1 - f1 * z0; d1 = f2 - f1; xn1 = f2 * x1 - f1 * x2; yn1 = f2 * y1 - f1 * y2; zn1 = f2 * z1 - f1 * z2; if (f3 > 0) { // +-++ d2 = f3 - f1; xn2 = f3 * x1 - f1 * x3; yn2 = f3 * y1 - f1 * y3; zn2 = f3 * z1 - f1 * z3; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else if (f3 < 0) { // +-+- d2 = f0 - f3; xn2 = f0 * x3 - f3 * x0; yn2 = f0 * y3 - f3 * y0; zn2 = f0 * z3 - f3 * z0; d3 = f2 - f3; xn3 = f2 * x3 - f3 * x2; yn3 = f2 * y3 - f3 * y2; zn3 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); AddTriangle( Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn3, d3, yn3, d3, zn3, d3), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else { // +-+0 AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x3, 1, y3, 1, z3, 1)); } } else if (f2 < 0) { d0 = f1 - f0; xn0 = f1 * x0 - f0 * x1; yn0 = f1 * y0 - f0 * y1; zn0 = f1 * z0 - f0 * z1; d1 = f2 - f0; xn1 = f2 * x0 - f0 * x2; yn1 = f2 * y0 - f0 * y2; zn1 = f2 * z0 - f0 * z2; if (f3 > 0) { // +--+ d2 = f1 - f3; xn2 = f1 * x3 - f3 * x1; yn2 = f1 * y3 - f3 * y1; zn2 = f1 * z3 - f3 * z1; d3 = f2 - f3; xn3 = f2 * x3 - f3 * x2; yn3 = f2 * y3 - f3 * y2; zn3 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); AddTriangle( Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn3, d3, yn3, d3, zn3, d3), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else if (f3 < 0) { // +--- d2 = f3 - f0; xn2 = f3 * x0 - f0 * x3; yn2 = f3 * y0 - f0 * y3; zn2 = f3 * z0 - f0 * z3; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(xn2, d2, yn2, d2, zn2, d2)); } else { // +--0 AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x3, 1, y3, 1, z3, 1)); } } else { d0 = f1 - f0; xn0 = f1 * x0 - f0 * x1; yn0 = f1 * y0 - f0 * y1; zn0 = f1 * z0 - f0 * z1; if (f3 > 0) { // +-0+ d1 = f1 - f3; xn1 = f1 * x3 - f3 * x1; yn1 = f1 * y3 - f3 * y1; zn1 = f1 * z3 - f3 * z1; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x2, 1, y2, 1, z2, 1)); } else if (f3 < 0) { // +-0- d1 = f3 - f0; xn1 = f3 * x0 - f0 * x3; yn1 = f3 * y0 - f0 * y3; zn1 = f3 * z0 - f0 * z3; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x2, 1, y2, 1, z2, 1)); } else { // +-00 AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(x2, 1, y2, 1, z2, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } } else { if (f2 > 0) { if (f3 > 0) { // +0++ AddVertex( Vertex(x1, 1, y1, 1, z1, 1)); } else if (f3 < 0) { // +0+- d0 = f0 - f3; xn0 = f0 * x3 - f3 * x0; yn0 = f0 * y3 - f3 * y0; zn0 = f0 * z3 - f3 * z0; d1 = f2 - f3; xn1 = f2 * x3 - f3 * x2; yn1 = f2 * y3 - f3 * y2; zn1 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x1, 1, y1, 1, z1, 1)); } else { // +0+0 AddEdge( Vertex(x1, 1, y1, 1, z1, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } else if (f2 < 0) { d0 = f2 - f0; xn0 = f2 * x0 - f0 * x2; yn0 = f2 * y0 - f0 * y2; zn0 = f2 * z0 - f0 * z2; if (f3 > 0) { // +0-+ d1 = f2 - f3; xn1 = f2 * x3 - f3 * x2; yn1 = f2 * y3 - f3 * y2; zn1 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x1, 1, y1, 1, z1, 1)); } else if (f3 < 0) { // +0-- d1 = f0 - f3; xn1 = f0 * x3 - f3 * x0; yn1 = f0 * y3 - f3 * y0; zn1 = f0 * z3 - f3 * z0; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x1, 1, y1, 1, z1, 1)); } else { // +0-0 AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(x1, 1, y1, 1, z1, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } else { if (f3 > 0) { // +00+ AddEdge( Vertex(x1, 1, y1, 1, z1, 1), Vertex(x2, 1, y2, 1, z2, 1)); } else if (f3 < 0) { // +00- d0 = f0 - f3; xn0 = f0 * x3 - f3 * x0; yn0 = f0 * y3 - f3 * y0; zn0 = f0 * z3 - f3 * z0; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(x1, 1, y1, 1, z1, 1), Vertex(x2, 1, y2, 1, z2, 1)); } else { // +000 AddTriangle( Vertex(x1, 1, y1, 1, z1, 1), Vertex(x2, 1, y2, 1, z2, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } } } else if (f1 != 0) { // convert to case 0+** if (f1 < 0) { f1 = -f1; f2 = -f2; f3 = -f3; } if (f2 > 0) { if (f3 > 0) { // 0+++ AddVertex( Vertex(x0, 1, y0, 1, z0, 1)); } else if (f3 < 0) { // 0++- d0 = f2 - f3; xn0 = f2 * x3 - f3 * x2; yn0 = f2 * y3 - f3 * y2; zn0 = f2 * z3 - f3 * z2; d1 = f1 - f3; xn1 = f1 * x3 - f3 * x1; yn1 = f1 * y3 - f3 * y1; zn1 = f1 * z3 - f3 * z1; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x0, 1, y0, 1, z0, 1)); } else { // 0++0 AddEdge( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } else if (f2 < 0) { d0 = f2 - f1; xn0 = f2 * x1 - f1 * x2; yn0 = f2 * y1 - f1 * y2; zn0 = f2 * z1 - f1 * z2; if (f3 > 0) { // 0+-+ d1 = f2 - f3; xn1 = f2 * x3 - f3 * x2; yn1 = f2 * y3 - f3 * y2; zn1 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x0, 1, y0, 1, z0, 1)); } else if (f3 < 0) { // 0+-- d1 = f1 - f3; xn1 = f1 * x3 - f3 * x1; yn1 = f1 * y3 - f3 * y1; zn1 = f1 * z3 - f3 * z1; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(xn1, d1, yn1, d1, zn1, d1), Vertex(x0, 1, y0, 1, z0, 1)); } else { // 0+-0 AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(x0, 1, y0, 1, z0, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } else { if (f3 > 0) { // 0+0+ AddEdge( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x2, 1, y2, 1, z2, 1)); } else if (f3 < 0) { // 0+0- d0 = f1 - f3; xn0 = f1 * x3 - f3 * x1; yn0 = f1 * y3 - f3 * y1; zn0 = f1 * z3 - f3 * z1; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(x0, 1, y0, 1, z0, 1), Vertex(x2, 1, y2, 1, z2, 1)); } else { // 0+00 AddTriangle( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x2, 1, y2, 1, z2, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } } else if (f2 != 0) { // convert to case 00+* if (f2 < 0) { f2 = -f2; f3 = -f3; } if (f3 > 0) { // 00++ AddEdge( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x1, 1, y1, 1, z1, 1)); } else if (f3 < 0) { // 00+- d0 = f2 - f3; xn0 = f2 * x3 - f3 * x2; yn0 = f2 * y3 - f3 * y2; zn0 = f2 * z3 - f3 * z2; AddTriangle( Vertex(xn0, d0, yn0, d0, zn0, d0), Vertex(x0, 1, y0, 1, z0, 1), Vertex(x1, 1, y1, 1, z1, 1)); } else { // 00+0 AddTriangle( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x1, 1, y1, 1, z1, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } else if (f3 != 0) { // cases 000+ or 000- AddTriangle( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x1, 1, y1, 1, z1, 1), Vertex(x2, 1, y2, 1, z2, 1)); } else { // case 0000 AddTriangle( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x1, 1, y1, 1, z1, 1), Vertex(x2, 1, y2, 1, z2, 1)); AddTriangle( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x1, 1, y1, 1, z1, 1), Vertex(x3, 1, y3, 1, z3, 1)); AddTriangle( Vertex(x0, 1, y0, 1, z0, 1), Vertex(x2, 1, y2, 1, z2, 1), Vertex(x3, 1, y3, 1, z3, 1)); AddTriangle( Vertex(x1, 1, y1, 1, z1, 1), Vertex(x2, 1, y2, 1, z2, 1), Vertex(x3, 1, y3, 1, z3, 1)); } } std::map<Vertex, int32_t> mVMap; std::set<Edge> mESet; std::set<Triangle> mTSet; int32_t mNextVertex; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/NaturalCubicSpline.h
.h
13,762
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.06.07 #pragma once #include <Mathematics/Matrix.h> #include <Mathematics/Matrix3x3.h> #include <Mathematics/ParametricCurve.h> #include <array> #include <cstdint> #include <vector> // Documentation for natural splines is found in // https://www.geometrictools.com/Documentation/NaturalSplines.pdf // The number of points must be 2 or larger. The points[] and times[] arrays // must have the same number of elements. The times[] values must be strictly // increasing. namespace gte { template <int32_t N, typename T> class NaturalCubicSpline : public ParametricCurve<N, T> { public: // Construct a free spline by setting 'isFree' to true or construct a // closed spline by setting 'isFree' to false. NaturalCubicSpline(bool isFree, int32_t numPoints, Vector<N, T> const* f0, T const* times) : ParametricCurve<N, T>(numPoints - 1, times), mPolynomials{}, mDelta{} { LogAssert( numPoints >= 2 && f0 != nullptr && times != nullptr, "Invalid input."); int32_t numPm1 = numPoints - 1; mPolynomials.resize(numPm1); mDelta.resize(numPm1); for (int32_t i0 = 0, i1 = 1; i1 < numPoints; i0 = i1++) { mDelta[i0] = times[i1] - times[i0]; } Vector<N, T> boundary0{}, boundary1{}; boundary0.MakeZero(); boundary1.MakeZero(); Matrix3x3<T> R{}; int32_t const numBElements = 3 * numPm1; std::vector<Vector<N, T>> B(numBElements); OnPresolve(numPoints, f0, boundary0, boundary1, R, B); T const r1 = static_cast<T>(1); T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); if (isFree) { R(1, 1) = r1; R(1, 2) = r3; Solve(0, 1, numPoints, f0, R, B); } else // is closed { int32_t const numPm2 = numPoints - 2; T lambda = mDelta[0] / mDelta[numPm2]; T lambdasqr = lambda * lambda; R(1, 0) = -lambda; R(1, 1) = -r2 * lambda; R(1, 2) = -r3 * lambda; R(2, 1) = -r1 * lambdasqr; R(2, 2) = -r3 * lambdasqr; Solve(1, 1, numPoints, f0, R, B); } this->mConstructed = true; } NaturalCubicSpline(bool isFree, std::vector<Vector<N, T>> const& f0, std::vector<T> const& times) : NaturalCubicSpline(isFree, static_cast<int32_t>(f0.size()), f0.data(), times.data()) { } // Construct a clamped spline. NaturalCubicSpline(int32_t numPoints, Vector<N, T> const* f0, T const* times, Vector<N, T> const& derivative0, Vector<N, T> const& derivative1) : ParametricCurve<N, T>(numPoints - 1, times), mPolynomials{}, mDelta{} { LogAssert( numPoints >= 2 && f0 != nullptr && times != nullptr, "Invalid input."); int32_t const numPm1 = numPoints - 1; mPolynomials.resize(numPm1); mDelta.resize(numPm1); for (int32_t i0 = 0, i1 = 1; i1 < numPoints; i0 = i1++) { mDelta[i0] = times[i1] - times[i0]; } int32_t const numPm2 = numPoints - 2; Vector<N, T> boundary0 = mDelta[0] * derivative0; Vector<N, T> boundary1 = mDelta[numPm2] * derivative1; Matrix3x3<T> R{}; int32_t const numBElements = 3 * numPm1; std::vector<Vector<N, T>> B(numBElements); OnPresolve(numPoints, f0, boundary0, boundary1, R, B); T const r1 = static_cast<T>(1); T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); R(2, 0) = r1; R(2, 1) = r2; R(2, 2) = r3; Solve(1, 0, numPoints, f0, R, B); this->mConstructed = true; } NaturalCubicSpline(std::vector<Vector<N, T>> const& f0, std::vector<T> const& times, Vector<N, T> const& derivative0, Vector<N, T> const& derivative1) : NaturalCubicSpline(static_cast<int32_t>(f0.size()), f0.data(), times.data(), derivative0, derivative1) { } virtual ~NaturalCubicSpline() = default; using Polynomial = std::array<Vector<N, T>, 4>; inline std::vector<Polynomial> const& GetPolynomials() const { return mPolynomials; } // Evaluation of the function and its derivatives through order 3. If // you want only the position, pass in order 0. If you want the // position and first derivative, pass in order of 1 and so on. The // output array 'jet' must have 'order + 1' elements. The values are // ordered as position, first derivative, second derivative and so on. virtual void Evaluate(T t, uint32_t order, Vector<N, T>* jet) const override { if (!this->mConstructed) { // Return a zero-valued jet for invalid state. for (uint32_t i = 0; i <= order; ++i) { jet[i].MakeZero(); } return; } size_t key = 0; T u = static_cast<T>(0); GetKeyInfo(t, key, u); auto const& poly = mPolynomials[key]; // Compute position. jet[0] = poly[0] + u * (poly[1] + u * (poly[2] + u * poly[3])); if (order >= 1) { // Compute first derivative. T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); T denom = mDelta[key]; jet[1] = (poly[1] + u * (r2 * poly[2] + u * (r3 * poly[3]))) / denom; if (order >= 2) { // Compute second derivative. T const r6 = static_cast<T>(6); denom *= mDelta[key]; jet[2] = (r2 * poly[2] + u * (r6 * poly[3])) / denom; if (order >= 3) { // Compute third derivative. denom *= mDelta[key]; jet[3] = (r6 * poly[3]) / denom; for (uint32_t i = 4; i <= order; ++i) { // Derivatives of order 4 and higher are zero. jet[i].MakeZero(); } } } } } private: void OnPresolve(int32_t numPoints, Vector<N, T> const* f0, Vector<N, T> const& boundary0, Vector<N, T> const& boundary1, Matrix3x3<T>& R, std::vector<Vector<N, T>>& B) { int32_t const numPm1 = numPoints - 1; int32_t const numPm2 = numPoints - 2; int32_t const numPm3 = numPoints - 3; T const r1 = static_cast<T>(1); T const r3 = static_cast<T>(3); std::array<T, 3> const coeff{ r3, -r3, r1 }; for (int32_t i0 = 0, i1 = 1; i0 <= numPm3; i0 = i1++) { Vector<N, T> diff = f0[i1] - f0[i0]; for (int32_t j = 0, k = 3 * i0; j < 3; ++j, ++k) { B[k] = coeff[j] * diff; } } B[B.size() - 3] = f0[numPm1] - f0[numPm2]; B[B.size() - 2] = boundary0; B[B.size() - 1] = boundary1; R(0, 0) = r1; R(0, 1) = r1; R(0, 2) = r1; } void Solve(int32_t ell10, int32_t ell21, int32_t numPoints, Vector<N, T> const* f0, Matrix3x3<T>& R, std::vector<Vector<N, T>>& B) { RowReduce(ell10, ell21, numPoints, R, B); BackSubstitute(f0, R, B); } void RowReduce(int32_t ell10, int32_t ell21, int32_t numPoints, Matrix<3, 3, T>& R, std::vector<Vector<N, T>>& B) { // Apply the row reductions to convert the matrix system to // upper-triangular block-matrix system. T const r1 = static_cast<T>(1); T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); int32_t const numPm3 = numPoints - 3; if (ell10 == 1) { Vector<N, T>& Btrg = B[B.size() - 2]; Btrg -= B[0]; T sigma = mDelta[0] / mDelta[1]; T sigmasqr = sigma * sigma; T LUProd0 = r2 * sigma, LUProd1 = -sigmasqr; T sign = -r1; for (int32_t i = 1; i <= numPm3; ++i) { Btrg -= sign * (LUProd0 * B[3 * i] + LUProd1 * B[3 * i + 1]); sigma = mDelta[i] / mDelta[i + 1]; sigmasqr = sigma * sigma; T temp0 = sigma * (r2 * LUProd0 - r3 * LUProd1); T temp1 = sigmasqr * (-LUProd0 + r2 * LUProd1); LUProd0 = temp0; LUProd1 = temp1; sign = -sign; } R(1, 0) += sign * LUProd0; R(1, 1) += sign * LUProd1; } if (ell21 == 1) { Vector<N, T>& Btrg = B[B.size() - 1]; Btrg -= B[1]; T sigma = mDelta[0] / mDelta[1]; T sigmasqr = sigma * sigma; T LUProd0 = -r3 * sigma, LUProd1 = r2 * sigmasqr; T sign = -r1; for (int32_t i = 1; i <= numPm3; ++i) { Btrg -= sign * (LUProd0 * B[3 * i] + LUProd1 * B[3 * i + 1]); sigma = mDelta[i] / mDelta[i + 1]; sigmasqr = sigma * sigma; T temp0 = sigma * (r2 * LUProd0 - r3 * LUProd1); T temp1 = sigmasqr * (-LUProd0 + r2 * LUProd1); LUProd0 = temp0; LUProd1 = temp1; sign = -sign; } R(2, 0) += sign * LUProd0; R(2, 1) += sign * LUProd1; } } void BackSubstitute(Vector<N, T> const* f0, Matrix3x3<T> const& R, std::vector<Vector<N, T>> const& B) { bool invertible = false; Matrix3x3<T> invR = Inverse(R, &invertible); LogAssert( invertible, "R matrix is not invertible."); auto& poly = mPolynomials.back(); size_t j0 = B.size() - 3; size_t j1 = j0 + 1; size_t j2 = j0 + 2; poly[0] = f0[mPolynomials.size() - 1]; poly[1] = invR(0, 0) * B[j0] + invR(0, 1) * B[j1] + invR(0, 2) * B[j2]; poly[2] = invR(1, 0) * B[j0] + invR(1, 1) * B[j1] + invR(1, 2) * B[j2]; poly[3] = invR(2, 0) * B[j0] + invR(2, 1) * B[j1] + invR(2, 2) * B[j2]; T const r2 = static_cast<T>(2); T const r3 = static_cast<T>(3); int32_t const numPolynomials = static_cast<int32_t>(mPolynomials.size()); for (int32_t i1 = numPolynomials - 2, i0 = i1 + 1; i1 >= 0; i0 = i1--) { auto const& prev = mPolynomials[i0]; auto& curr = mPolynomials[i1]; T sigma = mDelta[i1] / mDelta[i0]; T sigmasqr = sigma * sigma; T u00 = r2 * sigma; T u01 = -sigmasqr; T u10 = -r3 * sigma; T u11 = r2 * sigmasqr; T u20 = sigma; T u21 = -sigmasqr; j0 -= 3; j1 -= 3; j2 -= 3; curr[0] = f0[i1]; curr[1] = B[j0] - (u00 * prev[1] + u01 * prev[2]); curr[2] = B[j1] - (u10 * prev[1] + u11 * prev[2]); curr[3] = B[j2] - (u20 * prev[1] + u21 * prev[2]); } } // Determine the index key for which times[key] <= t < times[key+1]. // Return u = (t - times[key]) / delta[key] which is in [0,1]. void GetKeyInfo(T const& t, size_t& key, T& u) const { size_t const numSegments = static_cast<size_t>(this->GetNumSegments()); if (t > this->mTime[0]) { if (t < this->mTime[numSegments]) { for (size_t i = 0, ip1 = 1; i < numSegments; i = ip1++) { if (t < this->mTime[ip1]) { key = i; u = (t - this->mTime[i]) / mDelta[i]; break; } } } else { key = numSegments - 1; u = static_cast<T>(1); } } else { key = 0; u = static_cast<T>(0); } } std::vector<Polynomial> mPolynomials; std::vector<T> mDelta; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/MinimumAreaCircle2.h
.h
17,707
453
// 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/Logger.h> #include <Mathematics/ContCircle2.h> #include <Mathematics/Hypersphere.h> #include <Mathematics/LinearSystem.h> #include <functional> #include <random> // Compute the minimum area circle containing the input set of points. The // algorithm randomly permutes the input points so that the construction // occurs in 'expected' O(N) time. All internal minimal circle calculations // store the squared radius in the radius member of Circle2. Only at the // end is a sqrt computed. // // The most robust choice for ComputeType is BSRational<T> for exact rational // arithmetic. As long as this code is a correct implementation of the theory // (which I hope it is), you will obtain the minimum-area circle containing // the points. // // Instead, if you choose ComputeType to be float or double, floating-point // rounding errors can cause the UpdateSupport{2,3} functions to fail. // The failure is trapped in those functions and a simple bounding circle is // computed using GetContainer in file ContCircle2.h. This circle is // generally not the minimum-area circle containing the points. The // minimum-area algorithm is terminated immediately. The circle is returned // as well as a bool value of 'true' when the circle is minimum area or // 'false' when the failure is trapped. When 'false' is returned, you can // try another call to the operator()(...) function. The random shuffle // that occurs is highly likely to be different from the previous shuffle, // and there is a chance that the algorithm can succeed just because of the // different ordering of points. namespace gte { template <typename InputType, typename ComputeType> class MinimumAreaCircle2 { public: MinimumAreaCircle2() : mNumSupport(0), mSupport{ 0, 0, 0 }, mDRE{}, mComputePoints{} { } bool operator()(int32_t numPoints, Vector2<InputType> const* points, Circle2<InputType>& minimal) { if (numPoints >= 1 && points) { // Function array to avoid switch statement in the main loop. std::function<UpdateResult(int32_t)> update[4]; update[1] = [this](int32_t i) { return UpdateSupport1(i); }; update[2] = [this](int32_t i) { return UpdateSupport2(i); }; update[3] = [this](int32_t i) { return UpdateSupport3(i); }; // Process only the unique points. std::vector<int32_t> permuted(numPoints); for (int32_t i = 0; i < numPoints; ++i) { permuted[i] = i; } std::sort(permuted.begin(), permuted.end(), [points](int32_t i0, int32_t i1) { return points[i0] < points[i1]; }); auto end = std::unique(permuted.begin(), permuted.end(), [points](int32_t i0, int32_t i1) { return points[i0] == points[i1]; }); permuted.erase(end, permuted.end()); numPoints = static_cast<int32_t>(permuted.size()); // Create a random permutation of the points. std::shuffle(permuted.begin(), permuted.end(), mDRE); // Convert to the compute type, which is a simple copy when // ComputeType is the same as InputType. mComputePoints.resize(numPoints); for (int32_t i = 0; i < numPoints; ++i) { for (int32_t j = 0; j < 2; ++j) { mComputePoints[i][j] = points[permuted[i]][j]; } } // Start with the first point. Circle2<ComputeType> ctMinimal = ExactCircle1(0); mNumSupport = 1; mSupport[0] = 0; // The loop restarts from the beginning of the point list each // time the circle needs updating. Linus Källberg (Computer // Science at Mälardalen University in Sweden) discovered that // performance is better when the remaining points in the // array are processed before restarting. The points // processed before the point that caused the update are // likely to be enclosed by the new circle (or near the circle // boundary) because they were enclosed by the previous // circle. The chances are better that points after the // current one will cause growth of the bounding circle. for (int32_t i = 1 % numPoints, n = 0; i != n; i = (i + 1) % numPoints) { if (!SupportContains(i)) { if (!Contains(i, ctMinimal)) { auto result = update[mNumSupport](i); if (result.second == true) { if (result.first.radius > ctMinimal.radius) { ctMinimal = result.first; n = i; } } else { // This case can happen when ComputeType is // float or double. See the comments at the // beginning of this file. ComputeType is not // exact and failure occurred. Returning // non-minimal circle. TODO: Should we throw // an exception? GetContainer(numPoints, points, minimal); mNumSupport = 0; mSupport.fill(0); return false; } } } } for (int32_t j = 0; j < 2; ++j) { minimal.center[j] = static_cast<InputType>(ctMinimal.center[j]); } minimal.radius = static_cast<InputType>(ctMinimal.radius); minimal.radius = std::sqrt(minimal.radius); for (int32_t i = 0; i < mNumSupport; ++i) { mSupport[i] = permuted[mSupport[i]]; } return true; } else { LogError("Input must contain points."); } } // Member access. inline int32_t GetNumSupport() const { return mNumSupport; } inline std::array<int32_t, 3> const& GetSupport() const { return mSupport; } private: // Test whether point P is inside circle C using squared distance and // squared radius. bool Contains(int32_t i, Circle2<ComputeType> const& circle) const { // NOTE: In this algorithm, circle.radius is the *squared radius* // until the function returns at which time a square root is // applied. Vector2<ComputeType> diff = mComputePoints[i] - circle.center; return Dot(diff, diff) <= circle.radius; } Circle2<ComputeType> ExactCircle1(int32_t i0) const { Circle2<ComputeType> minimal; minimal.center = mComputePoints[i0]; minimal.radius = (ComputeType)0; return minimal; } Circle2<ComputeType> ExactCircle2(int32_t i0, int32_t i1) const { Vector2<ComputeType> const& P0 = mComputePoints[i0]; Vector2<ComputeType> const& P1 = mComputePoints[i1]; Vector2<ComputeType> diff = P1 - P0; Circle2<ComputeType> minimal; minimal.center = ((ComputeType)0.5)*(P0 + P1); minimal.radius = ((ComputeType)0.25)*Dot(diff, diff); return minimal; } Circle2<ComputeType> ExactCircle3(int32_t i0, int32_t i1, int32_t i2) const { // Compute the 2D circle containing P0, P1, and P2. The center in // barycentric coordinates is C = x0*P0 + x1*P1 + x2*P2, where // x0 + x1 + x2 = 1. The center is equidistant from the three // points, so |C - P0| = |C - P1| = |C - P2| = R, where R is the // radius of the circle. From these conditions, // C - P0 = x0*E0 + x1*E1 - E0 // C - P1 = x0*E0 + x1*E1 - E1 // C - P2 = x0*E0 + x1*E1 // where E0 = P0 - P2 and E1 = P1 - P2, which leads to // r^2 = |x0*E0 + x1*E1|^2 - 2*Dot(E0, x0*E0 + x1*E1) + |E0|^2 // r^2 = |x0*E0 + x1*E1|^2 - 2*Dot(E1, x0*E0 + x1*E1) + |E1|^2 // r^2 = |x0*E0 + x1*E1|^2 // Subtracting the last equation from the first two and writing // the equations as a linear system, // // +- -++ -+ +- -+ // | Dot(E0,E0) Dot(E0,E1) || x0 | = 0.5 | Dot(E0,E0) | // | Dot(E1,E0) Dot(E1,E1) || x1 | | Dot(E1,E1) | // +- -++ -+ +- -+ // // The following code solves this system for x0 and x1 and then // evaluates the third equation in r^2 to obtain r. Vector2<ComputeType> const& P0 = mComputePoints[i0]; Vector2<ComputeType> const& P1 = mComputePoints[i1]; Vector2<ComputeType> const& P2 = mComputePoints[i2]; Vector2<ComputeType> E0 = P0 - P2; Vector2<ComputeType> E1 = P1 - P2; Matrix2x2<ComputeType> A; A(0, 0) = Dot(E0, E0); A(0, 1) = Dot(E0, E1); A(1, 0) = A(0, 1); A(1, 1) = Dot(E1, E1); ComputeType const half = (ComputeType)0.5; Vector2<ComputeType> B{ half * A(0, 0), half* A(1, 1) }; Circle2<ComputeType> minimal; Vector2<ComputeType> X; if (LinearSystem<ComputeType>::Solve(A, B, X)) { ComputeType x2 = (ComputeType)1 - X[0] - X[1]; minimal.center = X[0] * P0 + X[1] * P1 + x2 * P2; Vector2<ComputeType> tmp = X[0] * E0 + X[1] * E1; minimal.radius = Dot(tmp, tmp); } else { minimal.center = Vector2<ComputeType>::Zero(); minimal.radius = (ComputeType)std::numeric_limits<InputType>::max(); } return minimal; } typedef std::pair<Circle2<ComputeType>, bool> UpdateResult; UpdateResult UpdateSupport1(int32_t i) { Circle2<ComputeType> minimal = ExactCircle2(mSupport[0], i); mNumSupport = 2; mSupport[1] = i; return std::make_pair(minimal, true); } UpdateResult UpdateSupport2(int32_t i) { // Permutations of type 2, used for calling ExactCircle2(...). int32_t const numType2 = 2; int32_t const type2[numType2][2] = { { 0, /*2*/ 1 }, { 1, /*2*/ 0 } }; // Permutations of type 3, used for calling ExactCircle3(...). int32_t const numType3 = 1; // {0, 1, 2} Circle2<ComputeType> circle[numType2 + numType3]; ComputeType minRSqr = (ComputeType)std::numeric_limits<InputType>::max(); int32_t iCircle = 0, iMinRSqr = -1; int32_t k0, k1; // Permutations of type 2. for (int32_t j = 0; j < numType2; ++j, ++iCircle) { k0 = mSupport[type2[j][0]]; circle[iCircle] = ExactCircle2(k0, i); if (circle[iCircle].radius < minRSqr) { k1 = mSupport[type2[j][1]]; if (Contains(k1, circle[iCircle])) { minRSqr = circle[iCircle].radius; iMinRSqr = iCircle; } } } // Permutations of type 3. k0 = mSupport[0]; k1 = mSupport[1]; circle[iCircle] = ExactCircle3(k0, k1, i); if (circle[iCircle].radius < minRSqr) { minRSqr = circle[iCircle].radius; iMinRSqr = iCircle; } switch (iMinRSqr) { case 0: mSupport[1] = i; break; case 1: mSupport[0] = i; break; case 2: mNumSupport = 3; mSupport[2] = i; break; case -1: // For exact arithmetic, iMinRSqr >= 0, but for floating-point // arithmetic, round-off errors can lead to iMinRSqr == -1. // When this happens, use a simple bounding circle for the // result and terminate the minimum-area algorithm. return std::make_pair(Circle2<ComputeType>(), false); } return std::make_pair(circle[iMinRSqr], true); } UpdateResult UpdateSupport3(int32_t i) { // Permutations of type 2, used for calling ExactCircle2(...). int32_t const numType2 = 3; int32_t const type2[numType2][3] = { { 0, /*3*/ 1, 2 }, { 1, /*3*/ 0, 2 }, { 2, /*3*/ 0, 1 } }; // Permutations of type 2, used for calling ExactCircle3(...). int32_t const numType3 = 3; int32_t const type3[numType3][3] = { { 0, 1, /*3*/ 2 }, { 0, 2, /*3*/ 1 }, { 1, 2, /*3*/ 0 } }; Circle2<ComputeType> circle[numType2 + numType3]; ComputeType minRSqr = (ComputeType)std::numeric_limits<InputType>::max(); int32_t iCircle = 0, iMinRSqr = -1; int32_t k0, k1, k2; // Permutations of type 2. for (int32_t j = 0; j < numType2; ++j, ++iCircle) { k0 = mSupport[type2[j][0]]; circle[iCircle] = ExactCircle2(k0, i); if (circle[iCircle].radius < minRSqr) { k1 = mSupport[type2[j][1]]; k2 = mSupport[type2[j][2]]; if (Contains(k1, circle[iCircle]) && Contains(k2, circle[iCircle])) { minRSqr = circle[iCircle].radius; iMinRSqr = iCircle; } } } // Permutations of type 3. for (int32_t j = 0; j < numType3; ++j, ++iCircle) { k0 = mSupport[type3[j][0]]; k1 = mSupport[type3[j][1]]; circle[iCircle] = ExactCircle3(k0, k1, i); if (circle[iCircle].radius < minRSqr) { k2 = mSupport[type3[j][2]]; if (Contains(k2, circle[iCircle])) { minRSqr = circle[iCircle].radius; iMinRSqr = iCircle; } } } switch (iMinRSqr) { case 0: mNumSupport = 2; mSupport[1] = i; break; case 1: mNumSupport = 2; mSupport[0] = i; break; case 2: mNumSupport = 2; mSupport[0] = mSupport[2]; mSupport[1] = i; break; case 3: mSupport[2] = i; break; case 4: mSupport[1] = i; break; case 5: mSupport[0] = i; break; case -1: // For exact arithmetic, iMinRSqr >= 0, but for floating-point // arithmetic, round-off errors can lead to iMinRSqr == -1. // When this happens, use a simple bounding circle for the // result and terminate the minimum-area algorithm. return std::make_pair(Circle2<ComputeType>(), false); } return std::make_pair(circle[iMinRSqr], true); } // Indices of points that support the current minimum area circle. bool SupportContains(int32_t j) const { for (int32_t i = 0; i < mNumSupport; ++i) { if (j == mSupport[i]) { return true; } } return false; } int32_t mNumSupport; std::array<int32_t, 3> mSupport; // Random permutation of the unique input points to produce expected // linear time for the algorithm. std::default_random_engine mDRE; std::vector<Vector2<ComputeType>> mComputePoints; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/IntrOrientedBox3Frustum3.h
.h
13,161
371
// 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/Frustum3.h> #include <Mathematics/OrientedBox.h> // The test-intersection query uses the method of separating axes. // https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf // The potential separating axes include the 3 box face normals, the 5 // distinct frustum normals (near and far plane have the same normal), and // cross products of normals, one from the box and one from the frustum. namespace gte { template <typename Real> class TIQuery<Real, OrientedBox3<Real>, Frustum3<Real>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(OrientedBox3<Real> const& box, Frustum3<Real> const& frustum) { Result result{}; // Convenience variables. Vector3<Real> const* axis = &box.axis[0]; Vector3<Real> const& extent = box.extent; Vector3<Real> diff = box.center - frustum.origin; // C-E std::array<Real, 3> A; // Dot(R,A[i]) std::array<Real, 3> B; // Dot(U,A[i]) std::array<Real, 3> C; // Dot(D,A[i]) std::array<Real, 3> D; // (Dot(R,C-E),Dot(U,C-E),Dot(D,C-E)) std::array<Real, 3> NA; // dmin*Dot(R,A[i]) std::array<Real, 3> NB; // dmin*Dot(U,A[i]) std::array<Real, 3> NC; // dmin*Dot(D,A[i]) std::array<Real, 3> ND; // dmin*(Dot(R,C-E),Dot(U,C-E),?) std::array<Real, 3> RC; // rmax*Dot(D,A[i]) std::array<Real, 3> RD; // rmax*(?,?,Dot(D,C-E)) std::array<Real, 3> UC; // umax*Dot(D,A[i]) std::array<Real, 3> UD; // umax*(?,?,Dot(D,C-E)) std::array<Real, 3> NApRC; // dmin*Dot(R,A[i]) + rmax*Dot(D,A[i]) std::array<Real, 3> NAmRC; // dmin*Dot(R,A[i]) - rmax*Dot(D,A[i]) std::array<Real, 3> NBpUC; // dmin*Dot(U,A[i]) + umax*Dot(D,A[i]) std::array<Real, 3> NBmUC; // dmin*Dot(U,A[i]) - umax*Dot(D,A[i]) std::array<Real, 3> RBpUA; // rmax*Dot(U,A[i]) + umax*Dot(R,A[i]) std::array<Real, 3> RBmUA; // rmax*Dot(U,A[i]) - umax*Dot(R,A[i]) Real DdD, radius, p, fmin, fmax, MTwoUF, MTwoRF, tmp; int32_t i, j; // M = D D[2] = Dot(diff, frustum.dVector); for (i = 0; i < 3; ++i) { C[i] = Dot(axis[i], frustum.dVector); } radius = extent[0] * std::fabs(C[0]) + extent[1] * std::fabs(C[1]) + extent[2] * std::fabs(C[2]); if (D[2] + radius < frustum.dMin || D[2] - radius > frustum.dMax) { result.intersect = false; return result; } // M = n*R - r*D for (i = 0; i < 3; ++i) { A[i] = Dot(axis[i], frustum.rVector); RC[i] = frustum.rBound * C[i]; NA[i] = frustum.dMin * A[i]; NAmRC[i] = NA[i] - RC[i]; } D[0] = Dot(diff, frustum.rVector); radius = extent[0] * std::fabs(NAmRC[0]) + extent[1] * std::fabs(NAmRC[1]) + extent[2] * std::fabs(NAmRC[2]); ND[0] = frustum.dMin * D[0]; RD[2] = frustum.rBound * D[2]; DdD = ND[0] - RD[2]; MTwoRF = frustum.GetMTwoRF(); if (DdD + radius < MTwoRF || DdD > radius) { result.intersect = false; return result; } // M = -n*R - r*D for (i = 0; i < 3; ++i) { NApRC[i] = NA[i] + RC[i]; } radius = extent[0] * std::fabs(NApRC[0]) + extent[1] * std::fabs(NApRC[1]) + extent[2] * std::fabs(NApRC[2]); DdD = -(ND[0] + RD[2]); if (DdD + radius < MTwoRF || DdD > radius) { result.intersect = false; return result; } // M = n*U - u*D for (i = 0; i < 3; ++i) { B[i] = Dot(axis[i], frustum.uVector); UC[i] = frustum.uBound * C[i]; NB[i] = frustum.dMin * B[i]; NBmUC[i] = NB[i] - UC[i]; } D[1] = Dot(diff, frustum.uVector); radius = extent[0] * std::fabs(NBmUC[0]) + extent[1] * std::fabs(NBmUC[1]) + extent[2] * std::fabs(NBmUC[2]); ND[1] = frustum.dMin * D[1]; UD[2] = frustum.uBound * D[2]; DdD = ND[1] - UD[2]; MTwoUF = frustum.GetMTwoUF(); if (DdD + radius < MTwoUF || DdD > radius) { result.intersect = false; return result; } // M = -n*U - u*D for (i = 0; i < 3; ++i) { NBpUC[i] = NB[i] + UC[i]; } radius = extent[0] * std::fabs(NBpUC[0]) + extent[1] * std::fabs(NBpUC[1]) + extent[2] * std::fabs(NBpUC[2]); DdD = -(ND[1] + UD[2]); if (DdD + radius < MTwoUF || DdD > radius) { result.intersect = false; return result; } // M = A[i] for (i = 0; i < 3; ++i) { p = frustum.rBound * std::fabs(A[i]) + frustum.uBound * std::fabs(B[i]); NC[i] = frustum.dMin * C[i]; fmin = NC[i] - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = NC[i] + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = A[i] * D[0] + B[i] * D[1] + C[i] * D[2]; if (DdD + extent[i] < fmin || DdD - extent[i] > fmax) { result.intersect = false; return result; } } // M = Cross(R,A[i]) for (i = 0; i < 3; ++i) { p = frustum.uBound * std::fabs(C[i]); fmin = -NB[i] - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = -NB[i] + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = C[i] * D[1] - B[i] * D[2]; radius = extent[0] * std::fabs(B[i] * C[0] - B[0] * C[i]) + extent[1] * std::fabs(B[i] * C[1] - B[1] * C[i]) + extent[2] * std::fabs(B[i] * C[2] - B[2] * C[i]); if (DdD + radius < fmin || DdD - radius > fmax) { result.intersect = false; return result; } } // M = Cross(U,A[i]) for (i = 0; i < 3; ++i) { p = frustum.rBound * std::fabs(C[i]); fmin = NA[i] - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = NA[i] + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = -C[i] * D[0] + A[i] * D[2]; radius = extent[0] * std::fabs(A[i] * C[0] - A[0] * C[i]) + extent[1] * std::fabs(A[i] * C[1] - A[1] * C[i]) + extent[2] * std::fabs(A[i] * C[2] - A[2] * C[i]); if (DdD + radius < fmin || DdD - radius > fmax) { result.intersect = false; return result; } } // M = Cross(n*D+r*R+u*U,A[i]) for (i = 0; i < 3; ++i) { Real fRB = frustum.rBound * B[i]; Real fUA = frustum.uBound * A[i]; RBpUA[i] = fRB + fUA; RBmUA[i] = fRB - fUA; } for (i = 0; i < 3; ++i) { p = frustum.rBound * std::fabs(NBmUC[i]) + frustum.uBound * std::fabs(NAmRC[i]); tmp = -frustum.dMin * RBmUA[i]; fmin = tmp - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = tmp + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = D[0] * NBmUC[i] - D[1] * NAmRC[i] - D[2] * RBmUA[i]; radius = (Real)0; for (j = 0; j < 3; j++) { radius += extent[j] * std::fabs(A[j] * NBmUC[i] - B[j] * NAmRC[i] - C[j] * RBmUA[i]); } if (DdD + radius < fmin || DdD - radius > fmax) { result.intersect = false; return result; } } // M = Cross(n*D+r*R-u*U,A[i]) for (i = 0; i < 3; ++i) { p = frustum.rBound * std::fabs(NBpUC[i]) + frustum.uBound * std::fabs(NAmRC[i]); tmp = -frustum.dMin * RBpUA[i]; fmin = tmp - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = tmp + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = D[0] * NBpUC[i] - D[1] * NAmRC[i] - D[2] * RBpUA[i]; radius = (Real)0; for (j = 0; j < 3; ++j) { radius += extent[j] * std::fabs(A[j] * NBpUC[i] - B[j] * NAmRC[i] - C[j] * RBpUA[i]); } if (DdD + radius < fmin || DdD - radius > fmax) { result.intersect = false; return result; } } // M = Cross(n*D-r*R+u*U,A[i]) for (i = 0; i < 3; ++i) { p = frustum.rBound * std::fabs(NBmUC[i]) + frustum.uBound * std::fabs(NApRC[i]); tmp = frustum.dMin * RBpUA[i]; fmin = tmp - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = tmp + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = D[0] * NBmUC[i] - D[1] * NApRC[i] + D[2] * RBpUA[i]; radius = (Real)0; for (j = 0; j < 3; ++j) { radius += extent[j] * std::fabs(A[j] * NBmUC[i] - B[j] * NApRC[i] + C[j] * RBpUA[i]); } if (DdD + radius < fmin || DdD - radius > fmax) { result.intersect = false; return result; } } // M = Cross(n*D-r*R-u*U,A[i]) for (i = 0; i < 3; ++i) { p = frustum.rBound * std::fabs(NBpUC[i]) + frustum.uBound * std::fabs(NApRC[i]); tmp = frustum.dMin * RBmUA[i]; fmin = tmp - p; if (fmin < (Real)0) { fmin *= frustum.GetDRatio(); } fmax = tmp + p; if (fmax > (Real)0) { fmax *= frustum.GetDRatio(); } DdD = D[0] * NBpUC[i] - D[1] * NApRC[i] + D[2] * RBmUA[i]; radius = (Real)0; for (j = 0; j < 3; ++j) { radius += extent[j] * std::fabs(A[j] * NBpUC[i] - B[j] * NApRC[i] + C[j] * RBmUA[i]); } if (DdD + radius < fmin || DdD - radius > fmax) { result.intersect = false; return result; } } result.intersect = true; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/DistPointRectangle.h
.h
2,548
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/DCPQuery.h> #include <Mathematics/Rectangle.h> // Compute the distance between a point and a rectangle in nD. // // 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 input point is stored in closest[0]. The closest point on the // rectangle is stored in closest[1] with W-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 <int32_t N, typename T> class DCPQuery<T, Vector<N, T>, Rectangle<N, T>> { public: struct Result { Result() : distance(static_cast<T>(0)), sqrDistance(static_cast<T>(0)), cartesian{ static_cast<T>(0), static_cast<T>(0) }, closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() } { } T distance, sqrDistance; std::array<T, 2> cartesian; std::array<Vector<N, T>, 2> closest; }; Result operator()(Vector<N, T> const& point, Rectangle<N, T> const& rectangle) { Result result{}; Vector<N, T> diff = point - rectangle.center; result.closest[0] = point; result.closest[1] = rectangle.center; for (int32_t i = 0; i < 2; ++i) { result.cartesian[i] = Dot(rectangle.axis[i], diff); if (result.cartesian[i] < -rectangle.extent[i]) { result.cartesian[i] = -rectangle.extent[i]; } else if (result.cartesian[i] > rectangle.extent[i]) { result.cartesian[i] = rectangle.extent[i]; } result.closest[1] += result.cartesian[i] * rectangle.axis[i]; } 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/IntrPlane3Circle3.h
.h
7,331
189
// 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/IntrPlane3Plane3.h> #include <Mathematics/Circle3.h> namespace gte { template <typename T> class TIQuery<T, Plane3<T>, Circle3<T>> { public: struct Result { Result() : intersect(false) { } bool intersect; }; Result operator()(Plane3<T> const& plane, Circle3<T> const& circle) { Result result{}; // Construct the plane of the circle. Plane3<T> cPlane(circle.normal, circle.center); // Compute the intersection of this plane with the input plane. FIQuery<T, Plane3<T>, Plane3<T>> ppQuery{}; auto ppResult = ppQuery(plane, cPlane); if (!ppResult.intersect) { // The planes are parallel and nonintersecting. result.intersect = false; return result; } if (!ppResult.isLine) { // The planes are the same, so the circle is the set of // intersection. result.intersect = true; return result; } // The planes intersect in a line. Locate one or two points that // are on the circle and line. If the line is t*D+P, the circle // center is C and the circle radius is r, then // r^2 = |t*D+P-C|^2 = |D|^2*t^2 + 2*Dot(D,P-C)*t + |P-C|^2 // This is a quadratic equation of the form // a2*t^2 + 2*a1*t + a0 = 0. Vector3<T> diff = ppResult.line.origin - circle.center; T a2 = Dot(ppResult.line.direction, ppResult.line.direction); T a1 = Dot(diff, ppResult.line.direction); T a0 = Dot(diff, diff) - circle.radius * circle.radius; // T-valued roots imply an intersection. T discr = a1 * a1 - a0 * a2; result.intersect = (discr >= static_cast<T>(0)); return result; } }; template <typename T> class FIQuery<T, Plane3<T>, Circle3<T>> { public: struct Result { Result() : intersect(false), numIntersections(0), point{ Vector3<T>::Zero(), Vector3<T>::Zero() }, circle(Vector3<T>::Zero(), Vector3<T>::Zero(), static_cast<T>(0)) { } // If 'intersect' is false, the set of intersection is empty. // 'numIntersections' is 0 and 'points[]' and 'circle' have // members all set to 0. // // If 'intersect' is true, the set of intersection contains either // 1 or 2 points or the entire circle. // // (1) When the set of intersection has 1 point, the circle is // just touching the plane. 'numIntersections' is 1 and // 'point[0]' and 'point[1]' are the same point. The // 'circle' is set to invalid (center at the origin, normal // is the zero vector, radius is 0). // // (2) When the set of intersection has 2 points, the plane cuts // the circle into 2 arcs. 'numIntersections' is 2 and // 'point[0]' and 'point[1]' are the distinct intersection // points. The 'circle' is set to invalid (center at the // origin, normal is the zero vector, radius is 0). // // (3) When the set of intersection contains the entire circle, the // plane of the circle and the input plane are the same. // 'numIntersections' is std::numeric_limits<size_t>::max(). // 'points[0]' and 'points[1]' are set to the zero vector. // 'circle' is set to the input circle. // bool intersect; size_t numIntersections; std::array<Vector3<T>, 2> point; Circle3<T> circle; }; Result operator()(Plane3<T> const& plane, Circle3<T> const& circle) { // The 'result' members have initial values set by the default // constructor. In each return block, only the relevant members // are modified. Result result{}; // Construct the plane of the circle. Plane3<T> cPlane(circle.normal, circle.center); // Compute the intersection of this plane with the input plane. FIQuery<T, Plane3<T>, Plane3<T>> ppQuery; auto ppResult = ppQuery(plane, cPlane); if (!ppResult.intersect) { // The planes are parallel and nonintersecting. return result; } if (!ppResult.isLine) { // The planes are the same, so the circle is the set of // intersection. result.intersect = true; result.numIntersections = std::numeric_limits<size_t>::max(); result.circle = circle; return result; } // The planes intersect in a line. Locate one or two points that // are on the circle and line. If the line is t*D+P, the circle // center is C, and the circle radius is r, then // r^2 = |t*D+P-C|^2 = |D|^2*t^2 + 2*Dot(D,P-C)*t + |P-C|^2 // This is a quadratic equation of the form // a2*t^2 + 2*a1*t + a0 = 0. Vector3<T> diff = ppResult.line.origin - circle.center; T a2 = Dot(ppResult.line.direction, ppResult.line.direction); T a1 = Dot(diff, ppResult.line.direction); T a0 = Dot(diff, diff) - circle.radius * circle.radius; T const zero = static_cast<T>(0); T discr = a1 * a1 - a0 * a2; if (discr < zero) { // No real roots, the circle does not intersect the plane. return result; } if (discr == zero) { // The quadratic polynomial has 1 real-valued repeated root. // The circle just touches the plane. result.intersect = true; result.numIntersections = 1; result.point[0] = ppResult.line.origin - (a1 / a2) * ppResult.line.direction; result.point[1] = result.point[0]; return result; } // The quadratic polynomial has 2 distinct, real-valued roots. // The circle intersects the plane in two points. T root = std::sqrt(discr); result.intersect = true; result.numIntersections = 2; result.point[0] = ppResult.line.origin - ((a1 + root) / a2) * ppResult.line.direction; result.point[1] = ppResult.line.origin - ((a1 - root) / a2) * ppResult.line.direction; return result; } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/ApprHeightPlane3.h
.h
4,340
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.01.06 #pragma once #include <Mathematics/ApprQuery.h> #include <Mathematics/Vector3.h> // Least-squares fit of a plane to height data (x,y,f(x,y)). The plane is of // the form (z - zAvr) = a*(x - xAvr) + b*(y - yAvr), where (xAvr,yAvr,zAvr) // is the average of the sample points. The return value is 'true' if and // only the if fit is successful (the input points are noncollinear). The // mParameters values are ((xAvr,yAvr,zAvr),(a,b,-1)) on success and // ((0,0,0),(0,0,0)) on failure. The error for (x0,y0,z0) is // [a*(x0-xAvr)+b*(y0-yAvr)-(z0-zAvr)]^2. namespace gte { template <typename Real> class ApprHeightPlane3 : public ApprQuery<Real, Vector3<Real>> { public: // Initialize the model parameters to zero. ApprHeightPlane3() { mParameters.first = Vector3<Real>::Zero(); mParameters.second = Vector3<Real>::Zero(); } // Basic fitting algorithm. See ApprQuery.h for the various Fit(...) // functions that you can call. virtual bool FitIndexed( size_t numPoints, Vector3<Real> const* points, size_t numIndices, int32_t const* indices) override { if (this->ValidIndices(numPoints, points, numIndices, indices)) { // Compute the mean of the points. Vector3<Real> mean = Vector3<Real>::Zero(); int32_t const* currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { mean += points[*currentIndex++]; } mean /= (Real)numIndices; if (std::isfinite(mean[0]) && std::isfinite(mean[1])) { // Compute the covariance matrix of the points. Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0; Real covar11 = (Real)0, covar12 = (Real)0; currentIndex = indices; for (size_t i = 0; i < numIndices; ++i) { Vector3<Real> diff = points[*currentIndex++] - mean; 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]; } // Decompose the covariance matrix. Real det = covar00 * covar11 - covar01 * covar01; if (det != (Real)0) { Real invDet = (Real)1 / det; mParameters.first = mean; mParameters.second[0] = (covar11 * covar02 - covar01 * covar12) * invDet; mParameters.second[1] = (covar00 * covar12 - covar01 * covar02) * invDet; mParameters.second[2] = (Real)-1; return true; } } } mParameters.first = Vector3<Real>::Zero(); mParameters.second = Vector3<Real>::Zero(); return false; } // Get the parameters for the best fit. std::pair<Vector3<Real>, Vector3<Real>> const& GetParameters() const { return mParameters; } virtual size_t GetMinimumRequired() const override { return 3; } virtual Real Error(Vector3<Real> const& point) const override { Real d = Dot(point - mParameters.first, mParameters.second); Real error = d * d; return error; } virtual void CopyParameters(ApprQuery<Real, Vector3<Real>> const* input) override { auto source = dynamic_cast<ApprHeightPlane3<Real> const*>(input); if (source) { *this = *source; } } private: std::pair<Vector3<Real>, Vector3<Real>> mParameters; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/GTE/Mathematics/Hypersphere.h
.h
2,359
92
// 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 hypersphere is represented as |X-C| = R where C is the center and R is // the radius. The hypersphere is a circle for dimension 2 or a sphere for // dimension 3. namespace gte { template <int32_t N, typename Real> class Hypersphere { public: // Construction and destruction. The default constructor sets the center // to (0,...,0) and the radius to 1. Hypersphere() : radius((Real)1) { center.MakeZero(); } Hypersphere(Vector<N, Real> const& inCenter, Real inRadius) : center(inCenter), radius(inRadius) { } // Public member access. Vector<N, Real> center; Real radius; public: // Comparisons to support sorted containers. bool operator==(Hypersphere const& hypersphere) const { return center == hypersphere.center && radius == hypersphere.radius; } bool operator!=(Hypersphere const& hypersphere) const { return !operator==(hypersphere); } bool operator< (Hypersphere const& hypersphere) const { if (center < hypersphere.center) { return true; } if (center > hypersphere.center) { return false; } return radius < hypersphere.radius; } bool operator<=(Hypersphere const& hypersphere) const { return !hypersphere.operator<(*this); } bool operator> (Hypersphere const& hypersphere) const { return hypersphere.operator<(*this); } bool operator>=(Hypersphere const& hypersphere) const { return !operator<(hypersphere); } }; // Template aliases for convenience. template <typename Real> using Circle2 = Hypersphere<2, Real>; template <typename Real> using Sphere3 = Hypersphere<3, Real>; }
Unknown