30void gradient_jointParams_to_modelParams_filtered(
31 const T& grad_jointParams,
32 const Eigen::Index iJointParam,
35 Eigen::Ref<Eigen::VectorX<T>> gradient) {
36 for (
auto index = parameterTransform.transform.outerIndexPtr()[iJointParam];
37 index < parameterTransform.transform.outerIndexPtr()[iJointParam + 1];
39 const auto modelParamIndex = parameterTransform.transform.innerIndexPtr()[index];
40 if (activeModelParams[modelParamIndex]) {
41 gradient[modelParamIndex] +=
42 grad_jointParams * parameterTransform.transform.valuePtr()[index];
49template <
typename T,
typename Derived>
50void jacobian_jointParams_to_modelParams_filtered(
51 const T& jacobian_jointParams,
52 const Eigen::Index iJointParam,
55 Eigen::MatrixBase<Derived>& jacobian) {
56 for (
auto index = parameterTransform.transform.outerIndexPtr()[iJointParam];
57 index < parameterTransform.transform.outerIndexPtr()[iJointParam + 1];
59 const auto modelParamIndex = parameterTransform.transform.innerIndexPtr()[index];
60 if (activeModelParams[modelParamIndex]) {
61 jacobian(0, modelParamIndex) +=
62 jacobian_jointParams * parameterTransform.transform.valuePtr()[index];
73 const Eigen::Vector3<T>& upDirection,
76 character_(character),
77 targetHeight_(targetHeight),
78 upDirection_(upDirection.normalized()),
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");
96 targetHeight_ = height;
101 upDirection_ = upDirection.normalized();
112 for (Eigen::Index i = 0; i < result.
size(); ++i) {
113 if (!activeModelParams_.test(i)) {
122typename HeightErrorFunctionT<T>::HeightResult HeightErrorFunctionT<T>::calculateHeight()
const {
127 if (meshState_.posedMesh_->vertices.empty()) {
128 return {T(0), {}, {}, {}, {}};
134 using ProjectionPair = std::pair<T, size_t>;
137 std::priority_queue<ProjectionPair, std::vector<ProjectionPair>, std::less<>> minQueue;
140 std::priority_queue<ProjectionPair, std::vector<ProjectionPair>, std::greater<>> maxQueue;
143 for (
size_t i = 0; i < meshState_.posedMesh_->vertices.size(); ++i) {
144 const T projection = upDirection_.dot(meshState_.posedMesh_->vertices[i]);
147 if (minQueue.size() < k_) {
148 minQueue.push({projection, i});
149 }
else if (projection < minQueue.top().first) {
151 minQueue.push({projection, i});
155 if (maxQueue.size() < k_) {
156 maxQueue.push({projection, i});
157 }
else if (projection > maxQueue.top().first) {
159 maxQueue.push({projection, i});
165 result.minVertexIndices.reserve(k_);
166 result.minVertexWeights.reserve(k_);
167 result.maxVertexIndices.reserve(k_);
168 result.maxVertexWeights.reserve(k_);
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;
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;
187 const T weight = T(1) / T(k_);
188 result.minVertexWeights.resize(k_, weight);
189 result.maxVertexWeights.resize(k_, weight);
192 const T avgMinProjection = minProjectionSum / T(k_);
193 const T avgMaxProjection = maxProjectionSum / T(k_);
194 result.height = avgMaxProjection - avgMinProjection;
214 meshState_.update(activeOnlyParams, skeletonState_, character_);
216 const auto heightResult = calculateHeight();
217 const T heightDiff = heightResult.height - targetHeight_;
219 return this->
weight_ * heightDiff * heightDiff;
227 Eigen::Ref<Eigen::VectorX<T>> gradient) {
238 meshState_.update(activeOnlyParams, skeletonState_, character_);
240 const auto heightResult = calculateHeight();
241 const T heightDiff = heightResult.height - targetHeight_;
243 const T wgt = T(2) * heightDiff * this->
weight_;
246 for (
size_t i = 0; i < heightResult.maxVertexIndices.size(); ++i) {
247 calculateVertexGradient(
248 heightResult.maxVertexIndices[i],
249 wgt * heightResult.maxVertexWeights[i] * upDirection_,
254 for (
size_t i = 0; i < heightResult.minVertexIndices.size(); ++i) {
255 calculateVertexGradient(
256 heightResult.minVertexIndices[i],
257 -wgt * heightResult.minVertexWeights[i] * upDirection_,
261 return this->weight_ * heightDiff * heightDiff;
269 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
270 Eigen::Ref<Eigen::VectorX<T>> residual,
275 jacobian.cols() ==
static_cast<Eigen::Index
>(this->parameterTransform_.transform.cols()));
287 meshState_.update(activeOnlyParams, skeletonState_, character_);
289 const auto heightResult = calculateHeight();
290 const T heightDiff = heightResult.height - targetHeight_;
292 const T wgt = std::sqrt(this->
weight_);
293 residual(0) = wgt * heightDiff;
295 jacobian.row(0).setZero();
296 auto jac_row = jacobian.row(0);
299 for (
size_t i = 0; i < heightResult.maxVertexIndices.size(); ++i) {
300 calculateVertexJacobian(
301 heightResult.maxVertexIndices[i],
302 wgt * heightResult.maxVertexWeights[i] * upDirection_,
307 for (
size_t i = 0; i < heightResult.minVertexIndices.size(); ++i) {
308 calculateVertexJacobian(
309 heightResult.minVertexIndices[i],
310 -wgt * heightResult.minVertexWeights[i] * upDirection_,
315 return wgt * wgt * heightDiff * heightDiff;
324template <
typename Derived>
325void HeightErrorFunctionT<T>::calculateVertexJacobian(
327 const Eigen::Vector3<T>& jacobianDirection,
328 Eigen::MatrixBase<Derived>& jacobian)
const {
334 this->character_, *meshState_.restMesh_, skeletonState_, vertexIndex);
336 while (!skinningIter.finished()) {
337 size_t jointIndex = 0;
339 Eigen::Vector3<T> pos;
340 std::tie(jointIndex, boneWeight, pos) = skinningIter.next();
342 MT_CHECK(jointIndex < this->skeleton_.joints.size());
344 const auto& jointState = skeletonState_.jointState[jointIndex];
346 const Eigen::Vector3<T> posd = pos - jointState.translation();
349 for (
size_t d = 0; d < 3; d++) {
350 if (this->activeJointParams_[paramIndex + d]) {
352 jacobian_jointParams_to_modelParams_filtered<T>(
353 boneWeight * jacobianDirection.dot(jointState.getTranslationDerivative(d)),
355 this->parameterTransform_,
359 if (this->activeJointParams_[paramIndex + 3 + d]) {
361 jacobian_jointParams_to_modelParams_filtered<T>(
362 boneWeight * jacobianDirection.dot(jointState.getRotationDerivative(d, posd)),
364 this->parameterTransform_,
369 if (this->activeJointParams_[paramIndex + 6]) {
371 jacobian_jointParams_to_modelParams_filtered<T>(
372 boneWeight * jacobianDirection.dot(jointState.getScaleDerivative(posd)),
374 this->parameterTransform_,
380 if (this->character_.blendShape) {
381 for (Eigen::Index iBlendShape = 0;
382 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
384 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
389 const Eigen::Vector3<T> d_restPos =
390 this->character_.blendShape->getShapeVectors()
391 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
393 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
396 jacobian(0, paramIdx) += jacobianDirection.dot(d_worldPos);
400 if (this->character_.faceExpressionBlendShape) {
401 for (Eigen::Index iBlendShape = 0;
402 iBlendShape < this->parameterTransform_.faceExpressionParameters.size();
404 const auto paramIdx = this->parameterTransform_.faceExpressionParameters[iBlendShape];
409 const Eigen::Vector3<T> d_restPos =
410 this->character_.faceExpressionBlendShape->getShapeVectors()
411 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
413 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
416 jacobian(0, paramIdx) += jacobianDirection.dot(d_worldPos);
422void HeightErrorFunctionT<T>::calculateVertexGradient(
424 const Eigen::Vector3<T>& gradientDirection,
425 Eigen::Ref<Eigen::VectorX<T>> gradient)
const {
431 this->character_, *meshState_.restMesh_, skeletonState_, vertexIndex);
433 while (!skinningIter.finished()) {
434 size_t jointIndex = 0;
436 Eigen::Vector3<T> pos;
437 std::tie(jointIndex, boneWeight, pos) = skinningIter.next();
439 MT_CHECK(jointIndex < this->skeleton_.joints.size());
441 const auto& jointState = skeletonState_.jointState[jointIndex];
443 const Eigen::Vector3<T> posd = pos - jointState.translation();
446 for (
size_t d = 0; d < 3; d++) {
447 if (this->activeJointParams_[paramIndex + d]) {
449 gradient_jointParams_to_modelParams_filtered<T>(
450 boneWeight * gradientDirection.dot(jointState.getTranslationDerivative(d)),
452 this->parameterTransform_,
456 if (this->activeJointParams_[paramIndex + 3 + d]) {
458 gradient_jointParams_to_modelParams_filtered<T>(
459 boneWeight * gradientDirection.dot(jointState.getRotationDerivative(d, posd)),
461 this->parameterTransform_,
466 if (this->activeJointParams_[paramIndex + 6]) {
468 gradient_jointParams_to_modelParams_filtered<T>(
469 boneWeight * gradientDirection.dot(jointState.getScaleDerivative(posd)),
471 this->parameterTransform_,
477 if (this->character_.blendShape) {
478 for (Eigen::Index iBlendShape = 0;
479 iBlendShape < this->parameterTransform_.blendShapeParameters.size();
481 const auto paramIdx = this->parameterTransform_.blendShapeParameters[iBlendShape];
486 const Eigen::Vector3<T> d_restPos =
487 this->character_.blendShape->getShapeVectors()
488 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
490 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
493 gradient[paramIdx] += gradientDirection.dot(d_worldPos);
497 if (this->character_.faceExpressionBlendShape) {
498 for (Eigen::Index iBlendShape = 0;
499 iBlendShape < this->parameterTransform_.faceExpressionParameters.size();
501 const auto paramIdx = this->parameterTransform_.faceExpressionParameters[iBlendShape];
506 const Eigen::Vector3<T> d_restPos =
507 this->character_.faceExpressionBlendShape->getShapeVectors()
508 .template block<3, 1>(3 * vertexIndex, iBlendShape, 3, 1)
510 Eigen::Vector3<T> d_worldPos = Eigen::Vector3<T>::Zero();
513 gradient[paramIdx] += gradientDirection.dot(d_worldPos);
519void HeightErrorFunctionT<T>::calculateDWorldPos(
521 const Eigen::Vector3<T>& d_restPos,
522 Eigen::Vector3<T>& d_worldPos)
const {
523 const auto& skinWeights = *character_.skinWeights;
526 const auto w = skinWeights.weight(vertexIndex, i);
527 const auto parentBone = skinWeights.index(vertexIndex, i);
530 (skeletonState_.jointState[parentBone].transform.toLinear() *
531 (character_.inverseBindPose[parentBone].linear().template
cast<T>() * d_restPos));
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...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Error function for character height constraints.
~HeightErrorFunctionT() override
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.
size_t getJacobianSize() const final
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
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
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
A character model with skeletal structure, mesh, and optional components.
Mesh_u mesh
3D mesh representing the character's surface
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE auto size() const
Represents the complete state of a model's mesh.
A vector of size numModelParams holding the values of all model parameters for a character.
Represents the complete state of a skeleton.