Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
transform_pose.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
16#include "momentum/common/log.h"
20
21#include <numeric>
22
23namespace momentum {
24
25namespace {
26
27momentum::Character createRigidBodySkeleton(const momentum::Character& character) {
28 const auto rigidBodyParameters = character.parameterTransform.getRigidParameters();
29
30 std::vector<bool> rigidJoints = character.parametersToActiveJoints(rigidBodyParameters);
31 // Note that we need to keep _all_ the parameters that affect the rigid joints.
32
33 // The rigidly transformed joints should appear near the top of the skeleton.
34 // Rather than trying to be fancy about this, we'll just find the last affected joint and
35 // keep all the joints in the list before it. This will also allow us to much more easily
36 // simplify the parameter transform since we don't need to deal with missing joints in the
37 // middle.
38 size_t numRigidJoints = 0;
39 for (size_t i = 0; i < rigidJoints.size(); ++i) {
40 if (rigidJoints[i]) {
41 numRigidJoints = i + 1;
42 }
43 }
44
46 numRigidJoints == 0, "No rigid joints found in character, unable to apply transformation.");
47
48 // Need to include all joints and parameters in the parent chain:
49 std::fill(rigidJoints.begin(), rigidJoints.begin() + numRigidJoints, true);
50
51 // Retain all parameters that affect the rigid pose, which means all parameters
52 // affecting joints above the root.
53 const auto parametersToKeep = character.activeJointsToParameters(rigidJoints);
54
55 // This only changes the parameters:
56 auto [intermediateTransform, intermediateLimits] =
57 subsetParameterTransform(character.parameterTransform, ParameterLimits{}, parametersToKeep);
58
59 // Construct the new skeleton by just clipping the skeleton to the rigid joints.
60 momentum::Skeleton resultSkeleton;
61 resultSkeleton.joints.reserve(numRigidJoints);
62 for (size_t i = 0; i < numRigidJoints; ++i) {
63 resultSkeleton.joints.push_back(character.skeleton.joints.at(i));
64 }
65
66 std::vector<size_t> jointMapping(character.skeleton.joints.size(), kInvalidIndex);
67 std::iota(jointMapping.begin(), jointMapping.begin() + resultSkeleton.joints.size(), 0);
68
69 return {
70 resultSkeleton,
72 intermediateTransform, resultSkeleton.joints.size(), jointMapping)};
73}
74
75} // namespace
76
77template <typename T>
78std::vector<ModelParametersT<T>> transformPose(
79 const Character& character,
80 const std::vector<ModelParametersT<T>>& modelParameters,
81 const TransformT<T>& transforms) {
82 return transformPose(character, modelParameters, std::vector<TransformT<T>>{transforms}, true);
83}
84
85template <typename T>
87 numModelParametersFull_ = character.parameterTransform.numAllModelParameters();
88
89 characterSimplified_ = createRigidBodySkeleton(character);
90 MT_CHECK(!characterSimplified_.skeleton.joints.empty(), "No joints in simplified character");
91 // Use the farthest joint since it should have all parameters applied to it:
92 rootJointSimplified_ = characterSimplified_.skeleton.joints.size() - 1;
93
94 parameterTransformSimplified_ = characterSimplified_.parameterTransform.cast<T>();
95 rigidParametersSimplified_ = characterSimplified_.parameterTransform.getRigidParameters();
96
97 simplifiedParamToFullParamIdx_.resize(parameterTransformSimplified_.numAllModelParameters());
98 for (Eigen::Index iSimplifiedParam = 0;
99 iSimplifiedParam < characterSimplified_.parameterTransform.numAllModelParameters();
100 ++iSimplifiedParam) {
101 const auto fullParamIdx = character.parameterTransform.getParameterIdByName(
102 characterSimplified_.parameterTransform.name[iSimplifiedParam]);
103 MT_CHECK(fullParamIdx != momentum::kInvalidIndex);
104 simplifiedParamToFullParamIdx_.at(iSimplifiedParam) = fullParamIdx;
105 }
106
107 positionError_ = std::make_shared<momentum::PositionErrorFunctionT<T>>(characterSimplified_);
108 orientationError_ =
109 std::make_shared<momentum::OrientationErrorFunctionT<T>>(characterSimplified_);
110
111 solverFunction_ = std::make_unique<momentum::SkeletonSolverFunctionT<T>>(
112 characterSimplified_, parameterTransformSimplified_);
113 solverFunction_->addErrorFunction(positionError_);
114 solverFunction_->addErrorFunction(orientationError_);
115
117 solverOptions.maxIterations = 1000;
118 solverOptions.minIterations = 10;
119 // It shouldn't need regularization:
120 solverOptions.regularization = std::numeric_limits<T>::epsilon();
121 solverOptions.useBlockJtJ = true;
122
123 solver_ = std::make_unique<GaussNewtonSolverT<T>>(solverOptions, solverFunction_.get());
124 solver_->setEnabledParameters(rigidParametersSimplified_);
125
126 solvedParametersSimplified_ =
127 ModelParametersT<T>::Zero(parameterTransformSimplified_.numAllModelParameters());
128}
129
130template <typename T>
132
133template <typename T>
135 ModelParametersT<T>& modelParametersFull,
136 const TransformT<T>& transform,
137 const ModelParametersT<T>& modelParametersPrev) {
138 MT_CHECK(
139 modelParametersFull.size() == numModelParametersFull_,
140 "Model parameters don't match full character");
141 MT_CHECK(
142 modelParametersPrev.size() == numModelParametersFull_ || modelParametersPrev.size() == 0,
143 "Prev model parameters don't match full character");
144
145 // Initialize with params copied from fullParams:
146 solvedParametersSimplified_.v.setZero();
147 for (size_t iSimplifiedParam = 0; iSimplifiedParam < simplifiedParamToFullParamIdx_.size();
148 ++iSimplifiedParam) {
149 const auto fullParamIdx = simplifiedParamToFullParamIdx_[iSimplifiedParam];
150 solvedParametersSimplified_[iSimplifiedParam] = modelParametersFull[fullParamIdx];
151 }
152
153 skelStateSimplified_.set(
154 parameterTransformSimplified_.apply(solvedParametersSimplified_),
155 characterSimplified_.skeleton,
156 false);
157
158 if (modelParametersPrev.size() != 0) {
159 // Copy rigid parameters from previous solve to ensure continuity:
160 for (size_t iSimplifiedParam = 0; iSimplifiedParam < simplifiedParamToFullParamIdx_.size();
161 ++iSimplifiedParam) {
162 const auto fullParamIdx = simplifiedParamToFullParamIdx_[iSimplifiedParam];
163 if (rigidParametersSimplified_.test(iSimplifiedParam)) {
164 solvedParametersSimplified_[iSimplifiedParam] = modelParametersPrev[fullParamIdx];
165 }
166 }
167 }
168
169 const TransformT<T> worldFromRootTarget =
170 transform * skelStateSimplified_.jointState[rootJointSimplified_].transform;
171
172 positionError_->clearConstraints();
173 positionError_->addConstraint(
175 Eigen::Vector3<T>::Zero(), worldFromRootTarget.translation, rootJointSimplified_, 100.0));
176
177 orientationError_->clearConstraints();
178 orientationError_->addConstraint(
180 Eigen::Quaternion<T>::Identity(),
181 worldFromRootTarget.rotation,
182 rootJointSimplified_,
183 10.0));
184
185 // The momentum solver has a lot of local minima issues related to the use
186 // of Euler angles. As a result for any given solve there is a chance if will
187 // get stuck somewhere non-optimal, which would be really bad in this case because
188 // we'd end up with a single pose out of the set which is flipped backward or whatever.
189 // To avoid this, we'll do the solve with restarts: each solve will start with a random
190 // set of rigid parameters and we'll run to convergence, then exit when the resulting
191 // rotation is close enough.
192
193 for (size_t iIter = 0;; ++iIter) {
194 if (iIter > 10000) {
195 MT_LOGW(
196 "Solver failed to converge after {} iterations when solving for rigid transform.", iIter);
197 break;
198 }
199
200 solver_->solve(solvedParametersSimplified_.v);
201 skelStateSimplified_.set(
202 parameterTransformSimplified_.apply(solvedParametersSimplified_),
203 characterSimplified_.skeleton,
204 false);
205 if ((skelStateSimplified_.jointState[rootJointSimplified_].rotation().toRotationMatrix() -
206 worldFromRootTarget.rotation.toRotationMatrix())
207 .norm() < 1e-3) {
208 break;
209 }
210
211 // Randomize the starting location to deal with Euler angle local minimum issues:
212 for (int k = 0; k < characterSimplified_.parameterTransform.numAllModelParameters(); ++k) {
213 if (rigidParametersSimplified_.test(k)) {
214 solvedParametersSimplified_[k] = rng_.uniform(-pi(), pi());
215 }
216 }
217 }
218
219 for (size_t simplifiedParamIdx = 0; simplifiedParamIdx < simplifiedParamToFullParamIdx_.size();
220 ++simplifiedParamIdx) {
221 if (rigidParametersSimplified_.test(simplifiedParamIdx)) {
222 const auto fullParamIdx = simplifiedParamToFullParamIdx_[simplifiedParamIdx];
223 modelParametersFull.v[fullParamIdx] = solvedParametersSimplified_[simplifiedParamIdx];
224 }
225 }
226}
227
228template <typename T>
229std::vector<ModelParametersT<T>> transformPose(
230 const Character& character,
231 const std::vector<ModelParametersT<T>>& modelParameters,
232 const std::vector<TransformT<T>>& transforms,
233 [[maybe_unused]] bool ensureContinuousOutput) {
234 MT_CHECK(
235 transforms.size() == 1 || modelParameters.size() == transforms.size(),
236 "Mismatched transforms and parameters");
237
238 // Applies a transform to a character by solving for the new set of model
239 // parameters such that the new character's root matches up with the transformed
240 // version of the old character's root. This could in principle be done in a closed
241 // form but such a solution would need to be hand-coded for each parametrization
242 // of character, so for now we'll do it using an IK solve (which is very fast
243 // in this case because we're only working with the rigid parameters).
244 const auto nPoses = modelParameters.size();
245
246 PoseTransformSolverT<T> transformSolver(character);
247
248 std::vector<momentum::ModelParametersT<T>> result(modelParameters.size());
249
251 for (size_t iFrame = 0; iFrame < nPoses; ++iFrame) {
252 const auto& fullParams_init = modelParameters.at(iFrame);
253 if (fullParams_init.size() == 0) {
254 continue;
255 }
256
257 const TransformT<T>& transform =
258 (iFrame < transforms.size()) ? transforms.at(iFrame) : transforms.at(0);
259
260 result[iFrame] = modelParameters[iFrame];
261 transformSolver.transformPose(result[iFrame], transform, prevSolve);
262 prevSolve = result[iFrame];
263 }
264
265 return result;
266}
267
268template std::vector<ModelParametersT<float>> transformPose(
269 const Character& characterFull,
270 const std::vector<ModelParametersT<float>>& modelParametersFull,
271 const std::vector<TransformT<float>>& transforms,
272 bool ensureContinuousOutput);
273
274template std::vector<ModelParametersT<double>> transformPose(
275 const Character& characterFull,
276 const std::vector<ModelParametersT<double>>& modelParametersFull,
277 const std::vector<TransformT<double>>& transforms,
278 bool ensureContinuousOutput);
279
280template std::vector<ModelParametersT<float>> transformPose(
281 const Character& character,
282 const std::vector<ModelParametersT<float>>& modelParameters,
283 const TransformT<float>& transform);
284
285template std::vector<ModelParametersT<double>> transformPose(
286 const Character& character,
287 const std::vector<ModelParametersT<double>>& modelParameters,
288 const TransformT<double>& transform);
289
290template class PoseTransformSolverT<float>;
291template class PoseTransformSolverT<double>;
292
293} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Solver which can be reused to repeatedly apply the transformPose function listed above.
void transformPose(ModelParametersT< T > &modelParameters, const TransformT< T > &transform, const ModelParametersT< T > &modelParametersPrev=ModelParametersT< T >{})
Applies a rigid transform to the given model parameters.
PoseTransformSolverT(const Character &character)
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
#define MT_LOGW(...)
Definition log.h:180
SkeletonT< float > Skeleton
Definition fwd.h:263
std::tuple< ParameterTransformT< T >, ParameterLimits > subsetParameterTransform(const ParameterTransformT< T > &paramTransformOld, const ParameterLimits &paramLimitsOld, const ParameterSet &paramSet)
Return a parameter mapping that only includes the listed parameters.
std::vector< ParameterLimit > ParameterLimits
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
std::vector< ModelParametersT< T > > transformPose(const Character &character, const std::vector< ModelParametersT< T > > &modelParameters, const TransformT< T > &transforms)
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50
ParameterTransformT< T > mapParameterTransformJoints(const ParameterTransformT< T > &parameterTransform, size_t numTargetJoints, const std::vector< size_t > &jointMapping)
Construct a new parameter transform where the joints have been mapped to a new skeleton.
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
std::vector< bool > parametersToActiveJoints(const ParameterSet &parameterSet) const
Determines which joints are affected by the specified parameters.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
ParameterSet activeJointsToParameters(const std::vector< bool > &activeJoints) const
Determines which parameters affect the specified joints.
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Definition types.h:87
static EIGEN_DEVICE_FUNC ModelParametersT< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
float regularization
Damping parameter added to Hessian diagonal for numerical stability; see https://en....
Extended options specific to the Gauss-Newton optimization algorithm.
bool useBlockJtJ
Uses pre-computed JᵀJ and JᵀR from the solver function.
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Constraint data on 3x3 rotation represented in quaternions.
Eigen::Index numAllModelParameters() const
Dimension of all model parameters, including pose, scaling, marker joints, and blendshape parameters ...
ParameterSet getRigidParameters() const
Get a list of root parameters (with prefix "root_").
size_t getParameterIdByName(const std::string &nm) const
Return the index of a model parameter from its name.
3D position constraint data
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
size_t minIterations
Minimum number of iterations before checking convergence criteria.
Definition solver.h:21
size_t maxIterations
Maximum number of iterations before terminating.
Definition solver.h:24
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36
Vector3< T > translation
Definition transform.h:40
Quaternion< T > rotation
Unit quaternion encoding the rotation.
Definition transform.h:39