Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
height_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
9
21#include "momentum/math/mesh.h"
22
23namespace momentum {
24
25namespace {
26
29template <typename T>
30void gradient_jointParams_to_modelParams_filtered(
31 const T& grad_jointParams,
32 const Eigen::Index iJointParam,
33 const ParameterTransform& parameterTransform,
34 const ParameterSet& activeModelParams,
35 Eigen::Ref<Eigen::VectorX<T>> gradient) {
36 for (auto index = parameterTransform.transform.outerIndexPtr()[iJointParam];
37 index < parameterTransform.transform.outerIndexPtr()[iJointParam + 1];
38 ++index) {
39 const auto modelParamIndex = parameterTransform.transform.innerIndexPtr()[index];
40 if (activeModelParams[modelParamIndex]) {
41 gradient[modelParamIndex] +=
42 grad_jointParams * parameterTransform.transform.valuePtr()[index];
43 }
44 }
45}
46
49template <typename T, typename Derived>
50void jacobian_jointParams_to_modelParams_filtered(
51 const T& jacobian_jointParams,
52 const Eigen::Index iJointParam,
53 const ParameterTransform& parameterTransform,
54 const ParameterSet& activeModelParams,
55 Eigen::MatrixBase<Derived>& jacobian) {
56 for (auto index = parameterTransform.transform.outerIndexPtr()[iJointParam];
57 index < parameterTransform.transform.outerIndexPtr()[iJointParam + 1];
58 ++index) {
59 const auto modelParamIndex = parameterTransform.transform.innerIndexPtr()[index];
60 if (activeModelParams[modelParamIndex]) {
61 jacobian(0, modelParamIndex) +=
62 jacobian_jointParams * parameterTransform.transform.valuePtr()[index];
63 }
64 }
65}
66
67} // namespace
68
69template <typename T>
71 const Character& character,
72 T targetHeight,
73 const Eigen::Vector3<T>& upDirection,
74 size_t k)
75 : SkeletonErrorFunctionT<T>(character.skeleton, character.parameterTransform),
76 character_(character),
77 targetHeight_(targetHeight),
78 upDirection_(upDirection.normalized()),
79 k_(k),
80 skeletonState_(),
81 meshState_() {
82 MT_CHECK(k > 0, "k must be greater than 0, got {}", k);
83 MT_CHECK(character.mesh != nullptr, "HeightErrorFunction requires a character with a mesh");
84
85 // Set up active parameters (blend shapes, face expressions, and scale only)
86 activeModelParams_ = character.parameterTransform.getBlendShapeParameters() |
89}
90
91template <typename T>
93
94template <typename T>
96 targetHeight_ = height;
97}
98
99template <typename T>
100void HeightErrorFunctionT<T>::setUpDirection(const Eigen::Vector3<T>& upDirection) {
101 upDirection_ = upDirection.normalized();
102}
103
104template <typename T>
105ModelParametersT<T> HeightErrorFunctionT<T>::applyActiveParameters(
106 const ModelParametersT<T>& modelParameters) const {
108
109 ModelParametersT<T> result = modelParameters;
110
111 // Zero out all inactive parameters
112 for (Eigen::Index i = 0; i < result.size(); ++i) {
113 if (!activeModelParams_.test(i)) {
114 result[i] = T(0);
115 }
116 }
117
118 return result;
119}
120
121template <typename T>
122typename HeightErrorFunctionT<T>::HeightResult HeightErrorFunctionT<T>::calculateHeight() const {
124
125 MT_CHECK_NOTNULL(meshState_.posedMesh_);
126
127 if (meshState_.posedMesh_->vertices.empty()) {
128 return {T(0), {}, {}, {}, {}};
129 }
130
131 // Use priority queues to track k lowest and k highest projections
132 // For min heap (highest projections): use std::greater
133 // For max heap (lowest projections): use std::less
134 using ProjectionPair = std::pair<T, size_t>; // (projection, vertex_index)
135
136 // Max heap for k lowest projections (top element is largest of the k lowest)
137 std::priority_queue<ProjectionPair, std::vector<ProjectionPair>, std::less<>> minQueue;
138
139 // Min heap for k highest projections (top element is smallest of the k highest)
140 std::priority_queue<ProjectionPair, std::vector<ProjectionPair>, std::greater<>> maxQueue;
141
142 // Populate the priority queues
143 for (size_t i = 0; i < meshState_.posedMesh_->vertices.size(); ++i) {
144 const T projection = upDirection_.dot(meshState_.posedMesh_->vertices[i]);
145
146 // For k lowest projections
147 if (minQueue.size() < k_) {
148 minQueue.push({projection, i});
149 } else if (projection < minQueue.top().first) {
150 minQueue.pop();
151 minQueue.push({projection, i});
152 }
153
154 // For k highest projections
155 if (maxQueue.size() < k_) {
156 maxQueue.push({projection, i});
157 } else if (projection > maxQueue.top().first) {
158 maxQueue.pop();
159 maxQueue.push({projection, i});
160 }
161 }
162
163 // Extract results from queues
164 HeightResult result;
165 result.minVertexIndices.reserve(k_);
166 result.minVertexWeights.reserve(k_);
167 result.maxVertexIndices.reserve(k_);
168 result.maxVertexWeights.reserve(k_);
169
170 T minProjectionSum = T(0);
171 while (!minQueue.empty()) {
172 const auto& pair = minQueue.top();
173 result.minVertexIndices.push_back(pair.second);
174 minProjectionSum += pair.first;
175 minQueue.pop();
176 }
177
178 T maxProjectionSum = T(0);
179 while (!maxQueue.empty()) {
180 const auto& pair = maxQueue.top();
181 result.maxVertexIndices.push_back(pair.second);
182 maxProjectionSum += pair.first;
183 maxQueue.pop();
184 }
185
186 // Compute uniform weights (1/k for each vertex)
187 const T weight = T(1) / T(k_);
188 result.minVertexWeights.resize(k_, weight);
189 result.maxVertexWeights.resize(k_, weight);
190
191 // Average height is the difference of average projections
192 const T avgMinProjection = minProjectionSum / T(k_);
193 const T avgMaxProjection = maxProjectionSum / T(k_);
194 result.height = avgMaxProjection - avgMinProjection;
195
196 return result;
197}
198
199template <typename T>
201 const ModelParametersT<T>& modelParameters,
202 const SkeletonStateT<T>& /* state */,
203 const MeshStateT<T>& /* meshState */) {
205
206 // Create modified parameters with inactive parameters zeroed out
207 const ModelParametersT<T> activeOnlyParams = applyActiveParameters(modelParameters);
208
209 // Update skeleton state with active parameters only
210 skeletonState_.set(
211 this->parameterTransform_.template cast<T>().apply(activeOnlyParams), this->skeleton_, false);
212
213 // Update internal mesh state using the modified parameters
214 meshState_.update(activeOnlyParams, skeletonState_, character_);
215
216 const auto heightResult = calculateHeight();
217 const T heightDiff = heightResult.height - targetHeight_;
218
219 return this->weight_ * heightDiff * heightDiff;
220}
221
222template <typename T>
224 const ModelParametersT<T>& modelParameters,
225 const SkeletonStateT<T>& /* state */,
226 const MeshStateT<T>& /* meshState */,
227 Eigen::Ref<Eigen::VectorX<T>> gradient) {
229
230 // Create modified parameters with inactive parameters zeroed out
231 const ModelParametersT<T> activeOnlyParams = applyActiveParameters(modelParameters);
232
233 // Update skeleton state with active parameters only
234 skeletonState_.set(
235 this->parameterTransform_.template cast<T>().apply(activeOnlyParams), this->skeleton_, true);
236
237 // Update internal mesh state
238 meshState_.update(activeOnlyParams, skeletonState_, character_);
239
240 const auto heightResult = calculateHeight();
241 const T heightDiff = heightResult.height - targetHeight_;
242
243 const T wgt = T(2) * heightDiff * this->weight_;
244
245 // Average gradients over k highest points
246 for (size_t i = 0; i < heightResult.maxVertexIndices.size(); ++i) {
247 calculateVertexGradient(
248 heightResult.maxVertexIndices[i],
249 wgt * heightResult.maxVertexWeights[i] * upDirection_,
250 gradient);
251 }
252
253 // Average gradients over k lowest points
254 for (size_t i = 0; i < heightResult.minVertexIndices.size(); ++i) {
255 calculateVertexGradient(
256 heightResult.minVertexIndices[i],
257 -wgt * heightResult.minVertexWeights[i] * upDirection_,
258 gradient);
259 }
260
261 return this->weight_ * heightDiff * heightDiff;
262}
263
264template <typename T>
266 const ModelParametersT<T>& modelParameters,
267 const SkeletonStateT<T>& /* state */,
268 const MeshStateT<T>& /* meshState */,
269 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
270 Eigen::Ref<Eigen::VectorX<T>> residual,
271 int& usedRows) {
273
274 MT_CHECK(
275 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()));
276 MT_CHECK(jacobian.rows() >= 1);
277 MT_CHECK(residual.rows() >= 1);
278
279 // Create modified parameters with inactive parameters zeroed out
280 const ModelParametersT<T> activeOnlyParams = applyActiveParameters(modelParameters);
281
282 // Update skeleton state with active parameters only
283 skeletonState_.set(
284 this->parameterTransform_.template cast<T>().apply(activeOnlyParams), this->skeleton_, true);
285
286 // Update internal mesh state
287 meshState_.update(activeOnlyParams, skeletonState_, character_);
288
289 const auto heightResult = calculateHeight();
290 const T heightDiff = heightResult.height - targetHeight_;
291
292 const T wgt = std::sqrt(this->weight_);
293 residual(0) = wgt * heightDiff;
294
295 jacobian.row(0).setZero();
296 auto jac_row = jacobian.row(0);
297
298 // Average jacobians over k highest points
299 for (size_t i = 0; i < heightResult.maxVertexIndices.size(); ++i) {
300 calculateVertexJacobian(
301 heightResult.maxVertexIndices[i],
302 wgt * heightResult.maxVertexWeights[i] * upDirection_,
303 jac_row);
304 }
305
306 // Average jacobians over k lowest points
307 for (size_t i = 0; i < heightResult.minVertexIndices.size(); ++i) {
308 calculateVertexJacobian(
309 heightResult.minVertexIndices[i],
310 -wgt * heightResult.minVertexWeights[i] * upDirection_,
311 jac_row);
312 }
313
314 usedRows = 1;
315 return wgt * wgt * heightDiff * heightDiff;
316}
317
318template <typename T>
320 return 1;
321}
322
323template <typename T>
324template <typename Derived>
325void HeightErrorFunctionT<T>::calculateVertexJacobian(
326 size_t vertexIndex,
327 const Eigen::Vector3<T>& jacobianDirection,
328 Eigen::MatrixBase<Derived>& jacobian) const {
330
331 MT_CHECK_NOTNULL(meshState_.restMesh_);
332
333 SkinningWeightIteratorT<T> skinningIter(
334 this->character_, *meshState_.restMesh_, skeletonState_, vertexIndex);
335
336 while (!skinningIter.finished()) {
337 size_t jointIndex = 0;
338 T boneWeight;
339 Eigen::Vector3<T> pos;
340 std::tie(jointIndex, boneWeight, pos) = skinningIter.next();
341
342 MT_CHECK(jointIndex < this->skeleton_.joints.size());
343
344 const auto& jointState = skeletonState_.jointState[jointIndex];
345 const size_t paramIndex = jointIndex * kParametersPerJoint;
346 const Eigen::Vector3<T> posd = pos - jointState.translation();
347
348 // Calculate derivatives based on active joints
349 for (size_t d = 0; d < 3; d++) {
350 if (this->activeJointParams_[paramIndex + d]) {
351 // Jacobian wrt translation:
352 jacobian_jointParams_to_modelParams_filtered<T>(
353 boneWeight * jacobianDirection.dot(jointState.getTranslationDerivative(d)),
354 paramIndex + d,
355 this->parameterTransform_,
356 activeModelParams_,
357 jacobian);
358 }
359 if (this->activeJointParams_[paramIndex + 3 + d]) {
360 // Jacobian wrt rotation:
361 jacobian_jointParams_to_modelParams_filtered<T>(
362 boneWeight * jacobianDirection.dot(jointState.getRotationDerivative(d, posd)),
363 paramIndex + 3 + d,
364 this->parameterTransform_,
365 activeModelParams_,
366 jacobian);
367 }
368 }
369 if (this->activeJointParams_[paramIndex + 6]) {
370 // Jacobian wrt scale:
371 jacobian_jointParams_to_modelParams_filtered<T>(
372 boneWeight * jacobianDirection.dot(jointState.getScaleDerivative(posd)),
373 paramIndex + 6,
374 this->parameterTransform_,
375 activeModelParams_,
376 jacobian);
377 }
378 }
379
380 if (this->character_.blendShape) {
381 for (Eigen::Index iBlendShape = 0;
382 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
383 ++iBlendShape) {
384 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
385 if (paramIdx < 0) {
386 continue;
387 }
388
389 const Eigen::Vector3<T> d_restPos =
390 this->character_.blendShape->getShapeVectors()
391 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
392 .template cast<T>();
393 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
394 calculateDWorldPos(vertexIndex, d_restPos, d_worldPos);
395
396 jacobian(0, paramIdx) += jacobianDirection.dot(d_worldPos);
397 }
398 }
399
400 if (this->character_.faceExpressionBlendShape) {
401 for (Eigen::Index iBlendShape = 0;
402 iBlendShape < this->parameterTransform_.faceExpressionParameters.size();
403 ++iBlendShape) {
404 const auto paramIdx = this->parameterTransform_.faceExpressionParameters[iBlendShape];
405 if (paramIdx < 0) {
406 continue;
407 }
408
409 const Eigen::Vector3<T> d_restPos =
410 this->character_.faceExpressionBlendShape->getShapeVectors()
411 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
412 .template cast<T>();
413 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
414 calculateDWorldPos(vertexIndex, d_restPos, d_worldPos);
415
416 jacobian(0, paramIdx) += jacobianDirection.dot(d_worldPos);
417 }
418 }
419}
420
421template <typename T>
422void HeightErrorFunctionT<T>::calculateVertexGradient(
423 size_t vertexIndex,
424 const Eigen::Vector3<T>& gradientDirection,
425 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
427
428 MT_CHECK_NOTNULL(meshState_.restMesh_);
429
430 SkinningWeightIteratorT<T> skinningIter(
431 this->character_, *meshState_.restMesh_, skeletonState_, vertexIndex);
432
433 while (!skinningIter.finished()) {
434 size_t jointIndex = 0;
435 T boneWeight;
436 Eigen::Vector3<T> pos;
437 std::tie(jointIndex, boneWeight, pos) = skinningIter.next();
438
439 MT_CHECK(jointIndex < this->skeleton_.joints.size());
440
441 const auto& jointState = skeletonState_.jointState[jointIndex];
442 const size_t paramIndex = jointIndex * kParametersPerJoint;
443 const Eigen::Vector3<T> posd = pos - jointState.translation();
444
445 // Calculate derivatives based on active joints
446 for (size_t d = 0; d < 3; d++) {
447 if (this->activeJointParams_[paramIndex + d]) {
448 // Gradient wrt translation:
449 gradient_jointParams_to_modelParams_filtered<T>(
450 boneWeight * gradientDirection.dot(jointState.getTranslationDerivative(d)),
451 paramIndex + d,
452 this->parameterTransform_,
453 activeModelParams_,
454 gradient);
455 }
456 if (this->activeJointParams_[paramIndex + 3 + d]) {
457 // Gradient wrt rotation:
458 gradient_jointParams_to_modelParams_filtered<T>(
459 boneWeight * gradientDirection.dot(jointState.getRotationDerivative(d, posd)),
460 paramIndex + 3 + d,
461 this->parameterTransform_,
462 activeModelParams_,
463 gradient);
464 }
465 }
466 if (this->activeJointParams_[paramIndex + 6]) {
467 // Gradient wrt scale:
468 gradient_jointParams_to_modelParams_filtered<T>(
469 boneWeight * gradientDirection.dot(jointState.getScaleDerivative(posd)),
470 paramIndex + 6,
471 this->parameterTransform_,
472 activeModelParams_,
473 gradient);
474 }
475 }
476
477 if (this->character_.blendShape) {
478 for (Eigen::Index iBlendShape = 0;
479 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
480 ++iBlendShape) {
481 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
482 if (paramIdx < 0) {
483 continue;
484 }
485
486 const Eigen::Vector3<T> d_restPos =
487 this->character_.blendShape->getShapeVectors()
488 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
489 .template cast<T>();
490 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
491 calculateDWorldPos(vertexIndex, d_restPos, d_worldPos);
492
493 gradient[paramIdx] += gradientDirection.dot(d_worldPos);
494 }
495 }
496
497 if (this->character_.faceExpressionBlendShape) {
498 for (Eigen::Index iBlendShape = 0;
499 iBlendShape < this->parameterTransform_.faceExpressionParameters.size();
500 ++iBlendShape) {
501 const auto paramIdx = this->parameterTransform_.faceExpressionParameters[iBlendShape];
502 if (paramIdx < 0) {
503 continue;
504 }
505
506 const Eigen::Vector3<T> d_restPos =
507 this->character_.faceExpressionBlendShape->getShapeVectors()
508 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
509 .template cast<T>();
510 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
511 calculateDWorldPos(vertexIndex, d_restPos, d_worldPos);
512
513 gradient[paramIdx] += gradientDirection.dot(d_worldPos);
514 }
515 }
516}
517
518template <typename T>
519void HeightErrorFunctionT<T>::calculateDWorldPos(
520 size_t vertexIndex,
521 const Eigen::Vector3<T>& d_restPos,
522 Eigen::Vector3<T>& d_worldPos) const {
523 const auto& skinWeights = *character_.skinWeights;
524
525 for (uint32_t i = 0; i < kMaxSkinJoints; ++i) {
526 const auto w = skinWeights.weight(vertexIndex, i);
527 const auto parentBone = skinWeights.index(vertexIndex, i);
528 if (w > 0) {
529 d_worldPos += w *
530 (skeletonState_.jointState[parentBone].transform.toLinear() *
531 (character_.inverseBindPose[parentBone].linear().template cast<T>() * d_restPos));
532 }
533 }
534}
535
536template class HeightErrorFunctionT<float>;
537template class HeightErrorFunctionT<double>;
538
539} // namespace momentum
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
Definition checks.h:45
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Error function for character height constraints.
void setTargetHeight(T height)
Set the target height.
double getJacobian(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) final
void setUpDirection(const Eigen::Vector3< T > &upDirection)
Set the up direction for height measurement.
double getError(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
HeightErrorFunctionT(const Character &character, T targetHeight, const Eigen::Vector3< T > &upDirection=Eigen::Vector3< T >::UnitY(), size_t k=1)
Construct a height error function.
double getGradient(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) final
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
Functions for linear blend skinning (Skeletal Subspace Deformation).
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
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
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
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
Mesh_u mesh
3D mesh representing the character's surface
Definition character.h:55
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
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
ParameterSet getScalingParameters() const
Get a list of scaling parameters (with prefix "scale_").
ParameterSet getBlendShapeParameters() const
Get a list of blend shape parameters.
ParameterSet getFaceExpressionParameters() const
Get a list of face expression parameters.
Represents the complete state of a skeleton.