Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
joint_to_joint_orientation_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>
29
30template <typename T>
32 size_t sourceJoint,
33 size_t referenceJoint,
34 const Eigen::Quaternion<T>& target,
35 T weight,
36 const std::string& name) {
38 sourceJoint < this->skeleton_.joints.size(), "Invalid sourceJoint index: {}", sourceJoint);
40 referenceJoint < this->skeleton_.joints.size(),
41 "Invalid referenceJoint index: {}",
42 referenceJoint);
43
45 constraint.sourceJoint = sourceJoint;
46 constraint.referenceJoint = referenceJoint;
47 constraint.target = target.normalized();
48 constraint.weight = weight;
49 constraint.name = name;
50 constraints_.push_back(constraint);
51}
52
53template <typename T>
55 const JointToJointOrientationDataT<T>& constraint) {
57 constraint.sourceJoint < this->skeleton_.joints.size(),
58 "Invalid sourceJoint index: {}",
59 constraint.sourceJoint);
61 constraint.referenceJoint < this->skeleton_.joints.size(),
62 "Invalid referenceJoint index: {}",
63 constraint.referenceJoint);
64 constraints_.push_back(constraint);
65}
66
67template <typename T>
71
72template <typename T>
74 const ModelParametersT<T>& /* params */,
75 const SkeletonStateT<T>& state,
76 const MeshStateT<T>& /* meshState */) {
77 if (state.jointState.empty() || constraints_.empty()) {
78 return 0.0;
79 }
80
81 double error = 0.0;
82
83 for (const auto& constr : constraints_) {
84 const auto& srcJointState = state.jointState[constr.sourceJoint];
85 const auto& refJointState = state.jointState[constr.referenceJoint];
86
87 // Compute relative rotation: R_rel = R_ref^T * R_src
88 const Matrix3<T> srcRot = srcJointState.rotation().toRotationMatrix();
89 const Matrix3<T> refRot = refJointState.rotation().toRotationMatrix();
90 const Matrix3<T> relativeRot = refRot.transpose() * srcRot;
91
92 // Compute error: difference between relative rotation and target rotation
93 const Matrix3<T> targetRot = constr.target.toRotationMatrix();
94 const Matrix3<T> rotError = relativeRot - targetRot;
95
96 error += constr.weight * rotError.squaredNorm() * this->weight_;
97 }
98
99 return error;
100}
101
102template <typename T>
104 const ModelParametersT<T>& /* params */,
105 const SkeletonStateT<T>& state,
106 const MeshStateT<T>& /* meshState */,
107 Ref<VectorX<T>> gradient) {
109
110 if (state.jointState.empty() || constraints_.empty()) {
111 return 0.0;
112 }
113
114 double error = 0.0;
115
116 for (const auto& constr : constraints_) {
117 const auto& srcJointState = state.jointState[constr.sourceJoint];
118 const auto& refJointState = state.jointState[constr.referenceJoint];
119
120 // Compute relative rotation: R_rel = R_ref^T * R_src
121 const Matrix3<T> srcRot = srcJointState.rotation().toRotationMatrix();
122 const Matrix3<T> refRot = refJointState.rotation().toRotationMatrix();
123 const Matrix3<T> relativeRot = refRot.transpose() * srcRot;
124
125 // Compute error
126 const Matrix3<T> targetRot = constr.target.toRotationMatrix();
127 const Matrix3<T> rotError = relativeRot - targetRot;
128 error += constr.weight * rotError.squaredNorm() * this->weight_;
129
130 const T wgt = T(2) * constr.weight * this->weight_;
131
132 // The error is ||R_ref^T * R_src - R_target||_F^2
133 // d(error)/dq = 2 * sum_ij (R_rel - R_target)_ij * d(R_rel)_ij/dq
134 //
135 // R_rel = R_ref^T * R_src, so each column of R_rel is:
136 // R_rel[:,k] = R_ref^T * R_src[:,k]
137 //
138 // This has the same structure as the position case but with 3 columns
139 // of the rotation matrix instead of a single position vector.
140
141 // Process source joint chain: d(R_ref^T * R_src)/d(src params)
142 // = R_ref^T * d(R_src)/d(src params)
143 // For each column k of R_src, the derivative with respect to rotation parameters
144 // gives cross product with the column vector.
145 for (int col = 0; col < 3; col++) {
146 const Vector3<T> srcCol = srcRot.col(col);
147 const Vector3<T> errCol = rotError.col(col);
148 // worldGrad = R_ref * errCol transforms back to world frame
149 const Vector3<T> worldGrad = refRot * errCol;
150
151 // Process source joint chain (positive contribution)
152 size_t currentJoint = constr.sourceJoint;
153 while (currentJoint != kInvalidIndex) {
154 const auto& currentJointState = state.jointState[currentJoint];
155 const size_t paramIndex = currentJoint * kParametersPerJoint;
156
157 // Only rotation derivatives affect the rotation matrix columns
158 for (size_t d = 0; d < 3; d++) {
159 if (this->activeJointParams_[paramIndex + 3 + d]) {
160 const T val = worldGrad.dot(currentJointState.getRotationDerivative(d, srcCol)) * wgt;
161 for (auto index =
162 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
163 index <
164 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
165 ++index) {
166 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
167 val * this->parameterTransform_.transform.valuePtr()[index];
168 }
169 }
170 }
171
172 currentJoint = this->skeleton_.joints[currentJoint].parent;
173 }
174
175 // Process reference joint chain: d(R_ref^T * R_src[:,col])/d(ref params)
176 // This has two parts:
177 // 1. d(R_ref^T)/d(ref params) * R_src[:,col] (rotation of reference frame)
178 currentJoint = constr.referenceJoint;
179 while (currentJoint != kInvalidIndex) {
180 const auto& currentJointState = state.jointState[currentJoint];
181 const size_t paramIndex = currentJoint * kParametersPerJoint;
182
183 for (size_t d = 0; d < 3; d++) {
184 if (this->activeJointParams_[paramIndex + 3 + d]) {
185 // d(R_ref^T)/d(rot_i) * srcCol = -R_ref^T * [axis_i]_x * srcCol
186 // The gradient contribution is: errCol^T * (-R_ref^T * [axis_i]_x * srcCol)
187 // = -worldGrad^T * getRotationDerivative(d, srcCol)
188 const T val = -worldGrad.dot(currentJointState.getRotationDerivative(d, srcCol)) * wgt;
189 for (auto index =
190 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
191 index <
192 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
193 ++index) {
194 gradient[this->parameterTransform_.transform.innerIndexPtr()[index]] +=
195 val * this->parameterTransform_.transform.valuePtr()[index];
196 }
197 }
198 }
199
200 currentJoint = this->skeleton_.joints[currentJoint].parent;
201 }
202 }
203 }
204
205 return error;
206}
207
208template <typename T>
210 const ModelParametersT<T>& /* params */,
211 const SkeletonStateT<T>& state,
212 const MeshStateT<T>& /* meshState */,
213 Ref<MatrixX<T>> jacobian,
214 Ref<VectorX<T>> residual,
215 int& usedRows) {
217
218 MT_CHECK(
219 jacobian.rows() >= gsl::narrow<Eigen::Index>(9 * constraints_.size()),
220 "Jacobian rows mismatch: Actual {}, Expected at least {}",
221 jacobian.rows(),
222 9 * constraints_.size());
223
224 MT_CHECK(
225 residual.rows() >= gsl::narrow<Eigen::Index>(9 * constraints_.size()),
226 "Residual rows mismatch: Actual {}, Expected at least {}",
227 residual.rows(),
228 9 * constraints_.size());
229
230 if (state.jointState.empty() || constraints_.empty()) {
231 usedRows = 0;
232 return 0.0;
233 }
234
235 const T wgt = std::sqrt(this->weight_);
236 int pos = 0;
237 double error = 0.0;
238
239 for (const auto& constr : constraints_) {
240 const auto& srcJointState = state.jointState[constr.sourceJoint];
241 const auto& refJointState = state.jointState[constr.referenceJoint];
242
243 // Compute relative rotation
244 const Matrix3<T> srcRot = srcJointState.rotation().toRotationMatrix();
245 const Matrix3<T> refRot = refJointState.rotation().toRotationMatrix();
246 const Matrix3<T> refRotT = refRot.transpose();
247 const Matrix3<T> relativeRot = refRotT * srcRot;
248
249 // Compute error
250 const Matrix3<T> targetRot = constr.target.toRotationMatrix();
251 const Matrix3<T> rotError = relativeRot - targetRot;
252 error += constr.weight * rotError.squaredNorm() * this->weight_;
253
254 const T fac = std::sqrt(constr.weight) * wgt;
255 const int baseRow = pos;
256 pos += 9;
257
258 // Set residual: 9 elements from the rotation error matrix (column-major)
259 for (int col = 0; col < 3; col++) {
260 for (int row = 0; row < 3; row++) {
261 residual(baseRow + col * 3 + row) = rotError(row, col) * fac;
262 }
263 }
264
265 // Jacobian: for each column of the rotation matrix
266 for (int col = 0; col < 3; col++) {
267 const Vector3<T> srcCol = srcRot.col(col);
268
269 // Source joint chain: d(R_ref^T * R_src[:,col])/d(src params)
270 // = R_ref^T * d(R_src[:,col])/d(src params)
271 size_t currentJoint = constr.sourceJoint;
272 while (currentJoint != kInvalidIndex) {
273 const auto& currentJointState = state.jointState[currentJoint];
274 const size_t paramIndex = currentJoint * kParametersPerJoint;
275
276 for (size_t d = 0; d < 3; d++) {
277 if (this->activeJointParams_[paramIndex + 3 + d]) {
278 // d(R_src[:,col])/d(rot_i) = getRotationDerivative(d, srcCol)
279 const Vector3<T> dWorldCol = currentJointState.getRotationDerivative(d, srcCol);
280 const Vector3<T> dRelativeCol = refRotT * dWorldCol;
281 for (auto index =
282 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
283 index <
284 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
285 ++index) {
286 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
287 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
288 for (int row = 0; row < 3; row++) {
289 jacobian(baseRow + col * 3 + row, paramCol) += dRelativeCol(row) * coeff;
290 }
291 }
292 }
293 }
294
295 currentJoint = this->skeleton_.joints[currentJoint].parent;
296 }
297
298 // Reference joint chain: d(R_ref^T * srcCol)/d(ref params)
299 // = d(R_ref^T)/d(ref params) * srcCol
300 currentJoint = constr.referenceJoint;
301 while (currentJoint != kInvalidIndex) {
302 const auto& currentJointState = state.jointState[currentJoint];
303 const size_t paramIndex = currentJoint * kParametersPerJoint;
304
305 for (size_t d = 0; d < 3; d++) {
306 if (this->activeJointParams_[paramIndex + 3 + d]) {
307 // d(R_ref^T)/d(rot_i) * srcCol = -R_ref^T * [axis_i]_x * srcCol
308 const Vector3<T> dRotCol = currentJointState.getRotationDerivative(d, srcCol);
309 const Vector3<T> dRelativeCol = -refRotT * dRotCol;
310 for (auto index =
311 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d];
312 index <
313 this->parameterTransform_.transform.outerIndexPtr()[paramIndex + 3 + d + 1];
314 ++index) {
315 const auto paramCol = this->parameterTransform_.transform.innerIndexPtr()[index];
316 const T coeff = this->parameterTransform_.transform.valuePtr()[index] * fac;
317 for (int row = 0; row < 3; row++) {
318 jacobian(baseRow + col * 3 + row, paramCol) += dRelativeCol(row) * coeff;
319 }
320 }
321 }
322 }
323
324 currentJoint = this->skeleton_.joints[currentJoint].parent;
325 }
326 }
327 }
328
329 usedRows = pos;
330 return error;
331}
332
333template <typename T>
335 return 9 * constraints_.size();
336}
337
340
341} // 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 orientation expressed relative to a reference j...
double getGradient(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Ref< VectorX< T > > gradient) override
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
void addConstraint(size_t sourceJoint, size_t referenceJoint, const Eigen::Quaternion< T > &target, T weight=T(1), const std::string &name={})
Add a joint-to-joint orientation constraint.
JointToJointOrientationErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
double getError(const ModelParametersT< T > &params, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
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 orientation error between two joints.
std::string name
Name of the constraint (for debugging).
Eigen::Quaternion< T > target
Target relative orientation as a quaternion (R_ref^T * R_src should match this).
size_t sourceJoint
Index of the source joint (the joint whose orientation we want to constrain).
size_t referenceJoint
Index of the reference joint (the joint whose coordinate frame we use).
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.