Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
character.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
23#include <numeric>
24#include <utility>
25#include <vector>
26
27namespace momentum {
28
29namespace {
30
31ParameterTransform zeroActiveJointOffsets(
32 ParameterTransform parameterTransform,
33 const std::vector<bool>& activeJoints) {
34 for (size_t jointIndex = 0; jointIndex < activeJoints.size(); ++jointIndex) {
35 if (!activeJoints[jointIndex]) {
36 continue;
37 }
38
39 for (size_t offset = 0; offset < kParametersPerJoint; ++offset) {
40 parameterTransform.offsets(jointIndex * kParametersPerJoint + offset) = 0.0f;
41 }
42 }
43
44 return parameterTransform;
45}
46
47struct SimplifiedJointPlacement {
48 size_t parent = kInvalidIndex;
49 size_t retainedAncestor = kInvalidIndex;
50 Vector3f translationOffset = Vector3f::Zero();
51};
52
53SimplifiedJointPlacement getSimplifiedJointPlacement(
54 const Skeleton& skeleton,
55 const SkeletonState& referenceState,
56 const std::vector<size_t>& lastJoint,
57 const size_t jointIndex) {
58 const Joint& joint = skeleton.joints.at(jointIndex);
59 if (joint.parent == kInvalidIndex) {
60 return {kInvalidIndex, jointIndex, joint.translationOffset};
61 }
62
63 size_t retainedAncestor = jointIndex;
64 size_t simplifiedParent = kInvalidIndex;
65 while (simplifiedParent == kInvalidIndex && retainedAncestor != kInvalidIndex) {
66 retainedAncestor = skeleton.joints.at(retainedAncestor).parent;
67 if (retainedAncestor != kInvalidIndex) {
68 simplifiedParent = lastJoint.at(retainedAncestor);
69 }
70 }
71
72 const Vector3f offset = retainedAncestor != kInvalidIndex
73 ? referenceState.jointState.at(retainedAncestor).transform.inverse() *
74 referenceState.jointState.at(jointIndex).translation()
75 : referenceState.jointState.at(jointIndex).translation();
76 return {simplifiedParent, retainedAncestor, offset};
77}
78
79Joint makeSimplifiedJoint(
80 const Skeleton& skeleton,
81 const size_t jointIndex,
82 const SimplifiedJointPlacement& placement) {
83 Joint result = skeleton.joints.at(jointIndex);
84 result.parent = placement.parent;
85 result.translationOffset = placement.translationOffset;
86
87 size_t parent = skeleton.joints.at(jointIndex).parent;
88 while (parent != placement.retainedAncestor && parent != kInvalidIndex) {
89 result.preRotation = skeleton.joints.at(parent).preRotation * result.preRotation;
90 parent = skeleton.joints.at(parent).parent;
91 }
92
93 return result;
94}
95
96size_t findSimplifiedAncestor(
97 const Skeleton& skeleton,
98 const std::vector<size_t>& intermediateJointMap,
99 const size_t jointIndex) {
100 size_t ancestor = jointIndex;
101 while (ancestor != kInvalidIndex && intermediateJointMap.at(ancestor) == kInvalidIndex) {
102 ancestor = skeleton.joints.at(ancestor).parent;
103 }
104
106 ancestor == kInvalidIndex,
107 "During skeleton simplification, inactive joint '{}' has no valid parent joint. "
108 "Every joint in the simplified skeleton must have at least one parent joint that is not disabled.",
109 skeleton.joints.at(jointIndex).name);
110 return intermediateJointMap.at(ancestor);
111}
112
113Matrix3f inertiaInJointFrame(const JointPhysicalProperties& properties) {
114 const Matrix3f inertiaRotation = properties.inertiaRotation.toRotationMatrix();
115 return inertiaRotation * properties.inertia * inertiaRotation.transpose();
116}
117
118void addParallelAxisShift(Matrix3f& inertia, const float mass, const Vector3f& offset) {
119 const float dx = offset.x();
120 const float dy = offset.y();
121 const float dz = offset.z();
122 inertia(0, 0) += mass * (dy * dy + dz * dz);
123 inertia(1, 1) += mass * (dx * dx + dz * dz);
124 inertia(2, 2) += mass * (dx * dx + dy * dy);
125
126 const float xy = -mass * dx * dy;
127 const float xz = -mass * dx * dz;
128 const float yz = -mass * dy * dz;
129 inertia(0, 1) += xy;
130 inertia(1, 0) += xy;
131 inertia(0, 2) += xz;
132 inertia(2, 0) += xz;
133 inertia(1, 2) += yz;
134 inertia(2, 1) += yz;
135}
136
137Matrix3f inertiaShiftedToCenter(
138 const JointPhysicalProperties& properties,
139 const Vector3f& centerOfMassOffset) {
140 Matrix3f result = inertiaInJointFrame(properties);
141 const Vector3f offset = properties.centerOfMassOffset - centerOfMassOffset;
142 addParallelAxisShift(result, properties.mass, offset);
143 return result;
144}
145
146void symmetrizeInPlace(Matrix3f& inertia) {
147 const float xy = 0.5f * (inertia(0, 1) + inertia(1, 0));
148 const float xz = 0.5f * (inertia(0, 2) + inertia(2, 0));
149 const float yz = 0.5f * (inertia(1, 2) + inertia(2, 1));
150 inertia(0, 1) = xy;
151 inertia(1, 0) = xy;
152 inertia(0, 2) = xz;
153 inertia(2, 0) = xz;
154 inertia(1, 2) = yz;
155 inertia(2, 1) = yz;
156}
157
158void mergePhysicalProperties(
160 const JointPhysicalProperties& source) {
161 const float mergedMass = target.mass + source.mass;
162 const Vector3f mergedCenterOfMassOffset = mergedMass > 0.0f
163 ? (target.mass * target.centerOfMassOffset + source.mass * source.centerOfMassOffset) /
164 mergedMass
165 : target.centerOfMassOffset;
166 Matrix3f mergedInertia = inertiaShiftedToCenter(target, mergedCenterOfMassOffset) +
167 inertiaShiftedToCenter(source, mergedCenterOfMassOffset);
168 symmetrizeInPlace(mergedInertia);
169
170 target.mass = mergedMass;
171 target.centerOfMassOffset = mergedCenterOfMassOffset;
172 target.inertia = mergedInertia;
173 target.inertiaRotation = Quaternionf::Identity();
174}
175
176PhysicalProperties remapPhysicalProperties(
177 const PhysicalProperties& physicalProperties,
178 const Skeleton& sourceSkeleton,
179 const Skeleton& targetSkeleton,
180 const std::vector<size_t>& jointMap,
181 const SkeletonState& sourceBindState,
182 const SkeletonState& targetBindState) {
183 PhysicalProperties result;
184 result.reserve(physicalProperties.size());
185 std::vector<size_t> resultIndexByJoint(targetSkeleton.joints.size(), kInvalidIndex);
186
187 for (const auto& jointProperties : physicalProperties) {
188 const size_t oldJointIndex =
189 resolvePhysicalPropertiesJointIndex(jointProperties, sourceSkeleton);
190 if (oldJointIndex == kInvalidIndex || oldJointIndex >= jointMap.size()) {
191 continue;
192 }
193
194 const size_t newJointIndex = jointMap[oldJointIndex];
195 if (newJointIndex == kInvalidIndex || newJointIndex >= targetSkeleton.joints.size()) {
196 continue;
197 }
198
199 JointPhysicalProperties mappedProperties = jointProperties;
200 mappedProperties.jointIndex = newJointIndex;
201 mappedProperties.jointName = targetSkeleton.joints.at(newJointIndex).name;
202
203 const auto oldToNewLocal = targetBindState.jointState.at(newJointIndex).transform.inverse() *
204 sourceBindState.jointState.at(oldJointIndex).transform;
205 mappedProperties.centerOfMassOffset = oldToNewLocal * jointProperties.centerOfMassOffset;
206 mappedProperties.inertiaRotation =
207 (oldToNewLocal.rotation * jointProperties.inertiaRotation).normalized();
208
209 // Skeleton simplification can fold multiple source joints into one target joint. Keep the
210 // one-body-per-joint invariant by merging those bodies in the target joint frame.
211 size_t& resultIndex = resultIndexByJoint.at(newJointIndex);
212 if (resultIndex == kInvalidIndex) {
213 resultIndex = result.size();
214 result.push_back(std::move(mappedProperties));
215 } else {
216 mergePhysicalProperties(result.at(resultIndex), mappedProperties);
217 }
218 }
219
220 return result;
221}
222
223std::unique_ptr<CollisionGeometry> remapCollisionGeometry(
224 const CollisionGeometry* collision,
225 const std::vector<size_t>& jointMap,
226 const SkeletonState& sourceBindState,
227 const SkeletonState& targetBindState) {
228 if (collision == nullptr) {
229 return {};
230 }
231
232 auto result = std::make_unique<CollisionGeometry>(*collision);
233 for (auto& collisionGeometry : *result) {
234 const auto oldParent = collisionGeometry.parent;
235 collisionGeometry.parent = jointMap.at(collisionGeometry.parent);
236 // Re-express the collision shape's local transform in the new parent's frame:
237 // newLocal = targetParentBind^-1 * sourceParentBind * oldLocal
238 collisionGeometry.transformation =
239 targetBindState.jointState.at(collisionGeometry.parent).transform.inverse() *
240 sourceBindState.jointState.at(oldParent).transform * collisionGeometry.transformation;
241 }
242
243 return result;
244}
245
246} // namespace
247
249 const Skeleton& s,
250 const ParameterTransform& pt,
251 const ParameterLimits& pl,
252 const LocatorList& l,
253 const Mesh* m,
254 const SkinWeights* sw,
255 const CollisionGeometry* cg,
256 const PoseShape* bs,
257 BlendShape_const_p blendShapes,
258 BlendShapeBase_const_p faceExpressionBlendShapes,
259 const std::string& nameIn,
260 const momentum::TransformationList& inverseBindPose_in,
262 std::string_view metadataIn,
263 const PhysicalProperties& physicalPropertiesIn)
264 : skeleton(s),
266 parameterLimits(pl),
267 locators(l),
269 physicalProperties(physicalPropertiesIn),
270 blendShape(std::move(blendShapes)),
271 faceExpressionBlendShape(std::move(faceExpressionBlendShapes)),
272 inverseBindPose(inverseBindPose_in),
273 name(nameIn),
274 metadata(metadataIn) {
275 if (m) {
276 mesh = std::make_unique<Mesh>(*m);
277 // Skin weights are only meaningful in the presence of a mesh; drop them otherwise.
278 if (sw) {
279 skinWeights = std::make_unique<SkinWeights>(*sw);
280 }
281 }
282
283 if (bs) {
284 poseShapes = std::make_unique<PoseShape>(*bs);
285 }
286
287 if (inverseBindPose.empty()) {
288 initInverseBindPose();
289 }
290 MT_CHECK(this->inverseBindPose.size() == skeleton.joints.size());
291
292 if (cg) {
293 collision = std::make_unique<CollisionGeometry>(*cg);
294 }
295
297}
298
300 : skeleton(c.skeleton),
310 name(c.name),
311 metadata(c.metadata) {
312 if (c.mesh) {
313 mesh = std::make_unique<Mesh>(*c.mesh);
314 // Skin weights are only meaningful in the presence of a mesh; drop them otherwise.
315 if (c.skinWeights) {
316 skinWeights = std::make_unique<SkinWeights>(*c.skinWeights);
317 }
318 }
319
320 if (c.poseShapes) {
321 poseShapes = std::make_unique<PoseShape>(*c.poseShapes);
322 }
323
324 if (c.collision) {
325 collision = std::make_unique<CollisionGeometry>(*c.collision);
326 }
327}
328
329Character::Character(Character&& c) noexcept = default;
330
331Character::Character() = default;
332
333Character::~Character() = default;
334
336 // Copy-and-swap: build a temporary copy, then swap members in for strong exception safety.
337 Character tmp(rhs);
338
339 std::swap(skeleton, tmp.skeleton);
341 std::swap(parameterLimits, tmp.parameterLimits);
342 std::swap(locators, tmp.locators);
343 std::swap(skinnedLocators, tmp.skinnedLocators);
344 std::swap(inverseBindPose, tmp.inverseBindPose);
345 std::swap(jointMap, tmp.jointMap);
346 std::swap(mesh, tmp.mesh);
347 std::swap(poseShapes, tmp.poseShapes);
348 std::swap(skinWeights, tmp.skinWeights);
349 std::swap(collision, tmp.collision);
351 std::swap(blendShape, tmp.blendShape);
353 std::swap(name, tmp.name);
354 std::swap(metadata, tmp.metadata);
355
356 return *this;
357}
358
359Character& Character::operator=(Character&& rhs) noexcept = default;
360
361std::vector<bool> Character::parametersToActiveJoints(const ParameterSet& parameterSet) const {
362 const auto nJoints = skeleton.joints.size();
363 std::vector<bool> result(nJoints, false);
364 for (int k = 0; k < parameterTransform.transform.outerSize(); ++k) {
365 for (SparseRowMatrixf::InnerIterator it(parameterTransform.transform, k); it; ++it) {
366 // Row index encodes (jointIndex * kParametersPerJoint + jointParamSlot); col is the model
367 // parameter that drives it.
368 const auto& row = it.row();
369 const auto& col = it.col();
370
371 if (!parameterSet.test(col)) {
372 continue;
373 }
374
375 const auto jointIndex = row / kParametersPerJoint;
376 MT_CHECK(jointIndex < nJoints, "{} vs {}", jointIndex, nJoints);
377 result[jointIndex] = true;
378 }
379 }
380
381 return result;
382}
383
384ParameterSet Character::activeJointsToParameters(const std::vector<bool>& activeJoints) const {
385 MT_CHECK(
386 activeJoints.size() == skeleton.joints.size(),
387 "{} is not {}",
388 activeJoints.size(),
389 skeleton.joints.size());
390
391 ParameterSet result;
392
393 for (int k = 0; k < parameterTransform.transform.outerSize(); ++k) {
394 for (SparseRowMatrixf::InnerIterator it(parameterTransform.transform, k); it; ++it) {
395 const auto globalParam = it.row();
396 const auto kParam = it.col();
397 MT_CHECK(
398 kParam < (Eigen::Index)parameterTransform.numAllModelParameters(),
399 "{} vs {}",
400 kParam,
401 parameterTransform.numAllModelParameters());
402 const auto jointIndex = globalParam / kParametersPerJoint;
403
404 if (activeJoints[jointIndex] != 0) {
405 result.set(kParam, true);
406 }
407 }
408 }
409
410 return result;
411}
412
413Character Character::simplifySkeleton(const std::vector<bool>& activeJoints) const {
414 MT_CHECK(
415 activeJoints.size() == skeleton.joints.size(),
416 "{} is not {}",
417 activeJoints.size(),
418 skeleton.joints.size());
420 std::find(activeJoints.begin(), activeJoints.end(), true) == activeJoints.end(),
421 "In simplifySkeleton, no joints are enabled; resulting skeleton must have at least one valid joint.");
422
423 Skeleton simplifiedSkeleton;
424
425 // -------------------------------------------------------------------
426 // start by remapping the skeleton and parameter transform
427 // -------------------------------------------------------------------
428
429 // Build a parameter transform whose offsets are zero for active joints but preserved for
430 // inactive ones, so the reference state below "bakes" the inactive offsets in.
431 const auto zeroTransform = zeroActiveJointOffsets(parameterTransform, activeJoints);
432
433 // Maps each original joint index to its position in `simplifiedSkeleton.joints` (or
434 // kInvalidIndex if the joint is dropped). Populated below as we iterate.
435 std::vector<size_t> intermediateJointMap(skeleton.joints.size(), kInvalidIndex);
436
437 // Reference state where disabled joints contribute their offsets but enabled joints sit at
438 // their bind values. Used to bake inactive joint offsets into active children.
439 const SkeletonState referenceState(
440 zeroTransform.apply(ModelParameters::Zero(zeroTransform.numAllModelParameters())),
441 skeleton,
442 false);
443
444 // For each original joint index, the last simplified-joint index seen at-or-above it in the
445 // hierarchy. Used to find the new parent for an active joint after intermediate parents are
446 // pruned.
447 std::vector<size_t> lastJoint(skeleton.joints.size(), kInvalidIndex);
448
449 std::vector<size_t> simplifiedJointMap(skeleton.joints.size(), kInvalidIndex);
450 for (size_t aIndex = 0; aIndex < skeleton.joints.size(); aIndex++) {
451 // `retainedAncestor` identifies the original ancestor whose simplified mapping supplies the
452 // new parent frame. Dropped joints between it and this joint are folded into the kept joint.
453 const auto placement = getSimplifiedJointPlacement(skeleton, referenceState, lastJoint, aIndex);
454
455 if (activeJoints[aIndex]) {
456 simplifiedSkeleton.joints.push_back(makeSimplifiedJoint(skeleton, aIndex, placement));
457 const size_t newJointIndex = simplifiedSkeleton.joints.size() - 1;
458 intermediateJointMap.at(aIndex) = newJointIndex;
459 lastJoint.at(aIndex) = newJointIndex;
460 simplifiedJointMap.at(aIndex) = newJointIndex;
461 } else {
462 // Inactive joints are not added to the simplified skeleton; instead, point their entry in
463 // simplifiedJointMap at the nearest active ancestor so consumers (locators, skin weights,
464 // etc.) can still resolve them.
465 simplifiedJointMap.at(aIndex) =
466 findSimplifiedAncestor(skeleton, intermediateJointMap, aIndex);
467 }
468 }
470 simplifiedSkeleton.joints.empty(),
471 "During skeleton simplification, resulting skeleton was empty. Simplified skeleton must have at least one valid joint.");
472
473 const ParameterTransform simplifiedTransform = mapParameterTransformJoints(
474 parameterTransform, simplifiedSkeleton.joints.size(), intermediateJointMap);
475
476 Character result(simplifiedSkeleton, simplifiedTransform);
477 result.name = name;
478 result.metadata = metadata;
479
480 result.jointMap = simplifiedJointMap;
481
482 // -------------------------------------------------------------------
483 // remap the parameterlimits
484 // -------------------------------------------------------------------
486
487 // -------------------------------------------------------------------
488 // remap the locators if we have any
489 // -------------------------------------------------------------------
490 result.locators = result.remapLocators(locators, *this);
492
493 // -------------------------------------------------------------------
494 // remap the mesh and skinning if present
495 // -------------------------------------------------------------------
496
497 // Bind states for source and target skeleton — used by the collision-remap block below to
498 // transport collision shapes between the two joint frames.
499 const SkeletonState sourceBindState(parameterTransform.bindPose(), skeleton, false);
500 const SkeletonState targetBindState(result.parameterTransform.bindPose(), result.skeleton, false);
501
502 // -------------------------------------------------------------------
503 // remap physical joint properties if present
504 // -------------------------------------------------------------------
505 result.physicalProperties = remapPhysicalProperties(
507 skeleton,
508 result.skeleton,
509 result.jointMap,
510 sourceBindState,
511 targetBindState);
512
513 if (mesh && skinWeights) {
514 result.mesh = std::make_unique<Mesh>(*mesh);
515 result.skinWeights =
516 std::make_unique<SkinWeights>(result.remapSkinWeights(*skinWeights, *this));
517 }
518
519 // -------------------------------------------------------------------
520 // remap the collision if we have any
521 // -------------------------------------------------------------------
522 result.collision =
523 remapCollisionGeometry(collision.get(), result.jointMap, sourceBindState, targetBindState);
524
525 return result;
526}
527
529 MT_CHECK(
530 parameterSet.count() > 0, "No active parameters in the input to simplifyParameterTransform.");
531
532 auto [subsetParamTransform, subsetParamLimits] =
534
535 return {
536 skeleton,
537 subsetParamTransform,
538 subsetParamLimits,
539 locators,
540 mesh.get(),
541 skinWeights.get(),
542 collision.get(),
543 poseShapes.get(),
546 name,
549 metadata,
551}
552
553Character Character::simplify(const ParameterSet& activeParams) const {
554 auto activeJoints = parametersToActiveJoints(activeParams);
555 // always keep the root joint to ensure valid simplification.
556 // This is needed because while previously we generally parametrized the root joint with
557 // the root transform, modern skeletons sometimes have a body_world above b_root that is
558 // not parametrized, but if we throw it out we end up with an invalid character.
559 if (!activeJoints.empty()) {
560 activeJoints[0] = true;
561 }
562
563 return simplifySkeleton(activeJoints);
564}
565
567 const SkinWeights& inSkinWeights,
568 const Character& originalCharacter) const {
569 MT_CHECK(
570 originalCharacter.parameterTransform.numAllModelParameters() ==
571 parameterTransform.numAllModelParameters(),
572 "{} is not {}",
573 originalCharacter.parameterTransform.numAllModelParameters(),
574 parameterTransform.numAllModelParameters());
575 MT_CHECK(
576 jointMap.size() == originalCharacter.skeleton.joints.size(),
577 "{} is not {}",
578 jointMap.size(),
579 originalCharacter.skeleton.joints.size());
580
581 SkinWeights result = inSkinWeights;
582
583 for (int v = 0; v < result.index.rows(); v++) {
584 // Translate each joint index from the original character to the simplified character.
585 for (int i = 0; i < gsl::narrow_cast<int>(kMaxSkinJoints); i++) {
586 result.index(v, i) = static_cast<uint32_t>(jointMap[result.index(v, i)]);
587 }
588
589 // Multiple original joints may collapse to the same simplified joint; merge their weights
590 // into the first slot and zero the duplicates.
591 for (int i = 0; i < gsl::narrow_cast<int>(kMaxSkinJoints); i++) {
592 const auto& joint = result.index(v, i);
593 for (int j = i + 1; j < gsl::narrow_cast<int>(kMaxSkinJoints); j++) {
594 if (result.index(v, j) == joint) {
595 result.weight(v, i) += result.weight(v, j);
596 result.weight(v, j) = 0.0f;
597 }
598 }
599 }
600
601 // Sort influences by weight (descending) so callers that truncate to fewer slots keep the
602 // most significant ones.
603 for (int i = 0; i < gsl::narrow_cast<int>(kMaxSkinJoints); i++) {
604 for (int j = i + 1; j < gsl::narrow_cast<int>(kMaxSkinJoints); j++) {
605 if (result.weight(v, i) < result.weight(v, j)) {
606 std::swap(result.weight(v, i), result.weight(v, j));
607 std::swap(result.index(v, i), result.index(v, j));
608 }
609 }
610 }
611 }
612
613 return result;
614}
615
617 const ParameterLimits& limits,
618 const Character& originalCharacter) const {
619 MT_CHECK(
620 originalCharacter.parameterTransform.numAllModelParameters() ==
621 parameterTransform.numAllModelParameters(),
622 "{} is not {}",
623 originalCharacter.parameterTransform.numAllModelParameters(),
624 parameterTransform.numAllModelParameters());
625 MT_CHECK(
626 jointMap.size() == originalCharacter.skeleton.joints.size(),
627 "{} is not {}",
628 jointMap.size(),
629 originalCharacter.skeleton.joints.size());
630
631 ParameterLimits result;
632
633 // create bind states for both source and target skeleton
634 const SkeletonState sourceBindState(
635 originalCharacter.parameterTransform.bindPose(), originalCharacter.skeleton, false);
636 const SkeletonState targetBindState(parameterTransform.bindPose(), skeleton, false);
637
638 result = limits;
639 for (auto&& limit : result) {
640 // only need to remap limits that depend on joints
641 if (limit.type == MinMaxJoint || limit.type == MinMaxJointPassive) {
642 auto& data = limit.data.minMaxJoint;
643 data.jointIndex = jointMap[data.jointIndex];
644 } else if (limit.type == Ellipsoid) {
645 // ellipsoid limit requires re-targeting the ellipsoid to the new joint's local system
646 auto& data = limit.data.ellipsoid;
647 const auto sourceParent = data.parent;
648 const auto targetParent = jointMap[sourceParent];
649 MT_CHECK(
650 targetParent < targetBindState.jointState.size(),
651 "{} vs {}",
652 targetParent,
653 targetBindState.jointState.size());
654 data.parent = targetParent;
655
656 const auto targetTransformationInverse =
657 targetBindState.jointState[targetParent].transform.inverse();
658 const auto sourceTransformation = sourceBindState.jointState[sourceParent].transform;
659 data.offset = targetTransformationInverse * sourceTransformation * data.offset;
660
661 const auto sourceEllipsoidParent = data.ellipsoidParent;
662 data.ellipsoidParent = jointMap[data.ellipsoidParent];
663 const auto targetEllipsoidInverse =
664 targetBindState.jointState[data.ellipsoidParent].transform.inverse();
665 const auto sourceEllipsoid = sourceBindState.jointState[sourceEllipsoidParent].transform;
666 data.ellipsoid = targetEllipsoidInverse * sourceEllipsoid * data.ellipsoid;
667 data.ellipsoidInv = data.ellipsoid.inverse();
668 }
669 }
670
671 return result;
672}
673
675 const SkinnedLocatorList& locs,
676 const Character& originalCharacter) const {
677 MT_CHECK(
678 originalCharacter.parameterTransform.numAllModelParameters() ==
679 parameterTransform.numAllModelParameters(),
680 "{} is not {}",
681 originalCharacter.parameterTransform.numAllModelParameters(),
682 parameterTransform.numAllModelParameters());
683 MT_CHECK(
684 jointMap.size() == originalCharacter.skeleton.joints.size(),
685 "{} is not {}",
686 jointMap.size(),
687 originalCharacter.skeleton.joints.size());
688
689 SkinnedLocatorList result = locs;
690
691 // Note: unlike remapLocators(), this function does not need the source/target bind states.
692 // A skinned locator stores a single bind-frame offset that is blended across its weighted
693 // parents at evaluation time; it has no per-influence offset to re-express. When collapsed
694 // joints share the same bind transform (the typical case for redundant intermediate joints),
695 // the merged-weight result is unchanged. If callers ever simplify across joints whose bind
696 // transforms differ, the locator offset will need explicit remapping.
697
698 for (auto& sl : result) {
699 // Translate each parent joint index from the original character to the simplified character.
700 for (int i = 0; i < gsl::narrow_cast<int>(kMaxSkinJoints); i++) {
701 sl.parents(i) = static_cast<uint32_t>(jointMap[sl.parents(i)]);
702 }
703
704 // Multiple original joints may collapse to the same simplified joint; merge their weights
705 // into the first slot and zero the duplicates.
706 for (int i = 0; i < gsl::narrow_cast<int>(kMaxSkinJoints); i++) {
707 const auto& joint = sl.parents(i);
708 for (int j = i + 1; j < gsl::narrow_cast<int>(kMaxSkinJoints); j++) {
709 if (sl.parents(j) == joint) {
710 sl.skinWeights(i) += sl.skinWeights(j);
711 sl.skinWeights(j) = 0.0f;
712 }
713 }
714 }
715
716 // Sort influences by weight (descending) so callers that truncate to fewer slots keep the
717 // most significant ones.
718 for (int i = 0; i < gsl::narrow_cast<int>(kMaxSkinJoints); i++) {
719 for (int j = i + 1; j < gsl::narrow_cast<int>(kMaxSkinJoints); j++) {
720 if (sl.skinWeights(i) < sl.skinWeights(j)) {
721 std::swap(sl.skinWeights(i), sl.skinWeights(j));
722 std::swap(sl.parents(i), sl.parents(j));
723 }
724 }
725 }
726 }
727
728 return result;
729}
730
731LocatorList Character::remapLocators(const LocatorList& locs, const Character& originalCharacter)
732 const {
733 MT_CHECK(
734 originalCharacter.parameterTransform.numAllModelParameters() ==
735 parameterTransform.numAllModelParameters(),
736 "{} is not {}",
737 originalCharacter.parameterTransform.numAllModelParameters(),
738 parameterTransform.numAllModelParameters());
739 MT_CHECK(
740 jointMap.size() == originalCharacter.skeleton.joints.size(),
741 "{} is not {}",
742 jointMap.size(),
743 originalCharacter.skeleton.joints.size());
744
745 LocatorList result;
746
747 // Bind states for source and target skeletons; used below to re-express each locator's offset
748 // in the new parent joint's local frame.
749 const SkeletonState sourceBindState(
750 originalCharacter.parameterTransform.bindPose(), originalCharacter.skeleton, false);
751 const SkeletonState targetBindState(parameterTransform.bindPose(), skeleton, false);
752
753 for (const auto& sourceLocator : locs) {
754 result.emplace_back(sourceLocator);
755 auto& loc = result.back();
756 loc.parent = jointMap[loc.parent];
757 // newOffset = targetParentBind^-1 * sourceParentBind * oldOffset
758 loc.offset = targetBindState.jointState[loc.parent].transform.inverse() *
759 sourceBindState.jointState[sourceLocator.parent].transform * sourceLocator.offset;
760 }
761
762 return result;
763}
764
766 CharacterParameters result;
767 result.pose = VectorXf::Zero(parameterTransform.numAllModelParameters());
768 result.offsets = VectorXf::Zero(skeleton.joints.size() * kParametersPerJoint);
769 return result;
770}
771
773 size_t nParams = skeleton.joints.size() * kParametersPerJoint;
775}
776
778 // Identity map: jointMap[i] = i. Used when no skeleton simplification has been performed.
779 jointMap.resize(skeleton.joints.size());
780 std::iota(jointMap.begin(), jointMap.end(), 0);
781}
782
784 const SkeletonState bindState(parameterTransform.bindPose(), skeleton, false);
785 if (!inverseBindPose.empty()) {
786 inverseBindPose.clear();
787 }
788 inverseBindPose.reserve(bindState.jointState.size());
789 for (const auto& t : bindState.jointState) {
790 inverseBindPose.push_back(t.transform.inverse().toAffine3());
791 }
792}
793
795 const Character& character,
796 const CharacterParameters& parameters,
797 const ParameterSet& parameterSet) {
798 auto parameterSplit = parameters;
799 auto offsetSplit = parameters;
800 for (int j = 0; j < offsetSplit.pose.size(); j++) {
801 if (parameterSet.test(j)) {
802 parameterSplit.pose[j] = 0.0f;
803 } else {
804 offsetSplit.pose[j] = 0.0f;
805 }
806 }
807 parameterSplit.offsets = character.parameterTransform.apply(offsetSplit);
808 return parameterSplit;
809}
810
812 const BlendShape_const_p& blendShape_in,
813 Eigen::Index maxBlendShapes) const {
814 Character result = *this;
815 result.addBlendShape(blendShape_in, maxBlendShapes);
816 return result;
817}
818
820 const BlendShape_const_p& blendShape_in,
821 Eigen::Index maxBlendShapes) {
822 MT_CHECK(this->mesh);
823 if (!blendShape_in) {
826 this->blendShape.reset();
827 return;
828 }
829
830 // TODO should we accommodate passing in a BlendShape with "extra" vertices (for the
831 // higher subdivision levels)?
832 MT_CHECK(
833 blendShape_in->modelSize() == this->mesh->vertices.size(),
834 "{} is not {}",
835 blendShape_in->modelSize(),
836 this->mesh->vertices.size());
837
838 blendShape = blendShape_in;
839
840 // Augment the parameter transform with blend shape parameters:
842 parameterTransform, parameterLimits, std::min(maxBlendShapes, blendShape_in->shapeSize()));
843}
844
846 const BlendShapeBase_const_p& blendShape_in,
847 Eigen::Index maxBlendShapes) const {
848 Character res = *this;
849 res.addFaceExpressionBlendShape(blendShape_in, maxBlendShapes);
850 return res;
851}
852
854 const BlendShapeBase_const_p& blendShape_in,
855 Eigen::Index maxBlendShapes) {
856 MT_CHECK(mesh);
857
858 if (!blendShape_in) {
861 this->faceExpressionBlendShape.reset();
862 return;
863 }
864
865 MT_CHECK(
866 blendShape_in->modelSize() == mesh->vertices.size(),
867 "{} is not {}",
868 blendShape_in->modelSize(),
869 mesh->vertices.size());
870
871 faceExpressionBlendShape = blendShape_in;
872
873 auto nBlendShapes = blendShape_in->shapeSize();
874 if (maxBlendShapes > 0) {
875 nBlendShapes = std::min(maxBlendShapes, nBlendShapes);
876 }
877
878 // Augment the parameter transform with blend shape parameters:
881}
882
884 Character result = *this;
885 MT_CHECK(result.mesh);
886 if (this->blendShape) {
887 result.mesh->vertices = this->blendShape->template computeShape<float>(blendWeights);
888 result.mesh->updateNormals();
889 }
890
892 this->parameterTransform,
893 this->parameterLimits,
894 ~this->parameterTransform.getBlendShapeParameters());
895
896 return result;
897}
898
900 return bakeBlendShape(extractBlendWeights(this->parameterTransform, modelParams));
901}
902
903Character Character::bake(const ModelParameters& modelParams, bool bakeBlendShapes, bool bakeScales)
904 const {
905 // 1. Clone the character so we don't mutate the original.
906 Character result = *this;
907 MT_CHECK(result.mesh);
908
909 // 2. Blend-shape baking: replace the rest-pose vertices with the blend-shape evaluation.
910 if (bakeBlendShapes && this->blendShape) {
911 const BlendWeights blendWeights = extractBlendWeights(result.parameterTransform, modelParams);
912 result.mesh->vertices = this->blendShape->template computeShape<float>(blendWeights);
913 }
914
915 // 3. Scale (or any joint transform) baking: skin the rest mesh through the posed skeleton so
916 // the resulting vertices already include the joint transforms; then strip those parameters
917 // below.
918 if (bakeScales && this->skinWeights) {
919 const SkeletonState posed(
920 result.parameterTransform.apply(modelParams),
921 result.skeleton,
922 /*computeDeriv =*/false);
923 Mesh restMesh = *result.mesh;
924 applySSD(result.inverseBindPose, *result.skinWeights, restMesh, posed, *result.mesh);
925 }
926
927 result.mesh->updateNormals();
928
929 // 4. Strip baked parameters from the rig
930 ParameterSet baked = ParameterSet();
931 if (bakeBlendShapes) {
933 }
934 if (bakeScales) {
936 }
937
939 result.parameterTransform,
940 result.parameterLimits,
941 ~baked); // keep unbaked params only
942
943 return result;
944}
945
946} // namespace momentum
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
Functions for linear blend skinning (Skeletal Subspace Deformation).
Matrix3< float > Matrix3f
Definition types.h:107
CollisionGeometryT< float > CollisionGeometry
SkeletonT< float > Skeleton
Definition fwd.h:263
::std::shared_ptr< const BlendShapeBase > BlendShapeBase_const_p
Definition fwd.h:32
std::tuple< ParameterTransformT< T >, ParameterLimits > subsetParameterTransform(const ParameterTransformT< T > &paramTransformOld, const ParameterLimits &paramLimitsOld, const ParameterSet &paramSet)
Return a parameter mapping that only includes the listed parameters.
std::vector< Affine3f > TransformationList
One affine transform per joint, indexed by joint id.
Definition types.h:410
std::vector< ParameterLimit > ParameterLimits
MeshT< float > Mesh
Definition fwd.h:20
BlendWeightsT< float > BlendWeights
Definition types.h:115
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
std::tuple< ParameterTransform, ParameterLimits > addBlendShapeParameters(ParameterTransform paramTransform, ParameterLimits paramLimits, Eigen::Index nBlendShapes)
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
Definition joint.h:114
SkeletonStateT< float > SkeletonState
Definition fwd.h:282
std::vector< SkinnedLocator > SkinnedLocatorList
A collection of locators attached to a skeleton.
CharacterParametersT< float > CharacterParameters
Definition types.h:168
constexpr size_t kParametersPerJoint
Definition types.h:21
JointT< float > Joint
Definition fwd.h:206
ModelParametersT< float > ModelParameters
Definition types.h:105
std::vector< Vector3< T > > applySSD(const SkinWeights &skin, typename DeduceSpanType< const Vector3< T > >::type points, typename DeduceSpanType< const Eigen::Matrix4< T > >::type skinningTransforms)
Applies forward SSD (linear blend skinning) to points using precomputed skinning transforms.
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
size_t resolvePhysicalPropertiesJointIndex(const JointPhysicalProperties &properties, const Skeleton &skeleton)
Resolves physical mass properties to a skeleton joint.
Vector3< float > Vector3f
Definition types.h:251
::std::shared_ptr< const BlendShape > BlendShape_const_p
Definition fwd.h:23
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
BlendWeightsT< T > extractBlendWeights(const ParameterTransform &paramTransform, const ModelParametersT< T > &modelParams)
Extracts blend shape weights from model parameters.
std::tuple< ParameterTransform, ParameterLimits > addFaceExpressionParameters(ParameterTransform paramTransform, ParameterLimits paramLimits, Eigen::Index nFaceExpressionBlendShapes)
ParameterTransformT< T > mapParameterTransformJoints(const ParameterTransformT< T > &parameterTransform, size_t numTargetJoints, const std::vector< size_t > &jointMapping)
Construct a new parameter transform where the joints have been mapped to a new skeleton.
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Definition locator.h:79
JointParametersT< T > offsets
The joint parameter vector representing the unique bone lengths of the character, defining the charac...
Definition types.h:165
ModelParametersT< T > pose
The model parameter vector representing the pose of the character.
Definition types.h:161
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
void addFaceExpressionBlendShape(const BlendShapeBase_const_p &blendShape_in, Eigen::Index maxBlendShapes=-1)
Adds face expression blend shapes to this character.
ParameterLimits remapParameterLimits(const ParameterLimits &limits, const Character &originalCharacter) const
Remaps parameter limits from original character to simplified version.
SkinWeights remapSkinWeights(const SkinWeights &skinWeights, const Character &originalCharacter) const
Remaps skin weights from original character to simplified version.
std::vector< bool > parametersToActiveJoints(const ParameterSet &parameterSet) const
Determines which joints are affected by the specified parameters.
TransformationList inverseBindPose
Inverse of the bind pose transformations for each joint.
Definition character.h:76
Character bake(const ModelParameters &modelParams, bool bakeBlendShapes=true, bool bakeScales=true) const
Generic "bake-out" for turning a character into self-contained geometry.
LocatorList locators
Points of interest attached to joints.
Definition character.h:49
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
Definition character.h:58
CharacterParameters bindPose() const
Returns parameters representing the character's bind pose.
void initInverseBindPose()
Initializes the inverse bind pose transformations.
static CharacterParameters splitParameters(const Character &character, const CharacterParameters &parameters, const ParameterSet &parameterSet)
Splits character parameters into active and inactive components.
void resetJointMap()
Resets the joint map to identity (each joint maps to itself).
PhysicalProperties physicalProperties
Joint-level physical mass and inertia data loaded from model assets.
Definition character.h:67
Character simplifyParameterTransform(const ParameterSet &parameterSet) const
Creates a simplified character with only the specified parameters.
BlendShapeBase_const_p faceExpressionBlendShape
Facial expression blend shapes.
Definition character.h:73
ParameterLimits parameterLimits
Constraints on model parameters.
Definition character.h:46
Mesh_u mesh
3D mesh representing the character's surface
Definition character.h:55
PoseShape_u poseShapes
Pose-dependent shape corrections.
Definition character.h:61
Character simplifySkeleton(const std::vector< bool > &activeJoints) const
Creates a simplified character with only the specified joints.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
void addBlendShape(const BlendShape_const_p &blendShape_in, Eigen::Index maxBlendShapes)
Adds blend shapes to this character.
SkinnedLocatorList remapSkinnedLocators(const SkinnedLocatorList &locs, const Character &originalCharacter) const
std::string name
Character identifier.
Definition character.h:82
Character withFaceExpressionBlendShape(const BlendShapeBase_const_p &blendShape_in, Eigen::Index maxBlendShapes=-1) const
Creates a new character with the specified face expression blend shapes.
Character & operator=(const Character &rhs)
Character withBlendShape(const BlendShape_const_p &blendShape_in, Eigen::Index maxBlendShapes) const
Creates a new character with the specified blend shapes.
SkinnedLocatorList skinnedLocators
Points of interest attached to joints, with skinning weights.
Definition character.h:52
Character simplify(const ParameterSet &activeParams=ParameterSet().flip()) const
Creates a simplified character with only joints affected by the specified parameters.
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
ParameterSet activeJointsToParameters(const std::vector< bool > &activeJoints) const
Determines which parameters affect the specified joints.
BlendShape_const_p blendShape
Shape variations that can be blended.
Definition character.h:70
Character bakeBlendShape(const ModelParameters &modelParams) const
Creates a new character with blend shapes baked into the mesh.
std::vector< size_t > jointMap
Maps from original joint indices to simplified joint indices.
Definition character.h:79
void initParameterTransform()
Initializes the parameter transform with the correct dimensions for this character.
LocatorList remapLocators(const LocatorList &locs, const Character &originalCharacter) const
Remaps locators from original character to simplified version.
std::string metadata
Metadata (as a JSON-serialized string).
Definition character.h:85
CollisionGeometry_u collision
Collision volumes for the character.
Definition character.h:64
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
Physical mass properties attached to one skeleton joint.
Definition joint.h:88
size_t jointIndex
Cached joint index.
Definition joint.h:97
ParameterSet getScalingParameters() const
Get a list of scaling parameters (with prefix "scale_").
static ParameterTransformT< float > empty(size_t nJointParameters)
JointParametersT< T > apply(const ModelParametersT< T > &parameters) const
Map model parameters to joint parameters using a linear transformation.
JointParametersT< T > bindPose() const
Return bind pose joint parameters (same as the rest pose here).
Eigen::Index numAllModelParameters() const
Dimension of all model parameters, including pose, scaling, marker joints, and blendshape parameters ...
ParameterSet getBlendShapeParameters() const
Get a list of blend shape parameters.
Computes shape deformations based on joint rotations.
Definition pose_shape.h:20
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.
WeightMatrix weight
Joint influence weights per vertex.
IndexMatrix index
Joint indices influencing each vertex.