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/IntrDisk2Sector2.h | .h | 8,158 | 191 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/TIQuery.h>
#include <Mathematics/Hypersphere.h>
#include <Mathematics/Sector2.h>
// The Circle2 object is considered to be a disk whose points X satisfy the
// constraint |X-C| <= R, where C is the disk center and R is the disk
// radius. The Sector2 object is also considered to be a solid. Also,
// the Sector2 object is required to be convex, so the sector angle must
// be in (0,pi/2], even though the Sector2 definition allows for angles
// larger than pi/2 (leading to nonconvex sectors). The sector vertex is
// V, the radius is L, the axis direction is D, and the angle is A. Sector
// points X satisfy |X-V| <= L and Dot(D,X-V) >= cos(A)|X-V| >= 0.
//
// A subproblem for the test-intersection query is to determine whether
// the disk intersects the cone of the sector. Although the query is in
// 2D, it is analogous to the 3D problem of determining whether a sphere
// and cone overlap. That algorithm is described in
// https://www.geometrictools.com/Documentation/IntersectionSphereCone.pdf
// The algorithm leads to coordinate-free pseudocode that applies to 2D
// as well as 3D. That function is the first SphereIntersectsCone on
// page 4 of the PDF.
//
// If the disk is outside the cone, there is no intersection. If the disk
// overlaps the cone, we then need to test whether the disk overlaps the
// disk of the sector.
namespace gte
{
template <typename Real>
class TIQuery<Real, Circle2<Real>, Sector2<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Circle2<Real> const& disk, Sector2<Real> const& sector)
{
Result result{};
// Test whether the disk and the disk of the sector overlap.
Vector2<Real> CmV = disk.center - sector.vertex;
Real sqrLengthCmV = Dot(CmV, CmV);
Real lengthCmV = std::sqrt(sqrLengthCmV);
if (lengthCmV > disk.radius + sector.radius)
{
// The disk is outside the disk of the sector.
result.intersect = false;
return result;
}
// Test whether the disk and cone of the sector overlap. The
// comments about K, K', and K" refer to the PDF mentioned
// previously.
Vector2<Real> U = sector.vertex - (disk.radius / sector.sinAngle) * sector.direction;
Vector2<Real> CmU = disk.center - U;
Real lengthCmU = Length(CmU);
if (Dot(sector.direction, CmU) < lengthCmU * sector.cosAngle)
{
// The disk center is outside K" (in the white or gray
// regions).
result.intersect = false;
return result;
}
// The disk center is inside K" (in the red, orange, blue, or
// green regions).
Real dotDirCmV = Dot(sector.direction, CmV);
if (-dotDirCmV >= lengthCmV * sector.sinAngle)
{
// The disk center is inside K" and inside K' (in the blue
// or green regions).
if (lengthCmV <= disk.radius)
{
// The disk center is in the blue region, in which case
// the disk contains the sector's vertex.
result.intersect = true;
}
else
{
// The disk center is in the green region.
result.intersect = false;
}
return result;
}
// To reach here, we know that the disk overlaps the sector's disk
// and the sector's cone. The disk center is in the orange region
// or in the red region (not including the segments that separate
// the red and blue regions).
// Test whether the ray of the right boundary of the sector
// overlaps the disk. The ray direction U0 is a clockwise
// rotation of the cone axis by the cone angle.
Vector2<Real> U0
{
+sector.cosAngle * sector.direction[0] + sector.sinAngle * sector.direction[1],
-sector.sinAngle * sector.direction[0] + sector.cosAngle * sector.direction[1]
};
Real dp0 = Dot(U0, CmV);
Real discr0 = disk.radius * disk.radius + dp0 * dp0 - sqrLengthCmV;
if (discr0 >= (Real)0)
{
// The ray intersects the disk. Now test whether the sector
// boundary segment contained by the ray overlaps the disk.
// The quadratic root tmin generates the ray-disk point of
// intersection closest to the sector vertex.
Real tmin = dp0 - std::sqrt(discr0);
if (sector.radius >= tmin)
{
// The segment overlaps the disk.
result.intersect = true;
return result;
}
else
{
// The segment does not overlap the disk. We know the
// disks overlap, so if the disk center is outside the
// sector cone or on the right-boundary ray, the overlap
// occurs outside the cone, which implies the disk and
// sector do not intersect.
if (dotDirCmV <= lengthCmV * sector.cosAngle)
{
// The disk center is not inside the sector cone.
result.intersect = false;
return result;
}
}
}
// Test whether the ray of the left boundary of the sector
// overlaps the disk. The ray direction U1 is a counterclockwise
// rotation of the cone axis by the cone angle.
Vector2<Real> U1
{
+sector.cosAngle * sector.direction[0] - sector.sinAngle * sector.direction[1],
+sector.sinAngle * sector.direction[0] + sector.cosAngle * sector.direction[1]
};
Real dp1 = Dot(U1, CmV);
Real discr1 = disk.radius * disk.radius + dp1 * dp1 - sqrLengthCmV;
if (discr1 >= (Real)0)
{
// The ray intersects the disk. Now test whether the sector
// boundary segment contained by the ray overlaps the disk.
// The quadratic root tmin generates the ray-disk point of
// intersection closest to the sector vertex.
Real tmin = dp1 - std::sqrt(discr1);
if (sector.radius >= tmin)
{
result.intersect = true;
return result;
}
else
{
// The segment does not overlap the disk. We know the
// disks overlap, so if the disk center is outside the
// sector cone or on the right-boundary ray, the overlap
// occurs outside the cone, which implies the disk and
// sector do not intersect.
if (dotDirCmV <= lengthCmV * sector.cosAngle)
{
// The disk center is not inside the sector cone.
result.intersect = false;
return result;
}
}
}
// To reach here, a strict subset of the sector's arc boundary
// must intersect the disk.
result.intersect = true;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Arc2.h | .h | 3,682 | 130 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector2.h>
// The circle containing the arc is represented as |X-C| = R where C is the
// center and R is the radius. The arc is defined by two points end0 and
// end1 on the circle so that end1 is obtained from end0 by traversing
// counterclockwise. The application is responsible for ensuring that end0
// and end1 are on the circle and that they are properly ordered.
namespace gte
{
template <typename Real>
class Arc2
{
public:
// Construction and destruction. The default constructor sets the
// center to (0,0), radius to 1, end0 to (1,0), and end1 to (0,1).
Arc2()
:
center(Vector2<Real>::Zero()),
radius((Real)1)
{
end[0] = Vector2<Real>::Unit(0);
end[1] = Vector2<Real>::Unit(1);
}
Arc2(Vector2<Real> const& inCenter, Real inRadius,
Vector2<Real>const& inEnd0, Vector2<Real>const& inEnd1)
:
center(inCenter),
radius(inRadius)
{
end[0] = inEnd0;
end[1] = inEnd1;
}
// Test whether P is on the arc. The application must ensure that P
// is on the circle; that is, |P-C| = R. This test works for any
// angle between B-C and A-C, not just those between 0 and pi
// radians.
bool Contains(Vector2<Real> const& p) const
{
// Assert: |P-C| = R where P is the input point, C is the circle
// center and R is the circle radius. For P to be on the arc from
// A to B, it must be on the side of the plane containing A with
// normal N = Perp(B-A) where Perp(u,v) = (v,-u).
Vector2<Real> diffPE0 = p - end[0];
Vector2<Real> diffE1E0 = end[1] - end[0];
Real dotPerp = DotPerp(diffPE0, diffE1E0);
return dotPerp >= (Real)0;
}
Vector2<Real> center;
Real radius;
std::array<Vector2<Real>, 2> end;
public:
// Comparisons to support sorted containers.
bool operator==(Arc2 const& arc) const
{
return center == arc.center && radius == arc.radius
&& end[0] == arc.end[0] && end[1] == arc.end[1];
}
bool operator!=(Arc2 const& arc) const
{
return !operator==(arc);
}
bool operator< (Arc2 const& arc) const
{
if (center < arc.center)
{
return true;
}
if (center > arc.center)
{
return false;
}
if (radius < arc.radius)
{
return true;
}
if (radius > arc.radius)
{
return false;
}
if (end[0] < arc.end[0])
{
return true;
}
if (end[0] > arc.end[0])
{
return false;
}
return end[1] < arc.end[1];
}
bool operator<=(Arc2 const& arc) const
{
return !arc.operator<(*this);
}
bool operator> (Arc2 const& arc) const
{
return arc.operator<(*this);
}
bool operator>=(Arc2 const& arc) const
{
return !operator<(arc);
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Line.h | .h | 2,258 | 90 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector.h>
// The line is represented by P+t*D, where P is an origin point, D is a
// unit-length direction vector, and t is any real number. The user must
// ensure that D is unit length.
namespace gte
{
template <int32_t N, typename Real>
class Line
{
public:
// Construction and destruction. The default constructor sets the
// origin to (0,...,0) and the line direction to (1,0,...,0).
Line()
{
origin.MakeZero();
direction.MakeUnit(0);
}
Line(Vector<N, Real> const& inOrigin, Vector<N, Real> const& inDirection)
:
origin(inOrigin),
direction(inDirection)
{
}
// Public member access. The direction must be unit length.
Vector<N, Real> origin, direction;
public:
// Comparisons to support sorted containers.
bool operator==(Line const& line) const
{
return origin == line.origin && direction == line.direction;
}
bool operator!=(Line const& line) const
{
return !operator==(line);
}
bool operator< (Line const& line) const
{
if (origin < line.origin)
{
return true;
}
if (origin > line.origin)
{
return false;
}
return direction < line.direction;
}
bool operator<=(Line const& line) const
{
return !line.operator<(*this);
}
bool operator> (Line const& line) const
{
return line.operator<(*this);
}
bool operator>=(Line const& line) const
{
return !operator<(line);
}
};
// Template aliases for convenience.
template <typename Real>
using Line2 = Line<2, Real>;
template <typename Real>
using Line3 = Line<3, Real>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/GaussianElimination.h | .h | 9,158 | 276 | // 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/LexicoArray2.h>
#include <cstring>
#include <vector>
// The input matrix M must be NxN. The storage convention for element lookup
// is determined by GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR, whichever is
// active. If you want the inverse of M, pass a nonnull pointer inverseM;
// this matrix must also be NxN and use the same storage convention as M. If
// you do not want the inverse of M, pass a nullptr for inverseM. If you want
// to solve M*X = B for X, where X and B are Nx1, pass nonnull pointers for B
// and X. If you want to solve M*Y = C for Y, where X and C are NxK, pass
// nonnull pointers for C and Y and pass K to numCols. In all cases, pass
// N to numRows.
namespace gte
{
template <typename Real>
class GaussianElimination
{
public:
bool operator()(int32_t numRows,
Real const* M, Real* inverseM, Real& determinant,
Real const* B, Real* X,
Real const* C, int32_t numCols, Real* Y) const
{
if (numRows <= 0 || !M
|| ((B != nullptr) != (X != nullptr))
|| ((C != nullptr) != (Y != nullptr))
|| (C != nullptr && numCols < 1))
{
LogError("Invalid input.");
}
int32_t numElements = numRows * numRows;
bool wantInverse = (inverseM != nullptr);
std::vector<Real> localInverseM;
if (!wantInverse)
{
localInverseM.resize(numElements);
inverseM = localInverseM.data();
}
Set(numElements, M, inverseM);
if (B)
{
Set(numRows, B, X);
}
if (C)
{
Set(numRows * numCols, C, Y);
}
#if defined(GTE_USE_ROW_MAJOR)
LexicoArray2<true, Real> matInvM(numRows, numRows, inverseM);
LexicoArray2<true, Real> matY(numRows, numCols, Y);
#else
LexicoArray2<false, Real> matInvM(numRows, numRows, inverseM);
LexicoArray2<false, Real> matY(numRows, numCols, Y);
#endif
std::vector<int32_t> colIndex(numRows), rowIndex(numRows), pivoted(numRows);
std::fill(pivoted.begin(), pivoted.end(), 0);
Real const zero = (Real)0;
Real const one = (Real)1;
bool odd = false;
determinant = one;
// Elimination by full pivoting.
int32_t i1, i2, row = 0, col = 0;
for (int32_t i0 = 0; i0 < numRows; ++i0)
{
// Search matrix (excluding pivoted rows) for maximum absolute entry.
Real maxValue = zero;
for (i1 = 0; i1 < numRows; ++i1)
{
if (!pivoted[i1])
{
for (i2 = 0; i2 < numRows; ++i2)
{
if (!pivoted[i2])
{
Real value = matInvM(i1, i2);
Real absValue = (value >= zero ? value : -value);
if (absValue > maxValue)
{
maxValue = absValue;
row = i1;
col = i2;
}
}
}
}
}
if (maxValue == zero)
{
// The matrix is not invertible.
if (wantInverse)
{
Set(numElements, nullptr, inverseM);
}
determinant = zero;
if (B)
{
Set(numRows, nullptr, X);
}
if (C)
{
Set(numRows * numCols, nullptr, Y);
}
return false;
}
pivoted[col] = true;
// Swap rows so that the pivot entry is in row 'col'.
if (row != col)
{
odd = !odd;
for (int32_t i = 0; i < numRows; ++i)
{
std::swap(matInvM(row, i), matInvM(col, i));
}
if (B)
{
std::swap(X[row], X[col]);
}
if (C)
{
for (int32_t i = 0; i < numCols; ++i)
{
std::swap(matY(row, i), matY(col, i));
}
}
}
// Keep track of the permutations of the rows.
rowIndex[i0] = row;
colIndex[i0] = col;
// Scale the row so that the pivot entry is 1.
Real diagonal = matInvM(col, col);
determinant *= diagonal;
Real inv = one / diagonal;
matInvM(col, col) = one;
for (i2 = 0; i2 < numRows; ++i2)
{
matInvM(col, i2) *= inv;
}
if (B)
{
X[col] *= inv;
}
if (C)
{
for (i2 = 0; i2 < numCols; ++i2)
{
matY(col, i2) *= inv;
}
}
// Zero out the pivot column locations in the other rows.
for (i1 = 0; i1 < numRows; ++i1)
{
if (i1 != col)
{
Real save = matInvM(i1, col);
matInvM(i1, col) = zero;
for (i2 = 0; i2 < numRows; ++i2)
{
matInvM(i1, i2) -= matInvM(col, i2) * save;
}
if (B)
{
X[i1] -= X[col] * save;
}
if (C)
{
for (i2 = 0; i2 < numCols; ++i2)
{
matY(i1, i2) -= matY(col, i2) * save;
}
}
}
}
}
if (wantInverse)
{
// Reorder rows to undo any permutations in Gaussian elimination.
for (i1 = numRows - 1; i1 >= 0; --i1)
{
if (rowIndex[i1] != colIndex[i1])
{
for (i2 = 0; i2 < numRows; ++i2)
{
std::swap(matInvM(i2, rowIndex[i1]),
matInvM(i2, colIndex[i1]));
}
}
}
}
if (odd)
{
determinant = -determinant;
}
return true;
}
private:
// Support for copying source to target or to set target to zero. If
// source is nullptr, then target is set to zero; otherwise source is
// copied to target. This function hides the type traits used to
// determine whether Real is native floating-point or otherwise (such
// as BSNumber or BSRational).
void Set(int32_t numElements, Real const* source, Real* target) const
{
if (std::is_floating_point<Real>() == std::true_type())
{
// Fast set/copy for native floating-point.
size_t numBytes = numElements * sizeof(Real);
if (source)
{
std::memcpy(target, source, numBytes);
}
else
{
std::memset(target, 0, numBytes);
}
}
else
{
// The inputs are not std containers, so ensure assignment works
// correctly.
if (source)
{
for (int32_t i = 0; i < numElements; ++i)
{
target[i] = source[i];
}
}
else
{
Real const zero = (Real)0;
for (int32_t i = 0; i < numElements; ++i)
{
target[i] = zero;
}
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrLine3Torus3.h | .h | 6,232 | 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.3.2022.03.28
#pragma once
#include <Mathematics/FIQuery.h>
#include <Mathematics/Line.h>
#include <Mathematics/Torus3.h>
#include <Mathematics/Polynomial1.h>
#include <Mathematics/RootsPolynomial.h>
// The line is parameterized by L(t) = P + t * D, where P is a point on the
// line and D is a nonzero direction vector that is not necessarily unit
// length.
//
// The standard torus has center (0,0,0), plane of symmetry z = 0, axis of
// symmetry containing (0,0,0) in the direction (0,0,1), outer radius r0
// and inner radius r1 > r0 (a "ring torus"). It is defined implicitly by
// (x^2 + y^2 + z^2 + r0^2 - r1^2)^2 - 4 * r0^2 * (x^2 + y^2) = 0
// where (x,y,z) is a point on the torus. A parameterization is
// x(u,v) = (r0 + r1 * cos(v)) * cos(u)
// y(u,v) = (r0 + r1 * cos(v)) * sin(u)
// z(u,v) = r1 * sin(v)
// for u in [0,2*pi) and v in [0,2*pi).
//
// Generally, the torus has center C with plane of symmetry containing C and
// having unit-length normal N. The axis of symmetry is the normal line to
// the plane at C. If X is a point on the torus, the implicit formulation is
// (|X-C|^2 + r0^2 - r1^2)^2 - 4 * r0^2 * (|X-C|^2 - (Dot(N,X-C))^2) = 0
// Let D0 and D1 be unit-length vectors that span the symmetry plane where
// {D0,D1,N} is a right-handed orthonormal basis. A parameterization for the
// torus is
// X(u,v) = C + (r0 + r1*cos(v))*(cos(u)*D0 + sin(u)*D1) + r1*sin(v)*N
// for u in [0,2*pi) and v in [0,2*pi).
//
// Compute the intersections of a line with a torus. The number of
// intersections is between 0 and 4. As noted, line direction D does not
// have to be unit length. The normal vector N must be unit length, but
// notice that the implicit formulation has a term
// (Dot(N,X-C))^2 = (X-C)^T * (N * N^T) * (X - C)
// If the normal were chosen to be nonzero but not unit length, say M, then
// N = M/|M}. The term can be modified to
// (Dot(N,X-C))^2 = (X-C)^T * ((M * M^T)/|M|^2) * (X - C)
// This formulation supports exact rational arithmetic when computing the
// roots of a quartic polynomial associated with the find-intersection query.
// The rational arithmetic allows for a theoretically correct classification
// of the polynomial roots, although the actual root computation will have
// rounding errors when converting to a floating-point result.
namespace gte
{
template <typename T>
class FIQuery<T, Line3<T>, Torus3<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
numIntersections(0),
lineParameter{
static_cast<T>(0),
static_cast<T>(0),
static_cast<T>(0),
static_cast<T>(0)
},
torusParameter{ {
{ static_cast<T>(0), static_cast<T>(0) },
{ static_cast<T>(0), static_cast<T>(0) },
{ static_cast<T>(0), static_cast<T>(0) },
{ static_cast<T>(0), static_cast<T>(0) }
} },
point{
Vector3<T>::Zero(),
Vector3<T>::Zero(),
Vector3<T>::Zero(),
Vector3<T>::Zero()
}
{
}
bool intersect;
size_t numIntersections;
std::array<T, 4> lineParameter;
std::array<std::array<T, 2>, 4> torusParameter;
std::array<Vector3<T>, 4> point;
};
Result operator()(Line3<T> const& line, Torus3<T> const& torus)
{
Result result{};
// Short names for readability.
auto const& P = line.origin;
auto const& D = line.direction;
auto const& C = torus.center;
auto const& N = torus.normal;
auto const& r0 = torus.radius0; // outer radius
auto const& r1 = torus.radius1; // inner radius
// Common intermediate terms.
T const two = static_cast<T>(2);
T const four = static_cast<T>(4);
T r0Sqr = r0 * r0;
T r1Sqr = r1 * r1;
Vector3<T> PmC = P - C;
T sqrLenPmC = Dot(PmC, PmC);
T dotDPmC = Dot(D, PmC);
T sqrLenD = Dot(D, D);
T sqrLenN = Dot(N, N);
T dotND = Dot(N, D);
T dotNPmC = Dot(N, PmC);
// |X-C|^2
Polynomial1<T> quad0(2);
quad0[0] = sqrLenPmC;
quad0[1] = two * dotDPmC;
quad0[2] = sqrLenD;
// |X-C|^2 + r0^2 - r1^2
Polynomial1<T> quad1 = quad0;
quad1[0] += r0Sqr - r1Sqr;
// Dot(N,X-C)
Polynomial1<T> linear{ dotNPmC, dotND };
// Dot(N,X-C)^2 with adjustment for non-unit N
Polynomial1<T> quad2 = (linear * linear) / sqrLenN;
// |X-C|^2 - (Dot(N,X-C))^2
Polynomial1<T> quad3 = quad0 - quad2;
// (|X-C|^2 + r0^2-r1^2)^2 - 4*r0^2 * (|X-C|^2 - (Dot(N,X-C))^2)
Polynomial1<T> quartic = quad1 * quad1 - four * r0Sqr * quad3;
// Solve the quartic.
std::map<T, int32_t> rmMap{};
RootsPolynomial<T>::SolveQuartic(quartic[0], quartic[1],
quartic[2], quartic[3], quartic[4], rmMap);
// Get the intersection parameters and points.
result.numIntersections = rmMap.size();
result.intersect = (result.numIntersections > 0);
size_t i = 0;
for (auto const& element : rmMap)
{
result.lineParameter[i] = element.first;
result.point[i] = line.origin + element.first * line.direction;
torus.GetParameters(result.point[i],
result.torusParameter[i][0], result.torusParameter[i][1]);
++i;
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Log2Estimate.h | .h | 4,965 | 148 | // 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 log2(x). The polynomial p(x) of
// degree D minimizes the quantity maximum{|log2(x) - p(x)| : x in [1,2]}
// over all polynomials of degree D.
namespace gte
{
template <typename Real>
class Log2Estimate
{
public:
// The input constraint is x in [1,2]. For example,
// float x; // in [1,2]
// float result = Log2Estimate<float>::Degree<3>(x);
template <int32_t D>
inline static Real Degree(Real x)
{
Real t = x - (Real)1; // t in (0,1]
return Evaluate(degree<D>(), t);
}
// The input constraint is x > 0. Range reduction is used to generate
// a value y in (0,1], call Degree(y), and add the exponent for the
// power of two in the binary scientific representation of x. For
// example,
// float x; // x > 0
// float result = Log2Estimate<float>::DegreeRR<3>(x);
template <int32_t D>
inline static Real DegreeRR(Real x)
{
int32_t p;
Real y = std::frexp(x, &p); // y in [1/2,1)
y = ((Real)2) * y; // y in [1,2)
--p;
Real poly = Degree<D>(y);
Real result = poly + (Real)p;
return result;
}
private:
// Metaprogramming and private implementation to allow specialization
// of a template member function.
template <int32_t D> struct degree {};
inline static Real Evaluate(degree<1>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG1_C1;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<2>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG2_C2;
poly = (Real)GTE_C_LOG2_DEG2_C1 + poly * t;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<3>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG3_C3;
poly = (Real)GTE_C_LOG2_DEG3_C2 + poly * t;
poly = (Real)GTE_C_LOG2_DEG3_C1 + poly * t;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<4>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG4_C4;
poly = (Real)GTE_C_LOG2_DEG4_C3 + poly * t;
poly = (Real)GTE_C_LOG2_DEG4_C2 + poly * t;
poly = (Real)GTE_C_LOG2_DEG4_C1 + poly * t;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<5>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG5_C5;
poly = (Real)GTE_C_LOG2_DEG5_C4 + poly * t;
poly = (Real)GTE_C_LOG2_DEG5_C3 + poly * t;
poly = (Real)GTE_C_LOG2_DEG5_C2 + poly * t;
poly = (Real)GTE_C_LOG2_DEG5_C1 + poly * t;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<6>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG6_C6;
poly = (Real)GTE_C_LOG2_DEG6_C5 + poly * t;
poly = (Real)GTE_C_LOG2_DEG6_C4 + poly * t;
poly = (Real)GTE_C_LOG2_DEG6_C3 + poly * t;
poly = (Real)GTE_C_LOG2_DEG6_C2 + poly * t;
poly = (Real)GTE_C_LOG2_DEG6_C1 + poly * t;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<7>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG7_C7;
poly = (Real)GTE_C_LOG2_DEG7_C6 + poly * t;
poly = (Real)GTE_C_LOG2_DEG7_C5 + poly * t;
poly = (Real)GTE_C_LOG2_DEG7_C4 + poly * t;
poly = (Real)GTE_C_LOG2_DEG7_C3 + poly * t;
poly = (Real)GTE_C_LOG2_DEG7_C2 + poly * t;
poly = (Real)GTE_C_LOG2_DEG7_C1 + poly * t;
poly = poly * t;
return poly;
}
inline static Real Evaluate(degree<8>, Real t)
{
Real poly;
poly = (Real)GTE_C_LOG2_DEG8_C8;
poly = (Real)GTE_C_LOG2_DEG8_C7 + poly * t;
poly = (Real)GTE_C_LOG2_DEG8_C6 + poly * t;
poly = (Real)GTE_C_LOG2_DEG8_C5 + poly * t;
poly = (Real)GTE_C_LOG2_DEG8_C4 + poly * t;
poly = (Real)GTE_C_LOG2_DEG8_C3 + poly * t;
poly = (Real)GTE_C_LOG2_DEG8_C2 + poly * t;
poly = (Real)GTE_C_LOG2_DEG8_C1 + poly * t;
poly = poly * t;
return poly;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/RootsBisection.h | .h | 5,538 | 171 | // 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 <functional>
// Compute a root of a function F(t) on an interval [t0, t1]. The caller
// specifies the maximum number of iterations, in case you want limited
// accuracy for the root. However, the function is designed for native types
// (Real = float/double). If you specify a sufficiently large number of
// iterations, the root finder bisects until either F(t) is identically zero
// [a condition dependent on how you structure F(t) for evaluation] or the
// midpoint (t0 + t1)/2 rounds numerically to tmin or tmax. Of course, it
// is required that t0 < t1. The return value of Find is:
// 0: F(t0)*F(t1) > 0, we cannot determine a root
// 1: F(t0) = 0 or F(t1) = 0
// 2..maxIterations: the number of bisections plus one
// maxIterations+1: the loop executed without a break (no convergence)
namespace gte
{
template <typename Real>
class RootsBisection
{
public:
// Use this function when F(t0) and F(t1) are not already known.
static uint32_t Find(std::function<Real(Real)> const& F, Real t0,
Real t1, uint32_t maxIterations, Real& root)
{
// Set 'root' initially to avoid "potentially uninitialized
// variable" warnings by a compiler.
root = t0;
if (t0 < t1)
{
// Test the endpoints to see whether F(t) is zero.
Real f0 = F(t0);
if (f0 == (Real)0)
{
root = t0;
return 1;
}
Real f1 = F(t1);
if (f1 == (Real)0)
{
root = t1;
return 1;
}
if (f0 * f1 > (Real)0)
{
// It is not known whether the interval bounds a root.
return 0;
}
uint32_t i;
for (i = 2; i <= maxIterations; ++i)
{
root = (Real)0.5 * (t0 + t1);
if (root == t0 || root == t1)
{
// The numbers t0 and t1 are consecutive
// floating-point numbers.
break;
}
Real fm = F(root);
Real product = fm * f0;
if (product < (Real)0)
{
t1 = root;
f1 = fm;
}
else if (product > (Real)0)
{
t0 = root;
f0 = fm;
}
else
{
break;
}
}
return i;
}
else
{
// The interval endpoints are invalid.
return 0;
}
}
// If f0 = F(t0) and f1 = F(t1) are already known, pass them to the
// bisector. This is useful when |f0| or |f1| is infinite, and you
// can pass sign(f0) or sign(f1) rather than then infinity because
// the bisector cares only about the signs of f.
static uint32_t Find(std::function<Real(Real)> const& F, Real t0,
Real t1, Real f0, Real f1, uint32_t maxIterations, Real& root)
{
// Set 'root' initially to avoid "potentially uninitialized
// variable" warnings by a compiler.
root = t0;
if (t0 < t1)
{
// Test the endpoints to see whether F(t) is zero.
if (f0 == (Real)0)
{
root = t0;
return 1;
}
if (f1 == (Real)0)
{
root = t1;
return 1;
}
if (f0 * f1 > (Real)0)
{
// It is not known whether the interval bounds a root.
return 0;
}
uint32_t i;
root = t0;
for (i = 2; i <= maxIterations; ++i)
{
root = (Real)0.5 * (t0 + t1);
if (root == t0 || root == t1)
{
// The numbers t0 and t1 are consecutive
// floating-point numbers.
break;
}
Real fm = F(root);
Real product = fm * f0;
if (product < (Real)0)
{
t1 = root;
f1 = fm;
}
else if (product > (Real)0)
{
t0 = root;
f0 = fm;
}
else
{
break;
}
}
return i;
}
else
{
// The interval endpoints are invalid.
return 0;
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrPlane3Sphere3.h | .h | 3,127 | 105 | // 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/DistPointHyperplane.h>
#include <Mathematics/Hypersphere.h>
#include <Mathematics/Circle3.h>
namespace gte
{
template <typename T>
class TIQuery<T, Plane3<T>, Sphere3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Plane3<T> const& plane, Sphere3<T> const& sphere)
{
Result result{};
DCPQuery<T, Vector3<T>, Plane3<T>> ppQuery;
auto ppResult = ppQuery(sphere.center, plane);
result.intersect = (ppResult.distance <= sphere.radius);
return result;
}
};
template <typename T>
class FIQuery<T, Plane3<T>, Sphere3<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
isCircle(false),
circle(Vector3<T>::Zero(), Vector3<T>::Zero(), (T)0),
point(Vector3<T>::Zero())
{
}
bool intersect;
// If 'intersect' is true, the intersection is either a point or a
// circle. When 'isCircle' is true, 'circle' is valid. When
// 'isCircle' is false, 'point' is valid.
bool isCircle;
Circle3<T> circle;
Vector3<T> point;
};
Result operator()(Plane3<T> const& plane, Sphere3<T> const& sphere)
{
Result result{};
DCPQuery<T, Vector3<T>, Plane3<T>> ppQuery;
auto ppResult = ppQuery(sphere.center, plane);
if (ppResult.distance < sphere.radius)
{
result.intersect = true;
result.isCircle = true;
result.circle.center = sphere.center - ppResult.signedDistance * plane.normal;
result.circle.normal = plane.normal;
// The sum and diff are both positive numbers.
T sum = sphere.radius + ppResult.distance;
T dif = sphere.radius - ppResult.distance;
// arg = sqr(sphere.radius) - sqr(ppResult.distance)
T arg = sum * dif;
result.circle.radius = std::sqrt(arg);
return result;
}
else if (ppResult.distance == sphere.radius)
{
result.intersect = true;
result.isCircle = false;
result.point = sphere.center - ppResult.signedDistance * plane.normal;
return result;
}
else
{
result.intersect = false;
return result;
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistPlane3OrientedBox3.h | .h | 2,592 | 74 | // 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/OrientedBox.h>
// Compute the distance between a plane and a solid oriented box in 3D.
//
// 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.
//
// 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 plane 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.
//
// TODO: Modify to support non-unit-length N and non-unit-length U[].
namespace gte
{
template <typename T>
class DCPQuery<T, Plane3<T>, OrientedBox3<T>>
{
public:
using PCQuery = DCPQuery<T, Plane3<T>, CanonicalBox3<T>>;
using Result = typename PCQuery::Result;
Result operator()(Plane3<T> const& plane, OrientedBox3<T> const& box)
{
Result result{};
// Rotate and translate the plane and box so that the box is
// aligned and has center at the origin.
CanonicalBox3<T> cbox(box.extent);
Vector3<T> delta = plane.origin - box.center;
Vector3<T> xfrmOrigin{}, xfrmNormal{};
for (int32_t i = 0; i < 3; ++i)
{
xfrmOrigin[i] = Dot(box.axis[i], delta);
xfrmNormal[i] = Dot(box.axis[i], plane.normal);
}
// The query computes 'output' relative to the box with center
// at the origin.
Plane3<T> xfrmPlane(xfrmNormal, xfrmOrigin);
PCQuery pcQuery{};
result = pcQuery(xfrmPlane, cbox);
// Rotate and translate the closest points to the original
// coordinates.
std::array<Vector3<T>, 2> closest{ box.center, box.center };
for (size_t i = 0; i < 2; ++i)
{
for (int32_t j = 0; j < 3; ++j)
{
closest[i] += result.closest[i][j] * box.axis[j];
}
}
result.closest = closest;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/QuadricSurface.h | .h | 23,155 | 701 | // 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/ArbitraryPrecision.h>
#include <Mathematics/Matrix3x3.h>
// A quadric surface is defined implicitly by
//
// 0 = a0 + a1*x[0] + a2*x[1] + a3*x[2] + a4*x[0]^2 + a5*x[0]*x[1] +
// a6*x[0]*x[2] + a7*x[1]^2 + a8*x[1]*x[2] + a9*x[2]^2
//
// = a0 + [a1 a2 a3]*X + X^T*[a4 a5/2 a6/2]*X
// [a5/2 a7 a8/2]
// [a6/2 a8/2 a9 ]
// = C + B^T*X + X^T*A*X
//
// The matrix A is symmetric.
namespace gte
{
template <typename Real>
class QuadricSurface
{
public:
// Construction and destruction. The default constructor sets all
// coefficients to zero.
QuadricSurface()
{
mCoefficient.fill((Real)0);
mC = (Real)0;
mB.MakeZero();
mA.MakeZero();
}
QuadricSurface(std::array<Real, 10> const& coefficient)
:
mCoefficient(coefficient)
{
mC = mCoefficient[0];
mB[0] = mCoefficient[1];
mB[1] = mCoefficient[2];
mB[2] = mCoefficient[3];
mA(0, 0) = mCoefficient[4];
mA(0, 1) = (Real)0.5 * mCoefficient[5];
mA(0, 2) = (Real)0.5 * mCoefficient[6];
mA(1, 0) = mA(0, 1);
mA(1, 1) = mCoefficient[7];
mA(1, 2) = (Real)0.5 * mCoefficient[8];
mA(2, 0) = mA(0, 2);
mA(2, 1) = mA(1, 2);
mA(2, 2) = mCoefficient[9];
}
// Member access.
inline std::array<Real, 10> const& GetCoefficients() const
{
return mCoefficient;
}
inline Real const& GetC() const
{
return mC;
}
inline Vector3<Real> const& GetB() const
{
return mB;
}
inline Matrix3x3<Real> const& GetA() const
{
return mA;
}
// Evaluate the function.
Real F(Vector3<Real> const& position) const
{
Real f = Dot(position, mA * position + mB) + mC;
return f;
}
// Evaluate the first-order partial derivatives (gradient).
Real FX(Vector3<Real> const& position) const
{
Real sum = mA(0, 0) * position[0] + mA(0, 1) * position[1] + mA(0, 2) * position[2];
Real fx = (Real)2 * sum + mB[0];
return fx;
}
Real FY(Vector3<Real> const& position) const
{
Real sum = mA(1, 0) * position[0] + mA(1, 1) * position[1] + mA(1, 2) * position[2];
Real fy = (Real)2 * sum + mB[1];
return fy;
}
Real FZ(Vector3<Real> const& position) const
{
Real sum = mA(2, 0) * position[0] + mA(2, 1) * position[1] + mA(2, 2) * position[2];
Real fz = (Real)2 * sum + mB[2];
return fz;
}
// Evaluate the second-order partial derivatives (Hessian).
Real FXX(Vector3<Real> const&) const
{
Real fxx = (Real)2 * mA(0, 0);
return fxx;
}
Real FXY(Vector3<Real> const&) const
{
Real fxy = (Real)2 * mA(0, 1);
return fxy;
}
Real FXZ(Vector3<Real> const&) const
{
Real fxz = (Real)2 * mA(0, 2);
return fxz;
}
Real FYY(Vector3<Real> const&) const
{
Real fyy = (Real)2 * mA(1, 1);
return fyy;
}
Real FYZ(Vector3<Real> const&) const
{
Real fyz = (Real)2 * mA(1, 2);
return fyz;
}
Real FZZ(Vector3<Real> const&) const
{
Real fzz = (Real)2 * mA(2, 2);
return fzz;
}
// Classification of the quadric. The implementation uses exact
// rational arithmetic to avoid misclassification due to
// floating-point rounding errors.
enum class Classification
{
NONE,
POINT,
LINE,
PLANE,
TWO_PLANES,
PARABOLIC_CYLINDER,
ELLIPTIC_CYLINDER,
HYPERBOLIC_CYLINDER,
ELLIPTIC_PARABOLOID,
HYPERBOLIC_PARABOLOID,
ELLIPTIC_CONE,
HYPERBOLOID_ONE_SHEET,
HYPERBOLOID_TWO_SHEETS,
ELLIPSOID
};
Classification GetClassification() const
{
// Convert the coefficients to their rational representations and
// compute various derived quantities.
RReps reps(mCoefficient);
// Use Sturm sequences to determine the signs of the roots.
int32_t positiveRoots, negativeRoots, zeroRoots;
GetRootSigns(reps, positiveRoots, negativeRoots, zeroRoots);
// Classify the solution set to the equation.
Classification type = Classification::NONE;
switch (zeroRoots)
{
case 0:
type = ClassifyZeroRoots0(reps, positiveRoots);
break;
case 1:
type = ClassifyZeroRoots1(reps, positiveRoots);
break;
case 2:
type = ClassifyZeroRoots2(reps, positiveRoots);
break;
case 3:
type = ClassifyZeroRoots3(reps);
break;
}
return type;
}
private:
typedef BSRational<UIntegerAP32> Rational;
typedef Vector<3, Rational> RVector3;
class RReps
{
public:
RReps(std::array<Real, 10> const& coefficient)
{
Rational half = (Real)0.5;
c = Rational(coefficient[0]);
b0 = Rational(coefficient[1]);
b1 = Rational(coefficient[2]);
b2 = Rational(coefficient[3]);
a00 = Rational(coefficient[4]);
a01 = half * Rational(coefficient[5]);
a02 = half * Rational(coefficient[6]);
a11 = Rational(coefficient[7]);
a12 = half * Rational(coefficient[8]);
a22 = Rational(coefficient[9]);
sub00 = a11 * a22 - a12 * a12;
sub01 = a01 * a22 - a12 * a02;
sub02 = a01 * a12 - a02 * a11;
sub11 = a00 * a22 - a02 * a02;
sub12 = a00 * a12 - a02 * a01;
sub22 = a00 * a11 - a01 * a01;
k0 = a00 * sub00 - a01 * sub01 + a02 * sub02;
k1 = sub00 + sub11 + sub22;
k2 = a00 + a11 + a22;
k3 = Rational(0);
k4 = Rational(0);
k5 = Rational(0);
}
// Quadratic coefficients.
Rational a00, a01, a02, a11, a12, a22, b0, b1, b2, c;
// 2-by-2 determinants
Rational sub00, sub01, sub02, sub11, sub12, sub22;
// Characteristic polynomial L^3 - k2 * L^2 + k1 * L - k0.
Rational k0, k1, k2;
// For Sturm sequences.
Rational k3, k4, k5;
};
static void GetRootSigns(RReps& reps, int32_t& positiveRoots, int32_t& negativeRoots, int32_t& zeroRoots)
{
// Use Sturm sequences to determine the signs of the roots.
int32_t signChangeMI, signChange0, signChangePI, distinctNonzeroRoots;
std::array<Rational, 4> value;
Rational const zero(0);
if (reps.k0 != zero)
{
reps.k3 = Rational(2, 9) * reps.k2 * reps.k2 - Rational(2, 3) * reps.k1;
reps.k4 = reps.k0 - Rational(1, 9) * reps.k1 * reps.k2;
if (reps.k3 != zero)
{
reps.k5 = -(reps.k1 + ((Rational(2) * reps.k2 * reps.k3 +
Rational(3) * reps.k4) * reps.k4) / (reps.k3 * reps.k3));
value[0] = 1;
value[1] = -reps.k3;
value[2] = reps.k5;
signChangeMI = 1 + GetSignChanges(3, value);
value[0] = -reps.k0;
value[1] = reps.k1;
value[2] = reps.k4;
value[3] = reps.k5;
signChange0 = GetSignChanges(4, value);
value[0] = 1;
value[1] = reps.k3;
value[2] = reps.k5;
signChangePI = GetSignChanges(3, value);
}
else
{
value[0] = -reps.k0;
value[1] = reps.k1;
value[2] = reps.k4;
signChange0 = GetSignChanges(3, value);
value[0] = 1;
value[1] = reps.k4;
signChangePI = GetSignChanges(2, value);
signChangeMI = 1 + signChangePI;
}
positiveRoots = signChange0 - signChangePI;
LogAssert(positiveRoots >= 0, "Unexpected condition.");
negativeRoots = signChangeMI - signChange0;
LogAssert(negativeRoots >= 0, "Unexpected condition.");
zeroRoots = 0;
distinctNonzeroRoots = positiveRoots + negativeRoots;
if (distinctNonzeroRoots == 2)
{
if (positiveRoots == 2)
{
positiveRoots = 3;
}
else if (negativeRoots == 2)
{
negativeRoots = 3;
}
else
{
// One root is positive and one is negative. One root
// has multiplicity 2, the other of multiplicity 1.
// Distinguish between the two cases by computing the
// sign of the polynomial at the inflection point
// L = k2/3.
Rational X = Rational(1, 3) * reps.k2;
Rational poly = X * (X * (X - reps.k2) + reps.k1) - reps.k0;
if (poly > zero)
{
positiveRoots = 2;
}
else
{
negativeRoots = 2;
}
}
}
else if (distinctNonzeroRoots == 1)
{
// Root of multiplicity 3.
if (positiveRoots == 1)
{
positiveRoots = 3;
}
else
{
negativeRoots = 3;
}
}
return;
}
if (reps.k1 != zero)
{
reps.k3 = Rational(1, 4) * reps.k2 * reps.k2 - reps.k1;
value[0] = -1;
value[1] = reps.k3;
signChangeMI = 1 + GetSignChanges(2, value);
value[0] = reps.k1;
value[1] = -reps.k2;
value[2] = reps.k3;
signChange0 = GetSignChanges(3, value);
value[0] = 1;
value[1] = reps.k3;
signChangePI = GetSignChanges(2, value);
positiveRoots = signChange0 - signChangePI;
LogAssert(positiveRoots >= 0, "Unexpected condition.");
negativeRoots = signChangeMI - signChange0;
LogAssert(negativeRoots >= 0, "Unexpected condition.");
zeroRoots = 1;
distinctNonzeroRoots = positiveRoots + negativeRoots;
if (distinctNonzeroRoots == 1)
{
positiveRoots = 2;
}
return;
}
if (reps.k2 != zero)
{
zeroRoots = 2;
if (reps.k2 > zero)
{
positiveRoots = 1;
negativeRoots = 0;
}
else
{
positiveRoots = 0;
negativeRoots = 1;
}
return;
}
positiveRoots = 0;
negativeRoots = 0;
zeroRoots = 3;
}
static int32_t GetSignChanges(int32_t quantity, std::array<Rational, 4> const& value)
{
int32_t signChanges = 0;
Rational const zero(0);
Rational prev = value[0];
for (int32_t i = 1; i < quantity; ++i)
{
Rational next = value[i];
if (next != zero)
{
if (prev * next < zero)
{
++signChanges;
}
prev = next;
}
}
return signChanges;
}
static Classification ClassifyZeroRoots0(RReps const& reps, int32_t positiveRoots)
{
// The inverse matrix is
// +- -+
// | sub00 -sub01 sub02 |
// | -sub01 sub11 -sub12 | * (1/det)
// | sub02 -sub12 sub22 |
// +- -+
Rational fourDet = Rational(4) * reps.k0;
Rational qForm = reps.b0 * (reps.sub00 * reps.b0 -
reps.sub01 * reps.b1 + reps.sub02 * reps.b2) -
reps.b1 * (reps.sub01 * reps.b0 - reps.sub11 * reps.b1 +
reps.sub12 * reps.b2) + reps.b2 * (reps.sub02 * reps.b0 -
reps.sub12 * reps.b1 + reps.sub22 * reps.b2);
Rational r = Rational(1, 4) * qForm / fourDet - reps.c;
Rational const zero(0);
if (r > zero)
{
if (positiveRoots == 3)
{
return Classification::ELLIPSOID;
}
else if (positiveRoots == 2)
{
return Classification::HYPERBOLOID_ONE_SHEET;
}
else if (positiveRoots == 1)
{
return Classification::HYPERBOLOID_TWO_SHEETS;
}
else
{
return Classification::NONE;
}
}
else if (r < zero)
{
if (positiveRoots == 3)
{
return Classification::NONE;
}
else if (positiveRoots == 2)
{
return Classification::HYPERBOLOID_TWO_SHEETS;
}
else if (positiveRoots == 1)
{
return Classification::HYPERBOLOID_ONE_SHEET;
}
else
{
return Classification::ELLIPSOID;
}
}
// else r == 0
if (positiveRoots == 3 || positiveRoots == 0)
{
return Classification::POINT;
}
return Classification::ELLIPTIC_CONE;
}
static Classification ClassifyZeroRoots1(RReps const& reps, int32_t positiveRoots)
{
// Generate an orthonormal set {p0,p1,p2}, where p0 is an
// eigenvector of A corresponding to eigenvalue zero.
RVector3 P0, P1, P2;
Rational const zero(0);
if (reps.sub00 != zero || reps.sub01 != zero || reps.sub02 != zero)
{
// Rows 1 and 2 are linearly independent.
P0 = { reps.sub00, -reps.sub01, reps.sub02 };
P1 = { reps.a01, reps.a11, reps.a12 };
P2 = Cross(P0, P1);
return ClassifyZeroRoots1(reps, positiveRoots, P0, P1, P2);
}
if (reps.sub01 != zero || reps.sub11 != zero || reps.sub12 != zero)
{
// Rows 2 and 0 are linearly independent.
P0 = { -reps.sub01, reps.sub11, -reps.sub12 };
P1 = { reps.a02, reps.a12, reps.a22 };
P2 = Cross(P0, P1);
return ClassifyZeroRoots1(reps, positiveRoots, P0, P1, P2);
}
// Rows 0 and 1 are linearly independent.
P0 = { reps.sub02, -reps.sub12, reps.sub22 };
P1 = { reps.a00, reps.a01, reps.a02 };
P2 = Cross(P0, P1);
return ClassifyZeroRoots1(reps, positiveRoots, P0, P1, P2);
}
static Classification ClassifyZeroRoots1(RReps const& reps, int32_t positiveRoots,
RVector3 const& P0, RVector3 const& P1, RVector3 const& P2)
{
Rational const zero(0);
Rational e0 = P0[0] * reps.b0 + P0[1] * reps.b1 + P0[2] * reps.b2;
if (e0 != zero)
{
if (positiveRoots == 1)
{
return Classification::HYPERBOLIC_PARABOLOID;
}
else
{
return Classification::ELLIPTIC_PARABOLOID;
}
}
// Matrix F.
Rational f11 = P1[0] * (reps.a00 * P1[0] + reps.a01 * P1[1] +
reps.a02 * P1[2]) + P1[1] * (reps.a01 * P1[0] +
reps.a11 * P1[1] + reps.a12 * P1[2]) + P1[2] * (
reps.a02 * P1[0] + reps.a12 * P1[1] + reps.a22 * P1[2]);
Rational f12 = P2[0] * (reps.a00 * P1[0] + reps.a01 * P1[1] +
reps.a02 * P1[2]) + P2[1] * (reps.a01 * P1[0] +
reps.a11 * P1[1] + reps.a12 * P1[2]) + P2[2] * (
reps.a02 * P1[0] + reps.a12 * P1[1] + reps.a22 * P1[2]);
Rational f22 = P2[0] * (reps.a00 * P2[0] + reps.a01 * P2[1] +
reps.a02 * P2[2]) + P2[1] * (reps.a01 * P2[0] +
reps.a11 * P2[1] + reps.a12 * P2[2]) + P2[2] * (
reps.a02 * P2[0] + reps.a12 * P2[1] + reps.a22 * P2[2]);
// Vector g.
Rational g1 = P1[0] * reps.b0 + P1[1] * reps.b1 + P1[2] * reps.b2;
Rational g2 = P2[0] * reps.b0 + P2[1] * reps.b1 + P2[2] * reps.b2;
// Compute g^T*F^{-1}*g/4 - c.
Rational fourDet = Rational(4) * (f11 * f22 - f12 * f12);
Rational r = (g1 * (f22 * g1 - f12 * g2) + g2 * (f11 * g2 - f12 * g1)) / fourDet - reps.c;
if (r > zero)
{
if (positiveRoots == 2)
{
return Classification::ELLIPTIC_CYLINDER;
}
else if (positiveRoots == 1)
{
return Classification::HYPERBOLIC_CYLINDER;
}
else
{
return Classification::NONE;
}
}
else if (r < zero)
{
if (positiveRoots == 2)
{
return Classification::NONE;
}
else if (positiveRoots == 1)
{
return Classification::HYPERBOLIC_CYLINDER;
}
else
{
return Classification::ELLIPTIC_CYLINDER;
}
}
// else r == 0
return (positiveRoots == 1 ? Classification::TWO_PLANES : Classification::LINE);
}
static Classification ClassifyZeroRoots2(const RReps& reps, int32_t positiveRoots)
{
// Generate an orthonormal set {p0,p1,p2}, where p0 and p1 are
// eigenvectors of A corresponding to eigenvalue zero. The vector
// p2 is an eigenvector of A corresponding to eigenvalue c2.
Rational const zero(0);
RVector3 P0, P1, P2;
if (reps.a00 != zero || reps.a01 != zero || reps.a02 != zero)
{
// row 0 is not zero
P2 = { reps.a00, reps.a01, reps.a02 };
}
else if (reps.a01 != zero || reps.a11 != zero || reps.a12 != zero)
{
// row 1 is not zero
P2 = { reps.a01, reps.a11, reps.a12 };
}
else
{
// row 2 is not zero
P2 = { reps.a02, reps.a12, reps.a22 };
}
if (P2[0] != zero)
{
P1[0] = P2[1];
P1[1] = -P2[0];
P1[2] = zero;
}
else
{
P1[0] = zero;
P1[1] = P2[2];
P1[2] = -P2[1];
}
P0 = Cross(P1, P2);
return ClassifyZeroRoots2(reps, positiveRoots, P0, P1, P2);
}
static Classification ClassifyZeroRoots2(RReps const& reps, int32_t positiveRoots,
RVector3 const& P0, RVector3 const& P1, RVector3 const& P2)
{
Rational const zero(0);
Rational e0 = P0[0] * reps.b0 + P0[1] * reps.b1 + P0[2] * reps.b1;
if (e0 != zero)
{
return Classification::PARABOLIC_CYLINDER;
}
Rational e1 = P1[0] * reps.b0 + P1[1] * reps.b1 + P1[2] * reps.b1;
if (e1 != zero)
{
return Classification::PARABOLIC_CYLINDER;
}
Rational f1 = reps.k2 * Dot(P2, P2);
Rational e2 = P2[0] * reps.b0 + P2[1] * reps.b1 + P2[2] * reps.b1;
Rational r = e2 * e2 / (Rational(4) * f1) - reps.c;
if (r > zero)
{
if (positiveRoots == 1)
{
return Classification::TWO_PLANES;
}
else
{
return Classification::NONE;
}
}
else if (r < zero)
{
if (positiveRoots == 1)
{
return Classification::NONE;
}
else
{
return Classification::TWO_PLANES;
}
}
// else r == 0
return Classification::PLANE;
}
static Classification ClassifyZeroRoots3(RReps const& reps)
{
Rational const zero(0);
if (reps.b0 != zero || reps.b1 != zero || reps.b2 != zero)
{
return Classification::PLANE;
}
return Classification::NONE;
}
std::array<Real, 10> mCoefficient;
Real mC;
Vector3<Real> mB;
Matrix3x3<Real> mA;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Histogram.h | .h | 11,317 | 339 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Logger.h>
#include <algorithm>
#include <vector>
namespace gte
{
class Histogram
{
public:
// In the constructor with input 'int32_t const* samples', set noRescaling
// to 'true' when you want the sample values mapped directly to the
// buckets. Typically, you know that the sample values are in the set
// of numbers {0,1,...,numBuckets-1}, but in the event of out-of-range
// values, the histogram stores a count for those numbers smaller than
// 0 and those numbers larger or equal to numBuckets.
Histogram(int32_t numBuckets, int32_t numSamples, int32_t const* samples, bool noRescaling)
:
mBuckets(numBuckets),
mExcessLess(0),
mExcessGreater(0)
{
LogAssert(numBuckets > 0 && numSamples > 0 && samples != nullptr, "Invalid input.");
std::fill(mBuckets.begin(), mBuckets.end(), 0);
if (noRescaling)
{
// Map to the buckets, also counting out-of-range pixels.
for (int32_t i = 0; i < numSamples; ++i)
{
int32_t value = samples[i];
if (0 <= value)
{
if (value < numBuckets)
{
++mBuckets[value];
}
else
{
++mExcessGreater;
}
}
else
{
++mExcessLess;
}
}
}
else
{
// Compute the extremes.
int32_t minValue = samples[0], maxValue = minValue;
for (int32_t i = 1; i < numSamples; ++i)
{
int32_t value = samples[i];
if (value < minValue)
{
minValue = value;
}
else if (value > maxValue)
{
maxValue = value;
}
}
// Map to the buckets.
if (minValue < maxValue)
{
// The image is not constant.
double numer = static_cast<double>(numBuckets) - 1.0;
double denom = static_cast<double>(maxValue) - static_cast<double>(minValue);
double mult = numer / denom;
for (int32_t i = 0; i < numSamples; ++i)
{
int32_t index = static_cast<int32_t>(mult * (static_cast<double>(samples[i]) - static_cast<double>(minValue)));
++mBuckets[index];
}
}
else
{
// The image is constant.
mBuckets[0] = numSamples;
}
}
}
Histogram(int32_t numBuckets, int32_t numSamples, float const* samples)
:
mBuckets(numBuckets),
mExcessLess(0),
mExcessGreater(0)
{
LogAssert(numBuckets > 0 && numSamples > 0 && samples != nullptr, "Invalid input.");
std::fill(mBuckets.begin(), mBuckets.end(), 0);
// Compute the extremes.
float minValue = samples[0], maxValue = minValue;
for (int32_t i = 1; i < numSamples; ++i)
{
float value = samples[i];
if (value < minValue)
{
minValue = value;
}
else if (value > maxValue)
{
maxValue = value;
}
}
// Map to the buckets.
if (minValue < maxValue)
{
// The image is not constant.
double numer = static_cast<double>(numBuckets) - 1.0;
double denom = static_cast<double>(maxValue) - static_cast<double>(minValue);
double mult = numer / denom;
for (int32_t i = 0; i < numSamples; ++i)
{
int32_t index = static_cast<int32_t>(mult * (static_cast<double>(samples[i]) - static_cast<double>(minValue)));
++mBuckets[index];
}
}
else
{
// The image is constant.
mBuckets[0] = numSamples;
}
}
Histogram(int32_t numBuckets, int32_t numSamples, double const* samples)
:
mBuckets(numBuckets),
mExcessLess(0),
mExcessGreater(0)
{
LogAssert(numBuckets > 0 && numSamples > 0 && samples != nullptr, "Invalid input.");
std::fill(mBuckets.begin(), mBuckets.end(), 0);
// Compute the extremes.
double minValue = samples[0], maxValue = minValue;
for (int32_t i = 1; i < numSamples; ++i)
{
double value = samples[i];
if (value < minValue)
{
minValue = value;
}
else if (value > maxValue)
{
maxValue = value;
}
}
// Map to the buckets.
if (minValue < maxValue)
{
// The image is not constant.
double numer = static_cast<double>(numBuckets) - 1.0;
double denom = maxValue - minValue;
double mult = numer / denom;
for (int32_t i = 0; i < numSamples; ++i)
{
int32_t index = static_cast<int32_t>(mult * (samples[i] - minValue));
++mBuckets[index];
}
}
else
{
// The image is constant.
mBuckets[0] = numSamples;
}
}
// Construction when you plan on updating the histogram incrementally.
// The incremental update is implemented only for integer samples and
// no rescaling.
Histogram(int32_t numBuckets)
:
mBuckets(numBuckets),
mExcessLess(0),
mExcessGreater(0)
{
LogAssert(numBuckets > 0, "Invalid input.");
std::fill(mBuckets.begin(), mBuckets.end(), 0);
}
// This function is called when you have used the Histogram(int32_t)
// constructor. No bounds checking is used; you must ensure that the
// input value is in {0,...,numBuckets-1}.
inline void Insert(int32_t value)
{
++mBuckets[value];
}
// This function is called when you have used the Histogram(int32_t)
// constructor. Bounds checking is used.
void InsertCheck(int32_t value)
{
if (0 <= value)
{
if (value < static_cast<int32_t>(mBuckets.size()))
{
++mBuckets[value];
}
else
{
++mExcessGreater;
}
}
else
{
++mExcessLess;
}
}
// Member access.
inline std::vector<int32_t> const& GetBuckets() const
{
return mBuckets;
}
inline int32_t GetExcessLess() const
{
return mExcessLess;
}
inline int32_t GetExcessGreater() const
{
return mExcessGreater;
}
// In the following, define cdf(V) = sum_{i=0}^{V} bucket[i], where
// 0 <= V < B and B is the number of buckets. Define N = cdf(B-1),
// which must be the number of pixels in the image.
// Get the lower tail of the histogram. The returned index L has the
// properties: cdf(L-1)/N < tailAmount and cdf(L)/N >= tailAmount.
int32_t GetLowerTail(double tailAmount)
{
int32_t const numBuckets = static_cast<int32_t>(mBuckets.size());
int32_t hSum = 0;
for (int32_t i = 0; i < numBuckets; ++i)
{
hSum += mBuckets[i];
}
int32_t hTailSum = static_cast<int32_t>(tailAmount * hSum);
int32_t hLowerSum = 0;
int32_t lower;
for (lower = 0; lower < numBuckets; ++lower)
{
hLowerSum += mBuckets[lower];
if (hLowerSum >= hTailSum)
{
break;
}
}
return lower;
}
// Get the upper tail of the histogram. The returned index U has the
// properties: cdf(U)/N >= 1-tailAmount and cdf(U+1) < 1-tailAmount.
int32_t GetUpperTail(double tailAmount)
{
int32_t const numBuckets = static_cast<int32_t>(mBuckets.size());
int32_t hSum = 0;
for (int32_t i = 0; i < numBuckets; ++i)
{
hSum += mBuckets[i];
}
int32_t hTailSum = static_cast<int32_t>(tailAmount * hSum);
int32_t hUpperSum = 0;
int32_t upper;
for (upper = numBuckets - 1; upper >= 0; --upper)
{
hUpperSum += mBuckets[upper];
if (hUpperSum >= hTailSum)
{
break;
}
}
return upper;
}
// Get the lower and upper tails of the histogram. The returned
// indices are L and U and have the properties:
// cdf(L-1)/N < tailAmount/2, cdf(L)/N >= tailAmount/2,
// cdf(U)/N >= 1-tailAmount/2, and cdf(U+1) < 1-tailAmount/2.
void GetTails(double tailAmount, int32_t& lower, int32_t& upper)
{
int32_t const numBuckets = static_cast<int32_t>(mBuckets.size());
int32_t hSum = 0;
for (int32_t i = 0; i < numBuckets; ++i)
{
hSum += mBuckets[i];
}
int32_t hTailSum = static_cast<int32_t>(0.5 * tailAmount * hSum);
int32_t hLowerSum = 0;
for (lower = 0; lower < numBuckets; ++lower)
{
hLowerSum += mBuckets[lower];
if (hLowerSum >= hTailSum)
{
break;
}
}
int32_t hUpperSum = 0;
for (upper = numBuckets - 1; upper >= 0; --upper)
{
hUpperSum += mBuckets[upper];
if (hUpperSum >= hTailSum)
{
break;
}
}
}
private:
std::vector<int32_t> mBuckets;
int32_t mExcessLess, mExcessGreater;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/VEManifoldMesh.h | .h | 8,514 | 272 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Logger.h>
#include <array>
#include <map>
#include <memory>
namespace gte
{
class VEManifoldMesh
{
public:
// Vertex data types.
class Vertex;
typedef std::shared_ptr<Vertex>(*VCreator)(int32_t);
typedef std::map<int32_t, std::shared_ptr<Vertex>> VMap;
// Edge data types.
class Edge;
typedef std::shared_ptr<Edge>(*ECreator)(int32_t, int32_t);
typedef std::map<std::pair<int32_t, int32_t>, std::shared_ptr<Edge>> EMap;
// Vertex object.
class Vertex
{
public:
virtual ~Vertex() = default;
Vertex(int32_t v)
:
V(v)
{
}
// The unique vertex index.
int32_t V;
// The edges (if any) sharing the vertex.
std::array<std::weak_ptr<Edge>, 2> E;
};
// Edge object.
class Edge
{
public:
virtual ~Edge() = default;
Edge(int32_t v0, int32_t v1)
:
V{ v0, v1 }
{
}
// Vertices, listed as a directed edge <V[0],V[1]>.
std::array<int32_t, 2> V;
// Adjacent edges. E[i] points to edge sharing V[i].
std::array<std::weak_ptr<Edge>, 2> E;
};
// Construction and destruction.
virtual ~VEManifoldMesh() = default;
VEManifoldMesh(VCreator vCreator = nullptr, ECreator eCreator = nullptr)
:
mVCreator(vCreator ? vCreator : CreateVertex),
mECreator(eCreator ? eCreator : CreateEdge),
mThrowOnNonmanifoldInsertion(true)
{
}
// Member access.
inline VMap const& GetVertices() const
{
return mVMap;
}
inline EMap const& GetEdges() const
{
return mEMap;
}
// If the insertion of an edge 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.
void ThrowOnNonmanifoldInsertion(bool doException)
{
mThrowOnNonmanifoldInsertion = doException;
}
// If <v0,v1> is not in the mesh, an Edge object is created and
// returned; otherwise, <v0,v1> is in the mesh and nullptr is
// returned. If the insertion leads to a nonmanifold mesh, the
// call fails with a nullptr returned.
std::shared_ptr<Edge> Insert(int32_t v0, int32_t v1)
{
std::pair<int32_t, int32_t> ekey(v0, v1);
if (mEMap.find(ekey) != mEMap.end())
{
// The edge already exists. Return a null pointer as a
// signal to the caller that the insertion failed.
return nullptr;
}
// Add the new edge.
std::shared_ptr<Edge> edge = mECreator(v0, v1);
mEMap[ekey] = edge;
// Add the vertices if they do not already exist.
for (int32_t i = 0; i < 2; ++i)
{
int32_t v = edge->V[i];
std::shared_ptr<Vertex> vertex;
auto viter = mVMap.find(v);
if (viter == mVMap.end())
{
// This is the first time the vertex is encountered.
vertex = mVCreator(v);
mVMap[v] = vertex;
// Update the vertex.
vertex->E[0] = edge;
}
else
{
// This is the second time the vertex is encountered.
vertex = viter->second;
LogAssert(vertex != nullptr, "Unexpected condition.");
// Update the vertex.
if (vertex->E[1].lock())
{
if (mThrowOnNonmanifoldInsertion)
{
LogError("The mesh must be manifold.");
}
else
{
return nullptr;
}
}
vertex->E[1] = edge;
// Update the adjacent edge.
auto adjacent = vertex->E[0].lock();
LogAssert(adjacent != nullptr, "Unexpected condition.");
for (int32_t j = 0; j < 2; ++j)
{
if (adjacent->V[j] == v)
{
adjacent->E[j] = edge;
break;
}
}
// Update the edge.
edge->E[i] = adjacent;
}
}
return edge;
}
// If <v0,v1> is in the mesh, it is removed and 'true' is returned;
// otherwise, <v0,v1> is not in the mesh and 'false' is returned.
bool Remove(int32_t v0, int32_t v1)
{
std::pair<int32_t, int32_t> ekey(v0, v1);
auto eiter = mEMap.find(ekey);
if (eiter == mEMap.end())
{
// The edge does not exist.
return false;
}
// Get the edge.
std::shared_ptr<Edge> edge = eiter->second;
// Remove the vertices if necessary (when they are not shared).
for (int32_t i = 0; i < 2; ++i)
{
// Inform the vertices the edge is being deleted.
auto viter = mVMap.find(edge->V[i]);
LogAssert(viter != mVMap.end(), "Unexpected condition.");
std::shared_ptr<Vertex> vertex = viter->second;
LogAssert(vertex != nullptr, "Unexpected condition.");
if (vertex->E[0].lock() == edge)
{
// One-edge vertices always have pointer at index zero.
vertex->E[0] = vertex->E[1];
vertex->E[1].reset();
}
else if (vertex->E[1].lock() == edge)
{
vertex->E[1].reset();
}
else
{
LogError("Unexpected condition.");
}
// Remove the vertex if you have the last reference to it.
if (!vertex->E[0].lock() && !vertex->E[1].lock())
{
mVMap.erase(vertex->V);
}
// Inform adjacent edges the edge is being deleted.
auto adjacent = edge->E[i].lock();
if (adjacent)
{
for (int32_t j = 0; j < 2; ++j)
{
if (adjacent->E[j].lock() == edge)
{
adjacent->E[j].reset();
break;
}
}
}
}
mEMap.erase(ekey);
return true;
}
// A manifold mesh is closed if each vertex is shared twice.
bool IsClosed() const
{
for (auto const& element : mVMap)
{
auto vertex = element.second;
if (!vertex->E[0].lock() || !vertex->E[1].lock())
{
return false;
}
}
return true;
}
protected:
// The vertex data and default vertex creation.
static std::shared_ptr<Vertex> CreateVertex(int32_t v0)
{
return std::make_shared<Vertex>(v0);
}
VCreator mVCreator;
VMap mVMap;
// The edge data and default edge creation.
static std::shared_ptr<Edge> CreateEdge(int32_t v0, int32_t v1)
{
return std::make_shared<Edge>(v0, v1);
}
ECreator mECreator;
EMap mEMap;
bool mThrowOnNonmanifoldInsertion; // default: true
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistPointSegment.h | .h | 3,342 | 105 | // 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/Segment.h>
// Compute the distance between a point and a segment in nD.
//
// The segment is P0 + t * (P1 - P0) for 0 <= t <= 1. The direction D = P1-P0
// is generally not unit length.
//
// The input point is stored in closest[0]. The closest point on the segment
// 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>, Segment<N, T>>
{
public:
struct Result
{
Result()
:
distance(static_cast<T>(0)),
sqrDistance(static_cast<T>(0)),
parameter(static_cast<T>(0)),
closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() }
{
}
T distance, sqrDistance;
T parameter;
std::array<Vector<N, T>, 2> closest;
};
Result operator()(Vector<N, T> const& point, Segment<N, T> const& segment)
{
Result result{};
// The direction vector is not unit length. The normalization is
// deferred until it is needed.
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
Vector<N, T> direction = segment.p[1] - segment.p[0];
Vector<N, T> diff = point - segment.p[1];
T t = Dot(direction, diff);
if (t >= zero)
{
result.parameter = one;
result.closest[1] = segment.p[1];
}
else
{
diff = point - segment.p[0];
t = Dot(direction, diff);
if (t <= zero)
{
result.parameter = zero;
result.closest[1] = segment.p[0];
}
else
{
T sqrLength = Dot(direction, direction);
if (sqrLength > zero)
{
t /= sqrLength;
result.parameter = t;
result.closest[1] = segment.p[0] + t * direction;
}
else
{
result.parameter = zero;
result.closest[1] = segment.p[0];
}
}
}
result.closest[0] = point;
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 DCPPointSegment = DCPQuery<T, Vector<N, T>, Segment<N, T>>;
template <typename T>
using DCPPoint2Segment2 = DCPPointSegment<2, T>;
template <typename T>
using DCPPoint3Segment3 = DCPPointSegment<3, T>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrRay3Cylinder3.h | .h | 2,758 | 84 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/IntrIntervals.h>
#include <Mathematics/IntrLine3Cylinder3.h>
#include <Mathematics/Ray.h>
// The queries consider the cylinder to be a solid.
namespace gte
{
template <typename T>
class FIQuery<T, Ray3<T>, Cylinder3<T>>
:
public FIQuery<T, Line3<T>, Cylinder3<T>>
{
public:
struct Result
:
public FIQuery<T, Line3<T>, Cylinder3<T>>::Result
{
Result()
:
FIQuery<T, Line3<T>, Cylinder3<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray3<T> const& ray, Cylinder3<T> const& cylinder)
{
Result result{};
DoQuery(ray.origin, ray.direction, cylinder, result);
if (result.intersect)
{
for (size_t i = 0; i < 2; ++i)
{
result.point[i] = ray.origin + result.parameter[i] * ray.direction;
}
}
return result;
}
protected:
// The caller must ensure that on entry, 'result' is default
// constructed as if there is no intersection. If an intersection is
// found, the 'result' values will be modified accordingly.
void DoQuery(Vector3<T> const& rayOrigin,
Vector3<T> const& rayDirection, Cylinder3<T> const& cylinder,
Result& result)
{
FIQuery<T, Line3<T>, Cylinder3<T>>::DoQuery(
rayOrigin, rayDirection, cylinder, result);
if (result.intersect)
{
// The line containing the ray intersects the cylinder; the
// t-interval is [t0,t1]. The ray intersects the cylinder as
// long as [t0,t1] overlaps the ray t-interval [0,+infinity).
FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery;
auto iiResult = iiQuery(result.parameter, static_cast<T>(0), true);
if (iiResult.intersect)
{
result.numIntersections = iiResult.numIntersections;
result.parameter = iiResult.overlap;
}
else
{
// The line containing the ray does not intersect the
// cylinder.
result = Result{};
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/AtomicMinMax.h | .h | 1,107 | 44 | // 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 <atomic>
// Implementations of atomic minimum and atomic maximum computations. These
// are based on std::atomic_compare_exchange_strong.
namespace gte
{
template <typename T>
T AtomicMin(std::atomic<T>& v0, T const& v1)
{
T vInitial, vMin;
do
{
vInitial = v0;
vMin = std::min(vInitial, v1);
}
while (!std::atomic_compare_exchange_strong(&v0, &vInitial, vMin));
return vInitial;
}
template <typename T>
T AtomicMax(std::atomic<T>& v0, T const& v1)
{
T vInitial, vMax;
do
{
vInitial = v0;
vMax = std::max(vInitial, v1);
}
while (!std::atomic_compare_exchange_strong(&v0, &vInitial, vMax));
return vInitial;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistRectangle3CanonicalBox3.h | .h | 5,170 | 129 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/DistPlane3CanonicalBox3.h>
#include <Mathematics/DistSegment3CanonicalBox3.h>
#include <Mathematics/Rectangle.h>
// Compute the distance between a rectangle and a solid canonical box in 3D.
//
// The rectangle has center C, unit-length axis directions W[0] and W[1], and
// extents e[0] and e[1]. A rectangle point is X = C + sum_{i=0}^2 s[i] * W[i]
// where |s[i]| <= e[i] for all i.
//
// The 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 rectangle is stored in closest[0] with
// W-coordinates (s[0],s[1]). The closest point on the box is stored in
// closest[1]. When there are infinitely many choices for the pair of closest
// points, only one of them is returned.
//
// TODO: Modify to support non-unit-length W[].
namespace gte
{
template <typename T>
class DCPQuery<T, Rectangle3<T>, CanonicalBox3<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{ Vector3<T>::Zero(), Vector3<T>::Zero() }
{
}
T distance, sqrDistance;
std::array<T, 2> cartesian;
std::array<Vector3<T>, 2> closest;
};
Result operator()(Rectangle3<T> const& rectangle, CanonicalBox3<T> const& box)
{
Result result{};
using PBQuery = DCPQuery<T, Plane3<T>, CanonicalBox3<T>>;
PBQuery pbQuery{};
Vector3<T> normal = Cross(rectangle.axis[0], rectangle.axis[1]);
Plane3<T> plane(normal, rectangle.center);
auto pbOutput = pbQuery(plane, box);
Vector3<T> delta = pbOutput.closest[0] - rectangle.center;
result.cartesian[0] = Dot(rectangle.axis[0], delta);
result.cartesian[1] = Dot(rectangle.axis[1], delta);
if (std::fabs(result.cartesian[0]) <= rectangle.extent[0] &&
std::fabs(result.cartesian[1]) <= rectangle.extent[1])
{
result.distance = pbOutput.distance;
result.sqrDistance = pbOutput.sqrDistance;
result.closest = pbOutput.closest;
}
else
{
// The closest plane point is outside the rectangle, although
// it is possible there are points inside the rectangle that
// also are closest points to the box. Regardless, locate a
// point on an edge of the rectangle that is closest to the
// box. TODO: Will clamping work as is the case for distances
// between line segments and objects?
using SBQuery = DCPQuery<T, Segment3<T>, CanonicalBox3<T>>;
SBQuery sbQuery{};
typename SBQuery::Result sbOutput{};
Segment3<T> segment{};
T const one = static_cast<T>(1);
T const negOne = static_cast<T>(-1);
T const two = static_cast<T>(2);
T const invalid = static_cast<T>(-1);
result.distance = invalid;
result.sqrDistance = invalid;
std::array<T, 4> const sign{ negOne, one, negOne, one };
std::array<int32_t, 4> j0{ 0, 0, 1, 1 };
std::array<int32_t, 4> j1{ 1, 1, 0, 0 };
std::array<std::array<size_t, 2>, 4> const edges
{{
{ 0, 1 }, { 2, 3 }, // horizontal edges
{ 0, 2 }, { 1, 3 } // vertical edges
}};
std::array<Vector3<T>, 4> vertices{};
rectangle.GetVertices(vertices);
for (size_t i = 0; i < 4; ++i)
{
auto const& edge = edges[i];
segment.p[0] = vertices[edge[0]];
segment.p[1] = vertices[edge[1]];
sbOutput = sbQuery(segment, box);
if (result.sqrDistance == invalid ||
sbOutput.sqrDistance < result.sqrDistance)
{
result.distance = sbOutput.distance;
result.sqrDistance = sbOutput.sqrDistance;
result.closest = sbOutput.closest;
T const scale = two * sbOutput.parameter - one;
result.cartesian[j0[i]] = scale * rectangle.extent[j0[i]];
result.cartesian[j1[i]] = sign[i] * rectangle.extent[j1[i]];
}
}
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/EllipsoidGeodesic.h | .h | 4,885 | 144 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/RiemannianGeodesic.h>
namespace gte
{
template <typename Real>
class EllipsoidGeodesic : public RiemannianGeodesic<Real>
{
public:
// The ellipsoid is (x/a)^2 + (y/b)^2 + (z/c)^2 = 1, where xExtent is
// 'a', yExtent is 'b', and zExtent is 'c'. The surface is represented
// parametrically by angles u and v, say
// P(u,v) = (x(u,v),y(u,v),z(u,v)),
// P(u,v) =(a*cos(u)*sin(v), b*sin(u)*sin(v), c*cos(v))
// with 0 <= u < 2*pi and 0 <= v <= pi. The first-order derivatives
// are
// dP/du = (-a*sin(u)*sin(v), b*cos(u)*sin(v), 0)
// dP/dv = (a*cos(u)*cos(v), b*sin(u)*cos(v), -c*sin(v))
// The metric tensor elements are
// g_{00} = Dot(dP/du,dP/du)
// g_{01} = Dot(dP/du,dP/dv)
// g_{10} = g_{01}
// g_{11} = Dot(dP/dv,dP/dv)
EllipsoidGeodesic(Real xExtent, Real yExtent, Real zExtent)
:
RiemannianGeodesic<Real>(2),
mXExtent(xExtent),
mYExtent(yExtent),
mZExtent(zExtent),
mCos0((Real)0),
mSin0((Real)0),
mCos1((Real)0),
mSin1((Real)0),
mDer0(Vector3<Real>::Zero()),
mDer1(Vector3<Real>::Zero())
{
}
virtual ~EllipsoidGeodesic()
{
}
Vector3<Real> ComputePosition(GVector<Real> const& point)
{
Real cos0 = std::cos(point[0]);
Real sin0 = std::sin(point[0]);
Real cos1 = std::cos(point[1]);
Real sin1 = std::sin(point[1]);
return Vector3<Real>
{
mXExtent * cos0 * sin1,
mYExtent * sin0 * sin1,
mZExtent * cos1
};
}
// To compute the geodesic path connecting two parameter points
// (u0,v0) and (u1,v1):
//
// float a, b, c; // the extents of the ellipsoid
// EllipsoidGeodesic<float> EG(a,b,c);
// GVector<float> param0(2), param1(2);
// param0[0] = u0;
// param0[1] = v0;
// param1[0] = u1;
// param1[1] = v1;
//
// int32_t quantity;
// std:vector<GVector<float>> path;
// EG.ComputeGeodesic(param0, param1, quantity, path);
private:
virtual void ComputeMetric(GVector<Real> const& point) override
{
mCos0 = std::cos(point[0]);
mSin0 = std::sin(point[0]);
mCos1 = std::cos(point[1]);
mSin1 = std::sin(point[1]);
mDer0 = { -mXExtent * mSin0 * mSin1, mYExtent * mCos0 * mSin1, (Real)0 };
mDer1 = { mXExtent * mCos0 * mCos1, mYExtent * mSin0 * mCos1, -mZExtent * mSin1 };
this->mMetric(0, 0) = Dot(mDer0, mDer0);
this->mMetric(0, 1) = Dot(mDer0, mDer1);
this->mMetric(1, 0) = this->mMetric(0, 1);
this->mMetric(1, 1) = Dot(mDer1, mDer1);
}
virtual void ComputeChristoffel1(GVector<Real> const&) override
{
Vector3<Real> der00
{
-mXExtent * mCos0 * mSin1,
-mYExtent * mSin0 * mSin1,
(Real)0
};
Vector3<Real> der01
{
-mXExtent * mSin0 * mCos1,
mYExtent * mCos0 * mCos1,
(Real)0
};
Vector3<Real> der11
{
-mXExtent * mCos0 * mSin1,
-mYExtent * mSin0 * mSin1,
-mZExtent * mCos1
};
this->mChristoffel1[0](0, 0) = Dot(der00, mDer0);
this->mChristoffel1[0](0, 1) = Dot(der01, mDer0);
this->mChristoffel1[0](1, 0) = this->mChristoffel1[0](0, 1);
this->mChristoffel1[0](1, 1) = Dot(der11, mDer0);
this->mChristoffel1[1](0, 0) = Dot(der00, mDer1);
this->mChristoffel1[1](0, 1) = Dot(der01, mDer1);
this->mChristoffel1[1](1, 0) = this->mChristoffel1[1](0, 1);
this->mChristoffel1[1](1, 1) = Dot(der11, mDer1);
}
// The ellipsoid axis half-lengths.
Real mXExtent, mYExtent, mZExtent;
// We are guaranteed that RiemannianGeodesic calls ComputeMetric
// before ComputeChristoffel1. Thus, we can compute the surface
// first- and second-order derivatives in ComputeMetric and cache
// the results for use in ComputeChristoffel1.
Real mCos0, mSin0, mCos1, mSin1;
Vector3<Real> mDer0, mDer1;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistRayRay.h | .h | 5,516 | 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/DCPQuery.h>
#include <Mathematics/Ray.h>
// Compute the distance between two rays in nD.
//
// The rays are P[i] + s[i] * D[i] for s[i] >= 0, where D[i] is not required
// to be unit length.
//
// The closest point on ray[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, Ray<N, T>, Ray<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()(Ray<N, T> const& ray0, Ray<N, T> const& ray1)
{
Result result{};
T const zero = static_cast<T>(0);
Vector<N, T> diff = ray0.origin - ray1.origin;
T a00 = Dot(ray0.direction, ray0.direction);
T a01 = -Dot(ray0.direction, ray1.direction);
T a11 = Dot(ray1.direction, ray1.direction);
T b0 = Dot(ray0.direction, diff);
T det = std::max(a00 * a11 - a01 * a01, zero);
T s0{}, s1{};
if (det > zero)
{
// The rays are not parallel.
T b1 = -Dot(ray1.direction, diff);
s0 = a01 * b1 - a11 * b0;
s1 = a01 * b0 - a00 * b1;
if (s0 >= zero)
{
if (s1 >= zero) // region 0 (interior)
{
// The minimum occurs at two interior points of
// the rays.
s0 /= det;
s1 /= det;
}
else // region 3 (side)
{
if (b0 >= zero)
{
s0 = zero;
}
else
{
s0 = -b0 / a00;
}
s1 = zero;
}
}
else
{
if (s1 >= zero) // region 1 (side)
{
s0 = zero;
if (b1 >= zero)
{
s1 = zero;
}
else
{
s1 = -b1 / a11;
}
}
else // region 2 (corner)
{
if (b0 < zero)
{
s0 = -b0 / a00;
s1 = zero;
}
else
{
s0 = zero;
if (b1 >= zero)
{
s1 = zero;
}
else
{
s1 = -b1 / a11;
}
}
}
}
}
else
{
// The rays are parallel.
if (a01 > zero)
{
// Opposite direction vectors.
s1 = zero;
if (b0 >= zero)
{
s0 = zero;
}
else
{
s0 = -b0 / a00;
}
}
else
{
// Same direction vectors.
if (b0 >= zero)
{
T b1 = -Dot(ray1.direction, diff);
s0 = zero;
s1 = -b1 / a11;
}
else
{
s0 = -b0 / a00;
s1 = zero;
}
}
}
result.parameter[0] = s0;
result.parameter[1] = s1;
result.closest[0] = ray0.origin + s0 * ray0.direction;
result.closest[1] = ray1.origin + s1 * ray1.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 DCPRayRay = DCPQuery<T, Ray<N, T>, Ray<N, T>>;
template <typename T>
using DCPRay2Ray2 = DCPRayRay<2, T>;
template <typename T>
using DCPRay3Ray3 = DCPRayRay<3, T>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrTriangle3OrientedBox3.h | .h | 7,528 | 221 | // 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/IntrConvexPolygonHyperplane.h>
#include <Mathematics/Triangle.h>
#include <Mathematics/OrientedBox.h>
#include <Mathematics/Vector3.h>
// The test-intersection query is based on the document
// https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf
// The find-intersection query clips the triangle against the faces of
// the oriented box.
namespace gte
{
template <typename Real>
class TIQuery<Real, Triangle3<Real>, OrientedBox3<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Triangle3<Real> const& triangle, OrientedBox3<Real> const& box)
{
Result result{};
Real min0 = (Real)0, max0 = (Real)0, min1 = (Real)0, max1 = (Real)0;
Vector3<Real> D, edge[3];
// Test direction of triangle normal.
edge[0] = triangle.v[1] - triangle.v[0];
edge[1] = triangle.v[2] - triangle.v[0];
D = Cross(edge[0], edge[1]);
min0 = Dot(D, triangle.v[0]);
max0 = min0;
GetProjection(D, box, min1, max1);
if (max1 < min0 || max0 < min1)
{
result.intersect = false;
return result;
}
// Test direction of box faces.
for (int32_t i = 0; i < 3; ++i)
{
D = box.axis[i];
GetProjection(D, triangle, min0, max0);
Real DdC = Dot(D, box.center);
min1 = DdC - box.extent[i];
max1 = DdC + box.extent[i];
if (max1 < min0 || max0 < min1)
{
result.intersect = false;
return result;
}
}
// Test direction of triangle-box edge cross products.
edge[2] = edge[1] - edge[0];
for (int32_t i0 = 0; i0 < 3; ++i0)
{
for (int32_t i1 = 0; i1 < 3; ++i1)
{
D = Cross(edge[i0], box.axis[i1]);
GetProjection(D, triangle, min0, max0);
GetProjection(D, box, min1, max1);
if (max1 < min0 || max0 < min1)
{
result.intersect = false;
return result;
}
}
}
result.intersect = true;
return result;
}
private:
void GetProjection(Vector3<Real> const& axis, Triangle3<Real> const& triangle, Real& imin, Real& imax)
{
Real dot[3] =
{
Dot(axis, triangle.v[0]),
Dot(axis, triangle.v[1]),
Dot(axis, triangle.v[2])
};
imin = dot[0];
imax = imin;
if (dot[1] < imin)
{
imin = dot[1];
}
else if (dot[1] > imax)
{
imax = dot[1];
}
if (dot[2] < imin)
{
imin = dot[2];
}
else if (dot[2] > imax)
{
imax = dot[2];
}
}
void GetProjection(Vector3<Real> const& axis, OrientedBox3<Real> const& box, Real& imin, Real& imax)
{
Real origin = Dot(axis, box.center);
Real maximumExtent =
std::fabs(box.extent[0] * Dot(axis, box.axis[0])) +
std::fabs(box.extent[1] * Dot(axis, box.axis[1])) +
std::fabs(box.extent[2] * Dot(axis, box.axis[2]));
imin = origin - maximumExtent;
imax = origin + maximumExtent;
}
};
template <typename Real>
class FIQuery<Real, Triangle3<Real>, OrientedBox3<Real>>
{
public:
struct Result
{
Result()
:
insidePolygon{},
outsidePolygons{}
{
}
std::vector<Vector3<Real>> insidePolygon;
std::vector<std::vector<Vector3<Real>>> outsidePolygons;
};
Result operator()(Triangle3<Real> const& triangle, OrientedBox3<Real> const& box)
{
Result result{};
// Start with the triangle and clip it against each face of the
// box. The largest number of vertices for the polygon of
// intersection is 7.
result.insidePolygon.resize(3);
for (int32_t i = 0; i < 3; ++i)
{
result.insidePolygon[i] = triangle.v[i];
}
typedef FIQuery<Real, std::vector<Vector<3, Real>>, Hyperplane<3, Real>> PPQuery;
Plane3<Real> plane{};
PPQuery ppQuery{};
typename PPQuery::Result ppResult{};
for (int32_t dir = -1; dir <= 1; dir += 2)
{
for (int32_t side = 0; side < 3; ++side)
{
// Create a plane for the box face that points inside the box.
plane.normal = ((Real)dir) * box.axis[side];
plane.constant = Dot(plane.normal, box.center) - box.extent[side];
ppResult = ppQuery(result.insidePolygon, plane);
switch (ppResult.configuration)
{
case PPQuery::Configuration::SPLIT:
result.insidePolygon = ppResult.positivePolygon;
result.outsidePolygons.push_back(ppResult.negativePolygon);
break;
case PPQuery::Configuration::POSITIVE_SIDE_VERTEX:
case PPQuery::Configuration::POSITIVE_SIDE_EDGE:
case PPQuery::Configuration::POSITIVE_SIDE_STRICT:
// The result.insidePolygon is already
// ppResult.positivePolygon, but to make it clear,
// assign it here.
result.insidePolygon = ppResult.positivePolygon;
break;
case PPQuery::Configuration::NEGATIVE_SIDE_VERTEX:
case PPQuery::Configuration::NEGATIVE_SIDE_EDGE:
case PPQuery::Configuration::NEGATIVE_SIDE_STRICT:
result.insidePolygon.clear();
result.outsidePolygons.push_back(ppResult.negativePolygon);
return result;
case PPQuery::Configuration::CONTAINED:
// A triangle coplanar with a box face will be
// processed as if it is inside the box.
result.insidePolygon = ppResult.intersection;
break;
default:
result.insidePolygon.clear();
result.outsidePolygons.clear();
break;
}
}
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrConvexPolygonHyperplane.h | .h | 14,585 | 418 | // 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/FIQuery.h>
#include <Mathematics/Hyperplane.h>
#include <Mathematics/Vector.h>
#include <list>
#include <vector>
// The intersection queries are based on the document
// https://www.geometrictools.com/Documentation/ClipConvexPolygonByHyperplane.pdf
namespace gte
{
template <int32_t N, typename Real>
class TIQuery<Real, std::vector<Vector<N, Real>>, Hyperplane<N, Real>>
{
public:
enum class Configuration
{
SPLIT,
POSITIVE_SIDE_VERTEX,
POSITIVE_SIDE_EDGE,
POSITIVE_SIDE_STRICT,
NEGATIVE_SIDE_VERTEX,
NEGATIVE_SIDE_EDGE,
NEGATIVE_SIDE_STRICT,
CONTAINED,
INVALID_POLYGON
};
struct Result
{
Result()
:
intersect(false),
configuration(Configuration::INVALID_POLYGON)
{
}
bool intersect;
Configuration configuration;
};
Result operator()(std::vector<Vector<N, Real>> const& polygon, Hyperplane<N, Real> const& hyperplane)
{
Result result{};
size_t const numVertices = polygon.size();
if (numVertices < 3)
{
// The convex polygon must have at least 3 vertices.
result.intersect = false;
result.configuration = Configuration::INVALID_POLYGON;
return result;
}
// Determine on which side of the hyperplane each vertex lies.
size_t numPositive = 0, numNegative = 0, numZero = 0;
for (size_t i = 0; i < numVertices; ++i)
{
Real h = Dot(hyperplane.normal, polygon[i]) - hyperplane.constant;
if (h > (Real)0)
{
++numPositive;
}
else if (h < (Real)0)
{
++numNegative;
}
else
{
++numZero;
}
}
if (numPositive > 0)
{
if (numNegative > 0)
{
result.intersect = true;
result.configuration = Configuration::SPLIT;
}
else if (numZero == 0)
{
result.intersect = false;
result.configuration = Configuration::POSITIVE_SIDE_STRICT;
}
else if (numZero == 1)
{
result.intersect = true;
result.configuration = Configuration::POSITIVE_SIDE_VERTEX;
}
else // numZero > 1
{
result.intersect = true;
result.configuration = Configuration::POSITIVE_SIDE_EDGE;
}
}
else if (numNegative > 0)
{
if (numZero == 0)
{
result.intersect = false;
result.configuration = Configuration::NEGATIVE_SIDE_STRICT;
}
else if (numZero == 1)
{
// The polygon touches the plane in a vertex or an edge.
result.intersect = true;
result.configuration = Configuration::NEGATIVE_SIDE_VERTEX;
}
else // numZero > 1
{
result.intersect = true;
result.configuration = Configuration::NEGATIVE_SIDE_EDGE;
}
}
else // numZero == numVertices
{
result.intersect = true;
result.configuration = Configuration::CONTAINED;
}
return result;
}
};
template <int32_t N, typename Real>
class FIQuery<Real, std::vector<Vector<N, Real>>, Hyperplane<N, Real>>
{
public:
enum class Configuration
{
SPLIT,
POSITIVE_SIDE_VERTEX,
POSITIVE_SIDE_EDGE,
POSITIVE_SIDE_STRICT,
NEGATIVE_SIDE_VERTEX,
NEGATIVE_SIDE_EDGE,
NEGATIVE_SIDE_STRICT,
CONTAINED,
INVALID_POLYGON
};
struct Result
{
Result()
:
configuration(Configuration::INVALID_POLYGON),
intersection{},
positivePolygon{},
negativePolygon{}
{
}
// The intersection is either empty, a single vertex, a single
// edge or the polygon is contained by the hyperplane.
Configuration configuration;
std::vector<Vector<N, Real>> intersection;
// If 'configuration' is POSITIVE_* or SPLIT, this polygon is the
// portion of the query input 'polygon' on the positive side of
// the hyperplane with possibly a vertex or edge on the hyperplane.
std::vector<Vector<N, Real>> positivePolygon;
// If 'configuration' is NEGATIVE_* or SPLIT, this polygon is the
// portion of the query input 'polygon' on the negative side of
// the hyperplane with possibly a vertex or edge on the hyperplane.
std::vector<Vector<N, Real>> negativePolygon;
};
Result operator()(std::vector<Vector<N, Real>> const& polygon, Hyperplane<N, Real> const& hyperplane)
{
Result result{};
size_t const numVertices = polygon.size();
if (numVertices < 3)
{
// The convex polygon must have at least 3 vertices.
result.configuration = Configuration::INVALID_POLYGON;
return result;
}
// Determine on which side of the hyperplane the vertices live.
// The index maxPosIndex stores the index of the vertex on the
// positive side of the hyperplane that is farthest from the
// hyperplane. The index maxNegIndex stores the index of the
// vertex on the negative side of the hyperplane that is farthest
// from the hyperplane. If one or the other such vertex does not
// exist, the corresponding index will remain its initial value of
// max(size_t).
std::vector<Real> height(numVertices);
std::vector<size_t> zeroHeightIndices;
zeroHeightIndices.reserve(numVertices);
size_t numPositive = 0, numNegative = 0;
Real maxPosHeight = -std::numeric_limits<Real>::max();
Real maxNegHeight = std::numeric_limits<Real>::max();
size_t maxPosIndex = std::numeric_limits<size_t>::max();
size_t maxNegIndex = std::numeric_limits<size_t>::max();
for (size_t i = 0; i < numVertices; ++i)
{
height[i] = Dot(hyperplane.normal, polygon[i]) - hyperplane.constant;
if (height[i] > (Real)0)
{
++numPositive;
if (height[i] > maxPosHeight)
{
maxPosHeight = height[i];
maxPosIndex = i;
}
}
else if (height[i] < (Real)0)
{
++numNegative;
if (height[i] < maxNegHeight)
{
maxNegHeight = height[i];
maxNegIndex = i;
}
}
else
{
zeroHeightIndices.push_back(i);
}
}
if (numPositive > 0)
{
if (numNegative > 0)
{
result.configuration = Configuration::SPLIT;
bool doSwap = (maxPosHeight < -maxNegHeight);
if (doSwap)
{
for (auto& h : height)
{
h = -h;
}
std::swap(maxPosIndex, maxNegIndex);
}
SplitPolygon(polygon, height, maxPosIndex, result);
if (doSwap)
{
std::swap(result.positivePolygon, result.negativePolygon);
}
}
else
{
size_t numZero = zeroHeightIndices.size();
if (numZero == 0)
{
result.configuration = Configuration::POSITIVE_SIDE_STRICT;
}
else if (numZero == 1)
{
result.configuration = Configuration::POSITIVE_SIDE_VERTEX;
result.intersection =
{
polygon[zeroHeightIndices[0]]
};
}
else // numZero > 1
{
result.configuration = Configuration::POSITIVE_SIDE_EDGE;
result.intersection =
{
polygon[zeroHeightIndices[0]],
polygon[zeroHeightIndices[1]]
};
}
result.positivePolygon = polygon;
}
}
else if (numNegative > 0)
{
size_t numZero = zeroHeightIndices.size();
if (numZero == 0)
{
result.configuration = Configuration::NEGATIVE_SIDE_STRICT;
}
else if (numZero == 1)
{
result.configuration = Configuration::NEGATIVE_SIDE_VERTEX;
result.intersection =
{
polygon[zeroHeightIndices[0]]
};
}
else // numZero > 1
{
result.configuration = Configuration::NEGATIVE_SIDE_EDGE;
result.intersection =
{
polygon[zeroHeightIndices[0]],
polygon[zeroHeightIndices[1]]
};
}
result.negativePolygon = polygon;
}
else // numZero == numVertices
{
result.configuration = Configuration::CONTAINED;
result.intersection = polygon;
}
return result;
}
protected:
void SplitPolygon(std::vector<Vector<N, Real>> const& polygon,
std::vector<Real> const& height, size_t maxPosIndex, Result& result)
{
// Find the largest contiguous subset of indices for which
// height[i] >= 0.
size_t const numVertices = polygon.size();
std::list<Vector<N, Real>> positiveList;
positiveList.push_back(polygon[maxPosIndex]);
size_t end0 = maxPosIndex;
size_t end0prev = std::numeric_limits<size_t>::max();
for (size_t i = 0; i < numVertices; ++i)
{
end0prev = (end0 + numVertices - 1) % numVertices;
if (height[end0prev] >= (Real)0)
{
positiveList.push_front(polygon[end0prev]);
end0 = end0prev;
}
else
{
break;
}
}
size_t end1 = maxPosIndex;
size_t end1next = std::numeric_limits<size_t>::max();
for (size_t i = 0; i < numVertices; ++i)
{
end1next = (end1 + 1) % numVertices;
if (height[end1next] >= (Real)0)
{
positiveList.push_back(polygon[end1next]);
end1 = end1next;
}
else
{
break;
}
}
size_t index = end1next;
std::list<Vector<N, Real>> negativeList;
for (size_t i = 0; i < numVertices; ++i)
{
negativeList.push_back(polygon[index]);
index = (index + 1) % numVertices;
if (index == end0)
{
break;
}
}
// Clip the polygon.
if (height[end0] > (Real)0)
{
Real t = -height[end0prev] / (height[end0] - height[end0prev]);
Real omt = (Real)1 - t;
Vector<N, Real> V = omt * polygon[end0prev] + t * polygon[end0];
positiveList.push_front(V);
negativeList.push_back(V);
result.intersection.push_back(V);
}
else
{
negativeList.push_back(polygon[end0]);
result.intersection.push_back(polygon[end0]);
}
if (height[end1] > (Real)0)
{
Real t = -height[end1next] / (height[end1] - height[end1next]);
Real omt = (Real)1 - t;
Vector<N, Real> V = omt * polygon[end1next] + t * polygon[end1];
positiveList.push_back(V);
negativeList.push_front(V);
result.intersection.push_back(V);
}
else
{
negativeList.push_front(polygon[end1]);
result.intersection.push_back(polygon[end1]);
}
result.positivePolygon.reserve(positiveList.size());
for (auto const& p : positiveList)
{
result.positivePolygon.push_back(p);
}
result.negativePolygon.reserve(negativeList.size());
for (auto const& p : negativeList)
{
result.negativePolygon.push_back(p);
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ApprParallelLines2.h | .h | 12,581 | 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
// Least-squares fit of two parallel lines to points that presumably are
// clustered on the lines. The algorithm is described in
// https://www.geometrictools.com/Documentation/FitParallelLinesToPoints2D.pdf
#include <Mathematics/Polynomial1.h>
#include <Mathematics/RootsPolynomial.h>
#include <Mathematics/Vector2.h>
namespace gte
{
template <typename Real>
class ApprParallelLines2
{
public:
ApprParallelLines2()
:
mR0(0), mR1(1), mR2(2), mR3(3), mR4(4), mR5(5), mR6(6)
{
// The constants are set here in case Real is a rational type,
// which avoids construction costs for those types.
}
void Fit(std::vector<Vector2<Real>> const& P, uint32_t maxIterations,
Vector2<Real>& C, Vector2<Real>& V, Real& radius)
{
// Compute the average of the samples.
size_t const n = P.size();
Real const invN = static_cast<Real>(1) / static_cast<Real>(n);
std::vector<Vector2<Real>> PAdjust = P;
Vector2<Real> A{ mR0, mR0 };
for (auto const& sample : PAdjust)
{
A += sample;
}
A *= invN;
// Subtract the average from the samples so that the replacement
// points have zero average.
for (auto& sample : PAdjust)
{
sample -= A;
}
// Compute the Zpq terms.
ZValues data(PAdjust);
// Compute F(sigma,gamma) = f0(sigma) + gamma * f1(sigma).
Polynomial1<Real> f0, f1;
ComputeF(data, f0, f1);
Polynomial1<Real> freduced0(4), freduced1(3);
for (int32_t i = 0; i <= 4; ++i)
{
freduced0[i] = f0[2 * i];
}
for (int32_t i = 0; i <= 3; ++i)
{
freduced1[i] = f1[2 * i + 1];
}
// Evaluate the error function at any (sigma,gamma). Choose (0,1)
// so that we do not have to process a root sigma=0 later.
Real minSigma = mR0, minGamma = mR1;
Real minK = data.Z03 / (mR2 * data.Z02);
Real minKSqr = minK * minK;
Real minRSqr = minKSqr + data.Z02;
Real minError = data.Z04 - mR4 * minK * data.Z03 + (mR4 * minKSqr - data.Z02) * data.Z02;
if (f1 != Polynomial1<Real>{ mR0 })
{
Polynomial1<Real> sigmaSqrPoly{ mR0, mR0, mR1 };
Polynomial1<Real> f0Sqr = f0 * f0, f1Sqr = f1 * f1;
Polynomial1<Real> h = sigmaSqrPoly * f1Sqr + (f0Sqr - f1Sqr);
Polynomial1<Real> hreduced(8);
for (int32_t i = 0; i <= 8; ++i)
{
hreduced[i] = h[2 * i];
}
std::array<Real, 8> roots;
int32_t numRoots = RootsPolynomial<Real>::Find(8, &hreduced[0],
maxIterations, roots.data());
for (int32_t i = 0; i < numRoots; ++i)
{
Real sigmaSqr = roots[i];
if (sigmaSqr > mR0)
{
Real sigma = std::sqrt(sigmaSqr);
Real gamma = -freduced0(sigmaSqr) / (sigma * freduced1(sigmaSqr));
UpdateParameters(data, sigma, sigmaSqr, gamma,
minSigma, minGamma, minK, minRSqr, minError);
}
}
}
else
{
Polynomial1<Real> hreduced(4);
for (int32_t i = 0; i <= 4; ++i)
{
hreduced[i] = f0[2 * i];
}
std::array<Real, 4> roots;
int32_t numRoots = RootsPolynomial<Real>::Find(4, &hreduced[0],
maxIterations, roots.data());
for (int32_t i = 0; i < numRoots; ++i)
{
Real sigmaSqr = roots[i];
if (sigmaSqr > mR0)
{
Real sigma = std::sqrt(sigmaSqr);
Real gamma = std::sqrt(sigma);
UpdateParameters(data, sigma, sigmaSqr, gamma,
minSigma, minGamma, minK, minRSqr, minError);
gamma = -gamma;
UpdateParameters(data, sigma, sigmaSqr, gamma,
minSigma, minGamma, minK, minRSqr, minError);
}
}
}
// Compute the minimizers V, C and radius. The center minK*U must have
// A added to it because the inputs P had A subtracted from them. The
// addition no longer guarantees that Dot(V,C) = 0, so the V-component
// of A+minK*U is projected out so that the returned center has only a
// U-component.
V = Vector2<Real>{ minGamma, minSigma };
C = A + minK * Vector2<Real>{ -minSigma, minGamma };
C -= Dot(C, V) * V;
radius = std::sqrt(minRSqr);
}
private:
struct ZValues
{
ZValues(std::vector<Vector2<Real>> const& P)
:
Z20(0), Z11(0), Z02(0),
Z30(0), Z21(0), Z12(0), Z03(0),
Z40(0), Z31(0), Z22(0), Z13(0), Z04(0)
{
Real const invN = static_cast<Real>(1) / static_cast<Real>(P.size());
for (auto const& sample : P)
{
Real xx = sample[0] * sample[0];
Real xy = sample[0] * sample[1];
Real yy = sample[1] * sample[1];
Real xxx = xx * sample[0];
Real xxy = xy * sample[0];
Real xyy = xy * sample[1];
Real yyy = yy * sample[1];
Real xxxx = xxx * sample[0];
Real xxxy = xxx * sample[1];
Real xxyy = xx * yy;
Real xyyy = yyy * sample[0];
Real yyyy = yyy * sample[1];
Z20 += xx;
Z11 += xy;
Z02 += yy;
Z30 += xxx;
Z21 += xxy;
Z12 += xyy;
Z03 += yyy;
Z40 += xxxx;
Z31 += xxxy;
Z22 += xxyy;
Z13 += xyyy;
Z04 += yyyy;
}
Z20 *= invN;
Z11 *= invN;
Z02 *= invN;
Z30 *= invN;
Z21 *= invN;
Z12 *= invN;
Z03 *= invN;
Z40 *= invN;
Z31 *= invN;
Z22 *= invN;
Z13 *= invN;
Z04 *= invN;
}
Real Z20, Z11, Z02;
Real Z30, Z21, Z12, Z03;
Real Z40, Z31, Z22, Z13, Z04;
};
// Given two polynomials A0+gamma*B0 and A1+gamma*B1, the product is
// [A0*A1+(1-sigma^2)*B0*B1] + gamma*[A0*B1+B0*A1] = A2+gamma*B2.
void ComputeProduct(
Polynomial1<Real> const& A0, Polynomial1<Real> const& B0,
Polynomial1<Real> const& A1, Polynomial1<Real> const& B1,
Polynomial1<Real>& A2, Polynomial1<Real>& B2)
{
Polynomial1<Real> gammaSqr{ mR1, mR0, -mR1 };
A2 = A0 * A1 + gammaSqr * B0 * B1;
B2 = A0 * B1 + B0 * A1;
}
void ComputeF(ZValues const& data, Polynomial1<Real>& f0, Polynomial1<Real>& f1)
{
// Compute the apq and bpq terms.
Polynomial1<Real> a11(2);
a11[0] = data.Z11;
a11[2] = -mR2 * data.Z11;
Polynomial1<Real> b11(1);
b11[1] = data.Z02 - data.Z20;
Polynomial1<Real> a20(2);
a20[0] = data.Z02;
a20[2] = data.Z20 - data.Z02;
Polynomial1<Real> b20(1);
b20[1] = -mR2 * data.Z11;
Polynomial1<Real> a30(3);
a30[1] = -mR3;
a30[3] = mR3 * data.Z12 - data.Z30;
Polynomial1<Real> b30(2);
b30[0] = data.Z03;
b30[2] = mR3 * data.Z21 - data.Z03;
Polynomial1<Real> a21(3);
a21[1] = data.Z03 - mR2 * data.Z21;
a21[3] = mR3 * data.Z21 - data.Z03;
Polynomial1<Real> b21(2);
b21[0] = data.Z12;
b21[2] = data.Z30 - mR3 * data.Z12;
Polynomial1<Real> a40(4);
a40[0] = data.Z04;
a40[2] = mR6 * data.Z22 - mR2 * data.Z04;
a40[4] = data.Z40 - mR6 * data.Z22 + data.Z04;
Polynomial1<Real> b40(3);
b40[1] = -mR4 * data.Z13;
b40[3] = mR4 * (data.Z13 - data.Z31);
Polynomial1<Real> a31(4);
a31[0] = data.Z13;
a31[2] = mR3 * data.Z31 - mR5 * data.Z13;
a31[4] = mR4 * (data.Z13 - data.Z31);
Polynomial1<Real> b31(3);
b31[1] = data.Z04 - mR3 * data.Z22;
b31[3] = mR6 * data.Z22 - data.Z40 - data.Z04;
// Compute S20^2 = c0 + gamma*d0.
Polynomial1<Real> c0, d0;
ComputeProduct(a20, b20, a20, b20, c0, d0);
// Compute S31 * S20^2 = c1 + gamma*d1.
Polynomial1<Real> c1, d1;
ComputeProduct(a31, b31, c0, d0, c1, d1);
// Compute S21 * S20 = c2 + gamma*d2.
Polynomial1<Real> c2, d2;
ComputeProduct(a21, b21, a20, b20, c2, d2);
// Compute S30 * (S21 * S20) = c3 + gamma*d3.
Polynomial1<Real> c3, d3;
ComputeProduct(a30, b30, c2, d2, c3, d3);
// Compute S30 * S11 = c4 + gamma*d4.
Polynomial1<Real> c4, d4;
ComputeProduct(a30, b30, a11, b11, c4, d4);
// Compute S30 * (S30 * S11) = c5 + gamma*d5.
Polynomial1<Real> c5, d5;
ComputeProduct(a30, b30, c4, d4, c5, d5);
// Compute S20^2 * S11 = c6 + gamma*d6.
Polynomial1<Real> c6, d6;
ComputeProduct(c0, d0, a11, b11, c6, d6);
// Compute S20 * (S20^2 * S11) = c7 + gamma*d7.
Polynomial1<Real> c7, d7;
ComputeProduct(a20, b20, c6, d6, c7, d7);
// Compute F = 2*S31*S20^2 - 3*S30*S21*S20 + S30^2*S11
// - 2*S20^3*S11 = f0 + gamma*f1, where f0 is even of degree 8
// and f1 is odd of degree 7.
f0 = mR2 * (c1 - c7) - mR3 * c3 + c5;
f1 = mR2 * (d1 - d7) - mR3 * d3 + d5;
}
void UpdateParameters(ZValues const& data, Real const& sigma, Real const& sigmaSqr,
Real const& gamma, Real& minSigma, Real& minGamma, Real& minK,
Real& minRSqr, Real& minError)
{
// Rather than evaluate apq(sigma) and bpq(sigma), the
// polynomials are evaluated at sigmaSqr to avoid the
// rounding errors that are inherent by computing
// s = sqrt(ssqr); ssqr = s * s;
Real A20 = data.Z02 + (data.Z20 - data.Z02) * sigmaSqr;
Real B20 = -mR2 * data.Z11 * sigma;
Real S20 = A20 + gamma * B20;
Real A30 = -sigma * (mR3 * data.Z12 + (data.Z30 - mR3 * data.Z12) * sigmaSqr);
Real B30 = data.Z03 + (mR3 * data.Z21 - data.Z03) * sigmaSqr;
Real S30 = A30 + gamma * B30;
Real A40 = data.Z04 + ((mR6 * data.Z22 - mR2 * data.Z04)
+ (data.Z40 - mR6 * data.Z22 + data.Z04) * sigmaSqr) * sigmaSqr;
Real B40 = -mR4 * sigma * (data.Z13 + (data.Z31 - data.Z13) * sigmaSqr);
Real S40 = A40 + gamma * B40;
Real k = S30 / (mR2 * S20);
Real ksqr = k * k;
Real rsqr = ksqr + S20;
Real error = S40 - mR4 * k * S30 + (mR4 * ksqr - S20) * S20;
if (error < minError)
{
minSigma = sigma;
minGamma = gamma;
minK = k;
minRSqr = rsqr;
minError = error;
}
}
Real const mR0, mR1, mR2, mR3, mR4, mR5, mR6;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/PolygonTree.h | .h | 12,540 | 288 | // 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 <cstdint>
#include <limits>
#include <memory>
#include <stack>
#include <vector>
namespace gte
{
// These classes are used by class TriangulateEC (triangulation based on
// ear clipping) and class TriangulateCDT (triangulation based on
// Constrained Delaunay triangulation). The PolygonTree class used to be
// the nested class Tree in those classes, but it has been factored out to
// allow applications to use either triangulator without having to
// duplicate the trees.
//
// NOTE: The polygon member does not duplicate endpoints. For example,
// if P[] are the point locations and the polygon is a triangle with
// counterclockwise ordering, <P[i0],P[i1],P[i2]>, then
// polygon = {i0,i1,i2}. The implication is that there are 3 directed
// edges: {P[i0],P[i1]}, {P[i1],P[i2]} and {P[i2],P[i0].
//
// Eventually, the PolygonTreeEx struct will replace PolygonTree because
// 1. The algorithms can be rewritten not to depend on the alternating
// winding order between parent and child.
// 2. The triangulation is explicitly stored in the tree nodes and can
// support point-in-polygon tree queries (In the tree? Which polygon
// contains the point?).
// 3. The polygon trees can be built not to use std::shared_ptr, making
// the trees more compact by using std::vector<PolygonTree> vpt. The
// ordering of the tree nodes must be that implied by a breadth-first
// search.
// A tree of nested polygons. The root node corresponds to an outer
// polygon. The children of the root correspond to inner polygons,
// which polygons strictly contained in the outer polygon. Each inner
// polygon may itself contain an outer polygon which in turn can
// contain inner polygons, thus leading to a hierarchy of polygons.
// The outer polygons have vertices listed in counterclockwise order.
// The inner polygons have vertices listed in clockwise order.
class PolygonTree
{
public:
PolygonTree()
:
polygon{},
child{}
{
}
std::vector<int32_t> polygon;
std::vector<std::shared_ptr<PolygonTree>> child;
};
// A tree of nested polygons with extra information about the polygon.
// The tree can be stored as: std::vector<PolygonTree> tree(numNodes).
// The point locations are specified separately to the triangulators.
//
// The chirality (winding ordering of the polygon) is set to +1 for a
// counterclockwise-ordered polygon or -1 for a clockwise-oriented
// polygon.
//
// The triangulation is computed by the triangulators and explicitly
// stored per tree node.
//
// The element node[0] is the root of the tree with node[0].parent = -1.
// If node[0] has C children, then node[0].minChild = 1 and
// node[0].supChild = 1 + C. Generally, node[i] is a node with parent
// node[p], where p = node[i].parent, and children node[c], where
// node[i].minChild <= c < node[i].supChild. If node[i].minChild >=
// node[i].supChild, the node has no children.
class PolygonTreeEx
{
public:
class Node
{
public:
Node()
:
polygon{},
chirality(0),
triangulation{},
self(0),
parent(0),
minChild(0),
supChild(0)
{
}
std::vector<int32_t> polygon;
int64_t chirality;
std::vector<std::array<int32_t, 3>> triangulation;
size_t self, parent, minChild, supChild;
};
// The nodes of the polygon tree, organized based on a breadth-first
// traversal of the tree.
std::vector<Node> nodes;
// These members support TriangulateCDT. The *NodeIndices members
// store the indices into 'nodes[]' for the triangles in the
// *Triangles members. For example, the triangle interiorTriangles[t]
// comes from nodes[interiorNodes[t]].
// The triangles in the polygon tree that cover each region bounded
// by an outer polygon and its contained inner polygons. This set
// is the equivalent of the output of TriangulateEC that uses ear
// clipping.
std::vector<std::array<int32_t, 3>> interiorTriangles;
std::vector<size_t> interiorNodeIndices;
// The triangles in the polygon tree that cover each region bounded
// by an inner polygon and its contained outer polygons.
std::vector<std::array<int32_t, 3>> exteriorTriangles;
std::vector<size_t> exteriorNodeIndices;
// The triangles inside the polygon tree.
// insideTriangles = interiorTriangle + exteriorTriangles
std::vector<std::array<int32_t, 3>> insideTriangles;
std::vector<size_t> insideNodeIndices;
// The triangles inside the convex hull of the Delaunay triangles but
// outside the polygon tree. These triangles are not associated with
// any 'nodes[]' element.
std::vector<std::array<int32_t, 3>> outsideTriangles;
// All the triangles:
// allTriangles = insideTriangles + outsideTriangles.
std::vector<std::array<int32_t, 3>> allTriangles;
public:
// Point-containment queries.
// Search the polygon tree for the triangle that contains 'test'. If
// there is such a triangle, the returned pair (nIndex,tIndex) states
// that the triangle is nodes[nIndex].triangulation[tIndex]. If there
// is no such triangle, the returned pair is (smax,smax) where
// smax = std::numeric_limits<size_t>::max(). The function is
// naturally recursive, but simulated recursion is used to avoid a
// large program stack by instead using the heap. A typical call is
// PolygonTreeEx tree = <some tree>;
// std::vector<Vector2<T>> points = <some vector of points>;
// Vector2<T> test = <some point>;
// std::pair<size_t, size_t> result;
// result = tree.GetContainingTriangle(test, points);
template <typename T>
std::pair<size_t, size_t> GetContainingTriangle(Vector2<T> const& test,
Vector2<T> const* points)
{
size_t constexpr smax = std::numeric_limits<size_t>::max();
std::pair<size_t, size_t> result = std::make_pair(smax, smax);
std::stack<size_t> stack;
stack.push(0);
while (stack.size() > 0 && result.first == smax)
{
auto nIndex = stack.top();
stack.pop();
auto const& node = nodes[nIndex];
for (size_t c = node.minChild; c < node.supChild; ++c)
{
stack.push(c);
}
for (size_t tIndex = 0; tIndex < node.triangulation.size(); ++tIndex)
{
if (PointInTriangle(test, node.chirality, node.triangulation[tIndex], points))
{
result = std::make_pair(nIndex, tIndex);
break;
}
}
}
return result;
}
// Search the triangles for the triangle that contains 'test'. If
// there is such a triangle, the returned pair (nIndex,tIndex) states
// that the triangle is nodes[nIndex].triangulation[tIndex]. If there
// is no such triangle, the returned pair is (smax,smax) where
// smax = std::numeric_limits<size_t>::max(). The function uses a
// linear search of the input triangles. Some typical calls are
// PolygonTreeEx tree = <some tree>;
// std::vector<Vector2<T>> points = <some vector of points>;
// Vector2<T> test = <some point>;
// std::pair<size_t, size_t> result;
// result = tree.GetContainingTriangle(test, tree.insideTriangles,
// tree.insideNodeIndices, points);
// result = tree.GetContainingTriangle(test, tree.interiorTriangles,
// tree.interiorNodeIndices, points);
// result = tree.GetContainingTriangle(test, tree.exteriorTriangles,
// tree.exteriorIndices, points);
template <typename T>
std::pair<size_t, size_t> GetContainingTriangle(Vector2<T> const& test,
std::vector<std::array<int32_t, 3>> const& triangles,
std::vector<size_t> const& nodeIndices,
Vector2<T> const* points)
{
LogAssert(triangles.size() == nodeIndices.size(), "Invalid argument.");
size_t constexpr smax = std::numeric_limits<size_t>::max();
std::pair<size_t, size_t> result = std::make_pair(smax, smax);
for (size_t tIndex = 0; tIndex < triangles.size(); ++tIndex)
{
size_t const nIndex = nodeIndices[tIndex];
auto const& node = nodes[nIndex];
if (PointInTriangle(test, node.chirality, triangles[tIndex], points))
{
result = std::make_pair(nIndex, tIndex);
break;
}
}
return result;
}
// Search the triangles for the triangle that contains 'test'. If
// there is such a triangle, the returned t-value is in the range
// 0 <= t < triangles.size(); otherwise, smax is returned where
// smax = std::numeric_limits<size_t>::max(). The function uses a
// linear search of the input triangles. No information is available
// about the 'nodes[]' element corresponding to the containing
// triangle of the test point. Typical calls are
// PolygonTreeEx tree = <some tree>;
// std::vector<Vector2<T>> points = <some vector of points>;
// Vector2<T> test = <some point>;
// size_t resultInt, resultExt, resultOut;
// resultInt = PolygonTreeEx::GetContainingTriangle(test,
// tree.interiorTriangles, +1, points);
// resultExt = PolygonTreeEx::GetContainingTriangle(test,
// tree.exteriorTriangles, -1, points);
// resultOut = PolygonTreeEx::GetContainingTriangle(test,
// tree.outsideTriangles, +1, points);
template <typename T>
size_t GetContainingTriangle(Vector2<T> const& test,
std::vector<std::array<int32_t, 3>> const& triangles, int64_t chirality,
Vector2<T> const* points)
{
size_t result = std::numeric_limits<size_t>::max();
for (size_t tIndex = 0; tIndex < triangles.size(); ++tIndex)
{
if (PointInTriangle(test, chirality, triangles[tIndex], points))
{
result = tIndex;
break;
}
}
return result;
}
private:
// Determine whether 'test' is inside the triangle whose vertices
// are points[triangle[0]], points[triangle[1]], points[triangle[2].
// If the points are counterclockwise ordered, set 'chirality' to +1.
// If the points are clockwise ordered, set 'chirality' to -1.
template <typename T>
static bool PointInTriangle(Vector2<T> const& test, int64_t chirality,
std::array<int32_t, 3> const& triangle, Vector2<T> const* points)
{
T const zero = static_cast<T>(0);
T const sign = static_cast<T>(chirality);
for (int32_t i1 = 0, i0 = 2; i1 < 3; i0 = i1++)
{
T nx = points[triangle[i1]][1] - points[triangle[i0]][1];
T ny = points[triangle[i0]][0] - points[triangle[i1]][0];
T dx = test[0] - points[triangle[i0]][0];
T dy = test[1] - points[triangle[i0]][1];
T sdot = sign * (nx * dx + ny * dy);
if (sdot > zero)
{
return false;
}
}
return true;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Ray.h | .h | 2,213 | 90 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector.h>
// The ray is represented as P+t*D, where P is the ray origin, D is a
// unit-length direction vector, and t >= 0. The user must ensure that D is
// unit length.
namespace gte
{
template <int32_t N, typename Real>
class Ray
{
public:
// Construction and destruction. The default constructor sets the
// origin to (0,...,0) and the ray direction to (1,0,...,0).
Ray()
{
origin.MakeZero();
direction.MakeUnit(0);
}
Ray(Vector<N, Real> const& inOrigin, Vector<N, Real> const& inDirection)
:
origin(inOrigin),
direction(inDirection)
{
}
// Public member access. The direction must be unit length.
Vector<N, Real> origin, direction;
public:
// Comparisons to support sorted containers.
bool operator==(Ray const& ray) const
{
return origin == ray.origin && direction == ray.direction;
}
bool operator!=(Ray const& ray) const
{
return !operator==(ray);
}
bool operator< (Ray const& ray) const
{
if (origin < ray.origin)
{
return true;
}
if (origin > ray.origin)
{
return false;
}
return direction < ray.direction;
}
bool operator<=(Ray const& ray) const
{
return !ray.operator<(*this);
}
bool operator> (Ray const& ray) const
{
return ray.operator<(*this);
}
bool operator>=(Ray const& ray) const
{
return !operator<(ray);
}
};
// Template aliases for convenience.
template <typename Real>
using Ray2 = Ray<2, Real>;
template <typename Real>
using Ray3 = Ray<3, Real>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/FastGaussianBlur2.h | .h | 6,212 | 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>
// 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 elements and be stored in lexicographical
// order. The indexing is i = x + xBound * y.
template <typename T>
class FastGaussianBlur2
{
public:
void Execute(int32_t xBound, int32_t yBound, T const* input, T* output,
double scale, double logBase)
{
mXBound = xBound;
mYBound = yBound;
mInput = input;
mOutput = output;
int32_t xBoundM1 = xBound - 1, yBoundM1 = yBound - 1;
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 = x + scale;
double rxms = 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);
double xsum = -2.0 * center, ysum = xsum;
// x portion of second central difference
if (xp1 >= xBoundM1) // use boundary value
{
xsum += Input(xBoundM1, y);
}
else // linearly interpolate
{
double imgXp1 = Input(xp1, y);
double imgXp2 = Input(xp1 + 1, y);
double delta = rxps - static_cast<double>(xp1);
xsum += imgXp1 + delta * (imgXp2 - imgXp1);
}
if (xm1 <= 0) // use boundary value
{
xsum += Input(0, y);
}
else // linearly interpolate
{
double imgXm1 = Input(xm1, y);
double imgXm2 = Input(xm1 - 1, y);
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);
}
else // linearly interpolate
{
double imgYp1 = Input(x, yp1);
double imgYp2 = Input(x, yp1 + 1);
double delta = ryps - static_cast<double>(yp1);
ysum += imgYp1 + delta * (imgYp2 - imgYp1);
}
if (ym1 <= 0) // use boundary value
{
ysum += Input(x, 0);
}
else // linearly interpolate
{
double imgYm1 = Input(x, ym1);
double imgYm2 = Input(x, ym1 - 1);
double delta = ryms - static_cast<double>(ym1);
ysum += imgYm1 + delta * (imgYm1 - imgYm2);
}
Output(x, y) = static_cast<T>(center + logBase * (xsum + ysum));
}
}
mXBound = 0;
mYBound = 0;
mInput = nullptr;
mOutput = nullptr;
}
private:
inline double Input(int32_t x, int32_t y) const
{
return static_cast<double>(mInput[x + mXBound * y]);
}
inline T& Output(int32_t x, int32_t y)
{
return mOutput[x + mXBound * y];
}
int32_t mXBound, mYBound;
T const* mInput;
T* mOutput;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrRay2Triangle2.h | .h | 3,878 | 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/IntrIntervals.h>
#include <Mathematics/IntrLine2Triangle2.h>
#include <Mathematics/Ray.h>
// The queries consider the triangle to be a solid.
namespace gte
{
template <typename Real>
class TIQuery<Real, Ray2<Real>, Triangle2<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
// The ray is P + t * D, where P is a point on the line and D is a
// direction vector that does not have to be unit length. This is
// useful when using a 2-point representation P0 + t * (P1 - P0). The
// t-parameter is constrained by t >= 0.
Result operator()(Ray2<Real> const& ray, Triangle2<Real> const& triangle)
{
Result result{};
FIQuery<Real, Ray2<Real>, Triangle2<Real>> rtQuery;
result.intersect = rtQuery(ray, triangle).intersect;
return result;
}
};
template <typename Real>
class FIQuery<Real, Ray2<Real>, Triangle2<Real>>
:
public FIQuery<Real, Line2<Real>, Triangle2<Real>>
{
public:
struct Result
:
public FIQuery<Real, Line2<Real>, Triangle2<Real>>::Result
{
Result()
:
FIQuery<Real, Line2<Real>, Triangle2<Real>>::Result{}
{
}
// No additional information to compute.
};
// The line is P + t * D, where P is a point on the line and D is a
// direction vector that does not have to be unit length. This is
// useful when using a 2-point representation P0 + t * (P1 - P0).
Result operator()(Ray2<Real> const& ray, Triangle2<Real> const& triangle)
{
Result result{};
DoQuery(ray.origin, ray.direction, triangle, result);
if (result.intersect)
{
for (size_t i = 0; i < 2; ++i)
{
result.point[i] = ray.origin + result.parameter[i] * ray.direction;
}
}
return result;
}
protected:
// The caller must ensure that on entry, 'result' is default
// constructed as if there is no intersection. If an intersection is
// found, the 'result' values will be modified accordingly.
void DoQuery(Vector2<Real> const& origin, Vector2<Real> const& direction,
Triangle2<Real> const& triangle, Result& result)
{
FIQuery<Real, Line2<Real>, Triangle2<Real>>::DoQuery(
origin, direction, triangle, result);
if (result.intersect)
{
// The line containing the ray intersects the triangle; the
// t-interval is [t0,t1]. The ray intersects the triangle as
// long as [t0,t1] overlaps the ray t-interval [0,+infinity).
FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>> iiQuery{};
auto iiResult = iiQuery(result.parameter, static_cast<Real>(0), true);
if (iiResult.intersect)
{
result.numIntersections = iiResult.numIntersections;
result.parameter = iiResult.overlap;
}
else
{
// The line containing the ray does not intersect the
// triangle.
result = Result{};
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Delaunay2Mesh.h | .h | 8,402 | 267 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.02.01
#pragma once
#include <Mathematics/Delaunay2.h>
namespace gte
{
template <typename T, typename...>
class Delaunay2Mesh {};
}
namespace gte
{
// The InputType is 'float' or 'double'. The ComputeType can be a
// floating-point type or BSNumber<*> type, because it does not require
// divisions. The RationalType requires division, so you can use
// BSRational<*>.
template <typename InputType, typename ComputeType, typename RationalType>
class // [[deprecated("Use Delaunay2Mesh<InputType> instead.")]]
Delaunay2Mesh<InputType, ComputeType, RationalType>
{
public:
// Construction.
Delaunay2Mesh(Delaunay2<InputType, ComputeType> const& delaunay)
:
mDelaunay(&delaunay)
{
}
// Mesh information.
inline int32_t GetNumVertices() const
{
return mDelaunay->GetNumVertices();
}
inline int32_t GetNumTriangles() const
{
return mDelaunay->GetNumTriangles();
}
inline Vector2<InputType> const* GetVertices() const
{
return mDelaunay->GetVertices();
}
inline int32_t const* GetIndices() const
{
return &mDelaunay->GetIndices()[0];
}
inline int32_t const* GetAdjacencies() const
{
return &mDelaunay->GetAdjacencies()[0];
}
inline int32_t GetInvalidIndex() const
{
return mDelaunay->negOne;
}
// Containment queries.
int32_t GetContainingTriangle(Vector2<InputType> const& P) const
{
// VS 2019 16.8.1 generates LNT1006 "Local variable is not
// initialized." Incorrect, because the default constructor
// initializes all the members.
typename Delaunay2<InputType, ComputeType>::SearchInfo info;
return mDelaunay->GetContainingTriangle(P, info);
}
bool GetVertices(int32_t t, std::array<Vector2<InputType>, 3>& vertices) const
{
if (mDelaunay->GetDimension() == 2)
{
std::array<int32_t, 3> indices = { 0, 0, 0 };
if (mDelaunay->GetIndices(t, indices))
{
PrimalQuery2<ComputeType> const& query = mDelaunay->GetQuery();
Vector2<ComputeType> const* ctVertices = query.GetVertices();
for (int32_t i = 0; i < 3; ++i)
{
Vector2<ComputeType> const& V = ctVertices[indices[i]];
for (int32_t j = 0; j < 2; ++j)
{
vertices[i][j] = (InputType)V[j];
}
}
return true;
}
}
return false;
}
bool GetIndices(int32_t t, std::array<int32_t, 3>& indices) const
{
return mDelaunay->GetIndices(t, indices);
}
bool GetAdjacencies(int32_t t, std::array<int32_t, 3>& adjacencies) const
{
return mDelaunay->GetAdjacencies(t, adjacencies);
}
bool GetBarycentrics(int32_t t, Vector2<InputType> const& P, std::array<InputType, 3>& bary) const
{
std::array<int32_t, 3> indices = { 0, 0, 0 };
if (mDelaunay->GetIndices(t, indices))
{
PrimalQuery2<ComputeType> const& query = mDelaunay->GetQuery();
Vector2<ComputeType> const* vertices = query.GetVertices();
Vector2<RationalType> rtP{ P[0], P[1] };
std::array<Vector2<RationalType>, 3> rtV;
for (int32_t i = 0; i < 3; ++i)
{
Vector2<ComputeType> const& V = vertices[indices[i]];
for (int32_t j = 0; j < 2; ++j)
{
rtV[i][j] = (RationalType)V[j];
}
};
std::array<RationalType, 3> rtBary{};
if (ComputeBarycentrics(rtP, rtV[0], rtV[1], rtV[2], rtBary))
{
for (int32_t i = 0; i < 3; ++i)
{
bary[i] = (InputType)rtBary[i];
}
return true;
}
}
return false;
}
private:
Delaunay2<InputType, ComputeType> const* mDelaunay;
};
}
namespace gte
{
// The input type T is 'float' or 'double'.
template <typename T>
class Delaunay2Mesh<T>
{
public:
// Construction.
Delaunay2Mesh(Delaunay2<T> const& delaunay)
:
mDelaunay(&delaunay)
{
}
// Mesh information.
inline size_t GetNumVertices() const
{
return mDelaunay->GetNumVertices();
}
inline size_t GetNumTriangles() const
{
return mDelaunay->GetNumTriangles();
}
inline std::vector<Vector2<T>> const* GetVertices() const
{
return mDelaunay->GetVertices();
}
inline std::vector<int32_t> const& GetIndices() const
{
return mDelaunay->GetIndices();
}
inline std::vector<int32_t> const& GetAdjacencies() const
{
return mDelaunay->GetAdjacencies();
}
// Containment queries.
size_t GetContainingTriangle(Vector2<T> const& P) const
{
// VS 2019 16.8.1 generates LNT1006 "Local variable is not
// initialized." Incorrect, because the default constructor
// initializes all the members.
typename Delaunay2<T>::SearchInfo info;
return mDelaunay->GetContainingTriangle(P, info);
}
inline size_t GetInvalidIndex() const
{
return mDelaunay->negOne;
}
bool GetVertices(size_t t, std::array<Vector2<T>, 3>& vertices) const
{
if (mDelaunay->GetDimension() == 2)
{
std::array<int32_t, 3> indices = { 0, 0, 0 };
if (mDelaunay->GetIndices(t, indices))
{
auto const& delaunayVertices = *mDelaunay->GetVertices();
for (size_t i = 0; i < 3; ++i)
{
vertices[i] = delaunayVertices[indices[i]];
}
return true;
}
}
return false;
}
bool GetIndices(size_t t, std::array<int32_t, 3>& indices) const
{
return mDelaunay->GetIndices(t, indices);
}
bool GetAdjacencies(size_t t, std::array<int32_t, 3>& adjacencies) const
{
return mDelaunay->GetAdjacencies(t, adjacencies);
}
bool GetBarycentrics(size_t t, Vector2<T> const& P, std::array<T, 3>& bary) const
{
std::array<int32_t, 3> indices = { 0, 0, 0 };
if (mDelaunay->GetIndices(t, indices))
{
auto const& delaunayVertices = *mDelaunay->GetVertices();
std::array<Vector2<Rational>, 3> rtV;
for (size_t i = 0; i < 3; ++i)
{
auto const& V = delaunayVertices[indices[i]];
for (size_t j = 0; j < 2; ++j)
{
rtV[i][j] = static_cast<Rational>(V[j]);
}
};
Vector2<Rational> rtP{ P[0], P[1] };
std::array<Rational, 3> rtBary{};
if (ComputeBarycentrics(rtP, rtV[0], rtV[1], rtV[2], rtBary))
{
for (size_t i = 0; i < 3; ++i)
{
bary[i] = static_cast<T>(rtBary[i]);
}
return true;
}
}
return false;
}
private:
using Rational = BSRational<UIntegerAP32>;
Delaunay2<T> const* mDelaunay;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/LinearSystem.h | .h | 12,064 | 343 | // 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/Matrix2x2.h>
#include <Mathematics/Matrix3x3.h>
#include <Mathematics/Matrix4x4.h>
#include <Mathematics/GaussianElimination.h>
#include <map>
// Solve linear systems of equations where the matrix A is NxN. The return
// value of a function is 'true' when A is invertible. In this case the
// solution X and the solution is valid. If the return value is 'false', A
// is not invertible and X and Y are invalid, so do not use them. When a
// matrix is passed as Real*, the storage order is assumed to be the one
// consistent with your choice of GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR.
//
// The linear solvers that use the conjugate gradient algorithm are based
// on the discussion in "Matrix Computations, 2nd edition" by G. H. Golub
// and Charles F. Van Loan, The Johns Hopkins Press, Baltimore MD, Fourth
// Printing 1993.
namespace gte
{
template <typename Real>
class LinearSystem
{
public:
// Solve 2x2, 3x3, and 4x4 systems by inverting the matrix directly.
// This avoids the overhead of Gaussian elimination in small
// dimensions.
static bool Solve(Matrix2x2<Real> const& A, Vector2<Real> const& B, Vector2<Real>& X)
{
bool invertible = false;
Matrix2x2<Real> invA = Inverse(A, &invertible);
if (invertible)
{
X = invA * B;
}
else
{
X = Vector2<Real>::Zero();
}
return invertible;
}
static bool Solve(Matrix3x3<Real> const& A, Vector3<Real> const& B, Vector3<Real>& X)
{
bool invertible = false;
Matrix3x3<Real> invA = Inverse(A, &invertible);
if (invertible)
{
X = invA * B;
}
else
{
X = Vector3<Real>::Zero();
}
return invertible;
}
static bool Solve(Matrix4x4<Real> const& A, Vector4<Real> const& B, Vector4<Real>& X)
{
bool invertible = false;
Matrix4x4<Real> invA = Inverse(A, &invertible);
if (invertible)
{
X = invA * B;
}
else
{
X = Vector4<Real>::Zero();
}
return invertible;
}
// Solve A*X = B, where B is Nx1 and the solution X is Nx1.
static bool Solve(int32_t N, Real const* A, Real const* B, Real* X)
{
Real determinant = static_cast<Real>(0);
return GaussianElimination<Real>()(N, A, nullptr, determinant, B, X,
nullptr, 0, nullptr);
}
// Solve A*X = B, where B is NxM and the solution X is NxM.
static bool Solve(int32_t N, int32_t M, Real const* A, Real const* B, Real* X)
{
Real determinant = static_cast<Real>(0);
return GaussianElimination<Real>()(N, A, nullptr, determinant, nullptr,
nullptr, B, M, X);
}
// Solve A*X = B, where A is tridiagonal. The function expects the
// subdiagonal, diagonal, and superdiagonal of A. The diagonal input
// must have N elements. The subdiagonal and superdiagonal inputs
// must have N-1 elements.
static bool SolveTridiagonal(int32_t N, Real const* subdiagonal,
Real const* diagonal, Real const* superdiagonal, Real const* B, Real* X)
{
if (diagonal[0] == (Real)0)
{
return false;
}
std::vector<Real> tmp(static_cast<size_t>(N) - 1);
Real expr = diagonal[0];
Real invExpr = ((Real)1) / expr;
X[0] = B[0] * invExpr;
int32_t i0, i1;
for (i0 = 0, i1 = 1; i1 < N; ++i0, ++i1)
{
tmp[i0] = superdiagonal[i0] * invExpr;
expr = diagonal[i1] - subdiagonal[i0] * tmp[i0];
if (expr == (Real)0)
{
return false;
}
invExpr = ((Real)1) / expr;
X[i1] = (B[i1] - subdiagonal[i0] * X[i0]) * invExpr;
}
for (i0 = N - 1, i1 = N - 2; i1 >= 0; --i0, --i1)
{
X[i1] -= tmp[i1] * X[i0];
}
return true;
}
// Solve A*X = B, where A is tridiagonal. The function expects the
// subdiagonal, diagonal, and superdiagonal of A. Moreover, the
// subdiagonal elements are a constant, the diagonal elements are a
// constant, and the superdiagonal elements are a constant.
static bool SolveConstantTridiagonal(int32_t N, Real subdiagonal,
Real diagonal, Real superdiagonal, Real const* B, Real* X)
{
if (diagonal == (Real)0)
{
return false;
}
std::vector<Real> tmp(static_cast<size_t>(N) - 1);
Real expr = diagonal;
Real invExpr = ((Real)1) / expr;
X[0] = B[0] * invExpr;
int32_t i0, i1;
for (i0 = 0, i1 = 1; i1 < N; ++i0, ++i1)
{
tmp[i0] = superdiagonal * invExpr;
expr = diagonal - subdiagonal * tmp[i0];
if (expr == (Real)0)
{
return false;
}
invExpr = ((Real)1) / expr;
X[i1] = (B[i1] - subdiagonal * X[i0]) * invExpr;
}
for (i0 = N - 1, i1 = N - 2; i1 >= 0; --i0, --i1)
{
X[i1] -= tmp[i1] * X[i0];
}
return true;
}
// Solve A*X = B using the conjugate gradient method, where A is
// symmetric. You must specify the maximum number of iterations and a
// tolerance for terminating the iterations. Reasonable choices for
// tolerance are 1e-06f for 'float' or 1e-08 for 'double'.
static uint32_t SolveSymmetricCG(int32_t N, Real const* A, Real const* B,
Real* X, uint32_t maxIterations, Real tolerance)
{
// The first iteration.
std::vector<Real> tmpR(N), tmpP(N), tmpW(N);
Real* R = &tmpR[0];
Real* P = &tmpP[0];
Real* W = &tmpW[0];
size_t numBytes = N * sizeof(Real);
std::memset(X, 0, numBytes);
std::memcpy(R, B, numBytes);
Real rho0 = Dot(N, R, R);
std::memcpy(P, R, numBytes);
Mul(N, A, P, W);
Real alpha = rho0 / Dot(N, P, W);
UpdateX(N, X, alpha, P);
UpdateR(N, R, alpha, W);
Real rho1 = Dot(N, R, R);
// The remaining iterations.
uint32_t iteration;
for (iteration = 1; iteration <= maxIterations; ++iteration)
{
Real root0 = std::sqrt(rho1);
Real norm = Dot(N, B, B);
Real root1 = std::sqrt(norm);
if (root0 <= tolerance * root1)
{
break;
}
Real beta = rho1 / rho0;
UpdateP(N, P, beta, R);
Mul(N, A, P, W);
alpha = rho1 / Dot(N, P, W);
UpdateX(N, X, alpha, P);
UpdateR(N, R, alpha, W);
rho0 = rho1;
rho1 = Dot(N, R, R);
}
return iteration;
}
// Solve A*X = B using the conjugate gradient method, where A is
// sparse and symmetric. The nonzero entries of the symmetrix matrix
// A are stored in a map whose keys are pairs (i,j) and whose values
// are real numbers. The pair (i,j) is the location of the value in
// the array. Only one of (i,j) and (j,i) should be stored since A is
// symmetric. The column vector B is stored as an array of contiguous
// values. You must specify the maximum number of iterations and a
// tolerance for terminating the iterations. Reasonable choices for
// tolerance are 1e-06f for 'float' or 1e-08 for 'double'.
typedef std::map<std::array<int32_t, 2>, Real> SparseMatrix;
static uint32_t SolveSymmetricCG(int32_t N, SparseMatrix const& A,
Real const* B, Real* X, uint32_t maxIterations, Real tolerance)
{
// The first iteration.
std::vector<Real> tmpR(N), tmpP(N), tmpW(N);
Real* R = &tmpR[0];
Real* P = &tmpP[0];
Real* W = &tmpW[0];
size_t numBytes = N * sizeof(Real);
std::memset(X, 0, numBytes);
std::memcpy(R, B, numBytes);
Real rho0 = Dot(N, R, R);
std::memcpy(P, R, numBytes);
Mul(N, A, P, W);
Real alpha = rho0 / Dot(N, P, W);
UpdateX(N, X, alpha, P);
UpdateR(N, R, alpha, W);
Real rho1 = Dot(N, R, R);
// The remaining iterations.
uint32_t iteration;
for (iteration = 1; iteration <= maxIterations; ++iteration)
{
Real root0 = std::sqrt(rho1);
Real norm = Dot(N, B, B);
Real root1 = std::sqrt(norm);
if (root0 <= tolerance * root1)
{
break;
}
Real beta = rho1 / rho0;
UpdateP(N, P, beta, R);
Mul(N, A, P, W);
alpha = rho1 / Dot(N, P, W);
UpdateX(N, X, alpha, P);
UpdateR(N, R, alpha, W);
rho0 = rho1;
rho1 = Dot(N, R, R);
}
return iteration;
}
private:
// Support for the conjugate gradient method.
static Real Dot(int32_t N, Real const* U, Real const* V)
{
Real dot = (Real)0;
for (int32_t i = 0; i < N; ++i)
{
dot += U[i] * V[i];
}
return dot;
}
static void Mul(int32_t N, Real const* A, Real const* X, Real* P)
{
#if defined(GTE_USE_ROW_MAJOR)
LexicoArray2<true, Real> matA(N, N, const_cast<Real*>(A));
#else
LexicoArray2<false, Real> matA(N, N, const_cast<Real*>(A));
#endif
std::memset(P, 0, N * sizeof(Real));
for (int32_t row = 0; row < N; ++row)
{
for (int32_t col = 0; col < N; ++col)
{
P[row] += matA(row, col) * X[col];
}
}
}
static void Mul(int32_t N, SparseMatrix const& A, Real const* X, Real* P)
{
std::memset(P, 0, N * sizeof(Real));
for (auto const& element : A)
{
int32_t i = element.first[0];
int32_t j = element.first[1];
Real value = element.second;
P[i] += value * X[j];
if (i != j)
{
P[j] += value * X[i];
}
}
}
static void UpdateX(int32_t N, Real* X, Real alpha, Real const* P)
{
for (int32_t i = 0; i < N; ++i)
{
X[i] += alpha * P[i];
}
}
static void UpdateR(int32_t N, Real* R, Real alpha, Real const* W)
{
for (int32_t i = 0; i < N; ++i)
{
R[i] -= alpha * W[i];
}
}
static void UpdateP(int32_t N, Real* P, Real beta, Real const* R)
{
for (int32_t i = 0; i < N; ++i)
{
P[i] = R[i] + beta * P[i];
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrLine2OrientedBox2.h | .h | 3,245 | 106 | // 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/IntrLine2AlignedBox2.h>
#include <Mathematics/OrientedBox.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 Real>
class TIQuery<Real, Line2<Real>, OrientedBox2<Real>>
:
public TIQuery<Real, Line2<Real>, AlignedBox2<Real>>
{
public:
struct Result
:
public TIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result
{
Result()
:
TIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result{}
{
}
// No additional relevant information to compute.
};
Result operator()(Line2<Real> const& line, OrientedBox2<Real> const& box)
{
// Transform the line to the oriented-box coordinate system.
Vector2<Real> diff = line.origin - box.center;
Vector2<Real> lineOrigin
{
Dot(diff, box.axis[0]),
Dot(diff, box.axis[1])
};
Vector2<Real> lineDirection
{
Dot(line.direction, box.axis[0]),
Dot(line.direction, box.axis[1])
};
Result result{};
this->DoQuery(lineOrigin, lineDirection, box.extent, result);
return result;
}
};
template <typename Real>
class FIQuery<Real, Line2<Real>, OrientedBox2<Real>>
:
public FIQuery<Real, Line2<Real>, AlignedBox2<Real>>
{
public:
struct Result
:
public FIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result
{
Result()
:
FIQuery<Real, Line2<Real>, AlignedBox2<Real>>::Result{}
{
}
// No additional relevant information to compute.
};
Result operator()(Line2<Real> const& line, OrientedBox2<Real> const& box)
{
// Transform the line to the oriented-box coordinate system.
Vector2<Real> diff = line.origin - box.center;
Vector2<Real> lineOrigin
{
Dot(diff, box.axis[0]),
Dot(diff, box.axis[1])
};
Vector2<Real> lineDirection
{
Dot(line.direction, box.axis[0]),
Dot(line.direction, box.axis[1])
};
Result result{};
this->DoQuery(lineOrigin, lineDirection, box.extent, result);
for (int32_t i = 0; i < result.numIntersections; ++i)
{
result.point[i] = line.origin + result.parameter[i] * line.direction;
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrSphere3Sphere3.h | .h | 5,001 | 153 | // 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/Hypersphere.h>
#include <Mathematics/Circle3.h>
// The queries consider the spheres to be solids.
namespace gte
{
template <typename Real>
class TIQuery<Real, Sphere3<Real>, Sphere3<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Sphere3<Real> const& sphere0, Sphere3<Real> const& sphere1)
{
Result result{};
Vector3<Real> diff = sphere1.center - sphere0.center;
Real rSum = sphere0.radius + sphere1.radius;
result.intersect = (Dot(diff, diff) <= rSum * rSum);
return result;
}
};
template <typename Real>
class FIQuery<Real, Sphere3<Real>, Sphere3<Real>>
{
public:
struct Result
{
Result()
:
intersect(false),
type(-1),
point(Vector3<Real>::Zero()),
circle(Vector3<Real>::Zero(), Vector3<Real>::Zero(), (Real)0)
{
}
// The type of intersection.
// 0: spheres are disjoint and separated
// 1: spheres touch at point, each sphere outside the other
// 2: spheres intersect in a circle
// 3: sphere0 strictly contained in sphere1
// 4: sphere0 contained in sphere1, share common point
// 5: sphere1 strictly contained in sphere0
// 6: sphere1 contained in sphere0, share common point
bool intersect;
int32_t type;
Vector3<Real> point; // types 1, 4, 6
Circle3<Real> circle; // type 2
};
Result operator()(Sphere3<Real> const& sphere0, Sphere3<Real> const& sphere1)
{
Result result{};
// The plane of intersection must have C1-C0 as its normal
// direction.
Vector3<Real> C1mC0 = sphere1.center - sphere0.center;
Real sqrLen = Dot(C1mC0, C1mC0);
Real r0 = sphere0.radius, r1 = sphere1.radius;
Real rSum = r0 + r1;
Real rSumSqr = rSum * rSum;
if (sqrLen > rSumSqr)
{
// The spheres are disjoint/separated.
result.intersect = false;
result.type = 0;
return result;
}
if (sqrLen == rSumSqr)
{
// The spheres are just touching with each sphere outside the
// other.
Normalize(C1mC0);
result.intersect = true;
result.type = 1;
result.point = sphere0.center + r0 * C1mC0;
return result;
}
Real rDif = r0 - r1;
Real rDifSqr = rDif * rDif;
if (sqrLen < rDifSqr)
{
// One sphere is strictly contained in the other. Compute a
// point in the intersection set.
result.intersect = true;
result.type = (rDif <= (Real)0 ? 3 : 5);
result.point = ((Real)0.5) * (sphere0.center + sphere1.center);
return result;
}
if (sqrLen == rDifSqr)
{
// One sphere is contained in the other sphere but with a
// single point of contact.
Normalize(C1mC0);
result.intersect = true;
if (rDif <= (Real)0)
{
result.type = 4;
result.point = sphere1.center + r1 * C1mC0;
}
else
{
result.type = 6;
result.point = sphere0.center + r0 * C1mC0;
}
return result;
}
// Compute t for which the circle of intersection has center
// K = C0 + t*(C1 - C0).
Real t = ((Real)0.5) * ((Real)1 + rDif * rSum / sqrLen);
// Compute the center and radius of the circle of intersection.
result.circle.center = sphere0.center + t * C1mC0;
result.circle.radius = std::sqrt(std::max(r0 * r0 - t * t * sqrLen, (Real)0));
// Compute the normal for the plane of the circle.
Normalize(C1mC0);
result.circle.normal = C1mC0;
// The intersection is a circle.
result.intersect = true;
result.type = 2;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrRay3Cone3.h | .h | 3,961 | 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/Ray.h>
#include <Mathematics/IntrLine3Cone3.h>
// The queries consider the cone to be single sided and solid. The
// cone height range is [hmin,hmax]. The cone can be infinite where
// hmin = 0 and hmax = +infinity, infinite truncated where hmin > 0
// and hmax = +infinity, finite where hmin = 0 and hmax < +infinity,
// or a cone frustum where hmin > 0 and hmax < +infinity. The
// algorithm details are found in
// https://www.geometrictools.com/Documentation/IntersectionLineCone.pdf
namespace gte
{
template <typename Real>
class FIQuery<Real, Ray3<Real>, Cone3<Real>>
:
public FIQuery<Real, Line3<Real>, Cone3<Real>>
{
public:
struct Result
:
public FIQuery<Real, Line3<Real>, Cone3<Real>>::Result
{
Result()
:
FIQuery<Real, Line3<Real>, Cone3<Real>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray3<Real> const& ray, Cone3<Real> const& cone)
{
// Execute the line-cone query.
Result result{};
this->DoQuery(ray.origin, ray.direction, cone, result);
// Adjust the t-interval depending on whether the line-cone
// t-interval overlaps the ray interval [0,+infinity). The block
// numbers are a continuation of those in IntrLine3Cone3.h.
if (result.type != Result::isEmpty)
{
using QFN1 = typename FIQuery<Real, Line3<Real>, Cone3<Real>>::QFN1;
QFN1 zero(0, 0, result.t[0].d);
if (result.type == Result::isPoint)
{
if (result.t[0] < zero)
{
// Block 12.
this->SetEmpty(result);
}
// else: Block 13.
}
else if (result.type == Result::isSegment)
{
if (result.t[1] > zero)
{
// Block 14.
this->SetSegment(std::max(result.t[0], zero), result.t[1], result);
}
else if (result.t[1] < zero)
{
// Block 15.
this->SetEmpty(result);
}
else // result.t[1] == zero
{
// Block 16.
this->SetPoint(zero, result);
}
}
else if (result.type == Result::isRayPositive)
{
// Block 17.
this->SetRayPositive(std::max(result.t[0], zero), result);
}
else // result.type == Result::isRayNegative
{
if (result.t[1] > zero)
{
// Block 18.
this->SetSegment(zero, result.t[1], result);
}
else if (result.t[1] < zero)
{
// Block 19.
this->SetEmpty(result);
}
else // result.t[1] == zero
{
// Block 20.
this->SetPoint(zero, result);
}
}
}
result.ComputePoints(ray.origin, ray.direction);
result.intersect = (result.type != Result::isEmpty);
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Tetrahedron3.h | .h | 9,515 | 263 | // 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/Hyperplane.h>
#include <Mathematics/Vector3.h>
// The tetrahedron is represented as an array of four vertices, V[i] for
// 0 <= i <= 3. The vertices are ordered so that the triangular faces are
// counterclockwise-ordered triangles when viewed by an observer outside the
// tetrahedron: face 0 = <V[0],V[2],V[1]>, face 1 = <V[0],V[1],V[3]>,
// face 2 = <V[0],V[3],V[2]> and face 3 = <V[1],V[2],V[3]>. The canonical
// tetrahedron has V[0] = (0,0,0), V[1] = (1,0,0), V[2] = (0,1,0) and
// V[3] = (0,0,1).
namespace gte
{
template <typename T>
class Tetrahedron3
{
public:
// Construction and destruction. The default constructor sets the
// vertices to (0,0,0), (1,0,0), (0,1,0) and (0,0,1).
Tetrahedron3()
:
v{ Vector3<T>::Zero(), Vector3<T>::Unit(0),
Vector3<T>::Unit(1), Vector3<T>::Unit(2) }
{
}
Tetrahedron3(Vector3<T> const& v0, Vector3<T> const& v1,
Vector3<T> const& v2, Vector3<T> const& v3)
:
v{ v0, v1, v2, v3 }
{
}
Tetrahedron3(std::array<Vector3<T>, 4> const& inV)
:
v(inV)
{
}
// Get the vertex indices for the specified face. The input 'face'
// must be in {0,1,2,3}.
static inline std::array<size_t, 3> const& GetFaceIndices(size_t face)
{
static std::array<std::array<size_t, 3>, 4> const sFaceIndices =
{ {
{ 0, 2, 1 },
{ 0, 1, 3 },
{ 0, 3, 2 },
{ 1, 2, 3 }
} };
return sFaceIndices[face];
}
static inline std::array<size_t, 12> const& GetAllFaceIndices()
{
static std::array<size_t, 12> sAllFaceIndices =
{
0, 2, 1,
0, 1, 3,
0, 3, 2,
1, 2, 3
};
return sAllFaceIndices;
}
// Get the vertex indices for the specified edge. The input 'edge'
// must be in {0,1,2,3,4,5}.
static inline std::array<size_t, 2> const& GetEdgeIndices(size_t edge)
{
static std::array<std::array<size_t, 2>, 6> sEdgeIndices =
{ {
{ 0, 1 },
{ 0, 2 },
{ 0, 3 },
{ 1, 2 },
{ 1, 3 },
{ 2, 3 }
} };
return sEdgeIndices[edge];
}
static inline std::array<size_t, 12> const& GetAllEdgeIndices()
{
static std::array<size_t, 12> sAllEdgeIndices =
{
0, 1, 0, 2, 0, 3, 1, 2, 1, 3, 2, 3
};
return sAllEdgeIndices;
}
// Get the vertex indices for the edges with the appropriately ordered
// adjacent indices. The input 'edge' must be in {0,1,2,3,4,5}. The
// output is {v0,v1,v2,v3} where the edge is {v0,v1}. The triangles
// sharing the edge are {v0,v2,v1} and {v0,v1,v3}.
static inline std::array<size_t, 4> const& GetEdgeAugmented(size_t edge)
{
static std::array<std::array<size_t, 4>, 6> sEdgeAugmented =
{ {
{ 0, 1, 2, 3 },
{ 0, 2, 3, 1 },
{ 0, 3, 1, 2 },
{ 1, 2, 0, 3 },
{ 1, 3, 2, 0 },
{ 2, 3, 0, 1}
} };
return sEdgeAugmented[edge];
}
// Get the augmented indices for the vertices with the appropriately
// ordered adjacent indices. The input 'vertex' must be in {0,1,2,3}.
// The output is {v0,v1,v2,v3} where the vertex is v0. The triangles
// sharing the vertex are {v0,v1,v2}, {v0,v2,v3} and {v0,v3,v1}.
static inline std::array<size_t, 4> const& GetVertexAugmented(size_t vertex)
{
static std::array<std::array<size_t, 4>, 4> sVertexAugmented =
{ {
{ 0, 1, 3, 2 },
{ 1, 3, 0, 2 },
{ 2, 1, 0, 3 },
{ 3, 2, 0, 1 },
} };
return sVertexAugmented[vertex];
}
// Compute a face normal. The input 'face' must be in {0,1,2,3}
// and correspond to faces {{0,2,1},{0,1,3},{0,3,2},{1,2,3}}.
Vector3<T> ComputeFaceNormal(size_t face) const
{
// Compute the normal for face <v0,v1,v2>.
auto const& indices = GetFaceIndices(face);
auto edge10 = v[indices[1]] - v[indices[0]];
auto edge20 = v[indices[2]] - v[indices[0]];
auto normal = UnitCross(edge10, edge20);
return normal;
}
// Compute an edge normal, an average of the normals of the 2 faces
// sharing the edge. The input 'edge' must be in {0,1,2,3,4,5} and
// correspond to edges {{0,1},{0,2},{0,3},{1,2},{1,3},{2,3}}.
Vector3<T> ComputeEdgeNormal(size_t edge) const
{
// Compute the weighted average of normals for faces <v0,a0,v1>
// and <v0,v1,a1> shared by edge <v0,v1>. In the comments,
// E10 = V[v1]-V[v0], E20 = V[v2]-V[v0], E30 = V[v3]-V[v0] and
// E23 = V[i2]-V[i3]. The unnormalized vector is
// N = E20 x E10 + E10 x E30
// = E20 x E10 - E30 x E10
// = (E20 - E30) x E10
// = E23 x E10
auto const& indices = GetEdgeAugmented(edge);
auto edge23 = v[indices[2]] - v[indices[3]];
auto edge10 = v[indices[1]] - v[indices[0]];
auto normal = UnitCross(edge23, edge10);
return normal;
}
// Compute a vertex normal, an average of the normals of the 3 faces
// sharing the vertex. The input 'vertex' must be in {0,1,2,3} and
// are the indices into the tetrahedron vertex array. The algebra
// shows that the vertex normal is the negative normal of the face
// opposite the vertex.
Vector3<T> ComputeVertexNormal(size_t vertex) const
{
// Compute the weighted average of normals for faces <v0,v1,v2>,
// <v0,v2,v3> and <v0,v3,v1>. In the comments, E10 = V[v1]-V[v0],
// E20 = V[v2]-V[v0, E30 = V[v3]-V[v0], E12 = V[v1]-V[v2],
// E21 = V[v2]-V[v1] and E31 = V[v3]-V[v1]. The unnormalized
// vector is
// N = E10 x E20 + E20 x E30 + E30 x E10
// = E10 x E20 - E30 x E20 + E30 x E10 - E10 x E10
// = E13 x E20 + E31 x E10
// = E13 x E20 - E13 x E10
// = E13 x E21
auto const& indices = GetVertexAugmented(vertex);
auto edge13 = v[indices[1]] - v[indices[3]];
auto edge21 = v[indices[2]] - v[indices[1]];
auto normal = UnitCross(edge13, edge21);
return normal;
}
// Construct the planes of the faces. The planes have outer pointing
// normal vectors. The plane indexing is the same as the face
// indexing mentioned previously.
void GetPlanes(std::array<Plane3<T>, 4>& plane) const
{
Vector3<T> edge10 = v[1] - v[0];
Vector3<T> edge20 = v[2] - v[0];
Vector3<T> edge30 = v[3] - v[0];
Vector3<T> edge21 = v[2] - v[1];
Vector3<T> edge31 = v[3] - v[1];
plane[0].normal = UnitCross(edge20, edge10); // <v0,v2,v1>
plane[1].normal = UnitCross(edge10, edge30); // <v0,v1,v3>
plane[2].normal = UnitCross(edge30, edge20); // <v0,v3,v2>
plane[3].normal = UnitCross(edge21, edge31); // <v1,v2,v3>
T det = Dot(edge10, plane[3].normal);
if (det < static_cast<T>(0))
{
// The normals are inner pointing, reverse their directions.
for (size_t i = 0; i < 4; ++i)
{
plane[i].normal = -plane[i].normal;
}
}
for (size_t i = 0; i < 4; ++i)
{
plane[i].constant = Dot(v[i], plane[i].normal);
}
}
Vector3<T> ComputeCentroid() const
{
return (v[0] + v[1] + v[2] + v[3]) * static_cast<T>(0.25);
}
// Public member access.
std::array<Vector3<T>, 4> v;
public:
// Comparisons to support sorted containers.
bool operator==(Tetrahedron3 const& tetrahedron) const
{
return v == tetrahedron.v;
}
bool operator!=(Tetrahedron3 const& tetrahedron) const
{
return v != tetrahedron.v;
}
bool operator< (Tetrahedron3 const& tetrahedron) const
{
return v < tetrahedron.v;
}
bool operator<=(Tetrahedron3 const& tetrahedron) const
{
return v <= tetrahedron.v;
}
bool operator> (Tetrahedron3 const& tetrahedron) const
{
return v > tetrahedron.v;
}
bool operator>=(Tetrahedron3 const& tetrahedron) const
{
return v >= tetrahedron.v;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/MinimumVolumeBox3.h | .h | 81,970 | 2,288 | // 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.16
#pragma once
#include <Mathematics/Logger.h>
#include <Mathematics/ConvexHull3.h>
#include <Mathematics/MinimumAreaBox2.h>
#include <Mathematics/VETManifoldMesh.h>
#include <Mathematics/AlignedBox.h>
#include <Mathematics/UniqueVerticesSimplices.h>
#include <cstring>
// Compute a minimum-volume oriented box containing the specified points. The
// algorithm is really about computing the minimum-volume box containing the
// convex hull of the points, so you must compute the convex hull or pass an
// an already built hull to the code. The convex hull is, of course, a convex
// polyhedron.
//
// According to
// J.O'Rourke, "Finding minimal enclosing boxes",
// Internat. J. Comput. Inform. Sci., 14:183-199, 1985.
// the minimum-volume oriented box must have at least two adjacent faces
// flush with edges of the convex polyhedron. The implementation processes
// all pairs of edges, determining for each pair the relevant box-face
// normals that are candidates for the minimum-volume box. I use an approach
// different from that of the details of proof in the paper; see
// https://www.geometrictools.com/Documentation/MinimumVolumeBox.pdf
// The computations involve an iterative minimizer, so you cannot expect
// to obtain the exact minimum-volume box, but you will obtain a good
// approximation to it based on how many samples the minimizer uses in its
// search. You can also derive from a class and override the virtual
// functions that are used for minimization in order to provided your own
// minimizer algorithm.
namespace gte
{
// The InputType is 'float' or 'double'. The ComputeType is 'double' when
// computeDouble is 'true' or it is the appropriate fixed-precision
// BSNumber<> class when computeDouble is 'false'. If you use rational
// arithmetic for the computations, you must increase the default program
// stack size significantly. In Microsoft Visual Studio, I set the Stack
// Reserve Size to 1 GB (which is 1073741824 bytes and is probably much
// more than required.).
template <typename InputType, bool computeDouble>
class MinimumVolumeBox3
{
public:
// Supporting constants and types for numerical computing.
static int32_t constexpr NumWords = std::is_same<InputType, float>::value ? 342 : 2561;
using UIntegerType = UIntegerFP32<NumWords>;
using ComputeType = typename std::conditional<computeDouble, double, BSNumber<UIntegerType>>::type;
using RationalType = typename std::conditional<computeDouble, double, BSRational<UIntegerType>>::type;
using VCompute3 = Vector3<ComputeType>;
using RVCompute3 = Vector3<RationalType>;
// Supporting constants types for a compact vertex-edge-triangle mesh
// that represents the convex polyhedron input.
static size_t constexpr invalidIndex = std::numeric_limits<size_t>::max();
struct Edge
{
Edge()
:
V{ invalidIndex, invalidIndex },
T{ invalidIndex, invalidIndex }
{
}
std::array<size_t, 2> V;
std::array<size_t, 2> T;
};
struct Triangle
{
Triangle()
:
V{ invalidIndex, invalidIndex },
E{ invalidIndex, invalidIndex },
T{ invalidIndex, invalidIndex }
{
}
std::array<size_t, 3> V;
std::array<size_t, 3> E;
std::array<size_t, 3> T;
};
// Information about candidates for the minimum-volume box and about
// that box itself.
struct Candidate
{
Candidate()
:
edgeIndex{ invalidIndex, invalidIndex },
edge{},
N{ VCompute3::Zero(), VCompute3::Zero() },
M{ VCompute3::Zero(), VCompute3::Zero() },
f00(static_cast<ComputeType>(0)),
f10(static_cast<ComputeType>(0)),
f01(static_cast<ComputeType>(0)),
f11(static_cast<ComputeType>(0)),
levelCurveProcessorIndex(invalidIndex),
axis{ VCompute3::Unit(0), VCompute3::Unit(1), VCompute3::Unit(2) },
minSupportIndex{ invalidIndex, invalidIndex, invalidIndex },
maxSupportIndex{ invalidIndex, invalidIndex, invalidIndex },
volume(static_cast<ComputeType>(0))
{
}
// Set by ProcessEdgePair.
std::array<size_t, 2> edgeIndex;
std::array<Edge, 2> edge;
std::array<VCompute3, 2> N, M;
ComputeType f00, f10, f01, f11;
size_t levelCurveProcessorIndex;
// Set by Pair, MinimizerConstantT, MinimizerConstantS,
// MinimizerVariableS and MinimizerVariableT. The axis[0] and
// axis[1] are set by the aforementioned functions. The axis[2]
// is computed by ComputeVolume.
std::array<VCompute3, 3> axis;
// Set by ComputeVolume.
std::array<size_t, 3> minSupportIndex;
std::array<size_t, 3> maxSupportIndex;
RationalType volume;
};
// The rational representation of the minimum-volume box. The axis[]
// vectors are generally not unit length. To obtain a unit-length
// vector, use axis[i]/std::sqrt(sqrLengthAxis[i]).
struct RBox
{
RBox()
:
center(RVCompute3::Zero()),
axis{ RVCompute3::Zero(), RVCompute3::Zero(), RVCompute3::Zero() },
sqrLengthAxis(RVCompute3::Zero()),
scaledExtent(RVCompute3::Zero()),
volume(static_cast<RationalType>(0))
{
}
RVCompute3 center;
std::array<RVCompute3, 3> axis;
RVCompute3 sqrLengthAxis;
RVCompute3 scaledExtent;
RationalType volume;
};
public:
// Construction and destruction. To execute in the main thread, set
// numThreads to 0. To run multithreaded on the CPU, set numThreads
// to a positive number.
MinimumVolumeBox3(size_t numThreads = 0)
:
mNumThreads(numThreads),
mDomainIndex{},
mZero(static_cast<ComputeType>(0)),
mOne(static_cast<ComputeType>(1)),
mHalf(static_cast<ComputeType>(0.5)),
mNumVertices(0),
mNumTriangles(0),
mAdjacentPool{},
mVertexAdjacent{},
mEdges{},
mTriangles{},
mEdgeIndices{},
mOrigin{},
mVertices{},
mNormals{},
mAlignedCandidate{},
mMinimumVolumeObject{},
mLevelCurveProcessor{}
{
static_assert(std::is_floating_point<InputType>::value,
"The input type must be 'float' or 'double'.");
InitializeLevelCurveProcessors();
}
virtual ~MinimumVolumeBox3() = default;
// The class is a wrapper for operator()(*), so there is no need for
// copy semantics.
MinimumVolumeBox3(MinimumVolumeBox3 const&) = delete;
MinimumVolumeBox3& operator=(MinimumVolumeBox3 const&) = delete;
// The convex hull of the input points is computed. The output
// box is determined by the dimension of the hull.
// 0D: The hull is a single point. The box has center at that
// point, the axes are the standard Euclidean basis, and the
// extents are all 0.
// 1D: The hull is a line segment. The box has center at the
// midpoint of the segment, axis[0] is the segment direction,
// axis[1] and axis[2] are chosen so that the three axes form
// a right-handed orthonormal set, extent[0] is the half-length
// of the segment, and extent[1] and extent[2] are 0.
// 2D: The hull is a planar polygon. The box is the minimum-area
// box containing that polygon. The axis[0] and axis[1] are
// the axis directions for the planar box, axis[2] is normal
// to the plane of the polygon, extent[0] and extent[1] are
// the extents of the planar box, and extent[2] is 0.
// 3D: The hull is a convex polyhedron. The other operator()(*)
// function is called to compute the minimum-volume box of the
// polyhedron.
// If the dimension is 0, 1 or 2, the objects returned by the
// GetMinimumVolumeObject() and GetRationalBox() are invalid for this
// operator()(*).
int32_t operator()(
int32_t numPoints,
Vector3<InputType> const* points,
size_t lgMaxSample,
OrientedBox3<InputType>& box,
InputType& volume)
{
LogAssert(numPoints > 0 && points != nullptr && lgMaxSample >= 2,
"Invalid argument.");
InputType const zero = static_cast<InputType>(0);
InputType const one = static_cast<InputType>(1);
InputType const half = static_cast<InputType>(0.5);
mConvexHull3(static_cast<size_t>(numPoints), points, 0);
size_t dimension = mConvexHull3.GetDimension();
auto const& hull = mConvexHull3.GetHull();
if (dimension == 0)
{
// The points are all the same.
box.center = points[hull[0]];
box.axis[0] = { one, zero, zero };
box.axis[1] = { zero, one, zero };
box.axis[2] = { zero, zero, one };
box.extent[0] = zero;
box.extent[1] = zero;
box.extent[2] = zero;
volume = zero;
return 0;
}
if (dimension == 1)
{
// The points lie on a line.
Vector3<InputType> direction = points[hull[1]] - points[hull[0]];
box.center = half * (points[hull[0]] + points[hull[1]]);
box.extent[0] = half * Normalize(direction);
box.extent[1] = zero;
box.extent[2] = zero;
box.axis[0] = direction;
ComputeOrthogonalComplement(1, &box.axis[0]);
volume = zero;
return 1;
}
if (dimension == 2)
{
// The points line on a plane. Get a coordinate system
// relative to the plane of the points. Choose the origin
// to be any of the input points.
Vector3<InputType> origin = points[hull[0]];
Vector3<InputType> normal = Vector3<InputType>::Zero();
size_t numHull = hull.size();
for (size_t i0 = numHull - 1, i1 = 1; i1 < numHull; i0 = i1++)
{
auto const& P0 = points[hull[i0]];
auto const& P1 = points[hull[i1]];
normal += Cross(P0, P1);
}
Vector3<InputType> basis[3];
basis[0] = normal;
ComputeOrthogonalComplement(1, basis);
// Project the input points onto the plane.
std::vector<Vector2<InputType>> projection(numPoints);
for (int32_t i = 0; i < numPoints; ++i)
{
Vector3<InputType> diff = points[i] - origin;
projection[i][0] = Dot(basis[1], diff);
projection[i][1] = Dot(basis[2], diff);
}
// Compute the minimum area box in 2D.
MinimumAreaBox2<InputType, BSRational<UIntegerAP32>> mab2;
OrientedBox2<InputType> rectangle = mab2(numPoints, &projection[0]);
// Lift the values into 3D.
box.center = origin + rectangle.center[0] * basis[1] + rectangle.center[1] * basis[2];
box.axis[0] = rectangle.axis[0][0] * basis[1] + rectangle.axis[0][1] * basis[2];
box.axis[1] = rectangle.axis[1][0] * basis[1] + rectangle.axis[1][1] * basis[2];
box.axis[2] = basis[0];
box.extent[0] = rectangle.extent[0];
box.extent[1] = rectangle.extent[1];
box.extent[2] = zero;
volume = zero;
return 2;
}
// Remove duplicated vertices and reindex them for the convex
// polyhedron.
std::vector<Vector3<InputType>> inVertices(numPoints);
std::memcpy(inVertices.data(), points, inVertices.size() * sizeof(Vector3<InputType>));
auto const& triangles = mConvexHull3.GetHull();
std::vector<int32_t> inIndices(triangles.size());
size_t current = 0;
for (auto index : triangles)
{
inIndices[current++] = static_cast<int32_t>(index);
}
UniqueVerticesSimplices<Vector3<InputType>, int32_t, 3> uvt;
std::vector<Vector3<InputType>> outVertices;
std::vector<int32_t> outIndices;
uvt.RemoveDuplicateAndUnusedVertices(inVertices, inIndices,
outVertices, outIndices);
operator()(static_cast<int32_t>(outVertices.size()), outVertices.data(),
static_cast<int32_t>(outIndices.size()), outIndices.data(),
lgMaxSample, box, volume);
return 3;
}
// The points form a nondegenerate convex polyhedron. The inputs
// 'vertices' and 'indices' must be nonempty and the 'vertices' must
// have no duplicates. The triangle faces are triples of the indices;
// there are indices.size()/3 triangles. Also, 0 <= indices[i] <
// vertices.size() for all 0 <= i < indices.size(). The logarithm base
// 2 of maximum sample index must satisfy the condition
// lgMaxSample >= 2, so there are at least 4 samples. Do not choose it
// to be too large when using rational computation because the
// computational costs are excessive. You can override the minimizer
// functions to use your own minimization algorithm; see the comments
// before MinimizerConstantT.
void operator()(
int32_t numVertices,
Vector3<InputType> const* inVertices,
int32_t numIndices,
int32_t const* inIndices,
size_t lgMaxSample,
OrientedBox3<InputType>& box,
InputType& volume)
{
LogAssert(
numVertices > 0 && inVertices != nullptr &&
numIndices > 0 && inIndices != nullptr &&
(numIndices % 3) == 0 && lgMaxSample >= 2,
"Invalid argument.");
for (int32_t i = 0; i < numIndices; ++i)
{
LogAssert(0 <= inIndices[i] && inIndices[i] < numVertices,
"Invalid index.");
}
// Reset old data
mAdjacentPool.clear();
mVertexAdjacent.clear();
mEdges.clear();
mTriangles.clear();
mEdgeIndices.clear();
mVertices.clear();
mNormals.clear();
std::vector<Vector3<InputType>> vertices(numVertices);
std::memcpy(vertices.data(), inVertices,
vertices.size() * sizeof(Vector3<InputType>));
std::vector<int32_t> indices(numIndices);
std::memcpy(indices.data(), inIndices,
indices.size() * sizeof(int32_t));
GenerateSubdivision(lgMaxSample);
CreateCompactMesh(vertices, indices);
PrepareVerticesAndNormals(vertices);
ComputeAlignedCandidate();
GetMinimumVolumeCandidate();
GetMinimumVolumeBox(box, volume);
}
// For more information about the minimum-volume box, access the
// candidate that stores it.
inline Candidate const& GetMinimumVolumeObject() const
{
return mMinimumVolumeObject;
}
// The operator()(*) function returns a floating-point box and volume.
// If you computed using rational arithmetic, the rational box is
// accessed by this member function.
inline void GetRationalBox(RBox& rbox) const
{
rbox = mRBox;
}
// Returns the convex hull that was computed for computing the minimum-volume box.
// Note that convex hull is not computed when using operator()(...int32_t const* inIndices...)
// since that overload uses the provided convex hull.
inline ConvexHull3<InputType> const& GetConvexHull3() const
{
return mConvexHull3;
}
protected:
void CreateDomainIndex(size_t& current, size_t end0, size_t end1)
{
size_t mid = (end0 + end1) / 2;
if (mid != end0 && mid != end1)
{
mDomainIndex[current++] = { mid, end0, end1 };
CreateDomainIndex(current, end0, mid);
CreateDomainIndex(current, mid, end1);
}
}
void GenerateSubdivision(size_t lgMaxSample)
{
mMaxSample = (static_cast<size_t>(1) << lgMaxSample);
mDomainIndex.resize(mMaxSample - 1);
size_t current = 0;
CreateDomainIndex(current, 0, mMaxSample);
}
// The vertices are stored in a vertex-edge-triangle manifold mesh.
// Each vertex as a set of adjacent vertices, a set of adjacent
// edges and a set of adjacent triangles. The adjacent vertices are
// repackaged into mVertexAdjacent[] and mAdjacentPool[]. For
// vertex v with n adjacent vertices, mVertexAdjacent[v] is the
// index into mAdjacentPool[] whre the n adjacent vertices are
// stored. If the adjacent vertices are a[0] through a[n-1], then
// mAdjacentPool[mVertexAdjacent[v] + i] is a[i].
void CreateCompactMesh(
std::vector<Vector3<InputType>> const& vertices,
std::vector<int32_t> const& indices)
{
mNumVertices = vertices.size();
mNumTriangles = indices.size() / 3;
VETManifoldMesh mesh;
int32_t const* current = indices.data();
for (size_t t = 0; t < mNumTriangles; ++t)
{
int32_t v0 = *current++;
int32_t v1 = *current++;
int32_t v2 = *current++;
mesh.Insert(v0, v1, v2);
}
// It is implicit in the construction of mVertexAdjacent that
// (1) the vertex indices v satisfy 0 <= v < N for a mesh of
// N vertices and
// (2) the vertex map itself is ordered as <0,vertex0>,
// <1,vertex1>, ..., <N-1,vertexNm1>.
// Condition (1) is guaranteed because the input to the MVB3
// constructor uses the contiguous indices of the position array.
// Condition (2) is not guaranteed because VETManifoldMesh::VMap
// is a std::unordered_map. The vertices must be sorted here to
// satisfy condition2.
auto const& vmap = mesh.GetVertices();
std::map<int32_t, VETManifoldMesh::Vertex*> sortedVMap;
for (auto const& element : vmap)
{
sortedVMap.emplace(element.first, element.second.get());
}
size_t numAdjacentPool = 0;
for (auto const& element : sortedVMap)
{
numAdjacentPool += element.second->VAdjacent.size() + 1;
}
mAdjacentPool.resize(numAdjacentPool);
mVertexAdjacent.resize(sortedVMap.size());
size_t apIndex = 0, vaIndex = 0;
for (auto const& element : sortedVMap)
{
auto const& adjacent = element.second->VAdjacent;
mVertexAdjacent[vaIndex++] = apIndex;
mAdjacentPool[apIndex++] = adjacent.size();
for (auto v : adjacent)
{
mAdjacentPool[apIndex++] = static_cast<size_t>(v);
}
}
auto const& emap = mesh.GetEdges();
auto const& tmap = mesh.GetTriangles();
mEdges.resize(emap.size());
mTriangles.resize(tmap.size());
std::map<ETManifoldMesh::Edge*, size_t> edgeIndexMap;
size_t index = 0;
for (auto const& element : emap)
{
edgeIndexMap.emplace(element.second.get(), index);
for (size_t j = 0; j < 2; ++j)
{
mEdges[index].V[j] = (size_t)element.second->V[j];
}
++index;
}
std::map<ETManifoldMesh::Triangle*, size_t> triangleIndexMap;
index = 0;
for (auto const& element : tmap)
{
triangleIndexMap.emplace(element.second.get(), index);
for (size_t j = 0; j < 3; ++j)
{
mTriangles[index].V[j] = (size_t)element.second->V[j];
}
++index;
}
index = 0;
for (auto const& element : emap)
{
for (size_t j = 0; j < 2; ++j)
{
auto tri = element.second->T[j];
auto titer = triangleIndexMap.find(tri);
mEdges[index].T[j] = titer->second;
}
++index;
}
index = 0;
for (auto const& element : tmap)
{
for (size_t j = 0; j < 3; ++j)
{
auto edg = element.second->E[j];
auto eiter = edgeIndexMap.find(edg);
mTriangles[index].E[j] = eiter->second;
}
for (size_t j = 0; j < 3; ++j)
{
auto tri = element.second->T[j];
auto titer = triangleIndexMap.find(tri);
mTriangles[index].T[j] = titer->second;
}
++index;
}
size_t const numEdges = mEdges.size();
mEdgeIndices.reserve(mEdges.size() * mEdges.size());
for (size_t e0 = 0; e0 < numEdges; ++e0)
{
for (size_t e1 = e0 + 1; e1 < numEdges; ++e1)
{
mEdgeIndices.push_back({ e0, e1 });
}
}
}
template <bool useDouble = computeDouble>
typename std::enable_if<useDouble, void>::type
ComputeNormal(VCompute3 const& edge0, VCompute3 const& edge1, VCompute3& normal)
{
normal = UnitCross(edge0, edge1);
}
template <bool useDouble = computeDouble>
typename std::enable_if<!useDouble, void>::type
ComputeNormal(VCompute3 const& edge0, VCompute3 const& edge1, VCompute3& normal)
{
normal = Cross(edge0, edge1);
}
void PrepareVerticesAndNormals(std::vector<Vector3<InputType>> const& vertices)
{
// Convert from floating-point type to the compute type (double or
// rational). The origin is considered to be inVertices[0]).
mVertices.resize(mNumVertices);
for (int32_t j = 0; j < 3; ++j)
{
mOrigin[j] = static_cast<ComputeType>(vertices[0][j]);
mVertices[0][j] = static_cast<ComputeType>(0);
}
for (size_t i = 1; i < mNumVertices; ++i)
{
for (int32_t j = 0; j < 3; ++j)
{
mVertices[i][j] = static_cast<ComputeType>(vertices[i][j]) - mOrigin[j];
}
}
// Compute inner-pointing normals that are not required to be
// unit length.
mNormals.resize(mNumTriangles);
for (size_t i = 0; i < mNumTriangles; ++i)
{
auto const& tri = mTriangles[i];
size_t v0 = tri.V[0], v1 = tri.V[1], v2 = tri.V[2];
VCompute3 edge10 = mVertices[v1] - mVertices[v0];
VCompute3 edge20 = mVertices[v2] - mVertices[v0];
ComputeNormal(edge20, edge10, mNormals[i]);
}
}
void ComputeAlignedCandidate()
{
VCompute3 pmin, pmax;
for (int32_t j = 0; j < 3; ++j)
{
mAlignedCandidate.maxSupportIndex[j] =
GetExtreme(mAlignedCandidate.axis[j], pmax[j]);
mAlignedCandidate.minSupportIndex[j] =
GetExtreme(-mAlignedCandidate.axis[j], pmin[j]);
pmin[j] = -pmin[j];
}
VCompute3 diff = pmax - pmin;
mAlignedCandidate.volume = diff[0] * diff[1] * diff[2];
}
size_t GetExtreme(VCompute3 const& direction, ComputeType& dMax)
{
size_t vMax = 0;
dMax = Dot(direction, mVertices[vMax]);
for (size_t i = 0; i < mNumVertices; ++i)
{
size_t vLocalMax = vMax;
ComputeType dLocalMax = dMax;
size_t const* adjacent = &mAdjacentPool[mVertexAdjacent[vMax]];
size_t numAdjacent = *adjacent++;
for (size_t j = 1; j <= numAdjacent; ++j)
{
size_t vCandidate = *adjacent++;
ComputeType dCandidate = Dot(direction, mVertices[vCandidate]);
if (dCandidate > dLocalMax)
{
vLocalMax = vCandidate;
dLocalMax = dCandidate;
}
}
if (vMax != vLocalMax)
{
vMax = vLocalMax;
dMax = dLocalMax;
}
else
{
break;
}
}
return vMax;
}
void ComputeVolume(Candidate& candidate)
{
// The last axis is needed only when computing the volume for
// comparison to the current candidate volume, so compute this
// axis now.
candidate.axis[2] = Cross(candidate.axis[0], candidate.axis[1]);
VCompute3 pmin, pmax;
candidate.minSupportIndex[0] = mEdges[candidate.edgeIndex[0]].V[0];
pmin[0] = Dot(candidate.axis[0], mVertices[candidate.minSupportIndex[0]]);
candidate.maxSupportIndex[0] = GetExtreme(candidate.axis[0], pmax[0]);
candidate.minSupportIndex[1] = mEdges[candidate.edgeIndex[1]].V[0];
pmin[1] = Dot(candidate.axis[1], mVertices[candidate.minSupportIndex[1]]);
candidate.maxSupportIndex[1] = GetExtreme(candidate.axis[1], pmax[1]);
candidate.axis[2] = Cross(candidate.axis[0], candidate.axis[1]);
candidate.minSupportIndex[2] = GetExtreme(-candidate.axis[2], pmin[2]);
pmin[2] = -pmin[2];
candidate.maxSupportIndex[2] = GetExtreme(candidate.axis[2], pmax[2]);
VCompute3 diff = pmax - pmin;
candidate.volume =
static_cast<RationalType>(diff[0] * diff[1] * diff[2]) /
static_cast<RationalType>(Dot(candidate.axis[2], candidate.axis[2]));
}
void ProcessEdgePair(std::array<size_t, 2> const& edgeIndex, Candidate& mvCandidate)
{
// Examine the zero-valued level curves for
// F(s,t)
// = Dot((1-s)*edge0.N0 + s*edge0.N1, (1-t)*edge1.N0 + t*edge1.N1)
// = (1-s)*(1-t)*Dot(edge0.N0,edge1.N0)
// + (1-s)*t*Dot(edge0.N0,edge1.N1)
// + s*(1-t)*Dot(edge0.N1,edge1.N0)
// + s*t*Dot(edge0.N1,edge1.N1)
// = (1-s)*(1-t)*f00 + (1-s)*t*f01 + s*(1-t)*f10 + s*t*f11
// = a00 + a10*s + a01*t + a11*s*t
// = [(a00*a11 - a01*a10) + (a01 + a11*s)*(a10 + a11*t)]/a11
// where a00 = f00, a10 = f10-f00, a01 = f01-f00 and
// a11 = f00-f01-f10+f11. Let d = a00*a11 - a01*a10 =
// f00*f11 - f01*f10. If d = 0, then the level curves are
// s = -a01/a11 and t = -a10/a11. If d != 0, then the level curves
// are hyperbolic curves with asymptotes s = -a01/a11 and
// t = -a10/a11.
Candidate candidate = mAlignedCandidate;
candidate.edgeIndex = edgeIndex;
Edge const& edge0 = mEdges[candidate.edgeIndex[0]];
Edge const& edge1 = mEdges[candidate.edgeIndex[1]];
candidate.edge[0] = edge0;
candidate.edge[1] = edge1;
candidate.N[0] = mNormals[edge0.T[0]];
candidate.N[1] = mNormals[edge0.T[1]];
candidate.M[0] = mNormals[edge1.T[0]];
candidate.M[1] = mNormals[edge1.T[1]];
candidate.f00 = Dot(candidate.N[0], candidate.M[0]);
candidate.f10 = Dot(candidate.N[1], candidate.M[0]);
candidate.f01 = Dot(candidate.N[0], candidate.M[1]);
candidate.f11 = Dot(candidate.N[1], candidate.M[1]);
uint32_t bits00 = (candidate.f00 > mZero ? 1 : (candidate.f00 < mZero ? 2 : 0));
uint32_t bits10 = (candidate.f10 > mZero ? 1 : (candidate.f10 < mZero ? 2 : 0));
uint32_t bits01 = (candidate.f01 > mZero ? 1 : (candidate.f01 < mZero ? 2 : 0));
uint32_t bits11 = (candidate.f11 > mZero ? 1 : (candidate.f11 < mZero ? 2 : 0));
uint32_t index = bits00 | (bits10 << 2) | (bits01 << 4) | (bits11 << 6);
if (index != 0x55 && index != 0xaa)
{
candidate.levelCurveProcessorIndex = index;
(this->*mLevelCurveProcessor[candidate.levelCurveProcessorIndex])(candidate, mvCandidate);
}
}
void GetMinimumVolumeCandidate()
{
mMinimumVolumeObject = mAlignedCandidate;
if (mNumThreads > 0)
{
size_t const numPairsPerThread = mEdgeIndices.size() / mNumThreads;
std::vector<size_t> imin(mNumThreads), imax(mNumThreads);
for (size_t t = 0; t < mNumThreads; ++t)
{
imin[t] = t * numPairsPerThread;
imax[t] = (t + 1) * numPairsPerThread;
}
imax.back() = mEdgeIndices.size();
std::vector<Candidate> candidates(mNumThreads);
std::vector<std::thread> process(mNumThreads);
for (size_t t = 0; t < mNumThreads; ++t)
{
process[t] = std::thread(
[this, t, &imin, &imax, &candidates]()
{
candidates[t] = mAlignedCandidate;
for (size_t i = imin[t]; i < imax[t]; ++i)
{
ProcessEdgePair(mEdgeIndices[i], candidates[t]);
}
});
}
for (size_t t = 0; t < mNumThreads; ++t)
{
process[t].join();
if (candidates[t].volume < mMinimumVolumeObject.volume)
{
mMinimumVolumeObject = candidates[t];
}
}
}
else
{
for (auto const& edgeIndex : mEdgeIndices)
{
ProcessEdgePair(edgeIndex, mMinimumVolumeObject);
}
}
}
void GetMinimumVolumeBox(OrientedBox3<InputType>& box, InputType& volume)
{
Candidate const& mvc = mMinimumVolumeObject;
// Compute the rational-valued box and volume.
Vector3<RationalType> pmin, pmax;
for (int32_t i = 0; i < 3; ++i)
{
mRBox.center[i] = mOrigin[i];
for (int32_t j = 0; j < 3; ++j)
{
mRBox.axis[i][j] = mvc.axis[i][j];
}
mRBox.sqrLengthAxis[i] = Dot(mRBox.axis[i], mRBox.axis[i]);
pmin[i] = static_cast<RationalType>(Dot(mvc.axis[i], mVertices[mvc.minSupportIndex[i]]));
pmax[i] = static_cast<RationalType>(Dot(mvc.axis[i], mVertices[mvc.maxSupportIndex[i]]));
}
RationalType const half(0.5);
Vector3<RationalType> average = half * (pmax + pmin);
for (int32_t i = 0; i < 3; ++i)
{
for (int32_t j = 0; j < 3; ++j)
{
mRBox.center[j] += (average[i] / mRBox.sqrLengthAxis[i]) * mRBox.axis[i][j];
}
}
Vector3<RationalType> difference = pmax - pmin;
mRBox.scaledExtent = half * difference;
mRBox.volume = difference[0] * difference[1] * difference[2] / mRBox.sqrLengthAxis[2];
// Compute the floating-point-valued box and volume.
for (int32_t i = 0; i < 3; ++i)
{
box.center[i] = static_cast<InputType>(mRBox.center[i]);
InputType length = static_cast<InputType>(std::sqrt(mRBox.sqrLengthAxis[i]));
for (int32_t j = 0; j < 3; ++j)
{
box.axis[i][j] = static_cast<InputType>(mRBox.axis[i][j]) / length;
}
box.extent[i] = static_cast<InputType>(mRBox.scaledExtent[i]) / length;
}
volume = static_cast<InputType>(mRBox.volume);
}
// The number of threads to use for computing. If 0, the main thread
// is used. If positive, std::thread objects are used.
size_t mNumThreads;
// The maximum sample index used to search each level curve for
// non-face-supporting boxes (mMaxSample + 1 values). The samples are
// visited using subdivision of the domain of the level curve. The
// subdivision/ information is stored in mDomainIndex(mNumSamples-1).
size_t mMaxSample;
std::vector<std::array<size_t, 3>> mDomainIndex;
// Convenient members to allow construction once when the ComputeType
// is BSNumber<*>.
ComputeType const mZero, mOne, mHalf;
// A mesh representation of the convex polyhedron. The mesh is
// generated dynamically from the inputs to operator() but then is
// converted to a pointerless representation. The mAdjacentPool and
// mVertexAdjacent member are used for fast lookup of adjacent
// vertices in GetExtreme(*).
size_t mNumVertices, mNumTriangles;
std::vector<size_t> mAdjacentPool;
std::vector<size_t> mVertexAdjacent;
std::vector<Edge> mEdges;
std::vector<Triangle> mTriangles;
std::vector<std::array<size_t, 2>> mEdgeIndices;
// Storage for translated vertices and normal vectors. If the
// compute type is 'double', the normals must be normalized to
// unit length (within floating-point rounding error).
VCompute3 mOrigin;
std::vector<VCompute3> mVertices;
std::vector<VCompute3> mNormals;
// The axis-aligned bounding box of the vertices is used as the
// initial candidate for the minimum-volume box.
Candidate mAlignedCandidate;
// The information for the minimum-volume bounding box of the
// vertices.
Candidate mMinimumVolumeObject;
RBox mRBox;
// Convex Hull
ConvexHull3<InputType> mConvexHull3;
// Each member function A00B10C01D11(*) corresponds to a bilinear
// function on the domain [0,1]^2. Each corner of the domain has a
// bilinear function value that is positive, negative or zero,
// leading to 3^4 = 81 possibilities. The 'A', 'B', 'C' and 'D' are
// in {'P', 'M', 'Z'} [for Plus, Minus, Zero].
typedef void (MinimumVolumeBox3::* LevelCurveProcessor)(Candidate&, Candidate&);
std::array<LevelCurveProcessor, 256> mLevelCurveProcessor;
protected:
// Support for the level-curve processing functions.
void InitializeLevelCurveProcessors()
{
// Generate the initialization code for mLevelCurveProcessor.
// To compile the code, include <fstream>, <strstream> and
// <iomanip.
//
// std::ofstream output("LevelCurveProcessor.txt");
// std::array<char, 3> signchar = { 'Z', 'P', 'M' };
// for (uint32_t index = 0; index < 256u; ++index)
// {
// if ((index & 0x00000003u) != 0x00000003u &&
// (index & 0x0000000Cu) != 0x0000000Cu &&
// (index & 0x00000030u) != 0x00000030u &&
// (index & 0x000000C0u) != 0x000000C0u)
// {
// char s00 = signchar[index & 0x00000003u];
// char s10 = signchar[(index & 0x0000000Cu) >> 2];
// char s01 = signchar[(index & 0x00000030u) >> 4];
// char s11 = signchar[(index & 0x000000C0u) >> 6];
// std::strstream ostream;
// ostream << std::hex << std::setfill('0') << std::setw(2);
// ostream
// << " mLevelCurveProcessor[0x0"
// << std::hex << std::setfill('0') << std::setw(2)
// << index
// << "] = &MinimumVolumeBox3::"
// << s00 << "00"
// << s10 << "10"
// << s01 << "01"
// << s11 << "11;"
// << std::ends;
// output << ostream.str() << std::endl;
// }
// }
// output.close();
mLevelCurveProcessor.fill(nullptr);
mLevelCurveProcessor[0x00] = &MinimumVolumeBox3::Z00Z10Z01Z11;
mLevelCurveProcessor[0x01] = &MinimumVolumeBox3::P00Z10Z01Z11;
mLevelCurveProcessor[0x02] = &MinimumVolumeBox3::M00Z10Z01Z11;
mLevelCurveProcessor[0x04] = &MinimumVolumeBox3::Z00P10Z01Z11;
mLevelCurveProcessor[0x05] = &MinimumVolumeBox3::P00P10Z01Z11;
mLevelCurveProcessor[0x06] = &MinimumVolumeBox3::M00P10Z01Z11;
mLevelCurveProcessor[0x08] = &MinimumVolumeBox3::Z00M10Z01Z11;
mLevelCurveProcessor[0x09] = &MinimumVolumeBox3::P00M10Z01Z11;
mLevelCurveProcessor[0x0a] = &MinimumVolumeBox3::M00M10Z01Z11;
mLevelCurveProcessor[0x10] = &MinimumVolumeBox3::Z00Z10P01Z11;
mLevelCurveProcessor[0x11] = &MinimumVolumeBox3::P00Z10P01Z11;
mLevelCurveProcessor[0x12] = &MinimumVolumeBox3::M00Z10P01Z11;
mLevelCurveProcessor[0x14] = &MinimumVolumeBox3::Z00P10P01Z11;
mLevelCurveProcessor[0x15] = &MinimumVolumeBox3::P00P10P01Z11;
mLevelCurveProcessor[0x16] = &MinimumVolumeBox3::M00P10P01Z11;
mLevelCurveProcessor[0x18] = &MinimumVolumeBox3::Z00M10P01Z11;
mLevelCurveProcessor[0x19] = &MinimumVolumeBox3::P00M10P01Z11;
mLevelCurveProcessor[0x1a] = &MinimumVolumeBox3::M00M10P01Z11;
mLevelCurveProcessor[0x20] = &MinimumVolumeBox3::Z00Z10M01Z11;
mLevelCurveProcessor[0x21] = &MinimumVolumeBox3::P00Z10M01Z11;
mLevelCurveProcessor[0x22] = &MinimumVolumeBox3::M00Z10M01Z11;
mLevelCurveProcessor[0x24] = &MinimumVolumeBox3::Z00P10M01Z11;
mLevelCurveProcessor[0x25] = &MinimumVolumeBox3::P00P10M01Z11;
mLevelCurveProcessor[0x26] = &MinimumVolumeBox3::M00P10M01Z11;
mLevelCurveProcessor[0x28] = &MinimumVolumeBox3::Z00M10M01Z11;
mLevelCurveProcessor[0x29] = &MinimumVolumeBox3::P00M10M01Z11;
mLevelCurveProcessor[0x2a] = &MinimumVolumeBox3::M00M10M01Z11;
mLevelCurveProcessor[0x40] = &MinimumVolumeBox3::Z00Z10Z01P11;
mLevelCurveProcessor[0x41] = &MinimumVolumeBox3::P00Z10Z01P11;
mLevelCurveProcessor[0x42] = &MinimumVolumeBox3::M00Z10Z01P11;
mLevelCurveProcessor[0x44] = &MinimumVolumeBox3::Z00P10Z01P11;
mLevelCurveProcessor[0x45] = &MinimumVolumeBox3::P00P10Z01P11;
mLevelCurveProcessor[0x46] = &MinimumVolumeBox3::M00P10Z01P11;
mLevelCurveProcessor[0x48] = &MinimumVolumeBox3::Z00M10Z01P11;
mLevelCurveProcessor[0x49] = &MinimumVolumeBox3::P00M10Z01P11;
mLevelCurveProcessor[0x4a] = &MinimumVolumeBox3::M00M10Z01P11;
mLevelCurveProcessor[0x50] = &MinimumVolumeBox3::Z00Z10P01P11;
mLevelCurveProcessor[0x51] = &MinimumVolumeBox3::P00Z10P01P11;
mLevelCurveProcessor[0x52] = &MinimumVolumeBox3::M00Z10P01P11;
mLevelCurveProcessor[0x54] = &MinimumVolumeBox3::Z00P10P01P11;
mLevelCurveProcessor[0x55] = &MinimumVolumeBox3::P00P10P01P11;
mLevelCurveProcessor[0x56] = &MinimumVolumeBox3::M00P10P01P11;
mLevelCurveProcessor[0x58] = &MinimumVolumeBox3::Z00M10P01P11;
mLevelCurveProcessor[0x59] = &MinimumVolumeBox3::P00M10P01P11;
mLevelCurveProcessor[0x5a] = &MinimumVolumeBox3::M00M10P01P11;
mLevelCurveProcessor[0x60] = &MinimumVolumeBox3::Z00Z10M01P11;
mLevelCurveProcessor[0x61] = &MinimumVolumeBox3::P00Z10M01P11;
mLevelCurveProcessor[0x62] = &MinimumVolumeBox3::M00Z10M01P11;
mLevelCurveProcessor[0x64] = &MinimumVolumeBox3::Z00P10M01P11;
mLevelCurveProcessor[0x65] = &MinimumVolumeBox3::P00P10M01P11;
mLevelCurveProcessor[0x66] = &MinimumVolumeBox3::M00P10M01P11;
mLevelCurveProcessor[0x68] = &MinimumVolumeBox3::Z00M10M01P11;
mLevelCurveProcessor[0x69] = &MinimumVolumeBox3::P00M10M01P11;
mLevelCurveProcessor[0x6a] = &MinimumVolumeBox3::M00M10M01P11;
mLevelCurveProcessor[0x80] = &MinimumVolumeBox3::Z00Z10Z01M11;
mLevelCurveProcessor[0x81] = &MinimumVolumeBox3::P00Z10Z01M11;
mLevelCurveProcessor[0x82] = &MinimumVolumeBox3::M00Z10Z01M11;
mLevelCurveProcessor[0x84] = &MinimumVolumeBox3::Z00P10Z01M11;
mLevelCurveProcessor[0x85] = &MinimumVolumeBox3::P00P10Z01M11;
mLevelCurveProcessor[0x86] = &MinimumVolumeBox3::M00P10Z01M11;
mLevelCurveProcessor[0x88] = &MinimumVolumeBox3::Z00M10Z01M11;
mLevelCurveProcessor[0x89] = &MinimumVolumeBox3::P00M10Z01M11;
mLevelCurveProcessor[0x8a] = &MinimumVolumeBox3::M00M10Z01M11;
mLevelCurveProcessor[0x90] = &MinimumVolumeBox3::Z00Z10P01M11;
mLevelCurveProcessor[0x91] = &MinimumVolumeBox3::P00Z10P01M11;
mLevelCurveProcessor[0x92] = &MinimumVolumeBox3::M00Z10P01M11;
mLevelCurveProcessor[0x94] = &MinimumVolumeBox3::Z00P10P01M11;
mLevelCurveProcessor[0x95] = &MinimumVolumeBox3::P00P10P01M11;
mLevelCurveProcessor[0x96] = &MinimumVolumeBox3::M00P10P01M11;
mLevelCurveProcessor[0x98] = &MinimumVolumeBox3::Z00M10P01M11;
mLevelCurveProcessor[0x99] = &MinimumVolumeBox3::P00M10P01M11;
mLevelCurveProcessor[0x9a] = &MinimumVolumeBox3::M00M10P01M11;
mLevelCurveProcessor[0xa0] = &MinimumVolumeBox3::Z00Z10M01M11;
mLevelCurveProcessor[0xa1] = &MinimumVolumeBox3::P00Z10M01M11;
mLevelCurveProcessor[0xa2] = &MinimumVolumeBox3::M00Z10M01M11;
mLevelCurveProcessor[0xa4] = &MinimumVolumeBox3::Z00P10M01M11;
mLevelCurveProcessor[0xa5] = &MinimumVolumeBox3::P00P10M01M11;
mLevelCurveProcessor[0xa6] = &MinimumVolumeBox3::M00P10M01M11;
mLevelCurveProcessor[0xa8] = &MinimumVolumeBox3::Z00M10M01M11;
mLevelCurveProcessor[0xa9] = &MinimumVolumeBox3::P00M10M01M11;
mLevelCurveProcessor[0xaa] = &MinimumVolumeBox3::M00M10M01M11;
}
// The subdivision-based sampling functions.
template <bool useDouble = computeDouble>
typename std::enable_if<useDouble, void>::type
Adjust(VCompute3& normal)
{
Normalize(normal);
}
template <bool useDouble = computeDouble>
typename std::enable_if<!useDouble, void>::type
Adjust(VCompute3&)
{
// Nothing to do when the compute type is rational.
}
void Pair(Candidate& c, Candidate& mvc)
{
ComputeVolume(c);
if (c.volume < mvc.volume)
{
mvc = c;
}
}
// The minimizers for the operator()(maxSample, *) function. The
// default behavior of MinimumVolumeBox3D is to use the built-in
// minimizers that sample the level curves as a simple search for a
// minimum volume. However, you can override the minimizers and
// provide a more sophisticated algorithm.
virtual void MinimizerConstantS(Candidate& c, Candidate& mvc)
{
std::vector<ComputeType> t(mMaxSample + 1);
t[0] = mZero;
t[mMaxSample] = mOne;
for (auto const& item : mDomainIndex)
{
t[item[0]] = mHalf * (t[item[1]] + t[item[2]]);
}
Adjust(c.axis[0]);
for (size_t i = 0, j = mMaxSample; i <= mMaxSample; ++i, --j)
{
c.axis[1] = t[j] * c.M[0] + t[i] * c.M[1];
Adjust(c.axis[1]);
ComputeVolume(c);
if (c.volume < mvc.volume)
{
mvc = c;
}
}
}
virtual void MinimizerConstantT(Candidate& c, Candidate& mvc)
{
std::vector<ComputeType> s(mMaxSample + 1);
s[0] = mZero;
s[mMaxSample] = mOne;
for (auto const& item : mDomainIndex)
{
s[item[0]] = mHalf * (s[item[1]] + s[item[2]]);
}
Adjust(c.axis[1]);
for (size_t i = 0, j = mMaxSample; i <= mMaxSample; ++i, --j)
{
c.axis[0] = s[j] * c.N[0] + s[i] * c.N[1];
Adjust(c.axis[0]);
ComputeVolume(c);
if (c.volume < mvc.volume)
{
mvc = c;
}
}
}
virtual void MinimizerVariableS(ComputeType const& sminNumer,
ComputeType const& smaxNumer, ComputeType const& sDenom,
Candidate& c, Candidate& mvc)
{
std::vector<ComputeType> s(mMaxSample + 1), oms(mMaxSample + 1);
s[0] = sminNumer;
oms[0] = sDenom - sminNumer;
s[mMaxSample] = smaxNumer;
oms[mMaxSample] = sDenom - smaxNumer;
for (auto const& item : mDomainIndex)
{
s[item[0]] = mHalf * (s[item[1]] + s[item[2]]);
oms[item[0]] = mHalf * (oms[item[1]] + oms[item[2]]);
}
for (size_t i = 0; i <= mMaxSample; ++i)
{
c.axis[0] = oms[i] * c.N[0] + s[i] * c.N[1];
Adjust(c.axis[0]);
ComputeType q0 = oms[i] * c.f00 + s[i] * c.f10;
ComputeType q1 = oms[i] * c.f01 + s[i] * c.f11;
if (q0 > q1)
{
c.axis[1] = q0 * c.M[1] - q1 * c.M[0];
}
else
{
c.axis[1] = q1 * c.M[0] - q0 * c.M[1];
}
Adjust(c.axis[1]);
ComputeVolume(c);
if (c.volume < mvc.volume)
{
mvc = c;
}
}
}
virtual void MinimizerVariableT(ComputeType const& tminNumer,
ComputeType const& tmaxNumer, ComputeType const& tDenom,
Candidate& c, Candidate& mvc)
{
std::vector<ComputeType> t(mMaxSample + 1), omt(mMaxSample + 1);
t[0] = tminNumer;
omt[0] = tDenom - tminNumer;
t[mMaxSample] = tmaxNumer;
omt[mMaxSample] = tDenom - tmaxNumer;
for (auto const& item : mDomainIndex)
{
t[item[0]] = mHalf * (t[item[1]] + t[item[2]]);
omt[item[0]] = mHalf * (omt[item[1]] + omt[item[2]]);
}
for (size_t i = 0; i <= mMaxSample; ++i)
{
ComputeType p0 = omt[i] * c.f00 + t[i] * c.f01;
ComputeType p1 = omt[i] * c.f10 + t[i] * c.f11;
if (p0 > p1)
{
c.axis[0] = p0 * c.N[1] - p1 * c.N[0];
}
else
{
c.axis[0] = p1 * c.N[0] - p0 * c.N[1];
}
Adjust(c.axis[0]);
c.axis[1] = omt[i] * c.M[0] + t[i] * c.M[1];
Adjust(c.axis[1]);
ComputeVolume(c);
if (c.volume < mvc.volume)
{
mvc = c;
}
}
}
void Z00Z10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x00
// 0 0
// 0 0
//
// This case occurs when each edge is shared by two coplanar
// faces, so we have only two different normals. The normals
// are perpendicular.
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void P00Z10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x01
// 0 0
// + 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void M00Z10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x02
// 0 0
// - 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void Z00P10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x04
// 0 0
// 0 +
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void P00P10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x05
// 0 0
// + +
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void M00P10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x06
// 0 0
// - +
// tmin = 0, tmax = 1
// s = -f00 / (f10 - f00), (+)/(+)
// 1-s = f10 / (f10 - f00), (+)/(+)
// N = (1-s) * N0 + s * N1, omit denominator
c.axis[0] = c.f10 * c.N[0] - c.f00 * c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void Z00M10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x08
// 0 0
// 0 -
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void P00M10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x09
// 0 0
// + -
// tmin = 0, tmax = 1
// s = f00 / (f00 - f10), (+)/(+)
// 1-s = -f10 / (f00 - f10), (+)/(+)
// N = s * N1 + (1-s) * N0, omit denominator
c.axis[0] = c.f00 * c.N[1] - c.f10 * c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 0, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void M00M10Z01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x0a
// 0 0
// - -
// smin = 0, smax = 1, t = 1
c.axis[1] = c.M[1];
MinimizerConstantT(c, mvc);
}
void Z00Z10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x10
// + 0
// 0 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x11
// + 0
// + 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
}
void M00Z10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x12
// + 0
// - 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1
// t = -f00 / (f01 - f00), (+)/(+)
// 1-t = f01 / (f01 - f00), (+)/(+)
// M = (1-t) * M0 + t * M1, omit denominator
c.axis[1] = c.f01 * c.M[0] - c.f00 * c.M[1];
MinimizerConstantT(c, mvc);
}
void Z00P10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x14
// + 0
// 0 +
// It is not possible for a level curve to connect the corners.
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void P00P10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x15
// + 0
// + +
c.axis[0] = c.N[1];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void M00P10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x16
// + 0
// - +
// smin = 0
// smax = -f00 / (f10 - f00), (+)/(+)
ComputeType f10mf00 = c.f10 - c.f00;
MinimizerVariableS(mZero, -c.f00, f10mf00, c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void Z00M10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x18
// + 0
// 0 -
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void P00M10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x19
// + 0
// + -
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void M00M10P01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x1a
// + 0
// - -
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void Z00Z10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x20
// - 0
// 0 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x21
// - 0
// + 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1
// t = f00 / (f00 - f01), (+)/(+)
// 1-t = -f01 / (f00 - f01), (+)/(+)
// M = t * M1 + (1-t) * M0, omit denominator
c.axis[1] = c.f00 * c.M[1] - c.f01 * c.M[0];
MinimizerConstantT(c, mvc);
}
void M00Z10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x22
// - 0
// - 0
// tmin = 0, tmax = 1, s = 1
c.axis[0] = c.N[1];
MinimizerConstantS(c, mvc);
}
void Z00P10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x24
// - 0
// 0 +
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void P00P10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x25
// - 0
// + +
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void M00P10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x26
// - 0
// - +
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void Z00M10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x28
// - 0
// 0 -
// It is not possible for a level curve to connect the corners.
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void P00M10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x29
// - 0
// + -
// smin = 0
// smax = f00 / (f00 - f10), (+)/(+)
ComputeType f00mf10 = c.f00 - c.f10;
MinimizerVariableS(mZero, c.f00, f00mf10, c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void M00M10M01Z11(Candidate& c, Candidate& mvc)
{
// index = 0x2a
// - 0
// - -
c.axis[0] = c.N[1];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void Z00Z10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x40
// 0 +
// 0 0
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
// smimn = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x41
// 0 +
// + 0
// It is not possible for a level curve to connect the corners.
c.axis[0] = c.N[0];
c.axis[1] = c.M[1];
Pair(c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void M00Z10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x42
// 0 +
// - 0
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void Z00P10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x44
// 0 +
// 0 +
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
}
void P00P10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x45
// 0 +
// + +
c.axis[0] = c.N[0];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void M00P10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x46
// 0 +
// - +
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void Z00M10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x48
// 0 +
// 0 -
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1
// t = -f10 / (f11 - f10), (+)/(+)
// 1-t = f11 / (f11 - f10), (+)/(+)
// M = (1-t) * M0 + t * M1, omit denominator
c.axis[1] = c.f11 * c.M[0] - c.f10 * c.M[1];
MinimizerConstantT(c, mvc);
}
void P00M10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x49
// 0 +
// + -
// smin = f00 / (f00 - f10), (+)/(+)
// smax = 1
ComputeType f00mf10 = c.f00 - c.f10;
MinimizerVariableS(c.f00, f00mf10, f00mf10, c, mvc);
c.axis[0] = c.N[0];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void M00M10Z01P11(Candidate& c, Candidate& mvc)
{
// index = 0x4a
// 0 +
// - -
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void Z00Z10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x50
// + +
// 0 0
// smin = 0, smax = 1, t = 0s
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x51
// + +
// + 0
c.axis[0] = c.N[1];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void M00Z10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x52
// + +
// - 0
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void Z00P10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x54
// + +
// 0 +
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void P00P10P01P11(Candidate&, Candidate&)
{
// index = 0x55
// + +
// + +
// Nothing to do.
}
void M00P10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x56
// + +
// - +
// smin = 0
// smax = -f00 / (f10 - f00), (+)/(+)
ComputeType f10mf00 = c.f10 - c.f00;
MinimizerVariableS(mZero, -c.f00, f10mf00, c, mvc);
}
void Z00M10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x58
// + +
// 0 -
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void P00M10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x59
// + +
// + -
// smin = f00 / (f00 - f10), (+)/(+)
// smax = 1
ComputeType f00mf10 = c.f00 - c.f10;
MinimizerVariableS(c.f00, f00mf10, f00mf10, c, mvc);
}
void M00M10P01P11(Candidate& c, Candidate& mvc)
{
// index = 0x5a
// + +
// - -
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void Z00Z10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x60
// - +
// 0 0
// tmin = 0, tmax = 1
// s = -f01 / (f11 - f01), (+)/(+)
// 1-s = f11 / (f11 - f01), (+)/(+)
// N = (1-s) * N0 + s * N1, omit denominator
c.axis[0] = c.f11 * c.N[0] - c.f01 * c.N[1];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x61
// - +
// + 0
// smin = 0
// smax = -f01 / (f11 - f01), (+)/(+)
ComputeType f11mf01 = c.f11 - c.f01;
MinimizerVariableS(mZero, -c.f01, f11mf01, c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void M00Z10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x62
// - +
// - 0
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void Z00P10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x64
// - +
// 0 +
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void P00P10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x65
// - +
// + +
// smin = 0
// smax = -f01 / (f11 - f01), (+)/(+)
ComputeType f11mf01 = c.f11 - c.f01;
MinimizerVariableS(mZero, -c.f01, f11mf01, c, mvc);
}
void M00P10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x66
// - +
// - +
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void Z00M10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x68
// - +
// 0 -
// smin = -f01 / (f11 - f01), (+)/(+)
// smax = 1
ComputeType f11mf01 = c.f11 - c.f01;
MinimizerVariableS(-c.f01, f11mf01, f11mf01, c, mvc);
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void P00M10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x69
// - +
// + -
//
// The level set F = 0 has two hyperbolic curves, each formed by a
// pair of endpoints in {(0,t0), (s0,0), (s1,1), (1,t1)}, where
// s0 = -f00 / (f10 - f00), s1 = -f01 / (f11 - f01),
// t0 = -f00 / (f01 - f00), t1 = -f10 / (f11 - f10), all quantites
// in (0,1). The two curves are on opposite sides of the
// asymptotes
// sa = (f01 - f00) / ((f01 - f00) + (f10 - f11))
// ta = (f10 - f00) / ((f10 - f00) + (f01 - f11))
// If s0 < sa, one curve has endpoints {(0,t0),(s0,0)} and the
// other curve has endpoints {(s1,1),(1,t1)}. If s0 > sa, one
// curve has endpoints {(0,t0),(s1,1)} and the other curve has
// endpoints {(s0,0),(1,t1)}. If s0 = sa, then segments of the
// asymptotes are the two curves for the level set. Define
// d = f00 * f11 - f10 * f01. It can be shown that
// s0 - sa = d / ((f10 - f00)((f10 - f00) + (f01 - f11))
// The denominator is positive, so sign(s0 - sa) = sign(d). A
// similar argument applies for the comparison between t0 and ta.
ComputeType d = c.f00 * c.f11 - c.f10 * c.f01;
if (d > mZero)
{
// endpoints (s0,0) and (1,t1)
// smin = f00 / (f00 - f10), (+)/(+)
// smax = 1
ComputeType f00mf10 = c.f00 - c.f10;
MinimizerVariableS(c.f00, f00mf10, f00mf10, c, mvc);
// endpoints (0,t0) and (s1,1)
// smin = 0
// smax = -f01 / (f11 - f01), (+)/(+)
ComputeType f11mf01 = c.f11 - c.f01;
MinimizerVariableS(mZero, -c.f01, f11mf01, c, mvc);
}
else if (d < mZero)
{
// endpoints (0,t0) and (s0,0)
// smin = 0
// smax = f00 / (f00 - f10), (+)/(+)
ComputeType f00mf10 = c.f00 - c.f10;
MinimizerVariableS(mZero, c.f00, f00mf10, c, mvc);
// endpoints (s1,1) and (1,t1)
// smin = -f01 / (f11 - f01), (+)/(+)
// smax = 1
ComputeType f11mf01 = c.f11 - c.f01;
MinimizerVariableS(-c.f01, f11mf01, f11mf01, c, mvc);
}
else
{
// endpoints (sa,0) and (sa,1)
// sa = (f00 - f01) / ((f00 - f01) + (f11 - f10)), (+)/(+)
// 1-sa = (f11 - f10) / ((f00 - f01) + (f11 - f10)), (+)/(+)
// N = (1-sa) * N0 + sa * N1, omit the denominator
c.axis[0] = (c.f11 - c.f10) * c.N[0] + (c.f00 - c.f01) * c.N[1];
MinimizerConstantS(c, mvc);
// endpoints (0,ta) and (1,ta)
// ta = (f00 - f10) / ((f00 - f10) + (f11 - f01)), (+)/(+)
// 1-ta = (f11 - f01) / ((f00 - f01) + (f11 - f01)), (+)/(+)
// M = (1-ta) * M0 + ta * M1, omit the denominator
c.axis[1] = (c.f11 - c.f01) * c.M[0] + (c.f00 - c.f10) * c.M[1];
MinimizerConstantT(c, mvc);
}
}
void M00M10M01P11(Candidate& c, Candidate& mvc)
{
// index = 0x6a
// - +
// - -
// smin = -f01 / (f11 - f01), (+)/(+)
// smax = 1
ComputeType f11mf01 = c.f11 - c.f01;
MinimizerVariableS(-c.f01, f11mf01, f11mf01, c, mvc);
}
void Z00Z10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x80
// 0 -
// 0 0
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x81
// 0 -
// + 0
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void M00Z10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x82
// 0 -
// - 0
// It is not possible for a level curve to connect the corners.
c.axis[0] = c.N[0];
c.axis[1] = c.M[1];
Pair(c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void Z00P10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x84
// 0 -
// 0 +
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1
// t = f10 / (f10 - f11), (+)/(+)
// 1-t = -f11 / (f10 - f11), (+)/(+)
// M = t * M1 + (1-t) * M0, omit the denominator
c.axis[1] = c.f10 * c.M[1] - c.f11 * c.M[0];
MinimizerConstantT(c, mvc);
}
void P00P10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x85
// 0 -
// + +
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void M00P10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x86
// 0 -
// - +
// smin = -f00 / (f10 - f00), (+)/(+)
// smax = 1
ComputeType f10mf00 = c.f10 - c.f00;
MinimizerVariableS(-c.f00, f10mf00, f10mf00, c, mvc);
}
void Z00M10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x88
// 0 -
// 0 -
// tmin = 0, tmax = 1, s = 0
c.axis[0] = c.N[0];
MinimizerConstantS(c, mvc);
}
void P00M10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x89
// 0 -
// + -
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void M00M10Z01M11(Candidate& c, Candidate& mvc)
{
// index = 0x8a
// 0 -
// - -
c.axis[0] = c.N[0];
c.axis[1] = c.M[1];
Pair(c, mvc);
}
void Z00Z10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x90
// + -
// 0 0
// tmin = 0, tmax = 1
// s = f01 / (f01 - f11), (+)/(+)
// 1-s = -f11 / (f01 - f11), (+)/(+)
// N = s * N1 + (1-s) * N0, omit the denominator
c.axis[0] = c.f01 * c.N[1] - c.f11 * c.N[0];
MinimizerConstantS(c, mvc);
// smin = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x91
// + -
// + 0
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void M00Z10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x92
// + -
// - 0
// smin = 0
// smax = f01 / (f01 - f11), (+)/(+)
ComputeType f01mf11 = c.f01 - c.f11;
MinimizerVariableS(mZero, c.f01, f01mf11, c, mvc);
c.axis[0] = c.N[1];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void Z00P10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x94
// + -
// 0 +
// smin = f01 / (f01 - f11), (+)/(+)
// smax = 1
ComputeType f01mf11 = c.f01 - c.f11;
MinimizerVariableS(c.f01, f01mf11, f01mf11, c, mvc);
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void P00P10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x95
// + -
// + +
// smin = f01 / (f01 - f11), (+)/(+)
// smax = 1
ComputeType f01mf11 = c.f01 - c.f11;
MinimizerVariableS(c.f01, f01mf11, f01mf11, c, mvc);
}
void M00P10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x96
// + -
// - +
//
// The level set F = 0 has two hyperbolic curves, each formed by a
// pair of endpoints in {(0,t0), (s0,0), (s1,1), (1,t1)}, where
// s0 = -f00 / (f10 - f00), s1 = -f01 / (f11 - f01),
// t0 = -f00 / (f01 - f00), t1 = -f10 / (f11 - f10), all quantites
// in (0,1). The two curves are on opposite sides of the
// asymptotes
// sa = (f01 - f00) / ((f01 - f00) + (f10 - f11))
// ta = (f10 - f00) / ((f10 - f00) + (f01 - f11))
// If s0 < sa, one curve has endpoints {(0,t0),(s0,0)} and the
// other curve has endpoints {(s1,1),(1,t1)}. If s0 > sa, one
// curve has endpoints {(0,t0),(s1,1)} and the other curve has
// endpoints {(s0,0),(1,t1)}. If s0 = sa, then segments of the
// asymptotes are the two curves for the level set. Define
// d = f00 * f11 - f10 * f01. It can be shown that
// s0 - sa = d / ((f10 - f00)((f10 - f00) + (f01 - f11))
// The denominator is positive, so sign(s0 - sa) = sign(d). A
// similar argument applies for the comparison between t0 and ta.
ComputeType d = c.f00 * c.f11 - c.f10 * c.f01;
if (d > mZero)
{
// endpoints (s0,0) and (1,t1)
// smin = -f00 / (f10 - f00), (+)/(+)
// smax = 1
ComputeType f10mf00 = c.f10 - c.f00;
MinimizerVariableS(-c.f00, f10mf00, f10mf00, c, mvc);
// endpoints (0,t0) and (s1,1)
// smin = 0
// smax = f01 / (f01 - f11)
ComputeType f01mf11 = c.f01 - c.f11;
MinimizerVariableS(mZero, c.f01, f01mf11, c, mvc);
}
else if (d < mZero)
{
// endpoints (0,t0) and (s0,0)
// smin = 0
// smax = -f00 / (f10- f00), (+)/(+)
ComputeType f10mf00 = c.f10 - c.f00;
MinimizerVariableS(mZero, -c.f00, f10mf00, c, mvc);
// endpoints (s1,1) and (1,t1)
// smin = f01 / (f01 - f11), (+)/(+)
// smax = 1
ComputeType f01mf11 = c.f01 - c.f11;
MinimizerVariableS(c.f01, f01mf11, f01mf11, c, mvc);
}
else
{
// endpoints (sa,0) and (sa,1)
// sa = (f01 - f00) / ((f01 - f00) + (f10 - f11)), (+)/(+)
// 1-sa = (f10 - f11) / ((f01 - f00) + (f10 - f11)), (+)/(+)
// N = (1-sa) * N0 + s1* N1
c.axis[0] = (c.f10 - c.f11) * c.N[0] + (c.f01 - c.f00) * c.N[1];
MinimizerConstantS(c, mvc);
// endpoints (0,ta) and (1,ta)
// ta = (f10 - f00) / ((f10 - f00) + (f01 - f11)), (+)/(+)
// 1-ta = (f01 - f11) / ((f10 - f00) + (f01 - f11)), (+)/(+)
// M = (1-ta) * M0 + ta * M1, omit the denominator
c.axis[1] = (c.f01 - c.f11) * c.M[0] + (c.f10 - c.f00) * c.M[1];
MinimizerConstantT(c, mvc);
}
}
void Z00M10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x98
// + -
// 0 -
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void P00M10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x99
// + -
// + -
// tmin = 0, tmax = 1
MinimizerVariableT(mZero, mOne, mOne, c, mvc);
}
void M00M10P01M11(Candidate& c, Candidate& mvc)
{
// index = 0x9a
// + -
// - -
// smin = 0
// smax = f01 / (f01 - f11), (+)/(+)
ComputeType f01mf11 = c.f01 - c.f11;
MinimizerVariableS(mZero, c.f01, f01mf11, c, mvc);
}
void Z00Z10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa0
// - -
// 0 0
// smin = 0, smax = 1, t = 0
c.axis[1] = c.M[0];
MinimizerConstantT(c, mvc);
}
void P00Z10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa1
// - -
// + 0
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void M00Z10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa2
// - -
// - 0
c.axis[0] = c.N[1];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void Z00P10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa4
// - -
// 0 +
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void P00P10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa5
// - -
// + +
// smin = 0, smax = 1
MinimizerVariableS(mZero, mOne, mOne, c, mvc);
}
void M00P10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa6
// - -
// - +
// smin = -f00 / (f10 - f00), (+)/(+)
// smax = 1
ComputeType f10mf00 = c.f10 - c.f00;
MinimizerVariableS(-c.f00, f10mf00, f10mf00, c, mvc);
}
void Z00M10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa8
// - -
// 0 -
c.axis[0] = c.N[0];
c.axis[1] = c.M[0];
Pair(c, mvc);
}
void P00M10M01M11(Candidate& c, Candidate& mvc)
{
// index = 0xa9
// - -
// + -
// smin = 0
// smax = f00 / (f00 - f10), (+)/(+)
ComputeType f00mf10 = c.f00 - c.f10;
MinimizerVariableS(mZero, c.f00, f00mf10, c, mvc);
}
void M00M10M01M11(Candidate&, Candidate&)
{
// index = 0xaa
// - -
// - -
// Nothing to do.
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrRay3Sphere3.h | .h | 4,186 | 134 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/IntrIntervals.h>
#include <Mathematics/IntrLine3Sphere3.h>
#include <Mathematics/Ray.h>
// The queries consider the sphere to be a solid.
//
// The sphere is (X-C)^T*(X-C)-r^2 = 0 and the ray is X = P+t*D for t >= 0.
// Substitute the ray equation into the sphere equation to obtain a quadratic
// equation Q(t) = t^2 + 2*a1*t + a0 = 0, where a1 = D^T*(P-C) and
// a0 = (P-C)^T*(P-C)-r^2. The algorithm involves an analysis of the
// real-valued roots of Q(t) for t >= 0.
namespace gte
{
template <typename T>
class TIQuery<T, Ray3<T>, Sphere3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Ray3<T> const& ray, Sphere3<T> const& sphere)
{
Result result{};
T const zero = static_cast<T>(0);
Vector3<T> diff = ray.origin - sphere.center;
T a0 = Dot(diff, diff) - sphere.radius * sphere.radius;
if (a0 <= zero)
{
// P is inside the sphere.
result.intersect = true;
return result;
}
// else: P is outside the sphere
T a1 = Dot(ray.direction, diff);
if (a1 >= zero)
{
result.intersect = false;
return result;
}
// Intersection occurs when Q(t) has real roots.
T discr = a1 * a1 - a0;
result.intersect = (discr >= zero);
return result;
}
};
template <typename T>
class FIQuery<T, Ray3<T>, Sphere3<T>>
:
public FIQuery<T, Line3<T>, Sphere3<T>>
{
public:
struct Result
:
public FIQuery<T, Line3<T>, Sphere3<T>>::Result
{
Result()
:
FIQuery<T, Line3<T>, Sphere3<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray3<T> const& ray, Sphere3<T> const& sphere)
{
Result result{};
DoQuery(ray.origin, ray.direction, sphere, result);
if (result.intersect)
{
for (size_t i = 0; i < 2; ++i)
{
result.point[i] = ray.origin + result.parameter[i] * ray.direction;
}
}
return result;
}
protected:
// The caller must ensure that on entry, 'result' is default
// constructed as if there is no intersection. If an intersection is
// found, the 'result' values will be modified accordingly.
void DoQuery(Vector3<T> const& rayOrigin,
Vector3<T> const& rayDirection, Sphere3<T> const& sphere,
Result& result)
{
FIQuery<T, Line3<T>, Sphere3<T>>::DoQuery(
rayOrigin, rayDirection, sphere, result);
if (result.intersect)
{
// The line containing the ray intersects the sphere; the
// t-interval is [t0,t1]. The ray intersects the sphere as
// long as [t0,t1] overlaps the ray t-interval [0,+infinity).
FIQuery<T, std::array<T, 2>, std::array<T, 2>> iiQuery{};
auto iiResult = iiQuery(result.parameter, static_cast<T>(0), true);
if (iiResult.intersect)
{
result.numIntersections = iiResult.numIntersections;
result.parameter = iiResult.overlap;
}
else
{
// The line containing the ray does not intersect the
// sphere.
result = Result{};
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrAlignedBox2OrientedBox2.h | .h | 3,572 | 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/FIQuery.h>
#include <Mathematics/TIQuery.h>
#include <Mathematics/AlignedBox.h>
#include <Mathematics/OrientedBox.h>
#include <Mathematics/Vector2.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 2 edge normals
// of box0 and the 2 edge normals of box1. The integer 'separating'
// identifies the axis that reported separation; there may be more than one
// but only one is reported. The value is 0 when box0.axis[0] separates,
// 1 when box0.axis[1] separates, 2 when box1.axis[0] separates, or 3 when
// box1.axis[1] separates.
namespace gte
{
template <typename T>
class TIQuery<T, AlignedBox2<T>, OrientedBox2<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
separating(0)
{
}
bool intersect;
int32_t separating;
};
Result operator()(AlignedBox2<T> const& box0, OrientedBox2<T> const& box1)
{
Result result{};
// Get the centered form of the aligned box. The axes are
// implicitly A0[0] = (1,0) and A0[1] = (0,1).
Vector2<T> C0, E0;
box0.GetCenteredForm(C0, E0);
// Convenience variables.
Vector2<T> const& C1 = box1.center;
Vector2<T> const* A1 = &box1.axis[0];
Vector2<T> const& E1 = box1.extent;
// Compute difference of box centers.
Vector2<T> D = C1 - C0;
std::array<std::array<T, 2>, 2> absDot01{};
T rSum{};
// Test box0.axis[0] = (1,0).
absDot01[0][0] = std::fabs(A1[0][0]);
absDot01[0][1] = std::fabs(A1[1][0]);
rSum = E0[0] + E1[0] * absDot01[0][0] + E1[1] * absDot01[0][1];
if (std::fabs(D[0]) > rSum)
{
result.intersect = false;
result.separating = 0;
return result;
}
// Test axis box0.axis[1] = (0,1).
absDot01[1][0] = std::fabs(A1[0][1]);
absDot01[1][1] = std::fabs(A1[1][1]);
rSum = E0[1] + E1[0] * absDot01[1][0] + E1[1] * absDot01[1][1];
if (std::fabs(D[1]) > rSum)
{
result.intersect = false;
result.separating = 1;
return result;
}
// Test axis box1.axis[0].
rSum = E1[0] + E0[0] * absDot01[0][0] + E0[1] * absDot01[1][0];
if (std::fabs(Dot(A1[0], D)) > rSum)
{
result.intersect = false;
result.separating = 2;
return result;
}
// Test axis box1.axis[1].
rSum = E1[1] + E0[0] * absDot01[0][1] + E0[1] * absDot01[1][1];
if (std::fabs(Dot(A1[1], D)) > rSum)
{
result.intersect = false;
result.separating = 3;
return result;
}
result.intersect = true;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/MinimalCycleBasis.h | .h | 26,906 | 682 | // 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/MinHeap.h>
#include <array>
#include <map>
#include <memory>
#include <set>
#include <stack>
// Extract the minimal cycle basis for a planar graph. The input vertices and
// edges must form a graph for which edges intersect only at vertices; that is,
// no two edges must intersect at an interior point of one of the edges. The
// algorithm is described in
// https://www.geometrictools.com/Documentation/MinimalCycleBasis.pdf
// The graph might have filaments, which are polylines in the graph that are
// not shared by a cycle. These are also extracted by the implementation.
// Because the inputs to the constructor are vertices and edges of the graph,
// isolated vertices are ignored.
//
// The computations that determine which adjacent vertex to visit next during
// a filament or cycle traversal do not require division, so the exact
// arithmetic type BSNumber<UIntegerAP32> suffices for ComputeType when you
// want to ensure a correct output. (Floating-point rounding errors
// potentially can lead to an incorrect output.)
namespace gte
{
template <typename Real>
class MinimalCycleBasis
{
public:
struct Tree
{
std::vector<int32_t> cycle;
std::vector<std::shared_ptr<Tree>> children;
};
// The input positions and edges must form a planar graph for which
// edges intersect only at vertices; that is, no two edges must
// intersect at an interior point of one of the edges.
MinimalCycleBasis(
std::vector<std::array<Real, 2>> const& positions,
std::vector<std::array<int32_t, 2>> const& edges,
std::vector<std::shared_ptr<Tree>>& forest)
{
forest.clear();
if (positions.size() == 0 || edges.size() == 0)
{
// The graph is empty, so there are no filaments or cycles.
return;
}
// Determine the unique positions referenced by the edges.
std::map<int32_t, std::shared_ptr<Vertex>> unique;
for (auto const& edge : edges)
{
for (int32_t i = 0; i < 2; ++i)
{
int32_t name = edge[i];
if (unique.find(name) == unique.end())
{
auto vertex = std::make_shared<Vertex>(name, &positions[name]);
unique.insert(std::make_pair(name, vertex));
}
}
}
// Assign responsibility for ownership of the Vertex objects.
std::vector<Vertex*> vertices;
mVertexStorage.reserve(unique.size());
vertices.reserve(unique.size());
for (auto const& element : unique)
{
mVertexStorage.push_back(element.second);
vertices.push_back(element.second.get());
}
// Determine the adjacencies from the edge information.
for (auto const& edge : edges)
{
auto iter0 = unique.find(edge[0]);
auto iter1 = unique.find(edge[1]);
iter0->second->adjacent.insert(iter1->second.get());
iter1->second->adjacent.insert(iter0->second.get());
}
// Get the connected components of the graph. The 'visited' flags
// are 0 (unvisited), 1 (discovered), 2 (finished). The Vertex
// constructor sets all 'visited' flags to 0.
std::vector<std::vector<Vertex*>> components;
for (auto vInitial : mVertexStorage)
{
if (vInitial->visited == 0)
{
components.push_back(std::vector<Vertex*>());
DepthFirstSearch(vInitial.get(), components.back());
}
}
// The depth-first search is used later for collecting vertices
// for subgraphs that are detached from the main graph, so the
// 'visited' flags must be reset to zero after component finding.
for (auto vertex : mVertexStorage)
{
vertex->visited = 0;
}
// Get the primitives for the components.
for (auto& component : components)
{
forest.push_back(ExtractBasis(component));
}
}
// No copy or assignment allowed.
MinimalCycleBasis(MinimalCycleBasis const&) = delete;
MinimalCycleBasis& operator=(MinimalCycleBasis const&) = delete;
private:
struct Vertex
{
Vertex(int32_t inName, std::array<Real, 2> const* inPosition)
:
name(inName),
position(inPosition),
visited(0)
{
}
bool operator< (Vertex const& vertex) const
{
return name < vertex.name;
}
// The index into the 'positions' input provided to the call to
// operator(). The index is used when reporting cycles to the
// caller of the constructor for MinimalCycleBasis.
int32_t name;
// Multiple vertices can share a position during processing of
// graph components.
std::array<Real, 2> const* position;
// The mVertexStorage member owns the Vertex objects and maintains
// the reference counts on those objects. The adjacent pointers
// are considered to be weak pointers; neither object ownership
// nor reference counting is required by 'adjacent'.
std::set<Vertex*> adjacent;
// Support for depth-first traversal of a graph.
int32_t visited;
};
// The constructor uses GetComponents(...) and DepthFirstSearch(...)
// to get the connected components of the graph implied by the input
// 'edges'. Recursive processing uses only DepthFirstSearch(...) to
// collect vertices of the subgraphs of the original graph.
static void DepthFirstSearch(Vertex* vInitial, std::vector<Vertex*>& component)
{
std::stack<Vertex*> vStack;
vStack.push(vInitial);
while (vStack.size() > 0)
{
Vertex* vertex = vStack.top();
vertex->visited = 1;
size_t i = 0;
for (auto adjacent : vertex->adjacent)
{
if (adjacent && adjacent->visited == 0)
{
vStack.push(adjacent);
break;
}
++i;
}
if (i == vertex->adjacent.size())
{
vertex->visited = 2;
component.push_back(vertex);
vStack.pop();
}
}
}
// Support for traversing a simply connected component of the graph.
std::shared_ptr<Tree> ExtractBasis(std::vector<Vertex*>& component)
{
// The root will not have its 'cycle' member set. The children
// are the cycle trees extracted from the component.
auto tree = std::make_shared<Tree>();
while (component.size() > 0)
{
RemoveFilaments(component);
if (component.size() > 0)
{
tree->children.push_back(ExtractCycleFromComponent(component));
}
}
if (tree->cycle.size() == 0 && tree->children.size() == 1)
{
// Replace the parent by the child to avoid having two empty
// cycles in parent/child.
auto child = tree->children.back();
tree->cycle = std::move(child->cycle);
tree->children = std::move(child->children);
}
return tree;
}
void RemoveFilaments(std::vector<Vertex*>& component)
{
// Locate all filament endpoints, which are vertices, each having
// exactly one adjacent vertex.
std::vector<Vertex*> endpoints;
for (auto vertex : component)
{
if (vertex->adjacent.size() == 1)
{
endpoints.push_back(vertex);
}
}
if (endpoints.size() > 0)
{
// Remove the filaments from the component. If a filament has
// two endpoints, each having one adjacent vertex, the
// adjacency set of the final visited vertex become empty.
// We must test for that condition before starting a new
// filament removal.
for (auto vertex : endpoints)
{
if (vertex->adjacent.size() == 1)
{
// Traverse the filament and remove the vertices.
while (vertex->adjacent.size() == 1)
{
// Break the connection between the two vertices.
Vertex* adjacent = *vertex->adjacent.begin();
adjacent->adjacent.erase(vertex);
vertex->adjacent.erase(adjacent);
// Traverse to the adjacent vertex.
vertex = adjacent;
}
}
}
// At this time the component is either empty (it was a union
// of polylines) or it has no filaments and at least one
// cycle. Remove the isolated vertices generated by filament
// extraction.
std::vector<Vertex*> remaining;
remaining.reserve(component.size());
for (auto vertex : component)
{
if (vertex->adjacent.size() > 0)
{
remaining.push_back(vertex);
}
}
component = std::move(remaining);
}
}
std::shared_ptr<Tree> ExtractCycleFromComponent(std::vector<Vertex*>& component)
{
// Search for the left-most vertex of the component. If two or
// more vertices attain minimum x-value, select the one that has
// minimum y-value.
Vertex* minVertex = component[0];
for (auto vertex : component)
{
if (*vertex->position < *minVertex->position)
{
minVertex = vertex;
}
}
// Traverse the closed walk, duplicating the starting vertex as
// the last vertex.
std::vector<Vertex*> closedWalk;
Vertex* vCurr = minVertex;
Vertex* vStart = vCurr;
closedWalk.push_back(vStart);
Vertex* vAdj = GetClockwiseMost(nullptr, vStart);
while (vAdj != vStart)
{
closedWalk.push_back(vAdj);
Vertex* vNext = GetCounterclockwiseMost(vCurr, vAdj);
vCurr = vAdj;
vAdj = vNext;
}
closedWalk.push_back(vStart);
// Recursively process the closed walk to extract cycles.
auto tree = ExtractCycleFromClosedWalk(closedWalk);
// The isolated vertices generated by cycle removal are also
// removed from the component.
std::vector<Vertex*> remaining;
remaining.reserve(component.size());
for (auto vertex : component)
{
if (vertex->adjacent.size() > 0)
{
remaining.push_back(vertex);
}
}
component = std::move(remaining);
return tree;
}
std::shared_ptr<Tree> ExtractCycleFromClosedWalk(std::vector<Vertex*>& closedWalk)
{
auto tree = std::make_shared<Tree>();
std::map<Vertex*, int32_t> duplicates;
std::set<int32_t> detachments;
int32_t numClosedWalk = static_cast<int32_t>(closedWalk.size());
for (int32_t i = 1; i < numClosedWalk - 1; ++i)
{
auto diter = duplicates.find(closedWalk[i]);
if (diter == duplicates.end())
{
// We have not yet visited this vertex.
duplicates.insert(std::make_pair(closedWalk[i], i));
continue;
}
// The vertex has been visited previously. Collapse the
// closed walk by removing the subwalk sharing this vertex.
// Note that the vertex is pointed to by
// closedWalk[diter->second] and closedWalk[i].
int32_t iMin = diter->second, iMax = i;
detachments.insert(iMin);
for (int32_t j = iMin + 1; j < iMax; ++j)
{
Vertex* vertex = closedWalk[j];
duplicates.erase(vertex);
detachments.erase(j);
}
closedWalk.erase(closedWalk.begin() + iMin + 1, closedWalk.begin() + iMax + 1);
numClosedWalk = static_cast<int32_t>(closedWalk.size());
i = iMin;
}
if (numClosedWalk > 3)
{
// We do not know whether closedWalk[0] is a detachment point.
// To determine this, we must test for any edges strictly
// contained by the wedge formed by the edges
// <closedWalk[0],closedWalk[N-1]> and
// <closedWalk[0],closedWalk[1]>. However, we must execute
// this test even for the known detachment points. The
// ensuing logic is designed to handle this and reduce the
// amount of code, so we insert closedWalk[0] into the
// detachment set and will ignore it later if it actually
// is not.
detachments.insert(0);
// Detach subgraphs from the vertices of the cycle.
for (auto i : detachments)
{
Vertex* original = closedWalk[i];
Vertex* maxVertex = closedWalk[static_cast<size_t>(i) + 1];
Vertex* minVertex = (i > 0 ? closedWalk[static_cast<size_t>(i) - 1] : closedWalk[static_cast<size_t>(numClosedWalk) - 2]);
std::array<Real, 2> dMin, dMax;
for (int32_t j = 0; j < 2; ++j)
{
dMin[j] = (*minVertex->position)[j] - (*original->position)[j];
dMax[j] = (*maxVertex->position)[j] - (*original->position)[j];
}
// For debugging.
bool isConvex = (dMax[0] * dMin[1] >= dMax[1] * dMin[0]);
(void)isConvex;
std::set<Vertex*> inWedge;
std::set<Vertex*> adjacent = original->adjacent;
for (auto vertex : adjacent)
{
if (vertex->name == minVertex->name || vertex->name == maxVertex->name)
{
continue;
}
std::array<Real, 2> dVer;
for (int32_t j = 0; j < 2; ++j)
{
dVer[j] = (*vertex->position)[j] - (*original->position)[j];
}
bool containsVertex;
if (isConvex)
{
containsVertex =
dVer[0] * dMin[1] > dVer[1] * dMin[0] &&
dVer[0] * dMax[1] < dVer[1] * dMax[0];
}
else
{
containsVertex =
(dVer[0] * dMin[1] > dVer[1] * dMin[0]) ||
(dVer[0] * dMax[1] < dVer[1] * dMax[0]);
}
if (containsVertex)
{
inWedge.insert(vertex);
}
}
if (inWedge.size() > 0)
{
// The clone will manage the adjacents for 'original'
// that lie inside the wedge defined by the first and
// last edges of the subgraph rooted at 'original'.
// The sorting is in the clockwise direction.
auto clone = std::make_shared<Vertex>(original->name, original->position);
mVertexStorage.push_back(clone);
// Detach the edges inside the wedge.
for (auto vertex : inWedge)
{
original->adjacent.erase(vertex);
vertex->adjacent.erase(original);
clone->adjacent.insert(vertex);
vertex->adjacent.insert(clone.get());
}
// Get the subgraph (it is a single connected
// component).
std::vector<Vertex*> component;
DepthFirstSearch(clone.get(), component);
// Extract the cycles of the subgraph.
tree->children.push_back(ExtractBasis(component));
}
// else the candidate was closedWalk[0] and it has no
// subgraph to detach.
}
tree->cycle = std::move(ExtractCycle(closedWalk));
}
else
{
// Detach the subgraph from vertex closedWalk[0]; the subgraph
// is attached via a filament.
Vertex* original = closedWalk[0];
Vertex* adjacent = closedWalk[1];
auto clone = std::make_shared<Vertex>(original->name, original->position);
mVertexStorage.push_back(clone);
original->adjacent.erase(adjacent);
adjacent->adjacent.erase(original);
clone->adjacent.insert(adjacent);
adjacent->adjacent.insert(clone.get());
// Get the subgraph (it is a single connected component).
std::vector<Vertex*> component;
DepthFirstSearch(clone.get(), component);
// Extract the cycles of the subgraph.
tree->children.push_back(ExtractBasis(component));
if (tree->cycle.size() == 0 && tree->children.size() == 1)
{
// Replace the parent by the child to avoid having two
// empty cycles in parent/child.
auto child = tree->children.back();
tree->cycle = std::move(child->cycle);
tree->children = std::move(child->children);
}
}
return tree;
}
std::vector<int32_t> ExtractCycle(std::vector<Vertex*>& closedWalk)
{
// TODO: This logic was designed not to remove filaments after
// the cycle deletion is complete. Modify this to allow filament
// removal.
// The closed walk is a cycle.
int32_t const numVertices = static_cast<int32_t>(closedWalk.size());
std::vector<int32_t> cycle(numVertices);
for (int32_t i = 0; i < numVertices; ++i)
{
cycle[i] = closedWalk[i]->name;
}
// The clockwise-most edge is always removable.
Vertex* v0 = closedWalk[0];
Vertex* v1 = closedWalk[1];
Vertex* vBranch = (v0->adjacent.size() > 2 ? v0 : nullptr);
v0->adjacent.erase(v1);
v1->adjacent.erase(v0);
// Remove edges while traversing counterclockwise.
while (v1 != vBranch && v1->adjacent.size() == 1)
{
Vertex* adj = *v1->adjacent.begin();
v1->adjacent.erase(adj);
adj->adjacent.erase(v1);
v1 = adj;
}
if (v1 != v0)
{
// If v1 had exactly 3 adjacent vertices, removal of the CCW
// edge that shared v1 leads to v1 having 2 adjacent vertices.
// When the CW removal occurs and we reach v1, the edge
// deletion will lead to v1 having 1 adjacent vertex, making
// it a filament endpoint. We must ensure we do not delete v1
// in this case, allowing the recursive algorithm to handle
// the filament later.
vBranch = v1;
// Remove edges while traversing clockwise.
while (v0 != vBranch && v0->adjacent.size() == 1)
{
v1 = *v0->adjacent.begin();
v0->adjacent.erase(v1);
v1->adjacent.erase(v0);
v0 = v1;
}
}
// else the cycle is its own connected component.
return cycle;
}
Vertex* GetClockwiseMost(Vertex* vPrev, Vertex* vCurr) const
{
Vertex* vNext = nullptr;
bool vCurrConvex = false;
std::array<Real, 2> dCurr, dNext;
if (vPrev)
{
dCurr[0] = (*vCurr->position)[0] - (*vPrev->position)[0];
dCurr[1] = (*vCurr->position)[1] - (*vPrev->position)[1];
}
else
{
dCurr[0] = static_cast<Real>(0);
dCurr[1] = static_cast<Real>(-1);
}
for (auto vAdj : vCurr->adjacent)
{
// vAdj is a vertex adjacent to vCurr. No backtracking is
// allowed.
if (vAdj == vPrev)
{
continue;
}
// Compute the potential direction to move in.
std::array<Real, 2> dAdj;
dAdj[0] = (*vAdj->position)[0] - (*vCurr->position)[0];
dAdj[1] = (*vAdj->position)[1] - (*vCurr->position)[1];
// Select the first candidate.
if (!vNext)
{
vNext = vAdj;
dNext = dAdj;
vCurrConvex = (dNext[0] * dCurr[1] <= dNext[1] * dCurr[0]);
continue;
}
// Update if the next candidate is clockwise of the current
// clockwise-most vertex.
if (vCurrConvex)
{
if (dCurr[0] * dAdj[1] < dCurr[1] * dAdj[0]
|| dNext[0] * dAdj[1] < dNext[1] * dAdj[0])
{
vNext = vAdj;
dNext = dAdj;
vCurrConvex = (dNext[0] * dCurr[1] <= dNext[1] * dCurr[0]);
}
}
else
{
if (dCurr[0] * dAdj[1] < dCurr[1] * dAdj[0]
&& dNext[0] * dAdj[1] < dNext[1] * dAdj[0])
{
vNext = vAdj;
dNext = dAdj;
vCurrConvex = (dNext[0] * dCurr[1] < dNext[1] * dCurr[0]);
}
}
}
return vNext;
}
Vertex* GetCounterclockwiseMost(Vertex* vPrev, Vertex* vCurr) const
{
Vertex* vNext = nullptr;
bool vCurrConvex = false;
std::array<Real, 2> dCurr, dNext;
if (vPrev)
{
dCurr[0] = (*vCurr->position)[0] - (*vPrev->position)[0];
dCurr[1] = (*vCurr->position)[1] - (*vPrev->position)[1];
}
else
{
dCurr[0] = static_cast<Real>(0);
dCurr[1] = static_cast<Real>(-1);
}
for (auto vAdj : vCurr->adjacent)
{
// vAdj is a vertex adjacent to vCurr. No backtracking is
// allowed.
if (vAdj == vPrev)
{
continue;
}
// Compute the potential direction to move in.
std::array<Real, 2> dAdj;
dAdj[0] = (*vAdj->position)[0] - (*vCurr->position)[0];
dAdj[1] = (*vAdj->position)[1] - (*vCurr->position)[1];
// Select the first candidate.
if (!vNext)
{
vNext = vAdj;
dNext = dAdj;
vCurrConvex = (dNext[0] * dCurr[1] <= dNext[1] * dCurr[0]);
continue;
}
// Select the next candidate if it is counterclockwise of the
// current counterclockwise-most vertex.
if (vCurrConvex)
{
if (dCurr[0] * dAdj[1] > dCurr[1] * dAdj[0]
&& dNext[0] * dAdj[1] > dNext[1] * dAdj[0])
{
vNext = vAdj;
dNext = dAdj;
vCurrConvex = (dNext[0] * dCurr[1] <= dNext[1] * dCurr[0]);
}
}
else
{
if (dCurr[0] * dAdj[1] > dCurr[1] * dAdj[0]
|| dNext[0] * dAdj[1] > dNext[1] * dAdj[0])
{
vNext = vAdj;
dNext = dAdj;
vCurrConvex = (dNext[0] * dCurr[1] <= dNext[1] * dCurr[0]);
}
}
}
return vNext;
}
// Storage for referenced vertices of the original graph and for new
// vertices added during graph traversal.
std::vector<std::shared_ptr<Vertex>> mVertexStorage;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/FastMarch2.h | .h | 11,943 | 352 | // 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 FastMarch2 : public FastMarch<Real>
{
public:
// Construction and destruction.
FastMarch2(size_t xBound, size_t yBound, Real xSpacing, Real ySpacing,
std::vector<size_t> const& seeds, std::vector<Real> const& speeds)
:
FastMarch<Real>(xBound * yBound, seeds, speeds)
{
Initialize(xBound, yBound, xSpacing, ySpacing);
}
FastMarch2(size_t xBound, size_t yBound, Real xSpacing, Real ySpacing,
std::vector<size_t> const& seeds, Real speed)
:
FastMarch<Real>(xBound * yBound, seeds, speed)
{
Initialize(xBound, yBound, xSpacing, ySpacing);
}
virtual ~FastMarch2()
{
}
// Member access.
inline size_t GetXBound() const
{
return mXBound;
}
inline size_t GetYBound() const
{
return mYBound;
}
inline Real GetXSpacing() const
{
return mXSpacing;
}
inline Real GetYSpacing() const
{
return mYSpacing;
}
inline size_t Index(size_t x, size_t y) const
{
return x + mXBound * y;
}
// Pixel 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))
{
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))
{
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]);
}
}
protected:
// Called by the constructors.
void Initialize(size_t xBound, size_t yBound, Real xSpacing, Real ySpacing)
{
mXBound = xBound;
mYBound = yBound;
mXBoundM1 = mXBound - 1;
mYBoundM1 = mYBound - 1;
mXSpacing = xSpacing;
mYSpacing = ySpacing;
mInvXSpacing = (Real)1 / xSpacing;
mInvYSpacing = (Real)1 / ySpacing;
// 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, i;
// vertex (0,0)
i = Index(0, 0);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
// vertex (xmax,0)
i = Index(mXBoundM1, 0);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
// vertex (0,ymax)
i = Index(0, mYBoundM1);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
// vertex (xmax,ymax)
i = Index(mXBoundM1, mYBoundM1);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
// edges (x,0) and (x,ymax)
for (x = 0; x < mXBound; ++x)
{
i = Index(x, 0);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
i = Index(x, mYBoundM1);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
}
// edges (0,y) and (xmax,y)
for (y = 0; y < mYBound; ++y)
{
i = Index(0, y);
this->mInvSpeeds[i] = std::numeric_limits<Real>::max();
this->mTimes[i] = -std::numeric_limits<Real>::max();
i = Index(mXBoundM1, y);
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 (y = 1; y < mYBoundM1; ++y)
{
for (x = 1; x < mXBoundM1; ++x)
{
i = Index(x, y);
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)))
{
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;
}
if (hasXTerm)
{
if (hasYTerm)
{
Real sum = xConst + yConst;
Real diff = xConst - yConst;
Real 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
{
// The equation is linear.
this->mTimes[i] = this->mInvSpeeds[i] + xConst;
}
}
else if (hasYTerm)
{
// The equation is linear.
this->mTimes[i] = this->mInvSpeeds[i] + yConst;
}
else
{
// Assert: The pixel must have at least one known neighbor.
}
}
size_t mXBound, mYBound, mXBoundM1, mYBoundM1;
Real mXSpacing, mYSpacing, mInvXSpacing, mInvYSpacing;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistSegment3CanonicalBox3.h | .h | 2,845 | 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/DistLine3CanonicalBox3.h>
#include <Mathematics/DistPointCanonicalBox.h>
#include <Mathematics/Segment.h>
// Compute the distance between a segment and a solid canonical 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 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 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>, CanonicalBox3<T>>
{
public:
using LBQuery = DCPQuery<T, Line3<T>, CanonicalBox3<T>>;
using Result = typename LBQuery::Result;
Result operator()(Segment3<T> const& segment, CanonicalBox3<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>, CanonicalBox3<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>, CanonicalBox3<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/CholeskyDecomposition.h | .h | 20,080 | 552 | // 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/GMatrix.h>
namespace gte
{
// Implementation for size known at compile time.
template <typename Real, int32_t N = 0>
class CholeskyDecomposition
{
public:
// Ensure that N > 0 at compile time.
CholeskyDecomposition()
{
static_assert(N > 0, "Invalid size in CholeskyDecomposition constructor.");
}
// Disallow copies and moves.
CholeskyDecomposition(CholeskyDecomposition const&) = delete;
CholeskyDecomposition& operator=(CholeskyDecomposition const&) = delete;
CholeskyDecomposition(CholeskyDecomposition&&) = delete;
CholeskyDecomposition& operator=(CholeskyDecomposition&&) = delete;
// On input, A is symmetric. Only the lower-triangular portion is
// modified. On output, the lower-triangular portion is L where
// A = L * L^T.
bool Factor(Matrix<N, N, Real>& A)
{
for (int32_t c = 0; c < N; ++c)
{
if (A(c, c) <= (Real)0)
{
return false;
}
A(c, c) = std::sqrt(A(c, c));
for (int32_t r = c + 1; r < N; ++r)
{
A(r, c) /= A(c, c);
}
for (int32_t k = c + 1; k < N; ++k)
{
for (int32_t r = k; r < N; ++r)
{
A(r, k) -= A(r, c) * A(k, c);
}
}
}
return true;
}
// Solve L*Y = B, where L is lower triangular and invertible. The
// input value of Y is B. On output, Y is the solution.
void SolveLower(Matrix<N, N, Real> const& L, Vector<N, Real>& Y)
{
for (int32_t r = 0; r < N; ++r)
{
for (int32_t c = 0; c < r; ++c)
{
Y[r] -= L(r, c) * Y[c];
}
Y[r] /= L(r, r);
}
}
// Solve L^T*X = Y, where L is lower triangular (L^T is upper
// triangular) and invertible. The input value of X is Y. On
// output, X is the solution.
void SolveUpper(Matrix<N, N, Real> const& L, Vector<N, Real>& X)
{
for (int32_t r = N - 1; r >= 0; --r)
{
for (int32_t c = r + 1; c < N; ++c)
{
X[r] -= L(c, r) * X[c];
}
X[r] /= L(r, r);
}
}
};
// Implementation for size known only at run time.
template <typename Real>
class CholeskyDecomposition<Real, 0>
{
public:
int32_t const N;
// Ensure that N > 0 at run time.
CholeskyDecomposition(int32_t n)
:
N(n)
{
}
// Disallow copies and moves. This is required to avoid compiler
// complaints about the 'int32_t const N' member.
CholeskyDecomposition(CholeskyDecomposition const&) = delete;
CholeskyDecomposition& operator=(CholeskyDecomposition const&) = delete;
CholeskyDecomposition(CholeskyDecomposition&&) = delete;
CholeskyDecomposition& operator=(CholeskyDecomposition&&) = delete;
// On input, A is symmetric. Only the lower-triangular portion is
// modified. On output, the lower-triangular portion is L where
// A = L * L^T.
bool Factor(GMatrix<Real>& A)
{
if (A.GetNumRows() == N && A.GetNumCols() == N)
{
for (int32_t c = 0; c < N; ++c)
{
if (A(c, c) <= (Real)0)
{
return false;
}
A(c, c) = std::sqrt(A(c, c));
for (int32_t r = c + 1; r < N; ++r)
{
A(r, c) /= A(c, c);
}
for (int32_t k = c + 1; k < N; ++k)
{
for (int32_t r = k; r < N; ++r)
{
A(r, k) -= A(r, c) * A(k, c);
}
}
}
return true;
}
LogError("Matrix must be square.");
}
// Solve L*Y = B, where L is lower triangular and invertible. The
// input value of Y is B. On output, Y is the solution.
void SolveLower(GMatrix<Real> const& L, GVector<Real>& Y)
{
if (L.GetNumRows() == N && L.GetNumCols() == N && Y.GetSize() == N)
{
for (int32_t r = 0; r < N; ++r)
{
for (int32_t c = 0; c < r; ++c)
{
Y[r] -= L(r, c) * Y[c];
}
Y[r] /= L(r, r);
}
return;
}
LogError("Invalid size.");
}
// Solve L^T*X = Y, where L is lower triangular (L^T is upper
// triangular) and invertible. The input value of X is Y. On
// output, X is the solution.
void SolveUpper(GMatrix<Real> const& L, GVector<Real>& X)
{
if (L.GetNumRows() == N && L.GetNumCols() == N && X.GetSize() == N)
{
for (int32_t r = N - 1; r >= 0; --r)
{
for (int32_t c = r + 1; c < N; ++c)
{
X[r] -= L(c, r) * X[c];
}
X[r] /= L(r, r);
}
}
else
{
LogError("Invalid size.");
}
}
};
// Implementation for sizes known at compile time.
template <typename Real, int32_t BlockSize = 0, int32_t NumBlocks = 0>
class BlockCholeskyDecomposition
{
public:
// Let B represent the block size and N represent the number of
// blocks. The matrix A is (N*B)-by-(N*B) but partitioned into an
// N-by-N matrix of blocks, each block of size B-by-B. The value
// N*B is NumDimensions.
enum
{
NumDimensions = NumBlocks * BlockSize
};
typedef std::array<Vector<BlockSize, Real>, NumBlocks> BlockVector;
typedef std::array<std::array<Matrix<BlockSize, BlockSize, Real>, NumBlocks>, NumBlocks> BlockMatrix;
// Ensure that BlockSize > 0 and NumBlocks > 0 at compile time.
BlockCholeskyDecomposition()
{
static_assert(BlockSize > 0 && NumBlocks > 0, "Invalid size in BlockCholeskyDecomposition constructor.");
}
// Disallow copies and moves.
BlockCholeskyDecomposition(BlockCholeskyDecomposition const&) = delete;
BlockCholeskyDecomposition& operator=(BlockCholeskyDecomposition const&) = delete;
BlockCholeskyDecomposition(BlockCholeskyDecomposition&&) = delete;
BlockCholeskyDecomposition& operator=(BlockCholeskyDecomposition&&) = delete;
// Treating the matrix as a 2D table of scalars with NUM_DIMENSIONS
// rows and NUM_DIMENSIONS columns, look up the correct block that
// stores the requested element and return a reference.
Real Get(BlockMatrix const& M, int32_t row, int32_t col)
{
int32_t b0 = col / BlockSize, b1 = row / BlockSize;
int32_t i0 = col % BlockSize, i1 = row % BlockSize;
auto const& block = M[b1][b0];
return block(i1, i0);
}
void Set(BlockMatrix& M, int32_t row, int32_t col, Real value)
{
int32_t b0 = col / BlockSize, b1 = row / BlockSize;
int32_t i0 = col % BlockSize, i1 = row % BlockSize;
auto& block = M[b1][b0];
block(i1, i0) = value;
}
bool Factor(BlockMatrix& A)
{
for (int32_t c = 0; c < NumBlocks; ++c)
{
if (!mDecomposer.Factor(A[c][c]))
{
return false;
}
for (int32_t r = c + 1; r < NumBlocks; ++r)
{
LowerTriangularSolver(r, c, A);
}
for (int32_t k = c + 1; k < NumBlocks; ++k)
{
for (int32_t r = k; r < NumBlocks; ++r)
{
SubtractiveUpdate(r, k, c, A);
}
}
}
return true;
}
// Solve L*Y = B, where L is an invertible lower-triangular block
// matrix whose diagonal blocks are lower-triangular matrices.
// The input B is a block vector of commensurate size. The input
// value of Y is B. On output, Y is the solution.
void SolveLower(BlockMatrix const& L, BlockVector& Y)
{
for (int32_t r = 0; r < NumBlocks; ++r)
{
auto& Yr = Y[r];
for (int32_t c = 0; c < r; ++c)
{
auto const& Lrc = L[r][c];
auto const& Yc = Y[c];
for (int32_t i = 0; i < BlockSize; ++i)
{
for (int32_t j = 0; j < BlockSize; ++j)
{
Yr[i] -= Lrc(i, j) * Yc[j];
}
}
}
mDecomposer.SolveLower(L[r][r], Yr);
}
}
// Solve L^T*X = Y, where L is an invertible lower-triangular block
// matrix (L^T is an upper-triangular block matrix) whose diagonal
// blocks are lower-triangular matrices. The input value of X is Y.
// On output, X is the solution.
void SolveUpper(BlockMatrix const& L, BlockVector& X)
{
for (int32_t r = NumBlocks - 1; r >= 0; --r)
{
auto& Xr = X[r];
for (int32_t c = r + 1; c < NumBlocks; ++c)
{
auto const& Lcr = L[c][r];
auto const& Xc = X[c];
for (int32_t i = 0; i < BlockSize; ++i)
{
for (int32_t j = 0; j < BlockSize; ++j)
{
Xr[i] -= Lcr(j, i) * Xc[j];
}
}
}
mDecomposer.SolveUpper(L[r][r], Xr);
}
}
private:
// Solve G(c,c)*G(r,c)^T = A(r,c)^T for G(r,c). The matrices
// G(c,c) and A(r,c) are known quantities, and G(c,c) occupies
// the lower triangular portion of A(c,c). The solver stores
// its results in-place, so A(r,c) stores the G(r,c) result.
void LowerTriangularSolver(int32_t r, int32_t c, BlockMatrix& A)
{
auto const& Acc = A[c][c];
auto& Arc = A[r][c];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < j; ++i)
{
Real Lji = Acc(j, i);
for (int32_t k = 0; k < BlockSize; ++k)
{
Arc(k, j) -= Lji * Arc(k, i);
}
}
Real Ljj = Acc(j, j);
for (int32_t k = 0; k < BlockSize; ++k)
{
Arc(k, j) /= Ljj;
}
}
}
void SubtractiveUpdate(int32_t r, int32_t k, int32_t c, BlockMatrix& A)
{
auto const& Arc = A[r][c];
auto const& Akc = A[k][c];
auto& Ark = A[r][k];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < BlockSize; ++i)
{
for (int32_t m = 0; m < BlockSize; ++m)
{
Ark(j, i) -= Arc(j, m) * Akc(i, m);
}
}
}
}
CholeskyDecomposition<Real, BlockSize> mDecomposer;
};
// Implementation for sizes known only at run time.
template <typename Real>
class BlockCholeskyDecomposition<Real, 0, 0>
{
public:
// Let B represent the block size and N represent the number of
// blocks. The matrix A is (N*B)-by-(N*B) but partitioned into an
// N-by-N matrix of blocks, each block of size B-by-B. The value
// N*B is NumDimensions.
int32_t const BlockSize;
int32_t const NumBlocks;
int32_t const NumDimensions;
// The number of elements in a BlockVector object must be NumBlocks
// and each GVector element has BlockSize components.
typedef std::vector<GVector<Real>> BlockVector;
// The BlockMatrix is an array of NumBlocks-by-NumBlocks matrices.
// Each block matrix is stored in row-major order. The BlockMatrix
// elements themselves are stored in row-major order. The block
// matrix element M = BlockMatrix[col + NumBlocks * row] is of size
// BlockSize-by-BlockSize (in row-major order) and is in the (row,col)
// location of the full matrix of blocks.
typedef std::vector<GMatrix<Real>> BlockMatrix;
// Ensure that BlockSize > 0 and NumDimensions > 0 at run time.
BlockCholeskyDecomposition(int32_t blockSize, int32_t numBlocks)
:
BlockSize(blockSize),
NumBlocks(numBlocks),
NumDimensions(numBlocks * blockSize),
mDecomposer(blockSize)
{
LogAssert(blockSize > 0 && numBlocks > 0, "Invalid input.");
}
// Disallow copies and moves. This is required to avoid compiler
// complaints about the 'int32_t const' members.
BlockCholeskyDecomposition(BlockCholeskyDecomposition const&) = delete;
BlockCholeskyDecomposition& operator=(BlockCholeskyDecomposition const&) = delete;
BlockCholeskyDecomposition(BlockCholeskyDecomposition&&) = delete;
BlockCholeskyDecomposition& operator=(BlockCholeskyDecomposition&&) = delete;
// Treating the matrix as a 2D table of scalars with NumDimensions
// rows and NumDimensions columns, look up the correct block that
// stores the requested element and return a reference.
Real Get(BlockMatrix const& M, int32_t row, int32_t col)
{
int32_t b0 = col / BlockSize, b1 = row / BlockSize;
int32_t i0 = col % BlockSize, i1 = row % BlockSize;
auto const& block = M[GetIndex(b1, b0)];
return block(i1, i0);
}
void Set(BlockMatrix& M, int32_t row, int32_t col, Real value)
{
int32_t b0 = col / BlockSize, b1 = row / BlockSize;
int32_t i0 = col % BlockSize, i1 = row % BlockSize;
auto& block = M[GetIndex(b1, b0)];
block(i1, i0) = value;
}
bool Factor(BlockMatrix& A)
{
for (int32_t c = 0; c < NumBlocks; ++c)
{
if (!mDecomposer.Factor(A[GetIndex(c, c)]))
{
return false;
}
for (int32_t r = c + 1; r < NumBlocks; ++r)
{
LowerTriangularSolver(r, c, A);
}
for (int32_t k = c + 1; k < NumBlocks; ++k)
{
for (int32_t r = k; r < NumBlocks; ++r)
{
SubtractiveUpdate(r, k, c, A);
}
}
}
return true;
}
// Solve L*Y = B, where L is an invertible lower-triangular block
// matrix whose diagonal blocks are lower-triangular matrices.
// The input B is a block vector of commensurate size. The input
// value of Y is B. On output, Y is the solution.
void SolveLower(BlockMatrix const& L, BlockVector& Y)
{
for (int32_t r = 0; r < NumBlocks; ++r)
{
auto& Yr = Y[r];
for (int32_t c = 0; c < r; ++c)
{
auto const& Lrc = L[GetIndex(r, c)];
auto const& Yc = Y[c];
for (int32_t i = 0; i < NumBlocks; ++i)
{
for (int32_t j = 0; j < NumBlocks; ++j)
{
Yr[i] -= Lrc[GetIndex(i, j)] * Yc[j];
}
}
}
mDecomposer.SolveLower(L[GetIndex(r, r)], Yr);
}
}
// Solve L^T*X = Y, where L is an invertible lower-triangular block
// matrix (L^T is an upper-triangular block matrix) whose diagonal
// blocks are lower-triangular matrices. The input value of X is Y.
// On output, X is the solution.
void SolveUpper(BlockMatrix const& L, BlockVector& X)
{
for (int32_t r = NumBlocks - 1; r >= 0; --r)
{
auto& Xr = X[r];
for (int32_t c = r + 1; c < NumBlocks; ++c)
{
auto const& Lcr = L[GetIndex(c, r)];
auto const& Xc = X[c];
for (int32_t i = 0; i < BlockSize; ++i)
{
for (int32_t j = 0; j < BlockSize; ++j)
{
Xr[i] -= Lcr[GetIndex(j, i)] * Xc[j];
}
}
}
mDecomposer.SolveUpper(L[GetIndex(r, r)], Xr);
}
}
private:
// Compute the 1-dimensional index of the block matrix in a
// 2-dimensional BlockMatrix object.
inline int32_t GetIndex(int32_t row, int32_t col) const
{
return col + row * NumBlocks;
}
// Solve G(c,c)*G(r,c)^T = A(r,c)^T for G(r,c). The matrices
// G(c,c) and A(r,c) are known quantities, and G(c,c) occupies
// the lower triangular portion of A(c,c). The solver stores
// its results in-place, so A(r,c) stores the G(r,c) result.
void LowerTriangularSolver(int32_t r, int32_t c, BlockMatrix& A)
{
auto const& Acc = A[GetIndex(c, c)];
auto& Arc = A[GetIndex(r, c)];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < j; ++i)
{
Real Lji = Acc[GetIndex(j, i)];
for (int32_t k = 0; k < BlockSize; ++k)
{
Arc[GetIndex(k, j)] -= Lji * Arc[GetIndex(k, i)];
}
}
Real Ljj = Acc[GetIndex(j, j)];
for (int32_t k = 0; k < BlockSize; ++k)
{
Arc[GetIndex(k, j)] /= Ljj;
}
}
}
void SubtractiveUpdate(int32_t r, int32_t k, int32_t c, BlockMatrix& A)
{
auto const& Arc = A[GetIndex(r, c)];
auto const& Akc = A[GetIndex(k, c)];
auto& Ark = A[GetIndex(r, k)];
for (int32_t j = 0; j < BlockSize; ++j)
{
for (int32_t i = 0; i < BlockSize; ++i)
{
for (int32_t m = 0; m < BlockSize; ++m)
{
Ark[GetIndex(j, i)] -= Arc[GetIndex(j, m)] * Akc[GetIndex(i, m)];
}
}
}
}
// The decomposer has size BlockSize.
CholeskyDecomposition<Real> mDecomposer;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/BSplineCurve.h | .h | 5,326 | 156 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/BasisFunction.h>
#include <Mathematics/ParametricCurve.h>
namespace gte
{
template <int32_t N, typename Real>
class BSplineCurve : public ParametricCurve<N, Real>
{
public:
// Construction. If the input controls is non-null, a copy is made of
// the controls. To defer setting the control points, pass a null
// pointer and later access the control points via GetControls() or
// SetControl() member functions. The domain is t in [t[d],t[n]],
// where t[d] and t[n] are knots with d the degree and n the number of
// control points.
BSplineCurve(BasisFunctionInput<Real> const& input, Vector<N, Real> const* controls)
:
ParametricCurve<N, Real>((Real)0, (Real)1),
mBasisFunction(input)
{
// The mBasisFunction stores the domain but so does
// ParametricCurve.
this->mTime.front() = mBasisFunction.GetMinDomain();
this->mTime.back() = mBasisFunction.GetMaxDomain();
// The replication of control points for periodic splines is
// avoided by wrapping the i-loop index in Evaluate.
mControls.resize(input.numControls);
if (controls)
{
std::copy(controls, controls + input.numControls, mControls.begin());
}
else
{
Vector<N, Real> zero{ (Real)0 };
std::fill(mControls.begin(), mControls.end(), zero);
}
this->mConstructed = true;
}
// Member access.
inline BasisFunction<Real> const& GetBasisFunction() const
{
return mBasisFunction;
}
inline int32_t GetNumControls() const
{
return static_cast<int32_t>(mControls.size());
}
inline Vector<N, Real> const* GetControls() const
{
return mControls.data();
}
inline Vector<N, Real>* GetControls()
{
return mControls.data();
}
void SetControl(int32_t i, Vector<N, Real> const& control)
{
if (0 <= i && i < GetNumControls())
{
mControls[i] = control;
}
}
Vector<N, Real> const& GetControl(int32_t i) const
{
if (0 <= i && i < GetNumControls())
{
return mControls[i];
}
else
{
return mControls[0];
}
}
// Evaluation of the curve. The function supports derivative
// calculation through order 3; that is, order <= 3 is required. 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 maximum
// order. The values are ordered as: position, first derivative,
// second derivative, third derivative.
virtual void Evaluate(Real t, uint32_t order, Vector<N, Real>* jet) const override
{
uint32_t const supOrder = ParametricCurve<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 imin, imax;
mBasisFunction.Evaluate(t, order, imin, imax);
// Compute position.
jet[0] = Compute(0, imin, imax);
if (order >= 1)
{
// Compute first derivative.
jet[1] = Compute(1, imin, imax);
if (order >= 2)
{
// Compute second derivative.
jet[2] = Compute(2, imin, imax);
if (order == 3)
{
jet[3] = Compute(3, imin, imax);
}
}
}
}
private:
// Support for Evaluate(...).
Vector<N, Real> Compute(uint32_t order, int32_t imin, int32_t imax) const
{
// The j-index introduces a tiny amount of overhead in order to handle
// both aperiodic and periodic splines. For aperiodic splines, j = i
// always.
int32_t numControls = GetNumControls();
Vector<N, Real> result;
result.MakeZero();
for (int32_t i = imin; i <= imax; ++i)
{
Real tmp = mBasisFunction.GetValue(order, i);
int32_t j = (i >= numControls ? i - numControls : i);
result += tmp * mControls[j];
}
return result;
}
BasisFunction<Real> mBasisFunction;
std::vector<Vector<N, Real>> mControls;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistOrientedBox3Cone3.h | .h | 8,839 | 257 | // 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/Cone.h>
#include <Mathematics/OrientedBox.h>
#include <Mathematics/LCPSolver.h>
#include <Mathematics/Matrix.h>
#include <Mathematics/Minimize1.h>
#include <Mathematics/Vector3.h>
// Compute the distance between an oriented box and a cone frustum. The
// frustum is part of a single-sided cone with heights measured along the
// axis direction. The single-sided cone heights h satisfy
// 0 <= h <= infinity. The cone frustum has heights that satisfy
// 0 <= hmin < h <= hmax < infinity. The algorithm is described in
// https://www.geometrictools.com/Documentation/DistanceBox3Cone3.pdf
namespace gte
{
template <typename T>
class DCPQuery<T, OrientedBox3<T>, Cone3<T>>
{
public:
DCPQuery()
{
static_assert(
std::is_floating_point<T>::value,
"The input type must be a floating-point type.");
}
// Parameters used internally for controlling the minimizer.
struct Control
{
Control(
int32_t inMaxSubdivisions = 8,
int32_t inMaxBisections = 128,
T inEpsilon = static_cast<T>(1e-08),
T inTolerance = static_cast<T>(1e-04))
:
maxSubdivisions(inMaxSubdivisions),
maxBisections(inMaxBisections),
epsilon(inEpsilon),
tolerance(inTolerance)
{
}
int32_t maxSubdivisions;
int32_t maxBisections;
T epsilon;
T tolerance;
};
// The output of the query, which is the distance between the
// objects and a pair of closest points, one from each object.
struct Result
{
Result()
:
distance(std::numeric_limits<T>::max()),
boxClosestPoint(Vector3<T>::Zero()),
coneClosestPoint(Vector3<T>::Zero())
{
}
T distance;
Vector3<T> boxClosestPoint, coneClosestPoint;
};
// The default minimizer controls are reasonable choices generally,
// in which case you can use
// using BCQuery = DCPQuery<T, OrientedBox3<T>, Cone3<T>>;
// BCQuery bcQuery{};
// BCQuery::Result bcResult = bcQuery(box, cone);
// If your application requires specialized controls,
// using BCQuery = DCPQuery<T, OrientedBox3<T>, Cone3<T>>;
// BCQuery bcQuery{};
// BCQuery::Control bcControl(your_parameters);
// BCQuery::Result bcResult = bcQuery(box, cone, &bcControl);
Result operator()(OrientedBox3<T> const& box, Cone3<T> const& cone,
Control const* inControl = nullptr)
{
Control control{};
if (inControl != nullptr)
{
control = *inControl;
}
// Compute a basis for the cone coordinate system.
std::array<Vector3<T>, 3> basis{};
basis[0] = cone.ray.direction;
ComputeOrthogonalComplement(1, basis.data());
Vector3<T> coneW0 = basis[1];
Vector3<T> coneW1 = basis[2];
Result result{};
result.distance = std::numeric_limits<T>::max();
auto F = [this, &box, &cone, &coneW0, &coneW1, &result](T angle)
{
T distance = std::numeric_limits<T>::max();
Vector3<T> boxClosestPoint{}, quadClosestPoint{};
DoBoxQuadQuery(box, cone, coneW0, coneW1, angle,
distance, boxClosestPoint, quadClosestPoint);
if (distance < result.distance)
{
result.distance = distance;
result.boxClosestPoint = boxClosestPoint;
result.coneClosestPoint = quadClosestPoint;
}
return distance;
};
Minimize1<T> minimizer(F, control.maxSubdivisions, control.maxBisections,
control.epsilon, control.tolerance);
T angle0 = static_cast<T>(-GTE_C_HALF_PI);
T angle1 = static_cast<T>(+GTE_C_HALF_PI);
T angleMin = static_cast<T>(0);
T distanceMin = std::numeric_limits<T>::max();
minimizer.GetMinimum(angle0, angle1, angleMin, distanceMin);
LogAssert(
distanceMin == result.distance,
"Unexpected mismatch in minimum distance.");
return result;
}
private:
void DoBoxQuadQuery(OrientedBox3<T> const& box, Cone3<T> const& cone,
Vector3<T> const& coneW0, Vector3<T> const& coneW1,
T const& quadAngle, T& distance, Vector3<T>& boxClosestPoint,
Vector3<T>& quadClosestPoint)
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const two = static_cast<T>(2);
Vector3<T> K = box.center, ell{};
for (int32_t i = 0; i < 3; ++i)
{
K -= box.extent[i] * box.axis[i];
ell[i] = two * box.extent[i];
}
T cs = std::cos(quadAngle), sn = std::sin(quadAngle);
Vector3<T> term = cone.tanAngle * (cs * coneW0 + sn * coneW1);
std::array<Vector3<T>, 2> G{};
G[0] = cone.ray.direction - term;
G[1] = cone.ray.direction + term;
Matrix<5, 5, T> A{}; // A is the zero matrix
A(0, 0) = one;
A(0, 1) = zero;
A(0, 2) = zero;
A(0, 3) = -Dot(box.axis[0], G[0]);
A(0, 4) = -Dot(box.axis[0], G[1]);
A(1, 0) = A(0, 1);
A(1, 1) = one;
A(1, 2) = zero;
A(1, 3) = -Dot(box.axis[1], G[0]);
A(1, 4) = -Dot(box.axis[1], G[1]);
A(2, 0) = A(0, 2);
A(2, 1) = A(1, 2);
A(2, 2) = one;
A(2, 3) = -Dot(box.axis[2], G[0]);
A(2, 4) = -Dot(box.axis[2], G[1]);
A(3, 0) = A(0, 3);
A(3, 1) = A(1, 3);
A(3, 2) = A(2, 3);
A(3, 3) = Dot(G[0], G[0]);
A(3, 4) = Dot(G[0], G[1]);
A(4, 0) = A(0, 4);
A(4, 1) = A(1, 4);
A(4, 2) = A(2, 4);
A(4, 3) = A(3, 4);
A(4, 4) = Dot(G[1], G[1]);
Vector3<T> KmV = K - cone.ray.origin;
Vector<5, T> b{};
b[0] = Dot(box.axis[0], KmV);
b[1] = Dot(box.axis[1], KmV);
b[2] = Dot(box.axis[2], KmV);
b[3] = -Dot(G[0], KmV);
b[4] = -Dot(G[1], KmV);
Matrix<5, 5, T> D{}; // D is the zero matrix
D(0, 0) = -one;
D(1, 1) = -one;
D(2, 2) = -one;
D(3, 3) = one;
D(3, 4) = one;
D(4, 3) = -one;
D(4, 4) = -one;
Vector<5, T> e{};
e[0] = -ell[0];
e[1] = -ell[1];
e[2] = -ell[2];
e[3] = cone.GetMinHeight();
e[4] = -cone.GetMaxHeight();
std::array<T, 10> q;
for (int32_t i = 0, ip5 = 5; i < 5; ++i, ++ip5)
{
q[i] = b[i];
q[ip5] = -e[i];
}
std::array<std::array<T, 10>, 10> M;
for (int32_t r = 0, rp5 = 5; r < 5; ++r, ++rp5)
{
for (int32_t c = 0, cp5 = 5; c < 5; ++c, ++cp5)
{
M[r][c] = A(r, c);
M[rp5][c] = D(r, c);
M[r][cp5] = -D(c, r);
M[rp5][cp5] = zero;
}
}
std::array<T, 10> w, z;
if (mLCP.Solve(q, M, w, z))
{
boxClosestPoint = K;
for (int32_t i = 0; i < 3; ++i)
{
boxClosestPoint += z[i] * box.axis[i];
}
quadClosestPoint = cone.ray.origin;
for (int32_t i = 0, ip3 = 3; i < 2; ++i, ++ip3)
{
quadClosestPoint += z[ip3] * G[i];
}
distance = Length(boxClosestPoint - quadClosestPoint);
}
else
{
boxClosestPoint.MakeZero();
quadClosestPoint.MakeZero();
distance = std::numeric_limits<T>::max();
}
}
LCPSolver<T, 10> mLCP;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Vector4.h | .h | 6,163 | 168 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector3.h>
namespace gte
{
// Template alias for convenience.
template <typename Real>
using Vector4 = Vector<4, Real>;
// In Vector3.h, the Vector3 Cross, UnitCross, and DotCross have a
// template parameter N that should be 3 or 4. The latter case supports
// affine vectors in 4D (last component w = 0) when you want to use
// 4-tuples and 4x4 matrices for affine algebra. Thus, you may use those
// template functions for Vector4.
// Compute the hypercross product using the formal determinant:
// hcross = det{{e0,e1,e2,e3},{x0,x1,x2,x3},{y0,y1,y2,y3},{z0,z1,z2,z3}}
// where e0 = (1,0,0,0), e1 = (0,1,0,0), e2 = (0,0,1,0), e3 = (0,0,0,1),
// v0 = (x0,x1,x2,x3), v1 = (y0,y1,y2,y3), and v2 = (z0,z1,z2,z3).
template <typename Real>
Vector4<Real> HyperCross(Vector4<Real> const& v0, Vector4<Real> const& v1, Vector4<Real> const& v2)
{
Real m01 = v0[0] * v1[1] - v0[1] * v1[0]; // x0*y1 - y0*x1
Real m02 = v0[0] * v1[2] - v0[2] * v1[0]; // x0*z1 - z0*x1
Real m03 = v0[0] * v1[3] - v0[3] * v1[0]; // x0*w1 - w0*x1
Real m12 = v0[1] * v1[2] - v0[2] * v1[1]; // y0*z1 - z0*y1
Real m13 = v0[1] * v1[3] - v0[3] * v1[1]; // y0*w1 - w0*y1
Real m23 = v0[2] * v1[3] - v0[3] * v1[2]; // z0*w1 - w0*z1
return Vector4<Real>
{
+m23 * v2[1] - m13 * v2[2] + m12 * v2[3], // +m23*y2 - m13*z2 + m12*w2
-m23 * v2[0] + m03 * v2[2] - m02 * v2[3], // -m23*x2 + m03*z2 - m02*w2
+m13 * v2[0] - m03 * v2[1] + m01 * v2[3], // +m13*x2 - m03*y2 + m01*w2
-m12 * v2[0] + m02 * v2[1] - m01 * v2[2] // -m12*x2 + m02*y2 - m01*z2
};
}
// Compute the normalized hypercross product.
template <typename Real>
Vector4<Real> UnitHyperCross(Vector4<Real> const& v0,
Vector4<Real> const& v1, Vector4<Real> const& v2, bool robust = false)
{
Vector4<Real> unitHyperCross = HyperCross(v0, v1, v2);
Normalize(unitHyperCross, robust);
return unitHyperCross;
}
// Compute Dot(HyperCross((x0,x1,x2,x3),(y0,y1,y2,y3),(z0,z1,z2,z3)),
// (w0,w1,w2,w3)), where v0 = (x0,x1,x2,x3), v1 = (y0,y1,y2,y3),
// v2 = (z0,z1,z2,z3), and v3 = (w0,w1,w2,w3).
template <typename Real>
Real DotHyperCross(Vector4<Real> const& v0, Vector4<Real> const& v1,
Vector4<Real> const& v2, Vector4<Real> const& v3)
{
return Dot(HyperCross(v0, v1, v2), v3);
}
// Compute a right-handed orthonormal basis for the orthogonal complement
// of the input vectors. The function returns the smallest length of the
// unnormalized vectors computed during the process. If this value is
// nearly zero, it is possible that the inputs are linearly dependent
// (within numerical round-off errors). On input, numInputs must be 1, 2
// or 3, and v[0] through v[numInputs-1] must be initialized. On output,
// the vectors v[0] through v[3] form an orthonormal set.
template <typename Real>
Real ComputeOrthogonalComplement(int32_t numInputs, Vector4<Real>* v, bool robust = false)
{
if (numInputs == 1)
{
int32_t maxIndex = 0;
Real maxAbsValue = std::fabs(v[0][0]);
for (int32_t i = 1; i < 4; ++i)
{
Real absValue = std::fabs(v[0][i]);
if (absValue > maxAbsValue)
{
maxIndex = i;
maxAbsValue = absValue;
}
}
if (maxIndex < 2)
{
v[1][0] = -v[0][1];
v[1][1] = +v[0][0];
v[1][2] = (Real)0;
v[1][3] = (Real)0;
}
else if (maxIndex == 3)
{
// Generally, you can skip this clause and swap the last two
// components. However, by swapping 2 and 3 in this case, we
// allow the function to work properly when the inputs are 3D
// vectors represented as 4D affine vectors (w = 0).
v[1][0] = (Real)0;
v[1][1] = +v[0][2];
v[1][2] = -v[0][1];
v[1][3] = (Real)0;
}
else
{
v[1][0] = (Real)0;
v[1][1] = (Real)0;
v[1][2] = -v[0][3];
v[1][3] = +v[0][2];
}
numInputs = 2;
}
if (numInputs == 2)
{
Real det[6] =
{
v[0][0] * v[1][1] - v[1][0] * v[0][1],
v[0][0] * v[1][2] - v[1][0] * v[0][2],
v[0][0] * v[1][3] - v[1][0] * v[0][3],
v[0][1] * v[1][2] - v[1][1] * v[0][2],
v[0][1] * v[1][3] - v[1][1] * v[0][3],
v[0][2] * v[1][3] - v[1][2] * v[0][3]
};
int32_t maxIndex = 0;
Real maxAbsValue = std::fabs(det[0]);
for (int32_t i = 1; i < 6; ++i)
{
Real absValue = std::fabs(det[i]);
if (absValue > maxAbsValue)
{
maxIndex = i;
maxAbsValue = absValue;
}
}
if (maxIndex == 0)
{
v[2] = { -det[4], +det[2], (Real)0, -det[0] };
}
else if (maxIndex <= 2)
{
v[2] = { +det[5], (Real)0, -det[2], +det[1] };
}
else
{
v[2] = { (Real)0, -det[5], +det[4], -det[3] };
}
numInputs = 3;
}
if (numInputs == 3)
{
v[3] = HyperCross(v[0], v[1], v[2]);
return Orthonormalize<4, Real>(4, v, robust);
}
return (Real)0;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistAlignedBox3OrientedBox3.h | .h | 1,937 | 56 | // 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/DistOrientedBox3OrientedBox3.h>
#include <Mathematics/AlignedBox.h>
// Compute the distance between solid aligned and oriented boxes in 3D.
//
// 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 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 aligned box is stored in closest[0]. The closest
// point of the oriented box is stored in closest[1].
namespace gte
{
template <typename T>
class DCPQuery<T, AlignedBox3<T>, OrientedBox3<T>>
{
public:
using BBQuery = DCPQuery<T, OrientedBox3<T>, OrientedBox3<T>>;
using Result = typename BBQuery::Result;
Result operator()(AlignedBox3<T> const& box0, OrientedBox3<T> const& box1)
{
Result result{};
// Convert the aligned box to an oriented box.
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const half = static_cast<T>(0.5);
OrientedBox3<T> obox0{};
obox0.center = half * (box0.max + box0.min);
obox0.extent = half * (box0.max - box0.min);
obox0.axis[0] = { one, zero, zero };
obox0.axis[1] = { zero, one, zero };
obox0.axis[2] = { zero, zero, one };
// Execute the query for two oriented boxes.
BBQuery bbQuery{};
result = bbQuery(obox0, box1);
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/RootsBisection1.h | .h | 8,348 | 210 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Logger.h>
#include <Mathematics/Math.h>
#include <functional>
// Estimate a root on an interval [tMin,tMax] for a continuous function F(t)
// defined on that interval. If a root is found, the function returns it via
// tRoot. Additionally, fAtTRoot = F(tRoot) is returned in case the caller
// wants to know how close to zero the function is at the root; numerical
// rounding errors can cause fAtTRoot not to be exactly zero. The returned
// uint32_t is the number of iterations used by the bisector. If that number
// is 0, F(tMin)*F(tMax) > 0 and it is unknown whether [tMin,tMax] contains
// a root. If that number is 1, either F(tMin) = 0 or F(tMax) = 0 (exactly),
// and tRoot is the corresponding interval endpoint. If that number is 2 or
// larger, the bisection is applied until tRoot is found for which F(tRoot)
// is exactly 0 or until the current root estimate is equal to tMin or tMax.
// The latter conditions can occur because of the fixed precision used in
// the computations (24-bit precision for 'float', 53-bit precision for
// 'double' or a user-specified precision for arbitrary-precision numbers.
namespace gte
{
template <typename Real>
class RootsBisection1
{
public:
// Use this constructor when Real is a floating-point type.
template <typename Dummy = Real>
RootsBisection1(uint32_t maxIterations,
typename std::enable_if<!is_arbitrary_precision<Dummy>::value>::type* = nullptr)
:
mPrecision(0),
mMaxIterations(maxIterations)
{
static_assert(!is_arbitrary_precision<Real>::value,
"Template parameter is not a floating-point type.");
LogAssert(mMaxIterations > 0, "Invalid maximum iterations.");
}
// Use this constructor when Real is an arbitrary-precision type.
// If you want infinite precision (no rounding of any computational
// results), set precision to std::numeric_limits<uint32_t>::max().
// For rounding of each computational result throughout the process,
// set precision to be a positive number smaller than the maximum of
// uint32_t.
template <typename Dummy = Real>
RootsBisection1(uint32_t precision, uint32_t maxIterations,
typename std::enable_if<is_arbitrary_precision<Dummy>::value>::type* = nullptr)
:
mPrecision(precision),
mMaxIterations(maxIterations)
{
static_assert(is_arbitrary_precision<Real>::value,
"Template parameter is not an arbitrary-precision type.");
LogAssert(mMaxIterations > 0, "Invalid maximum iterations.");
LogAssert(mPrecision > 0, "Invalid precision.");
}
// Disallow copy and move semantics.
RootsBisection1(RootsBisection1 const&) = delete;
RootsBisection1(RootsBisection1&&) = delete;
RootsBisection1& operator=(RootsBisection1 const&) = delete;
RootsBisection1& operator=(RootsBisection1&&) = delete;
// Use this function when F(tMin) and F(tMax) are not already known.
uint32_t operator()(std::function<Real(Real const&)> F,
Real const& tMin, Real const& tMax, Real& tRoot, Real& fAtTRoot)
{
LogAssert(tMin < tMax, "Invalid ordering of t-interval endpoints.");
// Use floating-point inputs as is. Round arbitrary-precision
// inputs to the specified precision.
Real t0, t1;
RoundInitial(tMin, tMax, t0, t1);
Real f0 = F(t0), f1 = F(t1);
return operator()(F, t0, t1, f0, f1, tRoot, fAtTRoot);
}
// Use this function when fAtTMin = F(tMin) and fAtTMax = F(tMax) are
// already known. This is useful when |fAtTMin| or |fAtTMax| is
// infinite, whereby you can pass sign(fAtTMin) or sign(fAtTMax)
// rather than then an infinity because the bisector cares only about
// the signs of F(t).
uint32_t operator()(std::function<Real(Real const&)> F,
Real const& tMin, Real const& tMax, Real const& fMin, Real const& fMax,
Real& tRoot, Real& fAtTRoot)
{
LogAssert(tMin < tMax, "Invalid ordering of t-interval endpoints.");
Real const zero(0);
int32_t sign0 = (fMin > zero ? +1 : (fMin < zero ? -1 : 0));
if (sign0 == 0)
{
tRoot = tMin;
fAtTRoot = zero;
return 1;
}
int32_t sign1 = (fMax > zero ? +1 : (fMax < zero ? -1 : 0));
if (sign1 == 0)
{
tRoot = tMax;
fAtTRoot = zero;
return 1;
}
if (sign0 == sign1)
{
// It is unknown whether the interval contains a root.
tRoot = zero;
fAtTRoot = zero;
return 0;
}
// The bisection steps.
Real t0 = tMin, t1 = tMax;
uint32_t iteration;
for (iteration = 2; iteration <= mMaxIterations; ++iteration)
{
// Use the floating-point average as is. Round the
// arbitrary-precision average to the specified precision.
tRoot = RoundAverage(t0, t1);
fAtTRoot = F(tRoot);
// If the function is exactly zero, a root is found. For
// fixed precision, the average of two consecutive numbers
// might one of the current interval endpoints.
int32_t signRoot = (fAtTRoot > zero ? +1 : (fAtTRoot < zero ? -1 : 0));
if (signRoot == 0 || tRoot == t0 || tRoot == t1)
{
break;
}
// Update the correct endpoint to the midpoint.
if (signRoot == sign0)
{
t0 = tRoot;
}
else // signRoot == sign1
{
t1 = tRoot;
}
}
return iteration;
}
private:
// Floating-point numbers are used without rounding.
template <typename Dummy = Real>
typename std::enable_if<!is_arbitrary_precision<Dummy>::value, void>::type
RoundInitial(Real const& inT0, Real const& inT1, Real& t0, Real& t1)
{
t0 = inT0;
t1 = inT1;
}
template <typename Dummy = Real>
typename std::enable_if<!is_arbitrary_precision<Dummy>::value, Real>::type
RoundAverage(Real const& t0, Real const& t1)
{
Real average = static_cast<Real>(0.5)* (t0 + t1);
return average;
}
// Arbitrary-precision numbers are used with rounding.
template <typename Dummy = Real>
typename std::enable_if<is_arbitrary_precision<Dummy>::value, void>::type
RoundInitial(Real const& inT0, Real const& inT1, Real& t0, Real& t1)
{
if (mPrecision < std::numeric_limits<uint32_t>::max())
{
Convert(inT0, mPrecision, FE_TONEAREST, t0);
Convert(inT1, mPrecision, FE_TONEAREST, t1);
}
else
{
t0 = inT0;
t1 = inT1;
}
}
template <typename Dummy = Real>
typename std::enable_if<is_arbitrary_precision<Dummy>::value, Real>::type
RoundAverage(Real const& t0, Real const& t1)
{
Real average = std::ldexp(t0 + t1, -1); // = (t0 + t1) / 2
if (mPrecision < std::numeric_limits<uint32_t>::max())
{
Real roundedAverage;
Convert(average, mPrecision, FE_TONEAREST, roundedAverage);
return roundedAverage;
}
else
{
return average;
}
}
uint32_t mPrecision, mMaxIterations;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/PdeFilter2.h | .h | 16,267 | 496 | // 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/Array2.h>
#include <array>
#include <limits>
namespace gte
{
template <typename Real>
class PdeFilter2 : public PdeFilter<Real>
{
public:
// Abstract base class.
PdeFilter2(int32_t xBound, int32_t yBound, Real xSpacing, Real ySpacing,
Real const* data, int32_t const* mask, Real borderValue,
typename PdeFilter<Real>::ScaleType scaleType)
:
PdeFilter<Real>(xBound * yBound, data, borderValue, scaleType),
mXBound(xBound),
mYBound(yBound),
mXSpacing(xSpacing),
mYSpacing(ySpacing),
mInvDx((Real)1 / xSpacing),
mInvDy((Real)1 / ySpacing),
mHalfInvDx((Real)0.5 * mInvDx),
mHalfInvDy((Real)0.5 * mInvDy),
mInvDxDx(mInvDx * mInvDx),
mFourthInvDxDy(mHalfInvDx * mHalfInvDy),
mInvDyDy(mInvDy * mInvDy),
mUmm(0), mUzm(0), mUpm(0),
mUmz(0), mUzz(0), mUpz(0),
mUmp(0), mUzp(0), mUpp(0),
mSrc(0),
mDst(1),
mMask(static_cast<size_t>(xBound) + 2, static_cast<size_t>(yBound) + 2),
mHasMask(mask != nullptr)
{
for (int32_t i = 0; i < 2; ++i)
{
mBuffer[i] = Array2<Real>(static_cast<size_t>(xBound) + 2, static_cast<size_t>(yBound) + 2);
}
// The mBuffer[] are ping-pong buffers for filtering.
for (int32_t y = 0, yp = 1, i = 0; y < mYBound; ++y, ++yp)
{
for (int32_t x = 0, xp = 1; x < mXBound; ++x, ++xp, ++i)
{
mBuffer[mSrc][yp][xp] = this->mOffset + (data[i] - this->mMin) * this->mScale;
mBuffer[mDst][yp][xp] = (Real)0;
mMask[yp][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 ~PdeFilter2()
{
}
// Member access. The internal 2D 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)-by-(ybound+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 Real GetXSpacing() const
{
return mXSpacing;
}
inline Real GetYSpacing() const
{
return mYSpacing;
}
// Pixel access and derivative estimation. The lookups into the
// padded data are handled correctly. The estimation involves only
// the 3-by-3 neighborhood of (x,y), where 0 <= x < xbound and
// 0 <= y < ybound. 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) const
{
auto const& F = mBuffer[mSrc];
int32_t xp1 = x + 1, yp1 = y + 1;
return F[yp1][xp1];
}
Real GetUx(int32_t x, int32_t y) const
{
auto const& F = mBuffer[mSrc];
int32_t xp2 = x + 2, yp1 = y + 1;
return mHalfInvDx * (F[yp1][xp2] - F[yp1][x]);
}
Real GetUy(int32_t x, int32_t y) const
{
auto const& F = mBuffer[mSrc];
int32_t xp1 = x + 1, yp2 = y + 2;
return mHalfInvDy * (F[yp2][xp1] - F[y][xp1]);
}
Real GetUxx(int32_t x, int32_t y) const
{
auto const& F = mBuffer[mSrc];
int32_t xp1 = x + 1, xp2 = x + 2, yp1 = y + 1;
return mInvDxDx * (F[yp1][xp2] - (Real)2 * F[yp1][xp1] + F[yp1][x]);
}
Real GetUxy(int32_t x, int32_t y) const
{
auto const& F = mBuffer[mSrc];
int32_t xp2 = x + 2, yp2 = y + 2;
return mFourthInvDxDy * (F[y][x] - F[y][xp2] + F[yp2][xp2] - F[yp2][x]);
}
Real GetUyy(int32_t x, int32_t y) const
{
auto const& F = mBuffer[mSrc];
int32_t xp1 = x + 1, yp1 = y + 1, yp2 = y + 2;
return mInvDyDy * (F[yp2][xp1] - (Real)2 * F[yp1][xp1] + F[y][xp1]);
}
int32_t GetMask(int32_t x, int32_t y) const
{
int32_t xp1 = x + 1, yp1 = y + 1;
return mMask[yp1][xp1];
}
protected:
// Assign values to the 1-pixel image border.
void AssignDirichletImageBorder()
{
int32_t xBp1 = mXBound + 1, yBp1 = mYBound + 1;
int32_t x, y;
// vertex (0,0)
mBuffer[mSrc][0][0] = this->mBorderValue;
mBuffer[mDst][0][0] = this->mBorderValue;
if (mHasMask)
{
mMask[0][0] = 0;
}
// vertex (xmax,0)
mBuffer[mSrc][0][xBp1] = this->mBorderValue;
mBuffer[mDst][0][xBp1] = this->mBorderValue;
if (mHasMask)
{
mMask[0][xBp1] = 0;
}
// vertex (0,ymax)
mBuffer[mSrc][yBp1][0] = this->mBorderValue;
mBuffer[mDst][yBp1][0] = this->mBorderValue;
if (mHasMask)
{
mMask[yBp1][0] = 0;
}
// vertex (xmax,ymax)
mBuffer[mSrc][yBp1][xBp1] = this->mBorderValue;
mBuffer[mDst][yBp1][xBp1] = this->mBorderValue;
if (mHasMask)
{
mMask[yBp1][xBp1] = 0;
}
// edges (x,0) and (x,ymax)
for (x = 1; x <= mXBound; ++x)
{
mBuffer[mSrc][0][x] = this->mBorderValue;
mBuffer[mDst][0][x] = this->mBorderValue;
if (mHasMask)
{
mMask[0][x] = 0;
}
mBuffer[mSrc][yBp1][x] = this->mBorderValue;
mBuffer[mDst][yBp1][x] = this->mBorderValue;
if (mHasMask)
{
mMask[yBp1][x] = 0;
}
}
// edges (0,y) and (xmax,y)
for (y = 1; y <= mYBound; ++y)
{
mBuffer[mSrc][y][0] = this->mBorderValue;
mBuffer[mDst][y][0] = this->mBorderValue;
if (mHasMask)
{
mMask[y][0] = 0;
}
mBuffer[mSrc][y][xBp1] = this->mBorderValue;
mBuffer[mDst][y][xBp1] = this->mBorderValue;
if (mHasMask)
{
mMask[y][xBp1] = 0;
}
}
}
void AssignNeumannImageBorder()
{
int32_t xBp1 = mXBound + 1, yBp1 = mYBound + 1;
int32_t x, y;
Real duplicate;
// vertex (0,0)
duplicate = mBuffer[mSrc][1][1];
mBuffer[mSrc][0][0] = duplicate;
mBuffer[mDst][0][0] = duplicate;
if (mHasMask)
{
mMask[0][0] = 0;
}
// vertex (xmax,0)
duplicate = mBuffer[mSrc][1][mXBound];
mBuffer[mSrc][0][xBp1] = duplicate;
mBuffer[mDst][0][xBp1] = duplicate;
if (mHasMask)
{
mMask[0][xBp1] = 0;
}
// vertex (0,ymax)
duplicate = mBuffer[mSrc][mYBound][1];
mBuffer[mSrc][yBp1][0] = duplicate;
mBuffer[mDst][yBp1][0] = duplicate;
if (mHasMask)
{
mMask[yBp1][0] = 0;
}
// vertex (xmax,ymax)
duplicate = mBuffer[mSrc][mYBound][mXBound];
mBuffer[mSrc][yBp1][xBp1] = duplicate;
mBuffer[mDst][yBp1][xBp1] = duplicate;
if (mHasMask)
{
mMask[yBp1][xBp1] = 0;
}
// edges (x,0) and (x,ymax)
for (x = 1; x <= mXBound; ++x)
{
duplicate = mBuffer[mSrc][1][x];
mBuffer[mSrc][0][x] = duplicate;
mBuffer[mDst][0][x] = duplicate;
if (mHasMask)
{
mMask[0][x] = 0;
}
duplicate = mBuffer[mSrc][mYBound][x];
mBuffer[mSrc][yBp1][x] = duplicate;
mBuffer[mDst][yBp1][x] = duplicate;
if (mHasMask)
{
mMask[yBp1][x] = 0;
}
}
// edges (0,y) and (xmax,y)
for (y = 1; y <= mYBound; ++y)
{
duplicate = mBuffer[mSrc][y][1];
mBuffer[mSrc][y][0] = duplicate;
mBuffer[mDst][y][0] = duplicate;
if (mHasMask)
{
mMask[y][0] = 0;
}
duplicate = mBuffer[mSrc][y][mXBound];
mBuffer[mSrc][y][xBp1] = duplicate;
mBuffer[mDst][y][xBp1] = duplicate;
if (mHasMask)
{
mMask[y][xBp1] = 0;
}
}
}
// Assign values to the 1-pixel mask border.
void AssignDirichletMaskBorder()
{
for (int32_t y = 1; y <= mYBound; ++y)
{
for (int32_t x = 1; x <= mXBound; ++x)
{
if (mMask[y][x])
{
continue;
}
bool found = false;
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[j1][j0])
{
mBuffer[mSrc][y][x] = this->mBorderValue;
mBuffer[mDst][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 y = 1; y <= mYBound; ++y)
{
for (int32_t x = 1; x <= mXBound; ++x)
{
if (mMask[y][x])
{
continue;
}
int32_t count = 0;
Real average = (Real)0;
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[j1][j0])
{
average += mBuffer[mSrc][j1][j0];
++count;
}
}
}
if (count > 0)
{
average /= (Real)count;
mBuffer[mSrc][y][x] = average;
mBuffer[mDst][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) for each pixel
// that is not masked out.
virtual void OnUpdate() override
{
for (int32_t y = 1; y <= mYBound; ++y)
{
for (int32_t x = 1; x <= mXBound; ++x)
{
if (!mHasMask || mMask[y][x])
{
OnUpdateSingle(x, y);
}
}
}
}
// 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)
// must be in padded coordinates: 1 <= x <= xbound and
// 1 <= y <= ybound.
virtual void OnUpdateSingle(int32_t x, int32_t y) = 0;
// Copy source data to temporary storage.
void LookUp5(int32_t x, int32_t y)
{
auto const& F = mBuffer[mSrc];
int32_t xm = x - 1, xp = x + 1;
int32_t ym = y - 1, yp = y + 1;
mUzm = F[ym][x];
mUmz = F[y][xm];
mUzz = F[y][x];
mUpz = F[y][xp];
mUzp = F[yp][x];
}
void LookUp9(int32_t x, int32_t y)
{
auto const& F = mBuffer[mSrc];
int32_t xm = x - 1, xp = x + 1;
int32_t ym = y - 1, yp = y + 1;
mUmm = F[ym][xm];
mUzm = F[ym][x];
mUpm = F[ym][xp];
mUmz = F[y][xm];
mUzz = F[y][x];
mUpz = F[y][xp];
mUmp = F[yp][xm];
mUzp = F[yp][x];
mUpp = F[yp][xp];
}
// Image parameters.
int32_t mXBound, mYBound;
Real mXSpacing; // dx
Real mYSpacing; // dy
Real mInvDx; // 1/dx
Real mInvDy; // 1/dy
Real mHalfInvDx; // 1/(2*dx)
Real mHalfInvDy; // 1/(2*dy)
Real mInvDxDx; // 1/(dx*dx)
Real mFourthInvDxDy; // 1/(4*dx*dy)
Real mInvDyDy; // 1/(dy*dy)
// Temporary storage for 3x3 neighborhood. In the notation mUxy, the
// x and y indices are in {m,z,p}, referring to subtract 1 (m), no
// change (z), or add 1 (p) to the appropriate index.
Real mUmm, mUzm, mUpm;
Real mUmz, mUzz, mUpz;
Real mUmp, mUzp, mUpp;
// Successive iterations toggle between two buffers.
std::array<Array2<Real>, 2> mBuffer;
int32_t mSrc, mDst;
Array2<int32_t> mMask;
bool mHasMask;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/RangeIteration.h | .h | 1,753 | 67 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <iterator>
#include <type_traits>
// For information on range-based for-loops, see
// http://en.cppreference.com/w/cpp/language/range-for
namespace gte
{
// The function gte::reverse supports reverse iteration in range-based
// for-loops using the auto keyword. For example,
//
// std::vector<int32_t> numbers(4);
// int32_t i = 0;
// for (auto& number : numbers)
// {
// number = i++;
// std::cout << number << ' ';
// }
// // Output: 0 1 2 3
//
// for (auto& number : gte::reverse(numbers))
// {
// std::cout << number << ' ';
// }
// // Output: 3 2 1 0
template <typename Iterator>
class ReversalObject
{
public:
ReversalObject(Iterator begin, Iterator end)
:
mBegin(begin),
mEnd(end)
{
}
Iterator begin() const { return mBegin; }
Iterator end() const { return mEnd; }
private:
Iterator mBegin, mEnd;
};
template
<
typename Iterable,
typename Iterator = decltype(std::begin(std::declval<Iterable>())),
typename ReverseIterator = std::reverse_iterator<Iterator>
>
ReversalObject<ReverseIterator> reverse(Iterable && range)
{
return ReversalObject<ReverseIterator>(
ReverseIterator(std::end(range)),
ReverseIterator(std::begin(range)));
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrAlignedBox3AlignedBox3.h | .h | 2,756 | 107 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/FIQuery.h>
#include <Mathematics/TIQuery.h>
#include <Mathematics/AlignedBox.h>
// The queries consider the box to be a solid.
//
// The aligned-aligned queries use simple min-max comparisions. The
// interesection of aligned boxes is an aligned box, possibly degenerate,
// where min[d] == max[d] for at least one dimension d.
namespace gte
{
template <typename T>
class TIQuery<T, AlignedBox3<T>, AlignedBox3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(AlignedBox3<T> const& box0, AlignedBox3<T> const& box1)
{
Result result{};
for (int32_t i = 0; i < 3; i++)
{
if (box0.max[i] < box1.min[i] || box0.min[i] > box1.max[i])
{
result.intersect = false;
return result;
}
}
result.intersect = true;
return result;
}
};
template <typename T>
class FIQuery<T, AlignedBox3<T>, AlignedBox3<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
box{}
{
}
bool intersect;
AlignedBox3<T> box;
};
Result operator()(AlignedBox3<T> const& box0, AlignedBox3<T> const& box1)
{
Result result{};
for (int32_t i = 0; i < 3; i++)
{
if (box0.max[i] < box1.min[i] || box0.min[i] > box1.max[i])
{
result.intersect = false;
return result;
}
}
for (int32_t i = 0; i < 3; i++)
{
if (box0.max[i] <= box1.max[i])
{
result.box.max[i] = box0.max[i];
}
else
{
result.box.max[i] = box1.max[i];
}
if (box0.min[i] <= box1.min[i])
{
result.box.min[i] = box1.min[i];
}
else
{
result.box.min[i] = box0.min[i];
}
}
result.intersect = true;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/PolynomialCurve.h | .h | 3,807 | 119 | // 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/ParametricCurve.h>
#include <Mathematics/Polynomial1.h>
namespace gte
{
template <int32_t N, typename Real>
class PolynomialCurve : public ParametricCurve<N, Real>
{
public:
// Construction and destruction. The default constructor creates a
// polynomial curve with all components set to the constant zero (all
// degree-0 polynomials). You can set these to other polynomials
// using member accessors.
PolynomialCurve(Real tmin, Real tmax)
:
ParametricCurve<N, Real>(tmin, tmax)
{
}
PolynomialCurve(Real tmin, Real tmax,
std::array<Polynomial1<Real>, N> const& components)
:
ParametricCurve<N, Real>(tmin, tmax)
{
for (int32_t i = 0; i < N; ++i)
{
SetPolynomial(i, components[i]);
}
}
virtual ~PolynomialCurve()
{
}
// Member access.
void SetPolynomial(int32_t i, Polynomial1<Real> const& poly)
{
mPolynomial[i] = poly;
mDer1Polynomial[i] = mPolynomial[i].GetDerivative();
mDer2Polynomial[i] = mDer1Polynomial[i].GetDerivative();
mDer3Polynomial[i] = mDer2Polynomial[i].GetDerivative();
}
inline Polynomial1<Real> const& GetPolynomial(int32_t i) const
{
return mPolynomial[i];
}
inline Polynomial1<Real> const& GetDer1Polynomial(int32_t i) const
{
return mDer1Polynomial[i];
}
inline Polynomial1<Real> const& GetDer2Polynomial(int32_t i) const
{
return mDer2Polynomial[i];
}
inline Polynomial1<Real> const& GetDer3Polynomial(int32_t i) const
{
return mDer3Polynomial[i];
}
// Evaluation of the curve. The function supports derivative
// calculation through order 3; that is, order <= 3 is required. 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 maximum
// order. The values are ordered as: position, first derivative,
// second derivative, third derivative.
virtual void Evaluate(Real t, uint32_t order, Vector<N, Real>* jet) const override
{
for (int32_t i = 0; i < N; ++i)
{
jet[0][i] = mPolynomial[i](t);
}
if (order >= 1)
{
for (int32_t i = 0; i < N; ++i)
{
jet[1][i] = mDer1Polynomial[i](t);
}
if (order >= 2)
{
for (int32_t i = 0; i < N; ++i)
{
jet[2][i] = mDer2Polynomial[i](t);
}
if (order == 3)
{
for (int32_t i = 0; i < N; ++i)
{
jet[3][i] = mDer3Polynomial[i](t);
}
}
}
}
}
protected:
std::array<Polynomial1<Real>, N> mPolynomial;
std::array<Polynomial1<Real>, N> mDer1Polynomial;
std::array<Polynomial1<Real>, N> mDer2Polynomial;
std::array<Polynomial1<Real>, N> mDer3Polynomial;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrTriangle2Triangle2.h | .h | 5,785 | 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/IntrConvexPolygonHyperplane.h>
#include <Mathematics/Triangle.h>
#include <Mathematics/Vector2.h>
// The test-intersection queries are based on the document
// https://www.geometrictools.com/Documentation/MethodOfSeparatingAxes.pdf
// The find-intersection query for stationary triangles is based on clipping
// one triangle against the edges of the other to compute the intersection
// set (if it exists). The find-intersection query for moving triangles is
// based on the previously mentioned document about the method of separating
// axes.
namespace gte
{
// Test whether two triangles intersect using the method of separating
// axes. The set of intersection, if it exists, is not computed. The
// input triangles' vertices must be counterclockwise ordered.
template <typename T>
class TIQuery<T, Triangle2<T>, Triangle2<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Triangle2<T> const& triangle0, Triangle2<T> const& triangle1)
{
Result result{};
result.intersect =
!Separated(triangle0, triangle1) &&
!Separated(triangle1, triangle0);
return result;
}
protected:
// The triangle vertices are projected to t-values for the line P+t*D.
// The D-vector is nonzero but does not have to be unit length. The
// return value is +1 if all t >= 0, -1 if all t <= 0, but 0 otherwise
// in which case the line splits the triangle into two subtriangles,
// each of positive area.
int32_t WhichSide(Triangle2<T> const& triangle, Vector2<T> const& P, Vector2<T> const& D) const
{
int32_t positive = 0, negative = 0;
for (int32_t i = 0; i < 3; ++i)
{
T t = Dot(D, triangle.v[i] - P);
if (t > (T)0)
{
++positive;
}
else if (t < (T)0)
{
--negative;
}
if (positive && negative)
{
// The triangle has vertices strictly on both sides of
// the line, so the line splits the triangle into two
// subtriangles each of positive area.
return 0;
}
}
// Either positive > 0 or negative > 0 but not both are positive.
return (positive > 0 ? +1 : -1);
}
bool Separated(Triangle2<T> const& triangle0, Triangle2<T> const& triangle1) const
{
// Test edges of triangle0 for separation. Because of the
// counterclockwise ordering, the projection interval for
// triangle0 is [T,0] for some T < 0. Determine whether
// triangle1 is on the positive side of the line; if it is,
// the triangles are separated.
for (int32_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
{
// The potential separating axis is P+t*D.
Vector2<T> P = triangle0.v[i0];
Vector2<T> D = Perp(triangle0.v[i1] - triangle0.v[i0]);
if (WhichSide(triangle1, P, D) > 0)
{
// The triangle1 projection interval is [a,b] where a > 0,
// so the triangles are separated.
return true;
}
}
return false;
}
};
// Find the convex polygon, segment or point of intersection of two
// triangles. The input triangles' vertices must be counterclockwise
// ordered.
template <typename T>
class FIQuery<T, Triangle2<T>, Triangle2<T>>
{
public:
struct Result
{
Result()
:
intersection{}
{
}
// An intersection exists iff intersection.size() > 0.
std::vector<Vector2<T>> intersection;
};
Result operator()(Triangle2<T> const& triangle0, Triangle2<T> const& triangle1)
{
Result result{};
// Start with triangle1 and clip against the edges of triangle0.
std::vector<Vector2<T>> polygon =
{
triangle1.v[0], triangle1.v[1], triangle1.v[2]
};
typedef FIQuery<T, std::vector<Vector<2, T>>, Hyperplane<2, T>> PPQuery;
PPQuery ppQuery;
for (int32_t i1 = 2, i0 = 0; i0 < 3; i1 = i0++)
{
// Create the clipping line for the current edge. The edge
// normal N points inside the triangle.
Vector2<T> P = triangle0.v[i0];
Vector2<T> N = Perp(triangle0.v[i1] - triangle0.v[i0]);
Hyperplane<2, T> clippingLine(N, Dot(N, P));
// Do the clipping operation.
auto ppResult = ppQuery(polygon, clippingLine);
if (ppResult.positivePolygon.size() == 0)
{
// The current clipped polygon is outside triangle0.
return result;
}
polygon = std::move(ppResult.positivePolygon);
}
result.intersection = polygon;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntpThinPlateSpline2.h | .h | 9,324 | 275 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/GMatrix.h>
#include <array>
// WARNING. The implementation allows you to transform the inputs (x,y) to
// the unit square and perform the interpolation in that space. The idea is
// to keep the floating-point numbers to order 1 for numerical stability of
// the algorithm. The classical thin-plate spline algorithm does not include
// this transformation. The interpolation is invariant to translations and
// rotations of (x,y) but not to scaling. The following document is about
// thin plate splines.
// https://www.geometrictools.com/Documentation/ThinPlateSplines.pdf
namespace gte
{
template <typename Real>
class IntpThinPlateSpline2
{
public:
// Construction. Data points are (x,y,f(x,y)). The smoothing
// parameter must be nonnegative.
IntpThinPlateSpline2(int32_t numPoints, Real const* X, Real const* Y,
Real const* F, Real smooth, bool transformToUnitSquare)
:
mNumPoints(numPoints),
mX(numPoints),
mY(numPoints),
mSmooth(smooth),
mA(numPoints),
mB{ (Real)0, (Real)0, (Real)0 },
mInitialized(false)
{
LogAssert(numPoints >= 3 && X != nullptr && Y != nullptr &&
F != nullptr && smooth >= (Real)0, "Invalid input.");
int32_t i, row, col;
if (transformToUnitSquare)
{
// Map input (x,y) to unit square. This is not part of the
// classical thin-plate spline algorithm because the
// interpolation is not invariant to scalings.
auto extreme = std::minmax_element(X, X + mNumPoints);
mXMin = *extreme.first;
mXMax = *extreme.second;
mXInvRange = (Real)1 / (mXMax - mXMin);
for (i = 0; i < mNumPoints; ++i)
{
mX[i] = (X[i] - mXMin) * mXInvRange;
}
extreme = std::minmax_element(Y, Y + mNumPoints);
mYMin = *extreme.first;
mYMax = *extreme.second;
mYInvRange = (Real)1 / (mYMax - mYMin);
for (i = 0; i < mNumPoints; ++i)
{
mY[i] = (Y[i] - mYMin) * mYInvRange;
}
}
else
{
// The classical thin-plate spline uses the data as is. The
// values mXMax and mYMax are not used, but they are
// initialized anyway (to irrelevant numbers).
mXMin = (Real)0;
mXMax = (Real)1;
mXInvRange = (Real)1;
mYMin = (Real)0;
mYMax = (Real)1;
mYInvRange = (Real)1;
std::copy(X, X + mNumPoints, mX.begin());
std::copy(Y, Y + mNumPoints, mY.begin());
}
// Compute matrix A = M + lambda*I [NxN matrix].
GMatrix<Real> AMat(mNumPoints, mNumPoints);
for (row = 0; row < mNumPoints; ++row)
{
for (col = 0; col < mNumPoints; ++col)
{
if (row == col)
{
AMat(row, col) = mSmooth;
}
else
{
Real dx = mX[row] - mX[col];
Real dy = mY[row] - mY[col];
Real t = std::sqrt(dx * dx + dy * dy);
AMat(row, col) = Kernel(t);
}
}
}
// Compute matrix B [Nx3 matrix].
GMatrix<Real> BMat(mNumPoints, 3);
for (row = 0; row < mNumPoints; ++row)
{
BMat(row, 0) = (Real)1;
BMat(row, 1) = mX[row];
BMat(row, 2) = mY[row];
}
// Compute A^{-1}.
bool invertible = false;
GMatrix<Real> invAMat = Inverse(AMat, &invertible);
if (!invertible)
{
return;
}
// Compute P = B^T A^{-1} [3xN matrix].
GMatrix<Real> PMat = MultiplyATB(BMat, invAMat);
// Compute Q = P B = B^T A^{-1} B [3x3 matrix].
GMatrix<Real> QMat = PMat * BMat;
// Compute Q^{-1}.
GMatrix<Real> invQMat = Inverse(QMat, &invertible);
if (!invertible)
{
return;
}
// Compute P*z.
std::array<Real, 3> prod;
for (row = 0; row < 3; ++row)
{
prod[row] = (Real)0;
for (i = 0; i < mNumPoints; ++i)
{
prod[row] += PMat(row, i) * F[i];
}
}
// Compute 'b' vector for smooth thin plate spline.
for (row = 0; row < 3; ++row)
{
mB[row] = (Real)0;
for (i = 0; i < 3; ++i)
{
mB[row] += invQMat(row, i) * prod[i];
}
}
// Compute z-B*b.
std::vector<Real> tmp(mNumPoints);
for (row = 0; row < mNumPoints; ++row)
{
tmp[row] = F[row];
for (i = 0; i < 3; ++i)
{
tmp[row] -= BMat(row, i) * mB[i];
}
}
// Compute 'a' vector for smooth thin plate spline.
for (row = 0; row < mNumPoints; ++row)
{
mA[row] = (Real)0;
for (i = 0; i < mNumPoints; ++i)
{
mA[row] += invAMat(row, i) * tmp[i];
}
}
mInitialized = true;
}
// Check this after the constructor call to see whether the thin plate
// spline coefficients were successfully computed. If so, then calls
// to operator()(Real,Real) will work properly. TODO: This needs to
// be removed because the constructor now throws exceptions?
inline bool IsInitialized() const
{
return mInitialized;
}
// Evaluate the interpolator. If IsInitialized() returns 'false', the
// operator will return std::numeric_limits<Real>::max().
Real operator()(Real x, Real y) const
{
if (mInitialized)
{
// Map (x,y) to the unit square.
x = (x - mXMin) * mXInvRange;
y = (y - mYMin) * mYInvRange;
Real result = mB[0] + mB[1] * x + mB[2] * y;
for (int32_t i = 0; i < mNumPoints; ++i)
{
Real dx = x - mX[i];
Real dy = y - mY[i];
Real t = std::sqrt(dx * dx + dy * dy);
result += mA[i] * Kernel(t);
}
return result;
}
return std::numeric_limits<Real>::max();
}
// Compute the functional value a^T*M*a when lambda is zero or
// lambda*w^T*(M+lambda*I)*w when lambda is positive. See the thin
// plate splines PDF for a description of these quantities.
Real ComputeFunctional() const
{
Real functional = (Real)0;
for (int32_t row = 0; row < mNumPoints; ++row)
{
for (int32_t col = 0; col < mNumPoints; ++col)
{
if (row == col)
{
functional += mSmooth * mA[row] * mA[col];
}
else
{
Real dx = mX[row] - mX[col];
Real dy = mY[row] - mY[col];
Real t = std::sqrt(dx * dx + dy * dy);
functional += Kernel(t) * mA[row] * mA[col];
}
}
}
if (mSmooth > (Real)0)
{
functional *= mSmooth;
}
return functional;
}
private:
// Kernel(t) = t^2 * log(t^2)
static Real Kernel(Real t)
{
if (t > (Real)0)
{
Real t2 = t * t;
return t2 * std::log(t2);
}
return (Real)0;
}
// Input data.
int32_t mNumPoints;
std::vector<Real> mX;
std::vector<Real> mY;
Real mSmooth;
// Thin plate spline coefficients. The A[] coefficients are associated
// with the Green's functions G(x,y,*) and the B[] coefficients are
// associated with the affine term B[0] + B[1]*x + B[2]*y.
std::vector<Real> mA; // mNumPoints elements
std::array<Real, 3> mB;
// Extent of input data.
Real mXMin, mXMax, mXInvRange;
Real mYMin, mYMax, mYInvRange;
bool mInitialized;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/LevenbergMarquardtMinimizer.h | .h | 11,673 | 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/CholeskyDecomposition.h>
#include <functional>
// See GaussNewtonMinimizer.h for a formulation of the minimization
// problem and how Levenberg-Marquardt relates to Gauss-Newton.
namespace gte
{
template <typename T>
class LevenbergMarquardtMinimizer
{
public:
// Convenient types for the domain vectors, the range vectors, the
// function F and the Jacobian J.
typedef GVector<T> DVector; // numPDimensions
typedef GVector<T> RVector; // numFDImensions
typedef GMatrix<T> JMatrix; // numFDimensions-by-numPDimensions
typedef GMatrix<T> JTJMatrix; // numPDimensions-by-numPDimensions
typedef GVector<T> JTFVector; // numPDimensions
typedef std::function<void(DVector const&, RVector&)> FFunction;
typedef std::function<void(DVector const&, JMatrix&)> JFunction;
typedef std::function<void(DVector const&, JTJMatrix&, JTFVector&)> JPlusFunction;
// Create the minimizer that computes F(p) and J(p) directly.
LevenbergMarquardtMinimizer(int32_t numPDimensions, int32_t numFDimensions,
FFunction const& inFFunction, JFunction const& inJFunction)
:
mNumPDimensions(numPDimensions),
mNumFDimensions(numFDimensions),
mFFunction(inFFunction),
mJFunction(inJFunction),
mF(mNumFDimensions),
mJ(mNumFDimensions, mNumPDimensions),
mJTJ(mNumPDimensions, mNumPDimensions),
mNegJTF(mNumPDimensions),
mDecomposer(mNumPDimensions),
mUseJFunction(true)
{
LogAssert(mNumPDimensions > 0 && mNumFDimensions > 0, "Invalid dimensions.");
}
// Create the minimizer that computes J^T(p)*J(p) and -J(p)*F(p).
LevenbergMarquardtMinimizer(int32_t numPDimensions, int32_t numFDimensions,
FFunction const& inFFunction, JPlusFunction const& inJPlusFunction)
:
mNumPDimensions(numPDimensions),
mNumFDimensions(numFDimensions),
mFFunction(inFFunction),
mJPlusFunction(inJPlusFunction),
mF(mNumFDimensions),
mJ(mNumFDimensions, mNumPDimensions),
mJTJ(mNumPDimensions, mNumPDimensions),
mNegJTF(mNumPDimensions),
mDecomposer(mNumPDimensions),
mUseJFunction(false)
{
LogAssert(mNumPDimensions > 0 && mNumFDimensions > 0, "Invalid dimensions.");
}
// Disallow copy, assignment and move semantics.
LevenbergMarquardtMinimizer(LevenbergMarquardtMinimizer const&) = delete;
LevenbergMarquardtMinimizer& operator=(LevenbergMarquardtMinimizer const&) = delete;
LevenbergMarquardtMinimizer(LevenbergMarquardtMinimizer&&) = delete;
LevenbergMarquardtMinimizer& operator=(LevenbergMarquardtMinimizer&&) = delete;
inline int32_t GetNumPDimensions() const { return mNumPDimensions; }
inline int32_t GetNumFDimensions() const { return mNumFDimensions; }
// The lambda is positive, the multiplier is positive, and the initial
// guess for the p-parameter is p0. Typical choices are lambda =
// 0.001 and multiplier = 10. TODO: Explain lambda in more detail,
// Multiview Geometry mentions lambda = 0.001*average(diagonal(JTJ)),
// but let's just expose the factor in front of the average.
struct Result
{
Result()
:
minLocation{},
minError(static_cast<T>(0)),
minErrorDifference(static_cast<T>(0)),
minUpdateLength(static_cast<T>(0)),
numIterations(0),
numAdjustments(0),
converged(false)
{
minLocation.MakeZero();
}
DVector minLocation;
T minError;
T minErrorDifference;
T minUpdateLength;
size_t numIterations;
size_t numAdjustments;
bool converged;
};
Result operator()(DVector const& p0, size_t maxIterations,
T updateLengthTolerance, T errorDifferenceTolerance,
T lambdaFactor, T lambdaAdjust, size_t maxAdjustments)
{
Result result{};
result.minLocation = p0;
result.minError = std::numeric_limits<T>::max();
result.minErrorDifference = std::numeric_limits<T>::max();
result.minUpdateLength = (T)0;
result.numIterations = 0;
result.numAdjustments = 0;
result.converged = false;
// As a simple precaution, ensure that the lambda inputs are
// valid. If invalid, fall back to Gauss-Newton iteration.
if (lambdaFactor <= (T)0 || lambdaAdjust <= (T)0)
{
maxAdjustments = 1;
lambdaFactor = (T)0;
lambdaAdjust = (T)1;
}
// As a simple precaution, ensure the tolerances are nonnegative.
updateLengthTolerance = std::max(updateLengthTolerance, (T)0);
errorDifferenceTolerance = std::max(errorDifferenceTolerance, (T)0);
// Compute the initial error.
mFFunction(p0, mF);
result.minError = Dot(mF, mF);
// Do the Levenberg-Marquart iterations.
auto pCurrent = p0;
for (result.numIterations = 1; result.numIterations <= maxIterations; ++result.numIterations)
{
std::pair<bool, bool> status;
DVector pNext;
for (result.numAdjustments = 0; result.numAdjustments < maxAdjustments; ++result.numAdjustments)
{
status = DoIteration(pCurrent, lambdaFactor, updateLengthTolerance,
errorDifferenceTolerance, pNext, result);
if (status.first)
{
// Either the Cholesky decomposition failed or the
// iterates converged within tolerance. TODO: See the
// note in DoIteration about not failing on Cholesky
// decomposition.
return result;
}
if (status.second)
{
// The error has been reduced but we have not yet
// converged within tolerance.
break;
}
lambdaFactor *= lambdaAdjust;
}
if (result.numAdjustments < maxAdjustments)
{
// The current value of lambda led us to an update that
// reduced the error, but the error is not yet small
// enough to conclude we converged. Reduce lambda for the
// next outer-loop iteration.
lambdaFactor /= lambdaAdjust;
}
else
{
// All lambdas tried during the inner-loop iteration did
// not lead to a reduced error. If we do nothing here,
// the next inner-loop iteration will continue to multiply
// lambda, risking eventual floating-point overflow. To
// avoid this, fall back to a Gauss-Newton iterate.
status = DoIteration(pCurrent, lambdaFactor, updateLengthTolerance,
errorDifferenceTolerance, pNext, result);
if (status.first)
{
// Either the Cholesky decomposition failed or the
// iterates converged within tolerance. TODO: See the
// note in DoIteration about not failing on Cholesky
// decomposition.
return result;
}
}
pCurrent = pNext;
}
return result;
}
private:
void ComputeLinearSystemInputs(DVector const& pCurrent, T lambda)
{
if (mUseJFunction)
{
mJFunction(pCurrent, mJ);
mJTJ = MultiplyATB(mJ, mJ);
mNegJTF = -(mF * mJ);
}
else
{
mJPlusFunction(pCurrent, mJTJ, mNegJTF);
}
T diagonalSum(0);
for (int32_t i = 0; i < mNumPDimensions; ++i)
{
diagonalSum += mJTJ(i, i);
}
T diagonalAdjust = lambda * diagonalSum / static_cast<T>(mNumPDimensions);
for (int32_t i = 0; i < mNumPDimensions; ++i)
{
mJTJ(i, i) += diagonalAdjust;
}
}
// The returned 'first' is true when the linear system cannot be
// solved (result.converged is false in this case) or when the
// error is reduced to within the tolerances specified by the caller
// (result.converged is true in this case). When the 'first' value
// is true, the 'second' value is true when the error is reduced or
// false when it is not.
std::pair<bool, bool> DoIteration(DVector const& pCurrent, T lambdaFactor,
T updateLengthTolerance, T errorDifferenceTolerance, DVector& pNext,
Result& result)
{
ComputeLinearSystemInputs(pCurrent, lambdaFactor);
if (!mDecomposer.Factor(mJTJ))
{
// TODO: The matrix mJTJ is positive semi-definite, so the
// failure can occur when mJTJ has a zero eigenvalue in
// which case mJTJ is not invertible. Generate an iterate
// anyway, perhaps using gradient descent?
return std::make_pair(true, false);
}
mDecomposer.SolveLower(mJTJ, mNegJTF);
mDecomposer.SolveUpper(mJTJ, mNegJTF);
pNext = pCurrent + mNegJTF;
mFFunction(pNext, mF);
T error = Dot(mF, mF);
if (error < result.minError)
{
result.minErrorDifference = result.minError - error;
result.minUpdateLength = Length(mNegJTF);
result.minLocation = pNext;
result.minError = error;
if (result.minErrorDifference <= errorDifferenceTolerance
|| result.minUpdateLength <= updateLengthTolerance)
{
result.converged = true;
return std::make_pair(true, true);
}
else
{
return std::make_pair(false, true);
}
}
else
{
return std::make_pair(false, false);
}
}
int32_t mNumPDimensions, mNumFDimensions;
FFunction mFFunction;
JFunction mJFunction;
JPlusFunction mJPlusFunction;
// Storage for J^T(p)*J(p) and -J^T(p)*F(p) during the iterations.
RVector mF;
JMatrix mJ;
JTJMatrix mJTJ;
JTFVector mNegJTF;
CholeskyDecomposition<T> mDecomposer;
bool mUseJFunction;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistRay3CanonicalBox3.h | .h | 2,109 | 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/DistLine3CanonicalBox3.h>
#include <Mathematics/DistPointCanonicalBox.h>
#include <Mathematics/Ray.h>
// Compute the distance between a ray and a solid canonical box in 3D.
//
// The ray is P + t * D for t >= 0, where D is not required to be unit length.
//
// The canonical box has center at the origin and is aligned with the
// coordinate axes. The extents are E = (e[0],e[1],e[2]). A box point is
// Y = (y[0],y[1],y[2]) with |y[i]| <= e[i] for all i.
//
// The closest point on the ray is stored in closest[0] with parameter t. The
// closest point on the box is stored in closest[1]. When there are infinitely
// many choices for the pair of closest points, only one of them is returned.
namespace gte
{
template <typename T>
class DCPQuery<T, Ray3<T>, CanonicalBox3<T>>
{
public:
using LBQuery = DCPQuery<T, Line3<T>, CanonicalBox3<T>>;
using Result = typename LBQuery::Result;
Result operator()(Ray3<T> const& ray, CanonicalBox3<T> const& box)
{
Result result{};
Line3<T> line(ray.origin, ray.direction);
LBQuery lbQuery{};
auto lbOutput = lbQuery(line, box);
T const zero = static_cast<T>(0);
if (lbOutput.parameter >= zero)
{
result = lbOutput;
}
else
{
DCPQuery<T, Vector3<T>, CanonicalBox3<T>> pbQuery{};
auto pbOutput = pbQuery(ray.origin, box);
result.distance = pbOutput.distance;
result.sqrDistance = pbOutput.sqrDistance;
result.parameter = zero;
result.closest[0] = ray.origin;
result.closest[1] = pbOutput.closest[1];
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntpAkimaUniform2.h | .h | 19,184 | 566 | // 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/Array2.h>
#include <algorithm>
#include <array>
#include <cstring>
// The interpolator is for uniformly spaced (x,y)-values. The input samples
// F must be stored in row-major order to represent f(x,y); that is,
// F[c + xBound*r] corresponds to f(x,y), where c is the index corresponding
// to x and r is the index corresponding to y.
namespace gte
{
template <typename Real>
class IntpAkimaUniform2
{
public:
// Construction and destruction.
IntpAkimaUniform2(int32_t xBound, int32_t yBound, Real xMin, Real xSpacing,
Real yMin, Real ySpacing, Real const* F)
:
mXBound(xBound),
mYBound(yBound),
mQuantity(xBound* yBound),
mXMin(xMin),
mXSpacing(xSpacing),
mYMin(yMin),
mYSpacing(ySpacing),
mF(F),
mPoly(static_cast<size_t>(xBound) - 1, static_cast<size_t>(yBound) - 1)
{
// At least a 3x3 block of data points is 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) - (Real)1);
mYMax = mYMin + mYSpacing * (static_cast<Real>(mYBound) - (Real)1);
// Create a 2D wrapper for the 1D samples.
Array2<Real> Fmap(mXBound, mYBound, const_cast<Real*>(mF));
// Construct first-order derivatives.
Array2<Real> FX(mXBound, mYBound), FY(mXBound, mYBound);
GetFX(Fmap, FX);
GetFY(Fmap, FY);
// Construct second-order derivatives.
Array2<Real> FXY(mXBound, mYBound);
GetFXY(Fmap, FXY);
// Construct polynomials.
GetPolynomials(Fmap, FX, FY, FXY);
}
~IntpAkimaUniform2() = default;
// 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
{
x = std::min(std::max(x, mXMin), mXMax);
y = std::min(std::max(y, mYMin), mYMax);
int32_t ix, iy;
Real dx, dy;
XLookup(x, ix, dx);
YLookup(y, iy, dy);
return mPoly[iy][ix](dx, dy);
}
Real operator()(int32_t xOrder, int32_t yOrder, Real x, Real y) const
{
x = std::min(std::max(x, mXMin), mXMax);
y = std::min(std::max(y, mYMin), mYMax);
int32_t ix, iy;
Real dx, dy;
XLookup(x, ix, dx);
YLookup(y, iy, dy);
return mPoly[iy][ix](xOrder, yOrder, dx, dy);
}
private:
class Polynomial
{
public:
Polynomial()
{
for (size_t i = 0; i < 4; ++i)
{
mCoeff[i].fill((Real)0);
}
}
// P(x,y) = (1,x,x^2,x^3)*A*(1,y,y^2,y^3). The matrix term A[ix][iy]
// corresponds to the polynomial term x^{ix} y^{iy}.
Real& A(int32_t ix, int32_t iy)
{
return mCoeff[ix][iy];
}
Real operator()(Real x, Real y) const
{
std::array<Real, 4> B;
for (int32_t i = 0; i <= 3; ++i)
{
B[i] = mCoeff[i][0] + y * (mCoeff[i][1] + y * (mCoeff[i][2] + y * mCoeff[i][3]));
}
return B[0] + x * (B[1] + x * (B[2] + x * B[3]));
}
Real operator()(int32_t xOrder, int32_t yOrder, Real x, Real y) const
{
std::array<Real, 4> xPow;
switch (xOrder)
{
case 0:
xPow[0] = (Real)1;
xPow[1] = x;
xPow[2] = x * x;
xPow[3] = x * x * x;
break;
case 1:
xPow[0] = (Real)0;
xPow[1] = (Real)1;
xPow[2] = (Real)2 * x;
xPow[3] = (Real)3 * x * x;
break;
case 2:
xPow[0] = (Real)0;
xPow[1] = (Real)0;
xPow[2] = (Real)2;
xPow[3] = (Real)6 * x;
break;
case 3:
xPow[0] = (Real)0;
xPow[1] = (Real)0;
xPow[2] = (Real)0;
xPow[3] = (Real)6;
break;
default:
return (Real)0;
}
std::array<Real, 4> yPow;
switch (yOrder)
{
case 0:
yPow[0] = (Real)1;
yPow[1] = y;
yPow[2] = y * y;
yPow[3] = y * y * y;
break;
case 1:
yPow[0] = (Real)0;
yPow[1] = (Real)1;
yPow[2] = (Real)2 * y;
yPow[3] = (Real)3 * y * y;
break;
case 2:
yPow[0] = (Real)0;
yPow[1] = (Real)0;
yPow[2] = (Real)2;
yPow[3] = (Real)6 * y;
break;
case 3:
yPow[0] = (Real)0;
yPow[1] = (Real)0;
yPow[2] = (Real)0;
yPow[3] = (Real)6;
break;
default:
return (Real)0;
}
Real p = (Real)0;
for (size_t iy = 0; iy <= 3; ++iy)
{
for (size_t ix = 0; ix <= 3; ++ix)
{
p += mCoeff[ix][iy] * xPow[ix] * yPow[iy];
}
}
return p;
}
private:
std::array<std::array<Real, 4>, 4> mCoeff;
};
// Support for construction.
void GetFX(Array2<Real> const& F, Array2<Real>& FX)
{
Array2<Real> slope(static_cast<size_t>(mXBound) + 3, mYBound);
Real invDX = (Real)1 / mXSpacing;
int32_t ix, iy;
for (iy = 0; iy < mYBound; ++iy)
{
for (ix = 0; ix < mXBound - 1; ++ix)
{
slope[iy][ix + 2] = (F[iy][ix + 1] - F[iy][ix]) * invDX;
}
slope[iy][1] = (Real)2 * slope[iy][2] - slope[iy][3];
slope[iy][0] = (Real)2 * slope[iy][1] - slope[iy][2];
slope[iy][mXBound + 1] = (Real)2 * slope[iy][mXBound] - slope[iy][mXBound - 1];
slope[iy][mXBound + 2] = (Real)2 * slope[iy][mXBound + 1] - slope[iy][mXBound];
}
for (iy = 0; iy < mYBound; ++iy)
{
for (ix = 0; ix < mXBound; ++ix)
{
FX[iy][ix] = ComputeDerivative(slope[iy] + ix);
}
}
}
void GetFY(Array2<Real> const& F, Array2<Real>& FY)
{
Array2<Real> slope(static_cast<size_t>(mYBound) + 3, mXBound);
Real invDY = (Real)1 / mYSpacing;
int32_t ix, iy;
for (ix = 0; ix < mXBound; ++ix)
{
for (iy = 0; iy < mYBound - 1; ++iy)
{
slope[ix][iy + 2] = (F[iy + 1][ix] - F[iy][ix]) * invDY;
}
slope[ix][1] = (Real)2 * slope[ix][2] - slope[ix][3];
slope[ix][0] = (Real)2 * slope[ix][1] - slope[ix][2];
slope[ix][mYBound + 1] = (Real)2 * slope[ix][mYBound] - slope[ix][mYBound - 1];
slope[ix][mYBound + 2] = (Real)2 * slope[ix][mYBound + 1] - slope[ix][mYBound];
}
for (ix = 0; ix < mXBound; ++ix)
{
for (iy = 0; iy < mYBound; ++iy)
{
FY[iy][ix] = ComputeDerivative(slope[ix] + iy);
}
}
}
void GetFXY(Array2<Real> const& F, Array2<Real>& FXY)
{
int32_t xBoundM1 = mXBound - 1;
int32_t yBoundM1 = mYBound - 1;
int32_t ix0 = xBoundM1, ix1 = ix0 - 1, ix2 = ix1 - 1;
int32_t iy0 = yBoundM1, iy1 = iy0 - 1, iy2 = iy1 - 1;
int32_t ix, iy;
Real invDXDY = (Real)1 / (mXSpacing * mYSpacing);
// corners
FXY[0][0] = (Real)0.25 * invDXDY * (
(Real)9 * F[0][0]
- (Real)12 * F[0][1]
+ (Real)3 * F[0][2]
- (Real)12 * F[1][0]
+ (Real)16 * F[1][1]
- (Real)4 * F[1][2]
+ (Real)3 * F[2][0]
- (Real)4 * F[2][1]
+ F[2][2]);
FXY[0][xBoundM1] = (Real)0.25 * invDXDY * (
(Real)9 * F[0][ix0]
- (Real)12 * F[0][ix1]
+ (Real)3 * F[0][ix2]
- (Real)12 * F[1][ix0]
+ (Real)16 * F[1][ix1]
- (Real)4 * F[1][ix2]
+ (Real)3 * F[2][ix0]
- (Real)4 * F[2][ix1]
+ F[2][ix2]);
FXY[yBoundM1][0] = (Real)0.25 * invDXDY * (
(Real)9 * F[iy0][0]
- (Real)12 * F[iy0][1]
+ (Real)3 * F[iy0][2]
- (Real)12 * F[iy1][0]
+ (Real)16 * F[iy1][1]
- (Real)4 * F[iy1][2]
+ (Real)3 * F[iy2][0]
- (Real)4 * F[iy2][1]
+ F[iy2][2]);
FXY[yBoundM1][xBoundM1] = (Real)0.25 * invDXDY * (
(Real)9 * F[iy0][ix0]
- (Real)12 * F[iy0][ix1]
+ (Real)3 * F[iy0][ix2]
- (Real)12 * F[iy1][ix0]
+ (Real)16 * F[iy1][ix1]
- (Real)4 * F[iy1][ix2]
+ (Real)3 * F[iy2][ix0]
- (Real)4 * F[iy2][ix1]
+ F[iy2][ix2]);
// x-edges
for (ix = 1; ix < xBoundM1; ++ix)
{
FXY[0][ix] = (Real)0.25 * invDXDY * (
(Real)3 * (F[0][ix - 1] - F[0][ix + 1])
- (Real)4 * (F[1][ix - 1] - F[1][ix + 1])
+ (F[2][ix - 1] - F[2][ix + 1]));
FXY[yBoundM1][ix] = (Real)0.25 * invDXDY * (
(Real)3 * (F[iy0][ix - 1] - F[iy0][ix + 1])
- (Real)4 * (F[iy1][ix - 1] - F[iy1][ix + 1])
+ (F[iy2][ix - 1] - F[iy2][ix + 1]));
}
// y-edges
for (iy = 1; iy < yBoundM1; ++iy)
{
FXY[iy][0] = (Real)0.25 * invDXDY * (
(Real)3 * (F[iy - 1][0] - F[iy + 1][0])
- (Real)4 * (F[iy - 1][1] - F[iy + 1][1])
+ (F[iy - 1][2] - F[iy + 1][2]));
FXY[iy][xBoundM1] = (Real)0.25 * invDXDY * (
(Real)3 * (F[iy - 1][ix0] - F[iy + 1][ix0])
- (Real)4 * (F[iy - 1][ix1] - F[iy + 1][ix1])
+ (F[iy - 1][ix2] - F[iy + 1][ix2]));
}
// interior
for (iy = 1; iy < yBoundM1; ++iy)
{
for (ix = 1; ix < xBoundM1; ++ix)
{
FXY[iy][ix] = (Real)0.25 * invDXDY * (F[iy - 1][ix - 1] -
F[iy - 1][ix + 1] - F[iy + 1][ix - 1] + F[iy + 1][ix + 1]);
}
}
}
void GetPolynomials(Array2<Real> const& F, Array2<Real> const& FX,
Array2<Real> const& FY, Array2<Real> const& FXY)
{
int32_t xBoundM1 = mXBound - 1;
int32_t yBoundM1 = mYBound - 1;
for (int32_t iy = 0; iy < yBoundM1; ++iy)
{
for (int32_t ix = 0; ix < xBoundM1; ++ix)
{
// Note the 'transposing' of the 2x2 blocks (to match
// notation used in the polynomial definition).
Real G[2][2] =
{
{ F[iy][ix], F[iy + 1][ix] },
{ F[iy][ix + 1], F[iy + 1][ix + 1] }
};
Real GX[2][2] =
{
{ FX[iy][ix], FX[iy + 1][ix] },
{ FX[iy][ix + 1], FX[iy + 1][ix + 1] }
};
Real GY[2][2] =
{
{ FY[iy][ix], FY[iy + 1][ix] },
{ FY[iy][ix + 1], FY[iy + 1][ix + 1] }
};
Real GXY[2][2] =
{
{ FXY[iy][ix], FXY[iy + 1][ix] },
{ FXY[iy][ix + 1], FXY[iy + 1][ix + 1] }
};
Construct(mPoly[iy][ix], G, GX, GY, GXY);
}
}
}
Real ComputeDerivative(Real const* slope) const
{
if (slope[1] != slope[2])
{
if (slope[0] != slope[1])
{
if (slope[2] != slope[3])
{
Real ad0 = std::fabs(slope[3] - slope[2]);
Real ad1 = std::fabs(slope[0] - slope[1]);
return (ad0 * slope[1] + ad1 * slope[2]) / (ad0 + ad1);
}
else
{
return slope[2];
}
}
else
{
if (slope[2] != slope[3])
{
return slope[1];
}
else
{
return (Real)0.5 * (slope[1] + slope[2]);
}
}
}
else
{
return slope[1];
}
}
void Construct(Polynomial& poly, Real const F[2][2], Real const FX[2][2],
Real const FY[2][2], Real const FXY[2][2])
{
Real dx = mXSpacing;
Real dy = mYSpacing;
Real invDX = (Real)1 / dx, invDX2 = invDX * invDX;
Real invDY = (Real)1 / dy, invDY2 = invDY * invDY;
Real b0, b1, b2, b3;
poly.A(0, 0) = F[0][0];
poly.A(1, 0) = FX[0][0];
poly.A(0, 1) = FY[0][0];
poly.A(1, 1) = FXY[0][0];
b0 = (F[1][0] - poly(0, 0, dx, (Real)0)) * invDX2;
b1 = (FX[1][0] - poly(1, 0, dx, (Real)0)) * invDX;
poly.A(2, 0) = (Real)3 * b0 - b1;
poly.A(3, 0) = ((Real)-2 * b0 + b1) * invDX;
b0 = (F[0][1] - poly(0, 0, (Real)0, dy)) * invDY2;
b1 = (FY[0][1] - poly(0, 1, (Real)0, dy)) * invDY;
poly.A(0, 2) = (Real)3 * b0 - b1;
poly.A(0, 3) = ((Real)-2 * b0 + b1) * invDY;
b0 = (FY[1][0] - poly(0, 1, dx, (Real)0)) * invDX2;
b1 = (FXY[1][0] - poly(1, 1, dx, (Real)0)) * invDX;
poly.A(2, 1) = (Real)3 * b0 - b1;
poly.A(3, 1) = ((Real)-2 * b0 + b1) * invDX;
b0 = (FX[0][1] - poly(1, 0, (Real)0, dy)) * invDY2;
b1 = (FXY[0][1] - poly(1, 1, (Real)0, dy)) * invDY;
poly.A(1, 2) = (Real)3 * b0 - b1;
poly.A(1, 3) = ((Real)-2 * b0 + b1) * invDY;
b0 = (F[1][1] - poly(0, 0, dx, dy)) * invDX2 * invDY2;
b1 = (FX[1][1] - poly(1, 0, dx, dy)) * invDX * invDY2;
b2 = (FY[1][1] - poly(0, 1, dx, dy)) * invDX2 * invDY;
b3 = (FXY[1][1] - poly(1, 1, dx, dy)) * invDX * invDY;
poly.A(2, 2) = (Real)9 * b0 - (Real)3 * b1 - (Real)3 * b2 + b3;
poly.A(3, 2) = ((Real)-6 * b0 + (Real)3 * b1 + (Real)2 * b2 - b3) * invDX;
poly.A(2, 3) = ((Real)-6 * b0 + (Real)2 * b1 + (Real)3 * b2 - b3) * invDY;
poly.A(3, 3) = ((Real)4 * b0 - (Real)2 * b1 - (Real)2 * b2 + b3) * invDX * invDY;
}
// Support for evaluation.
void XLookup(Real x, int32_t& xIndex, Real& dx) const
{
int32_t xIndexP1;
for (xIndex = 0, xIndexP1 = 1; xIndexP1 < mXBound; ++xIndex, ++xIndexP1)
{
if (x < mXMin + mXSpacing * static_cast<Real>(xIndexP1))
{
dx = x - (mXMin + mXSpacing * xIndex);
return;
}
}
--xIndex;
dx = x - (mXMin + mXSpacing * xIndex);
}
void YLookup(Real y, int32_t& yIndex, Real& dy) const
{
int32_t yIndexP1;
for (yIndex = 0, yIndexP1 = 1; yIndexP1 < mYBound; ++yIndex, ++yIndexP1)
{
if (y < mYMin + mYSpacing * static_cast<Real>(yIndexP1))
{
dy = y - (mYMin + mYSpacing * yIndex);
return;
}
}
yIndex--;
dy = y - (mYMin + mYSpacing * yIndex);
}
int32_t mXBound, mYBound, mQuantity;
Real mXMin, mXMax, mXSpacing;
Real mYMin, mYMax, mYSpacing;
Real const* mF;
Array2<Polynomial> mPoly;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/MinimumWidthPoints2.h | .h | 12,777 | 329 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.2.2022.03.07
#pragma once
#include <Mathematics/ConvexHull2.h>
#include <Mathematics/OrientedBox.h>
#include <Mathematics/RotatingCalipers.h>
#include <functional>
// The width for a set of 2D points is the minimum distance between pairs
// of parallel lines, each pair bounding the points. The width for a set
// of 2D points is equal to the width for the set of vertices of the convex
// hull of the 2D points. It can be computed using the rotating calipers
// algorithm. For details about the rotating calipers algorithm and computing
// the width of a set of 2D points, 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
namespace gte
{
template <typename T>
class MinimumWidthPoints2
{
public:
// The return value is an oriented box in 2D. The width of the point
// set is in the direction box.axis[0]; the width is 2*box.extent[0].
// The corresponding height is in the direction box.axis[1] =
// -Perp(box.axis[0]); the height is 2*box.extent[1].
// 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<T> operator()(int32_t numPoints, Vector2<T> const* points,
bool useRotatingCalipers = true)
{
LogAssert(
numPoints >= 3 && points != nullptr,
"Invalid input.");
OrientedBox2<T> box{};
// Get the convex hull of the points.
T const zero = static_cast<T>(0);
ConvexHull2<T> ch2{};
ch2(numPoints, points, zero);
int32_t dimension = ch2.GetDimension();
if (dimension == 0)
{
box.center = points[0];
box.axis[0] = Vector2<T>::Unit(0);
box.axis[1] = Vector2<T>::Unit(1);
box.extent[0] = zero;
box.extent[1] = zero;
return box;
}
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<T> const& line = ch2.GetLine();
T tmin = zero, tmax = zero;
for (int32_t i = 0; i < numPoints; ++i)
{
Vector2<T> diff = points[i] - line.origin;
T t = Dot(diff, line.direction);
if (t > tmax)
{
tmax = t;
}
else if (t < tmin)
{
tmin = t;
}
}
T const half = static_cast<T>(0.5);
box.center = line.origin + half * (tmin + tmax) * line.direction;
box.extent[0] = zero;
box.extent[1] = half * (tmax - tmin);
box.axis[0] = Perp(line.direction);
box.axis[1] = line.direction;
return box;
}
// Get the indexed convex hull with vertices converted to the
// compute type.
std::vector<int32_t> hull = ch2.GetHull();
std::vector<Vector2<T>> vertices(hull.size());
Vector2<T> const* hullPoints = ch2.GetPoints();
for (size_t i = 0; i < hull.size(); ++i)
{
vertices[i] = hullPoints[hull[i]];
}
ComputeMinWidth(vertices, useRotatingCalipers, box);
return box;
}
// 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<T> operator()(std::vector<Vector2<T>> const& points,
bool useRotatingCalipers = true)
{
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, set
// numIndices to 0 and indices to nullptr. If the polygon vertices
// are a subset of the incoming points, that subset is identified by
// numIndices >= 3 and indices having numIndices elements.
OrientedBox2<T> operator()(int32_t numPoints, Vector2<T> const* points,
int32_t numIndices, int32_t const* indices,
bool useRotatingCalipers = true)
{
LogAssert(
numPoints >= 3 && points != nullptr &&
((indices == nullptr && numIndices == 0) ||
(indices != nullptr && numIndices >= 3)),
"Invalid input.");
if (indices)
{
std::vector<Vector2<T>> compactPoints(numIndices);
for (int32_t i = 0; i < numIndices; ++i)
{
compactPoints[i] = points[indices[i]];
}
return operator()(compactPoints, useRotatingCalipers);
}
else
{
return operator()(numPoints, points, 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<T> operator()(std::vector<Vector2<T>> const& points,
std::vector<int32_t> const& indices,
bool useRotatingCalipers = true)
{
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);
}
}
private:
using RotatingCalipersType = RotatingCalipers<T>;
using AntipodeType = typename RotatingCalipersType::Antipode;
using Rational = BSRational<UIntegerAP32>;
void ComputeMinWidth(std::vector<Vector2<T>> const& vertices,
bool useRotatingCalipers, OrientedBox2<T>& box)
{
T const zero = static_cast<T>(0);
std::function<Vector2<T>(size_t)> GetVertex{};
std::vector<size_t> indices{};
size_t numElements{}, i0Min{}, i1Min{};
T minWidth{};
if (useRotatingCalipers)
{
std::vector<AntipodeType> antipodes{};
RotatingCalipersType::ComputeAntipodes(vertices, antipodes);
LogAssert(
antipodes.size() > 0,
"Antipodes must exist.");
Rational minSqrWidth = ComputeSqrWidth(vertices, antipodes[0]);
size_t minAntipode = 0;
for (size_t i = 1; i < antipodes.size(); ++i)
{
Rational sqrWidth = ComputeSqrWidth(vertices, antipodes[i]);
if (sqrWidth < minSqrWidth)
{
minSqrWidth = sqrWidth;
minAntipode = i;
}
}
minWidth = std::sqrt(minSqrWidth);
GetVertex = [&vertices](size_t j) { return vertices[j]; };
numElements = vertices.size();
i0Min = antipodes[minAntipode].edge[0];
i1Min = antipodes[minAntipode].edge[1];
}
else
{
// Remove duplicate and collinear vertices.
size_t const numVertices = vertices.size();
indices.reserve(numVertices);
Vector2<T> ePrev = vertices.front() - vertices.back();
for (size_t i0 = 0, i1 = 1; i0 < numVertices; ++i0)
{
Vector2<T> eNext = vertices[i1] - vertices[i0];
T dp = DotPerp(ePrev, eNext);
if (dp != zero)
{
indices.push_back(i0);
}
ePrev = eNext;
if (++i1 == numVertices)
{
i1 = 0;
}
}
// Iterate over the polygon edges to search for the edge that
// leads to the minimum width.
size_t const numIndices = indices.size();
minWidth = std::numeric_limits<T>::max();
i0Min = numIndices - 1;
i1Min = 0;
for (size_t i0 = numIndices - 1, i1 = 0; i1 < indices.size(); i0 = i1++)
{
Vector2<T> const& origin = vertices[indices[i0]];
Vector2<T> U = vertices[indices[i1]] - origin;
Normalize(U);
T maxWidth = zero;
for (size_t j = 0; j < numIndices; ++j)
{
Vector2<T> diff = vertices[indices[j]] - origin;
T width = U[0] * diff[1] - U[1] * diff[0];
if (width > maxWidth)
{
maxWidth = width;
}
}
if (maxWidth < minWidth)
{
minWidth = maxWidth;
i0Min = i0;
i1Min = i1;
}
}
GetVertex = [&vertices, &indices](size_t j)
{
return vertices[indices[j]];
};
numElements = numIndices;
}
Vector2<T> origin{}, U{};
T minHeight{}, maxHeight{};
Compute(GetVertex, numElements, i0Min, i1Min,
origin, U, minHeight, maxHeight);
T const half = static_cast<T>(0.5);
box.extent[0] = half * minWidth;
box.extent[1] = half * (maxHeight - minHeight);
box.axis[0] = -Perp(U);
box.axis[1] = U;
box.center = origin + box.extent[0] * box.axis[0] +
(half * (maxHeight + minHeight)) * box.axis[1];
}
Rational ComputeSqrWidth(std::vector<Vector2<T>> const& vertices,
AntipodeType const& antipode)
{
Vector2<T> const& V = vertices[antipode.vertex];
Vector2<T> const& E0 = vertices[antipode.edge[0]];
Vector2<T> const& E1 = vertices[antipode.edge[1]];
Vector2<Rational> rV = { V[0], V[1] };
Vector2<Rational> rE0 = { E0[0], E0[1] };
Vector2<Rational> rE1 = { E1[0], E1[1] };
Vector2<Rational> rU = rE1 - rE0;
Vector2<Rational> rDiff = rV - rE0;
Rational rDotPerp = rU[1] * rDiff[0] - rU[0] * rDiff[1];
Rational rSqrLenU = Dot(rU, rU);
Rational rSqrWidth = rDotPerp * rDotPerp / rSqrLenU;
return rSqrWidth;
}
void Compute(std::function<Vector2<T>(size_t)> const& GetVertex,
size_t numElements, size_t i0Min, size_t i1Min,
Vector2<T>& origin, Vector2<T>& U, T& minHeight, T& maxHeight)
{
T const zero = static_cast<T>(0);
origin = GetVertex(i0Min);
U = GetVertex(i1Min) - origin;
Normalize(U);
minHeight = zero;
maxHeight = zero;
for (size_t j = 0; j < numElements; ++j)
{
Vector2<T> diff = GetVertex(j) - origin;
T height = Dot(U, diff);
if (height < minHeight)
{
minHeight = height;
}
else if (height > maxHeight)
{
maxHeight = height;
}
}
}
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Frustum3.h | .h | 6,153 | 221 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector3.h>
// Orthogonal frustum. Let E be the origin, D be the direction vector, U be
// the up vector, and R be the right vector. Let u > 0 and r > 0 be the
// extents in the U and R directions, respectively. Let n and f be the
// extents in the D direction with 0 < n < f. The four corners of the frustum
// in the near plane are E + n*D + s0*u*U + s1*r*R where |s0| = |s1| = 1 (four
// choices). The four corners of the frustum in the far plane are
// E + f*D + (f/n)*(s0*u*U + s1*r*R) where |s0| = |s1| = 1 (four choices).
namespace gte
{
template <typename Real>
class Frustum3
{
public:
// Construction and destruction. The default constructor sets the
// following values: origin (E) to (0,0,0), dVector (D) to (0,0,1),
// uVector (U) to (0,1,0), rVector (R) to (1,0,0), dMin (n) to 1,
// dMax (f) to 2, uBound (u) to 1, and rBound (r) to 1.
Frustum3()
:
origin(Vector3<Real>::Zero()),
dVector(Vector3<Real>::Unit(2)),
uVector(Vector3<Real>::Unit(1)),
rVector(Vector3<Real>::Unit(0)),
dMin((Real)1),
dMax((Real)2),
uBound((Real)1),
rBound((Real)1)
{
Update();
}
Frustum3(Vector3<Real> const& inOrigin, Vector3<Real> const& inDVector,
Vector3<Real> const& inUVector, Vector3<Real> const& inRVector,
Real inDMin, Real inDMax, Real inUBound, Real inRBound)
:
origin(inOrigin),
dVector(inDVector),
uVector(inUVector),
rVector(inRVector),
dMin(inDMin),
dMax(inDMax),
uBound(inUBound),
rBound(inRBound)
{
Update();
}
// The Update() function must be called whenever changes are made to
// dMin, dMax, uBound or rBound. The values mDRatio, mMTwoUF and
// mMTwoRF are dependent on the changes, so call the Get*() accessors
// only after the Update() call.
void Update()
{
mDRatio = dMax / dMin;
mMTwoUF = (Real)-2 * uBound * dMax;
mMTwoRF = (Real)-2 * rBound * dMax;
}
inline Real GetDRatio() const
{
return mDRatio;
}
inline Real GetMTwoUF() const
{
return mMTwoUF;
}
inline Real GetMTwoRF() const
{
return mMTwoRF;
}
void ComputeVertices(std::array<Vector3<Real>, 8>& vertex) const
{
Vector3<Real> dScaled = dMin * dVector;
Vector3<Real> uScaled = uBound * uVector;
Vector3<Real> rScaled = rBound * rVector;
vertex[0] = dScaled - uScaled - rScaled;
vertex[1] = dScaled - uScaled + rScaled;
vertex[2] = dScaled + uScaled + rScaled;
vertex[3] = dScaled + uScaled - rScaled;
for (int32_t i = 0, ip = 4; i < 4; ++i, ++ip)
{
vertex[ip] = origin + mDRatio * vertex[i];
vertex[i] += origin;
}
}
Vector3<Real> origin, dVector, uVector, rVector;
Real dMin, dMax, uBound, rBound;
public:
// Comparisons to support sorted containers.
bool operator==(Frustum3 const& frustum) const
{
return origin == frustum.origin
&& dVector == frustum.dVector
&& uVector == frustum.uVector
&& rVector == frustum.rVector
&& dMin == frustum.dMin
&& dMax == frustum.dMax
&& uBound == frustum.uBound
&& rBound == frustum.rBound;
}
bool operator!=(Frustum3 const& frustum) const
{
return !operator==(frustum);
}
bool operator< (Frustum3 const& frustum) const
{
if (origin < frustum.origin)
{
return true;
}
if (origin > frustum.origin)
{
return false;
}
if (dVector < frustum.dVector)
{
return true;
}
if (dVector > frustum.dVector)
{
return false;
}
if (uVector < frustum.uVector)
{
return true;
}
if (uVector > frustum.uVector)
{
return false;
}
if (rVector < frustum.rVector)
{
return true;
}
if (rVector > frustum.rVector)
{
return false;
}
if (dMin < frustum.dMin)
{
return true;
}
if (dMin > frustum.dMin)
{
return false;
}
if (dMax < frustum.dMax)
{
return true;
}
if (dMax > frustum.dMax)
{
return false;
}
if (uBound < frustum.uBound)
{
return true;
}
if (uBound > frustum.uBound)
{
return false;
}
return rBound < frustum.rBound;
}
bool operator<=(Frustum3 const& frustum) const
{
return !frustum.operator<(*this);
}
bool operator> (Frustum3 const& frustum) const
{
return frustum.operator<(*this);
}
bool operator>=(Frustum3 const& frustum) const
{
return !operator<(frustum);
}
protected:
// Quantities derived from the constructor inputs.
Real mDRatio, mMTwoUF, mMTwoRF;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrSegment3Capsule3.h | .h | 3,746 | 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/DistSegmentSegment.h>
#include <Mathematics/IntrIntervals.h>
#include <Mathematics/IntrLine3Capsule3.h>
// The queries consider the capsule to be a solid.
//
// The test-intersection queries are based on distance computations.
namespace gte
{
template <typename T>
class TIQuery<T, Segment3<T>, Capsule3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Segment3<T> const& segment, Capsule3<T> const& capsule)
{
Result result{};
DCPQuery<T, Segment3<T>, Segment3<T>> ssQuery{};
auto ssResult = ssQuery(segment, capsule.segment);
result.intersect = (ssResult.distance <= capsule.radius);
return result;
}
};
template <typename T>
class FIQuery<T, Segment3<T>, Capsule3<T>>
:
public FIQuery<T, Line3<T>, Capsule3<T>>
{
public:
struct Result
:
public FIQuery<T, Line3<T>, Capsule3<T>>::Result
{
Result()
:
FIQuery<T, Line3<T>, Capsule3<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Segment3<T> const& segment, Capsule3<T> const& capsule)
{
Vector3<T> segOrigin{}, segDirection{};
T segExtent{};
segment.GetCenteredForm(segOrigin, segDirection, segExtent);
Result result{};
DoQuery(segOrigin, segDirection, segExtent, capsule, 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,
Capsule3<T> const& capsule, Result& result)
{
FIQuery<T, Line3<T>, Capsule3<T>>::DoQuery(
segOrigin, segDirection, capsule, result);
if (result.intersect)
{
// The line containing the segment intersects the capsule; the
// t-interval is [t0,t1]. The segment intersects the capsule
// 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
// capsule.
result = Result{};
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ContScribeCircle2.h | .h | 2,017 | 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/Hypersphere.h>
#include <Mathematics/LinearSystem.h>
namespace gte
{
// All functions return 'true' if the circle has been constructed, 'false'
// otherwise (input points are linearly dependent).
// Circle circumscribing triangle.
template <typename Real>
bool Circumscribe(Vector2<Real> const& v0, Vector2<Real> const& v1,
Vector2<Real> const& v2, Circle2<Real>& circle)
{
Vector2<Real> e10 = v1 - v0;
Vector2<Real> e20 = v2 - v0;
Matrix2x2<Real> A{ e10[0], e10[1], e20[0], e20[1] };
Vector2<Real> B{ (Real)0.5 * Dot(e10, e10), (Real)0.5 * Dot(e20, e20) };
Vector2<Real> solution;
if (LinearSystem<Real>::Solve(A, B, solution))
{
circle.center = v0 + solution;
circle.radius = Length(solution);
return true;
}
return false;
}
// Circle inscribing triangle.
template <typename Real>
bool Inscribe(Vector2<Real> const& v0, Vector2<Real> const& v1,
Vector2<Real> const& v2, Circle2<Real>& circle)
{
Vector2<Real> d10 = v1 - v0;
Vector2<Real> d20 = v2 - v0;
Vector2<Real> d21 = v2 - v1;
Real len10 = Length(d10);
Real len20 = Length(d20);
Real len21 = Length(d21);
Real perimeter = len10 + len20 + len21;
if (perimeter > (Real)0)
{
Real inv = (Real)1 / perimeter;
len10 *= inv;
len20 *= inv;
len21 *= inv;
circle.center = len21 * v0 + len20 * v1 + len10 * v2;
circle.radius = inv * std::fabs(DotPerp(d10, d20));
return circle.radius > (Real)0;
}
return false;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistRaySegment.h | .h | 7,063 | 209 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/DCPQuery.h>
#include <Mathematics/Ray.h>
#include <Mathematics/Segment.h>
// Compute the distance between a ray and a segment in nD.
//
// The ray is P[0] + s[0] * D[0] for s[0] >= 0. D[0] is not required to be
// unit length.
//
// The segment is Q[0] + s[1] * (Q[1] - Q[0]) for 0 <= s[1 <= 1. The
// direction D = Q[1] - Q[0] is generally not unit length.
//
// The closest point on the ray is stored in closest[0] with parameter[0]
// storing s[0]. The closest point on the segment is stored 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, Ray<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()(Ray<N, T> const& ray, 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 = ray.origin - segment.p[0];
T a00 = Dot(ray.direction, ray.direction);
T a01 = -Dot(ray.direction, segDirection);
T a11 = Dot(segDirection, segDirection);
T b0 = Dot(ray.direction, diff);
T det = std::max(a00 * a11 - a01 * a01, zero);
T s0{}, s1{};
if (det > zero)
{
// The ray and segment are not parallel.
T b1 = -Dot(segDirection, diff);
s0 = a01 * b1 - a11 * b0;
s1 = a01 * b0 - a00 * b1;
if (s0 >= zero)
{
if (s1 >= zero)
{
if (s1 <= det) // region 0
{
// The minimum occurs at interior points of the
// ray and the segment.
s0 /= det;
s1 /= det;
}
else // region 1
{
// The endpoint Q1 of the segment and an interior
// point of the line are closest.
s0 = -(a01 + b0) / a00;
s1 = one;
}
}
else // region 5
{
// The endpoint Q0 of the segment and an interior
// point of the line are closest.
s0 = -b0 / a00;
s1 = zero;
}
}
else // s0 < 0
{
if (s1 <= zero) // region 4
{
s0 = -b0;
if (s0 > zero)
{
s0 /= a00;
s1 = zero;
}
else
{
s0 = zero;
s1 = -b1;
if (s1 < zero)
{
s1 = zero;
}
else if (s1 > a11)
{
s1 = one;
}
else
{
s1 /= a11;
}
}
}
else if (s1 <= det) // region 3
{
s0 = zero;
s1 = -b1;
if (s1 < zero)
{
s1 = zero;
}
else if (s1 > a11)
{
s1 = one;
}
else
{
s1 /= a11;
}
}
else // region 2
{
s0 = -(a01 + b0);
if (s0 > zero)
{
s0 /= a00;
s1 = one;
}
else
{
s0 = zero;
s1 = -b1;
if (s1 < zero)
{
s1 = zero;
}
else if (s1 > a11)
{
s1 = one;
}
else
{
s1 /= a11;
}
}
}
}
}
else
{
// The ray and segment are parallel.
if (a01 > zero)
{
// Opposite direction vectors.
s0 = -b0 / a00;
s1 = zero;
}
else
{
// Same direction vectors.
s0 = -(a01 + b0) / a00;
s1 = one;
}
}
result.parameter[0] = s0;
result.parameter[1] = s1;
result.closest[0] = ray.origin + s0 * ray.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 DCPRaySegment = DCPQuery<T, Ray<N, T>, Segment<N, T>>;
template <typename T>
using DCPRay2Segment2 = DCPRaySegment<2, T>;
template <typename T>
using DCPRay3Segment3 = DCPRaySegment<3, T>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntpThinPlateSpline3.h | .h | 10,139 | 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/GMatrix.h>
#include <array>
// WARNING. The implementation allows you to transform the inputs (x,y,z) to
// the unit cube and perform the interpolation in that space. The idea is
// to keep the floating-point numbers to order 1 for numerical stability of
// the algorithm. The classical thin-plate spline algorithm does not include
// this transformation. The interpolation is invariant to translations and
// rotations of (x,y,z) but not to scaling. The following document is about
// thin plate splines.
// https://www.geometrictools.com/Documentation/ThinPlateSplines.pdf
namespace gte
{
template <typename Real>
class IntpThinPlateSpline3
{
public:
// Construction. Data points are (x,y,z,f(x,y,z)). The smoothing
// parameter must be nonnegative
IntpThinPlateSpline3(int32_t numPoints, Real const* X, Real const* Y,
Real const* Z, Real const* F, Real smooth, bool transformToUnitCube)
:
mNumPoints(numPoints),
mX(numPoints),
mY(numPoints),
mZ(numPoints),
mSmooth(smooth),
mA(numPoints),
mB{ (Real)0, (Real)0, (Real)0, (Real)0 },
mInitialized(false)
{
LogAssert(numPoints >= 4 && X != nullptr && Y != nullptr
&& Z != nullptr && F != nullptr && smooth >= (Real)0, "Invalid input.");
int32_t i, row, col;
if (transformToUnitCube)
{
// Map input (x,y,z) to unit cube. This is not part of the
// classical thin-plate spline algorithm, because the
// interpolation is not invariant to scalings.
auto extreme = std::minmax_element(X, X + mNumPoints);
mXMin = *extreme.first;
mXMax = *extreme.second;
mXInvRange = (Real)1 / (mXMax - mXMin);
for (i = 0; i < mNumPoints; ++i)
{
mX[i] = (X[i] - mXMin) * mXInvRange;
}
extreme = std::minmax_element(Y, Y + mNumPoints);
mYMin = *extreme.first;
mYMax = *extreme.second;
mYInvRange = (Real)1 / (mYMax - mYMin);
for (i = 0; i < mNumPoints; ++i)
{
mY[i] = (Y[i] - mYMin) * mYInvRange;
}
extreme = std::minmax_element(Z, Z + mNumPoints);
mZMin = *extreme.first;
mZMax = *extreme.second;
mZInvRange = (Real)1 / (mZMax - mZMin);
for (i = 0; i < mNumPoints; ++i)
{
mZ[i] = (Z[i] - mZMin) * mZInvRange;
}
}
else
{
// The classical thin-plate spline uses the data as is. The
// values mXMax, mYMax, and mZMax are not used, but they are
// initialized anyway (to irrelevant numbers).
mXMin = (Real)0;
mXMax = (Real)1;
mXInvRange = (Real)1;
mYMin = (Real)0;
mYMax = (Real)1;
mYInvRange = (Real)1;
mZMin = (Real)0;
mZMax = (Real)1;
mZInvRange = (Real)1;
std::copy(X, X + mNumPoints, mX.begin());
std::copy(Y, Y + mNumPoints, mY.begin());
std::copy(Z, Z + mNumPoints, mZ.begin());
}
// Compute matrix A = M + lambda*I [NxN matrix].
GMatrix<Real> AMat(mNumPoints, mNumPoints);
for (row = 0; row < mNumPoints; ++row)
{
for (col = 0; col < mNumPoints; ++col)
{
if (row == col)
{
AMat(row, col) = mSmooth;
}
else
{
Real dx = mX[row] - mX[col];
Real dy = mY[row] - mY[col];
Real dz = mZ[row] - mZ[col];
Real t = std::sqrt(dx * dx + dy * dy + dz * dz);
AMat(row, col) = Kernel(t);
}
}
}
// Compute matrix B [Nx4 matrix].
GMatrix<Real> BMat(mNumPoints, 4);
for (row = 0; row < mNumPoints; ++row)
{
BMat(row, 0) = (Real)1;
BMat(row, 1) = mX[row];
BMat(row, 2) = mY[row];
BMat(row, 3) = mZ[row];
}
// Compute A^{-1}.
bool invertible = false;
GMatrix<Real> invAMat = Inverse(AMat, &invertible);
if (!invertible)
{
return;
}
// Compute P = B^t A^{-1} [4xN matrix].
GMatrix<Real> PMat = MultiplyATB(BMat, invAMat);
// Compute Q = P B = B^t A^{-1} B [4x4 matrix].
GMatrix<Real> QMat = PMat * BMat;
// Compute Q^{-1}.
GMatrix<Real> invQMat = Inverse(QMat, &invertible);
if (!invertible)
{
return;
}
// Compute P*w.
std::array<Real, 4> prod;
for (row = 0; row < 4; ++row)
{
prod[row] = (Real)0;
for (i = 0; i < mNumPoints; ++i)
{
prod[row] += PMat(row, i) * F[i];
}
}
// Compute 'b' vector for smooth thin plate spline.
for (row = 0; row < 4; ++row)
{
mB[row] = (Real)0;
for (i = 0; i < 4; ++i)
{
mB[row] += invQMat(row, i) * prod[i];
}
}
// Compute w-B*b.
std::vector<Real> tmp(mNumPoints);
for (row = 0; row < mNumPoints; ++row)
{
tmp[row] = F[row];
for (i = 0; i < 4; ++i)
{
tmp[row] -= BMat(row, i) * mB[i];
}
}
// Compute 'a' vector for smooth thin plate spline.
for (row = 0; row < mNumPoints; ++row)
{
mA[row] = (Real)0;
for (i = 0; i < mNumPoints; ++i)
{
mA[row] += invAMat(row, i) * tmp[i];
}
}
mInitialized = true;
}
// Check this after the constructor call to see whether the thin plate
// spline coefficients were successfully computed. If so, then calls
// to operator()(Real,Real,Real) will work properly. TODO: This
// needs to be removed because the constructor now throws exceptions?
inline bool IsInitialized() const
{
return mInitialized;
}
// Evaluate the interpolator. If IsInitialized()returns 'false', the
// operator will return std::numeric_limits<Real>::max().
Real operator()(Real x, Real y, Real z) const
{
if (mInitialized)
{
// Map (x,y,z) to the unit cube.
x = (x - mXMin) * mXInvRange;
y = (y - mYMin) * mYInvRange;
z = (z - mZMin) * mZInvRange;
Real result = mB[0] + mB[1] * x + mB[2] * y + mB[3] * z;
for (int32_t i = 0; i < mNumPoints; ++i)
{
Real dx = x - mX[i];
Real dy = y - mY[i];
Real dz = z - mZ[i];
Real t = std::sqrt(dx * dx + dy * dy + dz * dz);
result += mA[i] * Kernel(t);
}
return result;
}
return std::numeric_limits<Real>::max();
}
// Compute the functional value a^T*M*a when lambda is zero or
// lambda*w^T*(M+lambda*I)*w when lambda is positive. See the thin
// plate splines PDF for a description of these quantities.
Real ComputeFunctional() const
{
Real functional = (Real)0;
for (int32_t row = 0; row < mNumPoints; ++row)
{
for (int32_t col = 0; col < mNumPoints; ++col)
{
if (row == col)
{
functional += mSmooth * mA[row] * mA[col];
}
else
{
Real dx = mX[row] - mX[col];
Real dy = mY[row] - mY[col];
Real dz = mZ[row] - mZ[col];
Real t = std::sqrt(dx * dx + dy * dy + dz * dz);
functional += Kernel(t) * mA[row] * mA[col];
}
}
}
if (mSmooth > (Real)0)
{
functional *= mSmooth;
}
return functional;
}
private:
// Kernel(t) = -|t|
static Real Kernel(Real t)
{
return -std::fabs(t);
}
// Input data.
int32_t mNumPoints;
std::vector<Real> mX;
std::vector<Real> mY;
std::vector<Real> mZ;
Real mSmooth;
// Thin plate spline coefficients. The A[] coefficients are associated
// with the Green's functions G(x,y,z,*) and the B[] coefficients are
// associated with the affine term B[0] + B[1]*x + B[2]*y + B[3]*z.
std::vector<Real> mA; // mNumPoints elements
std::array<Real, 4> mB;
// Extent of input data.
Real mXMin, mXMax, mXInvRange;
Real mYMin, mYMax, mYInvRange;
Real mZMin, mZMax, mZInvRange;
bool mInitialized;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrRay3OrientedBox3.h | .h | 3,510 | 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/IntrRay3AlignedBox3.h>
#include <Mathematics/OrientedBox.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, Ray3<T>, OrientedBox3<T>>
:
public TIQuery<T, Ray3<T>, AlignedBox3<T>>
{
public:
struct Result
:
public TIQuery<T, Ray3<T>, AlignedBox3<T>>::Result
{
Result()
:
TIQuery<T, Ray3<T>, AlignedBox3<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray3<T> const& ray, OrientedBox3<T> const& box)
{
// Transform the ray to the oriented-box coordinate system.
Vector3<T> diff = ray.origin - box.center;
Vector3<T> rayOrigin
{
Dot(diff, box.axis[0]),
Dot(diff, box.axis[1]),
Dot(diff, box.axis[2])
};
Vector3<T> rayDirection = Vector3<T>
{
Dot(ray.direction, box.axis[0]),
Dot(ray.direction, box.axis[1]),
Dot(ray.direction, box.axis[2])
};
Result result{};
this->DoQuery(rayOrigin, rayDirection, box.extent, result);
return result;
}
};
template <typename T>
class FIQuery<T, Ray3<T>, OrientedBox3<T>>
:
public FIQuery<T, Ray3<T>, AlignedBox3<T>>
{
public:
struct Result
:
public FIQuery<T, Ray3<T>, AlignedBox3<T>>::Result
{
Result()
:
FIQuery<T, Ray3<T>, AlignedBox3<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray3<T> const& ray, OrientedBox3<T> const& box)
{
// Transform the ray to the oriented-box coordinate system.
Vector3<T> diff = ray.origin - box.center;
Vector3<T> rayOrigin
{
Dot(diff, box.axis[0]),
Dot(diff, box.axis[1]),
Dot(diff, box.axis[2])
};
Vector3<T> rayDirection = Vector3<T>
{
Dot(ray.direction, box.axis[0]),
Dot(ray.direction, box.axis[1]),
Dot(ray.direction, box.axis[2])
};
Result result{};
this->DoQuery(rayOrigin, rayDirection, box.extent, result);
if (result.intersect)
{
for (size_t i = 0; i < 2; ++i)
{
result.point[i] = ray.origin + result.parameter[i] * ray.direction;
}
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrCircle2Circle2.h | .h | 6,138 | 172 | // 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/Hypersphere.h>
#include <Mathematics/Vector2.h>
namespace gte
{
template <typename Real>
class TIQuery<Real, Circle2<Real>, Circle2<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Circle2<Real> const& circle0, Circle2<Real> const& circle1)
{
Result result{};
Vector2<Real> diff = circle0.center - circle1.center;
result.intersect = (Length(diff) <= circle0.radius + circle1.radius);
return result;
}
};
template <typename Real>
class FIQuery<Real, Circle2<Real>, Circle2<Real>>
{
public:
struct Result
{
Result()
:
intersect(false),
numIntersections(0),
point{ Vector2<Real>::Zero(), Vector2<Real>::Zero() },
circle(Vector2<Real>::Zero(), (Real)0)
{
}
bool intersect;
// The number of intersections is 0, 1, 2 or maxInt =
// std::numeric_limits<int32_t>::max(). When 1, the circles are
// tangent and intersect in a single point. When 2, circles have
// two transverse intersection points. When maxInt, the circles
// are the same.
int32_t numIntersections;
// Valid only when numIntersections = 1 or 2.
std::array<Vector2<Real>, 2> point;
// Valid only when numIntersections = maxInt.
Circle2<Real> circle;
};
Result operator()(Circle2<Real> const& circle0, Circle2<Real> const& circle1)
{
// The two circles are |X-C0| = R0 and |X-C1| = R1. Define
// U = C1 - C0 and V = Perp(U) where Perp(x,y) = (y,-x). Note
// that Dot(U,V) = 0 and |V|^2 = |U|^2. The intersection points X
// can be written in the form X = C0+s*U+t*V and
// X = C1+(s-1)*U+t*V. Squaring the circle equations and
// substituting these formulas into them yields
// R0^2 = (s^2 + t^2)*|U|^2
// R1^2 = ((s-1)^2 + t^2)*|U|^2.
// Subtracting and solving for s yields
// s = ((R0^2-R1^2)/|U|^2 + 1)/2
// Then replace in the first equation and solve for t^2
// t^2 = (R0^2/|U|^2) - s^2.
// In order for there to be solutions, the right-hand side must be
// nonnegative. Some algebra leads to the condition for existence
// of solutions,
// (|U|^2 - (R0+R1)^2)*(|U|^2 - (R0-R1)^2) <= 0.
// This reduces to
// |R0-R1| <= |U| <= |R0+R1|.
// If |U| = |R0-R1|, then the circles are side-by-side and just
// tangent. If |U| = |R0+R1|, then the circles are nested and
// just tangent. If |R0-R1| < |U| < |R0+R1|, then the two circles
// to intersect in two points.
Result result{};
Vector2<Real> U = circle1.center - circle0.center;
Real USqrLen = Dot(U, U);
Real R0 = circle0.radius, R1 = circle1.radius;
Real R0mR1 = R0 - R1;
if (USqrLen == (Real)0 && R0mR1 == (Real)0)
{
// Circles are the same.
result.intersect = true;
result.numIntersections = std::numeric_limits<int32_t>::max();
result.circle = circle0;
return result;
}
Real R0mR1Sqr = R0mR1 * R0mR1;
if (USqrLen < R0mR1Sqr)
{
// The circles do not intersect.
result.intersect = false;
result.numIntersections = 0;
return result;
}
Real R0pR1 = R0 + R1;
Real R0pR1Sqr = R0pR1 * R0pR1;
if (USqrLen > R0pR1Sqr)
{
// The circles do not intersect.
result.intersect = false;
result.numIntersections = 0;
return result;
}
if (USqrLen < R0pR1Sqr)
{
if (R0mR1Sqr < USqrLen)
{
Real invUSqrLen = (Real)1 / USqrLen;
Real s = (Real)0.5 * ((R0 * R0 - R1 * R1) * invUSqrLen + (Real)1);
Vector2<Real> tmp = circle0.center + s * U;
// In theory, discr is nonnegative. However, numerical round-off
// errors can make it slightly negative. Clamp it to zero.
Real discr = R0 * R0 * invUSqrLen - s * s;
if (discr < (Real)0)
{
discr = (Real)0;
}
Real t = std::sqrt(discr);
Vector2<Real> V{ U[1], -U[0] };
result.point[0] = tmp - t * V;
result.point[1] = tmp + t * V;
result.numIntersections = (t > (Real)0 ? 2 : 1);
}
else
{
// |U| = |R0-R1|, circles are tangent.
result.numIntersections = 1;
result.point[0] = circle0.center + (R0 / R0mR1) * U;
}
}
else
{
// |U| = |R0+R1|, circles are tangent.
result.numIntersections = 1;
result.point[0] = circle0.center + (R0 / R0pR1) * U;
}
// The circles intersect in 1 or 2 points.
result.intersect = true;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/PrimalQuery3.h | .h | 10,093 | 294 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector3.h>
// Queries about the relation of a point to various geometric objects. The
// choices for N when using UIntegerFP32<N> for either BSNumber of BSRational
// are determined in GeometricTools/GTEngine/Tools/PrecisionCalculator. These
// N-values are worst case scenarios. Your specific input data might require
// much smaller N, in which case you can modify PrecisionCalculator to use the
// BSPrecision(int32_t,int32_t,int32_t,bool) constructors.
namespace gte
{
template <typename Real>
class PrimalQuery3
{
public:
// The caller is responsible for ensuring that the array is not empty
// before calling queries and that the indices passed to the queries
// are valid. The class does no range checking.
PrimalQuery3()
:
mNumVertices(0),
mVertices(nullptr)
{
}
PrimalQuery3(int32_t numVertices, Vector3<Real> const* vertices)
:
mNumVertices(numVertices),
mVertices(vertices)
{
}
// Member access.
inline void Set(int32_t numVertices, Vector3<Real> const* vertices)
{
mNumVertices = numVertices;
mVertices = vertices;
}
inline int32_t GetNumVertices() const
{
return mNumVertices;
}
inline Vector3<Real> const* GetVertices() const
{
return mVertices;
}
// In the following, point P refers to vertices[i] or 'test' and Vi
// refers to vertices[vi].
// For a plane with origin V0 and normal N = Cross(V1-V0,V2-V0),
// ToPlane returns
// +1, P on positive side of plane (side to which N points)
// -1, P on negative side of plane (side to which -N points)
// 0, P on the plane
//
// Choice of N for UIntegerFP32<N>.
// input type | compute type | N
// -----------+--------------+----
// float | BSNumber | 27
// double | BSNumber | 197
// float | BSRational | 79
// double | BSRational | 591
int32_t ToPlane(int32_t i, int32_t v0, int32_t v1, int32_t v2) const
{
return ToPlane(mVertices[i], v0, v1, v2);
}
int32_t ToPlane(Vector3<Real> const& test, int32_t v0, int32_t v1, int32_t v2) const
{
Vector3<Real> const& vec0 = mVertices[v0];
Vector3<Real> const& vec1 = mVertices[v1];
Vector3<Real> const& vec2 = mVertices[v2];
Real x0 = test[0] - vec0[0];
Real y0 = test[1] - vec0[1];
Real z0 = test[2] - vec0[2];
Real x1 = vec1[0] - vec0[0];
Real y1 = vec1[1] - vec0[1];
Real z1 = vec1[2] - vec0[2];
Real x2 = vec2[0] - vec0[0];
Real y2 = vec2[1] - vec0[1];
Real z2 = vec2[2] - vec0[2];
Real y1z2 = y1 * z2;
Real y2z1 = y2 * z1;
Real y2z0 = y2 * z0;
Real y0z2 = y0 * z2;
Real y0z1 = y0 * z1;
Real y1z0 = y1 * z0;
Real c0 = y1z2 - y2z1;
Real c1 = y2z0 - y0z2;
Real c2 = y0z1 - y1z0;
Real x0c0 = x0 * c0;
Real x1c1 = x1 * c1;
Real x2c2 = x2 * c2;
Real term = x0c0 + x1c1;
Real det = term + x2c2;
Real const zero(0);
return (det > zero ? +1 : (det < zero ? -1 : 0));
}
// For a tetrahedron with vertices ordered as described in the file
// TetrahedronKey.h, the function returns
// +1, P outside tetrahedron
// -1, P inside tetrahedron
// 0, P on tetrahedron
//
// Choice of N for UIntegerFP32<N>.
// input type | compute type | N
// -----------+--------------+----
// float | BSNumber | 27
// double | BSNumber | 197
// float | BSRational | 79
// double | BSRational | 591
// The query involves four calls of ToPlane, so the numbers match
// those of ToPlane.
int32_t ToTetrahedron(int32_t i, int32_t v0, int32_t v1, int32_t v2, int32_t v3) const
{
return ToTetrahedron(mVertices[i], v0, v1, v2, v3);
}
int32_t ToTetrahedron(Vector3<Real> const& test, int32_t v0, int32_t v1, int32_t v2, int32_t v3) const
{
int32_t sign0 = ToPlane(test, v1, v2, v3);
if (sign0 > 0)
{
return +1;
}
int32_t sign1 = ToPlane(test, v0, v2, v3);
if (sign1 < 0)
{
return +1;
}
int32_t sign2 = ToPlane(test, v0, v1, v3);
if (sign2 > 0)
{
return +1;
}
int32_t sign3 = ToPlane(test, v0, v1, v2);
if (sign3 < 0)
{
return +1;
}
return ((sign0 && sign1 && sign2 && sign3) ? -1 : 0);
}
// For a tetrahedron with vertices ordered as described in the file
// TetrahedronKey.h, the function returns
// +1, P outside circumsphere of tetrahedron
// -1, P inside circumsphere of tetrahedron
// 0, P on circumsphere of tetrahedron
//
// Choice of N for UIntegerFP32<N>.
// input type | compute type | N
// -----------+--------------+-----
// float | BSNumber | 44
// double | BSNumber | 329
// float | BSNumber | 262
// double | BSRational | 1969
int32_t ToCircumsphere(int32_t i, int32_t v0, int32_t v1, int32_t v2, int32_t v3) const
{
return ToCircumsphere(mVertices[i], v0, v1, v2, v3);
}
int32_t ToCircumsphere(Vector3<Real> const& test, int32_t v0, int32_t v1, int32_t v2, int32_t v3) const
{
Vector3<Real> const& vec0 = mVertices[v0];
Vector3<Real> const& vec1 = mVertices[v1];
Vector3<Real> const& vec2 = mVertices[v2];
Vector3<Real> const& vec3 = mVertices[v3];
Real x0 = vec0[0] - test[0];
Real y0 = vec0[1] - test[1];
Real z0 = vec0[2] - test[2];
Real s00 = vec0[0] + test[0];
Real s01 = vec0[1] + test[1];
Real s02 = vec0[2] + test[2];
Real t00 = s00 * x0;
Real t01 = s01 * y0;
Real t02 = s02 * z0;
Real t00pt01 = t00 + t01;
Real w0 = t00pt01 + t02;
Real x1 = vec1[0] - test[0];
Real y1 = vec1[1] - test[1];
Real z1 = vec1[2] - test[2];
Real s10 = vec1[0] + test[0];
Real s11 = vec1[1] + test[1];
Real s12 = vec1[2] + test[2];
Real t10 = s10 * x1;
Real t11 = s11 * y1;
Real t12 = s12 * z1;
Real t10pt11 = t10 + t11;
Real w1 = t10pt11 + t12;
Real x2 = vec2[0] - test[0];
Real y2 = vec2[1] - test[1];
Real z2 = vec2[2] - test[2];
Real s20 = vec2[0] + test[0];
Real s21 = vec2[1] + test[1];
Real s22 = vec2[2] + test[2];
Real t20 = s20 * x2;
Real t21 = s21 * y2;
Real t22 = s22 * z2;
Real t20pt21 = t20 + t21;
Real w2 = t20pt21 + t22;
Real x3 = vec3[0] - test[0];
Real y3 = vec3[1] - test[1];
Real z3 = vec3[2] - test[2];
Real s30 = vec3[0] + test[0];
Real s31 = vec3[1] + test[1];
Real s32 = vec3[2] + test[2];
Real t30 = s30 * x3;
Real t31 = s31 * y3;
Real t32 = s32 * z3;
Real t30pt31 = t30 + t31;
Real w3 = t30pt31 + t32;
Real x0y1 = x0 * y1;
Real x0y2 = x0 * y2;
Real x0y3 = x0 * y3;
Real x1y0 = x1 * y0;
Real x1y2 = x1 * y2;
Real x1y3 = x1 * y3;
Real x2y0 = x2 * y0;
Real x2y1 = x2 * y1;
Real x2y3 = x2 * y3;
Real x3y0 = x3 * y0;
Real x3y1 = x3 * y1;
Real x3y2 = x3 * y2;
Real a0 = x0y1 - x1y0;
Real a1 = x0y2 - x2y0;
Real a2 = x0y3 - x3y0;
Real a3 = x1y2 - x2y1;
Real a4 = x1y3 - x3y1;
Real a5 = x2y3 - x3y2;
Real z0w1 = z0 * w1;
Real z0w2 = z0 * w2;
Real z0w3 = z0 * w3;
Real z1w0 = z1 * w0;
Real z1w2 = z1 * w2;
Real z1w3 = z1 * w3;
Real z2w0 = z2 * w0;
Real z2w1 = z2 * w1;
Real z2w3 = z2 * w3;
Real z3w0 = z3 * w0;
Real z3w1 = z3 * w1;
Real z3w2 = z3 * w2;
Real b0 = z0w1 - z1w0;
Real b1 = z0w2 - z2w0;
Real b2 = z0w3 - z3w0;
Real b3 = z1w2 - z2w1;
Real b4 = z1w3 - z3w1;
Real b5 = z2w3 - z3w2;
Real a0b5 = a0 * b5;
Real a1b4 = a1 * b4;
Real a2b3 = a2 * b3;
Real a3b2 = a3 * b2;
Real a4b1 = a4 * b1;
Real a5b0 = a5 * b0;
Real term0 = a0b5 - a1b4;
Real term1 = term0 + a2b3;
Real term2 = term1 + a3b2;
Real term3 = term2 - a4b1;
Real det = term3 + a5b0;
Real const zero(0);
return (det > zero ? 1 : (det < zero ? -1 : 0));
}
private:
int32_t mNumVertices;
Vector3<Real> const* mVertices;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/WeakPtrCompare.h | .h | 2,226 | 82 | // 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 <memory>
// Comparison operators for std::weak_ptr objects. The type T must implement
// comparison operators. You must be careful when managing containers whose
// ordering is based on std::weak_ptr comparisons. The underlying objects
// can change, which invalidates the container ordering. If objects do not
// change while the container persists, these are safe to use.
namespace gte
{
// wp0 == wp1
template <typename T>
struct WeakPtrEQ
{
bool operator()(std::weak_ptr<T> const& wp0, std::weak_ptr<T> const& wp1) const
{
auto sp0 = wp0.lock(), sp1 = wp1.lock();
return (sp0 ? (sp1 ? *sp0 == *sp1 : false) : !sp1);
}
};
// wp0 != wp1
template <typename T>
struct WeakPtrNEQ
{
bool operator()(std::weak_ptr<T> const& wp0, std::weak_ptr<T> const& wp1) const
{
return !WeakPtrEQ<T>()(wp0, wp1);
}
};
// wp0 < wp1
template <typename T>
struct WeakPtrLT
{
bool operator()(std::weak_ptr<T> const& wp0, std::weak_ptr<T> const& wp1) const
{
auto sp0 = wp0.lock(), sp1 = wp1.lock();
return (sp1 ? (!sp0 || *sp0 < *sp1) : false);
}
};
// wp0 <= wp1
template <typename T>
struct WeakPtrLTE
{
bool operator()(std::weak_ptr<T> const& wp0, std::weak_ptr<T> const& wp1) const
{
return !WeakPtrLT<T>()(wp1, wp0);
}
};
// wp0 > wp1
template <typename T>
struct WeakPtrGT
{
bool operator()(std::weak_ptr<T> const& wp0, std::weak_ptr<T> const& wp1) const
{
return WeakPtrLT<T>()(wp1, wp0);
}
};
// wp0 >= wp1
template <typename T>
struct WeakPtrGTE
{
bool operator()(std::weak_ptr<T> const& wp0, std::weak_ptr<T> const& wp1) const
{
return !WeakPtrLT<T>()(wp0, wp1);
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Array2.h | .h | 3,922 | 146 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
// The Array2 class represents a 2-dimensional array that minimizes the number
// of new and delete calls. The T objects are stored in a contiguous array.
namespace gte
{
template <typename T>
class Array2
{
public:
// Construction. The first constructor generates an array of objects
// that are owned by Array2. The second constructor is given an array
// of objects that are owned by the caller. The array has bound0
// columns and bound1 rows.
Array2(size_t bound0, size_t bound1)
:
mBound0(bound0),
mBound1(bound1),
mObjects(bound0 * bound1),
mIndirect1(bound1)
{
SetPointers(mObjects.data());
}
Array2(size_t bound0, size_t bound1, T* objects)
:
mBound0(bound0),
mBound1(bound1),
mIndirect1(bound1)
{
SetPointers(objects);
}
// Support for dynamic resizing, copying, or moving. If 'other' does
// not own the original 'objects', they are not copied by the
// assignment operator.
Array2()
:
mBound0(0),
mBound1(0)
{
}
Array2(Array2 const& other)
:
mBound0(other.mBound0),
mBound1(other.mBound1)
{
*this = other;
}
Array2& operator=(Array2 const& other)
{
// The copy is valid whether or not other.mObjects has elements.
mObjects = other.mObjects;
SetPointers(other);
return *this;
}
Array2(Array2&& other) noexcept
:
mBound0(other.mBound0),
mBound1(other.mBound1)
{
*this = std::move(other);
}
Array2& operator=(Array2&& other) noexcept
{
// The move is valid whether or not other.mObjects has elements.
mObjects = std::move(other.mObjects);
SetPointers(other);
return *this;
}
// Access to the array. Sample usage is
// Array2<T> myArray(3, 2);
// T* row1 = myArray[1];
// T row1Col2 = myArray[1][2];
inline size_t GetBound0() const
{
return mBound0;
}
inline size_t GetBound1() const
{
return mBound1;
}
inline T const* operator[](int32_t row) const
{
return mIndirect1[row];
}
inline T* operator[](int32_t row)
{
return mIndirect1[row];
}
private:
void SetPointers(T* objects)
{
for (size_t i1 = 0; i1 < mBound1; ++i1)
{
size_t j0 = mBound0 * i1; // = bound0*(i1 + j1) where j1 = 0
mIndirect1[i1] = &objects[j0];
}
}
void SetPointers(Array2 const& other)
{
mBound0 = other.mBound0;
mBound1 = other.mBound1;
mIndirect1.resize(mBound1);
if (mBound0 > 0)
{
// The objects are owned.
SetPointers(mObjects.data());
}
else if (mIndirect1.size() > 0)
{
// The objects are not owned.
SetPointers(other.mIndirect1[0]);
}
// else 'other' is an empty Array2.
}
size_t mBound0, mBound1;
std::vector<T> mObjects;
std::vector<T*> mIndirect1;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Quaternion.h | .h | 14,847 | 484 | // 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/Vector.h>
#include <Mathematics/Matrix.h>
#include <Mathematics/ChebyshevRatio.h>
// A quaternion is of the form
// q = x * i + y * j + z * k + w * 1 = x * i + y * j + z * k + w
// where w, x, y, and z are real numbers. The scalar and vector parts are
// Vector(q) = x * i + y * j + z * k
// Scalar(q) = w
// q = Vector(q) + Scalar(q)
// I assume that you are familiar with the arithmetic and algebraic properties
// of quaternions. See
// https://www.geometrictools.com/Documentation/Quaternions.pdf
namespace gte
{
template <typename Real>
class Quaternion
{
public:
// The quaternions are of the form q = x*i + y*j + z*k + w. In tuple
// form, q = (x,y,z,w).
// Construction. The default constructor does not initialize the
// members.
Quaternion()
:
mTuple{ (Real)0, (Real)0, (Real)0, (Real)0 }
{
}
Quaternion(Real x, Real y, Real z, Real w)
:
mTuple{ x, y, z, w }
{
}
// Member access.
inline Real const& operator[](int32_t i) const
{
return mTuple[i];
}
inline Real& operator[](int32_t i)
{
return mTuple[i];
}
// Comparisons.
inline bool operator==(Quaternion const& q) const
{
return mTuple == q.mTuple;
}
inline bool operator!=(Quaternion const& q) const
{
return mTuple != q.mTuple;
}
inline bool operator<(Quaternion const& q) const
{
return mTuple < q.mTuple;
}
inline bool operator<=(Quaternion const& q) const
{
return mTuple <= q.mTuple;
}
inline bool operator>(Quaternion const& q) const
{
return mTuple > q.mTuple;
}
inline bool operator>=(Quaternion const& q) const
{
return mTuple >= q.mTuple;
}
// Special quaternions.
// z = 0*i + 0*j + 0*k + 0
static Quaternion Zero()
{
return Quaternion((Real)0, (Real)0, (Real)0, (Real)0);
}
// i = 1*i + 0*j + 0*k + 0
static Quaternion I()
{
return Quaternion((Real)1, (Real)0, (Real)0, (Real)0);
}
// j = 0*i + 1*j + 0*k + 0
static Quaternion J()
{
return Quaternion((Real)0, (Real)1, (Real)0, (Real)0);
}
// k = 0*i + 0*j + 1*k + 0
static Quaternion K()
{
return Quaternion((Real)0, (Real)0, (Real)1, (Real)0);
}
// 1 = 0*i + 0*j + 0*k + 1
static Quaternion Identity()
{
return Quaternion((Real)0, (Real)0, (Real)0, (Real)1);
}
protected:
std::array<Real, 4> mTuple;
};
// Unary operations.
template <typename Real>
Quaternion<Real> operator+(Quaternion<Real> const& q)
{
return q;
}
template <typename Real>
Quaternion<Real> operator-(Quaternion<Real> const& q)
{
Quaternion<Real> result;
for (int32_t i = 0; i < 4; ++i)
{
result[i] = -q[i];
}
return result;
}
// Linear algebraic operations.
template <typename Real>
Quaternion<Real> operator+(Quaternion<Real> const& q0, Quaternion<Real> const& q1)
{
Quaternion<Real> result = q0;
return result += q1;
}
template <typename Real>
Quaternion<Real> operator-(Quaternion<Real> const& q0, Quaternion<Real> const& q1)
{
Quaternion<Real> result = q0;
return result -= q1;
}
template <typename Real>
Quaternion<Real> operator*(Quaternion<Real> const& q, Real scalar)
{
Quaternion<Real> result = q;
return result *= scalar;
}
template <typename Real>
Quaternion<Real> operator*(Real scalar, Quaternion<Real> const& q)
{
Quaternion<Real> result = q;
return result *= scalar;
}
template <typename Real>
Quaternion<Real> operator/(Quaternion<Real> const& q, Real scalar)
{
Quaternion<Real> result = q;
return result /= scalar;
}
template <typename Real>
Quaternion<Real>& operator+=(Quaternion<Real>& q0, Quaternion<Real> const& q1)
{
for (int32_t i = 0; i < 4; ++i)
{
q0[i] += q1[i];
}
return q0;
}
template <typename Real>
Quaternion<Real>& operator-=(Quaternion<Real>& q0, Quaternion<Real> const& q1)
{
for (int32_t i = 0; i < 4; ++i)
{
q0[i] -= q1[i];
}
return q0;
}
template <typename Real>
Quaternion<Real>& operator*=(Quaternion<Real>& q, Real scalar)
{
for (int32_t i = 0; i < 4; ++i)
{
q[i] *= scalar;
}
return q;
}
template <typename Real>
Quaternion<Real>& operator/=(Quaternion<Real>& q, Real scalar)
{
if (scalar != (Real)0)
{
for (int32_t i = 0; i < 4; ++i)
{
q[i] /= scalar;
}
}
else
{
for (int32_t i = 0; i < 4; ++i)
{
q[i] = (Real)0;
}
}
return q;
}
// Geometric operations.
template <typename Real>
Real Dot(Quaternion<Real> const& q0, Quaternion<Real> const& q1)
{
Real dot = q0[0] * q1[0];
for (int32_t i = 1; i < 4; ++i)
{
dot += q0[i] * q1[i];
}
return dot;
}
template <typename Real>
Real Length(Quaternion<Real> const& q)
{
return std::sqrt(Dot(q, q));
}
template <typename Real>
Real Normalize(Quaternion<Real>& q)
{
Real length = std::sqrt(Dot(q, q));
if (length > (Real)0)
{
q /= length;
}
else
{
for (int32_t i = 0; i < 4; ++i)
{
q[i] = (Real)0;
}
}
return length;
}
// Multiplication of quaternions. This operation is not generally
// commutative; that is, q0*q1 and q1*q0 are not usually the same value.
// (x0*i + y0*j + z0*k + w0)*(x1*i + y1*j + z1*k + w1)
// =
// i*(+x0*w1 + y0*z1 - z0*y1 + w0*x1) +
// j*(-x0*z1 + y0*w1 + z0*x1 + w0*y1) +
// k*(+x0*y1 - y0*x1 + z0*w1 + w0*z1) +
// 1*(-x0*x1 - y0*y1 - z0*z1 + w0*w1)
template <typename Real>
Quaternion<Real> operator*(Quaternion<Real> const& q0, Quaternion<Real> const& q1)
{
// (x0*i + y0*j + z0*k + w0)*(x1*i + y1*j + z1*k + w1)
// =
// i*(+x0*w1 + y0*z1 - z0*y1 + w0*x1) +
// j*(-x0*z1 + y0*w1 + z0*x1 + w0*y1) +
// k*(+x0*y1 - y0*x1 + z0*w1 + w0*z1) +
// 1*(-x0*x1 - y0*y1 - z0*z1 + w0*w1)
return Quaternion<Real>
(
+q0[0] * q1[3] + q0[1] * q1[2] - q0[2] * q1[1] + q0[3] * q1[0],
-q0[0] * q1[2] + q0[1] * q1[3] + q0[2] * q1[0] + q0[3] * q1[1],
+q0[0] * q1[1] - q0[1] * q1[0] + q0[2] * q1[3] + q0[3] * q1[2],
-q0[0] * q1[0] - q0[1] * q1[1] - q0[2] * q1[2] + q0[3] * q1[3]
);
}
// For a nonzero quaternion q = (x,y,z,w), inv(q) = (-x,-y,-z,w)/|q|^2,
// where |q| is the length of the quaternion. When q is zero, the
// function returns zero, which is considered to be an improbable case.
template <typename Real>
Quaternion<Real> Inverse(Quaternion<Real> const& q)
{
Real sqrLen = Dot(q, q);
if (sqrLen > (Real)0)
{
Quaternion<Real> inverse = Conjugate(q) / sqrLen;
return inverse;
}
else
{
return Quaternion<Real>::Zero();
}
}
// The conjugate of q = (x,y,z,w) is conj(q) = (-x,-y,-z,w).
template <typename Real>
Quaternion<Real> Conjugate(Quaternion<Real> const& q)
{
return Quaternion<Real>(-q[0], -q[1], -q[2], +q[3]);
}
// Rotate a 3D vector v = (v0,v1,v2) using quaternion multiplication. The
// input quaternion must be unit length. If R is the rotation matrix
// corresponding to the quaternion q, the rotated vector u corresponding
// to v is u = R*v when GTE_USE_MAT_VEC is defined (the default for
// projects) or u = v*R when GTE_USE_MAT_VEC is not defined.
template <typename Real>
Vector<3, Real> Rotate(Quaternion<Real> const& q, Vector<3, Real> const& v)
{
Quaternion<Real> input(v[0], v[1], v[2], (Real)0);
#if defined(GTE_USE_MAT_VEC)
Quaternion<Real> output = q * input * Conjugate(q);
#else
Quaternion<Real> output = Conjugate(q) * input * q;
#endif
Vector<3, Real> u{ output[0], output[1], output[2] };
return u;
}
// Rotate a 3D vector, represented as a homogeneous 4D vector
// v = (v0,v1,v2,0), using quaternion multiplication. The input quaternion
// must be unit length. If R is the rotation matrix corresponding to the
// quaternion q, the rotated vector u corresponding to v is u = R*v when
// GTE_USE_MAT_VEC is defined (the default for projects) or u = v*R when
// GTE_USE_MAT_VEC is not defined.
template <typename Real>
Vector<4, Real> Rotate(Quaternion<Real> const& q, Vector<4, Real> const& v)
{
Quaternion<Real> input(v[0], v[1], v[2], (Real)0);
#if defined(GTE_USE_MAT_VEC)
Quaternion<Real> output = q * input * Conjugate(q);
#else
Quaternion<Real> output = Conjugate(q) * input * q;
#endif
Vector<4, Real> u{ output[0], output[1], output[2], (Real)0 };
return u;
}
// The spherical linear interpolation (slerp) of unit-length quaternions
// q0 and q1 for t in [0,1] is
// slerp(t,q0,q1) = [sin(t*theta)*q0 + sin((1-t)*theta)*q1]/sin(theta)
// where theta is the angle between q0 and q1 [cos(theta) = Dot(q0,q1)].
// This function is a parameterization of the great spherical arc between
// q0 and q1 on the unit hypersphere. Moreover, the parameterization is
// one of normalized arclength--a particle traveling along the arc through
// time t does so with constant speed.
//
// When using slerp in animations involving sequences of quaternions, it
// is typical that the quaternions are preprocessed so that consecutive
// ones form an acute angle A in [0,pi/2]. Other preprocessing can help
// with performance. See the function comments below.
//
// See SlerpEstimate.{h,inl} for various approximations, including
// SLERP<Real>::EstimateRPH that gives good performance and accurate
// results for preprocessed quaternions.
// The angle between q0 and q1 is in [0,pi). There are no angle
// restrictions and nothing is precomputed.
template <typename Real>
Quaternion<Real> Slerp(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1)
{
Real cosA = Dot(q0, q1);
Real sign;
if (cosA >= (Real)0)
{
sign = (Real)1;
}
else
{
cosA = -cosA;
sign = (Real)-1;
}
Real f0, f1;
ChebyshevRatio<Real>::Get(t, cosA, f0, f1);
return q0 * f0 + q1 * (sign * f1);
}
// The angle between q0 and q1 must be in [0,pi/2]. The suffix R is for
// 'Restricted'. The preprocessing code is
// Quaternion<Real> q[n]; // assuming initialized
// for (i0 = 0, i1 = 1; i1 < n; i0 = i1++)
// {
// cosA = Dot(q[i0], q[i1]);
// if (cosA < 0)
// {
// q[i1] = -q[i1]; // now Dot(q[i0], q[i]1) >= 0
// }
// }
template <typename Real>
Quaternion<Real> SlerpR(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1)
{
Real f0, f1;
ChebyshevRatio<Real>::Get(t, Dot(q0, q1), f0, f1);
return q0 * f0 + q1 * f1;
}
// The angle between q0 and q1 must be in [0,pi/2]. The suffix R is for
// 'Restricted' and the suffix P is for 'Preprocessed'. The preprocessing
// code is
// Quaternion<Real> q[n]; // assuming initialized
// Real cosA[n-1], omcosA[n-1]; // to be precomputed
// for (i0 = 0, i1 = 1; i1 < n; i0 = i1++)
// {
// cs = Dot(q[i0], q[i1]);
// if (cosA[i0] < 0)
// {
// q[i1] = -q[i1];
// cs = -cs;
// }
//
// // for Quaterion<Real>::SlerpRP
// cosA[i0] = cs;
//
// // for SLERP<Real>::EstimateRP
// omcosA[i0] = 1 - cs;
// }
template <typename Real>
Quaternion<Real> SlerpRP(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1, Real cosA)
{
Real f0, f1;
ChebyshevRatio<Real>::Get(t, cosA, f0, f1);
return q0 * f0 + q1 * f1;
}
// The angle between q0 and q1 is A and must be in [0,pi/2]. The suffix R
// is for 'Restricted', the suffix P is for 'Preprocessed' and the suffix
// H is for 'Half' (the quaternion qh halfway between q0 and q1 is
// precomputed). Quaternion qh is slerp(1/2,q0,q1) = (q0+q1)/|q0+q1|, so
// the angle between q0 and qh is A/2 and the angle between qh and q1 is
// A/2. The preprocessing code is
// Quaternion<Real> q[n]; // assuming initialized
// Quaternion<Real> qh[n-1]; // to be precomputed
// Real omcosAH[n-1]; // to be precomputed
// for (i0 = 0, i1 = 1; i1 < n; i0 = i1++)
// {
// cosA = Dot(q[i0], q[i1]);
// if (cosA < 0)
// {
// q[i1] = -q[i1];
// cosA = -cosA;
// }
//
// // for Quaternion<Real>::SlerpRPH and SLERP<Real>::EstimateRPH
// cosAH[i0] = sqrt((1+cosA)/2);
// qh[i0] = (q0 + q1) / (2 * cosAH[i0]);
//
// // for SLERP<Real>::EstimateRPH
// omcosAH[i0] = 1 - cosAH[i0];
// }
template <typename Real>
Quaternion<Real> SlerpRPH(Real t, Quaternion<Real> const& q0, Quaternion<Real> const& q1,
Quaternion<Real> const& qh, Real cosAH)
{
Real f0, f1;
Real twoT = static_cast<Real>(2) * t;
if (twoT <= static_cast<Real>(1))
{
ChebyshevRatio<Real>::Get(twoT, cosAH, f0, f1);
return q0 * f0 + qh * f1;
}
else
{
ChebyshevRatio<Real>::Get(twoT - static_cast<Real>(1), cosAH, f0, f1);
return qh * f0 + q1 * f1;
}
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ContScribeCircle3Sphere3.h | .h | 4,965 | 170 | // 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/Circle3.h>
#include <Mathematics/Hypersphere.h>
#include <Mathematics/LinearSystem.h>
namespace gte
{
// All functions return 'true' if circle/sphere has been constructed,
// 'false' otherwise (input points are linearly dependent).
// Circle circumscribing a triangle in 3D.
template <typename Real>
bool Circumscribe(Vector3<Real> const& v0, Vector3<Real> const& v1,
Vector3<Real> const& v2, Circle3<Real>& circle)
{
Vector3<Real> E02 = v0 - v2;
Vector3<Real> E12 = v1 - v2;
Real e02e02 = Dot(E02, E02);
Real e02e12 = Dot(E02, E12);
Real e12e12 = Dot(E12, E12);
Real det = e02e02 * e12e12 - e02e12 * e02e12;
if (det != (Real)0)
{
Real halfInvDet = (Real)0.5 / det;
Real u0 = halfInvDet * e12e12 * (e02e02 - e02e12);
Real u1 = halfInvDet * e02e02 * (e12e12 - e02e12);
Vector3<Real> tmp = u0 * E02 + u1 * E12;
circle.center = v2 + tmp;
circle.normal = UnitCross(E02, E12);
circle.radius = Length(tmp);
return true;
}
return false;
}
// Sphere circumscribing a tetrahedron.
template <typename Real>
bool Circumscribe(Vector3<Real> const& v0, Vector3<Real> const& v1,
Vector3<Real> const& v2, Vector3<Real> const& v3, Sphere3<Real>& sphere)
{
Vector3<Real> E10 = v1 - v0;
Vector3<Real> E20 = v2 - v0;
Vector3<Real> E30 = v3 - v0;
Matrix3x3<Real> A;
A.SetRow(0, E10);
A.SetRow(1, E20);
A.SetRow(2, E30);
Vector3<Real> B{
(Real)0.5 * Dot(E10, E10),
(Real)0.5 * Dot(E20, E20),
(Real)0.5 * Dot(E30, E30) };
Vector3<Real> solution;
if (LinearSystem<Real>::Solve(A, B, solution))
{
sphere.center = v0 + solution;
sphere.radius = Length(solution);
return true;
}
return false;
}
// Circle inscribing a triangle in 3D.
template <typename Real>
bool Inscribe(Vector3<Real> const& v0, Vector3<Real> const& v1,
Vector3<Real> const& v2, Circle3<Real>& circle)
{
// Edges.
Vector3<Real> E0 = v1 - v0;
Vector3<Real> E1 = v2 - v1;
Vector3<Real> E2 = v0 - v2;
// Plane normal.
circle.normal = Cross(E1, E0);
// Edge normals within the plane.
Vector3<Real> N0 = UnitCross(circle.normal, E0);
Vector3<Real> N1 = UnitCross(circle.normal, E1);
Vector3<Real> N2 = UnitCross(circle.normal, E2);
Real a0 = Dot(N1, E0);
if (a0 == (Real)0)
{
return false;
}
Real a1 = Dot(N2, E1);
if (a1 == (Real)0)
{
return false;
}
Real a2 = Dot(N0, E2);
if (a2 == (Real)0)
{
return false;
}
Real invA0 = (Real)1 / a0;
Real invA1 = (Real)1 / a1;
Real invA2 = (Real)1 / a2;
circle.radius = (Real)1 / (invA0 + invA1 + invA2);
circle.center = circle.radius * (invA0 * v0 + invA1 * v1 + invA2 * v2);
Normalize(circle.normal);
return true;
}
// Sphere inscribing tetrahedron.
template <typename Real>
bool Inscribe(Vector3<Real> const& v0, Vector3<Real> const& v1,
Vector3<Real> const& v2, Vector3<Real> const& v3, Sphere3<Real>& sphere)
{
// Edges.
Vector3<Real> E10 = v1 - v0;
Vector3<Real> E20 = v2 - v0;
Vector3<Real> E30 = v3 - v0;
Vector3<Real> E21 = v2 - v1;
Vector3<Real> E31 = v3 - v1;
// Normals.
Vector3<Real> N0 = Cross(E31, E21);
Vector3<Real> N1 = Cross(E20, E30);
Vector3<Real> N2 = Cross(E30, E10);
Vector3<Real> N3 = Cross(E10, E20);
// Normalize the normals.
if (Normalize(N0) == (Real)0)
{
return false;
}
if (Normalize(N1) == (Real)0)
{
return false;
}
if (Normalize(N2) == (Real)0)
{
return false;
}
if (Normalize(N3) == (Real)0)
{
return false;
}
Matrix3x3<Real> A;
A.SetRow(0, N1 - N0);
A.SetRow(1, N2 - N0);
A.SetRow(2, N3 - N0);
Vector3<Real> B{ (Real)0, (Real)0, -Dot(N3, E30) };
Vector3<Real> solution;
if (LinearSystem<Real>::Solve(A, B, solution))
{
sphere.center = v3 + solution;
sphere.radius = std::fabs(Dot(N0, solution));
return true;
}
return false;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistPointHyperellipsoid.h | .h | 13,034 | 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
#include <Mathematics/DCPQuery.h>
#include <Mathematics/Hyperellipsoid.h>
#include <Mathematics/Vector.h>
// Compute the distance from a point to a hyperellipsoid in nD. The
// hyperellipsoid is considered to be a closed surface, not a solid. In 2D,
// this is a point-ellipse distance query. In 3D, this is a point-ellipsoid
// distance query. The following document describes the algorithm.
// https://www.geometrictools.com/Documentation/DistancePointEllipseEllipsoid.pdf
// The hyperellipsoid can have arbitrary center and orientation; that is, it
// does not have to be axis-aligned with center at the origin.
//
// For the 2D query,
// Vector2<T> point; // initialized to something
// Ellipse2<T> ellipse; // initialized to something
// DCPQuery<T, Vector2<T>, Ellipse2<T>> query{};
// auto output = query(point, ellipse);
// T distance = output.distance;
// Vector2<T> closestEllipsePoint = output.closest[1];
//
// For the 3D query,
// Vector3<T> point; // initialized to something
// Ellipsoid3<T> ellipsoid; // initialized to something
// DCPQuery<T, Vector3<T>, Ellipsoid3<T>> query{};
// auto output = query(point, ellipsoid);
// T distance = output.distance;
// Vector3<T> closestEllipsoidPoint = output.closest[1];
//
// The input point is stored in closest[0]. The closest point on the
// hyperellipsoid is stored in closest[1].
namespace gte
{
template <int32_t N, typename T>
class DCPQuery<T, Vector<N, T>, Hyperellipsoid<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;
};
// The query for any hyperellipsoid.
Result operator()(Vector<N, T> const& point,
Hyperellipsoid<N, T> const& hyperellipsoid)
{
Result result{};
// Compute the coordinates of Y in the hyperellipsoid coordinate
// system.
Vector<N, T> diff = point - hyperellipsoid.center;
Vector<N, T> y{};
for (int32_t i = 0; i < N; ++i)
{
y[i] = Dot(diff, hyperellipsoid.axis[i]);
}
// Compute the closest hyperellipsoid point in the axis-aligned
// coordinate system.
Vector<N, T> x{};
result.sqrDistance = SqrDistance(hyperellipsoid.extent, y, x);
result.distance = std::sqrt(result.sqrDistance);
// Convert back to the original coordinate system.
result.closest[0] = point;
result.closest[1] = hyperellipsoid.center;
for (int32_t i = 0; i < N; ++i)
{
result.closest[1] += x[i] * hyperellipsoid.axis[i];
}
return result;
}
// The 'hyperellipsoid' is assumed to be axis-aligned and centered at
// the origin , so only the extent[] values are used.
Result operator()(Vector<N, T> const& point, Vector<N, T> const& extent)
{
Result result{};
result.closest[0] = point;
result.sqrDistance = SqrDistance(extent, point, result.closest[1]);
result.distance = std::sqrt(result.sqrDistance);
return result;
}
private:
// The hyperellipsoid is sum_{d=0}^{N-1} (x[d]/e[d])^2 = 1 with no
// constraints on the orderind of the e[d]. The query point is
// (y[0],...,y[N-1]) with no constraints on the signs of the
// components. The function returns the squared distance from the
// query point to the hyperellipsoid. It also computes the
// hyperellipsoid point (x[0],...,x[N-1]) that is closest to
// (y[0],...,y[N-1]).
T SqrDistance(Vector<N, T> const& e, Vector<N, T> const& y, Vector<N, T>& x)
{
// Determine negations for y to the first octant.
T const zero = static_cast<T>(0);
std::array<bool, N> negate{};
for (int32_t i = 0; i < N; ++i)
{
negate[i] = (y[i] < zero);
}
// Determine the axis order for decreasing extents.
std::array<std::pair<T, int32_t>, N> permute{};
for (int32_t i = 0; i < N; ++i)
{
permute[i].first = -e[i];
permute[i].second = i;
}
std::sort(permute.begin(), permute.end());
std::array<int32_t, N> invPermute{};
for (int32_t i = 0; i < N; ++i)
{
invPermute[permute[i].second] = i;
}
Vector<N, T> locE{}, locY{};
for (int32_t i = 0; i < N; ++i)
{
int32_t j = permute[i].second;
locE[i] = e[j];
locY[i] = std::fabs(y[j]);
}
Vector<N, T> locX{};
T sqrDistance = SqrDistanceSpecial(locE, locY, locX);
// Restore the axis order and reflections.
for (int32_t i = 0; i < N; ++i)
{
int32_t j = invPermute[i];
if (negate[i])
{
locX[j] = -locX[j];
}
x[i] = locX[j];
}
return sqrDistance;
}
// The hyperellipsoid is sum_{d=0}^{N-1} (x[d]/e[d])^2 = 1 with the
// e[d] positive and nonincreasing: e[d] >= e[d + 1] for all d. The
// query point is (y[0],...,y[N-1]) with y[d] >= 0 for all d. The
// function returns the squared distance from the query point to the
// hyperellipsoid. It also computes the hyperellipsoid point
// (x[0],...,x[N-1]) that is closest to (y[0],...,y[N-1]), where
// x[d] >= 0 for all d.
T SqrDistanceSpecial(Vector<N, T> const& e, Vector<N, T> const& y, Vector<N, T>& x)
{
T const zero = static_cast<T>(0);
T sqrDistance = zero;
Vector<N, T> ePos{}, yPos{}, xPos{};
int32_t numPos = 0;
for (int32_t i = 0; i < N; ++i)
{
if (y[i] > zero)
{
ePos[numPos] = e[i];
yPos[numPos] = y[i];
++numPos;
}
else
{
x[i] = zero;
}
}
if (y[N - 1] > zero)
{
sqrDistance = Bisector(numPos, ePos, yPos, xPos);
}
else // y[N-1] = 0
{
Vector<N - 1, T> numer{}, denom{};
T eNm1Sqr = e[N - 1] * e[N - 1];
for (int32_t i = 0; i < numPos; ++i)
{
numer[i] = ePos[i] * yPos[i];
denom[i] = ePos[i] * ePos[i] - eNm1Sqr;
}
bool inSubHyperbox = true;
for (int32_t i = 0; i < numPos; ++i)
{
if (numer[i] >= denom[i])
{
inSubHyperbox = false;
break;
}
}
bool inSubHyperellipsoid = false;
if (inSubHyperbox)
{
// yPos[] is inside the axis-aligned bounding box of the
// subhyperellipsoid. This intermediate test is designed
// to guard against the division by zero when
// ePos[i] == e[N-1] for some i.
Vector<N - 1, T> xde{};
T discr = static_cast<T>(1);
for (int32_t i = 0; i < numPos; ++i)
{
xde[i] = numer[i] / denom[i];
discr -= xde[i] * xde[i];
}
if (discr > zero)
{
// yPos[] is inside the subhyperellipsoid. The
// closest hyperellipsoid point has x[N-1] > 0.
sqrDistance = zero;
for (int32_t i = 0; i < numPos; ++i)
{
xPos[i] = ePos[i] * xde[i];
T diff = xPos[i] - yPos[i];
sqrDistance += diff * diff;
}
x[N - 1] = e[N - 1] * std::sqrt(discr);
sqrDistance += x[N - 1] * x[N - 1];
inSubHyperellipsoid = true;
}
}
if (!inSubHyperellipsoid)
{
// yPos[] is outside the subhyperellipsoid. The closest
// hyperellipsoid point has x[N-1] == 0 and is on the
// domain-boundary hyperellipsoid.
x[N - 1] = zero;
sqrDistance = Bisector(numPos, ePos, yPos, xPos);
}
}
// Fill in those x[] values that were not zeroed out initially.
numPos = 0;
for (int32_t i = 0; i < N; ++i)
{
if (y[i] > zero)
{
x[i] = xPos[numPos];
++numPos;
}
}
return sqrDistance;
}
// The bisection algorithm to find the unique root of F(t).
T Bisector(int32_t numComponents, Vector<N, T> const& e,
Vector<N, T> const& y, Vector<N, T>& x)
{
T const zero = static_cast<T>(0);
T const one = static_cast<T>(1);
T const half = static_cast<T>(0.5);
T sumZSqr = zero;
Vector<N, T> z{};
for (int32_t i = 0; i < numComponents; ++i)
{
z[i] = y[i] / e[i];
sumZSqr += z[i] * z[i];
}
if (sumZSqr == one)
{
// The point is on the hyperellipsoid.
for (int32_t i = 0; i < numComponents; ++i)
{
x[i] = y[i];
}
return zero;
}
T emin = e[numComponents - 1];
Vector<N, T> pSqr{}, numerator{};
pSqr.MakeZero();
numerator.MakeZero();
for (int32_t i = 0; i < numComponents; ++i)
{
T p = e[i] / emin;
pSqr[i] = p * p;
numerator[i] = pSqr[i] * z[i];
}
T s = zero, smin = z[numComponents - 1] - one, smax{};
if (sumZSqr < one)
{
// The point is strictly inside the hyperellipsoid.
smax = zero;
}
else
{
// The point is strictly outside the hyperellipsoid.
smax = Length(numerator, true) - one;
}
// The use of 'double' is intentional in case T is a BSNumber
// or BSRational type. We want the bisections to terminate in a
// reasonable amount of time.
uint32_t const jmax = GTE_C_MAX_BISECTIONS_GENERIC;
for (uint32_t j = 0; j < jmax; ++j)
{
s = half * (smin + smax);
if (s == smin || s == smax)
{
break;
}
T g = -one;
for (int32_t i = 0; i < numComponents; ++i)
{
T ratio = numerator[i] / (s + pSqr[i]);
g += ratio * ratio;
}
if (g > zero)
{
smin = s;
}
else if (g < zero)
{
smax = s;
}
else
{
break;
}
}
T sqrDistance = zero;
for (int32_t i = 0; i < numComponents; ++i)
{
x[i] = pSqr[i] * y[i] / (s + pSqr[i]);
T diff = x[i] - y[i];
sqrDistance += diff * diff;
}
return sqrDistance;
}
};
// Template aliases for convenience.
template <int32_t N, typename T>
using DCPPointHyperellipsoid = DCPQuery<T, Vector<N, T>, Hyperellipsoid<N, T>>;
template <typename T>
using DCPPoint2Ellipse2 = DCPPointHyperellipsoid<2, T>;
template <typename T>
using DCPPoint3Ellipsoid3 = DCPPointHyperellipsoid<3, T>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrHalfspace3Sphere3.h | .h | 1,397 | 49 | // 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/Hypersphere.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>, Sphere3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Halfspace3<T> const& halfspace, Sphere3<T> const& sphere)
{
Result result{};
// Project the sphere center onto the normal line. The plane of
// the halfspace occurs at the origin (zero) of the normal line.
T center = Dot(halfspace.normal, sphere.center) - halfspace.constant;
// The sphere and halfspace intersect when the projection interval
// maximum is nonnegative.
result.intersect = (center + sphere.radius >= (T)0);
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Vector.h | .h | 16,511 | 579 | // 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 <algorithm>
#include <array>
#include <initializer_list>
namespace gte
{
template <int32_t N, typename Real>
class Vector
{
public:
// The tuple is uninitialized.
Vector() = default;
// The tuple is fully initialized by the inputs.
Vector(std::array<Real, N> const& values)
:
mTuple(values)
{
}
// At most N elements are copied from the initializer list, setting
// any remaining elements to zero. Create the zero vector using the
// syntax
// Vector<N,Real> zero{(Real)0};
// WARNING: The C++ 11 specification states that
// Vector<N,Real> zero{};
// will lead to a call of the default constructor, not the initializer
// constructor!
Vector(std::initializer_list<Real> values)
{
int32_t const numValues = static_cast<int32_t>(values.size());
if (N == numValues)
{
std::copy(values.begin(), values.end(), mTuple.begin());
}
else if (N > numValues)
{
std::copy(values.begin(), values.end(), mTuple.begin());
std::fill(mTuple.begin() + numValues, mTuple.end(), (Real)0);
}
else // N < numValues
{
std::copy(values.begin(), values.begin() + N, mTuple.begin());
}
}
// For 0 <= d < N, element d is 1 and all others are 0. 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) and Unit(int32_t).
Vector(int32_t d)
{
MakeUnit(d);
}
// The copy constructor, destructor, and assignment operator are
// generated by the compiler.
// Member access. 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.
inline int32_t GetSize() const
{
return N;
}
inline Real const& operator[](int32_t i) const
{
return mTuple[i];
}
inline Real& operator[](int32_t i)
{
return mTuple[i];
}
// Comparisons for sorted containers and geometric ordering.
inline bool operator==(Vector const& vec) const
{
return mTuple == vec.mTuple;
}
inline bool operator!=(Vector const& vec) const
{
return mTuple != vec.mTuple;
}
inline bool operator< (Vector const& vec) const
{
return mTuple < vec.mTuple;
}
inline bool operator<=(Vector const& vec) const
{
return mTuple <= vec.mTuple;
}
inline bool operator> (Vector const& vec) const
{
return mTuple > vec.mTuple;
}
inline bool operator>=(Vector const& vec) const
{
return mTuple >= vec.mTuple;
}
// Special vectors.
// All components are 0.
void MakeZero()
{
std::fill(mTuple.begin(), mTuple.end(), (Real)0);
}
// All components are 1.
void MakeOnes()
{
std::fill(mTuple.begin(), mTuple.end(), (Real)1);
}
// 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 < N)
{
mTuple[d] = (Real)1;
}
}
static Vector Zero()
{
Vector<N, Real> v;
v.MakeZero();
return v;
}
static Vector Ones()
{
Vector<N, Real> v;
v.MakeOnes();
return v;
}
static Vector Unit(int32_t d)
{
Vector<N, Real> v;
v.MakeUnit(d);
return v;
}
protected:
// This data structure takes advantage of the built-in operator[],
// range checking, and visualizers in MSVS.
std::array<Real, N> mTuple;
};
// Unary operations.
template <int32_t N, typename Real>
Vector<N, Real> operator+(Vector<N, Real> const& v)
{
return v;
}
template <int32_t N, typename Real>
Vector<N, Real> operator-(Vector<N, Real> const& v)
{
Vector<N, Real> result;
for (int32_t i = 0; i < N; ++i)
{
result[i] = -v[i];
}
return result;
}
// Linear-algebraic operations.
template <int32_t N, typename Real>
Vector<N, Real> operator+(Vector<N, Real> const& v0, Vector<N, Real> const& v1)
{
Vector<N, Real> result = v0;
return result += v1;
}
template <int32_t N, typename Real>
Vector<N, Real> operator-(Vector<N, Real> const& v0, Vector<N, Real> const& v1)
{
Vector<N, Real> result = v0;
return result -= v1;
}
template <int32_t N, typename Real>
Vector<N, Real> operator*(Vector<N, Real> const& v, Real scalar)
{
Vector<N, Real> result = v;
return result *= scalar;
}
template <int32_t N, typename Real>
Vector<N, Real> operator*(Real scalar, Vector<N, Real> const& v)
{
Vector<N, Real> result = v;
return result *= scalar;
}
template <int32_t N, typename Real>
Vector<N, Real> operator/(Vector<N, Real> const& v, Real scalar)
{
Vector<N, Real> result = v;
return result /= scalar;
}
template <int32_t N, typename Real>
Vector<N, Real>& operator+=(Vector<N, Real>& v0, Vector<N, Real> const& v1)
{
for (int32_t i = 0; i < N; ++i)
{
v0[i] += v1[i];
}
return v0;
}
template <int32_t N, typename Real>
Vector<N, Real>& operator-=(Vector<N, Real>& v0, Vector<N, Real> const& v1)
{
for (int32_t i = 0; i < N; ++i)
{
v0[i] -= v1[i];
}
return v0;
}
template <int32_t N, typename Real>
Vector<N, Real>& operator*=(Vector<N, Real>& v, Real scalar)
{
for (int32_t i = 0; i < N; ++i)
{
v[i] *= scalar;
}
return v;
}
template <int32_t N, typename Real>
Vector<N, Real>& operator/=(Vector<N, Real>& v, Real scalar)
{
if (scalar != (Real)0)
{
Real invScalar = (Real)1 / scalar;
for (int32_t i = 0; i < N; ++i)
{
v[i] *= invScalar;
}
}
else
{
for (int32_t i = 0; i < N; ++i)
{
v[i] = (Real)0;
}
}
return v;
}
// Componentwise algebraic operations.
template <int32_t N, typename Real>
Vector<N, Real> operator*(Vector<N, Real> const& v0, Vector<N, Real> const& v1)
{
Vector<N, Real> result = v0;
return result *= v1;
}
template <int32_t N, typename Real>
Vector<N, Real> operator/(Vector<N, Real> const& v0, Vector<N, Real> const& v1)
{
Vector<N, Real> result = v0;
return result /= v1;
}
template <int32_t N, typename Real>
Vector<N, Real>& operator*=(Vector<N, Real>& v0, Vector<N, Real> const& v1)
{
for (int32_t i = 0; i < N; ++i)
{
v0[i] *= v1[i];
}
return v0;
}
template <int32_t N, typename Real>
Vector<N, Real>& operator/=(Vector<N, Real>& v0, Vector<N, Real> const& v1)
{
for (int32_t i = 0; i < N; ++i)
{
v0[i] /= v1[i];
}
return v0;
}
// 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 <int32_t N, typename Real>
Real Dot(Vector<N, Real> const& v0, Vector<N, Real> const& v1)
{
Real dot = v0[0] * v1[0];
for (int32_t i = 1; i < N; ++i)
{
dot += v0[i] * v1[i];
}
return dot;
}
template <int32_t N, typename Real>
Real Length(Vector<N, Real> const& v, bool robust = false)
{
if (robust)
{
Real maxAbsComp = std::fabs(v[0]);
for (int32_t i = 1; i < N; ++i)
{
Real absComp = std::fabs(v[i]);
if (absComp > maxAbsComp)
{
maxAbsComp = absComp;
}
}
Real length;
if (maxAbsComp > (Real)0)
{
Vector<N, 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 <int32_t N, typename Real>
Real Normalize(Vector<N, Real>& v, bool robust = false)
{
if (robust)
{
Real maxAbsComp = std::fabs(v[0]);
for (int32_t i = 1; i < N; ++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 < N; ++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 < N; ++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 <int32_t N, typename Real>
Real Orthonormalize(int32_t numInputs, Vector<N, Real>* v, bool robust = false)
{
if (v && 1 <= numInputs && numInputs <= N)
{
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;
}
return (Real)0;
}
// Construct a single vector orthogonal to the nonzero input vector. If
// the maximum absolute component occurs at index i, then the orthogonal
// vector U has u[i] = v[i+1], u[i+1] = -v[i], and all other components
// zero. The index addition i+1 is computed modulo N.
template <int32_t N, typename Real>
Vector<N, Real> GetOrthogonal(Vector<N, Real> const& v, bool unitLength)
{
Real cmax = std::fabs(v[0]);
int32_t imax = 0;
for (int32_t i = 1; i < N; ++i)
{
Real c = std::fabs(v[i]);
if (c > cmax)
{
cmax = c;
imax = i;
}
}
Vector<N, Real> result;
result.MakeZero();
int32_t inext = imax + 1;
if (inext == N)
{
inext = 0;
}
result[imax] = v[inext];
result[inext] = -v[imax];
if (unitLength)
{
Real sqrDistance = result[imax] * result[imax] + result[inext] * result[inext];
Real invLength = ((Real)1) / std::sqrt(sqrDistance);
result[imax] *= invLength;
result[inext] *= invLength;
}
return result;
}
// 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 <int32_t N, typename Real>
bool ComputeExtremes(int32_t numVectors, Vector<N, Real> const* v,
Vector<N, Real>& vmin, Vector<N, Real>& vmax)
{
if (v && numVectors > 0)
{
vmin = v[0];
vmax = vmin;
for (int32_t j = 1; j < numVectors; ++j)
{
Vector<N, Real> const& vec = v[j];
for (int32_t i = 0; i < N; ++i)
{
if (vec[i] < vmin[i])
{
vmin[i] = vec[i];
}
else if (vec[i] > vmax[i])
{
vmax[i] = vec[i];
}
}
}
return true;
}
return false;
}
// Lift n-tuple v to homogeneous (n+1)-tuple (v,last).
template <int32_t N, typename Real>
Vector<N + 1, Real> HLift(Vector<N, Real> const& v, Real last)
{
Vector<N + 1, Real> result;
for (int32_t i = 0; i < N; ++i)
{
result[i] = v[i];
}
result[N] = last;
return result;
}
// Project homogeneous n-tuple v = (u,v[n-1]) to (n-1)-tuple u.
template <int32_t N, typename Real>
Vector<N - 1, Real> HProject(Vector<N, Real> const& v)
{
static_assert(N >= 2, "Invalid dimension.");
Vector<N - 1, Real> result;
for (int32_t i = 0; i < N - 1; ++i)
{
result[i] = v[i];
}
return result;
}
// 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 <int32_t N, typename Real>
Vector<N + 1, Real> Lift(Vector<N, Real> const& v, int32_t inject, Real value)
{
Vector<N + 1, Real> result;
int32_t i;
for (i = 0; i < inject; ++i)
{
result[i] = v[i];
}
result[i] = value;
int32_t j = i;
for (++j; i < N; ++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 <int32_t N, typename Real>
Vector<N - 1, Real> Project(Vector<N, Real> const& v, int32_t reject)
{
static_assert(N >= 2, "Invalid dimension.");
Vector<N - 1, Real> result;
for (int32_t i = 0, j = 0; i < N - 1; ++i, ++j)
{
if (j == reject)
{
++j;
}
result[i] = v[j];
}
return result;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/NURBSCurve.h | .h | 7,199 | 217 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/BasisFunction.h>
#include <Mathematics/ParametricCurve.h>
namespace gte
{
template <int32_t N, typename Real>
class NURBSCurve : public ParametricCurve<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 domain is t in [t[d],t[n]], where t[d] and t[n] are
// knots with d the degree and n the number of control points.
NURBSCurve(BasisFunctionInput<Real> const& input,
Vector<N, Real> const* controls, Real const* weights)
:
ParametricCurve<N, Real>((Real)0, (Real)1),
mBasisFunction(input)
{
// The mBasisFunction stores the domain but so does
// ParametricCurve.
this->mTime.front() = mBasisFunction.GetMinDomain();
this->mTime.back() = mBasisFunction.GetMaxDomain();
// The replication of control points for periodic splines is
// avoided by wrapping the i-loop index in Evaluate.
mControls.resize(input.numControls);
mWeights.resize(input.numControls);
if (controls)
{
std::copy(controls, controls + input.numControls, mControls.begin());
}
else
{
Vector<N, Real> zero{ (Real)0 };
std::fill(mControls.begin(), mControls.end(), zero);
}
if (weights)
{
std::copy(weights, weights + input.numControls, mWeights.begin());
}
else
{
std::fill(mWeights.begin(), mWeights.end(), (Real)0);
}
this->mConstructed = true;
}
// Member access.
inline BasisFunction<Real> const& GetBasisFunction() const
{
return mBasisFunction;
}
inline int32_t GetNumControls() const
{
return static_cast<int32_t>(mControls.size());
}
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 i, Vector<N, Real> const& control)
{
if (0 <= i && i < GetNumControls())
{
mControls[i] = control;
}
}
Vector<N, Real> const& GetControl(int32_t i) const
{
if (0 <= i && i < GetNumControls())
{
return mControls[i];
}
else
{
// Invalid index, return something.
return mControls[0];
}
}
void SetWeight(int32_t i, Real weight)
{
if (0 <= i && i < GetNumControls())
{
mWeights[i] = weight;
}
}
Real const& GetWeight(int32_t i) const
{
if (0 <= i && i < GetNumControls())
{
return mWeights[i];
}
else
{
// Invalid index, return something.
return mWeights[0];
}
}
// Evaluation of the curve. The function supports derivative
// calculation through order 3; that is, order <= 3 is required. 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 maximum
// order. The values are ordered as: position, first derivative,
// second derivative, third derivative.
virtual void Evaluate(Real t, uint32_t order, Vector<N, Real>* jet) const override
{
uint32_t const supOrder = ParametricCurve<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 imin, imax;
mBasisFunction.Evaluate(t, order, imin, imax);
// Compute position.
Vector<N, Real> X;
Real w;
Compute(0, imin, imax, X, w);
Real invW = (Real)1 / w;
jet[0] = invW * X;
if (order >= 1)
{
// Compute first derivative.
Vector<N, Real> XDer1;
Real wDer1;
Compute(1, imin, imax, XDer1, wDer1);
jet[1] = invW * (XDer1 - wDer1 * jet[0]);
if (order >= 2)
{
// Compute second derivative.
Vector<N, Real> XDer2;
Real wDer2;
Compute(2, imin, imax, XDer2, wDer2);
jet[2] = invW * (XDer2 - (Real)2 * wDer1 * jet[1] - wDer2 * jet[0]);
if (order == 3)
{
// Compute third derivative.
Vector<N, Real> XDer3;
Real wDer3;
Compute(3, imin, imax, XDer3, wDer3);
jet[3] = invW * (XDer3 - (Real)3 * wDer1 * jet[2] -
(Real)3 * wDer2 * jet[1] - wDer3 * jet[0]);
}
}
}
}
protected:
// Support for Evaluate(...).
void Compute(uint32_t order, int32_t imin, int32_t imax, Vector<N, Real>& X, Real& w) const
{
// The j-index introduces a tiny amount of overhead in order to
// handle both aperiodic and periodic splines. For aperiodic
// splines, j = i always.
int32_t numControls = GetNumControls();
X.MakeZero();
w = (Real)0;
for (int32_t i = imin; i <= imax; ++i)
{
int32_t j = (i >= numControls ? i - numControls : i);
Real tmp = mBasisFunction.GetValue(order, i) * mWeights[j];
X += tmp * mControls[j];
w += tmp;
}
}
BasisFunction<Real> mBasisFunction;
std::vector<Vector<N, Real>> mControls;
std::vector<Real> mWeights;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Polyhedron3.h | .h | 6,407 | 173 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/Vector3.h>
#include <memory>
#include <set>
#include <vector>
// The Polyhedron3 object represents a simple polyhedron. The 'vertexPool'
// array can contain more points than needed to define the polyhedron, which
// allows the vertex pool to have multiple polyhedra associated with it.
// Thus, the programmer must ensure that the vertex pool persists as long as
// any Polyhedron3 objects exist that depend on the pool. The number of
// polyhedron indices is 'numIndices' and must be 6 or larger The 'indices'
// array refers to the points in 'vertexPool' that form the triangle faces,
// so 'numIndices' must be a multiple of 3. The number of vertices is
// the number of unique elements in 'indices' and is determined during
// construction. The programmer should ensure the polyhedron is simple. The
// geometric queries are valid regardless of whether the polyhedron triangles
// are oriented clockwise or counterclockwise.
//
// NOTE: Comparison operators are not provided. The semantics of equal
// polyhedra 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 permuted,
// leading to the same polyhedron abstractly but the data structures do not
// match.
namespace gte
{
template <typename Real>
class Polyhedron3
{
public:
// Construction. The constructor succeeds when 'numIndices >= 12' (at
// least 4 triangles), 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 number of vertices is set to zero, the index
// array has no elements, and the triangle face orientation is set to
// clockwise.
Polyhedron3(std::shared_ptr<std::vector<Vector3<Real>>> const& vertexPool,
int32_t numIndices, int32_t const* indices, bool counterClockwise)
:
mVertexPool(vertexPool),
mCounterClockwise(counterClockwise)
{
if (vertexPool && indices && numIndices >= 12 && (numIndices % 3) == 0)
{
for (int32_t i = 0; i < numIndices; ++i)
{
mUniqueIndices.insert(indices[i]);
}
mIndices.resize(numIndices);
std::copy(indices, indices + numIndices, mIndices.begin());
}
else
{
// Encountered an invalid input.
mVertexPool = nullptr;
mCounterClockwise = false;
}
}
// To validate construction, create an object as shown:
// Polyhedron3<Real> polyhedron(parameters);
// if (!polyhedron) { <constructor failed, handle accordingly>; }
inline operator bool() const
{
return mVertexPool != nullptr;
}
// Member access.
inline std::shared_ptr<std::vector<Vector3<Real>>> const& GetVertexPool() const
{
return mVertexPool;
}
inline std::vector<Vector3<Real>> const& GetVertices() const
{
return *mVertexPool.get();
}
inline std::set<int32_t> const& GetUniqueIndices() const
{
return mUniqueIndices;
}
inline std::vector<int32_t> const& GetIndices() const
{
return mIndices;
}
inline bool CounterClockwise() const
{
return mCounterClockwise;
}
// Geometric queries.
Vector3<Real> ComputeVertexAverage() const
{
Vector3<Real> average = Vector3<Real>::Zero();
if (mVertexPool)
{
auto vertexPool = GetVertices();
for (int32_t index : mUniqueIndices)
{
average += vertexPool[index];
}
average /= static_cast<Real>(mUniqueIndices.size());
}
return average;
}
Real ComputeSurfaceArea() const
{
Real surfaceArea(0);
if (mVertexPool)
{
auto vertexPool = GetVertices();
int32_t const numTriangles = static_cast<int32_t>(mIndices.size()) / 3;
int32_t const* indices = mIndices.data();
for (int32_t t = 0; t < numTriangles; ++t)
{
int32_t v0 = *indices++;
int32_t v1 = *indices++;
int32_t v2 = *indices++;
Vector3<Real> edge0 = vertexPool[v1] - vertexPool[v0];
Vector3<Real> edge1 = vertexPool[v2] - vertexPool[v0];
Vector3<Real> cross = Cross(edge0, edge1);
surfaceArea += Length(cross);
}
surfaceArea *= (Real)0.5;
}
return surfaceArea;
}
Real ComputeVolume() const
{
Real volume(0);
if (mVertexPool)
{
auto vertexPool = GetVertices();
int32_t const numTriangles = static_cast<int32_t>(mIndices.size()) / 3;
int32_t const* indices = mIndices.data();
for (int32_t t = 0; t < numTriangles; ++t)
{
int32_t v0 = *indices++;
int32_t v1 = *indices++;
int32_t v2 = *indices++;
volume += DotCross(vertexPool[v0], vertexPool[v1], vertexPool[v2]);
}
volume /= (Real)6;
}
return std::fabs(volume);
}
private:
std::shared_ptr<std::vector<Vector3<Real>>> mVertexPool;
std::set<int32_t> mUniqueIndices;
std::vector<int32_t> mIndices;
bool mCounterClockwise;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/PolyhedralMassProperties.h | .h | 5,510 | 143 | // 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>
namespace gte
{
// The input triangle mesh must represent a polyhedron. The triangles are
// represented as triples of indices <V0,V1,V2> into the vertex array.
// The index array has numTriangles such triples. The Boolean value
// 'bodyCoords is' 'true' if you want the inertia tensor to be relative to
// body coordinates but 'false' if you want it to be relative to world
// coordinates.
//
// The code assumes the rigid body has a constant density of 1. If your
// application assigns a constant density of 'd', then you must multiply
// the output 'mass' by 'd' and the output 'inertia' by 'd'.
template <typename Real>
void ComputeMassProperties(Vector3<Real> const* vertices, int32_t numTriangles,
int32_t const* indices, bool bodyCoords, Real& mass, Vector3<Real>& center,
Matrix3x3<Real>& inertia)
{
Real const oneDiv6 = (Real)1 / (Real)6;
Real const oneDiv24 = (Real)1 / (Real)24;
Real const oneDiv60 = (Real)1 / (Real)60;
Real const oneDiv120 = (Real)1 / (Real)120;
// order: 1, x, y, z, x^2, y^2, z^2, xy, yz, zx
std::array<Real, 10> integral;
integral.fill((Real)0);
int32_t const* index = indices;
for (int32_t i = 0; i < numTriangles; ++i)
{
// Get vertices of triangle i.
Vector3<Real> v0 = vertices[*index++];
Vector3<Real> v1 = vertices[*index++];
Vector3<Real> v2 = vertices[*index++];
// Get cross product of edges and normal vector.
Vector3<Real> V1mV0 = v1 - v0;
Vector3<Real> V2mV0 = v2 - v0;
Vector3<Real> N = Cross(V1mV0, V2mV0);
// Compute integral terms.
Real tmp0, tmp1, tmp2;
Real f1x, f2x, f3x, g0x, g1x, g2x;
tmp0 = v0[0] + v1[0];
f1x = tmp0 + v2[0];
tmp1 = v0[0] * v0[0];
tmp2 = tmp1 + v1[0] * tmp0;
f2x = tmp2 + v2[0] * f1x;
f3x = v0[0] * tmp1 + v1[0] * tmp2 + v2[0] * f2x;
g0x = f2x + v0[0] * (f1x + v0[0]);
g1x = f2x + v1[0] * (f1x + v1[0]);
g2x = f2x + v2[0] * (f1x + v2[0]);
Real f1y, f2y, f3y, g0y, g1y, g2y;
tmp0 = v0[1] + v1[1];
f1y = tmp0 + v2[1];
tmp1 = v0[1] * v0[1];
tmp2 = tmp1 + v1[1] * tmp0;
f2y = tmp2 + v2[1] * f1y;
f3y = v0[1] * tmp1 + v1[1] * tmp2 + v2[1] * f2y;
g0y = f2y + v0[1] * (f1y + v0[1]);
g1y = f2y + v1[1] * (f1y + v1[1]);
g2y = f2y + v2[1] * (f1y + v2[1]);
Real f1z, f2z, f3z, g0z, g1z, g2z;
tmp0 = v0[2] + v1[2];
f1z = tmp0 + v2[2];
tmp1 = v0[2] * v0[2];
tmp2 = tmp1 + v1[2] * tmp0;
f2z = tmp2 + v2[2] * f1z;
f3z = v0[2] * tmp1 + v1[2] * tmp2 + v2[2] * f2z;
g0z = f2z + v0[2] * (f1z + v0[2]);
g1z = f2z + v1[2] * (f1z + v1[2]);
g2z = f2z + v2[2] * (f1z + v2[2]);
// Update integrals.
integral[0] += N[0] * f1x;
integral[1] += N[0] * f2x;
integral[2] += N[1] * f2y;
integral[3] += N[2] * f2z;
integral[4] += N[0] * f3x;
integral[5] += N[1] * f3y;
integral[6] += N[2] * f3z;
integral[7] += N[0] * (v0[1] * g0x + v1[1] * g1x + v2[1] * g2x);
integral[8] += N[1] * (v0[2] * g0y + v1[2] * g1y + v2[2] * g2y);
integral[9] += N[2] * (v0[0] * g0z + v1[0] * g1z + v2[0] * g2z);
}
integral[0] *= oneDiv6;
integral[1] *= oneDiv24;
integral[2] *= oneDiv24;
integral[3] *= oneDiv24;
integral[4] *= oneDiv60;
integral[5] *= oneDiv60;
integral[6] *= oneDiv60;
integral[7] *= oneDiv120;
integral[8] *= oneDiv120;
integral[9] *= oneDiv120;
// mass
mass = integral[0];
// center of mass
center = Vector3<Real>{ integral[1], integral[2], integral[3] } / mass;
// inertia relative to world origin
inertia(0, 0) = integral[5] + integral[6];
inertia(0, 1) = -integral[7];
inertia(0, 2) = -integral[9];
inertia(1, 0) = inertia(0, 1);
inertia(1, 1) = integral[4] + integral[6];
inertia(1, 2) = -integral[8];
inertia(2, 0) = inertia(0, 2);
inertia(2, 1) = inertia(1, 2);
inertia(2, 2) = integral[4] + integral[5];
// inertia relative to center of mass
if (bodyCoords)
{
inertia(0, 0) -= mass * (center[1] * center[1] + center[2] * center[2]);
inertia(0, 1) += mass * center[0] * center[1];
inertia(0, 2) += mass * center[2] * center[0];
inertia(1, 0) = inertia(0, 1);
inertia(1, 1) -= mass * (center[2] * center[2] + center[0] * center[0]);
inertia(1, 2) += mass * center[1] * center[2];
inertia(2, 0) = inertia(0, 2);
inertia(2, 1) = inertia(1, 2);
inertia(2, 2) -= mass * (center[0] * center[0] + center[1] * center[1]);
}
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrIntervals.h | .h | 22,621 | 559 | // 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 <array>
// The intervals are of the form [t0,t1], [t0,+infinity) or (-infinity,t1].
// Degenerate intervals are allowed (t0 = t1). The queries do not perform
// validation on the input intervals to test whether t0 <= t1.
namespace gte
{
template <typename Real>
class TIQuery<Real, std::array<Real, 2>, std::array<Real, 2>>
{
public:
// The query tests overlap, whether a single point or an entire
// interval.
struct Result
{
Result()
:
intersect(false),
firstTime(static_cast<Real>(0)),
lastTime(static_cast<Real>(0))
{
}
bool intersect;
// Dynamic queries (intervals moving with constant speeds). If
// 'intersect' is true, the contact times are valid and
// 0 <= firstTime <= lastTime, firstTime <= maxTime
// If 'intersect' is false, there are two cases reported. If the
// intervals will intersect at firstTime > maxTime, the contact
// times are reported just as when 'intersect' is true. However,
// if the intervals will not intersect, then firstTime and
// lastTime are both set to zero (invalid because 'intersect' is
// false).
Real firstTime, lastTime;
};
// Static query. The firstTime and lastTime values are set to zero by
// the Result constructor, but they are invalid for the static query
// regardless of the value of 'intersect'.
Result operator()(std::array<Real, 2> const& interval0, std::array<Real, 2> const& interval1)
{
Result result{};
result.intersect = (interval0[0] <= interval1[1] && interval0[1] >= interval1[0]);
return result;
}
// Static queries where at least one interval is semiinfinite. The
// two types of semiinfinite intervals are [a,+infinity), which I call
// a positive-infinite interval, and (-infinity,a], which I call a
// negative-infinite interval. The firstTime and lastTime values are
// set to zero by the Result constructor, but they are invalid for the
// static query regardless of the value of 'intersect'.
Result operator()(std::array<Real, 2> const& finite, Real const& a, bool isPositiveInfinite)
{
Result result{};
if (isPositiveInfinite)
{
result.intersect = (finite[1] >= a);
}
else // is negative-infinite
{
result.intersect = (finite[0] <= a);
}
return result;
}
Result operator()(Real const& a0, bool isPositiveInfinite0,
Real const& a1, bool isPositiveInfinite1)
{
Result result{};
if (isPositiveInfinite0)
{
if (isPositiveInfinite1)
{
result.intersect = true;
}
else // interval1 is negative-infinite
{
result.intersect = (a0 <= a1);
}
}
else // interval0 is negative-infinite
{
if (isPositiveInfinite1)
{
result.intersect = (a0 >= a1);
}
else // interval1 is negative-infinite
{
result.intersect = true;
}
}
return result;
}
// Dynamic query. Current time is 0, maxTime > 0 is required.
Result operator()(Real maxTime, std::array<Real, 2> const& interval0,
Real speed0, std::array<Real, 2> const& interval1, Real speed1)
{
Real const zero = static_cast<Real>(0);
Result result{};
if (interval0[1] < interval1[0])
{
// interval0 initially to the left of interval1.
Real diffSpeed = speed0 - speed1;
if (diffSpeed > zero)
{
// The intervals must move towards each other. 'intersect'
// is true when the intervals will intersect by maxTime.
Real diffPos = interval1[0] - interval0[1];
result.intersect = (diffPos <= maxTime * diffSpeed);
result.firstTime = diffPos / diffSpeed;
result.lastTime = (interval1[1] - interval0[0]) / diffSpeed;
return result;
}
}
else if (interval0[0] > interval1[1])
{
// interval0 initially to the right of interval1.
Real diffSpeed = speed1 - speed0;
if (diffSpeed > zero)
{
// The intervals must move towards each other. 'intersect'
// is true when the intervals will intersect by maxTime.
Real diffPos = interval0[0] - interval1[1];
result.intersect = (diffPos <= maxTime * diffSpeed);
result.firstTime = diffPos / diffSpeed;
result.lastTime = (interval0[1] - interval1[0]) / diffSpeed;
return result;
}
}
else
{
// The intervals are initially intersecting.
result.intersect = true;
result.firstTime = zero;
if (speed1 > speed0)
{
result.lastTime = (interval0[1] - interval1[0]) / (speed1 - speed0);
}
else if (speed1 < speed0)
{
result.lastTime = (interval1[1] - interval0[0]) / (speed0 - speed1);
}
else
{
result.lastTime = std::numeric_limits<Real>::max();
}
return result;
}
// The Result constructor set 'intersect' to false and the
// 'firstTime' and 'lastTime' to zero.
return result;
}
};
template <typename Real>
class FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>>
{
public:
// The query finds overlap, whether a single point or an entire
// interval.
struct Result
{
Result()
:
intersect(false),
numIntersections(0),
overlap{ static_cast<Real>(0), static_cast<Real>(0) },
type(isEmpty),
firstTime(static_cast<Real>(0)),
lastTime(static_cast<Real>(0))
{
}
bool intersect;
// Static queries (no motion of intervals over time). The number
// of number of intersections is 0 (no overlap), 1 (intervals are
// just touching), or 2 (intervals overlap in an interval). If
// 'intersect' is false, numIntersections is 0 and 'overlap' is
// set to [0,0]. If 'intersect' is true, numIntersections is
// 1 or 2. When 1, 'overlap' is set to [x,x], which is degenerate
// and represents the single intersection point x. When 2,
// 'overlap' is the interval of intersection.
int32_t numIntersections;
std::array<Real, 2> overlap;
// No intersection.
static int32_t const isEmpty = 0;
// Intervals touch at an endpoint, [t0,t0].
static int32_t const isPoint = 1;
// Finite-length interval of intersection, [t0,t1].
static int32_t const isFinite = 2;
// Smiinfinite interval of intersection, [t0,+infinity). The
// result.overlap[0] is t0 and result.overlap[1] is +1 as a
// message that the right endpoint is +infinity (you still need
// the result.type to know this interpretation).
static int32_t const isPositiveInfinite = 3;
// Semiinfinite interval of intersection, (-infinity,t1]. The
// result.overlap[0] is -1 as a message that the left endpoint is
// -infinity (you still need the result.type to know this
// interpretation). The result.overlap[1] is t1.
static int32_t const isNegativeInfinite = 4;
// The dynamic queries all set the type to isDynamicQuery because
// the queries look for time of first and last contact.
static int32_t const isDynamicQuery = 5;
// The type is one of isEmpty, isPoint, isFinite,
// isPositiveInfinite, isNegativeInfinite or isDynamicQuery.
int32_t type;
// Dynamic queries (intervals moving with constant speeds). If
// 'intersect' is true, the contact times are valid and
// 0 <= firstTime <= lastTime, firstTime <= maxTime
// If 'intersect' is false, there are two cases reported. If the
// intervals will intersect at firstTime > maxTime, the contact
// times are reported just as when 'intersect' is true. However,
// if the intervals will not intersect, then firstTime and
// lastTime are both set to zero (invalid because 'intersect' is
// false).
Real firstTime, lastTime;
};
// Static query.
Result operator()(std::array<Real, 2> const& interval0, std::array<Real, 2> const& interval1)
{
Result result{};
if (interval0[1] < interval1[0] || interval0[0] > interval1[1])
{
result.numIntersections = 0;
result.overlap[0] = static_cast<Real>(0);
result.overlap[1] = static_cast<Real>(0);
result.type = Result::isEmpty;
}
else if (interval0[1] > interval1[0])
{
if (interval0[0] < interval1[1])
{
result.overlap[0] = (interval0[0] < interval1[0] ? interval1[0] : interval0[0]);
result.overlap[1] = (interval0[1] > interval1[1] ? interval1[1] : interval0[1]);
if (result.overlap[0] < result.overlap[1])
{
result.numIntersections = 2;
result.type = Result::isFinite;
}
else
{
result.numIntersections = 1;
result.type = Result::isPoint;
}
}
else // interval0[0] == interval1[1]
{
result.numIntersections = 1;
result.overlap[0] = interval0[0];
result.overlap[1] = result.overlap[0];
result.type = Result::isPoint;
}
}
else // interval0[1] == interval1[0]
{
result.numIntersections = 1;
result.overlap[0] = interval0[1];
result.overlap[1] = result.overlap[0];
result.type = Result::isPoint;
}
result.intersect = (result.numIntersections > 0);
return result;
}
// Static queries where at least one interval is semiinfinite. The
// two types of semiinfinite intervals are [a,+infinity), which I call
// a positive-infinite interval, and (-infinity,a], which I call a
// negative-infinite interval.
Result operator()(std::array<Real, 2> const& finite, Real const& a, bool isPositiveInfinite)
{
Result result{};
if (isPositiveInfinite)
{
if (finite[1] > a)
{
result.overlap[0] = std::max(finite[0], a);
result.overlap[1] = finite[1];
if (result.overlap[0] < result.overlap[1])
{
result.numIntersections = 2;
result.type = Result::isFinite;
}
else
{
result.numIntersections = 1;
result.type = Result::isPoint;
}
}
else if (finite[1] == a)
{
result.numIntersections = 1;
result.overlap[0] = a;
result.overlap[1] = result.overlap[0];
result.type = Result::isPoint;
}
else
{
result.numIntersections = 0;
result.overlap[0] = static_cast<Real>(0);
result.overlap[1] = static_cast<Real>(0);
result.type = Result::isEmpty;
}
}
else // is negative-infinite
{
if (finite[0] < a)
{
result.overlap[0] = finite[0];
result.overlap[1] = std::min(finite[1], a);
if (result.overlap[0] < result.overlap[1])
{
result.numIntersections = 2;
result.type = Result::isFinite;
}
else
{
result.numIntersections = 1;
result.type = Result::isPoint;
}
}
else if (finite[0] == a)
{
result.numIntersections = 1;
result.overlap[0] = a;
result.overlap[1] = result.overlap[0];
result.type = Result::isPoint;
}
else
{
result.numIntersections = 0;
result.overlap[0] = static_cast<Real>(0);
result.overlap[1] = static_cast<Real>(0);
result.type = Result::isEmpty;
}
}
result.intersect = (result.numIntersections > 0);
return result;
}
Result operator()(Real const& a0, bool isPositiveInfinite0,
Real const& a1, bool isPositiveInfinite1)
{
Result result{};
if (isPositiveInfinite0)
{
if (isPositiveInfinite1)
{
// overlap[1] is +infinity, but set it to +1 because Real
// might not have a representation for +infinity. The
// type indicates the interval is positive-infinite, so
// the +1 is a reminder that overlap[1] is +infinity.
result.numIntersections = 1;
result.overlap[0] = std::max(a0, a1);
result.overlap[1] = static_cast<Real>(+1);
result.type = Result::isPositiveInfinite;
}
else // interval1 is negative-infinite
{
if (a0 > a1)
{
result.numIntersections = 0;
result.overlap[0] = static_cast<Real>(0);
result.overlap[1] = static_cast<Real>(0);
result.type = Result::isEmpty;
}
else if (a0 < a1)
{
result.numIntersections = 2;
result.overlap[0] = a0;
result.overlap[1] = a1;
result.type = Result::isFinite;
}
else // a0 == a1
{
result.numIntersections = 1;
result.overlap[0] = a0;
result.overlap[1] = result.overlap[0];
result.type = Result::isPoint;
}
}
}
else // interval0 is negative-infinite
{
if (isPositiveInfinite1)
{
if (a0 < a1)
{
result.numIntersections = 0;
result.overlap[0] = static_cast<Real>(0);
result.overlap[1] = static_cast<Real>(0);
result.type = Result::isEmpty;
}
else if (a0 > a1)
{
result.numIntersections = 2;
result.overlap[0] = a1;
result.overlap[1] = a0;
result.type = Result::isFinite;
}
else
{
result.numIntersections = 1;
result.overlap[0] = a1;
result.overlap[1] = result.overlap[0];
result.type = Result::isPoint;
}
result.intersect = (a0 >= a1);
}
else // interval1 is negative-infinite
{
// overlap[0] is -infinity, but set it to -1 because Real
// might not have a representation for -infinity. The
// type indicates the interval is negative-infinite, so
// the -1 is a reminder that overlap[0] is -infinity.
result.numIntersections = 1;
result.overlap[0] = static_cast<Real>(-1);
result.overlap[1] = std::min(a0, a1);
result.type = Result::isNegativeInfinite;
}
}
result.intersect = (result.numIntersections > 0);
return result;
}
// Dynamic query. Current time is 0, maxTime > 0 is required.
Result operator()(Real maxTime, std::array<Real, 2> const& interval0,
Real speed0, std::array<Real, 2> const& interval1, Real speed1)
{
Result result{};
result.type = Result::isDynamicQuery;
if (interval0[1] < interval1[0])
{
// interval0 initially to the left of interval1.
Real diffSpeed = speed0 - speed1;
if (diffSpeed > static_cast<Real>(0))
{
// The intervals must move towards each other. 'intersect'
// is true when the intervals will intersect by maxTime.
Real diffPos = interval1[0] - interval0[1];
result.intersect = (diffPos <= maxTime * diffSpeed);
result.numIntersections = 1;
result.firstTime = diffPos / diffSpeed;
result.lastTime = (interval1[1] - interval0[0]) / diffSpeed;
result.overlap[0] = interval0[0] + result.firstTime * speed0;
result.overlap[1] = result.overlap[0];
return result;
}
}
else if (interval0[0] > interval1[1])
{
// interval0 initially to the right of interval1.
Real diffSpeed = speed1 - speed0;
if (diffSpeed > static_cast<Real>(0))
{
// The intervals must move towards each other. 'intersect'
// is true when the intervals will intersect by maxTime.
Real diffPos = interval0[0] - interval1[1];
result.intersect = (diffPos <= maxTime * diffSpeed);
result.numIntersections = 1;
result.firstTime = diffPos / diffSpeed;
result.lastTime = (interval0[1] - interval1[0]) / diffSpeed;
result.overlap[0] = interval1[1] + result.firstTime * speed1;
result.overlap[1] = result.overlap[0];
return result;
}
}
else
{
// The intervals are initially intersecting.
result.intersect = true;
result.firstTime = static_cast<Real>(0);
if (speed1 > speed0)
{
result.lastTime = (interval0[1] - interval1[0]) / (speed1 - speed0);
}
else if (speed1 < speed0)
{
result.lastTime = (interval1[1] - interval0[0]) / (speed0 - speed1);
}
else
{
result.lastTime = std::numeric_limits<Real>::max();
}
if (interval0[1] > interval1[0])
{
if (interval0[0] < interval1[1])
{
result.numIntersections = 2;
result.overlap[0] = (interval0[0] < interval1[0] ? interval1[0] : interval0[0]);
result.overlap[1] = (interval0[1] > interval1[1] ? interval1[1] : interval0[1]);
}
else // interval0[0] == interval1[1]
{
result.numIntersections = 1;
result.overlap[0] = interval0[0];
result.overlap[1] = result.overlap[0];
}
}
else // interval0[1] == interval1[0]
{
result.numIntersections = 1;
result.overlap[0] = interval0[1];
result.overlap[1] = result.overlap[0];
}
return result;
}
// The Result constructor sets the correct state for no-intersection.
return result;
}
};
// Template aliases for convenience.
template <typename Real>
using TIIntervalInterval = TIQuery<Real, std::array<Real, 2>, std::array<Real, 2>>;
template <typename Real>
using FIIntervalInterval = FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DCPQuery.h | .h | 452 | 18 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <cstdint>
namespace gte
{
// Distance and closest-point queries.
template <typename Real, typename Type0, typename Type1>
class DCPQuery {};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Matrix.h | .h | 22,385 | 748 | // 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>
#include <Mathematics/GaussianElimination.h>
namespace gte
{
template <int32_t NumRows, int32_t NumCols, typename Real>
class Matrix
{
public:
// The table is initialized to zero.
Matrix()
{
MakeZero();
}
// The table is fully initialized by the inputs. The 'values' must be
// specified in row-major order, regardless of the active storage
// scheme (GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR).
Matrix(std::array<Real, NumRows * NumCols> const& values)
{
for (int32_t r = 0, i = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c, ++i)
{
mTable(r, c) = values[i];
}
}
}
// At most NumRows*NumCols are copied from the initializer list,
// setting any remaining elements to zero. The 'values' must be
// specified in row-major order, regardless of the active storage
// scheme (GTE_USE_ROW_MAJOR or GTE_USE_COL_MAJOR). Create the zero
// matrix using the syntax
// Matrix<NumRows,NumCols,Real> zero{(Real)0};
// WARNING: The C++ 11 specification states that
// Matrix<NumRows,NumCols,Real> zero{};
// will lead to a call of the default constructor, not the initializer
// constructor!
Matrix(std::initializer_list<Real> values)
{
int32_t const numValues = static_cast<int32_t>(values.size());
auto iter = values.begin();
int32_t r, c, i;
for (r = 0, i = 0; r < NumRows; ++r)
{
for (c = 0; c < NumCols; ++c, ++i)
{
if (i < numValues)
{
mTable(r, c) = *iter++;
}
else
{
break;
}
}
if (c < NumCols)
{
// Fill in the remaining columns of the current row with zeros.
for (/**/; c < NumCols; ++c)
{
mTable(r, c) = (Real)0;
}
++r;
break;
}
}
if (r < NumRows)
{
// Fill in the remain rows with zeros.
for (/**/; r < NumRows; ++r)
{
for (c = 0; c < NumCols; ++c)
{
mTable(r, c) = (Real)0;
}
}
}
}
// For 0 <= r < NumRows and 0 <= c < NumCols, element (r,c) is 1 and
// all others are 0. If either of r or c is invalid, the zero matrix
// is created. This is a convenience for creating the standard
// Euclidean basis matrices; see also MakeUnit(int32_t,int32_t) and
// Unit(int32_t,int32_t).
Matrix(int32_t r, int32_t c)
{
MakeUnit(r, c);
}
// The copy constructor, destructor, and assignment operator are
// generated by the compiler.
// Member access for which the storage representation is transparent.
// The matrix entry in row r and column c is A(r,c). 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.
inline Real const& operator()(int32_t r, int32_t c) const
{
return mTable(r, c);
}
inline Real& operator()(int32_t r, int32_t c)
{
return mTable(r, c);
}
// Member access by rows or by columns.
void SetRow(int32_t r, Vector<NumCols, Real> const& vec)
{
for (int32_t c = 0; c < NumCols; ++c)
{
mTable(r, c) = vec[c];
}
}
void SetCol(int32_t c, Vector<NumRows, Real> const& vec)
{
for (int32_t r = 0; r < NumRows; ++r)
{
mTable(r, c) = vec[r];
}
}
Vector<NumCols, Real> GetRow(int32_t r) const
{
Vector<NumCols, Real> vec;
for (int32_t c = 0; c < NumCols; ++c)
{
vec[c] = mTable(r, c);
}
return vec;
}
Vector<NumRows, Real> GetCol(int32_t c) const
{
Vector<NumRows, Real> vec;
for (int32_t r = 0; r < NumRows; ++r)
{
vec[r] = mTable(r, c);
}
return vec;
}
// Member access by 1-dimensional index. NOTE: These accessors are
// useful for the manipulation of matrix entries when it does not
// matter whether storage is row-major or column-major. Do not use
// constructs such as M[c+NumCols*r] or M[r+NumRows*c] that expose the
// storage convention.
inline Real const& operator[](int32_t i) const
{
return mTable[i];
}
inline Real& operator[](int32_t i)
{
return mTable[i];
}
// Comparisons for sorted containers and geometric ordering.
inline bool operator==(Matrix const& mat) const
{
return mTable.mStorage == mat.mTable.mStorage;
}
inline bool operator!=(Matrix const& mat) const
{
return mTable.mStorage != mat.mTable.mStorage;
}
inline bool operator< (Matrix const& mat) const
{
return mTable.mStorage < mat.mTable.mStorage;
}
inline bool operator<=(Matrix const& mat) const
{
return mTable.mStorage <= mat.mTable.mStorage;
}
inline bool operator> (Matrix const& mat) const
{
return mTable.mStorage > mat.mTable.mStorage;
}
inline bool operator>=(Matrix const& mat) const
{
return mTable.mStorage >= mat.mTable.mStorage;
}
// Special matrices.
// All components are 0.
void MakeZero()
{
Real const zero(0);
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
mTable[i] = zero;
}
}
// Component (r,c) is 1, all others zero.
void MakeUnit(int32_t r, int32_t c)
{
MakeZero();
if (0 <= r && r < NumRows && 0 <= c && c < NumCols)
{
mTable(r, c) = (Real)1;
}
}
// Diagonal entries 1, others 0, even when nonsquare
void MakeIdentity()
{
MakeZero();
int32_t const numDiagonal = (NumRows <= NumCols ? NumRows : NumCols);
for (int32_t i = 0; i < numDiagonal; ++i)
{
mTable(i, i) = (Real)1;
}
}
static Matrix Zero()
{
Matrix M;
M.MakeZero();
return M;
}
static Matrix Unit(int32_t r, int32_t c)
{
Matrix M;
M.MakeUnit(r, c);
return M;
}
static Matrix Identity()
{
Matrix M;
M.MakeIdentity();
return M;
}
protected:
class Table
{
public:
Table()
:
mStorage{}
{
#if defined(GTE_USE_ROW_MAJOR)
for (size_t r = 0; r < NumRows; ++r)
{
for (size_t c = 0; c < NumCols; ++c)
{
mStorage[r][c] = (Real)0;
}
}
#else
for (size_t c = 0; c < NumCols; ++c)
{
for (size_t r = 0; r < NumRows; ++r)
{
mStorage[c][r] = (Real)0;
}
}
#endif
}
// Storage-order-independent element access as 2D array.
inline Real const& operator()(int32_t r, int32_t c) const
{
#if defined(GTE_USE_ROW_MAJOR)
return mStorage[r][c];
#else
return mStorage[c][r];
#endif
}
inline Real& operator()(int32_t r, int32_t c)
{
#if defined(GTE_USE_ROW_MAJOR)
return mStorage[r][c];
#else
return mStorage[c][r];
#endif
}
// Element access as 1D array. Use this internally only when
// the 2D storage order is not relevant.
inline Real const& operator[](int32_t i) const
{
Real const* elements = &mStorage[0][0];
return elements[i];
}
inline Real& operator[](int32_t i)
{
Real* elements = &mStorage[0][0];
return elements[i];
}
#if defined(GTE_USE_ROW_MAJOR)
std::array<std::array<Real, NumCols>, NumRows> mStorage;
#else
std::array<std::array<Real, NumRows>, NumCols> mStorage;
#endif
};
Table mTable;
};
// Unary operations.
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator+(Matrix<NumRows, NumCols, Real> const& M)
{
return M;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator-(Matrix<NumRows, NumCols, Real> const& M)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
result[i] = -M[i];
}
return result;
}
// Linear-algebraic operations.
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator+(
Matrix<NumRows, NumCols, Real> const& M0,
Matrix<NumRows, NumCols, Real> const& M1)
{
Matrix<NumRows, NumCols, Real> result = M0;
return result += M1;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator-(
Matrix<NumRows, NumCols, Real> const& M0,
Matrix<NumRows, NumCols, Real> const& M1)
{
Matrix<NumRows, NumCols, Real> result = M0;
return result -= M1;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator*(
Matrix<NumRows, NumCols, Real> const& M, Real scalar)
{
Matrix<NumRows, NumCols, Real> result = M;
return result *= scalar;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator*(
Real scalar, Matrix<NumRows, NumCols, Real> const& M)
{
Matrix<NumRows, NumCols, Real> result = M;
return result *= scalar;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> operator/(
Matrix<NumRows, NumCols, Real> const& M, Real scalar)
{
Matrix<NumRows, NumCols, Real> result = M;
return result /= scalar;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real>& operator+=(
Matrix<NumRows, NumCols, Real>& M0,
Matrix<NumRows, NumCols, Real> const& M1)
{
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
M0[i] += M1[i];
}
return M0;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real>& operator-=(
Matrix<NumRows, NumCols, Real>& M0,
Matrix<NumRows, NumCols, Real> const& M1)
{
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
M0[i] -= M1[i];
}
return M0;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real>& operator*=(
Matrix<NumRows, NumCols, Real>& M, Real scalar)
{
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
M[i] *= scalar;
}
return M;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real>& operator/=(
Matrix<NumRows, NumCols, Real>& M, Real scalar)
{
if (scalar != (Real)0)
{
Real invScalar = ((Real)1) / scalar;
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
M[i] *= invScalar;
}
}
else
{
for (int32_t i = 0; i < NumRows * NumCols; ++i)
{
M[i] = (Real)0;
}
}
return M;
}
// Geometric operations.
template <int32_t NumRows, int32_t NumCols, typename Real>
Real L1Norm(Matrix<NumRows, NumCols, Real> const& M)
{
Real sum = std::fabs(M[0]);
for (int32_t i = 1; i < NumRows * NumCols; ++i)
{
sum += std::fabs(M[i]);
}
return sum;
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Real L2Norm(Matrix<NumRows, NumCols, Real> const& M)
{
Real sum = M[0] * M[0];
for (int32_t i = 1; i < NumRows * NumCols; ++i)
{
sum += M[i] * M[i];
}
return std::sqrt(sum);
}
template <int32_t NumRows, int32_t NumCols, typename Real>
Real LInfinityNorm(Matrix<NumRows, NumCols, Real> const& M)
{
Real maxAbsElement = M[0];
for (int32_t i = 1; i < NumRows * NumCols; ++i)
{
Real absElement = std::fabs(M[i]);
if (absElement > maxAbsElement)
{
maxAbsElement = absElement;
}
}
return maxAbsElement;
}
template <int32_t N, typename Real>
Matrix<N, N, Real> Inverse(Matrix<N, N, Real> const& M, bool* reportInvertibility = nullptr)
{
Matrix<N, N, Real> invM;
Real determinant;
bool invertible = GaussianElimination<Real>()(N, &M[0], &invM[0],
determinant, nullptr, nullptr, nullptr, 0, nullptr);
if (reportInvertibility)
{
*reportInvertibility = invertible;
}
return invM;
}
template <int32_t N, typename Real>
Real Determinant(Matrix<N, N, Real> const& M)
{
Real determinant;
GaussianElimination<Real>()(N, &M[0], nullptr, determinant, nullptr,
nullptr, nullptr, 0, nullptr);
return determinant;
}
// M^T
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumCols, NumRows, Real> Transpose(Matrix<NumRows, NumCols, Real> const& M)
{
Matrix<NumCols, NumRows, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(c, r) = M(r, c);
}
}
return result;
}
// M*V
template <int32_t NumRows, int32_t NumCols, typename Real>
Vector<NumRows, Real> operator*(Matrix<NumRows, NumCols, Real> const& M,
Vector<NumCols, Real> const& V)
{
Vector<NumRows, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
result[r] = (Real)0;
for (int32_t c = 0; c < NumCols; ++c)
{
result[r] += M(r, c) * V[c];
}
}
return result;
}
// V^T*M
template <int32_t NumRows, int32_t NumCols, typename Real>
Vector<NumCols, Real> operator*(Vector<NumRows, Real> const& V,
Matrix<NumRows, NumCols, Real> const& M)
{
Vector<NumCols, Real> result;
for (int32_t c = 0; c < NumCols; ++c)
{
result[c] = (Real)0;
for (int32_t r = 0; r < NumRows; ++r)
{
result[c] += V[r] * M(r, c);
}
}
return result;
}
// A*B
template <int32_t NumRows, int32_t NumCols, int32_t NumCommon, typename Real>
Matrix<NumRows, NumCols, Real> operator*(
Matrix<NumRows, NumCommon, Real> const& A,
Matrix<NumCommon, NumCols, Real> const& B)
{
return MultiplyAB(A, B);
}
template <int32_t NumRows, int32_t NumCols, int32_t NumCommon, typename Real>
Matrix<NumRows, NumCols, Real> MultiplyAB(
Matrix<NumRows, NumCommon, Real> const& A,
Matrix<NumCommon, NumCols, Real> const& B)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = (Real)0;
for (int32_t i = 0; i < NumCommon; ++i)
{
result(r, c) += A(r, i) * B(i, c);
}
}
}
return result;
}
// A*B^T
template <int32_t NumRows, int32_t NumCols, int32_t NumCommon, typename Real>
Matrix<NumRows, NumCols, Real> MultiplyABT(
Matrix<NumRows, NumCommon, Real> const& A,
Matrix<NumCols, NumCommon, Real> const& B)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = (Real)0;
for (int32_t i = 0; i < NumCommon; ++i)
{
result(r, c) += A(r, i) * B(c, i);
}
}
}
return result;
}
// A^T*B
template <int32_t NumRows, int32_t NumCols, int32_t NumCommon, typename Real>
Matrix<NumRows, NumCols, Real> MultiplyATB(
Matrix<NumCommon, NumRows, Real> const& A,
Matrix<NumCommon, NumCols, Real> const& B)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = (Real)0;
for (int32_t i = 0; i < NumCommon; ++i)
{
result(r, c) += A(i, r) * B(i, c);
}
}
}
return result;
}
// A^T*B^T
template <int32_t NumRows, int32_t NumCols, int32_t NumCommon, typename Real>
Matrix<NumRows, NumCols, Real> MultiplyATBT(
Matrix<NumCommon, NumRows, Real> const& A,
Matrix<NumCols, NumCommon, Real> const& B)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = (Real)0;
for (int32_t i = 0; i < NumCommon; ++i)
{
result(r, c) += A(i, r) * B(c, i);
}
}
}
return result;
}
// M*D, D is diagonal NumCols-by-NumCols
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> MultiplyMD(
Matrix<NumRows, NumCols, Real> const& M,
Vector<NumCols, Real> const& D)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = M(r, c) * D[c];
}
}
return result;
}
// D*M, D is diagonal NumRows-by-NumRows
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> MultiplyDM(
Vector<NumRows, Real> const& D,
Matrix<NumRows, NumCols, Real> const& M)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = D[r] * M(r, c);
}
}
return result;
}
// U*V^T, U is NumRows-by-1, V is Num-Cols-by-1, result is NumRows-by-NumCols.
template <int32_t NumRows, int32_t NumCols, typename Real>
Matrix<NumRows, NumCols, Real> OuterProduct(
Vector<NumRows, Real> const& U, Vector<NumCols, Real> const& V)
{
Matrix<NumRows, NumCols, Real> result;
for (int32_t r = 0; r < NumRows; ++r)
{
for (int32_t c = 0; c < NumCols; ++c)
{
result(r, c) = U[r] * V[c];
}
}
return result;
}
// Initialization to a diagonal matrix whose diagonal entries are the
// components of D.
template <int32_t N, typename Real>
void MakeDiagonal(Vector<N, Real> const& D, Matrix<N, N, Real>& M)
{
for (int32_t i = 0; i < N * N; ++i)
{
M[i] = (Real)0;
}
for (int32_t i = 0; i < N; ++i)
{
M(i, i) = D[i];
}
}
// Create an (N+1)-by-(N+1) matrix H by setting the upper N-by-N block to
// the input N-by-N matrix and all other entries to 0 except for the last
// row and last column entry which is set to 1.
template <int32_t N, typename Real>
Matrix<N + 1, N + 1, Real> HLift(Matrix<N, N, Real> const& M)
{
Matrix<N + 1, N + 1, Real> result;
result.MakeIdentity();
for (int32_t r = 0; r < N; ++r)
{
for (int32_t c = 0; c < N; ++c)
{
result(r, c) = M(r, c);
}
}
return result;
}
// Extract the upper (N-1)-by-(N-1) block of the input N-by-N matrix.
template <int32_t N, typename Real>
Matrix<N - 1, N - 1, Real> HProject(Matrix<N, N, Real> const& M)
{
static_assert(N >= 2, "Invalid matrix dimension.");
Matrix<N - 1, N - 1, Real> result;
for (int32_t r = 0; r < N - 1; ++r)
{
for (int32_t c = 0; c < N - 1; ++c)
{
result(r, c) = M(r, c);
}
}
return result;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ContCylinder3.h | .h | 2,522 | 77 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/ApprOrthogonalLine3.h>
#include <Mathematics/Cylinder3.h>
#include <Mathematics/DistPointLine.h>
namespace gte
{
// Compute the cylinder axis segment using least-squares fit. The radius
// is the maximum distance from points to the axis. The height is
// determined by projection of points onto the axis and determining the
// containing interval.
template <typename Real>
bool GetContainer(int32_t numPoints, Vector3<Real> const* points, Cylinder3<Real>& cylinder)
{
ApprOrthogonalLine3<Real> fitter;
fitter.Fit(numPoints, points);
Line3<Real> line = fitter.GetParameters();
DCPQuery<Real, Vector3<Real>, Line3<Real>> plQuery;
Real maxRadiusSqr = (Real)0;
for (int32_t i = 0; i < numPoints; ++i)
{
auto result = plQuery(points[i], line);
if (result.sqrDistance > maxRadiusSqr)
{
maxRadiusSqr = result.sqrDistance;
}
}
Vector3<Real> diff = points[0] - line.origin;
Real wMin = Dot(line.direction, diff);
Real wMax = wMin;
for (int32_t i = 1; i < numPoints; ++i)
{
diff = points[i] - line.origin;
Real w = Dot(line.direction, diff);
if (w < wMin)
{
wMin = w;
}
else if (w > wMax)
{
wMax = w;
}
}
cylinder.axis.origin = line.origin + ((Real)0.5 * (wMax + wMin)) * line.direction;
cylinder.axis.direction = line.direction;
cylinder.radius = std::sqrt(maxRadiusSqr);
cylinder.height = wMax - wMin;
return true;
}
// Test for containment of a point by a cylinder.
template <typename Real>
bool InContainer(Vector3<Real> const& point, Cylinder3<Real> const& cylinder)
{
Vector3<Real> diff = point - cylinder.axis.origin;
Real zProj = Dot(diff, cylinder.axis.direction);
if (std::fabs(zProj) * (Real)2 > cylinder.height)
{
return false;
}
Vector3<Real> xyProj = diff - zProj * cylinder.axis.direction;
return Length(xyProj) <= cylinder.radius;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrPlane3Capsule3.h | .h | 1,647 | 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/TIQuery.h>
#include <Mathematics/DistPointHyperplane.h>
#include <Mathematics/Capsule.h>
namespace gte
{
template <typename Real>
class TIQuery<Real, Plane3<Real>, Capsule3<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Plane3<Real> const& plane, Capsule3<Real> const& capsule)
{
Result result{};
DCPQuery<Real, Vector3<Real>, Plane3<Real>> vpQuery;
Real sdistance0 = vpQuery(capsule.segment.p[0], plane).signedDistance;
Real sdistance1 = vpQuery(capsule.segment.p[1], plane).signedDistance;
if (sdistance0 * sdistance1 <= (Real)0)
{
// A capsule segment endpoint is on the plane or the two
// endpoints are on opposite sides of the plane.
result.intersect = true;
return result;
}
// The endpoints on same side of plane, but the endpoint spheres
// might intersect the plane.
result.intersect =
std::fabs(sdistance0) <= capsule.radius ||
std::fabs(sdistance1) <= capsule.radius;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrAlignedBox2AlignedBox2.h | .h | 2,756 | 107 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/FIQuery.h>
#include <Mathematics/TIQuery.h>
#include <Mathematics/AlignedBox.h>
// The queries consider the box to be a solid.
//
// The aligned-aligned queries use simple min-max comparisions. The
// interesection of aligned boxes is an aligned box, possibly degenerate,
// where min[d] == max[d] for at least one dimension d.
namespace gte
{
template <typename T>
class TIQuery<T, AlignedBox2<T>, AlignedBox2<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(AlignedBox2<T> const& box0, AlignedBox2<T> const& box1)
{
Result result{};
for (int32_t i = 0; i < 2; i++)
{
if (box0.max[i] < box1.min[i] || box0.min[i] > box1.max[i])
{
result.intersect = false;
return result;
}
}
result.intersect = true;
return result;
}
};
template <typename T>
class FIQuery<T, AlignedBox2<T>, AlignedBox2<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
box{}
{
}
bool intersect;
AlignedBox2<T> box;
};
Result operator()(AlignedBox2<T> const& box0, AlignedBox2<T> const& box1)
{
Result result{};
for (int32_t i = 0; i < 2; i++)
{
if (box0.max[i] < box1.min[i] || box0.min[i] > box1.max[i])
{
result.intersect = false;
return result;
}
}
for (int32_t i = 0; i < 2; i++)
{
if (box0.max[i] <= box1.max[i])
{
result.box.max[i] = box0.max[i];
}
else
{
result.box.max[i] = box1.max[i];
}
if (box0.min[i] <= box1.min[i])
{
result.box.min[i] = box1.min[i];
}
else
{
result.box.min[i] = box0.min[i];
}
}
result.intersect = true;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntpQuadraticNonuniform2.h | .h | 19,067 | 476 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.02.01
#pragma once
#include <Mathematics/Delaunay2.h>
#include <Mathematics/ContScribeCircle2.h>
#include <Mathematics/DistPointAlignedBox.h>
// Quadratic interpolation of a network of triangles whose vertices are of
// the form (x,y,f(x,y)). This code is an implementation of the algorithm
// found in
//
// Zoltan J. Cendes and Steven H. Wong,
// C1 quadratic interpolation over arbitrary point sets,
// IEEE Computer Graphics & Applications,
// pp. 8-16, 1987
//
// The TriangleMesh interface must support the following:
// int32_t GetNumVertices() const;
// int32_t GetNumTriangles() const;
// Vector2<Real> const* GetVertices() const;
// int32_t const* GetIndices() const;
// bool GetVertices(int32_t, std::array<Vector2<Real>, 3>&) const;
// bool GetIndices(int32_t, std::array<int32_t, 3>&) const;
// bool GetAdjacencies(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 IntpQuadraticNonuniform2
{
public:
// Construction.
//
// The first constructor requires only F and a measure of the rate of
// change of the function values relative to changes in the spatial
// variables. The df/dx and df/dy values are estimated at the sample
// points using mesh normals and spatialDelta.
//
// The second constructor requires you to specify function values F
// and first-order partial derivative values df/dx and df/dy.
IntpQuadraticNonuniform2(TriangleMesh const& mesh, Real const* F, Real spatialDelta)
:
mMesh(&mesh),
mF(F),
mFX(nullptr),
mFY(nullptr)
{
EstimateDerivatives(spatialDelta);
ProcessTriangles();
}
IntpQuadraticNonuniform2(TriangleMesh const& mesh, Real const* F, Real const* FX, Real const* FY)
:
mMesh(&mesh),
mF(F),
mFX(FX),
mFY(FY)
{
ProcessTriangles();
}
// Quadratic interpolation. The return value is 'true' if and only if
// the input point is in the convex hull of the input vertices, in
// which case the interpolation is valid.
bool operator()(Vector2<Real> const& P, Real& F, Real& FX, Real& FY) const
{
auto t = mMesh->GetContainingTriangle(P);
if (t == mMesh->GetInvalidIndex())
{
// The point is outside the triangulation.
return false;
}
// Get the vertices of the triangle.
std::array<Vector2<Real>, 3> V;
mMesh->GetVertices(t, V);
// Get the additional information for the triangle.
TriangleData const& tData = mTData[t];
// Determine which of the six subtriangles contains the target
// point. Theoretically, P must be in one of these subtriangles.
Vector2<Real> sub0 = tData.center;
Vector2<Real> sub1;
Vector2<Real> sub2 = tData.intersect[2];
Vector3<Real> bary;
int32_t index;
Real const zero = (Real)0, one = (Real)1;
AlignedBox3<Real> barybox({ zero, zero, zero }, { one, one, one });
DCPQuery<Real, Vector3<Real>, AlignedBox3<Real>> pbQuery;
int32_t minIndex = 0;
Real minDistance = (Real)-1;
Vector3<Real> minBary{ (Real)0, (Real)0, (Real)0 };
Vector2<Real> minSub0{ (Real)0, (Real)0 };
Vector2<Real> minSub1{ (Real)0, (Real)0 };
Vector2<Real> minSub2{ (Real)0, (Real)0 };
for (index = 1; index <= 6; ++index)
{
sub1 = sub2;
if ((index % 2) != 0) // index is odd
{
size_t lookup = static_cast<size_t>(index) / 2;
sub2 = V[lookup];
}
else // index is even
{
size_t lookup = (static_cast<size_t>(index) - 1) / 2;
sub2 = tData.intersect[lookup];
}
std::array<Real, 3> localBary{};
bool valid = ComputeBarycentrics(P, sub0, sub1, sub2, localBary);
for (int32_t k = 0; k < 3; ++k)
{
bary[k] = localBary[k];
}
if (valid
&& zero <= bary[0] && bary[0] <= one
&& zero <= bary[1] && bary[1] <= one
&& zero <= bary[2] && bary[2] <= one)
{
// P is in triangle <Sub0,Sub1,Sub2>
break;
}
// When computing with floating-point arithmetic, rounding
// errors can cause us to reach this code when, theoretically,
// the point is in the subtriangle. Keep track of the
// (b0,b1,b2) that is closest to the barycentric cube [0,1]^3
// and choose the triangle corresponding to it when all 6
// tests previously fail.
Real distance = pbQuery(bary, barybox).distance;
if (minIndex == 0 || distance < minDistance)
{
minDistance = distance;
minIndex = index;
minBary = bary;
minSub0 = sub0;
minSub1 = sub1;
minSub2 = sub2;
}
}
// If the subtriangle was not found, rounding errors caused
// problems. Choose the barycentric point closest to the box.
if (index > 6)
{
index = minIndex;
bary = minBary;
sub0 = minSub0;
sub1 = minSub1;
sub2 = minSub2;
}
// Fetch Bezier control points.
Real bez[6] =
{
tData.coeff[0],
tData.coeff[12 + static_cast<size_t>(index)],
tData.coeff[13 + (static_cast<size_t>(index) % 6)],
tData.coeff[static_cast<size_t>(index)],
tData.coeff[6 + static_cast<size_t>(index)],
tData.coeff[1 + (static_cast<size_t>(index) % 6)]
};
// Evaluate Bezier quadratic.
F = bary[0] * (bez[0] * bary[0] + bez[1] * bary[1] + bez[2] * bary[2]) +
bary[1] * (bez[1] * bary[0] + bez[3] * bary[1] + bez[4] * bary[2]) +
bary[2] * (bez[2] * bary[0] + bez[4] * bary[1] + bez[5] * bary[2]);
// Evaluate barycentric derivatives of F.
Real FU = ((Real)2) * (bez[0] * bary[0] + bez[1] * bary[1] +
bez[2] * bary[2]);
Real FV = ((Real)2) * (bez[1] * bary[0] + bez[3] * bary[1] +
bez[4] * bary[2]);
Real FW = ((Real)2) * (bez[2] * bary[0] + bez[4] * bary[1] +
bez[5] * bary[2]);
Real duw = FU - FW;
Real dvw = FV - FW;
// Convert back to (x,y) coordinates.
Real m00 = sub0[0] - sub2[0];
Real m10 = sub0[1] - sub2[1];
Real m01 = sub1[0] - sub2[0];
Real m11 = sub1[1] - sub2[1];
Real inv = ((Real)1) / (m00 * m11 - m10 * m01);
FX = inv * (m11 * duw - m10 * dvw);
FY = inv * (m00 * dvw - m01 * duw);
return true;
}
private:
void EstimateDerivatives(Real spatialDelta)
{
auto numVertices = mMesh->GetNumVertices();
Vector2<Real> const* vertices = mMesh->GetVertices();
auto numTriangles = mMesh->GetNumTriangles();
int32_t const* indices = mMesh->GetIndices();
mFXStorage.resize(numVertices);
mFYStorage.resize(numVertices);
std::vector<Real> FZ(numVertices);
std::fill(mFXStorage.begin(), mFXStorage.end(), (Real)0);
std::fill(mFYStorage.begin(), mFYStorage.end(), (Real)0);
std::fill(FZ.begin(), FZ.end(), (Real)0);
mFX = &mFXStorage[0];
mFY = &mFYStorage[0];
// Accumulate normals at spatial locations (averaging process).
for (auto t = 0; t < numTriangles; ++t)
{
// Get three vertices of triangle.
int32_t v0 = *indices++;
int32_t v1 = *indices++;
int32_t v2 = *indices++;
// Compute normal vector of triangle (with positive
// z-component).
Real dx1 = vertices[v1][0] - vertices[v0][0];
Real dy1 = vertices[v1][1] - vertices[v0][1];
Real dz1 = mF[v1] - mF[v0];
Real dx2 = vertices[v2][0] - vertices[v0][0];
Real dy2 = vertices[v2][1] - vertices[v0][1];
Real dz2 = mF[v2] - mF[v0];
Real nx = dy1 * dz2 - dy2 * dz1;
Real ny = dz1 * dx2 - dz2 * dx1;
Real nz = dx1 * dy2 - dx2 * dy1;
if (nz < (Real)0)
{
nx = -nx;
ny = -ny;
nz = -nz;
}
mFXStorage[v0] += nx; mFYStorage[v0] += ny; FZ[v0] += nz;
mFXStorage[v1] += nx; mFYStorage[v1] += ny; FZ[v1] += nz;
mFXStorage[v2] += nx; mFYStorage[v2] += ny; FZ[v2] += nz;
}
// Scale the normals to form (x,y,-1).
for (auto i = 0; i < numVertices; ++i)
{
if (FZ[i] != (Real)0)
{
Real inv = -spatialDelta / FZ[i];
mFXStorage[i] *= inv;
mFYStorage[i] *= inv;
}
else
{
mFXStorage[i] = (Real)0;
mFYStorage[i] = (Real)0;
}
}
}
void ProcessTriangles()
{
// Add degenerate triangles to boundary triangles so that
// interpolation at the boundary can be treated in the same way
// as interpolation in the interior.
// Compute centers of inscribed circles for triangles.
Vector2<Real> const* vertices = mMesh->GetVertices();
auto numTriangles = mMesh->GetNumTriangles();
int32_t const* indices = mMesh->GetIndices();
mTData.resize(numTriangles);
for (auto t = 0; t < numTriangles; ++t)
{
int32_t v0 = *indices++;
int32_t v1 = *indices++;
int32_t v2 = *indices++;
Circle2<Real> circle;
Inscribe(vertices[v0], vertices[v1], vertices[v2], circle);
mTData[t].center = circle.center;
}
// Compute cross-edge intersections.
for (auto t = 0; t < numTriangles; ++t)
{
ComputeCrossEdgeIntersections(t);
}
// Compute Bezier coefficients.
for (auto t = 0; t < numTriangles; ++t)
{
ComputeCoefficients(t);
}
}
void ComputeCrossEdgeIntersections(int32_t t)
{
// Get the vertices of the triangle.
std::array<Vector2<Real>, 3> V;
mMesh->GetVertices(t, V);
// Get the centers of adjacent triangles.
TriangleData& tData = mTData[t];
std::array<int32_t, 3> adjacencies = { 0, 0, 0 };
mMesh->GetAdjacencies(t, adjacencies);
for (int32_t j0 = 2, j1 = 0; j1 < 3; j0 = j1++)
{
int32_t a = adjacencies[j0];
if (a >= 0)
{
// Get center of adjacent triangle's inscribing circle.
Vector2<Real> U = mTData[a].center;
Real m00 = V[j0][1] - V[j1][1];
Real m01 = V[j1][0] - V[j0][0];
Real m10 = tData.center[1] - U[1];
Real m11 = U[0] - tData.center[0];
Real r0 = m00 * V[j0][0] + m01 * V[j0][1];
Real r1 = m10 * tData.center[0] + m11 * tData.center[1];
Real invDet = ((Real)1) / (m00 * m11 - m01 * m10);
tData.intersect[j0][0] = (m11 * r0 - m01 * r1) * invDet;
tData.intersect[j0][1] = (m00 * r1 - m10 * r0) * invDet;
}
else
{
// No adjacent triangle, use center of edge.
tData.intersect[j0] = (Real)0.5 * (V[j0] + V[j1]);
}
}
}
void ComputeCoefficients(int32_t t)
{
// Get the vertices of the triangle.
std::array<Vector2<Real>, 3> V;
mMesh->GetVertices(t, V);
// Get the additional information for the triangle.
TriangleData& tData = mTData[t];
// Get the sample data at main triangle vertices.
std::array<int32_t, 3> indices = { 0, 0, 0 };
mMesh->GetIndices(t, indices);
std::array<Jet, 3> jet;
for (int32_t j = 0; j < 3; ++j)
{
int32_t k = indices[j];
jet[j].F = mF[k];
jet[j].FX = mFX[k];
jet[j].FY = mFY[k];
}
// Get centers of adjacent triangles.
std::array<int32_t, 3> adjacencies = { 0, 0, 0 };
mMesh->GetAdjacencies(t, adjacencies);
Vector2<Real> U[3];
for (int32_t j0 = 2, j1 = 0; j1 < 3; j0 = j1++)
{
int32_t a = adjacencies[j0];
if (a >= 0)
{
// Get center of adjacent triangle's circumscribing
// circle.
U[j0] = mTData[a].center;
}
else
{
// No adjacent triangle, use center of edge.
U[j0] = ((Real)0.5) * (V[j0] + V[j1]);
}
}
// Compute intermediate terms.
std::array<Real, 3> cenT, cen0, cen1, cen2;
mMesh->GetBarycentrics(t, tData.center, cenT);
mMesh->GetBarycentrics(t, U[0], cen0);
mMesh->GetBarycentrics(t, U[1], cen1);
mMesh->GetBarycentrics(t, U[2], cen2);
Real alpha = (cenT[1] * cen1[0] - cenT[0] * cen1[1]) / (cen1[0] - cenT[0]);
Real beta = (cenT[2] * cen2[1] - cenT[1] * cen2[2]) / (cen2[1] - cenT[1]);
Real gamma = (cenT[0] * cen0[2] - cenT[2] * cen0[0]) / (cen0[2] - cenT[2]);
Real oneMinusAlpha = (Real)1 - alpha;
Real oneMinusBeta = (Real)1 - beta;
Real oneMinusGamma = (Real)1 - gamma;
Real const zero = static_cast<Real>(0);
std::array<Real, 9> A = { zero, zero, zero, zero, zero, zero, zero, zero, zero };
std::array<Real, 9> B = { zero, zero, zero, zero, zero, zero, zero, zero, zero };
Real tmp = cenT[0] * V[0][0] + cenT[1] * V[1][0] + cenT[2] * V[2][0];
A[0] = (Real)0.5 * (tmp - V[0][0]);
A[1] = (Real)0.5 * (tmp - V[1][0]);
A[2] = (Real)0.5 * (tmp - V[2][0]);
A[3] = (Real)0.5 * beta * (V[2][0] - V[0][0]);
A[4] = (Real)0.5 * oneMinusGamma * (V[1][0] - V[0][0]);
A[5] = (Real)0.5 * gamma * (V[0][0] - V[1][0]);
A[6] = (Real)0.5 * oneMinusAlpha * (V[2][0] - V[1][0]);
A[7] = (Real)0.5 * alpha * (V[1][0] - V[2][0]);
A[8] = (Real)0.5 * oneMinusBeta * (V[0][0] - V[2][0]);
tmp = cenT[0] * V[0][1] + cenT[1] * V[1][1] + cenT[2] * V[2][1];
B[0] = (Real)0.5 * (tmp - V[0][1]);
B[1] = (Real)0.5 * (tmp - V[1][1]);
B[2] = (Real)0.5 * (tmp - V[2][1]);
B[3] = (Real)0.5 * beta * (V[2][1] - V[0][1]);
B[4] = (Real)0.5 * oneMinusGamma * (V[1][1] - V[0][1]);
B[5] = (Real)0.5 * gamma * (V[0][1] - V[1][1]);
B[6] = (Real)0.5 * oneMinusAlpha * (V[2][1] - V[1][1]);
B[7] = (Real)0.5 * alpha * (V[1][1] - V[2][1]);
B[8] = (Real)0.5 * oneMinusBeta * (V[0][1] - V[2][1]);
// Compute Bezier coefficients.
tData.coeff[2] = jet[0].F;
tData.coeff[4] = jet[1].F;
tData.coeff[6] = jet[2].F;
tData.coeff[14] = jet[0].F + A[0] * jet[0].FX + B[0] * jet[0].FY;
tData.coeff[7] = jet[0].F + A[3] * jet[0].FX + B[3] * jet[0].FY;
tData.coeff[8] = jet[0].F + A[4] * jet[0].FX + B[4] * jet[0].FY;
tData.coeff[16] = jet[1].F + A[1] * jet[1].FX + B[1] * jet[1].FY;
tData.coeff[9] = jet[1].F + A[5] * jet[1].FX + B[5] * jet[1].FY;
tData.coeff[10] = jet[1].F + A[6] * jet[1].FX + B[6] * jet[1].FY;
tData.coeff[18] = jet[2].F + A[2] * jet[2].FX + B[2] * jet[2].FY;
tData.coeff[11] = jet[2].F + A[7] * jet[2].FX + B[7] * jet[2].FY;
tData.coeff[12] = jet[2].F + A[8] * jet[2].FX + B[8] * jet[2].FY;
tData.coeff[5] = alpha * tData.coeff[10] + oneMinusAlpha * tData.coeff[11];
tData.coeff[17] = alpha * tData.coeff[16] + oneMinusAlpha * tData.coeff[18];
tData.coeff[1] = beta * tData.coeff[12] + oneMinusBeta * tData.coeff[7];
tData.coeff[13] = beta * tData.coeff[18] + oneMinusBeta * tData.coeff[14];
tData.coeff[3] = gamma * tData.coeff[8] + oneMinusGamma * tData.coeff[9];
tData.coeff[15] = gamma * tData.coeff[14] + oneMinusGamma * tData.coeff[16];
tData.coeff[0] = cenT[0] * tData.coeff[14] + cenT[1] * tData.coeff[16] + cenT[2] * tData.coeff[18];
}
class TriangleData
{
public:
Vector2<Real> center;
std::array<Vector2<Real>, 3> intersect;
std::array<Real, 19> coeff;
};
class Jet
{
public:
Jet()
:
F(static_cast<Real>(0)),
FX(static_cast<Real>(0)),
FY(static_cast<Real>(0))
{
}
Real F, FX, FY;
};
TriangleMesh const* mMesh;
Real const* mF;
Real const* mFX;
Real const* mFY;
std::vector<Real> mFXStorage;
std::vector<Real> mFYStorage;
std::vector<TriangleData> mTData;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistPointLine.h | .h | 1,996 | 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/DCPQuery.h>
#include <Mathematics/Line.h>
// Compute the distance between a point and a line in nD.
//
// The line is P + t * D, where D is not required to be unit length.
//
// The input point is stored in closest[0]. The closest point on the line is
// stored in closest[1].
namespace gte
{
template <int32_t N, typename T>
class DCPQuery<T, Vector<N, T>, Line<N, T>>
{
public:
struct Result
{
Result()
:
distance(static_cast<T>(0)),
sqrDistance(static_cast<T>(0)),
parameter(static_cast<T>(0)),
closest{ Vector<N, T>::Zero(), Vector<N, T>::Zero() }
{
}
T distance, sqrDistance;
T parameter;
std::array<Vector<N, T>, 2> closest;
};
Result operator()(Vector<N, T> const& point, Line<N, T> const& line)
{
Result result{};
Vector<N, T> diff = point - line.origin;
result.parameter = Dot(line.direction, diff);
result.closest[0] = point;
result.closest[1] = line.origin + result.parameter * line.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 DCPPointLine = DCPQuery<T, Vector<N, T>, Line<N, T>>;
template <typename T>
using DCPPoint2Line2 = DCPPointLine<2, T>;
template <typename T>
using DCPPoint3Line3 = DCPPointLine<3, T>;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ApprEllipse2.h | .h | 12,356 | 314 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
// An ellipse is defined implicitly by (X-C)^T * M * (X-C) = 1, where C is
// the center, M is a positive definite matrix and X is any point on the
// ellipsoid. The code implements a nonlinear least-squares fitting algorithm
// for the error function
// F(C,M) = sum_{i=0}^{n-1} ((X[i] - C)^T * M * (X[i] - C) - 1)^2
// for n data points X[0] through X[n-1]. An Ellipse2<Real> object has
// member 'center' that corresponds to C. It also has axes with unit-length
// directions 'axis[]' and corresponding axis half-lengths 'extent[]'. The
// matrix is M = sum_{i=0}^1 axis[i] * axis[i]^T / extent[i]^2, where axis[i]
// is a 2x1 vector and axis[i]^T is a 1x2 vector.
//
// The minimizer uses a 2-step gradient descent algorithm.
//
// Given the current (C,M), locate a minimum of
// G(t) = F(C - t * dF(C,M)/dC, M)
// for t > 0. The function G(t) >= 0 is a polynomial of degree 4 with
// derivative G'(t) that is a polynomial of degree 3. G'(t) must have a
// positive root because G(0) > 0 and G'(0) < 0 and the G-coefficient of t^4
// is positive. The positive root that T produces the smallest G-value is used
// to update the center C' = C - T * dF/dC(C,M).
//
// Given the current (C,M), locate a minimum of
// H(t) = F(C, M - t * dF(C,M)/dM)
// for t > 0. The function H(t) >= 0 is a polynomial of degree 2 with
// derivative H'(t) that is a polynomial of degree 1. H'(t) must have a
// positive root because H(0) > 0 and H'(0) < 0 and the H-coefficient of t^2
// is positive. The positive root T that produces the smallest G-value is used
// to update the matrix M' = M - T * dF/dC(C,M) as long as M' is positive
// definite. If M' is not positive definite, the root is halved for a finite
// number of steps until M' is positive definite.
#include <Mathematics/ContOrientedBox2.h>
#include <Mathematics/Hyperellipsoid.h>
#include <Mathematics/Matrix2x2.h>
#include <Mathematics/RootsPolynomial.h>
namespace gte
{
template <typename Real>
class ApprEllipse2
{
public:
// If you want this function to compute the initial guess for the
// ellipsoid, set 'useEllipseForInitialGuess' to true. An oriented
// bounding box containing the points is used to start the minimizer.
// Set 'useEllipseForInitialGuess' to true if you want the initial
// guess to be the input ellipse. This is useful if you want to
// repeat the query. The returned 'Real' value is the error function
// value for the output 'ellipse'.
Real operator()(std::vector<Vector2<Real>> const& points,
size_t numIterations, bool useEllipseForInitialGuess,
Ellipse2<Real>& ellipse)
{
Vector2<Real> C;
Matrix2x2<Real> M; // the zero matrix
if (useEllipseForInitialGuess)
{
C = ellipse.center;
for (int32_t i = 0; i < 2; ++i)
{
auto product = OuterProduct(ellipse.axis[i], ellipse.axis[i]);
M += product / (ellipse.extent[i] * ellipse.extent[i]);
}
}
else
{
OrientedBox2<Real> box;
GetContainer(static_cast<int32_t>(points.size()), points.data(), box);
C = box.center;
for (int32_t i = 0; i < 2; ++i)
{
auto product = OuterProduct(box.axis[i], box.axis[i]);
M += product / (box.extent[i] * box.extent[i]);
}
}
Real error = ErrorFunction(points, C, M);
for (size_t i = 0; i < numIterations; ++i)
{
error = UpdateMatrix(points, C, M);
error = UpdateCenter(points, M, C);
}
// Extract the ellipse axes and extents.
SymmetricEigensolver2x2<Real> solver;
std::array<Real, 2> eval;
std::array<std::array<Real, 2>, 2> evec;
solver(M(0, 0), M(0, 1), M(1, 1), +1, eval, evec);
Real const one = static_cast<Real>(1);
ellipse.center = C;
for (int32_t i = 0; i < 2; ++i)
{
ellipse.axis[i] = { evec[i][0], evec[i][1] };
ellipse.extent[i] = one / std::sqrt(eval[i]);
}
return error;
}
private:
Real UpdateCenter(std::vector<Vector2<Real>> const& points,
Matrix2x2<Real> const& M, Vector2<Real>& C)
{
Real const zero = static_cast<Real>(0);
Real const one = static_cast<Real>(1);
Real const two = static_cast<Real>(2);
Real const three = static_cast<Real>(3);
Real const four = static_cast<Real>(4);
Real const epsilon = static_cast<Real>(1e-06);
std::vector<Vector2<Real>> MDelta(points.size());
std::vector<Real> a(points.size());
Real invQuantity = one / static_cast<Real>(points.size());
Vector2<Real> negDFDC = Vector2<Real>::Zero();
Real aMean = zero, aaMean = zero;
for (size_t i = 0; i < points.size(); ++i)
{
Vector2<Real> Delta = points[i] - C;
MDelta[i] = M * Delta;
a[i] = Dot(Delta, MDelta[i]) - one;
aMean += a[i];
aaMean += a[i] * a[i];
negDFDC += a[i] * MDelta[i];
}
aMean *= invQuantity;
aaMean *= invQuantity;
if (Normalize(negDFDC) < epsilon)
{
return aaMean;
}
Real bMean = zero, abMean = zero, bbMean = zero;
Real c = Dot(negDFDC, M * negDFDC);
for (size_t i = 0; i < points.size(); ++i)
{
Real b = Dot(negDFDC, MDelta[i]);
bMean += b;
abMean += a[i] * b;
bbMean += b * b;
}
bMean *= invQuantity;
abMean *= invQuantity;
bbMean *= invQuantity;
// Compute the coefficients of the quartic polynomial q(t) that
// represents the error function on the given line in the gradient
// descent minimization.
std::array<Real, 5> q;
q[0] = aaMean;
q[1] = -four * abMean;
q[2] = four * bbMean + two * c * aMean;
q[3] = -four * c * bMean;
q[4] = c * c;
// Compute the coefficients of q'(t).
std::array<Real, 4> dq;
dq[0] = q[1];
dq[1] = two * q[2];
dq[2] = three * q[3];
dq[3] = four * q[4];
// Compute the roots of q'(t).
std::map<Real, int32_t> rmMap;
RootsPolynomial<Real>::SolveCubic(dq[0], dq[1], dq[2], dq[3], rmMap);
// Choose the root that leads to the minimum along the gradient descent
// line and update the center to that point.
Real minError = aaMean;
Real minRoot = zero;
for (auto const& rm : rmMap)
{
Real root = rm.first;
if (root > zero)
{
Real error = q[0] + root * (q[1] + root * (q[2] + root * (q[3] + root * q[4])));
if (error < minError)
{
minError = error;
minRoot = root;
}
}
}
if (minRoot > zero)
{
C += minRoot * negDFDC;
return minError;
}
return aaMean;
}
Real UpdateMatrix(std::vector<Vector2<Real>> const& points,
Vector2<Real> const& C, Matrix2x2<Real>& M)
{
Real const zero = static_cast<Real>(0);
Real const one = static_cast<Real>(1);
Real const two = static_cast<Real>(2);
Real const half = static_cast<Real>(0.5);
Real const epsilon = static_cast<Real>(1e-06);
std::vector<Vector2<Real>> Delta(points.size());
std::vector<Real> a(points.size());
Real invQuantity = one / static_cast<Real>(points.size());
Matrix2x2<Real> negDFDM; // zero matrix, symmetric
Real aaMean = zero;
for (size_t i = 0; i < points.size(); ++i)
{
Delta[i] = points[i] - C;
a[i] = Dot(Delta[i], M * Delta[i]) - one;
Real twoA = two * a[i];
negDFDM(0, 0) -= a[i] * Delta[i][0] * Delta[i][0];
negDFDM(0, 1) -= twoA * Delta[i][0] * Delta[i][1];
negDFDM(1, 1) -= a[i] * Delta[i][1] * Delta[i][1];
aaMean += a[i] * a[i];
}
aaMean *= invQuantity;
// Normalize the matrix as if it were a vector of numbers.
Real length = std::sqrt(
negDFDM(0, 0) * negDFDM(0, 0) + negDFDM(0, 1) * negDFDM(0, 1) +
negDFDM(1, 1) * negDFDM(1, 1));
if (length < epsilon)
{
return aaMean;
}
Real invLength = one / length;
negDFDM(0, 0) *= invLength;
negDFDM(0, 1) *= invLength;
negDFDM(1, 1) *= invLength;
// Fill in the lower triangular portion because negGradM is a
// symmetric matrix.
negDFDM(1, 0) = negDFDM(0, 1);
Real abMean = zero, bbMean = zero;
for (size_t i = 0; i < points.size(); ++i)
{
Real b = Dot(Delta[i], negDFDM * Delta[i]);
abMean += a[i] * b;
bbMean += b * b;
}
abMean *= invQuantity;
bbMean *= invQuantity;
// Compute the coefficients of the quadratic polynomial q(t) that
// represents the error function on the given line in the gradient
// descent minimization.
std::array<Real, 3> q;
q[0] = aaMean;
q[1] = two * abMean;
q[2] = bbMean;
// Compute the coefficients of q'(t).
std::array<Real, 2> dq;
dq[0] = q[1];
dq[1] = two * q[2];
// Compute the root as long as it is positive and
// M + root * negGradM is a positive definite matrix.
Real root = -dq[0] / dq[1];
if (root > zero)
{
// Use Sylvester's criterion for testing positive definitess.
// A for(;;) loop terminates for floating-point arithmetic but
// not for rational (BSRational<UInteger>) arithmetic. Limit
// the number of iterations so that the loop terminates for
// rational arithmetic but 'return' occurs for floating-point
// arithmetic.
for (size_t k = 0; k < 2048; ++k)
{
Matrix2x2<Real> nextM = M + root * negDFDM;
if (nextM(0, 0) > zero)
{
Real det = Determinant(nextM);
if (det > zero)
{
M = nextM;
Real minError = q[0] + root * (q[1] + root * q[2]);
return minError;
}
}
root *= half;
}
}
return aaMean;
}
Real ErrorFunction(std::vector<Vector2<Real>> const& points,
Vector2<Real> const& C, Matrix2x2<Real> const& M) const
{
Real error = static_cast<Real>(0);
for (auto const& P : points)
{
Vector2<Real> Delta = P - C;
Real a = Dot(Delta, M * Delta) - static_cast<Real>(1);
error += a * a;
}
error /= static_cast<Real>(points.size());
return error;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistLine3OrientedBox3.h | .h | 2,618 | 74 | // 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/DistLine3CanonicalBox3.h>
#include <Mathematics/OrientedBox.h>
// Compute the distance between a line and a solid oriented box in 3D.
//
// The line is P + t * D, where D is not required to be unit length.
//
// The oriented box has center C, unit-length axis directions U[i] and extents
// e[i] for all i. A box point is X = C + sum_i y[i] * U[i], where
// |y[i]| <= e[i] for all i.
//
// The closest point on the line is stored in closest[0] with parameter t. The
// closest point on the box is stored in closest[1]. When there are infinitely
// many choices for the pair of closest points, only one of them is returned.
namespace gte
{
template <typename T>
class DCPQuery<T, Line3<T>, OrientedBox3<T>>
{
public:
using LBQuery = DCPQuery<T, Line3<T>, CanonicalBox3<T>>;
using Result = typename LBQuery::Result;
Result operator()(Line3<T> const& line, OrientedBox3<T> const& box)
{
Result result{};
// Rotate and translate the line and box so that the box is
// aligned and has center at the origin.
CanonicalBox3<T> cbox(box.extent);
Vector3<T> delta = line.origin - box.center;
Vector3<T> xfrmOrigin{}, xfrmDirection{};
for (int32_t i = 0; i < 3; ++i)
{
xfrmOrigin[i] = Dot(box.axis[i], delta);
xfrmDirection[i] = Dot(box.axis[i], line.direction);
}
// The query computes 'result' relative to the box with center
// at the origin.
Line3<T> xfrmLine(xfrmOrigin, xfrmDirection);
LBQuery lbQuery{};
result = lbQuery(xfrmLine, cbox);
// Compute the closest point on the line.
result.closest[0] = line.origin + result.parameter * line.direction;
// Rotate and translate the closest points to the original
// coordinates.
std::array<Vector3<T>, 2> closest{ box.center, box.center };
for (size_t i = 0; i < 2; ++i)
{
for (int32_t j = 0; j < 3; ++j)
{
closest[i] += result.closest[i][j] * box.axis[j];
}
}
result.closest = closest;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ApprGaussian3.h | .h | 5,203 | 140 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/ApprQuery.h>
#include <Mathematics/OrientedBox.h>
#include <Mathematics/SymmetricEigensolver3x3.h>
#include <Mathematics/Vector3.h>
// Fit points with a Gaussian distribution. The center is the mean of the
// points, the axes are the eigenvectors of the covariance matrix and the
// extents are the eigenvalues of the covariance matrix and are returned in
// increasing order. An oriented box is used to store the mean, axes and
// extents.
namespace gte
{
template <typename Real>
class ApprGaussian3 : public ApprQuery<Real, Vector3<Real>>
{
public:
// Initialize the model parameters to zero.
ApprGaussian3()
{
mParameters.center = Vector3<Real>::Zero();
mParameters.axis[0] = Vector3<Real>::Zero();
mParameters.axis[1] = Vector3<Real>::Zero();
mParameters.axis[2] = Vector3<Real>::Zero();
mParameters.extent = 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++];
}
Real invSize = (Real)1 / (Real)numIndices;
mean *= invSize;
if (std::isfinite(mean[0]) && std::isfinite(mean[1]))
{
// Compute the covariance matrix of the points.
Real covar00 = (Real)0, covar01 = (Real)0, covar02 = (Real)0;
Real covar11 = (Real)0, covar12 = (Real)0, covar22 = (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];
covar22 += diff[2] * diff[2];
}
covar00 *= invSize;
covar01 *= invSize;
covar02 *= invSize;
covar11 *= invSize;
covar12 *= invSize;
covar22 *= invSize;
// 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);
mParameters.center = mean;
mParameters.axis[0] = evec[0];
mParameters.axis[1] = evec[1];
mParameters.axis[2] = evec[2];
mParameters.extent = eval;
return true;
}
}
mParameters.center = Vector3<Real>::Zero();
mParameters.axis[0] = Vector3<Real>::Zero();
mParameters.axis[1] = Vector3<Real>::Zero();
mParameters.axis[2] = Vector3<Real>::Zero();
mParameters.extent = Vector3<Real>::Zero();
return false;
}
// Get the parameters for the best fit.
OrientedBox3<Real> const& GetParameters() const
{
return mParameters;
}
virtual size_t GetMinimumRequired() const override
{
return 2;
}
virtual Real Error(Vector3<Real> const& point) const override
{
Vector3<Real> diff = point - mParameters.center;
Real error = (Real)0;
for (int32_t i = 0; i < 3; ++i)
{
if (mParameters.extent[i] > (Real)0)
{
Real ratio = Dot(diff, mParameters.axis[i]) / mParameters.extent[i];
error += ratio * ratio;
}
}
return error;
}
virtual void CopyParameters(ApprQuery<Real, Vector3<Real>> const* input) override
{
auto source = dynamic_cast<ApprGaussian3 const*>(input);
if (source)
{
*this = *source;
}
}
private:
OrientedBox3<Real> mParameters;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistLine2AlignedBox2.h | .h | 10,250 | 249 | // 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/AlignedBox.h>
#include <Mathematics/OrientedBox.h>
#include <Mathematics/Vector2.h>
// Compute the distance between a line and a solid aligned box in 2D.
//
// The line is P + t * D, 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 line is stored in closest[0] with parameter t. The
// closest point on the box is stored in closest[1]. When there are infinitely
// many choices for the pair of closest points, only one of them is returned.
namespace gte
{
template <typename T>
class DCPQuery<T, Line2<T>, AlignedBox2<T>>
{
public:
struct Result
{
Result()
:
distance(static_cast<T>(0)),
sqrDistance(static_cast<T>(0)),
parameter(static_cast<T>(0)),
closest{ {
{ static_cast<T>(0), static_cast<T>(0) },
{ static_cast<T>(0), static_cast<T>(0) }
} }
{
}
T distance, sqrDistance;
T parameter;
std::array<Vector2<T>, 2> closest;
};
Result operator()(Line2<T> const& line, AlignedBox2<T> const& box)
{
Result result{};
// Translate the line and box so that the box has center at the
// origin.
Vector2<T> boxCenter{}, boxExtent{};
box.GetCenteredForm(boxCenter, boxExtent);
Vector2<T> origin = line.origin - boxCenter;
Vector2<T> direction = line.direction;
// The query computes 'result' relative to the box with center
// at the origin.
DoQuery(origin, direction, boxExtent, result);
// Translate the closest points to the original coordinates.
for (size_t i = 0; i < 2; ++i)
{
result.closest[i] += boxCenter;
}
// Compute the distance and squared distance.
Vector2<T> diff = result.closest[0] - result.closest[1];
result.sqrDistance = Dot(diff, diff);
result.distance = std::sqrt(result.sqrDistance);
return result;
}
protected:
// Allow the line-oriented_box query to access DoQuery without having
// to use class derivation.
friend class DCPQuery<T, Line2<T>, OrientedBox2<T>>;
// Compute the distance and closest point between a line and an
// aligned box whose center is the origin. The origin and direction
// are not const to allow for reflections that eliminate complicated
// sign logic in the queries themselves.
static void DoQuery(Vector2<T>& origin, Vector2<T>& direction,
Vector2<T> const& extent, Result& result)
{
// Apply reflections so that the direction has nonnegative
// components.
T const zero = static_cast<T>(0);
std::array<bool, 2> reflect{ false, false };
for (int32_t i = 0; i < 2; ++i)
{
if (direction[i] < zero)
{
origin[i] = -origin[i];
direction[i] = -direction[i];
reflect[i] = true;
}
}
// Compute the line-box distance and closest points. The DoQueryND
// calls compute result.parameter and result.closest[1]. The
// result.closest[0] can be computed after these calls.
if (direction[0] > zero)
{
if (direction[1] > zero)
{
// The direction signs are (+,+). If the line does not
// intersect the box, the only possible closest box points
// are K[0] = (-e0,e1) or K[1] = (e0,-e1). If the line
// intersects the box, the closest points are the same and
// chosen to be the intersection with box edge x0 = e0 or
// x1 = e1. For the remaining discussion, define K[2] =
// (e0,e1).
//
// Test where the candidate corners are relative to the
// line. If D = (d0,d1), then Perp(D) = (d1,-d0). The
// corner K[i] = P + t[i] * D + s[i] * Perp(D), where
// s[i] = Dot(K[i]-P,Perp(D))/|D|^2. K[0] is closest when
// s[0] >= 0 or K[1] is closest when s[1] <= 0. Otherwise,
// the line intersects the box. If s[2] >= 0, the common
// closest point is chosen to be (p0+(e1-p1)*d0/d1,e1). If
// s[2] < 0, the common closest point is chosen to be
// (e0,p1+(e0-p0)*d1/d0).
//
// It is sufficient to test the signs of Dot(K[i],Perp(D))
// and defer the division by |D|^2 until needed for
// computing the closest point.
DoQuery2D(origin, direction, extent, result);
}
else
{
// The direction signs are (+,0). The parameter is the
// value of t for which P + t * D = (e0, p1).
DoQuery1D(0, 1, origin, direction, extent, result);
}
}
else
{
if (direction[1] > zero)
{
// The direction signs are (0,+). The parameter is the
// value of t for which P + t * D = (p0, e1).
DoQuery1D(1, 0, origin, direction, extent, result);
}
else
{
// The direction signs are (0,0). The line is degenerate
// to a point (its origin). Clamp the origin to the box
// to obtain the closest point.
DoQuery0D(origin, extent, result);
}
}
result.closest[0] = origin + result.parameter * direction;
// Undo the reflections. The origin and direction are not consumed
// by the caller, so these do not need to be reflected. However,
// the closest points are consumed.
for (int32_t i = 0; i < 2; ++i)
{
if (reflect[i])
{
for (size_t j = 0; j < 2; ++j)
{
result.closest[j][i] = -result.closest[j][i];
}
}
}
}
private:
// Allow the line-oriented_box query to access DoQuery without having
// to use class derivation.
friend class DCPQuery<T, Line2<T>, OrientedBox2<T>>;
static void DoQuery2D(Vector2<T> const& origin, Vector2<T> const& direction,
Vector2<T> const& extent, Result& result)
{
T const zero = static_cast<T>(0);
Vector2<T> K0{ -extent[0], extent[1] };
Vector2<T> delta = K0 - origin;
T K0dotPerpD = DotPerp(delta, direction);
if (K0dotPerpD >= zero)
{
result.parameter = Dot(delta, direction) / Dot(direction, direction);
result.closest[0] = origin + result.parameter * direction;
result.closest[1] = K0;
}
else
{
Vector2<T> K1{ extent[0], -extent[1] };
delta = K1 - origin;
T K1dotPerpD = DotPerp(delta, direction);
if (K1dotPerpD <= zero)
{
result.parameter = Dot(delta, direction) / Dot(direction, direction);
result.closest[0] = origin + result.parameter * direction;
result.closest[1] = K1;
}
else
{
Vector2<T> K2{ extent[0], extent[1] };
delta = K2 - origin;
T K2dotPerpD = DotPerp(delta, direction);
if (K2dotPerpD >= zero)
{
result.parameter = (extent[1] - origin[1]) / direction[1];
result.closest[0] = origin + result.parameter * direction;
result.closest[1][0] = origin[0] + result.parameter * direction[0];
result.closest[1][1] = extent[1];
}
else
{
result.parameter = (extent[0] - origin[0]) / direction[0];
result.closest[0] = origin + result.parameter * direction;
result.closest[1][0] = extent[0];
result.closest[1][1] = origin[1] + result.parameter * direction[1];
}
}
}
}
static void DoQuery1D(int32_t i0, int32_t i1, Vector2<T> const& origin,
Vector2<T> const& direction, Vector2<T> const& extent, Result& result)
{
result.parameter = (extent[i0] - origin[i0]) / direction[i0];
result.closest[0] = origin + result.parameter * direction;
result.closest[1][i0] = extent[i0];
result.closest[1][i1] = clamp(origin[i1], -extent[i1], extent[i1]);
}
static void DoQuery0D(Vector2<T> const& origin, Vector2<T> const& extent,
Result& result)
{
result.parameter = static_cast<T>(0);
result.closest[0] = origin;
result.closest[1][0] = clamp(origin[0], -extent[0], extent[0]);
result.closest[1][1] = clamp(origin[1], -extent[1], extent[1]);
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/DistPoint3Tetrahedron3.h | .h | 4,409 | 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.02.06
#pragma once
#include <Mathematics/DistPointTriangle.h>
#include <Mathematics/Tetrahedron3.h>
// Compute the distance between a point and a solid tetrahedron in 3D.
//
// The tetrahedron is represented as an array of four vertices, V[i] for
// 0 <= i <= 3. The vertices are ordered so that the triangular faces are
// counterclockwise-ordered triangles when viewed by an observer outside the
// tetrahedron: face 0 = <V[0],V[2],V[1]>, face 1 = <V[0],V[1],V[3]>,
// face 2 = <V[0],V[3],V[2]> and face 3 = <V[1],V[2],V[3]>. The canonical
// tetrahedron has V[0] = (0,0,0), V[1] = (1,0,0), V[2] = (0,1,0) and
// V[3] = (0,0,1). A tetrahedron point is // X = sum_{i=0}^3 b[i] * V[i],
// where 0 <= b[i] <= 1 for all i and sum_{i=0}^3 b[i] = 1.
//
// The input P is stored in closest[0]. The closest point on the tetrahedron
// is stored in closest[1] with barycentric coordinates (b[0],b[1],b[2],b[3]).
namespace gte
{
template <typename T>
class DCPQuery<T, Vector3<T>, Tetrahedron3<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), static_cast<T>(0) },
closest{ Vector3<T>::Zero(), Vector3<T>::Zero() }
{
}
T distance, sqrDistance;
std::array<T, 4> barycentric;
std::array<Vector3<T>, 2> closest;
};
Result operator()(Vector3<T> const& point, Tetrahedron3<T> const& tetrahedron)
{
Result result{};
// Construct the planes for the faces of the tetrahedron. The
// normals are outer pointing, but specified not to be unit
// length. We only need to know sidedness of the query point, so
// we will save cycles by not computing unit-length normals.
std::array<Plane3<T>, 4> planes{};
tetrahedron.GetPlanes(planes);
// Determine which faces are visible to the query point. Only
// these need to be processed by point-to-triangle distance
// queries. To allow for arbitrary precision arithmetic, the
// initial sqrDistance is initialized to zero rather than a
// floating-point maximum value. Tracking the minimum requires a
// small amount of extra logic.
T const invalid = static_cast<T>(-1);
result.sqrDistance = invalid;
for (size_t i = 0; i < 4; ++i)
{
if (Dot(planes[i].normal, point) >= planes[i].constant)
{
auto const& indices = tetrahedron.GetFaceIndices(i);
Triangle3<T> triangle(
tetrahedron.v[indices[0]],
tetrahedron.v[indices[1]],
tetrahedron.v[indices[2]]);
DCPQuery<T, Vector3<T>, Triangle3<T>> ptQuery{};
auto ptResult = ptQuery(point, triangle);
if (result.sqrDistance == invalid ||
ptResult.sqrDistance < result.sqrDistance)
{
result.sqrDistance = ptResult.sqrDistance;
result.closest = ptResult.closest;
}
}
}
T const zero = static_cast<T>(0);
if (result.sqrDistance == invalid)
{
// The query point is inside the solid tetrahedron. Report a
// zero distance. The closest points are identical.
result.sqrDistance = zero;
result.closest[0] = point;
result.closest[1] = point;
}
result.distance = std::sqrt(result.sqrDistance);
std::array<T, 4> barycentric{};
(void)ComputeBarycentrics(result.closest[1], tetrahedron.v[0],
tetrahedron.v[1], tetrahedron.v[2], tetrahedron.v[3],
barycentric);
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ApprQuery.h | .h | 9,361 | 216 | // 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 <numeric>
#include <random>
#include <vector>
// Base class support for least-squares fitting algorithms and for RANSAC
// algorithms.
// Expose this define if you want the code to verify that the incoming
// indices to the fitting functions are valid.
#define GTE_APPR_QUERY_VALIDATE_INDICES
namespace gte
{
template <typename Real, typename ObservationType>
class ApprQuery
{
public:
// Construction and destruction.
ApprQuery() = default;
virtual ~ApprQuery() = default;
// The base-class Fit* functions are generic but need to call the
// indexed fitting function for the specific derived class.
virtual bool FitIndexed(
size_t numObservations, ObservationType const* observations,
size_t numIndices, int32_t const* indices) = 0;
bool ValidIndices(
size_t numObservations, ObservationType const* observations,
size_t numIndices, int32_t const* indices)
{
#if defined(GTE_APPR_QUERY_VALIDATE_INDICES)
if (observations && indices &&
GetMinimumRequired() <= numIndices && numIndices <= numObservations)
{
int32_t const* currentIndex = indices;
for (size_t i = 0; i < numIndices; ++i)
{
if (*currentIndex++ >= static_cast<int32_t>(numObservations))
{
return false;
}
}
return true;
}
return false;
#else
// The caller is responsible for passing correctly formed data.
(void)numObservations;
(void)observations;
(void)numIndices;
(void)indices;
return true;
#endif
}
// Estimate the model parameters for all observations passed in via
// raw pointers.
bool Fit(size_t numObservations, ObservationType const* observations)
{
std::vector<int32_t> indices(numObservations);
std::iota(indices.begin(), indices.end(), 0);
return FitIndexed(numObservations, observations, indices.size(), indices.data());
}
// Estimate the model parameters for all observations passed in via
// std::vector.
bool Fit(std::vector<ObservationType> const& observations)
{
std::vector<int32_t> indices(observations.size());
std::iota(indices.begin(), indices.end(), 0);
return FitIndexed(observations.size(), observations.data(), indices.size(), indices.data());
}
// Estimate the model parameters for a contiguous subset of
// observations.
bool Fit(std::vector<ObservationType> const& observations, size_t imin, size_t imax)
{
if (imin <= imax)
{
size_t numIndices = static_cast<size_t>(imax - imin + 1);
std::vector<int32_t> indices(numIndices);
std::iota(indices.begin(), indices.end(), static_cast<int32_t>(imin));
return FitIndexed(observations.size(), observations.data(), indices.size(), indices.data());
}
else
{
return false;
}
}
// Estimate the model parameters for an indexed subset of observations.
virtual bool Fit(std::vector<ObservationType> const& observations,
std::vector<int32_t> const& indices)
{
return FitIndexed(observations.size(), observations.data(), indices.size(), indices.data());
}
// Estimate the model parameters for the subset of observations
// specified by the indices and the number of indices that is possibly
// smaller than indices.size().
bool Fit(std::vector<ObservationType> const& observations,
std::vector<int32_t> const& indices, size_t numIndices)
{
size_t imax = std::min(numIndices, indices.size());
std::vector<int32_t> localindices(imax);
std::copy(indices.begin(), indices.begin() + imax, localindices.begin());
return FitIndexed(observations.size(), observations.data(), localindices.size(), localindices.data());
}
// Apply the RANdom SAmple Consensus algorithm for fitting a model to
// observations. The algorithm requires three virtual functions to be
// implemented by the derived classes.
// The minimum number of observations required to fit the model.
virtual size_t GetMinimumRequired() const = 0;
// Compute the model error for the specified observation for the
// current model parameters.
virtual Real Error(ObservationType const& observation) const = 0;
// Copy the parameters between two models. This is used to copy the
// candidate-model parameters to the current best-fit model.
virtual void CopyParameters(ApprQuery const* input) = 0;
static bool RANSAC(ApprQuery& candidateModel, std::vector<ObservationType> const& observations,
size_t numRequiredForGoodFit, Real maxErrorForGoodFit, size_t numIterations,
std::vector<int32_t>& bestConsensus, ApprQuery& bestModel)
{
size_t const numObservations = observations.size();
size_t const minRequired = candidateModel.GetMinimumRequired();
if (numObservations < minRequired)
{
// Too few observations for model fitting.
return false;
}
// The first part of the array will store the consensus set,
// initially filled with the minimum number of indices that
// correspond to the candidate inliers. The last part will store
// the remaining indices. These points are tested against the
// model and are added to the consensus set when they fit. All
// the index manipulation is done in place. Initially, the
// candidates are the identity permutation.
std::vector<int32_t> candidates(numObservations);
std::iota(candidates.begin(), candidates.end(), 0);
if (numObservations == minRequired)
{
// We have the minimum number of observations to generate the
// model, so RANSAC cannot be used. Compute the model with the
// entire set of observations.
bestConsensus = candidates;
return bestModel.Fit(observations);
}
size_t bestNumFittedObservations = minRequired;
for (size_t i = 0; i < numIterations; ++i)
{
// Randomly permute the previous candidates, partitioning the
// array into GetMinimumRequired() indices (the candidate
// inliers) followed by the remaining indices (candidates for
// testing against the model).
std::shuffle(candidates.begin(), candidates.end(), std::default_random_engine());
// Fit the model to the inliers.
if (candidateModel.Fit(observations, candidates, minRequired))
{
// Test each remaining observation whether it fits the
// model. If it does, include it in the consensus set.
size_t numFittedObservations = minRequired;
for (size_t j = minRequired; j < numObservations; ++j)
{
Real error = candidateModel.Error(observations[candidates[j]]);
if (error <= maxErrorForGoodFit)
{
std::swap(candidates[j], candidates[numFittedObservations]);
++numFittedObservations;
}
}
if (numFittedObservations >= numRequiredForGoodFit)
{
// We have observations that fit the model. Update the
// best model using the consensus set.
candidateModel.Fit(observations, candidates, numFittedObservations);
if (numFittedObservations > bestNumFittedObservations)
{
// The consensus set is larger than the previous
// consensus set, so its model becomes the best one.
bestModel.CopyParameters(&candidateModel);
bestConsensus.resize(numFittedObservations);
std::copy(candidates.begin(), candidates.begin() + numFittedObservations, bestConsensus.begin());
bestNumFittedObservations = numFittedObservations;
}
}
}
}
return bestNumFittedObservations >= numRequiredForGoodFit;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/SplitMeshByPlane.h | .h | 15,825 | 400 | // 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/DistPointHyperplane.h>
#include <Mathematics/EdgeKey.h>
#include <map>
// The algorithm for splitting a mesh by a plane is described in
// https://www.geometrictools.com/Documentation/ClipMesh.pdf
// Currently, the code here does not include generating a closed
// mesh (from the "positive" and "zero" vertices) by attaching
// triangulated faces to the mesh, where the those faces live in
// the splitting plane. (TODO: Add this code.)
namespace gte
{
template <typename Real>
class SplitMeshByPlane
{
public:
// The 'indices' are lookups into the 'vertices' array. The indices
// represent a triangle mesh. The number of indices must be a
// multiple of 3, each triple representing a triangle. If t is a
// triangle index, then the triangle is formed by
// vertices[indices[3 * t + i]] for 0 <= i <= 2. The outputs
// 'negIndices' and 'posIndices' are formatted similarly.
void operator()(
std::vector<Vector3<Real>> const& vertices,
std::vector<int32_t> const& indices,
Plane3<Real> const& plane,
std::vector<Vector3<Real>>& clipVertices,
std::vector<int32_t>& negIndices,
std::vector<int32_t>& posIndices)
{
mSignedDistances.resize(vertices.size());
mEMap.clear();
// Make a copy of the incoming vertices. If the mesh intersects
// the plane, new vertices must be generated. These are appended
// to the clipVertices array.
clipVertices = vertices;
ClassifyVertices(clipVertices, plane);
ClassifyEdges(clipVertices, indices);
ClassifyTriangles(indices, negIndices, posIndices);
}
private:
void ClassifyVertices(std::vector<Vector3<Real>> const& clipVertices,
Plane3<Real> const& plane)
{
DCPQuery<Real, Vector3<Real>, Plane3<Real>> query;
for (size_t i = 0; i < clipVertices.size(); ++i)
{
mSignedDistances[i] = query(clipVertices[i], plane).signedDistance;
}
}
void ClassifyEdges(std::vector<Vector3<Real>>& clipVertices,
std::vector<int32_t> const& indices)
{
size_t const numTriangles = indices.size() / 3;
int32_t nextIndex = static_cast<int32_t>(clipVertices.size());
for (size_t i = 0; i < numTriangles; ++i)
{
size_t threeI = 3 * static_cast<size_t>(i);
int32_t v0 = indices[threeI + 0];
int32_t v1 = indices[threeI + 1];
int32_t v2 = indices[threeI + 2];
Real sDist0 = mSignedDistances[v0];
Real sDist1 = mSignedDistances[v1];
Real sDist2 = mSignedDistances[v2];
EdgeKey<false> key;
Real t;
Vector3<Real> intr, diff;
// The change-in-sign tests are structured this way to avoid
// numerical round-off problems. For example, sDist0 > 0 and
// sDist1 < 0, but both are very small and sDist0 * sDist1 = 0
// because of round-off errors. The tests also guarantee
// consistency between this function and ClassifyTriangles,
// the latter function using sign tests only on the individual
// sDist values.
if ((sDist0 > (Real)0 && sDist1 < (Real)0)
|| (sDist0 < (Real)0 && sDist1 >(Real)0))
{
key = EdgeKey<false>(v0, v1);
if (mEMap.find(key) == mEMap.end())
{
t = sDist0 / (sDist0 - sDist1);
diff = clipVertices[v1] - clipVertices[v0];
intr = clipVertices[v0] + t * diff;
clipVertices.push_back(intr);
mEMap[key] = std::make_pair(intr, nextIndex);
++nextIndex;
}
}
if ((sDist1 > (Real)0 && sDist2 < (Real)0)
|| (sDist1 < (Real)0 && sDist2 >(Real)0))
{
key = EdgeKey<false>(v1, v2);
if (mEMap.find(key) == mEMap.end())
{
t = sDist1 / (sDist1 - sDist2);
diff = clipVertices[v2] - clipVertices[v1];
intr = clipVertices[v1] + t * diff;
clipVertices.push_back(intr);
mEMap[key] = std::make_pair(intr, nextIndex);
++nextIndex;
}
}
if ((sDist2 > (Real)0 && sDist0 < (Real)0)
|| (sDist2 < (Real)0 && sDist0 >(Real)0))
{
key = EdgeKey<false>(v2, v0);
if (mEMap.find(key) == mEMap.end())
{
t = sDist2 / (sDist2 - sDist0);
diff = clipVertices[v0] - clipVertices[v2];
intr = clipVertices[v2] + t * diff;
clipVertices.push_back(intr);
mEMap[key] = std::make_pair(intr, nextIndex);
++nextIndex;
}
}
}
}
void ClassifyTriangles(std::vector<int32_t> const& indices,
std::vector<int32_t>& negIndices, std::vector<int32_t>& posIndices)
{
size_t const numTriangles = static_cast<int32_t>(indices.size() / 3);
for (size_t i = 0; i < numTriangles; ++i)
{
size_t threeI = 3 * static_cast<size_t>(i);
int32_t v0 = indices[threeI + 0];
int32_t v1 = indices[threeI + 1];
int32_t v2 = indices[threeI + 2];
Real sDist0 = mSignedDistances[v0];
Real sDist1 = mSignedDistances[v1];
Real sDist2 = mSignedDistances[v2];
if (sDist0 > (Real)0)
{
if (sDist1 > (Real)0)
{
if (sDist2 > (Real)0)
{
// +++
AppendTriangle(posIndices, v0, v1, v2);
}
else if (sDist2 < (Real)0)
{
// ++-
SplitTrianglePPM(negIndices, posIndices, v0, v1, v2);
}
else
{
// ++0
AppendTriangle(posIndices, v0, v1, v2);
}
}
else if (sDist1 < (Real)0)
{
if (sDist2 > (Real)0)
{
// +-+
SplitTrianglePPM(negIndices, posIndices, v2, v0, v1);
}
else if (sDist2 < (Real)0)
{
// +--
SplitTriangleMMP(negIndices, posIndices, v1, v2, v0);
}
else
{
// +-0
SplitTrianglePMZ(negIndices, posIndices, v0, v1, v2);
}
}
else
{
if (sDist2 > (Real)0)
{
// +0+
AppendTriangle(posIndices, v0, v1, v2);
}
else if (sDist2 < (Real)0)
{
// +0-
SplitTriangleMPZ(negIndices, posIndices, v2, v0, v1);
}
else
{
// +00
AppendTriangle(posIndices, v0, v1, v2);
}
}
}
else if (sDist0 < (Real)0)
{
if (sDist1 > (Real)0)
{
if (sDist2 > (Real)0)
{
// -++
SplitTrianglePPM(negIndices, posIndices, v1, v2, v0);
}
else if (sDist2 < (Real)0)
{
// -+-
SplitTriangleMMP(negIndices, posIndices, v2, v0, v1);
}
else
{
// -+0
SplitTriangleMPZ(negIndices, posIndices, v0, v1, v2);
}
}
else if (sDist1 < (Real)0)
{
if (sDist2 > (Real)0)
{
// --+
SplitTriangleMMP(negIndices, posIndices, v0, v1, v2);
}
else if (sDist2 < (Real)0)
{
// ---
AppendTriangle(negIndices, v0, v1, v2);
}
else
{
// --0
AppendTriangle(negIndices, v0, v1, v2);
}
}
else
{
if (sDist2 > (Real)0)
{
// -0+
SplitTrianglePMZ(negIndices, posIndices, v2, v0, v1);
}
else if (sDist2 < (Real)0)
{
// -0-
AppendTriangle(negIndices, v0, v1, v2);
}
else
{
// -00
AppendTriangle(negIndices, v0, v1, v2);
}
}
}
else
{
if (sDist1 > (Real)0)
{
if (sDist2 > (Real)0)
{
// 0++
AppendTriangle(posIndices, v0, v1, v2);
}
else if (sDist2 < (Real)0)
{
// 0+-
SplitTrianglePMZ(negIndices, posIndices, v1, v2, v0);
}
else
{
// 0+0
AppendTriangle(posIndices, v0, v1, v2);
}
}
else if (sDist1 < (Real)0)
{
if (sDist2 > (Real)0)
{
// 0-+
SplitTriangleMPZ(negIndices, posIndices, v1, v2, v0);
}
else if (sDist2 < (Real)0)
{
// 0--
AppendTriangle(negIndices, v0, v1, v2);
}
else
{
// 0-0
AppendTriangle(negIndices, v0, v1, v2);
}
}
else
{
if (sDist2 > (Real)0)
{
// 00+
AppendTriangle(posIndices, v0, v1, v2);
}
else if (sDist2 < (Real)0)
{
// 00-
AppendTriangle(negIndices, v0, v1, v2);
}
else
{
// 000, reject triangles lying in the plane
}
}
}
}
}
void AppendTriangle(std::vector<int32_t>& indices, int32_t v0, int32_t v1, int32_t v2)
{
indices.push_back(v0);
indices.push_back(v1);
indices.push_back(v2);
}
void SplitTrianglePPM(std::vector<int32_t>& negIndices,
std::vector<int32_t>& posIndices, int32_t v0, int32_t v1, int32_t v2)
{
int32_t v12 = mEMap[EdgeKey<false>(v1, v2)].second;
int32_t v20 = mEMap[EdgeKey<false>(v2, v0)].second;
posIndices.push_back(v0);
posIndices.push_back(v1);
posIndices.push_back(v12);
posIndices.push_back(v0);
posIndices.push_back(v12);
posIndices.push_back(v20);
negIndices.push_back(v2);
negIndices.push_back(v20);
negIndices.push_back(v12);
}
void SplitTriangleMMP(std::vector<int32_t>& negIndices,
std::vector<int32_t>& posIndices, int32_t v0, int32_t v1, int32_t v2)
{
int32_t v12 = mEMap[EdgeKey<false>(v1, v2)].second;
int32_t v20 = mEMap[EdgeKey<false>(v2, v0)].second;
negIndices.push_back(v0);
negIndices.push_back(v1);
negIndices.push_back(v12);
negIndices.push_back(v0);
negIndices.push_back(v12);
negIndices.push_back(v20);
posIndices.push_back(v2);
posIndices.push_back(v20);
posIndices.push_back(v12);
}
void SplitTrianglePMZ(std::vector<int32_t>& negIndices,
std::vector<int32_t>& posIndices, int32_t v0, int32_t v1, int32_t v2)
{
int32_t v01 = mEMap[EdgeKey<false>(v0, v1)].second;
posIndices.push_back(v2);
posIndices.push_back(v0);
posIndices.push_back(v01);
negIndices.push_back(v2);
negIndices.push_back(v01);
negIndices.push_back(v1);
}
void SplitTriangleMPZ(std::vector<int32_t>& negIndices,
std::vector<int32_t>& posIndices, int32_t v0, int32_t v1, int32_t v2)
{
int32_t v01 = mEMap[EdgeKey<false>(v0, v1)].second;
negIndices.push_back(v2);
negIndices.push_back(v0);
negIndices.push_back(v01);
posIndices.push_back(v2);
posIndices.push_back(v01);
posIndices.push_back(v1);
}
// Stores the signed distances from the vertices to the plane.
std::vector<Real> mSignedDistances;
// Stores the edges whose vertices are on opposite sides of the
// plane. The key is a pair of indices into the vertex array.
// The value is the point of intersection of the edge with the
// plane and an index into m_kVertices (the index is larger or
// equal to the number of vertices of incoming rkVertices).
std::map<EdgeKey<false>, std::pair<Vector3<Real>, int32_t>> mEMap;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/PlanarMesh.h | .h | 16,829 | 451 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.02.01
#pragma once
#include <Mathematics/ContPointInPolygon2.h>
#include <Mathematics/ETManifoldMesh.h>
#include <Mathematics/PrimalQuery2.h>
#include <set>
// The planar mesh class is convenient for many applications involving
// searches for triangles containing a specified point. A couple of
// issues can show up in practice when the input data to the constructors
// is very large (number of triangles on the order of 10^5 or larger).
//
// The first constructor builds an ETManifoldMesh mesh that contains
// std::map objects. When such maps are large, the amount of time it
// takes to delete them is enormous. Although you can control the level
// of debug support in MSVS 2013 (see _ITERATOR_DEBUG_LEVEL), turning off
// checking might very well affect other classes for which you want
// iterator checking to be on. An alternative to reduce debugging time
// is to dynamically allocate the PlanarMesh object in the main thread but
// then launch another thread to delete the object and avoid stalling
// the main thread. For example,
//
// PlanarMesh<IT,CT,RT>* pmesh =
// new PlanarMesh<IT,CT,RT>(numV, vertices, numT, indices);
// <make various calls to pmesh>;
// std::thread deleter = [pmesh](){ delete pmesh; };
// deleter.detach(); // Do not wait for the thread to finish.
//
// The second constructor has the mesh passed in, but mTriIndexMap is used
// in both constructors and can take time to delete.
//
// The input mesh should be consistently oriented, say, the triangles are
// counterclockwise ordered. The vertices should be consistent with this
// ordering. However, floating-point rounding errors in generating the
// vertices can cause apparent fold-over of the mesh; that is, theoretically
// the vertex geometry supports counterclockwise geometry but numerical
// errors cause an inconsistency. This can manifest in the mQuery.ToLine
// tests whereby cycles of triangles occur in the linear walk. When cycles
// occur, GetContainingTriangle(P,startTriangle) will iterate numTriangle
// times before reporting that the triangle cannot be found, which is a
// very slow process (in debug or release builds). The function
// GetContainingTriangle(P,startTriangle,visited) is provided to avoid the
// performance loss, trapping a cycle the first time and exiting, but
// again reporting that the triangle cannot be found. If you know that the
// query should be (theoretically) successful, use the second version of
// GetContainingTriangle. If it fails by returning -1, then perform an
// exhaustive search over the triangles. For example,
//
// int32_t triangle = pmesh->GetContainingTriangle(P,startTriangle,visited);
// if (triangle >= 0)
// {
// <take action; for example, compute barycenteric coordinates>;
// }
// else
// {
// int32_t numTriangles = pmesh->GetNumTriangles();
// for (triangle = 0; triangle < numTriangles; ++triangle)
// {
// if (pmesh->Contains(triangle, P))
// {
// <take action>;
// break;
// }
// }
// if (triangle == numTriangles)
// {
// <Triangle still not found, take appropriate action>;
// }
// }
//
// The PlanarMesh<*>::Contains function does not require the triangles to
// be ordered.
namespace gte
{
template <typename InputType, typename ComputeType, typename RationalType>
class PlanarMesh
{
public:
// Construction. The inputs must represent a manifold mesh of
// triangles in the plane. The index array must have 3*numTriangles
// elements, each triple of indices representing a triangle in the
// mesh. Each index is into the 'vertices' array.
PlanarMesh(int32_t numVertices, Vector2<InputType> const* vertices, int32_t numTriangles, int32_t const* indices)
:
mNumVertices(0),
mVertices(nullptr),
mNumTriangles(0)
{
LogAssert(numVertices >= 3 && vertices != nullptr && numTriangles >= 1
&& indices != nullptr, "Invalid input.");
// Create a mesh in order to get adjacency information.
int32_t const* current = indices;
for (int32_t t = 0; t < numTriangles; ++t)
{
int32_t v0 = *current++;
int32_t v1 = *current++;
int32_t v2 = *current++;
if (!mMesh.Insert(v0, v1, v2))
{
// TODO: Fix this comment once the exception handling is
// tested.
//
// The 'mesh' object will throw on nonmanifold inputs.
return;
}
}
// We have a valid mesh.
CreateVertices(numVertices, vertices);
// Build the adjacency graph using the triangle ordering implied
// by the indices, not the mesh triangle map, to preserve the
// triangle ordering of the input indices.
mNumTriangles = numTriangles;
int32_t const numIndices = 3 * numTriangles;
mIndices.resize(numIndices);
std::copy(indices, indices + numIndices, mIndices.begin());
for (int32_t t = 0, vIndex = 0; t < numTriangles; ++t)
{
int32_t v0 = indices[vIndex++];
int32_t v1 = indices[vIndex++];
int32_t v2 = indices[vIndex++];
TriangleKey<true> key(v0, v1, v2);
mTriIndexMap.insert(std::make_pair(key, t));
}
mAdjacencies.resize(numIndices);
auto const& tmap = mMesh.GetTriangles();
for (int32_t t = 0, base = 0; t < numTriangles; ++t, base += 3)
{
int32_t v0 = indices[base];
int32_t v1 = indices[base + 1];
int32_t v2 = indices[base + 2];
TriangleKey<true> key(v0, v1, v2);
auto element = tmap.find(key);
for (int32_t i = 0; i < 3; ++i)
{
auto adj = element->second->T[i];
if (adj)
{
key = TriangleKey<true>(adj->V[0], adj->V[1], adj->V[2]);
mAdjacencies[static_cast<size_t>(base) + i] = mTriIndexMap.find(key)->second;
}
else
{
mAdjacencies[static_cast<size_t>(base) + i] = -1;
}
}
}
}
PlanarMesh(int32_t numVertices, Vector2<InputType> const* vertices, ETManifoldMesh const& mesh)
:
mNumVertices(0),
mVertices(nullptr),
mNumTriangles(0)
{
if (numVertices < 3 || !vertices || mesh.GetTriangles().size() < 1)
{
LogError("Invalid input in PlanarMesh constructor.");
}
// We have a valid mesh.
CreateVertices(numVertices, vertices);
// Build the adjacency graph using the triangle ordering implied
// by the mesh triangle map.
auto const& tmap = mesh.GetTriangles();
mNumTriangles = static_cast<int32_t>(tmap.size());
mIndices.resize(3 * static_cast<size_t>(mNumTriangles));
int32_t tIndex = 0, vIndex = 0;
for (auto const& element : tmap)
{
mTriIndexMap.insert(std::make_pair(element.first, tIndex++));
for (int32_t i = 0; i < 3; ++i, ++vIndex)
{
mIndices[vIndex] = element.second->V[i];
}
}
mAdjacencies.resize(3 * static_cast<size_t>(mNumTriangles));
vIndex = 0;
for (auto const& element : tmap)
{
for (int32_t i = 0; i < 3; ++i, ++vIndex)
{
auto adj = element.second->T[i];
if (adj)
{
TriangleKey<true> key(adj->V[0], adj->V[1], adj->V[2]);
mAdjacencies[vIndex] = mTriIndexMap.find(key)->second;
}
else
{
mAdjacencies[vIndex] = -1;
}
}
}
}
// Mesh information.
inline int32_t GetNumVertices() const
{
return mNumVertices;
}
inline int32_t GetNumTriangles() const
{
return mNumTriangles;
}
inline Vector2<InputType> const* GetVertices() const
{
return mVertices;
}
inline int32_t const* GetIndices() const
{
return mIndices.data();
}
inline int32_t const* GetAdjacencies() const
{
return mAdjacencies.data();
}
// Containment queries. The function GetContainingTriangle works
// correctly when the planar mesh is a convex set. If the mesh is not
// convex, it is possible that the linear-walk search algorithm exits
// the mesh before finding a containing triangle. For example, a
// C-shaped mesh can contain a point in the top branch of the "C".
// A starting point in the bottom branch of the "C" will lead to the
// search exiting the bottom branch and having no path to walk to the
// top branch. If your mesh is not convex and you want a correct
// containment query, you will have to append "outside" triangles to
// your mesh to form a convex set.
int32_t GetContainingTriangle(Vector2<InputType> const& P, int32_t startTriangle = 0) const
{
Vector2<ComputeType> test{ P[0], P[1] };
// Use triangle edges as binary separating lines.
int32_t triangle = startTriangle;
for (int32_t i = 0; i < mNumTriangles; ++i)
{
int32_t ibase = 3 * triangle;
int32_t const* v = &mIndices[ibase];
if (mQuery.ToLine(test, v[0], v[1]) > 0)
{
triangle = mAdjacencies[ibase];
if (triangle == -1)
{
return -1;
}
continue;
}
if (mQuery.ToLine(test, v[1], v[2]) > 0)
{
triangle = mAdjacencies[static_cast<size_t>(ibase) + 1];
if (triangle == -1)
{
return -1;
}
continue;
}
if (mQuery.ToLine(test, v[2], v[0]) > 0)
{
triangle = mAdjacencies[static_cast<size_t>(ibase) + 2];
if (triangle == -1)
{
return -1;
}
continue;
}
return triangle;
}
return -1;
}
int32_t GetContainingTriangle(Vector2<InputType> const& P, int32_t startTriangle, std::set<int32_t>& visited) const
{
Vector2<ComputeType> test{ P[0], P[1] };
visited.clear();
// Use triangle edges as binary separating lines.
int32_t triangle = startTriangle;
for (int32_t i = 0; i < mNumTriangles; ++i)
{
visited.insert(triangle);
int32_t ibase = 3 * triangle;
int32_t const* v = &mIndices[ibase];
if (mQuery.ToLine(test, v[0], v[1]) > 0)
{
triangle = mAdjacencies[ibase];
if (triangle == -1 || visited.find(triangle) != visited.end())
{
return -1;
}
continue;
}
if (mQuery.ToLine(test, v[1], v[2]) > 0)
{
triangle = mAdjacencies[static_cast<size_t>(ibase) + 1];
if (triangle == -1 || visited.find(triangle) != visited.end())
{
return -1;
}
continue;
}
if (mQuery.ToLine(test, v[2], v[0]) > 0)
{
triangle = mAdjacencies[static_cast<size_t>(ibase) + 2];
if (triangle == -1 || visited.find(triangle) != visited.end())
{
return -1;
}
continue;
}
return triangle;
}
return -1;
}
bool GetVertices(int32_t t, std::array<Vector2<InputType>, 3>& vertices) const
{
if (0 <= t && t < mNumTriangles)
{
for (int32_t i = 0, vIndex = 3 * t; i < 3; ++i, ++vIndex)
{
vertices[i] = mVertices[mIndices[vIndex]];
}
return true;
}
return false;
}
bool GetIndices(int32_t t, std::array<int32_t, 3>& indices) const
{
if (0 <= t && t < mNumTriangles)
{
for (int32_t i = 0, vIndex = 3 * t; i < 3; ++i, ++vIndex)
{
indices[i] = mIndices[vIndex];
}
return true;
}
return false;
}
bool GetAdjacencies(int32_t t, std::array<int32_t, 3>& adjacencies) const
{
if (0 <= t && t < mNumTriangles)
{
for (int32_t i = 0, vIndex = 3 * t; i < 3; ++i, ++vIndex)
{
adjacencies[i] = mAdjacencies[vIndex];
}
return true;
}
return false;
}
bool GetBarycentrics(int32_t t, Vector2<InputType> const& P, std::array<InputType, 3>& bary) const
{
std::array<int32_t, 3> indices;
if (GetIndices(t, indices))
{
Vector2<RationalType> rtP{ P[0], P[1] };
std::array<Vector2<RationalType>, 3> rtV;
for (int32_t i = 0; i < 3; ++i)
{
Vector2<ComputeType> const& V = mComputeVertices[indices[i]];
for (int32_t j = 0; j < 2; ++j)
{
rtV[i][j] = (RationalType)V[j];
}
};
std::array<RationalType, 3> rtBary{};
if (ComputeBarycentrics(rtP, rtV[0], rtV[1], rtV[2], rtBary))
{
for (int32_t i = 0; i < 3; ++i)
{
bary[i] = (InputType)rtBary[i];
}
return true;
}
}
return false;
}
bool Contains(int32_t triangle, Vector2<InputType> const& P) const
{
Vector2<ComputeType> test{ P[0], P[1] };
Vector2<ComputeType> v[3];
size_t base = 3 * static_cast<size_t>(triangle);
v[0] = mComputeVertices[mIndices[base + 0]];
v[1] = mComputeVertices[mIndices[base + 1]];
v[2] = mComputeVertices[mIndices[base + 2]];
PointInPolygon2<ComputeType> pip(3, v);
return pip.Contains(test);
}
public:
void CreateVertices(int32_t numVertices, Vector2<InputType> const* vertices)
{
mNumVertices = numVertices;
mVertices = vertices;
mComputeVertices.resize(mNumVertices);
for (int32_t i = 0; i < mNumVertices; ++i)
{
for (int32_t j = 0; j < 2; ++j)
{
mComputeVertices[i][j] = (ComputeType)mVertices[i][j];
}
}
mQuery.Set(mNumVertices, &mComputeVertices[0]);
}
int32_t mNumVertices;
Vector2<InputType> const* mVertices;
int32_t mNumTriangles;
std::vector<int32_t> mIndices;
ETManifoldMesh mMesh;
std::map<TriangleKey<true>, int32_t> mTriIndexMap;
std::vector<int32_t> mAdjacencies;
std::vector<Vector2<ComputeType>> mComputeVertices;
PrimalQuery2<ComputeType> mQuery;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrAlignedBox3Cylinder3.h | .h | 2,187 | 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/AlignedBox.h>
#include <Mathematics/IntrCanonicalBox3Cylinder3.h>
// The query is for finite cylinders. The cylinder and box are considered to
// be solids. The cylinder has center C, unit-length axis direction D, radius
// r and height h. The aligned box is converted to a canonical box after which
// a test-intersection query is performed on the finite cylinder and the
// canonical box. See the comments in IntrCanonicalBox3Cylinder3.h for a brief
// description. The details are in
// https://www.geometrictools.com/Documentation/IntersectionBoxCylinder.pdf
namespace gte
{
template <typename T>
class TIQuery<T, AlignedBox3<T>, Cylinder3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(AlignedBox3<T> const& box, Cylinder3<T> const& cylinder)
{
LogAssert(
cylinder.IsFinite(),
"Infinite cylinders are not yet supported.");
// Convert the problem to one involving a finite cylinder and a
// canonical box. This involves translating the box center to
// the origin. The cylinder center must also be translated.
T const half = static_cast<T>(0.5);
Vector3<T> boxCenter = half * (box.max + box.min);
Vector3<T> boxExtent = half * (box.max - box.min);
CanonicalBox3<T> cbox(boxExtent);
Cylinder3<T> translatedCylinder = cylinder;
translatedCylinder.axis.origin -= boxCenter;
TIQuery<T, CanonicalBox3<T>, Cylinder3<T>> bcQuery{};
auto bcResult = bcQuery(cbox, translatedCylinder);
Result result{};
result.intersect = bcResult.intersect;
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrRay2OrientedBox2.h | .h | 3,114 | 106 | // 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/IntrRay2AlignedBox2.h>
#include <Mathematics/OrientedBox.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, Ray2<T>, OrientedBox2<T>>
:
public TIQuery<T, Ray2<T>, AlignedBox2<T>>
{
public:
struct Result
:
public TIQuery<T, Ray2<T>, AlignedBox2<T>>::Result
{
Result()
:
TIQuery<T, Ray2<T>, AlignedBox2<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray2<T> const& ray, OrientedBox2<T> const& box)
{
// Transform the ray to the oriented-box coordinate system.
Vector2<T> diff = ray.origin - box.center;
Vector2<T> rayOrigin
{
Dot(diff, box.axis[0]),
Dot(diff, box.axis[1])
};
Vector2<T> rayDirection = Vector2<T>
{
Dot(ray.direction, box.axis[0]),
Dot(ray.direction, box.axis[1])
};
Result result{};
this->DoQuery(rayOrigin, rayDirection, box.extent, result);
return result;
}
};
template <typename T>
class FIQuery<T, Ray2<T>, OrientedBox2<T>>
:
public FIQuery<T, Ray2<T>, AlignedBox2<T>>
{
public:
struct Result
:
public FIQuery<T, Ray2<T>, AlignedBox2<T>>::Result
{
Result()
:
FIQuery<T, Ray2<T>, AlignedBox2<T>>::Result{}
{
}
// No additional information to compute.
};
Result operator()(Ray2<T> const& ray, OrientedBox2<T> const& box)
{
// Transform the ray to the oriented-box coordinate system.
Vector2<T> diff = ray.origin - box.center;
Vector2<T> rayOrigin
{
Dot(diff, box.axis[0]),
Dot(diff, box.axis[1])
};
Vector2<T> rayDirection = Vector2<T>
{
Dot(ray.direction, box.axis[0]),
Dot(ray.direction, box.axis[1])
};
Result result{};
this->DoQuery(rayOrigin, rayDirection, box.extent, result);
for (int32_t i = 0; i < result.numIntersections; ++i)
{
result.point[i] = ray.origin + result.parameter[i] * ray.direction;
}
return result;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/UIntegerFP32.h | .h | 7,899 | 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/Logger.h>
#include <Mathematics/UIntegerALU32.h>
#include <array>
#include <istream>
#include <ostream>
// Class UIntegerFP32 is designed to support fixed precision arithmetic
// using BSNumber and BSRational. It is not a general-purpose class for
// arithmetic of unsigned integers. The template parameter N is the
// number of 32-bit words required to store the precision for the desired
// computations (maximum number of bits is 32*N).
// Uncomment this to collect statistics on how large the UIntegerFP32 storage
// becomes when using it for the UInteger of BSNumber. If you use this
// feature, you must define gsUIntegerFP32MaxSize somewhere in your code.
//
//#define GTE_COLLECT_UINTEGERFP32_STATISTICS
#if defined(GTE_COLLECT_UINTEGERFP32_STATISTICS)
#include <Mathematics/AtomicMinMax.h>
namespace gte
{
extern std::atomic<int32_t> gsUIntegerFP32MaxSize;
}
#endif
namespace gte
{
template <int32_t N>
class UIntegerFP32 : public UIntegerALU32<UIntegerFP32<N>>
{
public:
// Construction.
UIntegerFP32()
:
mNumBits(0),
mSize(0),
mBits{}
{
static_assert(N >= 1, "Invalid size N.");
}
UIntegerFP32(UIntegerFP32 const& number)
:
mNumBits(0),
mSize(0),
mBits{}
{
static_assert(N >= 1, "Invalid size N.");
*this = number;
}
UIntegerFP32(uint32_t number)
:
mNumBits(0),
mSize(0),
mBits{}
{
static_assert(N >= 1, "Invalid size N.");
if (number > 0)
{
int32_t first = BitHacks::GetLeadingBit(number);
int32_t last = BitHacks::GetTrailingBit(number);
mNumBits = first - last + 1;
mSize = 1;
mBits[0] = (number >> last);
}
else
{
mNumBits = 0;
mSize = 0;
}
#if defined(GTE_COLLECT_UINTEGERFP32_STATISTICS)
AtomicMax(gsUIntegerFP32MaxSize, mSize);
#endif
}
UIntegerFP32(uint64_t number)
:
mNumBits(0),
mSize(0),
mBits{}
{
static_assert(N >= 2, "N not large enough to store 64-bit integers.");
if (number > 0)
{
int32_t first = BitHacks::GetLeadingBit(number);
int32_t last = BitHacks::GetTrailingBit(number);
number >>= last;
mNumBits = first - last + 1;
mSize = 1 + (mNumBits - 1) / 32;
mBits[0] = (uint32_t)(number & 0x00000000FFFFFFFFull);
if (mSize > 1)
{
mBits[1] = (uint32_t)((number >> 32) & 0x00000000FFFFFFFFull);
}
}
else
{
mNumBits = 0;
mSize = 0;
}
#if defined(GTE_COLLECT_UINTEGERFP32_STATISTICS)
AtomicMax(gsUIntegerFP32MaxSize, mSize);
#endif
}
// Assignment. Only mSize elements are copied.
UIntegerFP32& operator=(UIntegerFP32 const& number)
{
static_assert(N >= 1, "Invalid size N.");
mNumBits = number.mNumBits;
mSize = number.mSize;
std::copy(number.mBits.begin(), number.mBits.begin() + mSize, mBits.begin());
return *this;
}
// Support for std::move. The interface is required by BSNumber, but
// the std::move of std::array is a copy (no pointer stealing).
// Moreover, a std::array object in this class typically uses smaller
// than N elements, the actual size stored in mSize, so we do not want
// to move everything. Therefore, the move operator only copies the
// bits BUT 'number' is modified as if you have stolen the data
// (mNumBits and mSize set to zero).
UIntegerFP32(UIntegerFP32&& number) noexcept
{
*this = std::move(number);
}
UIntegerFP32& operator=(UIntegerFP32&& number) noexcept
{
mNumBits = number.mNumBits;
mSize = number.mSize;
std::copy(number.mBits.begin(), number.mBits.begin() + mSize,
mBits.begin());
number.mNumBits = 0;
number.mSize = 0;
return *this;
}
// Member access.
void SetNumBits(int32_t numBits)
{
if (numBits > 0)
{
mNumBits = numBits;
mSize = 1 + (numBits - 1) / 32;
}
else if (numBits == 0)
{
mNumBits = 0;
mSize = 0;
}
else
{
LogError("The number of bits must be nonnegative.");
}
#if defined(GTE_COLLECT_UINTEGERFP32_STATISTICS)
AtomicMax(gsUIntegerFP32MaxSize, mSize);
#endif
LogAssert(mSize <= N, "N not large enough to store number of bits.");
}
inline int32_t GetNumBits() const
{
return mNumBits;
}
inline std::array<uint32_t, N> const& GetBits() const
{
return mBits;
}
inline std::array<uint32_t, N>& GetBits()
{
return mBits;
}
inline void SetBack(uint32_t value)
{
mBits[static_cast<size_t>(mSize) - 1] = value;
}
inline uint32_t GetBack() const
{
return mBits[static_cast<size_t>(mSize) - 1];
}
inline int32_t GetSize() const
{
return mSize;
}
inline static int32_t GetMaxSize()
{
return N;
}
inline void SetAllBitsToZero()
{
std::fill(mBits.begin(), mBits.end(), 0u);
}
// Copy from UIntegerFP32<NSource> to UIntegerFP32<N> as long as
// NSource <= N.
template <int32_t NSource>
void CopyFrom(UIntegerFP32<NSource> const& source)
{
static_assert(NSource <= N,
"The source dimension cannot exceed the target dimension.");
mNumBits = source.GetNumBits();
mSize = source.GetSize();
auto const& srcBits = source.GetBits();
std::copy(srcBits.begin(), srcBits.end(), mBits.begin());
}
// Disk input/output. The fstream objects should be created using
// std::ios::binary. The return value is 'true' iff the operation
// was successful.
bool Write(std::ostream& output) const
{
if (output.write((char const*)& mNumBits, sizeof(mNumBits)).bad())
{
return false;
}
if (output.write((char const*)& mSize, sizeof(mSize)).bad())
{
return false;
}
return output.write((char const*)& mBits[0], mSize * sizeof(mBits[0])).good();
}
bool Read(std::istream& input)
{
if (input.read((char*)& mNumBits, sizeof(mNumBits)).bad())
{
return false;
}
if (input.read((char*)& mSize, sizeof(mSize)).bad())
{
return false;
}
return input.read((char*)& mBits[0], mSize * sizeof(mBits[0])).good();
}
private:
int32_t mNumBits, mSize;
std::array<uint32_t, N> mBits;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrLine3Plane3.h | .h | 3,939 | 131 | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Mathematics/FIQuery.h>
#include <Mathematics/TIQuery.h>
#include <Mathematics/Line.h>
#include <Mathematics/DistPointHyperplane.h>
namespace gte
{
template <typename T>
class TIQuery<T, Line3<T>, Plane3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Line3<T> const& line, Plane3<T> const& plane)
{
Result result{};
T DdN = Dot(line.direction, plane.normal);
if (DdN != (T)0)
{
// The line is not parallel to the plane, so they must
// intersect.
result.intersect = true;
}
else
{
// The line and plane are parallel.
DCPQuery<T, Vector3<T>, Plane3<T>> vpQuery;
result.intersect = (vpQuery(line.origin, plane).distance == (T)0);
}
return result;
}
};
template <typename T>
class FIQuery<T, Line3<T>, Plane3<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
numIntersections(0),
parameter((T)0),
point{ (T)0, (T)0, (T)0 }
{
}
bool intersect;
// The number of intersections is 0 (no intersection), 1 (linear
// component and plane intersect in a point), or
// std::numeric_limits<int32_t>::max() (linear component is on the
// plane). If the linear component is on the plane, 'point'
// component's origin and 'parameter' is zero.
int32_t numIntersections;
T parameter;
Vector3<T> point;
};
Result operator()(Line3<T> const& line, Plane3<T> const& plane)
{
Result result{};
DoQuery(line.origin, line.direction, plane, result);
if (result.intersect)
{
result.point = line.origin + result.parameter * line.direction;
}
return result;
}
protected:
void DoQuery(Vector3<T> const& lineOrigin,
Vector3<T> const& lineDirection, Plane3<T> const& plane,
Result& result)
{
T DdN = Dot(lineDirection, plane.normal);
DCPQuery<T, Vector3<T>, Plane3<T>> vpQuery;
auto vpResult = vpQuery(lineOrigin, plane);
if (DdN != (T)0)
{
// The line is not parallel to the plane, so they must
// intersect.
result.intersect = true;
result.numIntersections = 1;
result.parameter = -vpResult.signedDistance / DdN;
}
else
{
// The line and plane are parallel. Determine whether the
// line is on the plane.
if (vpResult.distance == (T)0)
{
// The line is coincident with the plane, so choose t = 0
// for the parameter.
result.intersect = true;
result.numIntersections = std::numeric_limits<int32_t>::max();
result.parameter = (T)0;
}
else
{
// The line is not on the plane.
result.intersect = false;
result.numIntersections = 0;
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrSegment2Triangle2.h | .h | 3,771 | 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/IntrIntervals.h>
#include <Mathematics/IntrLine2Triangle2.h>
#include <Mathematics/Segment.h>
// The queries consider the triangle to be a solid.
namespace gte
{
template <typename Real>
class TIQuery<Real, Segment2<Real>, Triangle2<Real>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
// The segment is P0 + t * (P1 - P0) for t in [0,1].
Result operator()(Segment2<Real> const& segment, Triangle2<Real> const& triangle)
{
Result result{};
FIQuery<Real, Segment2<Real>, Triangle2<Real>> stQuery{};
result.intersect = stQuery(segment, triangle).intersect;
return result;
}
};
template <typename Real>
class FIQuery <Real, Segment2<Real>, Triangle2<Real>>
:
public FIQuery<Real, Line2<Real>, Triangle2<Real>>
{
public:
struct Result
:
public FIQuery<Real, Line2<Real>, Triangle2<Real>>::Result
{
Result()
:
FIQuery<Real, Line2<Real>, Triangle2<Real>>::Result{}
{
}
// No additional information to compute.
};
// The segment is P0 + t * (P1 - P0) for t in [0,1].
Result operator()(Segment2<Real> const& segment, Triangle2<Real> const& triangle)
{
Result result{};
Vector2<Real> const& segOrigin = segment.p[0];
Vector2<Real> segDirection = segment.p[1] - segment.p[0];
DoQuery(segOrigin, segDirection, triangle, 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(Vector2<Real> const& origin, Vector2<Real> const& direction,
Triangle2<Real> const& triangle, Result& result)
{
FIQuery<Real, Line2<Real>, Triangle2<Real>>::DoQuery(
origin, direction, triangle, result);
if (result.intersect)
{
// The line containing the segment intersects the triangle;
// the t-interval is [t0,t1]. The segment intersects the
// triangle as long as [t0,t1] overlaps the segment t-interval
// [0,1].
FIQuery<Real, std::array<Real, 2>, std::array<Real, 2>> iiQuery{};
std::array<Real, 2> segInterval{ static_cast<Real>(0), static_cast<Real>(1) };
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
// triangle.
result = Result{};
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/FPInterval.h | .h | 19,371 | 634 | // 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 <array>
// The FPInterval [e0,e1] must satisfy e0 <= e1. Expose this define to trap
// invalid construction where e0 > e1.
#define GTE_THROW_ON_INVALID_INTERVAL
namespace gte
{
// The FPType must be 'float' or 'double'.
template <typename FPType>
class FPInterval
{
public:
// Construction. This is the only way to create an interval. All such
// intervals are immutable once created. The constructor
// FPInterval(FPType) is used to create the degenerate interval [e,e].
FPInterval()
:
mEndpoints{ static_cast<FPType>(0), static_cast<FPType>(0) }
{
static_assert(std::is_floating_point<FPType>::value, "Invalid type.");
}
FPInterval(FPInterval const& other)
:
mEndpoints(other.mEndpoints)
{
static_assert(std::is_floating_point<FPType>::value, "Invalid type.");
}
explicit FPInterval(FPType e)
:
mEndpoints{ e, e }
{
static_assert(std::is_floating_point<FPType>::value, "Invalid type.");
}
FPInterval(FPType e0, FPType e1)
:
mEndpoints{ e0, e1 }
{
static_assert(std::is_floating_point<FPType>::value, "Invalid type.");
#if defined(GTE_THROW_ON_INVALID_INTERVAL)
LogAssert(mEndpoints[0] <= mEndpoints[1], "Invalid FPInterval.");
#endif
}
FPInterval(std::array<FPType, 2> const& endpoint)
:
mEndpoints(endpoint)
{
static_assert(std::is_floating_point<FPType>::value, "Invalid type.");
#if defined(GTE_THROW_ON_INVALID_INTERVAL)
LogAssert(mEndpoints[0] <= mEndpoints[1], "Invalid FPInterval.");
#endif
}
FPInterval& operator=(FPInterval const& other)
{
static_assert(std::is_floating_point<FPType>::value, "Invalid type.");
mEndpoints = other.mEndpoints;
return *this;
}
// Member access. It is only possible to read the endpoints. You
// cannot modify the endpoints outside the arithmetic operations.
inline FPType operator[](size_t i) const
{
return mEndpoints[i];
}
inline std::array<FPType, 2> GetEndpoints() const
{
return mEndpoints;
}
// Arithmetic operations to compute intervals at the leaf nodes of
// an expression tree. Such nodes correspond to the raw floating-point
// variables of the expression. The non-class operators defined after
// the class definition are used to compute intervals at the interior
// nodes of the expression tree.
inline static FPInterval Add(FPType u, FPType v)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u + v;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u + v;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Sub(FPType u, FPType v)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u - v;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u - v;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Mul(FPType u, FPType v)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u * v;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u * v;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Div(FPType u, FPType v)
{
FPType const zero = static_cast<FPType>(0);
if (v != zero)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u / v;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u / v;
std::fesetround(saveMode);
return w;
}
else
{
// Division by zero does not lead to a determinate FPInterval.
// Just return the entire set of real numbers.
return Reals();
}
}
// This function is called to compute the lower bound on the product
// of two intervals. Before calling the function, you need to call
// std::fesetround(FE_DOWNWARD). The idea is to compute lower bounds
// in batch mode (multiple calls of ProductLowerBound) in order to
// minimize FPU control word state changes.
static FPType ProductLowerBound(std::array<FPType, 2> const& u,
std::array<FPType, 2> const& v)
{
FPType const zero = static_cast<FPType>(0);
FPType w0;
if (u[0] >= zero)
{
if (v[0] >= zero)
{
w0 = u[0] * v[0];
}
else if (v[1] <= zero)
{
w0 = u[1] * v[0];
}
else
{
w0 = u[1] * v[0];
}
}
else if (u[1] <= zero)
{
if (v[0] >= zero)
{
w0 = u[0] * v[1];
}
else if (v[1] <= zero)
{
w0 = u[1] * v[1];
}
else
{
w0 = u[0] * v[1];
}
}
else
{
if (v[0] >= zero)
{
w0 = u[0] * v[1];
}
else if (v[1] <= zero)
{
w0 = u[1] * v[0];
}
else
{
w0 = u[0] * v[0];
}
}
return w0;
}
// This function is called to compute the upper bound on the product
// of two intervals. Before calling the function, you need to call
// std::fesetround(FE_UPWARD). The idea is to compute lower bounds
// inbatch mode (multiple calls of ProductUpperBound) in order to
// minimize FPU control word state changes.
static FPType ProductUpperBound(std::array<FPType, 2> const& u,
std::array<FPType, 2> const& v)
{
FPType const zero = static_cast<FPType>(0);
FPType w1;
if (u[0] >= zero)
{
if (v[0] >= zero)
{
w1 = u[1] * v[1];
}
else if (v[1] <= zero)
{
w1 = u[0] * v[1];
}
else
{
w1 = u[1] * v[1];
}
}
else if (u[1] <= zero)
{
if (v[0] >= zero)
{
w1 = u[1] * v[0];
}
else if (v[1] <= zero)
{
w1 = u[0] * v[0];
}
else
{
w1 = u[0] * v[0];
}
}
else
{
if (v[0] >= zero)
{
w1 = u[1] * v[1];
}
else if (v[1] <= zero)
{
w1 = u[0] * v[0];
}
else
{
w1 = u[1] * v[1];
}
}
return w1;
}
private:
std::array<FPType, 2> mEndpoints;
public:
// FOR INTERNAL USE ONLY. These are used by the non-class operators
// defined after the class definition.
inline static FPInterval Add(FPType u0, FPType u1, FPType v0, FPType v1)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u0 + v0;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u1 + v1;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Sub(FPType u0, FPType u1, FPType v0, FPType v1)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u0 - v1;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u1 - v0;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Mul(FPType u0, FPType u1, FPType v0, FPType v1)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u0 * v0;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u1 * v1;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Mul2(FPType u0, FPType u1, FPType v0, FPType v1)
{
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
FPType u0mv1 = u0 * v1;
FPType u1mv0 = u1 * v0;
std::fesetround(FE_UPWARD);
FPType u0mv0 = u0 * v0;
FPType u1mv1 = u1 * v1;
std::fesetround(saveMode);
return FPInterval<FPType>(std::min(u0mv1, u1mv0), std::max(u0mv0, u1mv1));
}
inline static FPInterval Div(FPType u0, FPType u1, FPType v0, FPType v1)
{
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = u0 / v1;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = u1 / v0;
std::fesetround(saveMode);
return w;
}
inline static FPInterval Reciprocal(FPType v0, FPType v1)
{
FPType const one = static_cast<FPType>(1);
FPInterval w;
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
w.mEndpoints[0] = one / v1;
std::fesetround(FE_UPWARD);
w.mEndpoints[1] = one / v0;
std::fesetround(saveMode);
return w;
}
inline static FPInterval ReciprocalDown(FPType v)
{
auto saveMode = std::fegetround();
std::fesetround(FE_DOWNWARD);
FPType recpv = static_cast<FPType>(1) / v;
std::fesetround(saveMode);
FPType const inf = std::numeric_limits<FPType>::infinity();
return FPInterval<FPType>(recpv, +inf);
}
inline static FPInterval ReciprocalUp(FPType v)
{
auto saveMode = std::fegetround();
std::fesetround(FE_UPWARD);
FPType recpv = static_cast<FPType>(1) / v;
std::fesetround(saveMode);
FPType const inf = std::numeric_limits<FPType>::infinity();
return FPInterval<FPType>(-inf, recpv);
}
inline static FPInterval Reals()
{
FPType const inf = std::numeric_limits<FPType>::infinity();
return FPInterval(-inf, +inf);
}
};
// Unary operations. Negation of [e0,e1] produces [-e1,-e0]. This
// operation needs to be supported in the sense of negating a
// "number" in an arithmetic expression.
template <typename FPType>
FPInterval<FPType> operator+(FPInterval<FPType> const& u)
{
return u;
}
template <typename FPType>
FPInterval<FPType> operator-(FPInterval<FPType> const& u)
{
return FPInterval<FPType>(-u[1], -u[0]);
}
// Addition operations.
template <typename FPType>
FPInterval<FPType> operator+(FPType u, FPInterval<FPType> const& v)
{
return FPInterval<FPType>::Add(u, u, v[0], v[1]);
}
template <typename FPType>
FPInterval<FPType> operator+(FPInterval<FPType> const& u, FPType v)
{
return FPInterval<FPType>::Add(u[0], u[1], v, v);
}
template <typename FPType>
FPInterval<FPType> operator+(FPInterval<FPType> const& u, FPInterval<FPType> const& v)
{
return FPInterval<FPType>::Add(u[0], u[1], v[0], v[1]);
}
template <typename FPType>
FPInterval<FPType>& operator+=(FPInterval<FPType>& u, FPType v)
{
u = u + v;
return u;
}
template <typename FPType>
FPInterval<FPType>& operator+=(FPInterval<FPType>& u, FPInterval<FPType> const& v)
{
u = u + v;
return u;
}
// Subtraction operations.
template <typename FPType>
FPInterval<FPType> operator-(FPType u, FPInterval<FPType> const& v)
{
return FPInterval<FPType>::Sub(u, u, v[0], v[1]);
}
template <typename FPType>
FPInterval<FPType> operator-(FPInterval<FPType> const& u, FPType v)
{
return FPInterval<FPType>::Sub(u[0], u[1], v, v);
}
template <typename FPType>
FPInterval<FPType> operator-(FPInterval<FPType> const& u, FPInterval<FPType> const& v)
{
return FPInterval<FPType>::Sub(u[0], u[1], v[0], v[1]);
}
template <typename FPType>
FPInterval<FPType>& operator-=(FPInterval<FPType>& u, FPType v)
{
u = u - v;
return u;
}
template <typename FPType>
FPInterval<FPType>& operator-=(FPInterval<FPType>& u, FPInterval<FPType> const& v)
{
u = u - v;
return u;
}
// Multiplication operations.
template <typename FPType>
FPInterval<FPType> operator*(FPType u, FPInterval<FPType> const& v)
{
FPType const zero = static_cast<FPType>(0);
if (u >= zero)
{
return FPInterval<FPType>::Mul(u, u, v[0], v[1]);
}
else
{
return FPInterval<FPType>::Mul(u, u, v[1], v[0]);
}
}
template <typename FPType>
FPInterval<FPType> operator*(FPInterval<FPType> const& u, FPType v)
{
FPType const zero = static_cast<FPType>(0);
if (v >= zero)
{
return FPInterval<FPType>::Mul(u[0], u[1], v, v);
}
else
{
return FPInterval<FPType>::Mul(u[1], u[0], v, v);
}
}
template <typename FPType>
FPInterval<FPType> operator*(FPInterval<FPType> const& u, FPInterval<FPType> const& v)
{
FPType const zero = static_cast<FPType>(0);
if (u[0] >= zero)
{
if (v[0] >= zero)
{
return FPInterval<FPType>::Mul(u[0], u[1], v[0], v[1]);
}
else if (v[1] <= zero)
{
return FPInterval<FPType>::Mul(u[1], u[0], v[0], v[1]);
}
else // v[0] < 0 < v[1]
{
return FPInterval<FPType>::Mul(u[1], u[1], v[0], v[1]);
}
}
else if (u[1] <= zero)
{
if (v[0] >= zero)
{
return FPInterval<FPType>::Mul(u[0], u[1], v[1], v[0]);
}
else if (v[1] <= zero)
{
return FPInterval<FPType>::Mul(u[1], u[0], v[1], v[0]);
}
else // v[0] < 0 < v[1]
{
return FPInterval<FPType>::Mul(u[0], u[0], v[1], v[0]);
}
}
else // u[0] < 0 < u[1]
{
if (v[0] >= zero)
{
return FPInterval<FPType>::Mul(u[0], u[1], v[1], v[1]);
}
else if (v[1] <= zero)
{
return FPInterval<FPType>::Mul(u[1], u[0], v[0], v[0]);
}
else // v[0] < 0 < v[1]
{
return FPInterval<FPType>::Mul2(u[0], u[1], v[0], v[1]);
}
}
}
template <typename FPType>
FPInterval<FPType>& operator*=(FPInterval<FPType>& u, FPType v)
{
u = u * v;
return u;
}
template <typename FPType>
FPInterval<FPType>& operator*=(FPInterval<FPType>& u, FPInterval<FPType> const& v)
{
u = u * v;
return u;
}
// Division operations. If the divisor FPInterval is [v0,v1] with
// v0 < 0 < v1, then the returned FPInterval is (-infinity,+infinity)
// instead of Union((-infinity,1/v0),(1/v1,+infinity)). An application
// should try to avoid this case by branching based on [v0,0] and [0,v1].
template <typename FPType>
FPInterval<FPType> operator/(FPType u, FPInterval<FPType> const& v)
{
FPType const zero = static_cast<FPType>(0);
if (v[0] > zero || v[1] < zero)
{
return u * FPInterval<FPType>::Reciprocal(v[0], v[1]);
}
else
{
if (v[0] == zero)
{
return u * FPInterval<FPType>::ReciprocalDown(v[1]);
}
else if (v[1] == zero)
{
return u * FPInterval<FPType>::ReciprocalUp(v[0]);
}
else // v[0] < 0 < v[1]
{
return FPInterval<FPType>::Reals();
}
}
}
template <typename FPType>
FPInterval<FPType> operator/(FPInterval<FPType> const& u, FPType v)
{
FPType const zero = static_cast<FPType>(0);
if (v > zero)
{
return FPInterval<FPType>::Div(u[0], u[1], v, v);
}
else if (v < zero)
{
return FPInterval<FPType>::Div(u[1], u[0], v, v);
}
else // v = 0
{
return FPInterval<FPType>::Reals();
}
}
template <typename FPType>
FPInterval<FPType> operator/(FPInterval<FPType> const& u, FPInterval<FPType> const& v)
{
FPType const zero = static_cast<FPType>(0);
if (v[0] > zero || v[1] < zero)
{
return u * FPInterval<FPType>::Reciprocal(v[0], v[1]);
}
else
{
if (v[0] == zero)
{
return u * FPInterval<FPType>::ReciprocalDown(v[1]);
}
else if (v[1] == zero)
{
return u * FPInterval<FPType>::ReciprocalUp(v[0]);
}
else // v[0] < 0 < v[1]
{
return FPInterval<FPType>::Reals();
}
}
}
template <typename FPType>
FPInterval<FPType>& operator/=(FPInterval<FPType>& u, FPType v)
{
u = u / v;
return u;
}
template <typename FPType>
FPInterval<FPType>& operator/=(FPInterval<FPType>& u, FPInterval<FPType> const& v)
{
u = u / v;
return u;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/GaussianBlur2.h | .h | 1,487 | 52 | // 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/PdeFilter2.h>
namespace gte
{
template <typename Real>
class GaussianBlur2 : public PdeFilter2<Real>
{
public:
GaussianBlur2(int32_t xBound, int32_t yBound, Real xSpacing, Real ySpacing,
Real const* data, int32_t const* mask, Real borderValue,
typename PdeFilter<Real>::ScaleType scaleType)
:
PdeFilter2<Real>(xBound, yBound, xSpacing, ySpacing, data, mask,
borderValue, scaleType)
{
mMaximumTimeStep = (Real)0.5 / (this->mInvDxDx + this->mInvDyDy);
}
virtual ~GaussianBlur2()
{
}
inline Real GetMaximumTimeStep() const
{
return mMaximumTimeStep;
}
protected:
virtual void OnUpdateSingle(int32_t x, int32_t y) override
{
this->LookUp5(x, y);
Real uxx = this->mInvDxDx * (this->mUpz - (Real)2 * this->mUzz + this->mUmz);
Real uyy = this->mInvDyDy * (this->mUzp - (Real)2 * this->mUzz + this->mUzm);
this->mBuffer[this->mDst][y][x] = this->mUzz + this->mTimeStep * (uxx + uyy);
}
Real mMaximumTimeStep;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Lozenge3.h | .h | 2,103 | 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/Rectangle.h>
#include <Mathematics/Vector3.h>
namespace gte
{
// A lozenge is the set of points that are equidistant from a rectangle,
// the common distance called the radius.
template <typename Real>
class Lozenge3
{
public:
// Construction and destruction. The default constructor sets the
// rectangle to have origin (0,0,0), axes (1,0,0) and (0,1,0), and
// both extents 1. The default radius is 1.
Lozenge3()
:
radius((Real)1)
{
}
Lozenge3(Rectangle<3, Real> const& inRectangle, Real inRadius)
:
rectangle(inRectangle),
radius(inRadius)
{
}
// Public member access.
Rectangle<3, Real> rectangle;
Real radius;
// Comparisons to support sorted containers.
bool operator==(Lozenge3 const& other) const
{
return rectangle == other.rectangle && radius == other.radius;
}
bool operator!=(Lozenge3 const& other) const
{
return !operator==(other);
}
bool operator< (Lozenge3 const& other) const
{
if (rectangle < other.rectangle)
{
return true;
}
if (rectangle > other.rectangle)
{
return false;
}
return radius < other.radius;
}
bool operator<=(Lozenge3 const& other) const
{
return !other.operator<(*this);
}
bool operator> (Lozenge3 const& other) const
{
return other.operator<(*this);
}
bool operator>=(Lozenge3 const& other) const
{
return !operator<(other);
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/Matrix4x4.h | .h | 14,206 | 370 | // 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/Vector4.h>
namespace gte
{
// Template alias for convenience.
template <typename Real>
using Matrix4x4 = Matrix<4, 4, Real>;
// Geometric operations.
template <typename Real>
Matrix4x4<Real> Inverse(Matrix4x4<Real> const& M, bool* reportInvertibility = nullptr)
{
Matrix4x4<Real> inverse;
bool invertible;
Real a0 = M(0, 0) * M(1, 1) - M(0, 1) * M(1, 0);
Real a1 = M(0, 0) * M(1, 2) - M(0, 2) * M(1, 0);
Real a2 = M(0, 0) * M(1, 3) - M(0, 3) * M(1, 0);
Real a3 = M(0, 1) * M(1, 2) - M(0, 2) * M(1, 1);
Real a4 = M(0, 1) * M(1, 3) - M(0, 3) * M(1, 1);
Real a5 = M(0, 2) * M(1, 3) - M(0, 3) * M(1, 2);
Real b0 = M(2, 0) * M(3, 1) - M(2, 1) * M(3, 0);
Real b1 = M(2, 0) * M(3, 2) - M(2, 2) * M(3, 0);
Real b2 = M(2, 0) * M(3, 3) - M(2, 3) * M(3, 0);
Real b3 = M(2, 1) * M(3, 2) - M(2, 2) * M(3, 1);
Real b4 = M(2, 1) * M(3, 3) - M(2, 3) * M(3, 1);
Real b5 = M(2, 2) * M(3, 3) - M(2, 3) * M(3, 2);
Real det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
if (det != (Real)0)
{
Real invDet = (Real)1 / det;
inverse = Matrix4x4<Real>
{
(+M(1, 1) * b5 - M(1, 2) * b4 + M(1, 3) * b3) * invDet,
(-M(0, 1) * b5 + M(0, 2) * b4 - M(0, 3) * b3) * invDet,
(+M(3, 1) * a5 - M(3, 2) * a4 + M(3, 3) * a3) * invDet,
(-M(2, 1) * a5 + M(2, 2) * a4 - M(2, 3) * a3) * invDet,
(-M(1, 0) * b5 + M(1, 2) * b2 - M(1, 3) * b1) * invDet,
(+M(0, 0) * b5 - M(0, 2) * b2 + M(0, 3) * b1) * invDet,
(-M(3, 0) * a5 + M(3, 2) * a2 - M(3, 3) * a1) * invDet,
(+M(2, 0) * a5 - M(2, 2) * a2 + M(2, 3) * a1) * invDet,
(+M(1, 0) * b4 - M(1, 1) * b2 + M(1, 3) * b0) * invDet,
(-M(0, 0) * b4 + M(0, 1) * b2 - M(0, 3) * b0) * invDet,
(+M(3, 0) * a4 - M(3, 1) * a2 + M(3, 3) * a0) * invDet,
(-M(2, 0) * a4 + M(2, 1) * a2 - M(2, 3) * a0) * invDet,
(-M(1, 0) * b3 + M(1, 1) * b1 - M(1, 2) * b0) * invDet,
(+M(0, 0) * b3 - M(0, 1) * b1 + M(0, 2) * b0) * invDet,
(-M(3, 0) * a3 + M(3, 1) * a1 - M(3, 2) * a0) * invDet,
(+M(2, 0) * a3 - M(2, 1) * a1 + M(2, 2) * a0) * invDet
};
invertible = true;
}
else
{
inverse.MakeZero();
invertible = false;
}
if (reportInvertibility)
{
*reportInvertibility = invertible;
}
return inverse;
}
template <typename Real>
Matrix4x4<Real> Adjoint(Matrix4x4<Real> const& M)
{
Real a0 = M(0, 0) * M(1, 1) - M(0, 1) * M(1, 0);
Real a1 = M(0, 0) * M(1, 2) - M(0, 2) * M(1, 0);
Real a2 = M(0, 0) * M(1, 3) - M(0, 3) * M(1, 0);
Real a3 = M(0, 1) * M(1, 2) - M(0, 2) * M(1, 1);
Real a4 = M(0, 1) * M(1, 3) - M(0, 3) * M(1, 1);
Real a5 = M(0, 2) * M(1, 3) - M(0, 3) * M(1, 2);
Real b0 = M(2, 0) * M(3, 1) - M(2, 1) * M(3, 0);
Real b1 = M(2, 0) * M(3, 2) - M(2, 2) * M(3, 0);
Real b2 = M(2, 0) * M(3, 3) - M(2, 3) * M(3, 0);
Real b3 = M(2, 1) * M(3, 2) - M(2, 2) * M(3, 1);
Real b4 = M(2, 1) * M(3, 3) - M(2, 3) * M(3, 1);
Real b5 = M(2, 2) * M(3, 3) - M(2, 3) * M(3, 2);
return Matrix4x4<Real>
{
+M(1, 1) * b5 - M(1, 2) * b4 + M(1, 3) * b3,
-M(0, 1) * b5 + M(0, 2) * b4 - M(0, 3) * b3,
+M(3, 1) * a5 - M(3, 2) * a4 + M(3, 3) * a3,
-M(2, 1) * a5 + M(2, 2) * a4 - M(2, 3) * a3,
-M(1, 0) * b5 + M(1, 2) * b2 - M(1, 3) * b1,
+M(0, 0) * b5 - M(0, 2) * b2 + M(0, 3) * b1,
-M(3, 0) * a5 + M(3, 2) * a2 - M(3, 3) * a1,
+M(2, 0) * a5 - M(2, 2) * a2 + M(2, 3) * a1,
+M(1, 0) * b4 - M(1, 1) * b2 + M(1, 3) * b0,
-M(0, 0) * b4 + M(0, 1) * b2 - M(0, 3) * b0,
+M(3, 0) * a4 - M(3, 1) * a2 + M(3, 3) * a0,
-M(2, 0) * a4 + M(2, 1) * a2 - M(2, 3) * a0,
-M(1, 0) * b3 + M(1, 1) * b1 - M(1, 2) * b0,
+M(0, 0) * b3 - M(0, 1) * b1 + M(0, 2) * b0,
-M(3, 0) * a3 + M(3, 1) * a1 - M(3, 2) * a0,
+M(2, 0) * a3 - M(2, 1) * a1 + M(2, 2) * a0
};
}
template <typename Real>
Real Determinant(Matrix4x4<Real> const& M)
{
Real a0 = M(0, 0) * M(1, 1) - M(0, 1) * M(1, 0);
Real a1 = M(0, 0) * M(1, 2) - M(0, 2) * M(1, 0);
Real a2 = M(0, 0) * M(1, 3) - M(0, 3) * M(1, 0);
Real a3 = M(0, 1) * M(1, 2) - M(0, 2) * M(1, 1);
Real a4 = M(0, 1) * M(1, 3) - M(0, 3) * M(1, 1);
Real a5 = M(0, 2) * M(1, 3) - M(0, 3) * M(1, 2);
Real b0 = M(2, 0) * M(3, 1) - M(2, 1) * M(3, 0);
Real b1 = M(2, 0) * M(3, 2) - M(2, 2) * M(3, 0);
Real b2 = M(2, 0) * M(3, 3) - M(2, 3) * M(3, 0);
Real b3 = M(2, 1) * M(3, 2) - M(2, 2) * M(3, 1);
Real b4 = M(2, 1) * M(3, 3) - M(2, 3) * M(3, 1);
Real b5 = M(2, 2) * M(3, 3) - M(2, 3) * M(3, 2);
Real det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0;
return det;
}
template <typename Real>
Real Trace(Matrix4x4<Real> const& M)
{
Real trace = M(0, 0) + M(1, 1) + M(2, 2) + M(3, 3);
return trace;
}
// Multiply M and V according to the user-selected convention. If it is
// GTE_USE_MAT_VEC, the function returns M*V. If it is GTE_USE_VEC_MAT,
// the function returns V*M. This function is provided to hide the
// preprocessor symbols in the GTEngine sample applications.
template <typename Real>
Vector4<Real> DoTransform(Matrix4x4<Real> const& M, Vector4<Real> const& V)
{
#if defined(GTE_USE_MAT_VEC)
return M * V;
#else
return V * M;
#endif
}
template <typename Real>
Matrix4x4<Real> DoTransform(Matrix4x4<Real> const& A, Matrix4x4<Real> const& B)
{
#if defined(GTE_USE_MAT_VEC)
return A * B;
#else
return B * A;
#endif
}
// For GTE_USE_MAT_VEC, the columns of an invertible matrix form a basis
// for the range of the matrix. For GTE_USE_VEC_MAT, the rows of an
// invertible matrix form a basis for the range of the matrix. These
// functions allow you to access the basis vectors. The caller is
// responsible for ensuring that the matrix is invertible (although the
// inverse is not calculated by these functions).
template <typename Real>
void SetBasis(Matrix4x4<Real>& M, int32_t i, Vector4<Real> const& V)
{
#if defined(GTE_USE_MAT_VEC)
return M.SetCol(i, V);
#else
return M.SetRow(i, V);
#endif
}
template <typename Real>
Vector4<Real> GetBasis(Matrix4x4<Real> const& M, int32_t i)
{
#if defined(GTE_USE_MAT_VEC)
return M.GetCol(i);
#else
return M.GetRow(i);
#endif
}
// Special matrices. In the comments, the matrices are shown using the
// GTE_USE_MAT_VEC multiplication convention.
// The projection plane is Dot(N,X-P) = 0 where N is a 3-by-1 unit-length
// normal vector and P is a 3-by-1 point on the plane. The projection is
// oblique to the plane, in the direction of the 3-by-1 vector D.
// Necessarily Dot(N,D) is not zero for this projection to make sense.
// Given a 3-by-1 point U, compute the intersection of the line U+t*D with
// the plane to obtain t = -Dot(N,U-P)/Dot(N,D); then
//
// projection(U) = P + [I - D*N^T/Dot(N,D)]*(U-P)
//
// A 4-by-4 homogeneous transformation representing the projection is
//
// +- -+
// M = | D*N^T - Dot(N,D)*I -Dot(N,P)D |
// | 0^T -Dot(N,D) |
// +- -+
//
// where M applies to [U^T 1]^T by M*[U^T 1]^T. The matrix is chosen so
// that M[3][3] > 0 whenever Dot(N,D) < 0; the projection is onto the
// "positive side" of the plane.
template <typename Real>
Matrix4x4<Real> MakeObliqueProjection(Vector4<Real> const& origin,
Vector4<Real> const& normal, Vector4<Real> const& direction)
{
Matrix4x4<Real> M;
Real const zero = (Real)0;
Real dotND = Dot(normal, direction);
Real dotNO = Dot(origin, normal);
#if defined(GTE_USE_MAT_VEC)
M(0, 0) = direction[0] * normal[0] - dotND;
M(0, 1) = direction[0] * normal[1];
M(0, 2) = direction[0] * normal[2];
M(0, 3) = -dotNO * direction[0];
M(1, 0) = direction[1] * normal[0];
M(1, 1) = direction[1] * normal[1] - dotND;
M(1, 2) = direction[1] * normal[2];
M(1, 3) = -dotNO * direction[1];
M(2, 0) = direction[2] * normal[0];
M(2, 1) = direction[2] * normal[1];
M(2, 2) = direction[2] * normal[2] - dotND;
M(2, 3) = -dotNO * direction[2];
M(3, 0) = zero;
M(3, 1) = zero;
M(3, 2) = zero;
M(3, 3) = -dotND;
#else
M(0, 0) = direction[0] * normal[0] - dotND;
M(1, 0) = direction[0] * normal[1];
M(2, 0) = direction[0] * normal[2];
M(3, 0) = -dotNO * direction[0];
M(0, 1) = direction[1] * normal[0];
M(1, 1) = direction[1] * normal[1] - dotND;
M(2, 1) = direction[1] * normal[2];
M(3, 1) = -dotNO * direction[1];
M(0, 2) = direction[2] * normal[0];
M(1, 2) = direction[2] * normal[1];
M(2, 2) = direction[2] * normal[2] - dotND;
M(3, 2) = -dotNO * direction[2];
M(0, 2) = zero;
M(1, 3) = zero;
M(2, 3) = zero;
M(3, 3) = -dotND;
#endif
return M;
}
// The perspective projection of a point onto a plane is
//
// +- -+
// M = | Dot(N,E-P)*I - E*N^T -(Dot(N,E-P)*I - E*N^T)*E |
// | -N^t Dot(N,E) |
// +- -+
//
// where E is the eye point, P is a point on the plane, and N is a
// unit-length plane normal.
template <typename Real>
Matrix4x4<Real> MakePerspectiveProjection(Vector4<Real> const& origin,
Vector4<Real> const& normal, Vector4<Real> const& eye)
{
Matrix4x4<Real> M;
Real dotND = Dot(normal, eye - origin);
#if defined(GTE_USE_MAT_VEC)
M(0, 0) = dotND - eye[0] * normal[0];
M(0, 1) = -eye[0] * normal[1];
M(0, 2) = -eye[0] * normal[2];
M(0, 3) = -(M(0, 0) * eye[0] + M(0, 1) * eye[1] + M(0, 2) * eye[2]);
M(1, 0) = -eye[1] * normal[0];
M(1, 1) = dotND - eye[1] * normal[1];
M(1, 2) = -eye[1] * normal[2];
M(1, 3) = -(M(1, 0) * eye[0] + M(1, 1) * eye[1] + M(1, 2) * eye[2]);
M(2, 0) = -eye[2] * normal[0];
M(2, 1) = -eye[2] * normal[1];
M(2, 2) = dotND - eye[2] * normal[2];
M(2, 3) = -(M(2, 0) * eye[0] + M(2, 1) * eye[1] + M(2, 2) * eye[2]);
M(3, 0) = -normal[0];
M(3, 1) = -normal[1];
M(3, 2) = -normal[2];
M(3, 3) = Dot(eye, normal);
#else
M(0, 0) = dotND - eye[0] * normal[0];
M(1, 0) = -eye[0] * normal[1];
M(2, 0) = -eye[0] * normal[2];
M(3, 0) = -(M(0, 0) * eye[0] + M(0, 1) * eye[1] + M(0, 2) * eye[2]);
M(0, 1) = -eye[1] * normal[0];
M(1, 1) = dotND - eye[1] * normal[1];
M(2, 1) = -eye[1] * normal[2];
M(3, 1) = -(M(1, 0) * eye[0] + M(1, 1) * eye[1] + M(1, 2) * eye[2]);
M(0, 2) = -eye[2] * normal[0];
M(1, 2) = -eye[2] * normal[1];
M(2, 2) = dotND - eye[2] * normal[2];
M(3, 2) = -(M(2, 0) * eye[0] + M(2, 1) * eye[1] + M(2, 2) * eye[2]);
M(0, 3) = -normal[0];
M(1, 3) = -normal[1];
M(2, 3) = -normal[2];
M(3, 3) = Dot(eye, normal);
#endif
return M;
}
// The reflection of a point through a plane is
// +- -+
// M = | I-2*N*N^T 2*Dot(N,P)*N |
// | 0^T 1 |
// +- -+
//
// where P is a point on the plane and N is a unit-length plane normal.
template <typename Real>
Matrix4x4<Real> MakeReflection(Vector4<Real> const& origin,
Vector4<Real> const& normal)
{
Matrix4x4<Real> M;
Real const zero = (Real)0, one = (Real)1, two = (Real)2;
Real twoDotNO = two * Dot(origin, normal);
#if defined(GTE_USE_MAT_VEC)
M(0, 0) = one - two * normal[0] * normal[0];
M(0, 1) = -two * normal[0] * normal[1];
M(0, 2) = -two * normal[0] * normal[2];
M(0, 3) = twoDotNO * normal[0];
M(1, 0) = M(0, 1);
M(1, 1) = one - two * normal[1] * normal[1];
M(1, 2) = -two * normal[1] * normal[2];
M(1, 3) = twoDotNO * normal[1];
M(2, 0) = M(0, 2);
M(2, 1) = M(1, 2);
M(2, 2) = one - two * normal[2] * normal[2];
M(2, 3) = twoDotNO * normal[2];
M(3, 0) = zero;
M(3, 1) = zero;
M(3, 2) = zero;
M(3, 3) = one;
#else
M(0, 0) = one - two * normal[0] * normal[0];
M(1, 0) = -two * normal[0] * normal[1];
M(2, 0) = -two * normal[0] * normal[2];
M(3, 0) = twoDotNO * normal[0];
M(0, 1) = M(1, 0);
M(1, 1) = one - two * normal[1] * normal[1];
M(2, 1) = -two * normal[1] * normal[2];
M(3, 1) = twoDotNO * normal[1];
M(0, 2) = M(2, 0);
M(1, 2) = M(2, 1);
M(2, 2) = one - two * normal[2] * normal[2];
M(3, 2) = twoDotNO * normal[2];
M(0, 3) = zero;
M(1, 3) = zero;
M(2, 3) = zero;
M(3, 3) = one;
#endif
return M;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IncrementalDelaunay2.h | .h | 73,240 | 1,879 | // 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
// Incremental insertion and removal of vertices in a Delaunay triangulation.
// The triangles are counterclockwise ordered. The insertion code is that of
// template <typename T> class Delaunay2<T> in Delaunay2.h. For now, the code
// was copy-pasted here. Any changes made to this code must be made in both
// places. The duplication is
// using Triangle = VETManifoldMesh::Triangle;
// using DirectedEdgeKeySet = std::set<EdgeKey<true>>;
// using TrianglePtrSet = std::set<std::shared_ptr<Triangle>>;
// VETManifoldMesh mGraph;
// std::array<std::array<size_t, 2>, 3> const mIndex;
// bool GetContainingTriangle(size_t, std::shared_ptr<Triangle>&) const;
// void GetAndRemoveInsertionPolygon(size_t,
// TrianglePtrSet&, DirectedEdgeKeySet&);
// void Update(size_t);
// static ComputeRational const& Copy(InputRational const&,
// ComputeRational&);
// int32_t ToLine(size_t, size_t, size_t) const;
// int32_t ToTriangle(size_t, size_t, size_t, size_t) const;
// int32_t ToCircumcircle(size_t, size_t, size_t, size_t) const;
//
// The removal code is an implementation of the algorithm in
// Olivier Devillers,
// "On Deletion in Delaunay Triangulations",
// International Journal of Computational Geometry and Applications,
// World Scientific Publishing, 2002, 12, pp. 193-205.
// https://hal.inria.fr/inria-00167201/document
// The weight function for the priority queue, implemented as a min-heap, is
// the negative of the function power(p,circle(q0,q1,q2)) function described
// in the paper.
//
// The paper appears to assume that the removal point is an interior point of
// the trianglation. Just as the insertion algorithms are different for
// interior points and for boundary points, the removal algorithms are
// different for interior points and for boundary points.
//
// The paper mentions that degeneracies (colinear points, cocircular points)
// are handled by jittering. Although one hopes that jittering prevents
// degeneracies--and perhaps probabilistically this is acceptable, the only
// guarantee for a correct result is to use exact arithmetic on the input
// points. The implementation here uses a blend of interval and rational
// arithmetic for exactness; the input points are not jittered.
//
// The details of the algorithms and implementation are provided in
// https://www.geometrictools.com/Documentation/IncrementalDelaunayTriangulation.pdf
#include <Mathematics/ArbitraryPrecision.h>
#include <Mathematics/MinHeap.h>
#include <Mathematics/SWInterval.h>
#include <Mathematics/Vector2.h>
#include <Mathematics/VETManifoldMesh.h>
#include <functional>
#include <map>
#include <set>
namespace gte
// The input type must be 'float' or 'double'. The compute type is defined
// internally and has enough bits of precision to handle any
// floating-point inputs.
{
template <typename T>
class IncrementalDelaunay2
{
public:
// Construction and destruction. A bounding rectangle for the input
// points must be specified. NOTE: The bounding rectangle is inserted
// automatically into the triangulation as two triangles. Once you
// are finished inserting and removing points, call the function
// FinalizeTriangulation(). After this call, you cannot insert or
// remove points.
IncrementalDelaunay2(T const& xMin, T const& yMin, T const& xMax, T const& yMax)
:
mXMin(xMin),
mYMin(yMin),
mXMax(xMax),
mYMax(yMax),
mRectangleRemoved(0),
mCRPool(maxNumCRPool),
mGraph{},
mIndex{ { { 0, 1 }, { 1, 2 }, { 2, 0 } } },
mTriangles{},
mAdjacencies{},
mTrianglesAndAdjacenciesNeedUpdate(true),
mQueryPoint{},
mIRQueryPoint{}
{
static_assert(
std::is_floating_point<T>::value,
"Invalid floating-point type.");
LogAssert(
mXMin < mXMax && mYMin < mYMax,
"Invalid bounding rectangle.");
mToLineWrapper = [this](size_t vPrev, size_t vCurr, size_t vNext)
{
return ToLine(vPrev, vCurr, vNext);
};
// Create the vertices for a supertriangle that contains the
// input rectangle
// V[0] = (x0,y0) = (xmin - dx, ymin - dy)
// V[1] = (x1,y1) = (xmin + 5 * dx, ymin - dy)
// V[2] = (x2,y2) = (xmin - dx, ymax - 5 * dy)
// Create the vertices for the input rectangle
// V[3] = (x3,y3) = (xmin, ymin)
// V[4] = (x4,y4) = (xmax, ymin)
// V[5] = (x5,y5) = (xmin, ymax)
// V[6] = (x6,y6) = (xmax, ymax)
T xDelta = mXMax - mXMin;
T yDelta = mYMax - mYMin;
T x0 = mXMin - xDelta;
T y0 = mYMin - yDelta;
T x1 = mXMin + static_cast<T>(5) * xDelta;
T y1 = y0;
T x2 = x0;
T y2 = mYMin + static_cast<T>(5) * yDelta;
std::array<Vector2<T>, 7> vertices
{
Vector2<T>{ x0, y0 },
Vector2<T>{ x1, y1 },
Vector2<T>{ x2, y2 },
Vector2<T>{ mXMin, mYMin },
Vector2<T>{ mXMax, mYMin },
Vector2<T>{ mXMin, mYMax },
Vector2<T>{ mXMax, mYMax }
};
// Insert the vertices into the vertex storage.
for (size_t i = 0; i < vertices.size(); ++i)
{
auto const& vertex = vertices[i];
mVertexIndexMap.emplace(vertex, i);
mVertices.emplace_back(vertex);
mIRVertices.emplace_back(IRVector{ vertex[0], vertex[1] });
}
// Create the triangles formed by the supervertices and the
// input rectangle vertices.
std::array<std::array<int32_t, 3>, 9> triangles
{ {
{ 0, 5, 2 }, { 0, 3, 5 }, { 0, 4, 3 }, { 0, 1, 4 }, { 1, 6, 4 },
{ 1, 2, 6 }, { 2, 5, 6 }, { 3, 4, 6 }, { 3, 6, 5 }
} };
// Insert the triangles into the triangulation.
for (auto const& tri : triangles)
{
auto inserted = mGraph.Insert(tri[0], tri[1], tri[2]);
LogAssert(
inserted != nullptr,
"Failed to insert initial triangle.");
}
}
~IncrementalDelaunay2() = default;
// Insert a point into the triangulation. It is required that the
// point be strictly inside the input rectangle; if it is not, an
// exception is thrown. If the input point already exists, its
// vertex map index is returned; otherwise, the point is inserted
// into the vertex map and an index associated with the insertion
// is retured.
size_t Insert(Vector2<T> const& position)
{
LogAssert(
mXMin < position[0] && position[0] < mXMax &&
mYMin < position[1] && position[1] < mYMax,
"The position must be strictly inside the domain specified in the constructor.");
if (mRectangleRemoved == 2)
{
// You cannot insert points after the input rectangle is
// removed.
return std::numeric_limits<size_t>::max();
}
mTrianglesAndAdjacenciesNeedUpdate = true;
auto iter = mVertexIndexMap.find(position);
if (iter != mVertexIndexMap.end())
{
// The vertex already exists.
return iter->second;
}
// Store the position in the various pools.
size_t posIndex = mVertices.size();
mVertexIndexMap.emplace(position, posIndex);
mVertices.emplace_back(position);
mIRVertices.emplace_back(IRVector{ position[0], position[1] });
Update(posIndex);
return posIndex;
}
// Remove a point from the triangulation. The return value is the index
// associated with the vertex in the vertex map when that vertex exists.
// If the vertex does not exist, the return value is
// std::numeric_limit<size_t>::max().
size_t Remove(Vector2<T> const& position)
{
if (mRectangleRemoved == 0)
{
LogAssert(
mXMin < position[0] && position[0] < mXMax &&
mYMin < position[1] && position[1] < mYMax,
"The position must be strictly inside the domain specified in the constructor.");
}
if (mRectangleRemoved == 2)
{
// You cannot remove points after the input rectangle is
// removed.
return std::numeric_limits<size_t>::max();
}
mTrianglesAndAdjacenciesNeedUpdate = true;
auto iter = mVertexIndexMap.find(position);
if (iter == mVertexIndexMap.end())
{
// The position is not a vertex of the triangulation.
return invalid;
}
int32_t vRemovalIndex = static_cast<int32_t>(iter->second);
if (mVertexIndexMap.size() == 4)
{
// The last vertex of the input rectangle is to be removed.
for (int32_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
{
auto removed = mGraph.Remove(vRemovalIndex, i0, i1);
LogAssert(
removed,
"Unexpected removal failure.");
}
auto inserted = mGraph.Insert(0, 1, 2);
LogAssert(
inserted != nullptr,
"Failed to insert supertriangle.");
mVertexIndexMap.erase(iter);
return static_cast<size_t>(vRemovalIndex);
}
// Locate the position in the vertices of the graph.
auto const& vMap = mGraph.GetVertices();
auto vIter = vMap.find(vRemovalIndex);
LogAssert(
vIter != vMap.end(),
"Expecting to find the to-be-removed vertex in the triangulation.");
bool removalPointOnBoundary = false;
for (auto vIndex : vIter->second->VAdjacent)
{
if (IsSupervertex(vIndex))
{
// The triangle has a supervertex, so the removal point
// is on the boundary of the Delaunay triangulation.
removalPointOnBoundary = true;
break;
}
}
auto const& adjacents = vIter->second->TAdjacent;
std::vector<int32_t> polygon;
DeleteRemovalPolygon(vRemovalIndex, adjacents, polygon);
if (removalPointOnBoundary)
{
RetriangulateBoundaryRemovalPolygon(vRemovalIndex, polygon);
}
else
{
RetriangulateInteriorRemovalPolygon(vRemovalIndex, polygon);
}
mVertexIndexMap.erase(iter);
return static_cast<size_t>(vRemovalIndex);
}
// Call this only after you are finished inserting points into or
// removing points from the triangulation.
bool FinalizeTriangulation()
{
if (mRectangleRemoved == 2)
{
// You cannot remove the input rectangle more than once.
return false;
}
// Remove the input rectangle vertices. The triangles strictly
// interior to the input rectangle form the Delaunay
// triangulation. However, the triangles sharing a supervertex
// still exist in the graph.
std::array<Vector2<T>, 4> vertex
{
Vector2<T>{ mXMin, mYMin },
Vector2<T>{ mXMax, mYMin },
Vector2<T>{ mXMin, mYMax },
Vector2<T>{ mXMax, mYMax }
};
mRectangleRemoved = 1;
for (size_t i = 0; i < vertex.size(); ++i)
{
size_t index = Remove(vertex[i]);
LogAssert(
index == i + 3,
"Incorrect index for vertex.");
}
mRectangleRemoved = 2;
return true;
}
// Get the current triangulation including the supervertices and
// triangles containing supervertices.
void GetTriangulation(std::vector<Vector2<T>>& vertices,
std::vector<std::array<size_t, 3>>& triangles)
{
vertices.resize(mVertices.size());
std::copy(mVertices.begin(), mVertices.end(), vertices.begin());
auto const& tMap = mGraph.GetTriangles();
triangles.reserve(tMap.size());
triangles.clear();
for (auto const& tri : tMap)
{
auto const& tKey = tri.first;
triangles.push_back({
static_cast<size_t>(tKey.V[0]),
static_cast<size_t>(tKey.V[1]),
static_cast<size_t>(tKey.V[2]) });
}
}
// Get the current graph, which includes all triangles whether
// Delaunay or those containing a supervertex.
inline VETManifoldMesh const& GetGraph() const
{
return mGraph;
}
// Queries associated with the mesh of Delaunay triangles. The
// triangles containing a supervertex are not included in these
// queries.
inline size_t GetNumVertices() const
{
return mVertices.size();
}
inline std::vector<Vector2<T>> const& GetVertices() const
{
return mVertices;
}
size_t GetNumTriangles() const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
return mTriangles.size();
}
std::vector<std::array<size_t, 3>> const& GetTriangles() const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
return mTriangles;
}
std::vector<std::array<size_t, 3>> const& GetAdjacencies() const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
return mAdjacencies;
}
// Get the vertex indices for triangle t. The function returns 'true'
// when t is a valid triangle index, in which case 'triangle' is valid;
// otherwise, the function returns 'false' and 'triangle' is invalid.
bool GetTriangle(size_t t, std::array<size_t, 3>& triangle) const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
if (t < mTriangles.size())
{
triangle = mTriangles[t];
return true;
}
return false;
}
// Get the indices for triangles adjacent to triangle t. The function
// returns 'true' when t is a valid triangle index, in which case
// 'adjacent' is valid; otherwise, the function returns 'false' and
// 'adjacent' is invalid. When valid, triangle t has ordered vertices
// <V[0], V[1], V[2]>. The value adjacent[0] is the index for the
// triangle adjacent to edge <V[0], V[1]>, adjacent[1] is the index
// for the triangle adjacent to edge <V[1], V[2]>, and adjacent[2] is
// the index for the triangle adjacent to edge <V[2], V[0]>.
bool GetAdjacent(size_t t, std::array<size_t, 3>& adjacent) const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
if (t < mAdjacencies.size())
{
adjacent = mAdjacencies[t];
return true;
}
return false;
}
// Get the convex polygon that is the hull of the Delaunay triangles.
// The polygon is counterclockwise ordered with vertices V[hull[0]],
// V[hull[1]], ..., V[hull.size()-1].
void GetHull(std::vector<size_t>& hull) const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
// The hull edges are shared by the triangles with exactly one
// supervertex.
std::map<size_t, size_t> edges;
auto const& vmap = mGraph.GetVertices();
for (int32_t v = 0; v < 3; ++v)
{
auto vIter = vmap.find(v);
LogAssert(
vIter != vmap.end(),
"Expecting the supervertices to exist in the graph.");
for (auto const& adj : vIter->second->TAdjacent)
{
for (size_t i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2, ++i2)
{
if (adj->V[i0] == v)
{
if (IsDelaunayVertex(adj->V[i1]) && IsDelaunayVertex(adj->V[i2]))
{
edges.insert(std::make_pair(adj->V[i2], adj->V[i1]));
break;
}
}
}
}
}
// Repackage the edges into a convex polygon with vertices ordered
// counterclockwise.
size_t numEdges = edges.size();
hull.resize(numEdges);
auto eIter = edges.begin();
size_t vStart = eIter->first;
size_t vNext = eIter->second;
size_t i = 0;
hull[0] = vStart;
while (vNext != vStart)
{
hull[++i] = vNext;
eIter = edges.find(vNext);
LogAssert(
eIter != edges.end(),
"Expecting to find a hull edge.");
vNext = eIter->second;
}
}
// Support for searching the Delaunay triangles that contains the
// point p. If there is a containing triangle, the returned value is
// a triangle index i with 0 <= i < GetNumTriangles(). If there is
// not a containing triangle, 'invalid' is returned. The computations
// are performed using exact rational arithmetic.
//
// The SearchInfo input stores information about the triangle search
// when looking for the triangle (if any) that contains p. The first
// triangle searched is 'initialTriangle'. On return 'path' stores the
// ordered triangle indices visited during the search. The last
// visited triangle has index 'finalTriangle' and vertex indices
// 'finalV[0,1,2]', stored in counterclockwise order. The last edge of
// the search is <finalV[0], finalV[1]>. For spatially coherent inputs
// p for numerous calls to this function, you will want to specify
// 'finalTriangle' from the previous call as 'initialTriangle' for the
// next call, which should reduce search times.
static size_t constexpr invalid = std::numeric_limits<size_t>::max();
struct SearchInfo
{
SearchInfo()
:
initialTriangle(invalid),
finalTriangle(invalid),
finalV{ invalid, invalid, invalid },
numPath(0),
path{}
{
}
size_t initialTriangle;
size_t finalTriangle;
std::array<size_t, 3> finalV;
size_t numPath;
std::vector<size_t> path;
};
size_t GetContainingTriangle(Vector2<T> const& p, SearchInfo& info) const
{
if (mTrianglesAndAdjacenciesNeedUpdate)
{
UpdateTrianglesAndAdjacencies();
mTrianglesAndAdjacenciesNeedUpdate = false;
}
mQueryPoint = p;
mIRQueryPoint = IRVector{ p[0], p[1] };
size_t const numTriangles = mTriangles.size();
info.path.resize(numTriangles);
info.numPath = 0;
size_t tIndex;
if (info.initialTriangle < numTriangles)
{
tIndex = info.initialTriangle;
}
else
{
info.initialTriangle = 0;
tIndex = 0;
}
for (size_t t = 0; t < numTriangles; ++t)
{
auto const& v = mTriangles[tIndex];
auto const& adj = mAdjacencies[tIndex];
info.finalTriangle = tIndex;
info.finalV = v;
info.path[info.numPath++] = tIndex;
size_t i0, i1, i2;
for (i0 = 1, i1 = 2, i2 = 0; i2 < 3; i0 = i1, i1 = i2++)
{
// ToLine(pIndex, v0Index, v1Index) uses mQueryPoint when
// pIndex is set to 'invalid'.
if (ToLine(invalid, v[i0], v[i1]) > 0)
{
tIndex = adj[i0];
if (tIndex == invalid)
{
info.finalV[0] = v[i0];
info.finalV[1] = v[i1];
info.finalV[2] = v[i2];
return invalid;
}
break;
}
}
if (i2 == 3)
{
return tIndex;
}
}
return invalid;
}
private:
// The minimum-size rational type of the input points.
static int32_t constexpr InputNumWords = std::is_same<T, float>::value ? 2 : 4;
using InputRational = BSNumber<UIntegerFP32<InputNumWords>>;
using IRVector = Vector2<InputRational>;
// The compute type used for exact sign classification.
static int32_t constexpr ComputeNumWords = std::is_same<T, float>::value ? 36 : 264;
using ComputeRational = BSNumber<UIntegerFP32<ComputeNumWords>>;
using CRVector = Vector2<ComputeRational>;
// The rectangular domain in which all input points live.
T mXMin, mYMin, mXMax, mYMax;
// The rectangular domain is always inserted into the triangulation
// first. After all your insert and remove calls, if you remove the
// rectangle via FinalizeTriangulation(), you can no longer insert
// or remove points. That is, the triangulation is final. The values
// of this member are
// 0: rectangle has not been removed
// 1: rectangle is in the process of being removed
// 2: rectangle is removed
// The 3-valued member allows us to throw an exception in the
// Remove(position) call when the state is 2, but finalization can
// use Remove(position) without exceptions when the state is 1.
uint32_t mRectangleRemoved;
// The current vertices.
std::map<Vector2<T>, size_t> mVertexIndexMap;
std::vector<Vector2<T>> mVertices;
std::vector<IRVector> mIRVertices;
// Sufficient storage for the expression trees related to computing
// the exact signs in ToLine(...) and ToCircumcircle(...).
static size_t constexpr maxNumCRPool = 43;
mutable std::vector<ComputeRational> mCRPool;
// Support for inserting a point into the triangulation. The graph
// is the current triangulation. The mIndex array provides indexing
using Triangle = VETManifoldMesh::Triangle;
using DirectedEdgeKeySet = std::set<EdgeKey<true>>;
using TrianglePtrSet = std::set<Triangle*>;
VETManifoldMesh mGraph;
// Indexing for the vertices of the triangle adjacent to a vertex.
// The edge adjacent to vertex j is <mIndex[j][0], mIndex[j][1]> and
// is listed so that the triangle interior is to your left as you walk
// around the edges.
std::array<std::array<size_t, 2>, 3> const mIndex;
// Wrap the ToLine function for use in retriangulating the removal
// polygon.
std::function<int32_t(size_t, size_t, size_t)> mToLineWrapper;
template <typename IntegerType>
inline bool IsDelaunayVertex(IntegerType vIndex) const
{
return vIndex >= 3;
}
template <typename IntegerType>
inline bool IsDelaunayTriangle(IntegerType v0, IntegerType v1, IntegerType v2) const
{
return v0 >= 3 && v1 >= 3 && v2 >= 3;
}
template <typename IntegerType>
inline bool IsSupervertex(IntegerType vIndex) const
{
return vIndex < 3;
}
bool GetContainingTriangle(size_t pIndex, Triangle*& tri) const
{
size_t const numTriangles = mGraph.GetTriangles().size();
for (size_t t = 0; t < numTriangles; ++t)
{
size_t j;
for (j = 0; j < 3; ++j)
{
size_t v0Index = static_cast<size_t>(tri->V[mIndex[j][0]]);
size_t v1Index = static_cast<size_t>(tri->V[mIndex[j][1]]);
if (ToLine(pIndex, v0Index, v1Index) > 0)
{
// Point i sees edge <v0,v1> from outside the triangle.
auto adjTri = tri->T[j];
if (adjTri)
{
// Traverse to the triangle sharing the face.
tri = adjTri;
break;
}
else
{
// We reached a hull edge, so the point is outside
// the hull.
return false;
}
}
}
if (j == 3)
{
// The point is inside all three edges, so the point is
// inside a triangle.
return true;
}
}
LogError(
"Unexpected termination of loop while searching for a triangle.");
}
void GetAndRemoveInsertionPolygon(size_t pIndex,
TrianglePtrSet& candidates, DirectedEdgeKeySet& boundary)
{
// Locate the triangles that make up the insertion polygon.
ETManifoldMesh polygon;
while (candidates.size() > 0)
{
Triangle* tri = *candidates.begin();
candidates.erase(candidates.begin());
for (size_t j = 0; j < 3; ++j)
{
auto adj = tri->T[j];
if (adj && candidates.find(adj) == candidates.end())
{
size_t v0 = adj->V[0];
size_t v1 = adj->V[1];
size_t v2 = adj->V[2];
if (IsDelaunayTriangle(v0, v1, v2) &&
ToCircumcircle(pIndex, v0, v1, v2) <= 0)
{
// Point P is in the circumcircle.
candidates.insert(adj);
}
}
}
auto inserted = polygon.Insert(tri->V[0], tri->V[1], tri->V[2]);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
auto removed = mGraph.Remove(tri->V[0], tri->V[1], tri->V[2]);
LogAssert(
removed,
"Unexpected removal failure.");
}
// Get the boundary edges of the insertion polygon.
for (auto const& element : polygon.GetTriangles())
{
Triangle* tri = element.second.get();
for (size_t j = 0; j < 3; ++j)
{
if (!tri->T[j])
{
EdgeKey<true> ekey(tri->V[mIndex[j][0]], tri->V[mIndex[j][1]]);
boundary.insert(ekey);
}
}
}
}
void Update(size_t pIndex)
{
auto const& tmap = mGraph.GetTriangles();
Triangle* tri = tmap.begin()->second.get();
if (GetContainingTriangle(pIndex, tri))
{
// The point is inside the convex hull. The insertion polygon
// contains only triangles in the current triangulation; the
// hull does not change.
// Use a depth-first search for those triangles whose
// circumcircles contain point P.
TrianglePtrSet candidates;
candidates.insert(tri);
// Get the boundary of the insertion polygon C that contains
// the triangles whose circumcircles contain point P. Polygon
// Polygon C contains this point.
DirectedEdgeKeySet boundary;
GetAndRemoveInsertionPolygon(pIndex, candidates, boundary);
// The insertion polygon consists of the triangles formed by
// point P and the faces of C.
for (auto const& key : boundary)
{
size_t v0Index = static_cast<size_t>(key.V[0]);
size_t v1Index = static_cast<size_t>(key.V[1]);
if (ToLine(pIndex, v0Index, v1Index) < 0)
{
auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex),
key.V[0], key.V[1]);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
}
}
else
{
// The point is outside the convex hull. The insertion
// polygon is formed by point P and any triangles in the
// current triangulation whose circumcircles contain point P.
// Locate the convex hull of the triangles.
DirectedEdgeKeySet hull;
for (auto const& element : tmap)
{
Triangle* t = element.second.get();
for (size_t j = 0; j < 3; ++j)
{
if (!t->T[j])
{
hull.insert(EdgeKey<true>(t->V[mIndex[j][0]], t->V[mIndex[j][1]]));
}
}
}
// Iterate over all the hull edges and use the ones visible to
// point P to locate the insertion polygon.
auto const& emap = mGraph.GetEdges();
TrianglePtrSet candidates;
DirectedEdgeKeySet visible;
for (auto const& key : hull)
{
size_t v0Index = static_cast<size_t>(key.V[0]);
size_t v1Index = static_cast<size_t>(key.V[1]);
if (ToLine(pIndex, v0Index, v1Index) > 0)
{
auto iter = emap.find(EdgeKey<false>(key.V[0], key.V[1]));
if (iter != emap.end() && iter->second->T[1] == nullptr)
{
auto adj = iter->second->T[0];
if (adj && candidates.find(adj) == candidates.end())
{
size_t a0Index = static_cast<size_t>(adj->V[0]);
size_t a1Index = static_cast<size_t>(adj->V[1]);
size_t a2Index = static_cast<size_t>(adj->V[2]);
if (ToCircumcircle(pIndex, a0Index, a1Index, a2Index) <= 0)
{
// Point P is in the circumcircle.
candidates.insert(adj);
}
else
{
// Point P is not in the circumcircle but
// the hull edge is visible.
visible.insert(key);
}
}
}
else
{
LogError(
"This condition should not occur for rational arithmetic.");
}
}
}
// Get the boundary of the insertion subpolygon C that
// contains the triangles whose circumcircles contain point P.
DirectedEdgeKeySet boundary;
GetAndRemoveInsertionPolygon(pIndex, candidates, boundary);
// The insertion polygon P consists of the triangles formed by
// point i and the back edges of C and by the visible edges of
// mGraph-C.
for (auto const& key : boundary)
{
size_t v0Index = static_cast<size_t>(key.V[0]);
size_t v1Index = static_cast<size_t>(key.V[1]);
if (ToLine(pIndex, v0Index, v1Index) < 0)
{
// This is a back edge of the boundary.
auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex),
key.V[0], key.V[1]);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
}
for (auto const& key : visible)
{
auto inserted = mGraph.Insert(static_cast<int32_t>(pIndex),
key.V[1], key.V[0]);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
}
}
static ComputeRational const& Copy(InputRational const& source,
ComputeRational& target)
{
target.SetSign(source.GetSign());
target.SetBiasedExponent(source.GetBiasedExponent());
target.GetUInteger().CopyFrom(source.GetUInteger());
return target;
}
// Given a 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.
Vector2<T> const& inP = (pIndex != invalid ? mVertices[pIndex] : mQueryPoint);
Vector2<T> const& inV0 = mVertices[v0Index];
Vector2<T> const& inV1 = 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 = (pIndex != invalid ? mIRVertices[pIndex] : mIRQueryPoint);
Vector2<InputRational> const& irV0 = mIRVertices[v0Index];
Vector2<InputRational> const& irV1 = 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();
}
// For a triangle with counterclockwise vertices V0, V1 and V2, operator()
// returns
// +1, P outside triangle
// -1, P inside triangle
// 0, P on triangle
int32_t ToTriangle(size_t pIndex, size_t v0Index, size_t v1Index, size_t v2Index) const
{
int32_t sign0 = ToLine(pIndex, v1Index, v2Index);
if (sign0 > 0)
{
return +1;
}
int32_t sign1 = ToLine(pIndex, v0Index, v2Index);
if (sign1 < 0)
{
return +1;
}
int32_t sign2 = ToLine(pIndex, v0Index, v1Index);
if (sign2 > 0)
{
return +1;
}
return ((sign0 && sign1 && sign2) ? -1 : 0);
}
// For a triangle with counterclockwise vertices V0, V1 and V2 and a
// query point P, ToCircumcircle returns
// +1, P outside circumcircle of triangle
// -1, P inside circumcircle of triangle
// 0, P on circumcircle of triangle
int32_t ToCircumcircle(size_t pIndex, size_t v0Index, size_t v1Index, size_t v2Index) const
{
// The expression tree has 43 nodes consisting of 8 input
// leaves and 35 compute nodes.
// Use interval arithmetic to determine the sign if possible.
auto const& inP = mVertices[pIndex];
Vector2<T> const& inV0 = mVertices[v0Index];
Vector2<T> const& inV1 = mVertices[v1Index];
Vector2<T> const& inV2 = mVertices[v2Index];
auto x0 = SWInterval<T>::Sub(inV0[0], inP[0]);
auto y0 = SWInterval<T>::Sub(inV0[1], inP[1]);
auto s00 = SWInterval<T>::Add(inV0[0], inP[0]);
auto s01 = SWInterval<T>::Add(inV0[1], inP[1]);
auto x1 = SWInterval<T>::Sub(inV1[0], inP[0]);
auto y1 = SWInterval<T>::Sub(inV1[1], inP[1]);
auto s10 = SWInterval<T>::Add(inV1[0], inP[0]);
auto s11 = SWInterval<T>::Add(inV1[1], inP[1]);
auto x2 = SWInterval<T>::Sub(inV2[0], inP[0]);
auto y2 = SWInterval<T>::Sub(inV2[1], inP[1]);
auto s20 = SWInterval<T>::Add(inV2[0], inP[0]);
auto s21 = SWInterval<T>::Add(inV2[1], inP[1]);
auto t00 = s00 * x0;
auto t01 = s01 * y0;
auto t10 = s10 * x1;
auto t11 = s11 * y1;
auto t20 = s20 * x2;
auto t21 = s21 * y2;
auto z0 = t00 + t01;
auto z1 = t10 + t11;
auto z2 = t20 + t21;
auto y0z1 = y0 * z1;
auto y0z2 = y0 * z2;
auto y1z0 = y1 * z0;
auto y1z2 = y1 * z2;
auto y2z0 = y2 * z0;
auto y2z1 = y2 * z1;
auto c0 = y1z2 - y2z1;
auto c1 = y2z0 - y0z2;
auto c2 = y0z1 - y1z0;
auto x0c0 = x0 * c0;
auto x1c1 = x1 * c1;
auto x2c2 = x2 * c2;
auto det = x0c0 + x1c1 + x2c2;
T constexpr zero = 0;
if (det[0] > zero)
{
return -1;
}
else if (det[1] < zero)
{
return +1;
}
// The exact sign of the determinant is not known, so compute
// the determinant using rational arithmetic.
// Name the nodes of the expression tree.
auto const& irP = mIRVertices[pIndex];
Vector2<InputRational> const& irV0 = mIRVertices[v0Index];
Vector2<InputRational> const& irV1 = mIRVertices[v1Index];
Vector2<InputRational> const& irV2 = mIRVertices[v2Index];
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 const& crV20 = Copy(irV2[0], mCRPool[6]);
auto const& crV21 = Copy(irV2[1], mCRPool[7]);
auto& crX0 = mCRPool[8];
auto& crY0 = mCRPool[9];
auto& crS00 = mCRPool[10];
auto& crS01 = mCRPool[11];
auto& crT00 = mCRPool[12];
auto& crT01 = mCRPool[13];
auto& crZ0 = mCRPool[14];
auto& crX1 = mCRPool[15];
auto& crY1 = mCRPool[16];
auto& crS10 = mCRPool[17];
auto& crS11 = mCRPool[18];
auto& crT10 = mCRPool[19];
auto& crT11 = mCRPool[20];
auto& crZ1 = mCRPool[21];
auto& crX2 = mCRPool[22];
auto& crY2 = mCRPool[23];
auto& crS20 = mCRPool[24];
auto& crS21 = mCRPool[25];
auto& crT20 = mCRPool[26];
auto& crT21 = mCRPool[27];
auto& crZ2 = mCRPool[28];
auto& crY0Z1 = mCRPool[29];
auto& crY0Z2 = mCRPool[30];
auto& crY1Z0 = mCRPool[31];
auto& crY1Z2 = mCRPool[32];
auto& crY2Z0 = mCRPool[33];
auto& crY2Z1 = mCRPool[34];
auto& crC0 = mCRPool[35];
auto& crC1 = mCRPool[36];
auto& crC2 = mCRPool[37];
auto& crX0C0 = mCRPool[38];
auto& crX1C1 = mCRPool[39];
auto& crX2C2 = mCRPool[40];
auto& crTerm = mCRPool[41];
auto& crDet = mCRPool[42];
// Evaluate the expression tree.
crX0 = crV00 - crP0;
crY0 = crV01 - crP1;
crS00 = crV00 + crP0;
crS01 = crV01 + crP1;
crT00 = crS00 * crX0;
crT01 = crS01 * crY0;
crZ0 = crT00 + crT01;
crX1 = crV10 - crP0;
crY1 = crV11 - crP1;
crS10 = crV10 + crP0;
crS11 = crV11 + crP1;
crT10 = crS10 * crX1;
crT11 = crS11 * crY1;
crZ1 = crT10 + crT11;
crX2 = crV20 - crP0;
crY2 = crV21 - crP1;
crS20 = crV20 + crP0;
crS21 = crV21 + crP1;
crT20 = crS20 * crX2;
crT21 = crS21 * crY2;
crZ2 = crT20 + crT21;
crY0Z1 = crY0 * crZ1;
crY0Z2 = crY0 * crZ2;
crY1Z0 = crY1 * crZ0;
crY1Z2 = crY1 * crZ2;
crY2Z0 = crY2 * crZ0;
crY2Z1 = crY2 * crZ1;
crC0 = crY1Z2 - crY2Z1;
crC1 = crY2Z0 - crY0Z2;
crC2 = crY0Z1 - crY1Z0;
crX0C0 = crX0 * crC0;
crX1C1 = crX1 * crC1;
crX2C2 = crX2 * crC2;
crTerm = crX0C0 + crX1C1;
crDet = crTerm + crX2C2;
return -crDet.GetSign();
}
private:
// Support for triangulating the removal polygon.
// Let Vc be a vertex in the removal polygon. If Vc is not an ear, its
// weight is +infinity. If Vc is an ear, let Vp be its predecessor and
// let Vn be its successor when traversing counterclockwise. Let P be
// the removal point. The weight is
// W = -H(Vp, Vc, Vn, P) / D(Vp, Vc, Vn) = WNumer / WDenom
// where
// +- -+
// | Vp.x Vc.x Vn.x | +- -+
// D = det | Vp.y Vc.y Vn.y | = det | Vc.x-Vp.x Vn.x-Vp.x |
// | 1 1 1 | | Vc.y-Vp.y Vn.y-Vp.y |
// +- -+ +- -+
// and
// +- -+
// | Vp.x Vc.x Vn.x P.x |
// H = det | Vp.y Vc.y Vn.y P.y |
// | |Vp|^2 |Vc|^2 |Vn|^2 |P|^2 |
// | 1 1 1 1 |
// +- -+
//
// +- -+
// | Vc.x-Vp.x Vn.x-Vp.x P.x-Vp.x |
// = -det | Vc.y-Vp.y Vn.y-Vp.y P.y-Vp.y |
// | |Vc|^2-|Vp|^2 |Vn|^2-|Vp|^2 |P|^2-|Vp|^2 |
// +- -+
//
// To use BSNumber-based rationals, the weight is a ratio stored as a
// pair (WNumer, WDenom) with WDenom > 0. The comparison of weights is
// WN0/WD0 < WN1/WD1, implemented as WN0*WD1 < WN1*WD0. Additionally,
// a Boolean flag isFinite is used to distinguish between a finite
// ratio (for convex vertices) and a weight that is infinite (for
// reflex vertices).
class RPWeight
{
public:
enum class Type
{
finite,
infinite,
unmodifiable
};
RPWeight(Type inType = Type::unmodifiable)
:
numerator(0),
denominator(inType == Type::finite ? 1 : 0),
type(inType)
{
}
bool operator<(RPWeight const& other) const
{
// finite < infinite < unmodifiable
if (type == Type::finite)
{
if (other.type == Type::finite)
{
ComputeRational lhs = numerator * other.denominator;
ComputeRational rhs = other.numerator * denominator;
return lhs < rhs;
}
else // other.type is infinite or unmodifiable
{
return true;
}
}
else if (type == Type::infinite)
{
if (other.type == Type::finite)
{
return false;
}
else // other.type is infinite or unmodifiable
{
return other.type == Type::unmodifiable;
}
}
else // type is unmodifiable
{
return false;
}
}
bool operator<=(RPWeight const& other) const
{
return !(other < *this);
}
// The finite weight is numerator/denominator with a nonnegative
// numerator and a positive denominator. If the weight is
// infinite, the numerator and denominator values are invalid.
ComputeRational numerator, denominator;
Type type;
};
class RPVertex
{
public:
RPVertex()
:
vIndex(invalid),
isConvex(false),
iPrev(invalid),
iNext(invalid),
record(nullptr)
{
}
// The index relative to IncrementalDelaunay2 mVertices[].
size_t vIndex;
// A vertex is either convex or reflex.
bool isConvex;
// Vertex indices for the polygon. These are indices relative to
// RPPolygon mVertices[].
size_t iPrev, iNext;
// Support for the priority queue of ears.
typename MinHeap<size_t, RPWeight>::Record* record;
};
class RPPolygon
{
public:
RPPolygon(std::vector<int32_t> const& polygon,
std::function<int32_t(size_t, size_t, size_t)> const& ToLine)
:
mNumActive(polygon.size()),
mVertices(polygon.size())
{
// Create a circular list of the polygon vertices for dynamic
// removal of vertices.
size_t const numVertices = mVertices.size();
for (size_t i = 0; i < numVertices; ++i)
{
RPVertex& vertex = mVertices[i];
vertex.vIndex = static_cast<size_t>(polygon[i]);
vertex.iPrev = (i > 0 ? i - 1 : numVertices - 1);
vertex.iNext = (i < numVertices - 1 ? i + 1 : 0);
}
// Create a linear list of the polygon convex vertices and a
// linear list of the polygon reflex vertices, both used for
// dynamic removal of vertices.
for (size_t i = 0; i < numVertices; ++i)
{
// Determine whether the vertex is convex or reflex.
size_t vPrev = invalid, vCurr = invalid, vNext = invalid;
GetTriangle(i, vPrev, vCurr, vNext);
mVertices[i].isConvex = (ToLine(vPrev, vCurr, vNext) < 0);
}
}
inline RPVertex const& Vertex(size_t i) const
{
return mVertices[i];
}
inline RPVertex& Vertex(size_t i)
{
return mVertices[i];
}
void GetTriangle(size_t i, size_t& vPrev, size_t& vCurr, size_t& vNext) const
{
RPVertex const& vertex = mVertices[i];
vCurr = vertex.vIndex;
vPrev = mVertices[vertex.iPrev].vIndex;
vNext = mVertices[vertex.iNext].vIndex;
}
void Classify(size_t i,
std::function<int32_t(size_t, size_t, size_t)> const& ToLine)
{
size_t vPrev = invalid, vCurr = invalid, vNext = invalid;
GetTriangle(i, vPrev, vCurr, vNext);
mVertices[i].isConvex = (ToLine(vPrev, vCurr, vNext) < 0);
}
inline size_t GetNumActive() const
{
return mNumActive;
}
size_t GetActive() const
{
for (size_t i = 0; i < mVertices.size(); ++i)
{
if (mVertices[i].iPrev != invalid)
{
return i;
}
}
LogError(
"Expecting to find an active vertex.");
}
inline void Remove(size_t i)
{
// Remove the vertex from the polygon.
RPVertex& vertex = mVertices[i];
size_t iPrev = vertex.iPrev;
size_t iNext = vertex.iNext;
mVertices[iPrev].iNext = iNext;
mVertices[iNext].iPrev = iPrev;
vertex.vIndex = invalid;
vertex.isConvex = false;
vertex.iPrev = invalid;
vertex.iNext = invalid;
vertex.record = nullptr;
--mNumActive;
}
private:
size_t mNumActive;
std::vector<RPVertex> mVertices;
};
RPWeight ComputeWeight(size_t iConvexIndex, int32_t vRemovalIndex,
RPPolygon& rpPolygon)
{
// Get the triangle <VP,VC,VN> with convex vertex VC.
size_t vPrev = invalid, vCurr = invalid, vNext = invalid;
rpPolygon.GetTriangle(iConvexIndex, vPrev, vCurr, vNext);
auto const& irVP = mIRVertices[vPrev];
auto const& irVC = mIRVertices[vCurr];
auto const& irVN = mIRVertices[vNext];
auto const& irPR = mIRVertices[vRemovalIndex];
CRVector VP, VC, VN, PR;
Copy(irVP[0], VP[0]);
Copy(irVP[1], VP[1]);
Copy(irVC[0], VC[0]);
Copy(irVC[1], VC[1]);
Copy(irVN[0], VN[0]);
Copy(irVN[1], VN[1]);
Copy(irPR[0], PR[0]);
Copy(irPR[1], PR[1]);
auto subVCVP = VC - VP;
auto subVNVP = VN - VP;
auto subPRVP = PR - VP;
auto addVCVP = VC + VP;
auto addVNVP = VN + VP;
auto addPRVP = PR + VP;
auto c20 = DotPerp(subVNVP, subPRVP);
auto c21 = DotPerp(subPRVP, subVCVP);
auto c22 = DotPerp(subVCVP, subVNVP);
auto a20 = Dot(subVCVP, addVCVP);
auto a21 = Dot(subVNVP, addVNVP);
auto a22 = Dot(subPRVP, addPRVP);
RPWeight weight(RPWeight::Type::finite);
weight.numerator = a20 * c20 + a21 * c21 + a22 * c22;
weight.numerator.SetSign(-weight.numerator.GetSign());
weight.denominator = std::move(c22);
if (weight.denominator.GetSign() < 0)
{
weight.numerator.SetSign(-weight.numerator.GetSign());
weight.denominator.SetSign(1);
}
return weight;
}
void DoEarClipping(MinHeap<size_t, RPWeight>& earHeap,
std::function<RPWeight(size_t)> const& WeightFunction,
RPPolygon& rpPolygon)
{
// Remove the finite-weight vertices from the priority queue,
// one at a time.
size_t i;
RPWeight weight{};
while (earHeap.GetNumElements() >= 3)
{
// Get the ear of minimum weight. The vertex at index i must
// be convex.
(void)earHeap.GetMinimum(i, weight);
if (weight.type != RPWeight::Type::finite)
{
break;
}
earHeap.Remove(i, weight);
// Get the triangle associated with the ear.
size_t vPrev = invalid, vCurr = invalid, vNext = invalid;
rpPolygon.GetTriangle(i, vPrev, vCurr, vNext);
// Insert the triangle into the graph.
auto inserted = mGraph.Insert(
static_cast<int32_t>(vPrev),
static_cast<int32_t>(vCurr),
static_cast<int32_t>(vNext));
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
if (earHeap.GetNumElements() < 3)
{
earHeap.Reset(0);
break;
}
// Remove the vertex from the polygon. The previous and next
// neighbor indices are required to update the adjacent
// vertices after the removal.
RPVertex const& vertex = rpPolygon.Vertex(i);
size_t iPrev = vertex.iPrev;
size_t iNext = vertex.iNext;
rpPolygon.Remove(i);
// Removal of the ear can cause an adjacent vertex to become
// an ear or to stop being an ear.
bool wasConvex, nowConvex;
RPVertex& vertexP = rpPolygon.Vertex(iPrev);
wasConvex = vertexP.isConvex;
rpPolygon.Classify(iPrev, mToLineWrapper);
nowConvex = vertexP.isConvex;
if (wasConvex)
{
// The 'vertex' is convex. If 'vertexP' was convex, it
// cannot become reflex after the ear is clipped.
LogAssert(
nowConvex,
"Unexpected condition.");
if (vertexP.record->value.type != RPWeight::Type::unmodifiable)
{
weight = WeightFunction(iPrev);
earHeap.Update(vertexP.record, weight);
}
}
else // 'vertexP' was reflex
{
if (nowConvex)
{
if (vertexP.record->value.type != RPWeight::Type::unmodifiable)
{
weight = WeightFunction(iPrev);
earHeap.Update(vertexP.record, weight);
}
}
}
RPVertex& vertexN = rpPolygon.Vertex(iNext);
wasConvex = vertexN.isConvex;
rpPolygon.Classify(iNext, mToLineWrapper);
nowConvex = vertexN.isConvex;
if (wasConvex)
{
// The 'vertex' is convex. If 'vertexN' was convex, it
// cannot become reflex after the ear is clipped.
LogAssert(
nowConvex,
"Unexpected condition.");
if (vertexN.record->value.type != RPWeight::Type::unmodifiable)
{
weight = WeightFunction(iNext);
earHeap.Update(vertexN.record, weight);
}
}
else // 'vertexN' was reflex
{
if (nowConvex)
{
if (vertexN.record->value.type != RPWeight::Type::unmodifiable)
{
weight = WeightFunction(iNext);
earHeap.Update(vertexN.record, weight);
}
}
}
}
}
void DeleteRemovalPolygon(int32_t vRemovalIndex,
std::unordered_set<Triangle*> const& adjacents,
std::vector<int32_t>& polygon)
{
// Get the edges of the removal polygon. The polygon is star
// shaped relative to the removal position.
std::map<int32_t, int32_t> edges;
for (auto const& adj : adjacents)
{
size_t i;
for (i = 0; i < 3; ++i)
{
if (vRemovalIndex == adj->V[i])
{
break;
}
}
LogAssert(
i < 3,
"Unexpected condition.");
int32_t opposite1 = adj->V[(i + 1) % 3];
int32_t opposite2 = adj->V[(i + 2) % 3];
edges.insert(std::make_pair(opposite1, opposite2));
}
// Remove the triangles.
for (auto const& edge : edges)
{
bool removed = mGraph.Remove(vRemovalIndex, edge.first, edge.second);
LogAssert(
removed,
"Unexpected removal failure.");
}
// Create the removal polygon; its vertices are counterclockwise
// ordered.
polygon.reserve(edges.size());
polygon.clear();
int32_t vStart = edges.begin()->first;
int32_t vCurr = edges.begin()->second;
polygon.push_back(vStart);
while (vCurr != vStart)
{
polygon.push_back(vCurr);
auto eIter = edges.find(vCurr);
LogAssert(
eIter != edges.end(),
"Unexpected condition.");
vCurr = eIter->second;
}
}
void RetriangulateInteriorRemovalPolygon(int32_t vRemovalIndex,
std::vector<int32_t> const& polygon)
{
// Create a representation of 'polygon' that can be processed
// using a priority queue.
RPPolygon rpPolygon(polygon, mToLineWrapper);
auto WeightFunction = [this, &rpPolygon, vRemovalIndex](size_t i)
{
return ComputeWeight(i, vRemovalIndex, rpPolygon);
};
// Create a priority queue of vertices. Convex vertices have a
// finite and positive weight. Reflex vertices have a weight of
// +infinity.
MinHeap<size_t, RPWeight> earHeap(static_cast<int32_t>(polygon.size()));
RPWeight const posInfinity(RPWeight::Type::infinite);
RPWeight weight{};
for (size_t i = 0; i < polygon.size(); ++i)
{
RPVertex& vertex = rpPolygon.Vertex(i);
if (vertex.isConvex)
{
weight = WeightFunction(i);
}
else
{
weight = posInfinity;
}
vertex.record = earHeap.Insert(i, weight);
}
// Remove the finite-weight vertices from the priority queue,
// one at a time.
DoEarClipping(earHeap, WeightFunction, rpPolygon);
LogAssert(
earHeap.GetNumElements() == 0,
"Expecting the hole to be completely filled.");
}
void RetriangulateBoundaryRemovalPolygon(int32_t vRemovalIndex,
std::vector<int32_t> const& polygon)
{
size_t const numPolygon = polygon.size();
if (numPolygon >= 3)
{
// Create a representation of 'polygon' that can be processed
// using a priority queue.
RPPolygon rpPolygon(polygon, mToLineWrapper);
auto WeightFunction = [this, &rpPolygon, vRemovalIndex](size_t i)
{
return ComputeWeight(i, vRemovalIndex, rpPolygon);
};
auto ZeroWeightFunction = [](size_t)
{
return RPWeight(RPWeight::Type::finite);
};
// Create a priority queue of vertices. The removal index
// (polygon[0] = vRemovalIndex) and its two vertex neighbors
// have a weight of +infinity. Of the other vertices, convex
// vertices have a finite and positive weight and reflex
// vertices have a weight of +infinity.
MinHeap<size_t, RPWeight> earHeap(static_cast<int32_t>(polygon.size()));
RPWeight const rigid(RPWeight::Type::unmodifiable);
RPWeight const posInfinity(RPWeight::Type::infinite);
size_t iPrev = numPolygon - 2, iCurr = iPrev + 1, iNext = 0;
for (; iNext < numPolygon; iPrev = iCurr, iCurr = iNext, ++iNext)
{
RPVertex& vertexPrev = rpPolygon.Vertex(iPrev);
RPVertex& vertexCurr = rpPolygon.Vertex(iCurr);
RPVertex& vertexNext = rpPolygon.Vertex(iNext);
if (IsSupervertex(vertexPrev.vIndex) ||
IsSupervertex(vertexCurr.vIndex) ||
IsSupervertex(vertexNext.vIndex))
{
vertexCurr.record = earHeap.Insert(iCurr, rigid);
}
else
{
if (vertexCurr.isConvex)
{
vertexCurr.record = earHeap.Insert(iCurr,
WeightFunction(iCurr));
}
else
{
vertexCurr.record = earHeap.Insert(iCurr, posInfinity);
}
}
}
// Remove the finite-weight vertices from the priority queue,
// one at a time. This process fills in the subpolygon of the
// removal polygon that is contained by the Delaunay
// triangulation.
DoEarClipping(earHeap, WeightFunction, rpPolygon);
// Get the subpolygon of the removal polygon that is external
// to the Delaunay triangulation.
size_t numExternal = rpPolygon.GetNumActive();
std::vector<size_t> external(numExternal);
iCurr = rpPolygon.GetActive();
for (size_t i = 0; i < numExternal; ++i)
{
external[i] = iCurr;
rpPolygon.Classify(iCurr, mToLineWrapper);
iCurr = rpPolygon.Vertex(iCurr).iNext;
}
earHeap.Reset(static_cast<int32_t>(numExternal));
for (size_t i = 0; i < numExternal; ++i)
{
size_t index = external[i];
RPVertex& vertex = rpPolygon.Vertex(index);
if (IsSupervertex(vertex.vIndex))
{
vertex.record = earHeap.Insert(index, rigid);
}
else
{
if (vertex.isConvex)
{
vertex.record = earHeap.Insert(index,
ZeroWeightFunction(index));
}
else
{
vertex.record = earHeap.Insert(index, posInfinity);
}
}
}
// Remove the finite-weight vertices from the priority queue,
// one at a time. This process fills in a portion or all of
// the subpolygon of the removal polygon that is external to
// the Delaunay triangulation.
DoEarClipping(earHeap, ZeroWeightFunction, rpPolygon);
if (earHeap.GetNumElements() == 0)
{
// The external polygon contained only 1 supervertex.
return;
}
// The remaining external polygon is a triangle fan with
// 2 or 3 supervertices.
numExternal = rpPolygon.GetNumActive();
external.resize(numExternal);
iCurr = rpPolygon.GetActive();
for (size_t i = 0; i < numExternal; ++i)
{
external[i] = iCurr;
rpPolygon.Classify(iCurr, mToLineWrapper);
iCurr = rpPolygon.Vertex(iCurr).iNext;
}
earHeap.Reset(static_cast<int32_t>(numExternal));
iPrev = numExternal - 2;
iCurr = iPrev + 1;
iNext = 0;
for (; iNext < numExternal; iPrev = iCurr, iCurr = iNext, ++iNext)
{
size_t index = external[iCurr];
RPVertex& vertexPrev = rpPolygon.Vertex(external[iPrev]);
RPVertex& vertexCurr = rpPolygon.Vertex(index);
RPVertex& vertexNext = rpPolygon.Vertex(external[iNext]);
if (IsSupervertex(vertexCurr.vIndex))
{
if (IsDelaunayVertex(vertexPrev.vIndex) ||
IsDelaunayVertex(vertexNext.vIndex))
{
LogAssert(
vertexCurr.isConvex,
"Unexpected condition.");
vertexCurr.record = earHeap.Insert(index,
ZeroWeightFunction(index));
}
else
{
vertexCurr.record = earHeap.Insert(index, rigid);
}
}
else
{
vertexCurr.record = earHeap.Insert(index, posInfinity);
}
}
// Remove the finite-weight vertices from the priority queue,
// one at a time. This process fills in the triangle fan of
// the subpolygon of the removal polygon that is external to
// the Delaunay triangulation.
DoEarClipping(earHeap, ZeroWeightFunction, rpPolygon);
LogAssert(
earHeap.GetNumElements() == 0,
"Expecting the hole to be completely filled.");
}
else // numPolygon == 2
{
int32_t vOtherIndex;
if (polygon[0] == vRemovalIndex)
{
vOtherIndex = polygon[1];
}
else
{
vOtherIndex = polygon[0];
}
mGraph.Clear();
for (int32_t i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
{
auto inserted = mGraph.Insert(vOtherIndex, i0, i1);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
}
}
private:
// Support for queries associated with the mesh of Delaunay triangles.
mutable std::vector<std::array<size_t, 3>> mTriangles;
mutable std::vector<std::array<size_t, 3>> mAdjacencies;
mutable bool mTrianglesAndAdjacenciesNeedUpdate;
mutable Vector2<T> mQueryPoint;
mutable IRVector mIRQueryPoint;
void UpdateTrianglesAndAdjacencies() const
{
// Assign integer values to the triangles.
auto const& tmap = mGraph.GetTriangles();
if (tmap.size() == 0)
{
mTriangles.clear();
mAdjacencies.clear();
return;
}
std::unordered_map<Triangle*, size_t> permute;
permute[nullptr] = invalid;
size_t numTriangles = 0;
for (auto const& element : tmap)
{
if (IsDelaunayVertex(element.first.V[0]) &&
IsDelaunayVertex(element.first.V[1]) &&
IsDelaunayVertex(element.first.V[2]))
{
permute[element.second.get()] = numTriangles++;
}
else
{
permute[element.second.get()] = invalid;
}
}
mTriangles.resize(numTriangles);
mAdjacencies.resize(numTriangles);
size_t t = 0;
for (auto const& element : tmap)
{
auto const& tri = element.second;
if (permute[element.second.get()] != invalid)
{
for (size_t j = 0; j < 3; ++j)
{
mTriangles[t][j] = tri->V[j];
mAdjacencies[t][j] = permute[tri->T[j]];
}
++t;
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/MassSpringCurve.h | .h | 4,000 | 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/ParticleSystem.h>
namespace gte
{
template <int32_t N, typename Real>
class MassSpringCurve : public ParticleSystem<N, Real>
{
public:
// Construction and destruction. This class represents a set of N-1
// springs connecting N masses that lie on a curve.
virtual ~MassSpringCurve() = default;
MassSpringCurve(int32_t numParticles, Real step)
:
ParticleSystem<N, Real>(numParticles, step),
mConstant(static_cast<size_t>(numParticles) - 1),
mLength(static_cast<size_t>(numParticles) - 1)
{
std::fill(mConstant.begin(), mConstant.end(), (Real)0);
std::fill(mLength.begin(), mLength.end(), (Real)0);
}
// Member access. The parameters are spring constant and spring
// resting length.
inline int32_t GetNumSprings() const
{
return this->mNumParticles - 1;
}
inline void SetConstant(int32_t i, Real constant)
{
mConstant[i] = constant;
}
inline void SetLength(int32_t i, Real length)
{
mLength[i] = length;
}
inline Real const& GetConstant(int32_t i) const
{
return mConstant[i];
}
inline Real const& GetLength(int32_t i) const
{
return mLength[i];
}
// 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 endpoints of the curve of masses must be handled
// separately, because each has only one spring attached to it.
Vector<N, Real> acceleration = ExternalAcceleration(i, time, position, velocity);
Vector<N, Real> diff, force;
Real ratio;
if (i > 0)
{
int32_t iM1 = i - 1;
diff = position[iM1] - position[i];
ratio = mLength[iM1] / Length(diff);
force = mConstant[iM1] * ((Real)1 - ratio) * diff;
acceleration += this->mInvMass[i] * force;
}
int32_t iP1 = i + 1;
if (iP1 < this->mNumParticles)
{
diff = position[iP1] - position[i];
ratio = mLength[i] / Length(diff);
force = mConstant[i] * ((Real)1 - ratio) * diff;
acceleration += this->mInvMass[i] * force;
}
return acceleration;
}
std::vector<Real> mConstant, mLength;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/ConvexHull3.h | .h | 26,859 | 657 | // 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 convex hull of 3D points using incremental insertion. 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.
//
// TODO: A couple of potential optimizations need to be explored. The
// divide-and-conquer algorithm computes two convex hulls for a set of points.
// The two hulls are then merged into a single convex hull. The merge step
// is not the theoretical one that attempts to determine mutual visibility
// of the two hulls; rather, it combines the hulls into a single set of points
// and computes the convex hull of that set. This can be improved by using the
// left subhull in its current form and inserting points from the right subhull
// one at a time. It might be possible to insert points and stop the process
// when the partially merged polyhedron is the convex hull.
//
// The other optimization is based on profiling. The VETManifoldMesh memory
// management during insert/remove of vertices, edges and triangles suggests
// that a specialized VET data structure can be designed to avoid this cost.
//
// The main cost of the algorithm is testing which side of a plane a point is
// located. This test uses interval arithmetic to determine an exact sign,
// if possible. If that test fails, rational arithmetic is used. For typical
// datasets, the indeterminate sign from interval arithmetic happens rarely.
#include <Mathematics/ConvexHull2.h>
#include <Mathematics/SWInterval.h>
#include <Mathematics/Vector3.h>
#include <Mathematics/VETManifoldMesh.h>
#include <algorithm>
#include <numeric>
#include <queue>
#include <set>
#include <thread>
namespace gte
{
template <typename Real>
class ConvexHull3
{
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 ? 27 : 197;
using Rational = BSNumber<UIntegerFP32<NumWords>>;
// The class is a functor to support computing the convex hull of
// multiple data sets using the same class object.
ConvexHull3()
:
mPoints(nullptr),
mRPoints{},
mConverted{},
mDimension(0),
mVertices{},
mHull{},
mHullMesh{}
{
}
// Compute the exact convex hull using a blend of interval arithmetic
// and rational arithmetic. The code runs single-threaded when
// lgNumThreads = 0. It runs multithreaded when lgNumThreads > 0,
// where the number of threads is 2^{lgNumThreads} > 1.
void operator()(size_t numPoints, Vector3<Real> const* points,
size_t lgNumThreads)
{
LogAssert(numPoints > 0 && points != nullptr, "Invalid argument.");
// Allocate storage for any rational points that must be computed
// in the exact sign predicates. The rational points are memoized.
mPoints = points;
mRPoints.resize(numPoints);
mConverted.resize(numPoints);
std::fill(mConverted.begin(), mConverted.end(), 0);
// Sort all the points indirectly.
auto lessThanPoints = [this](size_t s0, size_t s1)
{
return mPoints[s0] < mPoints[s1];
};
auto equalPoints = [this](size_t s0, size_t s1)
{
return mPoints[s0] == mPoints[s1];
};
std::vector<size_t> sorted(numPoints);
std::iota(sorted.begin(), sorted.end(), 0);
std::sort(sorted.begin(), sorted.end(), lessThanPoints);
auto newEnd = std::unique(sorted.begin(), sorted.end(), equalPoints);
sorted.erase(newEnd, sorted.end());
if (lgNumThreads > 0)
{
size_t numThreads = (static_cast<size_t>(1) << lgNumThreads);
size_t load = sorted.size() / numThreads;
std::vector<size_t> inNumSorted(numThreads);
std::vector<size_t*> inSorted(numThreads);
std::vector<std::vector<size_t>> outVertices(numThreads);
std::vector<std::thread> process(numThreads);
inNumSorted.back() = sorted.size();
inSorted.front() = sorted.data();
for (size_t i0 = 0, i1 = 1; i1 < numThreads; i0 = i1++)
{
inNumSorted[i0] = load;
inNumSorted.back() -= load;
inSorted[i1] = inSorted[i0] + load;
}
while (numThreads > 1)
{
for (size_t i = 0; i < numThreads; ++i)
{
process[i] = std::thread(
[this, i, &inNumSorted, &inSorted, &outVertices]()
{
size_t dimension = 0;
std::vector<size_t> hull;
VETManifoldMesh hullMesh;
ComputeHull(inNumSorted[i], inSorted[i], dimension,
outVertices[i], hull, hullMesh);
});
}
numThreads /= 2;
auto target = sorted.begin();
inSorted[0] = sorted.data();
for (size_t i = 0, k = 0; i < numThreads; ++i)
{
process[2 * i].join();
process[2 * i + 1].join();
inNumSorted[i] = 0;
auto begin = target;
for (size_t j = 0; j < 2; ++j, ++k)
{
size_t numVertices = outVertices[k].size();
inNumSorted[i] += numVertices;
std::copy(outVertices[k].begin(), outVertices[k].end(), target);
target += numVertices;
}
inSorted[i + 1] = inSorted[i] + inNumSorted[i];
std::sort(begin, target, lessThanPoints);
}
}
ComputeHull(inNumSorted[0], inSorted[0], mDimension, mVertices,
mHull, mHullMesh);
}
else
{
ComputeHull(sorted.size(), sorted.data(), mDimension, mVertices,
mHull, mHullMesh);
}
}
void operator()(std::vector<Vector3<Real>> const& points, size_t lgNumThreads)
{
operator()(points.size(), points.data(), lgNumThreads);
}
// The dimension is 0 (hull is a single point), 1 (hull is a line
// segment), 2 (hull is a convex polygon in 3D) or 3 (hull is a convex
// polyhedron).
inline size_t GetDimension() const
{
return mDimension;
}
// Get the indices into the input 'points[]' that correspond to hull
// vertices.
inline std::vector<size_t> const& GetVertices() const
{
return mVertices;
}
// Get the indices into the input 'points[]' that correspond to hull
// vertices. The returned array is organized according to the hull
// dimension.
// 0: The hull is a single point. The returned array has size 1 with
// index corresponding to that point.
// 1: The hull is a line segment. The returned array has size 2 with
// indices corresponding to the segment endpoints.
// 2: The hull is a convex polygon in 3D. The returned array has
// size N with indices corresponding to the polygon vertices.
// The vertices are ordered.
// 3: The hull is a convex polyhedron. The returned array has T
// triples of indices, each triple corresponding to a triangle
// face of the hull. The face vertices are counterclockwise when
// viewed by an observer outside the polyhedron. It is possible
// that some triangle faces are coplanar.
// The number of vertices and triangles can vary depending on the
// number of threads used for computation. This is not an error. For
// example, when running with N threads it is possible to have a
// convex quadrilateral face formed by 2 coplanar triangles {v0,v1,v2}
// and {v0,v2,v3}. When running with M threads, it is possible that
// the same convex quadrilateral face is formed by 4 coplanar triangles
// {v0,v1,v2}, {v1,v2,v4}, {v2,v3,v4} and {v3,v0,v4}, where the
// vertices v0, v2 and v4 are colinear. In both cases, if V is the
// number of vertices and T is the number of triangles, then the
// number of edges is E = T/2 and Euler's formula is satisfied:
// V - E + T = 2.
inline std::vector<size_t> const& GetHull() const
{
return mHull;
}
// Get the hull mesh, which is valid only when the dimension is 3.
// This allows access to the graph of vertices, edges and triangles
// of the convex (polyhedron) hull.
inline VETManifoldMesh const& GetHullMesh() const
{
return mHullMesh;
}
private:
void ComputeHull(size_t numSorted, size_t* sorted, size_t& dimension,
std::vector<size_t>& vertices, std::vector<size_t>& hull,
VETManifoldMesh& hullMesh)
{
dimension = 0;
vertices.clear();
hull.reserve(numSorted);
hull.clear();
hullMesh.Clear();
size_t current = 0;
if (Hull0(hull, numSorted, sorted, dimension, current))
{
vertices.resize(1);
vertices[0] = hull[0];
return;
}
if (Hull1(hull, numSorted, sorted, dimension, current))
{
vertices.resize(2);
vertices[0] = hull[0];
vertices[1] = hull[1];
return;
}
if (Hull2(hull, numSorted, sorted, dimension, current))
{
vertices.resize(hull.size());
std::copy(hull.begin(), hull.end(), vertices.begin());
return;
}
Hull3(hull, numSorted, sorted, hullMesh, current);
auto const& vMap = hullMesh.GetVertices();
vertices.resize(vMap.size());
size_t index = 0;
for (auto const& element : vMap)
{
vertices[index++] = element.first;
}
auto const& tMap = hullMesh.GetTriangles();
hull.resize(3 * tMap.size());
index = 0;
for (auto const& element : tMap)
{
hull[index++] = element.first.V[0];
hull[index++] = element.first.V[1];
hull[index++] = element.first.V[2];
}
}
// Support for computing a 0-dimensional convex hull.
bool Hull0(std::vector<size_t>& hull, size_t numSorted, size_t* sorted,
size_t& dimension, size_t& current)
{
hull.push_back(sorted[current]); // hull[0]
for (++current; current < numSorted; ++current)
{
if (!Colocated(hull[0], sorted[current]))
{
dimension = 1;
break;
}
}
return dimension == 0;
}
// Support for computing a 1-dimensional convex hull.
bool Hull1(std::vector<size_t>& hull, size_t numSorted, size_t* sorted,
size_t& dimension, size_t& current)
{
hull.push_back(sorted[current]); // hull[1]
for (++current; current < numSorted; ++current)
{
if (!Colinear(hull[0], hull[1], sorted[current]))
{
dimension = 2;
break;
}
hull.push_back(sorted[current]);
}
if (hull.size() > 2)
{
// Sort the points and choose the extreme points as the
// endpoints of the line segment that is the convex hull.
std::sort(hull.begin(), hull.end(),
[this](size_t v0, size_t v1)
{
return mPoints[v0] < mPoints[v1];
});
size_t hmin = hull.front();
size_t hmax = hull.back();
hull.clear();
hull.push_back(hmin);
hull.push_back(hmax);
}
return dimension == 1;
}
// Support for computing a 2-dimensional convex hull.
bool Hull2(std::vector<size_t>& hull, size_t numSorted, size_t* sorted,
size_t& dimension, size_t& current)
{
hull.push_back(sorted[current]); // hull[2]
for (++current; current < numSorted; ++current)
{
if (ToPlane(hull[0], hull[1], hull[2], sorted[current]) != 0)
{
dimension = 3;
break;
}
hull.push_back(sorted[current]);
}
if (hull.size() > 3)
{
// Compute the planar convex hull of the points. The coplanar
// points are projected onto a 2D plane determined by the
// maximum absolute component of the normal of the first
// triangle. The extreme points of the projected hull generate
// the extreme points of the planar hull in 3D.
auto const& rV0 = GetRationalPoint(hull[0]);
auto const& rV1 = GetRationalPoint(hull[1]);
auto const& rV2 = GetRationalPoint(hull[2]);
auto const rDiff1 = rV1 - rV0;
auto const rDiff2 = rV2 - rV0;
auto rNormal = Cross(rDiff1, rDiff2);
// The signs are used to select 2 of the 3 point components so
// that when the planar hull is viewed from the side of the
// plane to which rNormal is directed, the triangles are
// counterclockwise ordered.
std::array<int32_t, 3> sign{};
for (int32_t i = 0; i < 3; ++i)
{
sign[i] = rNormal[i].GetSign();
rNormal[i].SetSign(std::abs(sign[i]));
};
std::pair<int32_t, int32_t> c;
if (rNormal[0] > rNormal[1])
{
if (rNormal[0] > rNormal[2])
{
c = (sign[0] > 0 ? std::make_pair(1, 2) : std::make_pair(2, 1));
}
else
{
c = (sign[2] > 0 ? std::make_pair(0, 1) : std::make_pair(1, 0));
}
}
else
{
if (rNormal[1] > rNormal[2])
{
c = (sign[1] > 0 ? std::make_pair(2, 0) : std::make_pair(0, 2));
}
else
{
c = (sign[2] > 0 ? std::make_pair(0, 1) : std::make_pair(1, 0));
}
}
std::vector<Vector2<Real>> projections(hull.size());
for (size_t i = 0; i < projections.size(); ++i)
{
size_t h = hull[i];
projections[i][0] = mPoints[h][c.first];
projections[i][1] = mPoints[h][c.second];
}
ConvexHull2<Real> ch2;
ch2((int32_t)projections.size(), projections.data(), static_cast<Real>(0));
auto const& hull2 = ch2.GetHull();
std::vector<size_t> tempHull(hull2.size());
for (size_t i = 0; i < hull2.size(); ++i)
{
tempHull[i] = hull[static_cast<size_t>(hull2[i])];
}
hull.clear();
for (size_t i = 0; i < hull2.size(); ++i)
{
hull.push_back(tempHull[i]);
}
}
return dimension == 2;
}
// Support for computing a 3-dimensional convex hull.
void Hull3(std::vector<size_t>& hull, size_t numSorted, size_t* sorted,
VETManifoldMesh& hullMesh, size_t& current)
{
using TrianglePtr = VETManifoldMesh::Triangle*;
// The hull points previous to the current one are coplanar and
// are the vertices of a convex polygon. To initialize the 3D
// hull, use triangles from a triangle fan of the convex polygon
// and use triangles connecting the current point to the edges
// of the convex polygon. The vertex ordering of these triangles
// depends on whether sorted[current] is on the positive or
// negative side of the plane determined by hull[0], hull[1] and
// hull[2].
int32_t sign = ToPlane(hull[0], hull[1], hull[2], sorted[current]);
int32_t h0, h1, h2;
if (sign > 0)
{
h0 = static_cast<int32_t>(hull[0]);
for (size_t i1 = 1, i2 = 2; i2 < hull.size(); i1 = i2++)
{
h1 = static_cast<int32_t>(hull[i1]);
h2 = static_cast<int32_t>(hull[i2]);
auto inserted = hullMesh.Insert(h0, h2, h1);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
h0 = static_cast<int32_t>(sorted[current]);
for (size_t i1 = hull.size() - 1, i2 = 0; i2 < hull.size(); i1 = i2++)
{
h1 = static_cast<int32_t>(hull[i1]);
h2 = static_cast<int32_t>(hull[i2]);
auto inserted = hullMesh.Insert(h0, h1, h2);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
}
else
{
h0 = static_cast<int32_t>(hull[0]);
for (size_t i1 = 1, i2 = 2; i2 < hull.size(); i1 = i2++)
{
h1 = static_cast<int32_t>(hull[i1]);
h2 = static_cast<int32_t>(hull[i2]);
auto inserted = hullMesh.Insert(h0, h1, h2);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
h0 = static_cast<int32_t>(sorted[current]);
for (size_t i1 = hull.size() - 1, i2 = 0; i2 < hull.size(); i1 = i2++)
{
h1 = static_cast<int32_t>(hull[i1]);
h2 = static_cast<int32_t>(hull[i2]);
auto inserted = hullMesh.Insert(h0, h2, h1);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
}
// The hull is now maintained in hullMesh, so there is no need
// to add members to hull. At the time the full hull is known,
// hull will be assigned the triangle indices.
std::vector<std::array<int32_t, 2>> terminator;
for (++current; current < numSorted; ++current)
{
// The index h0 refers to the previously inserted hull point.
// The index h1 refers to the current point to be inserted
// into the hull.
auto const& vMap = hullMesh.GetVertices();
auto vIter = vMap.find(h0);
LogAssert(vIter != vMap.end(), "Unexpected condition.");
h1 = static_cast<int32_t>(sorted[current]);
// The sorting guarantees that the point at h0 is visible to
// the point at h1. Find the triangles that share h0 and are
// visible to h1
std::queue<TrianglePtr> visible;
std::set<TrianglePtr> visited;
for (auto const& tri : vIter->second->TAdjacent)
{
sign = ToPlane(tri->V[0], tri->V[1], tri->V[2], h1);
if (sign > 0)
{
visible.push(tri);
visited.insert(tri);
break;
}
}
LogAssert(visible.size() > 0, "Unexpected condition.");
// Remove the connected component of visible triangles. Save
// the terminator edges for insertion of the new visible set
// of triangles.
terminator.clear();
while (visible.size() > 0)
{
TrianglePtr tri = visible.front();
visible.pop();
for (size_t i = 0; i < 3; ++i)
{
auto adj = tri->T[i];
if (adj)
{
if (ToPlane(adj->V[0], adj->V[1], adj->V[2], h1) <= 0)
{
// The shared edge of tri and adj is a
// terminator.
terminator.push_back({ tri->V[i], tri->V[(i + 1) % 3] });
}
else
{
if (visited.find(adj) == visited.end())
{
visible.push(adj);
visited.insert(adj);
}
}
}
}
visited.erase(tri);
bool removed = hullMesh.Remove(tri->V[0], tri->V[1], tri->V[2]);
LogAssert(
removed,
"Unexpected removal failure.");
}
// Insert the new hull triangles.
for (auto const& edge : terminator)
{
auto inserted = hullMesh.Insert(edge[0], edge[1], h1);
LogAssert(
inserted != nullptr,
"Unexpected insertion failure.");
}
// The current index h1 becomes the previous index h0 for the
// next pass of the 'current' loop.
h0 = h1;
}
}
// Memoized access to the rational representation of the points.
Vector3<Rational> const& GetRationalPoint(size_t index)
{
if (mConverted[index] == 0)
{
mConverted[index] = 1;
for (int32_t i = 0; i < 3; ++i)
{
mRPoints[index][i] = mPoints[index][i];
}
}
return mRPoints[index];
}
bool Colocated(size_t v0, size_t v1)
{
auto const& r0 = GetRationalPoint(v0);
auto const& r1 = GetRationalPoint(v1);
return r0 == r1;
}
bool Colinear(size_t v0, size_t v1, size_t v2)
{
auto const& rvec0 = GetRationalPoint(v0);
auto const& rvec1 = GetRationalPoint(v1);
auto const& rvec2 = GetRationalPoint(v2);
auto const rdiff1 = rvec1 - rvec0;
auto const rdiff2 = rvec2 - rvec0;
auto const rcross = Cross(rdiff1, rdiff2);
return rcross[0].GetSign() == 0
&& rcross[1].GetSign() == 0
&& rcross[2].GetSign() == 0;
}
// For a plane with origin V0 and normal N = Cross(V1-V0,V2-V0),
// ToPlane returns
// +1, V3 on positive side of plane (side to which N points)
// -1, V3 on negative side of plane (side to which -N points)
// 0, V3 on the plane
int32_t ToPlane(size_t v0, size_t v1, size_t v2, size_t v3)
{
using SInterval = SWInterval<Real>;
using SVector3 = Vector3<SInterval>;
// Attempt to classify the sign using interval arithmetic.
SVector3 const s0{ mPoints[v0][0], mPoints[v0][1], mPoints[v0][2] };
SVector3 const s1{ mPoints[v1][0], mPoints[v1][1], mPoints[v1][2] };
SVector3 const s2{ mPoints[v2][0], mPoints[v2][1], mPoints[v2][2] };
SVector3 const s3{ mPoints[v3][0], mPoints[v3][1], mPoints[v3][2] };
auto const sDiff1 = s1 - s0;
auto const sDiff2 = s2 - s0;
auto const sDiff3 = s3 - s0;
auto const sDet = DotCross(sDiff1, sDiff2, sDiff3);
if (sDet[0] > 0)
{
return +1;
}
if (sDet[1] < 0)
{
return -1;
}
// The sign is indeterminate using interval arithmetic.
auto const& r0 = GetRationalPoint(v0);
auto const& r1 = GetRationalPoint(v1);
auto const& r2 = GetRationalPoint(v2);
auto const& r3 = GetRationalPoint(v3);
auto const rDiff1 = r1 - r0;
auto const rDiff2 = r2 - r0;
auto const rDiff3 = r3 - r0;
auto const rDet = DotCross(rDiff1, rDiff2, rDiff3);
return rDet.GetSign();
}
private:
// A blend of interval arithmetic and exact arithmetic is used to
// ensure correctness.
Vector3<Real> const* mPoints;
std::vector<Vector3<Rational>> mRPoints;
std::vector<uint32_t> mConverted;
// The output data.
size_t mDimension;
std::vector<size_t> mVertices;
std::vector<size_t> mHull;
VETManifoldMesh mHullMesh;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/extern/GTE/Mathematics/IntrHalfspace3Segment3.h | .h | 4,807 | 157 | // 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/Segment.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>, Segment3<T>>
{
public:
struct Result
{
Result()
:
intersect(false)
{
}
bool intersect;
};
Result operator()(Halfspace3<T> const& halfspace, Segment3<T> const& segment)
{
Result result{};
// Project the segment endpoints onto the normal line. The plane
// of the halfspace occurs at the origin (zero) of the normal
// line.
std::array<T, 2> s{};
for (int32_t i = 0; i < 2; ++i)
{
s[i] = Dot(halfspace.normal, segment.p[i]) - halfspace.constant;
}
// The segment and halfspace intersect when the projection
// interval maximum is nonnegative.
result.intersect = (std::max(s[0], s[1]) >= (T)0);
return result;
}
};
template <typename T>
class FIQuery<T, Halfspace3<T>, Segment3<T>>
{
public:
struct Result
{
Result()
:
intersect(false),
numPoints(0),
point{ Vector3<T>::Zero(), Vector3<T>::Zero() }
{
}
bool intersect;
// The segment is clipped against the plane defining the
// halfspace. The 'numPoints' is either 0 (no intersection),
// 1 (point), or 2 (segment).
int32_t numPoints;
std::array<Vector3<T>, 2> point;
};
Result operator()(Halfspace3<T> const& halfspace, Segment3<T> const& segment)
{
// Determine on which side of the plane the endpoints lie. The
// table of possibilities is listed next with n = numNegative,
// p = numPositive, and z = numZero.
//
// n p z intersection
// -------------------------
// 0 2 0 segment (original)
// 0 1 1 segment (original)
// 0 0 2 segment (original)
// 1 1 0 segment (clipped)
// 1 0 1 point (endpoint)
// 2 0 0 none
std::array<T, 2> s{};
int32_t numPositive = 0, numNegative = 0, numZero = 0;
for (int32_t i = 0; i < 2; ++i)
{
s[i] = Dot(halfspace.normal, segment.p[i]) - halfspace.constant;
if (s[i] > (T)0)
{
++numPositive;
}
else if (s[i] < (T)0)
{
++numNegative;
}
else
{
++numZero;
}
}
Result result{};
if (numNegative == 0)
{
// The segment is in the halfspace.
result.intersect = true;
result.numPoints = 2;
result.point[0] = segment.p[0];
result.point[1] = segment.p[1];
}
else if (numNegative == 1)
{
result.intersect = true;
result.numPoints = 1;
if (numPositive == 1)
{
// The segment is intersected at an interior point.
result.point[0] = segment.p[0] +
(s[0] / (s[0] - s[1])) * (segment.p[1] - segment.p[0]);
}
else // numZero = 1
{
// One segment endpoint is on the plane.
if (s[0] == (T)0)
{
result.point[0] = segment.p[0];
}
else
{
result.point[0] = segment.p[1];
}
}
}
else // numNegative == 2
{
// The segment is outside the halfspace. (numNegative == 2)
result.intersect = false;
result.numPoints = 0;
}
return result;
}
};
}
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.