Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
floor_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
19#include "momentum/math/mesh.h"
20
21#include <queue>
22
23namespace momentum {
24
25template <typename T>
27 const Character& character,
28 std::vector<size_t> vertexIndices,
29 T targetHeight,
30 const Eigen::Vector3<T>& upDirection,
31 size_t k)
32 : SkeletonErrorFunctionT<T>(character.skeleton, character.parameterTransform),
33 character_(character),
34 vertexIndices_(std::move(vertexIndices)),
35 targetHeight_(targetHeight),
36 upDirection_(upDirection.normalized()),
37 k_(k) {
38 MT_CHECK(k > 0, "k must be greater than 0, got {}", k);
39 MT_CHECK(!vertexIndices_.empty(), "FloorErrorFunction requires at least one vertex index");
40 MT_CHECK(character.mesh != nullptr, "FloorErrorFunction requires a character with a mesh");
41}
42
43template <typename T>
45
46template <typename T>
48 targetHeight_ = height;
49}
50
51template <typename T>
52void FloorErrorFunctionT<T>::setUpDirection(const Eigen::Vector3<T>& upDirection) {
53 upDirection_ = upDirection.normalized();
54}
55
56template <typename T>
57void FloorErrorFunctionT<T>::setVertexIndices(std::vector<size_t> indices) {
58 MT_CHECK(!indices.empty(), "FloorErrorFunction requires at least one vertex index");
59 vertexIndices_ = std::move(indices);
60}
61
62template <typename T>
63typename FloorErrorFunctionT<T>::MinHeightResult FloorErrorFunctionT<T>::calculateMinHeight(
64 const MeshStateT<T>& meshState) const {
66
68
69 const size_t effectiveK = std::min(k_, vertexIndices_.size());
70
71 // Max heap for k lowest projections (top = largest of the k lowest)
72 using ProjectionPair = std::pair<T, size_t>; // (projection, vertex_index)
73 std::priority_queue<ProjectionPair, std::vector<ProjectionPair>, std::less<>> minQueue;
74
75 for (const auto vertexIdx : vertexIndices_) {
77 vertexIdx < meshState.posedMesh_->vertices.size(),
78 "Vertex index {} out of range (mesh has {} vertices)",
79 vertexIdx,
80 meshState.posedMesh_->vertices.size());
81
82 const T projection = upDirection_.dot(meshState.posedMesh_->vertices[vertexIdx]);
83
84 if (minQueue.size() < effectiveK) {
85 minQueue.push({projection, vertexIdx});
86 } else if (projection < minQueue.top().first) {
87 minQueue.pop();
88 minQueue.push({projection, vertexIdx});
89 }
90 }
91
92 MinHeightResult result;
93 result.vertexIndices.reserve(effectiveK);
94 result.vertexWeights.reserve(effectiveK);
95
96 T projectionSum = T(0);
97 while (!minQueue.empty()) {
98 const auto& pair = minQueue.top();
99 result.vertexIndices.push_back(pair.second);
100 projectionSum += pair.first;
101 minQueue.pop();
102 }
103
104 const T weight = T(1) / T(effectiveK);
105 result.vertexWeights.resize(effectiveK, weight);
106 result.avgProjection = projectionSum / T(effectiveK);
107
108 return result;
109}
110
111template <typename T>
113 const ModelParametersT<T>& /* modelParameters */,
114 const SkeletonStateT<T>& /* state */,
115 const MeshStateT<T>& meshState) {
117
118 const auto minResult = calculateMinHeight(meshState);
119 const T diff = minResult.avgProjection - targetHeight_;
120
121 return this->weight_ * diff * diff;
122}
123
124template <typename T>
126 const ModelParametersT<T>& /* modelParameters */,
127 const SkeletonStateT<T>& state,
128 const MeshStateT<T>& meshState,
129 Eigen::Ref<Eigen::VectorX<T>> gradient) {
131
132 const auto minResult = calculateMinHeight(meshState);
133 const T diff = minResult.avgProjection - targetHeight_;
134
135 const T wgt = T(2) * diff * this->weight_;
136
137 for (size_t i = 0; i < minResult.vertexIndices.size(); ++i) {
138 calculateVertexGradient(
139 minResult.vertexIndices[i],
140 state,
141 meshState,
142 wgt * minResult.vertexWeights[i] * upDirection_,
143 gradient);
144 }
145
146 return this->weight_ * diff * diff;
147}
148
149template <typename T>
151 const ModelParametersT<T>& /* modelParameters */,
152 const SkeletonStateT<T>& state,
153 const MeshStateT<T>& meshState,
154 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
155 Eigen::Ref<Eigen::VectorX<T>> residual,
156 int& usedRows) {
158
159 MT_CHECK(
160 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()));
161 MT_CHECK(jacobian.rows() >= 1);
162 MT_CHECK(residual.rows() >= 1);
163
164 const auto minResult = calculateMinHeight(meshState);
165 const T diff = minResult.avgProjection - targetHeight_;
166
167 const T wgt = std::sqrt(this->weight_);
168 residual(0) = wgt * diff;
169
170 jacobian.row(0).setZero();
171 auto jac_row = jacobian.row(0);
172
173 for (size_t i = 0; i < minResult.vertexIndices.size(); ++i) {
174 calculateVertexJacobian(
175 minResult.vertexIndices[i],
176 state,
177 meshState,
178 wgt * minResult.vertexWeights[i] * upDirection_,
179 jac_row);
180 }
181
182 usedRows = 1;
183 return wgt * wgt * diff * diff;
184}
185
186template <typename T>
188 return 1;
189}
190
191template <typename T>
192template <typename Derived>
193void FloorErrorFunctionT<T>::calculateVertexJacobian(
194 size_t vertexIndex,
195 const SkeletonStateT<T>& state,
196 const MeshStateT<T>& meshState,
197 const Eigen::Vector3<T>& jacobianDirection,
198 Eigen::MatrixBase<Derived>& jacobian) const {
200
201 MT_CHECK_NOTNULL(meshState.restMesh_);
202
203 SkinningWeightIteratorT<T> skinningIter(
204 this->character_, *meshState.restMesh_, state, vertexIndex);
205
206 while (!skinningIter.finished()) {
207 size_t jointIndex = 0;
208 T boneWeight;
209 Eigen::Vector3<T> pos;
210 std::tie(jointIndex, boneWeight, pos) = skinningIter.next();
211
212 MT_CHECK(jointIndex < this->skeleton_.joints.size());
213
214 const auto& jointState = state.jointState[jointIndex];
215 const size_t paramIndex = jointIndex * kParametersPerJoint;
216 const Eigen::Vector3<T> posd = pos - jointState.translation();
217
218 for (size_t d = 0; d < 3; d++) {
219 if (this->activeJointParams_[paramIndex + d]) {
221 boneWeight * jacobianDirection.dot(jointState.getTranslationDerivative(d)),
222 paramIndex + d,
223 this->parameterTransform_,
224 jacobian);
225 }
226 if (this->activeJointParams_[paramIndex + 3 + d]) {
228 boneWeight * jacobianDirection.dot(jointState.getRotationDerivative(d, posd)),
229 paramIndex + 3 + d,
230 this->parameterTransform_,
231 jacobian);
232 }
233 }
234 if (this->activeJointParams_[paramIndex + 6]) {
236 boneWeight * jacobianDirection.dot(jointState.getScaleDerivative(posd)),
237 paramIndex + 6,
238 this->parameterTransform_,
239 jacobian);
240 }
241 }
242}
243
244template <typename T>
245void FloorErrorFunctionT<T>::calculateVertexGradient(
246 size_t vertexIndex,
247 const SkeletonStateT<T>& state,
248 const MeshStateT<T>& meshState,
249 const Eigen::Vector3<T>& gradientDirection,
250 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
252
253 MT_CHECK_NOTNULL(meshState.restMesh_);
254
255 SkinningWeightIteratorT<T> skinningIter(
256 this->character_, *meshState.restMesh_, state, vertexIndex);
257
258 while (!skinningIter.finished()) {
259 size_t jointIndex = 0;
260 T boneWeight;
261 Eigen::Vector3<T> pos;
262 std::tie(jointIndex, boneWeight, pos) = skinningIter.next();
263
264 MT_CHECK(jointIndex < this->skeleton_.joints.size());
265
266 const auto& jointState = state.jointState[jointIndex];
267 const size_t paramIndex = jointIndex * kParametersPerJoint;
268 const Eigen::Vector3<T> posd = pos - jointState.translation();
269
270 for (size_t d = 0; d < 3; d++) {
271 if (this->activeJointParams_[paramIndex + d]) {
273 boneWeight * gradientDirection.dot(jointState.getTranslationDerivative(d)),
274 paramIndex + d,
275 this->parameterTransform_,
276 gradient);
277 }
278 if (this->activeJointParams_[paramIndex + 3 + d]) {
280 boneWeight * gradientDirection.dot(jointState.getRotationDerivative(d, posd)),
281 paramIndex + 3 + d,
282 this->parameterTransform_,
283 gradient);
284 }
285 }
286 if (this->activeJointParams_[paramIndex + 6]) {
288 boneWeight * gradientDirection.dot(jointState.getScaleDerivative(posd)),
289 paramIndex + 6,
290 this->parameterTransform_,
291 gradient);
292 }
293 }
294}
295
296template class FloorErrorFunctionT<float>;
297template class FloorErrorFunctionT<double>;
298
299} // namespace momentum
#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 that constrains the minimum vertex height to a target value.
FloorErrorFunctionT(const Character &character, std::vector< size_t > vertexIndices, T targetHeight=T(0), const Eigen::Vector3< T > &upDirection=Eigen::Vector3< T >::UnitY(), size_t k=5)
Construct a floor error function.
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 setTargetHeight(T height)
Set the target height for the minimum vertices.
void setUpDirection(const Eigen::Vector3< T > &upDirection)
Set the up direction for height measurement.
void setVertexIndices(std::vector< size_t > indices)
Set the candidate vertex indices.
double getGradient(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) final
double getError(const ModelParametersT< T > &modelParameters, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState) final
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
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)
void gradient_jointParams_to_modelParams(const T &grad_jointParams, const Eigen::Index iJointParam, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
constexpr size_t kParametersPerJoint
Definition types.h:21
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
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
Definition mesh_state.h:32
std::unique_ptr< MeshT< T > > restMesh_
Rest positions of the mesh after the shape basis (and potentially facial expression basis) has been a...
Definition mesh_state.h:30
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.