Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
skeleton_state.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
15
16#include <algorithm>
17#include <numeric>
18
19namespace momentum {
20
21template <typename T>
23 const JointParametersT<T>& parameters,
24 const Skeleton& referenceSkeleton,
25 bool computeDeriv)
26 : jointParameters(parameters), jointState(referenceSkeleton.joints.size()) {
27 set(referenceSkeleton, computeDeriv);
28}
29
30template <typename T>
32 JointParametersT<T>&& parameters,
33 const Skeleton& referenceSkeleton,
34 bool computeDeriv)
35 : jointParameters(std::move(parameters)), jointState(referenceSkeleton.joints.size()) {
36 set(referenceSkeleton, computeDeriv);
37}
38
39template <typename T>
40template <typename T2>
42 : jointParameters(rhs.jointParameters.template cast<T>()), jointState(rhs.jointState.size()) {
43 copy(rhs);
44}
45
46template <typename T>
47template <typename T2>
51 jointState.resize(rhs.jointState.size());
52 copy(rhs);
53}
54
55template <typename T>
56template <typename T2>
57void SkeletonStateT<T>::copy(const SkeletonStateT<T2>& rhs) {
59 for (size_t iJoint = 0; iJoint < jointState.size(); ++iJoint) {
60 jointState[iJoint].set(rhs.jointState[iJoint]);
61 }
62}
63
64template <typename T>
66 const JointParametersT<T>& parameters,
67 const Skeleton& referenceSkeleton,
68 bool computeDeriv) {
70 this->jointParameters = parameters;
71 this->jointState.resize(referenceSkeleton.joints.size());
72 set(referenceSkeleton, computeDeriv);
73}
74
75template <typename T>
77 JointParametersT<T>&& parameters,
78 const Skeleton& referenceSkeleton,
79 bool computeDeriv) {
81 this->jointParameters = std::move(parameters);
82 this->jointState.resize(referenceSkeleton.joints.size());
83 set(referenceSkeleton, computeDeriv);
84}
85
86template <typename T>
87void SkeletonStateT<T>::set(const Skeleton& referenceSkeleton, bool computeDeriv) {
89 const JointListT<T>& joints = ::momentum::cast<T>(referenceSkeleton.joints);
90 const size_t numJoints = joints.size();
91
93 jointParameters.size() == static_cast<Eigen::Index>(numJoints * kParametersPerJoint),
94 "Unexpected joint parameter size. Expected '{}' (# of joints '{}' X kParametersPerJoint '{}') but got '{}'.",
95 numJoints * kParametersPerJoint,
96 numJoints,
98 jointParameters.size());
99
100 // IMPORTANT: this single forward pass assumes parents always precede their children in the
101 // joint list (i.e. the skeleton is topologically sorted). Each child reads its parent's
102 // already-computed JointState, so violating that ordering will silently propagate stale
103 // parent transforms into children.
104 for (size_t jointID = 0; jointID < numJoints; jointID++) {
105 const Eigen::Index parameterOffset = jointID * kParametersPerJoint;
106 const JointT<T>& joint = joints[jointID];
107
108 if (joint.parent == kInvalidIndex) {
109 jointState[jointID].set(
110 joint, jointParameters.v.template middleRows<7>(parameterOffset), nullptr, computeDeriv);
111 } else {
112 jointState[jointID].set(
113 joint,
114 jointParameters.v.template middleRows<7>(parameterOffset),
115 &jointState[joint.parent],
116 computeDeriv);
117 }
118 }
119
120 MT_CHECK(jointState.size() == numJoints, "{} is not {}", jointState.size(), numJoints);
121}
122
123template <typename T>
125 TransformListT<T> result;
126 result.reserve(jointState.size());
127 for (const auto& js : jointState) {
128 result.push_back(js.transform);
129 }
130 return result;
131}
132
133template <typename T>
135 const SkeletonStateT<T>& state1,
136 const SkeletonStateT<T>& state2) {
137 MT_CHECK(
138 state1.jointParameters.size() == state2.jointParameters.size(),
139 "{} is not {}",
140 state1.jointParameters.size(),
141 state2.jointParameters.size());
142 MT_CHECK(
143 state1.jointState.size() == state2.jointState.size(),
144 "{} is not {}",
145 state1.jointState.size(),
146 state2.jointState.size());
147
148 StateSimilarity result;
149 result.positionError.resize(state1.jointState.size());
150 result.orientationError.resize(state1.jointState.size());
151
152 // Per-joint position/orientation error in world space. Quaternion dot is clamped to [-1, 1]
153 // to guard acos against numerical drift just outside the valid domain, and the sign flip on
154 // negative dot picks the shorter of the two equivalent quaternion representations (q and -q
155 // encode the same rotation) so the angular error stays in [0, pi].
156 for (size_t i = 0; i < state1.jointState.size(); i++) {
157 result.positionError[i] =
158 (state1.jointState[i].translation() - state2.jointState[i].translation()).norm();
159 const T dot = std::min(
160 std::max(
161 state1.jointState[i].rotation().normalized().dot(
162 state2.jointState[i].rotation().normalized()),
163 T(-1.0)),
164 T(1.0));
165 const T sgn = dot < T(0) ? T(-1) : T(1);
166 result.orientationError[i] = gsl::narrow_cast<float>(T(2) * std::acos(sgn * dot));
167 }
168
169 const auto rootMeanSquare = [](const VectorXf& errors) {
170 return std::sqrt(errors.squaredNorm() / static_cast<float>(errors.size()));
171 };
172 result.positionRMSE = rootMeanSquare(result.positionError);
173 result.orientationRMSE = rootMeanSquare(result.orientationError);
174 result.positionMax = result.positionError.maxCoeff();
175 result.orientationMax = result.orientationError.maxCoeff();
176
177 return result;
178}
179
180// Because the skeleton is topologically sorted (parent index < child index), the lowest common
181// ancestor of A and B can be found by repeatedly walking the joint with the larger index up to
182// its parent until both pointers meet. We accumulate the local-transform chain on each side,
183// so the final result composes A->ancestor and ancestor->B without ever inverting world-space
184// transforms.
185template <typename T>
187 size_t jointA,
188 size_t jointB,
189 const Skeleton& referenceSkeleton,
190 const SkeletonStateT<T>& skelState) {
191 size_t ancestorA = jointA;
192 size_t ancestorB = jointB;
193
194 TransformT<T> B_to_ancestorB;
195 TransformT<T> A_to_ancestorA;
196
197 while (true) {
198 // kInvalidIndex represents "world" and is treated as the lowest index, since world is the
199 // topological ancestor of every joint.
200 if (ancestorB != kInvalidIndex && (ancestorA == kInvalidIndex || ancestorA < ancestorB)) {
201 // ancestorB has the larger index, so it cannot be an ancestor of ancestorA -- walk B up.
202 B_to_ancestorB = skelState.jointState[ancestorB].localTransform * B_to_ancestorB;
203 if (ancestorB < referenceSkeleton.joints.size()) {
204 ancestorB = referenceSkeleton.joints[ancestorB].parent;
205 } else {
206 break;
207 }
208 } else if (
209 ancestorA != kInvalidIndex && (ancestorB == kInvalidIndex || ancestorB < ancestorA)) {
210 A_to_ancestorA = skelState.jointState[ancestorA].localTransform * A_to_ancestorA;
211 if (ancestorA < referenceSkeleton.joints.size()) {
212 ancestorA = referenceSkeleton.joints[ancestorA].parent;
213 } else {
214 break;
215 }
216 } else {
217 // Indices are equal -- we've reached the common ancestor.
218 break;
219 }
220 }
221
222 MT_CHECK(ancestorA == ancestorB, "{} is not {}", ancestorA, ancestorB);
223 return B_to_ancestorB.inverse() * A_to_ancestorA;
224}
225
226namespace {
227
228template <typename T>
229[[nodiscard]] Eigen::Vector<T, kParametersPerJoint> localTransformToJointParameters(
230 const Joint& joint,
231 const TransformT<T>& localTransform) {
232 Eigen::Vector<T, kParametersPerJoint> result = Eigen::Vector<T, kParametersPerJoint>::Zero();
233 result.template segment<3>(0) =
234 localTransform.translation - joint.translationOffset.template cast<T>();
235
236 const Eigen::Quaternion<T> localRotation =
237 joint.preRotation.template cast<T>().inverse() * localTransform.rotation;
238 result.template segment<3>(3) = quaternionToEuler(localRotation);
239 result(6) = std::log2(localTransform.scale);
240 return result;
241}
242
243} // namespace
244
245template <typename T>
247 const SkeletonStateT<T>& state,
248 const Skeleton& skeleton) {
249 JointParametersT<T> result =
251 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
252 const TransformT<T> localXF = state.jointState[i].localTransform;
253 result.v.template segment<kParametersPerJoint>(i * kParametersPerJoint) =
254 localTransformToJointParameters(skeleton.joints[i], localXF);
255 }
256
257 return result;
258}
259
260template <typename T>
262 const TransformListT<T>& state,
263 const Skeleton& skeleton) {
264 JointParametersT<T> result =
266 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
267 const auto parentJoint = skeleton.joints[i].parent;
268 TransformT<T> parentXF;
269 if (parentJoint != kInvalidIndex) {
270 parentXF = state[parentJoint];
271 }
272
273 // parentXF * localXF = jointXF, so localXF = parentXF^-1 * jointXF.
274 const TransformT<T> localXF = parentXF.inverse() * state[i];
275 result.v.template segment<kParametersPerJoint>(i * kParametersPerJoint) =
276 localTransformToJointParameters(skeleton.joints[i], localXF);
277 }
278 return result;
279}
280
281namespace {
282
283// Constrained inverse of localTransformToJointParameters: zero-fill any parameter slot whose
284// activeJointParams entry is false, and pick the rotation extraction that matches how many
285// rotation axes are active. This avoids the Euler-angle ambiguity that the unconstrained 3-axis
286// path suffers from when a joint really only has 1 or 2 free rotation DOFs.
287template <typename T>
288[[nodiscard]] Eigen::Vector<T, kParametersPerJoint>
289localTransformToJointParametersRespectingConstraints(
290 const Joint& joint,
291 const TransformT<T>& localTransform,
292 const VectorX<bool>& activeJointParams,
293 size_t jointIndex) {
294 const size_t paramOffset = jointIndex * kParametersPerJoint;
295
296 Eigen::Vector<T, kParametersPerJoint> result = Eigen::Vector<T, kParametersPerJoint>::Zero();
297
298 for (int k = 0; k < 3; ++k) {
299 if (activeJointParams[paramOffset + k]) {
300 result(k) = localTransform.translation(k) - static_cast<T>(joint.translationOffset(k));
301 }
302 }
303
304 // Strip the joint's pre-rotation so we work in the joint's own rotation frame.
305 const Eigen::Quaternion<T> localRotation =
306 joint.preRotation.template cast<T>().inverse() * localTransform.rotation;
307
308 const Matrix3<T> rotationMatrix = localRotation.toRotationMatrix();
309
310 std::array<int, 3> activeAxes{};
311 size_t numActiveAxes = 0;
312 for (int k = 0; k < 3; ++k) {
313 if (activeJointParams[paramOffset + 3 + k]) {
314 activeAxes[numActiveAxes++] = k;
315 }
316 }
317
318 if (numActiveAxes == 1) {
319 const auto axis = activeAxes[0];
320 const T angle = rotationMatrixToOneAxisEuler(rotationMatrix, axis);
321 result(3 + axis) = angle;
322 } else if (numActiveAxes == 2) {
323 const Vector2<T> angles =
324 rotationMatrixToTwoAxisEuler(rotationMatrix, activeAxes[0], activeAxes[1]);
325 result(3 + activeAxes[0]) = angles[0];
326 result(3 + activeAxes[1]) = angles[1];
327 } else if (numActiveAxes == 3) {
328 // Decompose into Extrinsic XYZ angles [rx, ry, rz], matching the convention used by
329 // JointStateT::set() and the unconstrained quaternionToEuler path.
330 result.template segment<3>(3) =
332 } else {
333 // numActiveAxes == 0: leave rotation parameters at zero.
334 }
335
336 if (activeJointParams[paramOffset + 6]) {
337 result(6) = std::log2(localTransform.scale);
338 }
339
340 return result;
341}
342
343} // namespace
344
345template <typename T>
347 const SkeletonStateT<T>& state,
348 const Skeleton& skeleton,
349 const VectorX<bool>& activeJointParams) {
350 MT_CHECK(
351 activeJointParams.size() ==
352 static_cast<Eigen::Index>(skeleton.joints.size() * kParametersPerJoint),
353 "activeJointParams size {} does not match expected size {} (skeleton joints: {})",
354 activeJointParams.size(),
355 skeleton.joints.size() * kParametersPerJoint,
356 skeleton.joints.size());
357
358 JointParametersT<T> result =
360
361 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
362 const TransformT<T> localXF = state.jointState[i].localTransform;
363 result.v.template segment<kParametersPerJoint>(i * kParametersPerJoint) =
364 localTransformToJointParametersRespectingConstraints(
365 skeleton.joints[i], localXF, activeJointParams, i);
366 }
367
368 return result;
369}
370
371template <typename T>
373 const TransformListT<T>& state,
374 const Skeleton& skeleton,
375 const VectorX<bool>& activeJointParams) {
376 MT_CHECK(
377 activeJointParams.size() ==
378 static_cast<Eigen::Index>(skeleton.joints.size() * kParametersPerJoint),
379 "activeJointParams size {} does not match expected size {} (skeleton joints: {})",
380 activeJointParams.size(),
381 skeleton.joints.size() * kParametersPerJoint,
382 skeleton.joints.size());
383
384 JointParametersT<T> result =
386
387 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
388 const auto parentJoint = skeleton.joints[i].parent;
389 TransformT<T> parentXF;
390 if (parentJoint != kInvalidIndex) {
391 parentXF = state[parentJoint];
392 }
393
394 // parentXF * localXF = jointXF, so localXF = parentXF^-1 * jointXF.
395 const TransformT<T> localXF = parentXF.inverse() * state[i];
396 result.v.template segment<kParametersPerJoint>(i * kParametersPerJoint) =
397 localTransformToJointParametersRespectingConstraints(
398 skeleton.joints[i], localXF, activeJointParams, i);
399 }
400
401 return result;
402}
403
404template struct SkeletonStateT<float>;
405template struct SkeletonStateT<double>;
406
407template void SkeletonStateT<float>::set(const SkeletonStateT<float>&);
408template void SkeletonStateT<float>::set(const SkeletonStateT<double>&);
409template void SkeletonStateT<double>::set(const SkeletonStateT<float>&);
410template void SkeletonStateT<double>::set(const SkeletonStateT<double>&);
411
412template SkeletonStateT<float>::SkeletonStateT(const SkeletonStateT<double>&);
413template SkeletonStateT<double>::SkeletonStateT(const SkeletonStateT<float>&);
414
416 size_t jointA,
417 size_t jointB,
418 const Skeleton& referenceSkeleton,
419 const SkeletonStateT<float>& skelState);
421 size_t jointA,
422 size_t jointB,
423 const Skeleton& referenceSkeleton,
424 const SkeletonStateT<double>& skelState);
425
427 const SkeletonStateT<float>& state,
428 const Skeleton& skeleton);
430 const SkeletonStateT<double>& state,
431 const Skeleton& skeleton);
432
434 const TransformListT<float>& state,
435 const Skeleton& skeleton);
437 const TransformListT<double>& state,
438 const Skeleton& skeleton);
439
441 const SkeletonStateT<float>& state,
442 const Skeleton& skeleton,
443 const VectorX<bool>& activeJointParams);
445 const SkeletonStateT<double>& state,
446 const Skeleton& skeleton,
447 const VectorX<bool>& activeJointParams);
448
450 const TransformListT<float>& state,
451 const Skeleton& skeleton,
452 const VectorX<bool>& activeJointParams);
454 const TransformListT<double>& state,
455 const Skeleton& skeleton,
456 const VectorX<bool>& activeJointParams);
457
458} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
T rotationMatrixToOneAxisEuler(const Matrix3< T > &m, int axis0)
Fits a single-axis Euler rotation to a rotation matrix.
Definition utility.cpp:819
SkeletonT< float > Skeleton
Definition fwd.h:263
Vector3< T > rotationMatrixToEulerXYZ(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 0, 1, 2, convention) or rotationMatrixToEuler(m,...
Definition utility.cpp:201
TransformT< T > transformAtoB(size_t jointA, size_t jointB, const Skeleton &referenceSkeleton, const SkeletonStateT< T > &skelState)
Computes the relative transform between two joints in a skeleton.
std::vector< TransformT< T > > TransformListT
Per-joint transform list describing the state of all joints in a skeleton (one entry per joint,...
Definition transform.h:228
Vector3< T > quaternionToEuler(const Quaternion< T > &q)
Converts a quaternion to Euler angles using the Extrinsic XYZ convention.
Definition utility.cpp:385
Eigen::Matrix< T, 3, 3 > Matrix3
Definition types.h:96
@ Extrinsic
The extrinsic convention.
Definition utility.h:178
FloatP dot(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes dot product of Eigen::Vector3f and 3-vector of packets.
Definition simd.h:191
Vector2< T > rotationMatrixToTwoAxisEuler(const Matrix3< T > &m, int axis0, int axis1)
Fits a two-axis Euler rotation to a rotation matrix.
Definition utility.cpp:840
JointParametersT< T > skeletonStateToJointParametersRespectingActiveParameters(const SkeletonStateT< T > &state, const Skeleton &skeleton, const VectorX< bool > &activeJointParams)
Converts skeleton state back to joint parameters, respecting active joint parameter constraints.
Vector< T, 2 > Vector2
Definition types.h:234
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
constexpr size_t kParametersPerJoint
Definition types.h:21
JointParametersT< T > skeletonStateToJointParameters(const SkeletonStateT< T > &state, const Skeleton &skeleton)
The "RespectingActiveParameters" variants use rotationMatrixToOneAxisEuler or rotationMatrixToTwoAxis...
JointT< float > Joint
Definition fwd.h:206
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
VectorX< float > VectorXf
Definition types.h:209
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Definition types.h:466
std::vector< JointT< T > > JointListT
A list of joints (e.g., of a skeleton).
Definition joint.h:80
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
static EIGEN_DEVICE_FUNC JointParametersT< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
A vector describing joint parameters, of size numSkeletonJoints * kParametersPerJoint.
Definition types.h:129
A simplified version of a Maya joint with pre-rotation only (no post-rotation).
Definition joint.h:18
size_t parent
Index of the parent joint in the skeleton hierarchy, or kInvalidIndex for the root.
Definition joint.h:24
Represents the complete state of a skeleton.
SkeletonStateT< T2 > cast() const
Converts the skeleton state to a different scalar type.
void set(const JointParametersT< T > &jointParameters, const Skeleton &referenceSkeleton, bool computeDeriv=true)
Updates the skeleton state with new joint parameters.
JointParametersT< T > jointParameters
Joint parameters for all joints in the skeleton.
TransformListT< T > toTransforms() const
Extracts global transforms for all joints in the skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
static StateSimilarity compare(const SkeletonStateT< T > &state1, const SkeletonStateT< T > &state2)
Compares two skeleton states and returns similarity metrics.
SkeletonStateT() noexcept=default
Creates an empty skeleton state.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25
Measures of similarity between two skeleton states.
float orientationRMSE
Root mean square of orientation errors across all joints.
float positionRMSE
Root mean square of position errors across all joints.
float orientationMax
Maximum orientation error across all joints.
float positionMax
Maximum position error across all joints.
VectorXf orientationError
Orientation error for each joint (in radians).
VectorXf positionError
Position error for each joint (in distance units).
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36
TransformT< T > inverse() const
Returns the inverse transform such that (*this) * inverse() == identity.
Definition transform.cpp:93