Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
transform.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
13
14#include <Eigen/Eigenvalues>
15
16#include <cassert>
17
18namespace momentum {
19
20template <typename T>
22 return TransformT<T>(Vector3<T>::Zero(), rotation_in, T(1));
23}
24
25template <typename T>
27 return TransformT<T>(translation_in, Quaternion<T>::Identity(), T(1));
28}
29
30template <typename T>
34
35template <typename T>
37 TransformT<T> result;
38
39 if (translation) {
40 result.translation.setRandom();
41 }
42
43 if (rotation) {
45 }
46
47 if (scale) {
48 result.scale = uniform<T>(0.1, 2);
49 }
50
51 return result;
52}
53
54template <typename T>
56 return fromMatrix(other.matrix());
57}
58
59template <typename T>
62 result.translation = other.template topRightCorner<3, 1>();
63 // Recover scale from the norm of column 0. This relies on the upper-left 3x3 being
64 // s*R where R is orthonormal (uniform scale, no shear, no reflection). For non-uniform
65 // scaling, shear, or negative determinant, the resulting rotation will be incorrect.
66 const auto& scaledR = other.template topLeftCorner<3, 3>();
67 result.scale = scaledR.col(0).norm();
68 // Guard against near-zero or near-infinite scale before dividing.
69 MT_CHECK(result.scale >= Eps<T>(), "Scale is too small: {}", result.scale);
70 MT_CHECK(result.scale < T(1) / Eps<T>(), "Inverse scale is too small: {}", result.scale);
71 // TODO: Detect non-uniform scale / shear / reflection (e.g. via SVD) and either error
72 // or project to the closest rigid+uniform-scale transform; current quaternion ctor
73 // silently ignores non-orthonormal input.
74 result.rotation = scaledR / result.scale;
75 return result;
76}
77
78template <typename T>
80 Affine3<T> xf;
81 xf.makeAffine();
82 xf.linear().noalias() = rotation.toRotationMatrix() * scale;
83 xf.translation() = translation;
84 return xf;
85}
86
87template <typename T>
89 return rotation * vec;
90}
91
92template <typename T>
94 // (translate(t) * rotation(R) * scale(s)).inv() =
95 // scale(s).inv() * rotation(R).inv() * translate(t).inv()
96 // = scale(1/s) * rotation(invR) * translate(-t)
97 // = translate(-invR*s*t) * rotation(invR) * scale(1/s)
98 const Quaternion<T> invRot = rotation.inverse();
99 const T invScale = T(1) / scale;
100 return TransformT<T>(-invScale * (invRot * translation), invRot, invScale);
101}
102
103template <typename T>
105 momentum::span<const TransformT<T>> transforms,
106 momentum::span<const T> weights) {
107 assert(transforms.size() == weights.size());
108 if (transforms.empty()) {
109 return TransformT<T>();
110 }
111
112 // Find average rotation by means described in
113 // https://stackoverflow.com/questions/12374087/average-of-multiple-quaternions
114 // http://www.acsu.buffalo.edu/~johnc/ave_quat07.pdf
115 //
116 // i.e. Stack quaternion coeffs in Q, compute M = Q^T x Q, and yield the eigenvector corresponding
117 // to the largest eigenvalue as the average rotation. This handles the q vs -q double-cover
118 // ambiguity correctly (since q*q^T == (-q)*(-q)^T) without needing manual sign alignment.
120
121 const auto n = transforms.size();
122 for (size_t i = 0; i < n; ++i) {
123 const auto& q = transforms[i].rotation;
124 QtQ += weights[i] * (q.coeffs() * q.coeffs().transpose());
125 }
126
127 const Eigen::SelfAdjointEigenSolver<Matrix4<T>> eigDecomp(QtQ);
128 assert(
129 eigDecomp.eigenvalues()[2] <=
130 eigDecomp.eigenvalues()[3]); // Eigen is supposed to sort smallest to largest.
131 Vector4<T> avgcoeffs = eigDecomp.eigenvectors().col(3);
132 assert(std::abs(avgcoeffs.norm() - 1) < 1e-4); // should be guaranteed by the eigensolver.
133 Quaternion<T> rot(avgcoeffs);
134
136 T weightSum = 0;
137 T scale = 0;
138 for (size_t i = 0; i < n; ++i) {
139 pos += weights[i] * transforms[i].translation;
140 scale += weights[i] * transforms[i].scale;
141 weightSum += weights[i];
142 }
143
144 // TODO: When weightSum is zero (e.g. all weights zero, or weights cancel), pos and scale
145 // are left at 0 which produces a degenerate transform; consider returning identity or
146 // the first input instead.
147 if (weightSum != 0) {
148 pos /= weightSum;
149 scale /= weightSum;
150 }
151
152 return TransformT<T>{pos, rot, scale};
153}
154
155template <typename T>
156TransformT<T> slerp(const TransformT<T>& t1, const TransformT<T>& t2, T weight) {
157 return TransformT<T>(
158 t1.translation + weight * (t2.translation - t1.translation),
159 t1.rotation.slerp(weight, t2.rotation),
160 t1.scale + weight * (t2.scale - t1.scale));
161}
162
164 momentum::span<const TransformT<float>> transforms,
167 momentum::span<const TransformT<double>> transforms,
169
172
173template struct TransformT<float>;
174template struct TransformT<double>;
175
176} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Vector< T, 4 > Vector4
Definition types.h:238
constexpr T Eps(T FloatEps=T(1e-7), T DoubleEps=T(1e-16))
Returns a type-appropriate tolerance/epsilon value.
Definition constants.h:30
T uniform(const T &min, const T &max)
Convenience wrappers that forward to Random<>::GetSingleton().
Definition random-inl.h:326
TransformT< T > slerp(const TransformT< T > &t1, const TransformT< T > &t2, T weight)
Spherical linear interpolation between two transforms.
Eigen::Matrix< T, 4, 4 > Matrix4
Definition types.h:98
Eigen::Quaternion< T > Quaternion
Unit quaternion representing a 3D rotation.
Definition types.h:385
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Definition span_compat.h:54
Vector< T, 3 > Vector3
Definition types.h:236
TransformT< T > blendTransforms(momentum::span< const TransformT< T > > transforms, momentum::span< const T > weights)
Weighted blend of transforms: rotations are blended via averaged quaternions, translations and scales...
Eigen::Transform< T, 3, Eigen::Affine > Affine3
3D affine transform (linear part + translation).
Definition types.h:404
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36
Vector3< T > rotate(const Vector3< T > &vec) const
Applies only the rotation to a direction vector (translation and scale are ignored).
Definition transform.cpp:88
static TransformT< T > makeRotation(const Quaternion< T > &rotation_in)
Creates a transform with the given rotation, identity translation, and unit scale.
Definition transform.cpp:21
Affine3< T > toAffine3() const
Definition transform.cpp:79
T scale
Uniform scale factor applied before rotation and translation.
Definition transform.h:42
static TransformT< T > makeRandom(bool translation=true, bool rotation=true, bool scale=true)
Creates a random transform.
Definition transform.cpp:36
static TransformT< T > fromMatrix(const Matrix4< T > &other)
Decomposes a 4x4 homogeneous matrix into rotation, translation, and uniform scale.
Definition transform.cpp:60
static TransformT< T > fromAffine3(const Affine3< T > &other)
Decomposes an Eigen::Affine3 into rotation, translation, and uniform scale.
Definition transform.cpp:55
Vector3< T > translation
Definition transform.h:40
TransformT()
Creates the identity transform (zero translation, identity rotation, unit scale).
Definition transform.h:74
static TransformT< T > makeTranslation(const Vector3< T > &translation_in)
Creates a transform with the given translation, identity rotation, and unit scale.
Definition transform.cpp:26
Quaternion< T > rotation
Unit quaternion encoding the rotation.
Definition transform.h:39
static TransformT< T > makeScale(const T &scale_in)
Creates a transform with the given scale, identity rotation, and zero translation.
Definition transform.cpp:31
TransformT< T > inverse() const
Returns the inverse transform such that (*this) * inverse() == identity.
Definition transform.cpp:93