Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
joint_to_joint_position_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
16
17namespace momentum {
18
19template <typename T>
24
25template <typename T>
27 const Character& character)
28 : JointToJointPositionErrorFunctionT(character.skeleton, character.parameterTransform) {}
29
30template <typename T>
32 size_t sourceJoint,
33 const Vector3<T>& sourceOffset,
34 size_t referenceJoint,
35 const Vector3<T>& referenceOffset,
36 const Vector3<T>& target,
37 T weight,
38 const std::string& name) {
40 sourceJoint < this->skeleton_.joints.size(), "Invalid sourceJoint index: {}", sourceJoint);
42 referenceJoint < this->skeleton_.joints.size(),
43 "Invalid referenceJoint index: {}",
44 referenceJoint);
45
47 constraint.sourceJoint = sourceJoint;
48 constraint.sourceOffset = sourceOffset;
49 constraint.referenceJoint = referenceJoint;
50 constraint.referenceOffset = referenceOffset;
51 constraint.target = target;
52 constraint.weight = weight;
53 constraint.name = name;
54 constraints_.push_back(constraint);
55}
56
57template <typename T>
59 const JointToJointPositionDataT<T>& constraint) {
61 constraint.sourceJoint < this->skeleton_.joints.size(),
62 "Invalid sourceJoint index: {}",
63 constraint.sourceJoint);
65 constraint.referenceJoint < this->skeleton_.joints.size(),
66 "Invalid referenceJoint index: {}",
67 constraint.referenceJoint);
68 constraints_.push_back(constraint);
69}
70
71template <typename T>
73 constraints_.clear();
74}
75
76template <typename T>
78 const ModelParametersT<T>& /* params */,
79 const SkeletonStateT<T>& state,
80 const MeshStateT<T>& /* meshState */) {
81 if (state.jointState.empty() || constraints_.empty()) {
82 return 0.0;
83 }
84
85 double error = 0.0;
86
87 for (const auto& constr : constraints_) {
88 const auto& srcJointState = state.jointState[constr.sourceJoint];
89 const auto& refJointState = state.jointState[constr.referenceJoint];
90
91 // Compute world positions
92 const Vector3<T> srcWorldPos = srcJointState.transform * constr.sourceOffset;
93 const Vector3<T> refWorldPos = refJointState.transform * constr.referenceOffset;
94
95 // Transform source position to reference frame
96 // relativePos = R_ref^T * (srcWorldPos - refWorldPos)
97 const Vector3<T> diff = srcWorldPos - refWorldPos;
98 const Vector3<T> relativePos = refJointState.transform.toRotationMatrix().transpose() * diff;
99
100 // Compute error: difference between relative position and target
101 const Vector3<T> posError = relativePos - constr.target;
102
103 error += constr.weight * posError.squaredNorm() * this->weight_;
104 }
105
106 return error;
107}
108
109template <typename T>
111 const ModelParametersT<T>& /* params */,
112 const SkeletonStateT<T>& state,
113 const MeshStateT<T>& /* meshState */,
114 Ref<VectorX<T>> gradient) {
116
117 if (state.jointState.empty() || constraints_.empty()) {
118 return 0.0;
119 }
120
121 double error = 0.0;
122
123 for (const auto& constr : constraints_) {
124 const auto& srcJointState = state.jointState[constr.sourceJoint];
125 const auto& refJointState = state.jointState[constr.referenceJoint];
126
127 // Compute world positions
128 const Vector3<T> srcWorldPos = srcJointState.transform * constr.sourceOffset;
129 const Vector3<T> refWorldPos = refJointState.transform * constr.referenceOffset;
130
131 // Transform source position to reference frame
132 const Vector3<T> diff = srcWorldPos - refWorldPos;
133 const Matrix3<T> refRotT = refJointState.transform.toRotationMatrix().transpose();
134 const Vector3<T> relativePos = refRotT * diff;
135
136 // Compute error
137 const Vector3<T> posError = relativePos - constr.target;
138 error += constr.weight * posError.squaredNorm() * this->weight_;
139
140 // Gradient computation
141 // d(error)/dq = 2 * w * posError^T * d(relativePos)/dq
142 // relativePos = R_ref^T * (srcWorldPos - refWorldPos)
143 // d(relativePos)/dq = R_ref^T * d(srcWorldPos)/dq
144 // - R_ref^T * d(refWorldPos)/dq
145 // + d(R_ref^T)/dq * (srcWorldPos - refWorldPos)
146
147 const T wgt = T(2) * constr.weight * this->weight_;
148 // Transform error back to world frame for gradient computation
149 const Vector3<T> worldGrad = refJointState.transform.toRotationMatrix() * posError;
150
151 // Process source joint chain (positive contribution)
152 auto processSourceJoint = [&](size_t jointIndex, const Vector3<T>& worldPos) {
153 size_t currentJoint = jointIndex;
154 while (currentJoint != kInvalidIndex) {
155 const auto& currentJointState = state.jointState[currentJoint];
156 const size_t paramIndex = currentJoint * kParametersPerJoint;
157 const Vector3<T> posd = worldPos - currentJointState.translation();
158
159 // Translation derivatives
160 for (size_t d = 0; d < 3; d++) {
161 if (this->activeJointParams_[paramIndex + d]) {
162 const T val = worldGrad.dot(currentJointState.getTranslationDerivative(d)) * wgt;
163 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d];
164 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d + 1];
165 ++index) {
166 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
167 val * this->parameterTransform_.transform.valuePtr()[index];
168 }
169 }
170 // Rotation derivatives
171 if (this->activeJointParams_[paramIndex + 3 + d]) {
172 const T val = worldGrad.dot(currentJointState.getRotationDerivative(d, posd)) * wgt;
173 for (auto index =
174 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
175 index <
176 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
177 ++index) {
178 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
179 val * this->parameterTransform_.transform.valuePtr()[index];
180 }
181 }
182 }
183 // Scale derivative
184 if (this->activeJointParams_[paramIndex + 6]) {
185 const T val = worldGrad.dot(currentJointState.getScaleDerivative(posd)) * wgt;
186 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6];
187 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6 + 1];
188 ++index) {
189 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
190 val * this->parameterTransform_.transform.valuePtr()[index];
191 }
192 }
193
194 currentJoint = this->skeleton_.joints[currentJoint].parent;
195 }
196 };
197
198 // Process reference joint chain (negative contribution for translation, plus rotation effect)
199 auto processReferenceJoint = [&](size_t jointIndex, const Vector3<T>& worldPos) {
200 size_t currentJoint = jointIndex;
201 while (currentJoint != kInvalidIndex) {
202 const auto& currentJointState = state.jointState[currentJoint];
203 const size_t paramIndex = currentJoint * kParametersPerJoint;
204 const Vector3<T> posd = worldPos - currentJointState.translation();
205
206 // Translation derivatives (negative contribution)
207 for (size_t d = 0; d < 3; d++) {
208 if (this->activeJointParams_[paramIndex + d]) {
209 const T val = -worldGrad.dot(currentJointState.getTranslationDerivative(d)) * wgt;
210 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d];
211 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d + 1];
212 ++index) {
213 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
214 val * this->parameterTransform_.transform.valuePtr()[index];
215 }
216 }
217 // Rotation derivatives (negative contribution from translation part)
218 if (this->activeJointParams_[paramIndex + 3 + d]) {
219 const T val = -worldGrad.dot(currentJointState.getRotationDerivative(d, posd)) * wgt;
220 for (auto index =
221 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
222 index <
223 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
224 ++index) {
225 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
226 val * this->parameterTransform_.transform.valuePtr()[index];
227 }
228 }
229 }
230 // Scale derivative (negative contribution)
231 if (this->activeJointParams_[paramIndex + 6]) {
232 const T val = -worldGrad.dot(currentJointState.getScaleDerivative(posd)) * wgt;
233 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6];
234 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6 + 1];
235 ++index) {
236 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
237 val * this->parameterTransform_.transform.valuePtr()[index];
238 }
239 }
240
241 currentJoint = this->skeleton_.joints[currentJoint].parent;
242 }
243 };
244
245 // Additional gradient from rotation of reference frame
246 // d(R_ref^T * diff)/dR_ref contributes to joints in reference chain
247 auto processReferenceRotation = [&](size_t jointIndex) {
248 size_t currentJoint = jointIndex;
249 while (currentJoint != kInvalidIndex) {
250 const auto& currentJointState = state.jointState[currentJoint];
251 const size_t paramIndex = currentJoint * kParametersPerJoint;
252
253 // Only rotation derivatives affect R_ref
254 for (size_t d = 0; d < 3; d++) {
255 if (this->activeJointParams_[paramIndex + 3 + d]) {
256 // d(R_ref^T)/d(rot_angle_i) * diff
257 // = ([axis_i]_x R_ref)^T * diff
258 // = -R_ref^T * [axis_i]_x * diff
259 // where [axis_i]_x is the skew-symmetric matrix of the rotation axis i
260 const T val = -worldGrad.dot(currentJointState.getRotationDerivative(d, diff)) * wgt;
261 for (auto index =
262 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
263 index <
264 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
265 ++index) {
266 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
267 val * this->parameterTransform_.transform.valuePtr()[index];
268 }
269 }
270 }
271
272 currentJoint = this->skeleton_.joints[currentJoint].parent;
273 }
274 };
275
276 processSourceJoint(constr.sourceJoint, srcWorldPos);
277 processReferenceJoint(constr.referenceJoint, refWorldPos);
278 processReferenceRotation(constr.referenceJoint);
279 }
280
281 return error;
282}
283
284template <typename T>
286 const ModelParametersT<T>& /* params */,
287 const SkeletonStateT<T>& state,
288 const MeshStateT<T>& /* meshState */,
289 Ref<MatrixX<T>> jacobian,
290 Ref<VectorX<T>> residual,
291 int& usedRows) {
293
294 MT_CHECK(
295 jacobian.rows() >= gsl::narrow<Eigen::Index>(3 * constraints_.size()),
296 "Jacobian rows mismatch: Actual {}, Expected at least {}",
297 jacobian.rows(),
298 3 * constraints_.size());
299
300 MT_CHECK(
301 residual.rows() >= gsl::narrow<Eigen::Index>(3 * constraints_.size()),
302 "Residual rows mismatch: Actual {}, Expected at least {}",
303 residual.rows(),
304 3 * constraints_.size());
305
306 if (state.jointState.empty() || constraints_.empty()) {
307 usedRows = 0;
308 return 0.0;
309 }
310
311 const T wgt = std::sqrt(this->weight_);
312 int pos = 0;
313 double error = 0.0;
314
315 for (const auto& constr : constraints_) {
316 const auto& srcJointState = state.jointState[constr.sourceJoint];
317 const auto& refJointState = state.jointState[constr.referenceJoint];
318
319 // Compute world positions
320 const Vector3<T> srcWorldPos = srcJointState.transform * constr.sourceOffset;
321 const Vector3<T> refWorldPos = refJointState.transform * constr.referenceOffset;
322
323 // Transform source position to reference frame
324 const Vector3<T> diff = srcWorldPos - refWorldPos;
325 const Matrix3<T> refRotT = refJointState.transform.toRotationMatrix().transpose();
326 const Vector3<T> relativePos = refRotT * diff;
327
328 // Compute error
329 const Vector3<T> posError = relativePos - constr.target;
330 error += constr.weight * posError.squaredNorm() * this->weight_;
331
332 const T fac = std::sqrt(constr.weight) * wgt;
333 const int baseRow = pos;
334 pos += 3;
335
336 // Set residual
337 for (int d = 0; d < 3; d++) {
338 residual(baseRow + d) = posError(d) * fac;
339 }
340
341 // Jacobian from source joint chain
342 auto processSourceJoint = [&](size_t jointIndex, const Vector3<T>& worldPos) {
343 size_t currentJoint = jointIndex;
344 while (currentJoint != kInvalidIndex) {
345 const auto& currentJointState = state.jointState[currentJoint];
346 const size_t paramIndex = currentJoint * kParametersPerJoint;
347 const Vector3<T> posd = worldPos - currentJointState.translation();
348
349 for (size_t d = 0; d < 3; d++) {
350 if (this->activeJointParams_[paramIndex + d]) {
351 // d(relativePos)/d(trans) = R_ref^T * d(srcWorldPos)/d(trans)
352 const Vector3<T> dWorldPos = currentJointState.getTranslationDerivative(d);
353 const Vector3<T> dRelativePos = refRotT * dWorldPos;
354 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d];
355 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d + 1];
356 ++index) {
357 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
358 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
359 for (int row = 0; row < 3; row++) {
360 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
361 }
362 }
363 }
364 if (this->activeJointParams_[paramIndex + 3 + d]) {
365 const Vector3<T> dWorldPos = currentJointState.getRotationDerivative(d, posd);
366 const Vector3<T> dRelativePos = refRotT * dWorldPos;
367 for (auto index =
368 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
369 index <
370 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
371 ++index) {
372 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
373 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
374 for (int row = 0; row < 3; row++) {
375 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
376 }
377 }
378 }
379 }
380 if (this->activeJointParams_[paramIndex + 6]) {
381 const Vector3<T> dWorldPos = currentJointState.getScaleDerivative(posd);
382 const Vector3<T> dRelativePos = refRotT * dWorldPos;
383 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6];
384 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6 + 1];
385 ++index) {
386 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
387 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
388 for (int row = 0; row < 3; row++) {
389 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
390 }
391 }
392 }
393
394 currentJoint = this->skeleton_.joints[currentJoint].parent;
395 }
396 };
397
398 // Jacobian from reference joint chain (translation part - negative)
399 auto processReferenceJoint = [&](size_t jointIndex, const Vector3<T>& worldPos) {
400 size_t currentJoint = jointIndex;
401 while (currentJoint != kInvalidIndex) {
402 const auto& currentJointState = state.jointState[currentJoint];
403 const size_t paramIndex = currentJoint * kParametersPerJoint;
404 const Vector3<T> posd = worldPos - currentJointState.translation();
405
406 for (size_t d = 0; d < 3; d++) {
407 if (this->activeJointParams_[paramIndex + d]) {
408 const Vector3<T> dWorldPos = currentJointState.getTranslationDerivative(d);
409 const Vector3<T> dRelativePos = -refRotT * dWorldPos;
410 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d];
411 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + d + 1];
412 ++index) {
413 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
414 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
415 for (int row = 0; row < 3; row++) {
416 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
417 }
418 }
419 }
420 if (this->activeJointParams_[paramIndex + 3 + d]) {
421 const Vector3<T> dWorldPos = currentJointState.getRotationDerivative(d, posd);
422 const Vector3<T> dRelativePos = -refRotT * dWorldPos;
423 for (auto index =
424 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
425 index <
426 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
427 ++index) {
428 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
429 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
430 for (int row = 0; row < 3; row++) {
431 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
432 }
433 }
434 }
435 }
436 if (this->activeJointParams_[paramIndex + 6]) {
437 const Vector3<T> dWorldPos = currentJointState.getScaleDerivative(posd);
438 const Vector3<T> dRelativePos = -refRotT * dWorldPos;
439 for (auto index = this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6];
440 index < this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 6 + 1];
441 ++index) {
442 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
443 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
444 for (int row = 0; row < 3; row++) {
445 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
446 }
447 }
448 }
449
450 currentJoint = this->skeleton_.joints[currentJoint].parent;
451 }
452 };
453
454 // Jacobian from reference joint rotation (affects R_ref^T)
455 auto processReferenceRotation = [&](size_t jointIndex) {
456 size_t currentJoint = jointIndex;
457 while (currentJoint != kInvalidIndex) {
458 const auto& currentJointState = state.jointState[currentJoint];
459 const size_t paramIndex = currentJoint * kParametersPerJoint;
460
461 for (size_t d = 0; d < 3; d++) {
462 if (this->activeJointParams_[paramIndex + 3 + d]) {
463 // d(R_ref^T)/d(rot_angle_i) * diff
464 // = ([axis_i]_x R_ref)^T * diff
465 // = -R_ref^T * [axis_i]_x * diff
466 // where [axis_i]_x is the skew-symmetric matrix of the rotation axis i
467 const Vector3<T> dRotDiff = currentJointState.getRotationDerivative(d, diff);
468 const Vector3<T> dRelativePos = -refRotT * dRotDiff;
469 for (auto index =
470 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
471 index <
472 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
473 ++index) {
474 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
475 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
476 for (int row = 0; row < 3; row++) {
477 jacobian(baseRow + row, paramCol) += dRelativePos(row) * coeff;
478 }
479 }
480 }
481 }
482
483 currentJoint = this->skeleton_.joints[currentJoint].parent;
484 }
485 };
486
487 processSourceJoint(constr.sourceJoint, srcWorldPos);
488 processReferenceJoint(constr.referenceJoint, refWorldPos);
489 processReferenceRotation(constr.referenceJoint);
490 }
491
492 usedRows = pos;
493 return error;
494}
495
496template <typename T>
498 return 3 * constraints_.size();
499}
500
503
504} // namespace momentum
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
Error function that penalizes deviation from a target position expressed in a reference joint's coord...
JointToJointPositionErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) override
void addConstraint(size_t sourceJoint, const Vector3< T > &sourceOffset, size_t referenceJoint, const Vector3< T > &referenceOffset, const Vector3< T > &target, T weight=T(1), const std::string &name={})
Add a joint-to-joint position constraint.
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
double getJacobian(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< MatrixX< T > > jacobian, Ref< VectorX< T > > residual, int &usedRows) override
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
const ParameterTransform & parameterTransform_
SkeletonT< float > Skeleton
Definition fwd.h:263
Eigen::Matrix< T, 3, 3 > Matrix3
Definition types.h:96
Eigen::Ref< T > Ref
Definition types.h:43
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
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
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector< T, 3 > Vector3
Definition types.h:236
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
Constraint data for joint-to-joint position error between two joints.
size_t referenceJoint
Index of the reference joint (the joint whose coordinate frame we use).
Vector3< T > referenceOffset
Offset from referenceJoint in the local coordinate system of referenceJoint.
size_t sourceJoint
Index of the source joint (the joint whose position we want to constrain).
std::string name
Name of the constraint (for debugging).
Vector3< T > target
Target position in the reference joint's coordinate frame.
Vector3< T > sourceOffset
Offset from sourceJoint in the local coordinate system of sourceJoint.
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.