18#include <unordered_set>
42 for (
auto& j : result.joints) {
43 j.translationOffset *= scale;
48std::unique_ptr<Mesh> scale(
const std::unique_ptr<Mesh>& mesh,
float scale) {
53 auto result = std::make_unique<Mesh>(*mesh);
54 for (
auto& v : result->vertices) {
62 for (
auto& l : result) {
64 l.limitOrigin *= scale;
71 for (
auto& limit : result) {
73 limit.data.ellipsoid.ellipsoid.translation() *= scale;
74 limit.data.ellipsoid.ellipsoidInv.translation() *= scale;
75 limit.data.ellipsoid.offset *= scale;
82std::unique_ptr<CollisionGeometry> scale(
83 const std::unique_ptr<CollisionGeometry>& geom,
89 auto result = std::make_unique<CollisionGeometry>(*geom);
90 for (
auto& primitive : (*result)) {
91 primitive.transformation.translation *= scale;
93 primitive.radius *= scale;
94 primitive.length *= scale;
96 primitive.ellipsoidRadii *= scale;
98 primitive.boxHalfExtents *= scale;
110 return lengthScale * lengthScale * lengthScale;
114 MT_THROW(
"Unknown CharacterMassScale policy: {}",
static_cast<int>(massScale));
121 const float massScaleValue = getPhysicalMassScale(massScale, lengthScale);
124 for (
auto& jointProperties : result) {
125 jointProperties.centerOfMassOffset *= lengthScale;
126 jointProperties.mass *= massScaleValue;
127 jointProperties.inertia *= massScaleValue * lengthScale * lengthScale;
137 for (
auto& t : result) {
138 t.translation() *= scale;
146 const std::vector<size_t>& jointMapping,
149 result.reserve(physicalProperties.size());
151 for (
const auto& jointProperties : physicalProperties) {
152 const size_t sourceJointIndex =
154 if (sourceJointIndex ==
kInvalidIndex || sourceJointIndex >= jointMapping.size()) {
158 const size_t targetJointIndex = jointMapping[sourceJointIndex];
159 if (targetJointIndex ==
kInvalidIndex || targetJointIndex >= targetSkeleton.joints.size()) {
164 mappedProperties.
jointIndex = targetJointIndex;
165 mappedProperties.jointName = targetSkeleton.joints.at(targetJointIndex).name;
166 result.push_back(std::move(mappedProperties));
173std::vector<T> mapParents(
const std::vector<T>& objects,
const std::vector<size_t>& jointMapping) {
174 std::vector<T> result;
175 result.reserve(objects.size());
176 for (
auto o : objects) {
182 o.parent < jointMapping.size(),
183 "Parent {} exceeds joint mapping size {}",
185 jointMapping.size());
186 o.parent = jointMapping[o.parent];
196 const std::vector<size_t>& jointMapping,
197 const std::vector<size_t>& parameterMapping) {
199 result.reserve(limits.size());
200 for (
auto l : limits) {
203 l.data.minMax.parameterIndex = parameterMapping[l.data.minMax.parameterIndex];
210 l.data.minMaxJoint.jointIndex = jointMapping[l.data.minMaxJoint.jointIndex];
216 l.data.linear.referenceIndex = parameterMapping[l.data.linear.referenceIndex];
217 l.data.linear.targetIndex = parameterMapping[l.data.linear.targetIndex];
224 l.data.linearJoint.referenceJointIndex =
225 parameterMapping[l.data.linearJoint.referenceJointIndex];
226 l.data.linearJoint.targetJointIndex = parameterMapping[l.data.linearJoint.targetJointIndex];
227 if (l.data.linearJoint.referenceJointIndex !=
kInvalidIndex &&
233 l.data.halfPlane.param1 = parameterMapping[l.data.halfPlane.param1];
234 l.data.halfPlane.param2 = parameterMapping[l.data.halfPlane.param2];
240 l.data.ellipsoid.parent = jointMapping[l.data.ellipsoid.parent];
241 l.data.ellipsoid.ellipsoidParent = jointMapping[l.data.ellipsoid.ellipsoidParent];
259 for (Eigen::Index iRow = 0; iRow < weights.index.rows(); ++iRow) {
260 for (Eigen::Index jCol = 0; jCol < weights.index.cols(); ++jCol) {
261 if (weights.weight(iRow, jCol) == 0) {
265 const auto mapped = jointMapping[result.index(iRow, jCol)];
267 result.index(iRow, jCol) = (int)mapped;
275std::vector<T> mergeVectors(
const std::vector<T>& left,
const std::vector<T>& right) {
276 std::vector<T> result;
277 result.reserve(left.size() + right.size());
278 std::copy(std::begin(left), std::end(left), std::back_inserter(result));
279 std::copy(std::begin(right), std::end(right), std::back_inserter(result));
284 std::vector<Eigen::Triplet<float>> result;
285 for (
int k = 0; k < mat.outerSize(); ++k) {
286 for (SparseRowMatrixf::InnerIterator it(mat, k); it; ++it) {
287 result.emplace_back(it.row(), it.col(), it.value());
293std::vector<size_t> addMappedParameters(
295 const std::vector<size_t>& jointMapping,
297 std::vector<bool> validParamsOrig(paramTransformOrig.numAllModelParameters());
300 for (Eigen::Index kJointParam = 0; kJointParam < paramTransformOrig.transform.outerSize();
303 const size_t mappedJointIndex = jointMapping[jointIndex];
309 for (SparseRowMatrixf::InnerIterator it(paramTransformOrig.transform, kJointParam); it; ++it) {
311 validParamsOrig[it.col()] =
true;
315 std::vector<size_t> origParamToNewParam(
316 static_cast<size_t>(paramTransformOrig.numAllModelParameters()),
kInvalidIndex);
317 std::unordered_set<std::string> existingParams(
318 paramTransformResult.name.begin(), paramTransformResult.name.end());
319 for (Eigen::Index iParamOld = 0; iParamOld < paramTransformOrig.numAllModelParameters();
322 if (!validParamsOrig[iParamOld]) {
327 existingParams.find(paramTransformOrig.name[iParamOld]) != existingParams.end(),
328 "Duplicate parameter {} found while merging parameter transforms.",
329 paramTransformOrig.name[iParamOld]);
332 origParamToNewParam[iParamOld] = paramTransformResult.name.size();
333 paramTransformResult.name.push_back(paramTransformOrig.name[iParamOld]);
336 std::vector<Eigen::Triplet<float>> tripletsNew = toTriplets(paramTransformResult.transform);
337 for (Eigen::Index kJointParam = 0; kJointParam < paramTransformOrig.transform.outerSize();
341 const size_t mappedJointIndex = jointMapping[jointIndex];
348 for (SparseRowMatrixf::InnerIterator it(paramTransformOrig.transform, kJointParam); it; ++it) {
349 const auto iOldParam = it.col();
351 const auto iNewParam = origParamToNewParam[iOldParam];
353 if (iNewParam != SIZE_MAX) {
354 tripletsNew.emplace_back((
int)mappedJointParam, (
int)iNewParam, it.value());
358 paramTransformResult.transform.resize(
359 paramTransformResult.transform.rows(), paramTransformResult.name.size());
360 paramTransformResult.transform.setFromTriplets(tripletsNew.begin(), tripletsNew.end());
363 for (
const auto& paramSetOrig : paramTransformOrig.parameterSets) {
364 for (Eigen::Index iOrigParam = 0; iOrigParam < paramTransformOrig.numAllModelParameters();
366 if (!paramSetOrig.second.test(iOrigParam)) {
371 const auto iNewParam = origParamToNewParam[iOrigParam];
373 paramTransformResult.parameterSets[paramSetOrig.first].set(iNewParam);
378 return origParamToNewParam;
382 std::unordered_set<std::string> toRemoveNames;
383 for (
const auto& l : toRemove) {
384 toRemoveNames.insert(l.name);
391 [&toRemoveNames](
const Locator& l) { return toRemoveNames.count(l.name) > 0; }),
400 std::unordered_set<size_t> toRemoveJointIndices;
401 for (
const auto& jointProperties : toRemove) {
402 toRemoveJointIndices.insert(jointProperties.jointIndex);
410 return toRemoveJointIndices.count(jointProperties.jointIndex) > 0;
420 MT_CHECK(s > 0.0f,
"scale > 0.0f, got {}", s);
427 scale(character.
mesh, s).get(),
442Skeleton transformSkeleton(
const Skeleton& skeleton,
const Eigen::Affine3f& xform) {
443 const Eigen::Vector3f singularValues = xform.linear().jacobiSvd().singularValues();
444 for (Eigen::Index i = 0; i < 3; ++i) {
446 singularValues(i) > 0.99f && singularValues(i) < 1.01f,
447 "Transform should not include scale or shear.");
450 const Eigen::Quaternionf rotation(xform.linear());
451 const Eigen::Vector3f translation(xform.translation());
456 if (!result.joints.empty() && !skeleton.joints.empty()) {
457 result.joints.front().preRotation = rotation * skeleton.joints.front().preRotation;
458 result.joints.front().translationOffset =
459 rotation * skeleton.joints.front().translationOffset + translation;
466 const Eigen::Affine3f& xform) {
471 const Eigen::Vector3f singularValues = xform.linear().jacobiSvd().singularValues();
472 for (Eigen::Index i = 0; i < 3; ++i) {
474 singularValues(i) > 0.99f && singularValues(i) < 1.01f,
475 "Transform should not include scale or shear.");
478 const Eigen::Quaternionf rotation(xform.linear());
479 const Eigen::Vector3f translation(xform.translation());
482 std::make_unique<momentum::BlendShape>(*blendShape);
485 std::vector<Vector3f> baseShape = blendShapeTransformed->getBaseShape();
486 for (
auto& v : baseShape) {
489 blendShapeTransformed->setBaseShape(baseShape);
492 Eigen::MatrixXf shapeVectors = blendShapeTransformed->getShapeVectors();
494 for (Eigen::Index iShape = 0; iShape < shapeVectors.cols(); ++iShape) {
495 for (Eigen::Index iVertex = 0; iVertex < shapeVectors.rows() / 3; ++iVertex) {
496 Eigen::Vector3f displacement = shapeVectors.block<3, 1>(iVertex * 3, iShape);
497 shapeVectors.block<3, 1>(iVertex * 3, iShape) = rotation * displacement;
500 blendShapeTransformed->setShapeVectors(shapeVectors);
502 return blendShapeTransformed;
505std::unique_ptr<Mesh> transformMesh(
const std::unique_ptr<Mesh>& mesh,
const Eigen::Affine3f& xf) {
510 auto result = std::make_unique<Mesh>(*mesh);
511 for (
auto& v : result->vertices) {
515 for (
auto& v : result->normals) {
524 const Eigen::Affine3f& xf) {
526 result.reserve(inverseBindPose.size());
527 const Eigen::Affine3f xfInv = xf.inverse();
528 for (
const auto& m : inverseBindPose) {
529 result.push_back(m * xfInv);
534std::unique_ptr<CollisionGeometry> transformCollisionGeometry(
535 const std::unique_ptr<CollisionGeometry>& collision,
536 const Eigen::Affine3f& xf) {
541 auto result = std::make_unique<CollisionGeometry>(*collision);
543 for (
auto& primitive : *result) {
545 primitive.transformation = xformTransform * primitive.transformation;
555 transformSkeleton(character.
skeleton, xform),
559 transformMesh(character.
mesh, xform).get(),
561 transformCollisionGeometry(character.
collision, xform).get(),
563 transformBlendShape(character.
blendShape, xform),
575 const std::string& srcRootJoint,
576 const std::string& tgtRootJoint) {
585 "Unable to re-root skeleton, target root joint {} not found.",
591 "Unable to re-root skeleton, source root joint {} not found.",
597 std::unordered_map<std::string, size_t> combinedSkeletonJointMapping;
600 [&](
const Skeleton& skeleton,
size_t jointIndex, std::vector<size_t>& jointMap) ->
size_t {
601 const Joint& origJoint = skeleton.
joints[jointIndex];
602 Joint combinedJoint = origJoint;
604 combinedSkeletonJointMapping.find(combinedJoint.
name) != combinedSkeletonJointMapping.end(),
605 "Duplicate joint '{}' found while reparenting.",
607 const size_t combinedIndex = combinedSkeleton.
joints.size();
608 jointMap[jointIndex] = combinedIndex;
609 combinedSkeletonJointMapping.insert({combinedJoint.
name, combinedIndex});
613 auto itr = combinedSkeletonJointMapping.find(skeleton.
joints[origJoint.
parent].name);
614 MT_CHECK(itr != combinedSkeletonJointMapping.end());
615 combinedJoint.
parent = itr->second;
618 combinedSkeleton.
joints.push_back(combinedJoint);
619 return combinedIndex;
625 for (
size_t iTgtJoint = 0; iTgtJoint < tgtSkeleton.
joints.size(); ++iTgtJoint) {
628 if (iTgtJoint == tgtRoot) {
629 addJoint(tgtSkeleton, iTgtJoint, tgtToCombinedJoints);
632 for (
size_t kSrcJoint = srcRoot + 1; kSrcJoint < srcSkeleton.
joints.size(); ++kSrcJoint) {
633 if (srcSkeleton.
isAncestor(kSrcJoint, srcRoot)) {
634 addJoint(srcSkeleton, kSrcJoint, srcToCombinedJoints);
637 }
else if (!tgtSkeleton.
isAncestor(iTgtJoint, tgtRoot)) {
638 addJoint(tgtSkeleton, iTgtJoint, tgtToCombinedJoints);
649 mapParents<Locator>(srcCharacter.
locators, srcToCombinedJoints);
651 mapParents<Locator>(tgtCharacter.
locators, tgtToCombinedJoints);
653 removeDuplicateLocators(remappedTgtLocators, remappedSrcLocators), remappedSrcLocators);
656 std::unordered_set<std::string> locatorNames;
657 for (
const auto& l : combinedLocators) {
658 MT_LOGW_IF(locatorNames.count(l.name) != 0,
"Duplicate locator: {}", l.name);
659 locatorNames.insert(l.name);
665 combinedCollisionGeometry = mergeVectors(
666 combinedCollisionGeometry, mapParents(*tgtCharacter.
collision, tgtToCombinedJoints));
669 combinedCollisionGeometry = mergeVectors(
670 combinedCollisionGeometry, mapParents(*srcCharacter.
collision, srcToCombinedJoints));
675 combinedParamTransform.
offsets =
678 const std::vector<size_t> tgtToCombinedParameters = addMappedParameters(
680 const std::vector<size_t> srcToCombinedParameters = addMappedParameters(
686 tgtCharacter.
parameterLimits, tgtToCombinedJoints, tgtToCombinedParameters),
688 srcCharacter.
parameterLimits, srcToCombinedJoints, srcToCombinedParameters));
690 std::unique_ptr<SkinWeights> skinWeightsCombined;
698 std::vector<size_t> tgtToCombinedWithParents(
700 for (
size_t iTgtJoint = 0; iTgtJoint < tgtSkeleton.
joints.size(); ++iTgtJoint) {
701 size_t tgtParent = iTgtJoint;
703 const auto itr = combinedSkeletonJointMapping.find(tgtSkeleton.
joints[tgtParent].name);
704 if (itr != combinedSkeletonJointMapping.end()) {
706 tgtToCombinedWithParents[iTgtJoint] = itr->second;
709 tgtParent = tgtSkeleton.
joints[iTgtJoint].parent;
715 skinWeightsCombined = std::make_unique<SkinWeights>(
716 mapSkinWeights(*tgtCharacter.
skinWeights, tgtToCombinedWithParents));
735 removeDuplicatePhysicalProperties(
736 remappedTgtPhysicalProperties, remappedSrcPhysicalProperties),
737 remappedSrcPhysicalProperties);
742 combinedParamTransform,
743 combinedParameterLimits,
745 tgtCharacter.
mesh.get(),
746 skinWeightsCombined.get(),
747 combinedCollisionGeometry.empty() ? nullptr : &combinedCollisionGeometry,
755 combinedPhysicalProperties};
759 std::vector<bool> toRemove(character.
skeleton.
joints.size(),
false);
760 for (
const auto& j : jointsToRemove) {
766 const auto& srcSkeleton = character.
skeleton;
767 std::vector<size_t> srcToResultJoints(srcSkeleton.joints.size(),
kInvalidIndex);
769 for (
size_t iJoint = 0; iJoint < srcSkeleton.joints.size(); ++iJoint) {
770 bool shouldRemove =
false;
772 size_t parent = iJoint;
775 if (toRemove[parent]) {
790 srcToResultJoints[iJoint] = resultSkeleton.
joints.size();
791 auto joint = srcSkeleton.joints[iJoint];
793 joint.parent = srcToResultJoints[joint.parent];
795 resultSkeleton.
joints.push_back(joint);
800 const std::vector<size_t> srcToResultParameters =
801 addMappedParameters(character.
parameterTransform, srcToResultJoints, resultParamTransform);
805 std::unique_ptr<SkinWeights> resultSkinWeights;
808 std::vector<size_t> srcToResultJointsWithParents(
810 for (
size_t iSrcJoint = 0; iSrcJoint < srcSkeleton.joints.size(); ++iSrcJoint) {
811 size_t srcParent = iSrcJoint;
815 srcToResultJointsWithParents[iSrcJoint] = srcToResultJoints[srcParent];
816 if (srcToResultJointsWithParents[iSrcJoint] !=
kInvalidIndex) {
819 srcParent = srcSkeleton.joints[srcParent].parent;
824 resultSkinWeights = std::make_unique<SkinWeights>(
825 mapSkinWeights(*character.
skinWeights, srcToResultJointsWithParents));
831 const LocatorList resultLocators = mapParents<Locator>(character.
locators, srcToResultJoints);
835 resultCollisionGeometry = mapParents(*character.
collision, srcToResultJoints);
839 mapParameterLimits(character.
parameterLimits, srcToResultJoints, srcToResultParameters);
846 resultParamTransform,
847 resultParameterLimits,
849 character.
mesh.get(),
850 resultSkinWeights.get(),
851 resultCollisionGeometry.empty() ? nullptr : &resultCollisionGeometry,
859 resultPhysicalProperties};
864 const std::string& name,
865 const Eigen::Vector3f& translationOffset,
866 const Eigen::Quaternionf& preRotation) {
871 newJoint.
name = name;
875 newJoints.push_back(newJoint);
876 Skeleton newSkeleton(std::move(newJoints));
881 const size_t numJoints = boneIndex + 1;
886 VectorXf newOffsets = VectorXf::Zero(newNumJointParams);
887 newOffsets.head(oldNumJointParams) = newParamTransform.
offsets;
888 newParamTransform.
offsets = std::move(newOffsets);
891 const size_t parameterStartIndex = newParamTransform.
name.size();
892 newParamTransform.
name.push_back(name +
"_tx");
893 newParamTransform.
name.push_back(name +
"_ty");
894 newParamTransform.
name.push_back(name +
"_tz");
895 newParamTransform.
name.push_back(name +
"_rx");
896 newParamTransform.
name.push_back(name +
"_ry");
897 newParamTransform.
name.push_back(name +
"_rz");
900 std::vector<Eigen::Triplet<float>> triplets = toTriplets(newParamTransform.
transform);
901 triplets.emplace_back(
903 static_cast<int>(parameterStartIndex + 0),
905 triplets.emplace_back(
907 static_cast<int>(parameterStartIndex + 1),
909 triplets.emplace_back(
911 static_cast<int>(parameterStartIndex + 2),
913 triplets.emplace_back(
915 static_cast<int>(parameterStartIndex + 3),
917 triplets.emplace_back(
919 static_cast<int>(parameterStartIndex + 4),
921 triplets.emplace_back(
923 static_cast<int>(parameterStartIndex + 5),
926 newParamTransform.
transform.resize(newNumJointParams, newParamTransform.
name.size());
927 newParamTransform.
transform.setFromTriplets(triplets.begin(), triplets.end());
940 character.
mesh.get(),
952 parameterStartIndex};
959 const auto& parameterNames = std::get<0>(inputMotion);
960 const auto& motion = std::get<1>(inputMotion);
963 static_cast<int>(parameterNames.size()) == motion.rows(),
964 "The number of parameter names {} does not match the number of rows {} in the motion.",
965 parameterNames.size(),
970 for (
size_t i = 0; i < parameterNames.size(); i++) {
973 result.row(index) = motion.row(i);
975 MT_LOGW(
"Model parameter {} not found in source motion", parameterNames[i]);
986 const auto& jointNames = std::get<0>(inputIdentity);
987 const auto& identity = std::get<1>(inputIdentity);
991 "The number of joint parameters {} does not match the identity vector size {}.",
996 for (
size_t i = 0; i < jointNames.size(); i++) {
1002 MT_LOGW(
"Joint {} not found in source identity", jointNames[i]);
1013std::vector<Vector3f> reduceBaseShapeVertices(
1014 const std::vector<Vector3f>& baseVertices,
1015 const std::vector<bool>& activeVertices,
1016 size_t newVertexCount) {
1017 std::vector<Vector3f> newBaseVertices;
1018 newBaseVertices.reserve(newVertexCount);
1020 for (
size_t i = 0; i < activeVertices.size(); ++i) {
1021 if (activeVertices[i]) {
1022 newBaseVertices.push_back(baseVertices[i]);
1026 return newBaseVertices;
1033 const std::vector<bool>& activeVertices,
1034 size_t newVertexCount) {
1035 MatrixXf newShapeVectors(newVertexCount * 3, shapeVectors.cols());
1038 for (
size_t i = 0; i < activeVertices.size(); ++i) {
1039 if (activeVertices[i]) {
1040 newShapeVectors.block(newIdx * 3, 0, 3, shapeVectors.cols()) =
1041 shapeVectors.block(i * 3, 0, 3, shapeVectors.cols());
1046 return newShapeVectors;
1049std::pair<std::vector<size_t>, std::vector<size_t>> createIndexMapping(
1050 const std::vector<bool>& activeElements) {
1051 std::vector<size_t> forwardMapping;
1052 std::vector<size_t> reverseMapping(activeElements.size(),
kInvalidIndex);
1053 for (
size_t i = 0; i < activeElements.size(); ++i) {
1054 if (activeElements[i]) {
1056 reverseMapping[i] = forwardMapping.size();
1057 forwardMapping.push_back(i);
1061 return {forwardMapping, reverseMapping};
1064template <
typename T>
1065std::vector<T> selectVertices(
1066 const std::vector<T>& sourceVector,
1067 const std::vector<size_t>& selected) {
1068 std::vector<T> result;
1069 result.reserve(selected.size());
1071 for (
unsigned long i : selected) {
1073 result.push_back(sourceVector[i]);
1079std::vector<Eigen::Vector3i> remapFaces(
1080 const std::vector<Eigen::Vector3i>& faces,
1081 const std::vector<size_t>& mapping,
1082 const std::vector<bool>& activeFaces) {
1083 const size_t nNewFaceCount = std::count(activeFaces.begin(), activeFaces.end(),
true);
1085 std::vector<Eigen::Vector3i> remappedFaces;
1086 remappedFaces.reserve(nNewFaceCount);
1088 for (
size_t iFace = 0; iFace < faces.size(); ++iFace) {
1089 if (!activeFaces[iFace]) {
1093 const auto& face = faces[iFace];
1098 remappedFaces.emplace_back(
1099 static_cast<int>(mapping[face[0]]),
1100 static_cast<int>(mapping[face[1]]),
1101 static_cast<int>(mapping[face[2]]));
1104 return remappedFaces;
1107template <
typename T>
1111 const std::vector<bool>& activeVertices,
1112 const std::vector<size_t>& reverseVertexMapping,
1113 const std::vector<size_t>& reverseTexcoordMapping) {
1114 if (mesh.polyFaces.empty()) {
1118 newMesh.polyFaceSizes.reserve(mesh.polyFaceSizes.size());
1119 newMesh.polyFaces.reserve(mesh.polyFaces.size());
1120 if (!mesh.polyTexcoordFaces.empty()) {
1121 newMesh.polyTexcoordFaces.reserve(mesh.polyTexcoordFaces.size());
1124 uint32_t offset = 0;
1125 for (
const auto polySize : mesh.polyFaceSizes) {
1127 bool allActive =
true;
1128 for (uint32_t i = 0; i < polySize; ++i) {
1129 const auto vtx = mesh.polyFaces[offset + i];
1130 if (vtx >= activeVertices.size() || !activeVertices[vtx]) {
1137 newMesh.polyFaceSizes.push_back(polySize);
1138 for (uint32_t i = 0; i < polySize; ++i) {
1139 newMesh.polyFaces.push_back(
1140 static_cast<uint32_t
>(reverseVertexMapping[mesh.polyFaces[offset + i]]));
1142 if (!mesh.polyTexcoordFaces.empty()) {
1143 for (uint32_t i = 0; i < polySize; ++i) {
1144 newMesh.polyTexcoordFaces.push_back(
1145 static_cast<uint32_t
>(reverseTexcoordMapping[mesh.polyTexcoordFaces[offset + i]]));
1154std::vector<std::vector<int32_t>> remapLines(
1155 const std::vector<std::vector<int32_t>>& lines,
1156 const std::vector<size_t>& mapping) {
1157 std::vector<std::vector<int32_t>> remappedLines;
1158 remappedLines.reserve(lines.size());
1160 for (
const auto& line : lines) {
1161 std::vector<int32_t> newLine;
1162 newLine.reserve(line.size());
1164 bool lineValid =
true;
1165 for (int32_t vertexIdx : line) {
1166 if (vertexIdx >= 0 && vertexIdx <
static_cast<int32_t
>(mapping.size()) &&
1168 newLine.push_back(
static_cast<int32_t
>(mapping[vertexIdx]));
1175 if (lineValid && !newLine.empty()) {
1176 remappedLines.push_back(std::move(newLine));
1180 return remappedLines;
1184 const std::vector<Eigen::Vector3i>& faces,
1185 const std::vector<bool>& activeVertices) {
1186 std::vector<bool> activeFaces(faces.size(),
false);
1188 for (
size_t faceIdx = 0; faceIdx < faces.size(); ++faceIdx) {
1189 const auto& face = faces[faceIdx];
1191 if (face[0] >= 0 && face[0] <
static_cast<int>(activeVertices.size()) && face[1] >= 0 &&
1192 face[1] <
static_cast<int>(activeVertices.size()) && face[2] >= 0 &&
1193 face[2] <
static_cast<int>(activeVertices.size()) && activeVertices[face[0]] &&
1194 activeVertices[face[1]] && activeVertices[face[2]]) {
1196 activeFaces[faceIdx] =
true;
1204 const std::vector<Eigen::Vector3i>& faces,
1205 const std::vector<bool>& activeFaces,
1206 size_t vertexCount) {
1208 activeFaces.size() == faces.size(),
1209 "Active faces size ({}) does not match face count ({})",
1213 std::vector<bool> activeVertices(vertexCount,
false);
1215 for (
size_t faceIdx = 0; faceIdx < activeFaces.size(); ++faceIdx) {
1216 if (activeFaces[faceIdx]) {
1217 const auto& face = faces[faceIdx];
1218 if (face[0] >= 0 && face[0] <
static_cast<int>(vertexCount)) {
1219 activeVertices[face[0]] =
true;
1221 if (face[1] >= 0 && face[1] <
static_cast<int>(vertexCount)) {
1222 activeVertices[face[1]] =
true;
1224 if (face[2] >= 0 && face[2] <
static_cast<int>(vertexCount)) {
1225 activeVertices[face[2]] =
true;
1230 return activeVertices;
1234 const std::vector<uint32_t>& polyFaces,
1235 const std::vector<uint32_t>& polyFaceSizes,
1236 const std::vector<bool>& activeVertices) {
1237 if (polyFaceSizes.empty()) {
1241 std::vector<bool> activePolys(polyFaceSizes.size(),
false);
1242 uint32_t offset = 0;
1243 for (
size_t polyIdx = 0; polyIdx < polyFaceSizes.size(); ++polyIdx) {
1244 const auto polySize = polyFaceSizes[polyIdx];
1245 bool allActive =
true;
1246 for (uint32_t i = 0; i < polySize; ++i) {
1247 const auto vtx = polyFaces[offset + i];
1248 if (vtx >= activeVertices.size() || !activeVertices[vtx]) {
1254 activePolys[polyIdx] = allActive;
1261 const std::vector<uint32_t>& polyFaces,
1262 const std::vector<uint32_t>& polyFaceSizes,
1263 const std::vector<bool>& activePolys,
1264 size_t vertexCount) {
1265 std::vector<bool> activeVertices(vertexCount,
false);
1266 if (activePolys.empty()) {
1267 return activeVertices;
1269 uint32_t offset = 0;
1270 for (
size_t polyIdx = 0; polyIdx < polyFaceSizes.size(); ++polyIdx) {
1271 const auto polySize = polyFaceSizes[polyIdx];
1272 if (activePolys[polyIdx]) {
1273 for (uint32_t i = 0; i < polySize; ++i) {
1274 const auto vtx = polyFaces[offset + i];
1275 if (vtx < vertexCount) {
1276 activeVertices[vtx] =
true;
1282 return activeVertices;
1287template <
typename T>
1290 const std::vector<bool>& activeVertices,
1291 const std::vector<bool>& activeFaces) {
1292 const auto [forwardVertexMapping, reverseVertexMapping] = createIndexMapping(activeVertices);
1296 newMesh.
vertices = selectVertices(mesh.vertices, forwardVertexMapping);
1298 if (!mesh.normals.empty()) {
1299 newMesh.normals = selectVertices(mesh.normals, forwardVertexMapping);
1302 if (!mesh.colors.empty()) {
1303 newMesh.colors = selectVertices(mesh.colors, forwardVertexMapping);
1306 if (!mesh.confidence.empty()) {
1307 newMesh.confidence = selectVertices(mesh.confidence, forwardVertexMapping);
1310 newMesh.faces = remapFaces(mesh.faces, reverseVertexMapping, activeFaces);
1312 if (!mesh.lines.empty()) {
1313 newMesh.lines = remapLines(mesh.lines, reverseVertexMapping);
1316 std::vector<size_t> reverseTextureVertexMapping;
1317 if (!mesh.texcoord_faces.empty() && !mesh.texcoords.empty()) {
1318 std::vector<bool> activeTextureTriangles = activeFaces;
1319 activeTextureTriangles.resize(mesh.texcoord_faces.size(),
false);
1321 const std::vector<bool> activeTextureVertices =
1322 facesToVertices(mesh.texcoord_faces, activeTextureTriangles, mesh.texcoords.size());
1324 auto [forwardTextureVertexMapping, revTexMapping] = createIndexMapping(activeTextureVertices);
1325 reverseTextureVertexMapping = std::move(revTexMapping);
1327 newMesh.texcoords = selectVertices(mesh.texcoords, forwardTextureVertexMapping);
1328 newMesh.texcoord_faces =
1329 remapFaces(mesh.texcoord_faces, reverseTextureVertexMapping, activeTextureTriangles);
1330 newMesh.texcoord_lines = remapLines(mesh.texcoord_lines, reverseTextureVertexMapping);
1333 remapPolyFaces(newMesh, mesh, activeVertices, reverseVertexMapping, reverseTextureVertexMapping);
1343 const std::vector<bool>& activeVertices,
1344 const std::vector<bool>& activeFaces) {
1345 MT_CHECK(character.mesh,
"Cannot reduce mesh: character has no mesh");
1347 activeVertices.size() == character.mesh->vertices.size(),
1348 "Active vertices size ({}) does not match mesh vertex count ({})",
1349 activeVertices.size(),
1350 character.mesh->vertices.size());
1352 activeFaces.size() == character.mesh->faces.size(),
1353 "Active faces size ({}) does not match mesh face count ({})",
1355 character.mesh->faces.size());
1357 const auto [forwardVertexMapping, reverseVertexMapping] = createIndexMapping(activeVertices);
1359 auto newMesh = std::make_unique<Mesh>(
1360 reduceMeshInternal<float>(*character.mesh, activeVertices, activeFaces));
1362 std::unique_ptr<SkinWeights> newSkinWeights;
1363 if (character.skinWeights) {
1364 newSkinWeights = std::make_unique<SkinWeights>();
1365 newSkinWeights->index.resize(forwardVertexMapping.size(),
kMaxSkinJoints);
1366 newSkinWeights->weight.resize(forwardVertexMapping.size(),
kMaxSkinJoints);
1368 for (
size_t newRowIdx = 0; newRowIdx < forwardVertexMapping.size(); ++newRowIdx) {
1369 const auto oldRowIdx = forwardVertexMapping[newRowIdx];
1370 newSkinWeights->index.row(newRowIdx) = character.skinWeights->index.row(oldRowIdx);
1371 newSkinWeights->weight.row(newRowIdx) = character.skinWeights->weight.row(oldRowIdx);
1375 std::unique_ptr<PoseShape> newPoseShapes;
1376 if (character.poseShapes) {
1377 newPoseShapes = std::make_unique<PoseShape>(*character.poseShapes);
1380 VectorXf newBaseShape(forwardVertexMapping.size() * 3);
1382 for (
size_t i = 0; i < activeVertices.size(); ++i) {
1383 if (activeVertices[i]) {
1384 newBaseShape.template segment<3>(newIdx * 3) =
1385 character.poseShapes->baseShape.template segment<3>(i * 3);
1389 newPoseShapes->baseShape = std::move(newBaseShape);
1392 forwardVertexMapping.size() * 3, character.poseShapes->shapeVectors.cols());
1394 for (
size_t i = 0; i < activeVertices.size(); ++i) {
1395 if (activeVertices[i]) {
1396 newShapeVectors.block(newIdx * 3, 0, 3, character.poseShapes->shapeVectors.cols()) =
1397 character.poseShapes->shapeVectors.block(
1398 i * 3, 0, 3, character.poseShapes->shapeVectors.cols());
1402 newPoseShapes->shapeVectors = std::move(newShapeVectors);
1406 if (character.blendShape) {
1407 auto blendShape = std::make_shared<BlendShape>();
1409 std::vector<Vector3f> newBaseVertices = reduceBaseShapeVertices(
1410 character.blendShape->getBaseShape(), activeVertices, forwardVertexMapping.size());
1411 blendShape->setBaseShape(newBaseVertices);
1413 MatrixXf newShapeVectors = reduceBlendShapeVectors(
1414 character.blendShape->getShapeVectors(), activeVertices, forwardVertexMapping.size());
1415 blendShape->setShapeVectors(newShapeVectors);
1417 newBlendShape = blendShape;
1421 if (character.faceExpressionBlendShape) {
1422 auto faceBlendShape = std::make_shared<BlendShapeBase>(
1423 forwardVertexMapping.size(), character.faceExpressionBlendShape->shapeSize());
1425 MatrixXf newShapeVectors = reduceBlendShapeVectors(
1426 character.faceExpressionBlendShape->getShapeVectors(),
1428 forwardVertexMapping.size());
1429 faceBlendShape->setShapeVectors(newShapeVectors);
1431 newFaceExpressionBlendShape = faceBlendShape;
1436 character.parameterTransform,
1437 character.parameterLimits,
1440 newSkinWeights.get(),
1441 character.collision.get(),
1442 newPoseShapes.get(),
1443 std::move(newBlendShape),
1444 std::move(newFaceExpressionBlendShape),
1446 character.inverseBindPose,
1447 character.skinnedLocators,
1449 character.physicalProperties};
1456 const std::vector<bool>& activeVertices) {
1457 MT_CHECK(character.
mesh,
"Cannot reduce mesh: character has no mesh");
1459 activeVertices.size() == character.
mesh->vertices.size(),
1460 "Active vertices size ({}) does not match mesh vertex count ({})",
1461 activeVertices.size(),
1462 character.
mesh->vertices.size());
1466 return reduceMeshComponents(character, activeVertices, activeFaces);
1470 MT_CHECK(character.
mesh,
"Cannot reduce mesh: character has no mesh");
1472 activeFaces.size() == character.
mesh->faces.size(),
1473 "Active faces size ({}) does not match mesh face count ({})",
1475 character.
mesh->faces.size());
1479 return reduceMeshComponents(character, activeVertices, activeFaces);
1482template <
typename T>
1485 activeVertices.size() == mesh.
vertices.size(),
1486 "Active vertices size ({}) does not match mesh vertex count ({})",
1487 activeVertices.size(),
1492 return reduceMeshInternal(mesh, activeVertices, activeFaces);
1495template <
typename T>
1498 activeFaces.size() == mesh.
faces.size(),
1499 "Active faces size ({}) does not match mesh face count ({})",
1505 return reduceMeshInternal(mesh, activeVertices, activeFaces);
1508template <
typename T>
1511 activeVertices.size() == mesh.
vertices.size(),
1512 "Active vertices size ({}) does not match mesh vertex count ({})",
1513 activeVertices.size(),
1519template <
typename T>
1522 activeFaces.size() == mesh.
faces.size(),
1523 "Active faces size ({}) does not match mesh face count ({})",
1530template <
typename T>
1533 activeVertices.size() == mesh.
vertices.size(),
1534 "Active vertices size ({}) does not match mesh vertex count ({})",
1535 activeVertices.size(),
1541template <
typename T>
1545 "Active polys size ({}) does not match polygon count ({})",
1552template <
typename T>
1556 "Active polys size ({}) does not match polygon count ({})",
1563 return reduceMeshInternal(mesh, activeVertices, activeFaces);
1567 MT_CHECK(character.
mesh,
"Cannot reduce mesh: character has no mesh");
1569 activePolys.size() == character.
mesh->polyFaceSizes.size(),
1570 "Active polys size ({}) does not match polygon count ({})",
1572 character.
mesh->polyFaceSizes.size());
1577 return reduceMeshComponents(character, activeVertices, activeFaces);
1582 const std::vector<bool>& activeVertices);
1586 const std::vector<bool>& activeVertices);
1590 const std::vector<bool>& activeFaces);
1594 const std::vector<bool>& activeFaces);
1598 const std::vector<bool>& activeVertices);
1602 const std::vector<bool>& activeVertices);
1606 const std::vector<bool>& activeFaces);
1610 const std::vector<bool>& activeFaces);
1614 const std::vector<bool>& activeVertices);
1618 const std::vector<bool>& activeVertices);
1622 const std::vector<bool>& activePolys);
1626 const std::vector<bool>& activePolys);
1630 const std::vector<bool>& activePolys);
1634 const std::vector<bool>& activePolys);
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
#define MT_LOGW_IF(condition,...)
template MeshT< double > reduceMeshByVertices< double >(const MeshT< double > &mesh, const std::vector< bool > &activeVertices)
TransformT< float > Transform
CollisionGeometryT< float > CollisionGeometry
SkeletonT< float > Skeleton
Affine3< float > Affine3f
::std::shared_ptr< const BlendShapeBase > BlendShapeBase_const_p
std::tuple< std::vector< std::string >, JointParameters > IdentityParameters
A tuple of skeleton joint names and identity parameters.
template std::vector< bool > facesToVertices< double >(const MeshT< double > &mesh, const std::vector< bool > &activeFaces)
Character replaceSkeletonHierarchy(const Character &srcCharacter, const Character &tgtCharacter, const std::string &srcRootJoint, const std::string &tgtRootJoint)
Replaces the subtree of tgtCharacter's skeleton rooted at tgtRootJoint with the subtree of srcCharact...
Character removeJoints(const Character &character, momentum::span< const size_t > jointsToRemove)
Removes the specified joints and any joints parented beneath them from the character.
JointListT< float > JointList
JointParameters mapIdentityToCharacter(const IdentityParameters &inputIdentity, const Character &targetCharacter)
Maps the input JointParameter vector to a target character by matching joint names.
template MeshT< float > reduceMeshByFaces< float >(const MeshT< float > &mesh, const std::vector< bool > &activeFaces)
template std::vector< bool > verticesToPolys< double >(const MeshT< double > &mesh, const std::vector< bool > &activeVertices)
std::vector< bool > facesToVertices(const MeshT< T > &mesh, const std::vector< bool > &activeFaces)
Converts a face selection to a vertex selection.
Character reduceMeshByVertices(const Character &character, const std::vector< bool > &activeVertices)
Reduces the character's mesh to only include the specified vertices and associated faces.
MatrixXf mapMotionToCharacter(const MotionParameters &inputMotion, const Character &targetCharacter)
Maps the input ModelParameter motion to a target character by matching model parameter names.
std::tuple< std::vector< std::string >, Eigen::MatrixXf > MotionParameters
A tuple of model parameter names and a matrix of poses across a sequence of frames.
std::vector< Affine3f > TransformationList
One affine transform per joint, indexed by joint id.
std::vector< ParameterLimit > ParameterLimits
template MeshT< float > reduceMeshByPolys< float >(const MeshT< float > &mesh, const std::vector< bool > &activePolys)
template std::vector< bool > verticesToFaces< double >(const MeshT< double > &mesh, const std::vector< bool > &activeVertices)
::std::shared_ptr< BlendShape > BlendShape_p
ParameterTransformT< float > ParameterTransform
template std::vector< bool > verticesToFaces< float >(const MeshT< float > &mesh, const std::vector< bool > &activeVertices)
std::vector< bool > verticesToPolys(const MeshT< T > &mesh, const std::vector< bool > &activeVertices)
Converts a vertex selection to a polygon selection.
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
std::vector< SkinnedLocator > SkinnedLocatorList
A collection of locators attached to a skeleton.
template std::vector< bool > facesToVertices< float >(const MeshT< float > &mesh, const std::vector< bool > &activeFaces)
JointParametersT< float > JointParameters
template MeshT< double > reduceMeshByPolys< double >(const MeshT< double > &mesh, const std::vector< bool > &activePolys)
MeshT< T > reduceMeshByPolys(const MeshT< T > &mesh, const std::vector< bool > &activePolys)
Reduces a standalone mesh to only include the specified polygons and associated vertices.
RigidTransformNodeResult addRigidTransformNode(const Character &character, const std::string &name, const Eigen::Vector3f &translationOffset, const Eigen::Quaternionf &preRotation)
Adds a new root-level joint with 6 rigid DOF parameters (tx/ty/tz/rx/ry/rz) to a character.
constexpr size_t kParametersPerJoint
template MeshT< double > reduceMeshByFaces< double >(const MeshT< double > &mesh, const std::vector< bool > &activeFaces)
std::vector< bool > polysToVertices(const MeshT< T > &mesh, const std::vector< bool > &activePolys)
Converts a polygon selection to a vertex selection.
template std::vector< bool > verticesToPolys< float >(const MeshT< float > &mesh, const std::vector< bool > &activeVertices)
template std::vector< bool > polysToVertices< float >(const MeshT< float > &mesh, const std::vector< bool > &activePolys)
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
size_t resolvePhysicalPropertiesJointIndex(const JointPhysicalProperties &properties, const Skeleton &skeleton)
Resolves physical mass properties to a skeleton joint.
VectorX< float > VectorXf
template std::vector< bool > polysToVertices< double >(const MeshT< double > &mesh, const std::vector< bool > &activePolys)
CharacterMassScale
Policy for choosing how physical mass changes when scaling a character.
@ PreserveDensity
Preserve density while scaling lengths, so mass changes with volume.
@ PreserveMass
Preserve total mass while scaling lengths. This is appropriate for unit conversions.
Character reduceMeshByFaces(const Character &character, const std::vector< bool > &activeFaces)
Reduces the character's mesh to only include the specified faces and associated vertices.
::std::shared_ptr< const BlendShape > BlendShape_const_p
std::vector< bool > verticesToFaces(const MeshT< T > &mesh, const std::vector< bool > &activeVertices)
Converts a vertex selection to a face selection.
constexpr uint32_t kMaxSkinJoints
Maximum number of joints that can influence a single vertex.
template MeshT< float > reduceMeshByVertices< float >(const MeshT< float > &mesh, const std::vector< bool > &activeVertices)
SparseRowMatrix< float > SparseRowMatrixf
MatrixX< float > MatrixXf
Character transformCharacter(const Character &character, const Affine3f &xform)
Transforms the character (mesh and skeleton) by the desired transformation matrix.
std::vector< Locator > LocatorList
A collection of locators attached to a skeleton.
Character scaleCharacter(const Character &character, float s, CharacterMassScale massScale)
Scales the character (mesh and skeleton) by the desired amount.
A character model with skeletal structure, mesh, and optional components.
TransformationList inverseBindPose
Inverse of the bind pose transformations for each joint.
LocatorList locators
Points of interest attached to joints.
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
PhysicalProperties physicalProperties
Joint-level physical mass and inertia data loaded from model assets.
BlendShapeBase_const_p faceExpressionBlendShape
Facial expression blend shapes.
ParameterLimits parameterLimits
Constraints on model parameters.
Mesh_u mesh
3D mesh representing the character's surface
PoseShape_u poseShapes
Pose-dependent shape corrections.
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
std::string name
Character identifier.
SkinnedLocatorList skinnedLocators
Points of interest attached to joints, with skinning weights.
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
BlendShape_const_p blendShape
Shape variations that can be blended.
std::string metadata
Metadata (as a JSON-serialized string).
CollisionGeometry_u collision
Collision volumes for the character.
Physical mass properties attached to one skeleton joint.
size_t jointIndex
Cached joint index.
std::string jointName
Skeleton joint that owns this physical body.
size_t parent
Index of the parent joint in the skeleton hierarchy, or kInvalidIndex for the root.
Quaternion< T > preRotation
Pre-rotation from the parent joint's axes to this joint's local axes.
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...
Represents a point attached to a joint in a skeleton.
A generic mesh representation with support for vertices, faces, lines, and texture coordinates.
std::vector< uint32_t > polyFaces
Packed polygon face vertex indices (all polygons concatenated back-to-back).
std::vector< uint32_t > polyFaceSizes
Number of vertices in each polygon face.
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
bool isAncestor(size_t jointId, size_t ancestorJointId) const
Returns true if ancestorJointId is an ancestor of jointId.
Linear blend skinning weights for a character mesh: per-vertex joint indices and influence weights.