Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
skinned_locator_error_function.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
10
20
21#include <numeric>
22
23namespace momentum {
24
25template <typename T>
27 : SkeletonErrorFunctionT<T>(character_in.skeleton, character_in.parameterTransform),
28 character_(character_in) {}
29
30template <typename T>
32
33template <typename T>
35 constraints_.clear();
36}
37
38template <typename T>
40 int locatorIndex,
41 T weight,
42 const Eigen::Vector3<T>& targetPosition) {
43 MT_CHECK(locatorIndex >= 0 && ((size_t)locatorIndex) < character_.skinnedLocators.size());
44 constraints_.push_back(SkinnedLocatorConstraintT<T>{locatorIndex, weight, targetPosition});
45}
46
47template <typename T>
49 const std::vector<SkinnedLocatorConstraintT<T>>& constraints) {
50 constraints_ = constraints;
51}
52
53template <typename T>
54Eigen::Vector3<T> SkinnedLocatorErrorFunctionT<T>::getLocatorRestPosition(
55 const ModelParametersT<T>& modelParams,
56 int locatorIndex) const {
57 MT_CHECK(locatorIndex >= 0 && locatorIndex < static_cast<int>(character_.skinnedLocators.size()));
58 const auto& locator = character_.skinnedLocators[locatorIndex];
59
60 Vector3<T> result = locator.position.template cast<T>();
61 int locatorParameterIndex = -1;
62 if (locatorIndex < character_.parameterTransform.skinnedLocatorParameters.size()) {
63 locatorParameterIndex = character_.parameterTransform.skinnedLocatorParameters[locatorIndex];
64 }
65
66 if (locatorParameterIndex >= 0) {
67 result += modelParams.v.template segment<3>(locatorParameterIndex).template cast<T>();
68 }
69
70 return result;
71}
72
73template <typename T>
74Eigen::Vector3<T> SkinnedLocatorErrorFunctionT<T>::calculateSkinnedLocatorPosition(
75 const SkeletonStateT<T>& state,
76 int locatorIndex,
77 const Eigen::Vector3<T>& locatorRestPos) const {
78 MT_CHECK(locatorIndex >= 0 && locatorIndex < static_cast<int>(character_.skinnedLocators.size()));
79 const auto& locator = character_.skinnedLocators[locatorIndex];
80
81 return getSkinnedLocatorPosition(locator, locatorRestPos, character_.inverseBindPose, state);
82}
83
84template <typename T>
86 const ModelParametersT<T>& modelParameters,
87 const SkeletonStateT<T>& state,
88 const MeshStateT<T>& /* meshState */) {
90
91 // loop over all constraints and calculate the error
92 double error = 0.0;
93
94 for (size_t i = 0; i < constraints_.size(); ++i) {
95 const SkinnedLocatorConstraintT<T>& constr = constraints_[i];
96
97 const Eigen::Vector3<T> locatorRestPos =
98 getLocatorRestPosition(modelParameters, constr.locatorIndex);
99 const Eigen::Vector3<T> locatorWorldPos =
100 calculateSkinnedLocatorPosition(state, constr.locatorIndex, locatorRestPos);
101 const Eigen::Vector3<T> diff = locatorWorldPos - constr.targetPosition;
102 error += constr.weight * diff.squaredNorm();
103 }
104
105 // return error
106 return error * this->weight_;
107}
108
109template <typename T>
110void SkinnedLocatorErrorFunctionT<T>::calculateDWorldPos(
111 const SkeletonStateT<T>& state,
112 const SkinnedLocatorConstraintT<T>& constr,
113 const Eigen::Vector3<T>& d_restPos,
114 Eigen::Vector3<T>& d_worldPos) const {
115 const auto& locator = character_.skinnedLocators[constr.locatorIndex];
116
117 for (int k = 0; k < locator.skinWeights.size(); ++k) {
118 const auto& weight = locator.skinWeights[k];
119 const auto boneIndex = locator.parents[k];
120 const auto& jointState = state.jointState[boneIndex];
121
122 if (weight > 0) {
123 // Use the full transformation matrix to be consistent with calculateSkinnedLocatorPosition
124 d_worldPos += weight *
125 ((jointState.transform * character_.inverseBindPose[boneIndex].template cast<T>())
126 .linear() *
127 d_restPos);
128 }
129 }
130}
131
132template <typename T>
133double SkinnedLocatorErrorFunctionT<T>::calculatePositionGradient(
134 const ModelParametersT<T>& modelParameters,
135 const SkeletonStateT<T>& state,
136 const SkinnedLocatorConstraintT<T>& constr,
137 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
138 const Eigen::Vector3<T> locatorRestPos =
139 getLocatorRestPosition(modelParameters, constr.locatorIndex);
140 const Eigen::Vector3<T> locatorWorldPos =
141 calculateSkinnedLocatorPosition(state, constr.locatorIndex, locatorRestPos);
142 const Eigen::Vector3<T> diff = locatorWorldPos - constr.targetPosition;
143
144 // calculate the difference between target and position and error
145 const T wgt = constr.weight * 2.0f * this->weight_;
146
147 // Handle derivatives wrt skinnedLocatorParameters if this locator is parameterized
148 int locatorParameterIndex = getSkinnedLocatorParameterIndex(constr.locatorIndex);
149 if (locatorParameterIndex >= 0) {
150 // For each coordinate (x, y, z), calculate the derivative
151 for (int d = 0; d < 3; ++d) {
152 // Create a unit vector in the direction of the coordinate
153 Eigen::Vector3<T> d_restPos = Eigen::Vector3<T>::Zero();
154 d_restPos[d] = 1.0;
155
156 // Calculate the derivative of the world position with respect to this coordinate
157 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
158 calculateDWorldPos(state, constr, d_restPos, d_worldPos);
159
160 // Add contribution to the gradient
161 gradient(locatorParameterIndex + d) += diff.dot(d_worldPos) * wgt;
162 }
163 }
164
165 SkinningWeightIteratorT<T> skinningIter(
166 this->character_, character_.skinnedLocators[constr.locatorIndex], locatorRestPos, state);
167
168 // Handle derivatives wrt jointParameters
169 while (!skinningIter.finished()) {
170 const auto [jointIndex, boneWeight, pos] = skinningIter.next();
171
172 // check for valid index
173 MT_CHECK(jointIndex < this->skeleton_.joints.size());
174
175 const auto& jointState = state.jointState[jointIndex];
176 const size_t paramIndex = jointIndex * kParametersPerJoint;
177 const Eigen::Vector3<T> posd = pos - jointState.translation();
178
179 // calculate derivatives based on active joints
180 for (size_t d = 0; d < 3; d++) {
181 if (this->activeJointParams_[paramIndex + d]) {
182 // Gradient wrt translation:
184 boneWeight * diff.dot(jointState.getTranslationDerivative(d)) * wgt,
185 paramIndex + d,
186 this->parameterTransform_,
187 gradient);
188 }
189 if (this->activeJointParams_[paramIndex + 3 + d]) {
190 // Gradient wrt rotation:
192 boneWeight * diff.dot(jointState.getRotationDerivative(d, posd)) * wgt,
193 paramIndex + 3 + d,
194 this->parameterTransform_,
195 gradient);
196 }
197 }
198 if (this->activeJointParams_[paramIndex + 6]) {
199 // Gradient wrt scale:
201 boneWeight * diff.dot(jointState.getScaleDerivative(posd)) * wgt,
202 paramIndex + 6,
203 this->parameterTransform_,
204 gradient);
205 }
206 }
207
208 return constr.weight * diff.squaredNorm();
209}
210
211template <typename T>
212double SkinnedLocatorErrorFunctionT<T>::calculatePositionJacobian(
213 const ModelParametersT<T>& modelParameters,
214 const SkeletonStateT<T>& state,
215 const SkinnedLocatorConstraintT<T>& constr,
216 Ref<Eigen::MatrixX<T>> jac,
217 Ref<Eigen::VectorX<T>> res) const {
218 const Eigen::Vector3<T> locatorRestPos =
219 getLocatorRestPosition(modelParameters, constr.locatorIndex);
220 const Eigen::Vector3<T> locatorWorldPos =
221 calculateSkinnedLocatorPosition(state, constr.locatorIndex, locatorRestPos);
222 const Eigen::Vector3<T> diff = locatorWorldPos - constr.targetPosition;
223
224 const T wgt = std::sqrt(constr.weight * this->weight_);
225
226 // Handle derivatives wrt skinnedLocatorParameters if this locator is parameterized
227 int locatorParameterIndex = getSkinnedLocatorParameterIndex(constr.locatorIndex);
228 if (locatorParameterIndex >= 0) {
229 // For each coordinate (x, y, z), calculate the derivative
230 for (int d = 0; d < 3; ++d) {
231 // Create a unit vector in the direction of the coordinate
232 Eigen::Vector3<T> d_restPos = Eigen::Vector3<T>::Zero();
233 d_restPos[d] = 1.0;
234
235 // Calculate the derivative of the world position with respect to this coordinate
236 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
237 calculateDWorldPos(state, constr, d_restPos, d_worldPos);
238
239 // Add contribution to the jacobian
240 jac.col(locatorParameterIndex + d).template segment<3>(0) += d_worldPos * wgt;
241 }
242 }
243
244 SkinningWeightIteratorT<T> skinningIter(
245 this->character_, character_.skinnedLocators[constr.locatorIndex], locatorRestPos, state);
246
247 // Handle derivatives wrt jointParameters
248 while (!skinningIter.finished()) {
249 const auto [jointIndex, boneWeight, pos] = skinningIter.next();
250
251 // check for valid index
252 MT_CHECK(jointIndex < this->skeleton_.joints.size());
253
254 const auto& jointState = state.jointState[jointIndex];
255 const size_t paramIndex = jointIndex * kParametersPerJoint;
256 const Eigen::Vector3<T> posd = pos - jointState.translation();
257
258 // calculate derivatives based on active joints
259 for (size_t d = 0; d < 3; d++) {
260 if (this->activeJointParams_[paramIndex + d]) {
262 boneWeight * wgt * jointState.getTranslationDerivative(d),
263 paramIndex + d,
264 this->parameterTransform_,
265 jac);
266 }
267 if (this->activeJointParams_[paramIndex + 3 + d]) {
269 boneWeight * wgt * jointState.getRotationDerivative(d, posd),
270 paramIndex + d + 3,
271 this->parameterTransform_,
272 jac);
273 }
274 }
275 if (this->activeJointParams_[paramIndex + 6]) {
277 boneWeight * wgt * jointState.getScaleDerivative(posd),
278 paramIndex + 6,
279 this->parameterTransform_,
280 jac);
281 }
282 }
283
284 res = diff * wgt;
285
286 return wgt * wgt * diff.squaredNorm();
287}
288
289template <typename T>
291 const ModelParametersT<T>& modelParameters,
292 const SkeletonStateT<T>& state,
293 const MeshStateT<T>& /* meshState */,
294 Eigen::Ref<Eigen::VectorX<T>> gradient) {
295 double error = 0;
296
297 // Process each constraint
298 for (const auto& constraint : constraints_) {
299 error += calculatePositionGradient(modelParameters, state, constraint, gradient);
300 }
301
302 return this->weight_ * error;
303}
304
305template <typename T>
307 const ModelParametersT<T>& modelParameters,
308 const SkeletonStateT<T>& state,
309 const MeshStateT<T>& /* meshState */,
310 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
311 Eigen::Ref<Eigen::VectorX<T>> residual,
312 int& usedRows) {
313 MT_CHECK(
314 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()));
315 MT_CHECK(jacobian.rows() >= (Eigen::Index)(3 * constraints_.size()));
316 MT_CHECK(residual.rows() >= (Eigen::Index)(3 * constraints_.size()));
317
318 double error = 0;
319
320 for (size_t iCons = 0; iCons < constraints_.size(); ++iCons) {
321 const auto& constraint = constraints_[iCons];
322 error += calculatePositionJacobian(
323 modelParameters,
324 state,
325 constraint,
326 jacobian.block(3 * iCons, 0, 3, modelParameters.size()),
327 residual.middleRows(3 * iCons, 3));
328 usedRows += 3;
329 }
330
331 return error;
332}
333
334template <typename T>
336 return 3 * constraints_.size();
337}
338
341
342} // namespace momentum
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
Error function for skinned locator constraints.
double getGradient(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &, Eigen::Ref< Eigen::VectorX< T > > gradient) final
Computes the gradient of the error function with respect to model parameters.
size_t getJacobianSize() const final
Returns the number of rows needed for the Jacobian matrix.
double getError(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &) final
Computes the total error for all skinned locator constraints.
double getJacobian(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) final
Computes the Jacobian matrix and residual vector for the error function.
void setConstraints(const std::vector< SkinnedLocatorConstraintT< T > > &constraints)
Sets all constraints at once, replacing any existing constraints.
SkinnedLocatorErrorFunctionT(const Character &character_in)
Constructs a skinned locator error function for the given character.
void addConstraint(int locatorIndex, T weight, const Eigen::Vector3< T > &targetPosition)
Adds a new skinned locator constraint.
Functions for linear blend skinning (Skeletal Subspace Deformation).
void jacobian_jointParams_to_modelParams(const Eigen::Ref< const Eigen::VectorX< T > > &jacobian_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobian)
Vector3< T > getSkinnedLocatorPosition(const SkinnedLocator &locator, const Vector3< T > &restPosition, const TransformationList &inverseBindPose, const SkeletonStateT< T > &state)
Computes the world position of a skinned locator using linear blend skinning.
Eigen::Ref< T > Ref
Definition types.h:43
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
Eigen::Vector3< T > calculateDWorldPos(const momentum::Character &character, const SkeletonStateT< T > &state, const int vertexIndex, const Eigen::Vector3< T > &d_restPos)
constexpr size_t kParametersPerJoint
Definition types.h:21
Vector< T, 3 > Vector3
Definition types.h:236
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
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Definition types.h:87
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
Constraint structure for skinned locator error function.