27#include <fbxsdk/scene/geometry/fbxcluster.h>
32#include <fbxsdk/fileio/fbxiosettings.h>
40#include <unordered_map>
41#include <unordered_set>
49[[nodiscard]] inline ::fbxsdk::FbxAxisSystem::EUpVector
toFbx(
const FbxUpVector upVector) {
52 return ::fbxsdk::FbxAxisSystem::EUpVector::eXAxis;
54 return ::fbxsdk::FbxAxisSystem::EUpVector::eYAxis;
56 return ::fbxsdk::FbxAxisSystem::EUpVector::eZAxis;
63 switch (frontVector) {
65 return ::fbxsdk::FbxAxisSystem::EFrontVector::eParityEven;
67 return ::fbxsdk::FbxAxisSystem::EFrontVector::eParityOdd;
69 MT_THROW(
"Unsupported front vector");
74 switch (coordSystem) {
76 return ::fbxsdk::FbxAxisSystem::ECoordSystem::eRightHanded;
78 return ::fbxsdk::FbxAxisSystem::ECoordSystem::eLeftHanded;
80 MT_THROW(
"Unsupported coordinate system");
95inline void setFrameRate(::fbxsdk::FbxScene* scene,
const double framerate) {
96 if (std::abs(framerate - 30.0) < 1e-6) {
97 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames30);
98 }
else if (std::abs(framerate - 24.0) < 1e-6) {
99 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames24);
100 }
else if (std::abs(framerate - 48.0) < 1e-6) {
101 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames48);
102 }
else if (std::abs(framerate - 50.0) < 1e-6) {
103 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames50);
104 }
else if (std::abs(framerate - 60.0) < 1e-6) {
105 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames60);
106 }
else if (std::abs(framerate - 72.0) < 1e-6) {
107 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames72);
108 }
else if (std::abs(framerate - 96.0) < 1e-6) {
109 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames96);
110 }
else if (std::abs(framerate - 100.0) < 1e-6) {
111 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames100);
112 }
else if (std::abs(framerate - 120.0) < 1e-6) {
113 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames120);
114 }
else if (std::abs(framerate - 1000.0) < 1e-6) {
115 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eFrames1000);
117 scene->GetGlobalSettings().SetTimeMode(::fbxsdk::FbxTime::eCustom);
118 scene->GetGlobalSettings().SetCustomFrameRate(framerate);
127 std::vector<::fbxsdk::FbxNode*>
nodes;
134 ::fbxsdk::FbxScene* scene) {
140 ::fbxsdk::FbxNode* skeletonNode = ::fbxsdk::FbxNode::Create(scene, joint.name.c_str());
141 ::fbxsdk::FbxSkeleton* skeletonAttribute =
142 ::fbxsdk::FbxSkeleton::Create(scene, joint.name.c_str());
146 skeletonAttribute->SetSkeletonType(::fbxsdk::FbxSkeleton::eRoot);
148 skeletonAttribute->SetSkeletonType(::fbxsdk::FbxSkeleton::eLimbNode);
150 skeletonNode->SetNodeAttribute(skeletonAttribute);
153 skeletonNode->LclTranslation.Set(FbxDouble3(
154 joint.translationOffset[0], joint.translationOffset[1], joint.translationOffset[2]));
158 skeletonNode->SetPivotState(FbxNode::eSourcePivot, FbxNode::ePivotActive);
159 skeletonNode->SetRotationActive(
true);
160 skeletonNode->SetPreRotation(
161 ::fbxsdk::FbxNode::eSourcePivot,
164 result.
nodes.emplace_back(skeletonNode);
173 joint.parent >= result.
nodes.size(),
174 "Joint parent index {} exceeds nodes size {}",
176 result.
nodes.size());
177 result.
nodes[joint.parent]->AddChild(skeletonNode);
186 const std::unordered_map<size_t, fbxsdk::FbxNode*>& jointToNodeMap) {
187 std::unordered_set<size_t> seenJoints;
189 const size_t jointIndex =
194 "Physical properties entry references unknown joint '{}'",
195 jointProperties.jointName);
197 !seenJoints.insert(jointIndex).second,
198 "Multiple physical properties entries resolve to joint '{}' (index {})",
202 const auto nodeIt = jointToNodeMap.find(jointIndex);
204 nodeIt == jointToNodeMap.end() || nodeIt->second ==
nullptr,
205 "Unable to find FBX node for physical properties joint '{}'",
208 ::fbxsdk::FbxProperty::Create(nodeIt->second, ::fbxsdk::FbxStringDT,
"physicalProperties")
218 if (skeletonRootNode !=
nullptr) {
219 ::fbxsdk::FbxProperty::Create(skeletonRootNode, ::fbxsdk::FbxStringDT,
"metadata")
220 .Set(FbxString(character.
metadata.c_str()));
221 ::fbxsdk::FbxProperty::Create(skeletonRootNode, ::fbxsdk::FbxStringDT,
"name")
222 .Set(FbxString(character.
name.c_str()));
223 ::fbxsdk::FbxProperty::Create(skeletonRootNode, ::fbxsdk::FbxStringDT,
"RigName")
224 .Set(FbxString(character.
name.c_str()));
230 ::fbxsdk::FbxScene* scene,
231 const std::vector<::fbxsdk::FbxNode*>& skeletonNodes) {
232 for (
const auto& loc : character.
locators) {
233 ::fbxsdk::FbxMarker* markerAttribute = ::fbxsdk::FbxMarker::Create(scene, loc.name.c_str());
234 markerAttribute->Look.Set(::fbxsdk::FbxMarker::ELook::eHardCross);
236 ::fbxsdk::FbxNode* locatorNode = ::fbxsdk::FbxNode::Create(scene, loc.name.c_str());
237 locatorNode->SetNodeAttribute(markerAttribute);
238 locatorNode->LclTranslation.Set(FbxVector4(loc.offset[0], loc.offset[1], loc.offset[2]));
242 loc.parent >= skeletonNodes.size(),
243 "Locator parent index {} exceeds skeletonNodes size {}",
245 skeletonNodes.size());
246 skeletonNodes[loc.parent]->AddChild(locatorNode);
253 ::fbxsdk::FbxScene* scene,
254 const std::vector<::fbxsdk::FbxNode*>& skeletonNodes) {
257 "No collision geometry found in character, skipping creation of collision geometry nodes");
261 const auto& collisions = *character.
collision;
262 for (
auto i = 0u; i < collisions.size(); ++i) {
263 const auto& collision = collisions[i];
265 ::fbxsdk::FbxNode* collisionNode =
266 ::fbxsdk::FbxNode::Create(scene, (
"Collision " + std::to_string(i)).c_str());
267 auto* nullNodeAttr = ::fbxsdk::FbxNull::Create(scene,
"Null");
268 collisionNode->SetNodeAttribute(nullNodeAttr);
270 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxBoolDT,
"Col_Type").Set(
true);
272 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxStringDT,
"Col_Shape")
273 .Set(FbxString(
"tapered_capsule"));
274 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Length")
275 .Set(collision.length);
276 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Rad_A")
277 .Set(collision.radius[0]);
278 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Rad_B")
279 .Set(collision.radius[1]);
281 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxStringDT,
"Col_Shape")
282 .Set(FbxString(
"ellipsoid"));
283 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Radii_X")
284 .Set(collision.ellipsoidRadii.x());
285 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Radii_Y")
286 .Set(collision.ellipsoidRadii.y());
287 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Radii_Z")
288 .Set(collision.ellipsoidRadii.z());
290 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxStringDT,
"Col_Shape")
291 .Set(FbxString(
"box"));
292 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Half_Extents_X")
293 .Set(collision.boxHalfExtents.x());
294 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Half_Extents_Y")
295 .Set(collision.boxHalfExtents.y());
296 ::fbxsdk::FbxProperty::Create(collisionNode, ::fbxsdk::FbxFloatDT,
"Half_Extents_Z")
297 .Set(collision.boxHalfExtents.z());
300 "Unsupported collision primitive type {} while writing FBX collision geometry",
301 static_cast<int>(collision.type));
304 collisionNode->LclTranslation.Set(FbxVector4(
305 collision.transformation.translation.x(),
306 collision.transformation.translation.y(),
307 collision.transformation.translation.z()));
310 collisionNode->LclRotation.Set(FbxDouble3(
toDeg(rot.x()),
toDeg(rot.y()),
toDeg(rot.z())));
311 collisionNode->LclScaling.Set(FbxDouble3(1));
315 collision.parent >= skeletonNodes.size(),
316 "Collision parent index {} exceeds skeletonNodes size {}",
318 skeletonNodes.size());
319 skeletonNodes[collision.parent]->AddChild(collisionNode);
321 MT_LOGE(
"Found a collision node with no parent");
331 ::fbxsdk::FbxScene* scene,
332 const char* stackName) {
333 ::fbxsdk::FbxAnimStack* animStack =
nullptr;
334 if (scene->GetSrcObjectCount<::fbxsdk::FbxAnimStack>() > 0) {
335 animStack = scene->GetSrcObject<::fbxsdk::FbxAnimStack>(0);
337 animStack = ::fbxsdk::FbxAnimStack::Create(scene, stackName);
340 ::fbxsdk::FbxAnimLayer* animBaseLayer =
nullptr;
341 if (animStack->GetMemberCount<::fbxsdk::FbxAnimLayer>() > 0) {
342 animBaseLayer = animStack->GetMember<::fbxsdk::FbxAnimLayer>(0);
344 animBaseLayer = ::fbxsdk::FbxAnimLayer::Create(scene,
"Layer0");
345 animStack->AddMember(animBaseLayer);
348 return {animStack, animBaseLayer};
363 if (curveOffset < 3) {
365 }
else if (curveOffset < 6) {
368 return std::exp2(value);
380 const std::vector<::fbxsdk::FbxNode*>& skeletonNodes,
381 ::fbxsdk::FbxAnimLayer* animBaseLayer,
382 const bool skipActiveJointParamCheck) {
390 const size_t index = i * 9;
391 skeletonNodes[i]->LclTranslation.GetCurveNode(
true);
393 if (skipActiveJointParamCheck || aj[jointIndex + 0]) {
394 setup.
animCurves[index + 0] = skeletonNodes[i]->LclTranslation.GetCurve(
395 animBaseLayer, FBXSDK_CURVENODE_COMPONENT_X,
true);
398 if (skipActiveJointParamCheck || aj[jointIndex + 1]) {
399 setup.
animCurves[index + 1] = skeletonNodes[i]->LclTranslation.GetCurve(
400 animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Y,
true);
403 if (skipActiveJointParamCheck || aj[jointIndex + 2]) {
404 setup.
animCurves[index + 2] = skeletonNodes[i]->LclTranslation.GetCurve(
405 animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Z,
true);
408 skeletonNodes[i]->LclRotation.GetCurveNode(
true);
409 if (skipActiveJointParamCheck || aj[jointIndex + 3]) {
411 skeletonNodes[i]->LclRotation.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_X,
true);
414 if (skipActiveJointParamCheck || aj[jointIndex + 4]) {
416 skeletonNodes[i]->LclRotation.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Y,
true);
419 if (skipActiveJointParamCheck || aj[jointIndex + 5]) {
421 skeletonNodes[i]->LclRotation.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Z,
true);
424 skeletonNodes[i]->LclScaling.GetCurveNode(
true);
425 if (skipActiveJointParamCheck || aj[jointIndex + 6]) {
427 skeletonNodes[i]->LclScaling.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_X,
true);
430 skeletonNodes[i]->LclScaling.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Y,
true);
433 skeletonNodes[i]->LclScaling.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Z,
true);
445 ::fbxsdk::FbxScene* scene,
446 const std::vector<::fbxsdk::FbxNode*>& skeletonNodes,
448 const double framerate,
449 const bool skipActiveJointParamCheck) {
456 auto [animCurves, animCurvesIndex] =
459 ::fbxsdk::FbxTime time;
460 for (
const auto ai : animCurvesIndex) {
461 const size_t jointIndex = ai / 9;
462 const size_t jointOffset = ai % 9;
463 const size_t parameterIndex =
465 if (!skipActiveJointParamCheck && aj[parameterIndex] == 0) {
471 animCurves[ai]->KeyModifyBegin();
472 for (
size_t f = 0; f < jointValues.cols(); f++) {
473 time.SetSecondDouble(
static_cast<double>(f) / framerate);
474 const float jointVal =
jointParamToFbx(jointValues(parameterIndex, f), jointOffset, joint);
475 const auto keyIndex = animCurves[ai]->KeyAdd(time);
476 animCurves[ai]->KeySet(keyIndex, time, jointVal);
478 animCurves[ai]->KeyModifyEnd();
489 ::fbxsdk::FbxScene* scene,
490 ::fbxsdk::FbxMesh* mesh,
491 const std::unordered_map<size_t, fbxsdk::FbxNode*>& jointToNodeMap) {
492 ::fbxsdk::FbxSkin* fbxskin = ::fbxsdk::FbxSkin::Create(scene,
"meshskinning");
493 fbxskin->SetSkinningType(::fbxsdk::FbxSkin::eLinear);
494 fbxskin->SetGeometry(mesh);
495 FbxAMatrix meshTransform;
496 meshTransform.SetIdentity();
497 for (
const auto& jointNode : jointToNodeMap) {
498 size_t jointIdx = jointNode.first;
499 auto* fbxJointNode = jointNode.second;
501 std::ostringstream s;
502 s <<
"skinningcluster_" << jointIdx;
503 FbxCluster* pCluster = ::fbxsdk::FbxCluster::Create(scene, s.str().c_str());
504 pCluster->SetLinkMode(::fbxsdk::FbxCluster::ELinkMode::eNormalize);
505 pCluster->SetLink(fbxJointNode);
507 ::fbxsdk::FbxAMatrix globalMatrix = fbxJointNode->EvaluateLocalTransform();
508 ::fbxsdk::FbxNode* pParent = fbxJointNode->GetParent();
509 while (pParent !=
nullptr) {
510 globalMatrix = pParent->EvaluateLocalTransform() * globalMatrix;
511 pParent = pParent->GetParent();
513 pCluster->SetTransformLinkMatrix(globalMatrix);
514 pCluster->SetTransformMatrix(meshTransform);
516 for (
int i = 0; i < character.
skinWeights->index.rows(); i++) {
517 for (
int j = 0; j < character.
skinWeights->index.cols(); j++) {
518 auto boneIndex = character.
skinWeights->index(i, j);
519 if (boneIndex == jointNode.first && character.
skinWeights->weight(i, j) > 0) {
520 pCluster->AddControlPointIndex(i, character.
skinWeights->weight(i, j));
524 fbxskin->AddCluster(pCluster);
526 mesh->AddDeformer(fbxskin);
537 lMesh->BeginPolygon();
538 for (uint32_t i = 0; i < polySize; ++i) {
539 lMesh->AddPolygon(mesh.
polyFaces[offset + i]);
545 for (
const auto& face : mesh.
faces) {
546 lMesh->BeginPolygon();
547 for (
int i = 0; i < 3; i++) {
548 lMesh->AddPolygon(face[i]);
557 ::fbxsdk::FbxMesh* lMesh,
558 fbxsdk::FbxLayerElement::EType uvType) {
563 for (uint32_t i = 0; i < polySize; ++i) {
566 lMesh->SetTextureUVIndex(polyIdx, i, texIdx, uvType);
572 for (
int faceIdx = 0; faceIdx < static_cast<int>(mesh.
texcoord_faces.size()); ++faceIdx) {
574 lMesh->SetTextureUVIndex(faceIdx, 0, texcoords[0], uvType);
575 lMesh->SetTextureUVIndex(faceIdx, 1, texcoords[1], uvType);
576 lMesh->SetTextureUVIndex(faceIdx, 2, texcoords[2], uvType);
592 ::fbxsdk::FbxScene* scene,
593 ::fbxsdk::FbxMesh* mesh,
594 const std::string& deformerName,
595 const std::string& channelPrefix) {
596 std::vector<::fbxsdk::FbxBlendShapeChannel*> channels;
598 ::fbxsdk::FbxBlendShape* fbxBlendShape =
599 ::fbxsdk::FbxBlendShape::Create(scene, deformerName.c_str());
600 fbxBlendShape->SetGeometry(mesh);
604 const int numVertices = mesh->GetControlPointsCount();
606 for (Eigen::Index i = 0; i < blendShape.
shapeSize(); i++) {
607 ::fbxsdk::FbxBlendShapeChannel* channelPtr =
608 ::fbxsdk::FbxBlendShapeChannel::Create(scene, (channelPrefix + std::to_string(i)).c_str());
609 fbxBlendShape->AddBlendShapeChannel(channelPtr);
610 channels.push_back(channelPtr);
612 ::fbxsdk::FbxShape* shape = ::fbxsdk::FbxShape::Create(scene, names[i].c_str());
613 shape->SetControlPointCount(numVertices);
614 for (
int j = 0; j < numVertices; j++) {
615 const auto basePoint = mesh->GetControlPointAt(j);
616 if (j * 3 + 2 < shapes.rows()) {
617 const Eigen::Vector3f delta = shapes.block<3, 1>(j * 3, i);
618 shape->SetControlPointAt(
620 basePoint[0] + delta.x(), basePoint[1] + delta.y(), basePoint[2] + delta.z()),
623 shape->SetControlPointAt(basePoint, j);
625 shape->AddControlPointIndex(j);
627 channelPtr->AddTargetShape(shape, 100.0);
630 mesh->AddDeformer(fbxBlendShape);
635 ::fbxsdk::FbxScene* scene,
636 const std::vector<::fbxsdk::FbxBlendShapeChannel*>& channels,
638 const double framerate) {
639 if (channels.empty() || weights.cols() == 0) {
645 auto [animStack, animBaseLayer] =
648 const Eigen::Index numChannels =
649 std::min(
static_cast<Eigen::Index
>(channels.size()), weights.rows());
651 for (Eigen::Index i = 0; i < numChannels; i++) {
652 ::fbxsdk::FbxAnimCurve* curve = channels[i]->DeformPercent.GetCurve(animBaseLayer,
true);
653 if (curve ==
nullptr) {
657 curve->KeyModifyBegin();
658 for (Eigen::Index f = 0; f < weights.cols(); f++) {
659 ::fbxsdk::FbxTime time;
660 time.SetSecondDouble(
static_cast<double>(f) / framerate);
661 const float value = weights(i, f) * 100.0f;
662 const auto keyIndex = curve->KeyAdd(time);
663 curve->KeySet(keyIndex, time, value);
665 curve->KeyModifyEnd();
673 ::fbxsdk::FbxScene* scene,
674 ::fbxsdk::FbxNode* parentNode,
675 const std::unordered_map<size_t, fbxsdk::FbxNode*>& jointToNodeMap,
677 const std::string& meshName =
"body_mesh") {
679 const auto numVertices =
static_cast<int>(character.
mesh.get()->vertices.size());
680 ::fbxsdk::FbxNode* meshNode = ::fbxsdk::FbxNode::Create(scene, meshName.c_str());
681 ::fbxsdk::FbxMesh* lMesh = ::fbxsdk::FbxMesh::Create(scene,
"mesh");
682 lMesh->SetControlPointCount(numVertices);
683 lMesh->InitNormals(numVertices);
684 for (
int i = 0; i < numVertices; i++) {
686 character.
mesh.get()->vertices[i].x(),
687 character.
mesh.get()->vertices[i].y(),
688 character.
mesh.get()->vertices[i].z());
690 character.
mesh.get()->normals[i].x(),
691 character.
mesh.get()->normals[i].y(),
692 character.
mesh.get()->normals[i].z());
693 lMesh->SetControlPointAt(point,
normal, i);
696 lMesh->BuildMeshEdgeArray();
697 meshNode->SetNodeAttribute(lMesh);
700 if (!character.
mesh->texcoords.empty()) {
701 const fbxsdk::FbxLayerElement::EType uvType = fbxsdk::FbxLayerElement::eTextureDiffuse;
702 lMesh->InitTextureUV(0, uvType);
703 lMesh->InitTextureUVIndices(::fbxsdk::FbxLayerElement::EMappingMode::eByPolygonVertex, uvType);
704 for (
const auto& texcoords : character.
mesh->texcoords) {
705 lMesh->AddTextureUV(::fbxsdk::FbxVector2(texcoords[0], 1.0f - texcoords[1]), uvType);
713 "The character '{}' has no skinning weights and permissive mode is not enabled.",
722 const auto& base = character.
blendShape->getBaseShape();
723 for (
int j = 0; j < numVertices; j++) {
724 FbxVector4 point(base[j].x(), base[j].y(), base[j].z());
725 lMesh->SetControlPointAt(point, j);
737 "face_expression_blendshape",
738 "face_expr_channel_");
741 parentNode->AddChild(meshNode);
751 if (poses.cols() == 0 || pt.blendShapeParameters.size() == 0 || !character.
blendShape ||
757 MatrixXf weights(numShapes, poses.cols());
758 for (Eigen::Index i = 0; i < numShapes; i++) {
759 const auto paramIdx = pt.blendShapeParameters(i);
760 if (paramIdx >= 0 && paramIdx < poses.rows()) {
761 weights.row(i) = poses.row(paramIdx);
763 weights.row(i).setZero();
771 if (poses.cols() == 0 || pt.faceExpressionParameters.size() == 0 ||
777 MatrixXf weights(numExprs, poses.cols());
778 for (Eigen::Index i = 0; i < numExprs; i++) {
779 const auto paramIdx = pt.faceExpressionParameters(i);
780 if (paramIdx >= 0 && paramIdx < poses.rows()) {
781 weights.row(i) = poses.row(paramIdx);
783 weights.row(i).setZero();
798 ::fbxsdk::FbxScene* scene,
799 std::span<
const std::vector<Marker>> markerSequence,
800 const double framerate) {
801 std::vector<::fbxsdk::FbxNode*> markerNodes;
802 if (markerSequence.empty()) {
808 ::fbxsdk::FbxNode* markersRootNode = ::fbxsdk::FbxNode::Create(scene,
"Markers");
809 ::fbxsdk::FbxNull* markersRootAttr = ::fbxsdk::FbxNull::Create(scene,
"MarkersRootNull");
810 markersRootNode->SetNodeAttribute(markersRootAttr);
815 std::map<std::string, size_t> markerNameToIndex;
816 std::vector<std::string> markerNames;
817 std::vector<std::vector<float>> timestamps;
818 std::vector<std::vector<Vector3d>> markerPositions;
820 for (
size_t frameIndex = 0; frameIndex < markerSequence.size(); ++frameIndex) {
821 const float timestamp =
static_cast<float>(frameIndex) /
static_cast<float>(framerate);
822 for (
const auto& marker : markerSequence[frameIndex]) {
823 if (marker.occluded) {
827 if (markerNameToIndex.count(marker.name) == 0) {
828 const auto index = timestamps.size();
829 timestamps.emplace_back();
830 markerPositions.emplace_back();
831 markerNameToIndex[marker.name] = index;
832 markerNames.emplace_back(marker.name);
835 const auto& index = markerNameToIndex.at(marker.name);
837 index >= timestamps.size() || index >= markerPositions.size(),
838 "Marker index {} exceeds container size",
840 timestamps[index].push_back(timestamp);
841 markerPositions[index].push_back(marker.pos);
845 for (
const auto& markerName : markerNames) {
846 ::fbxsdk::FbxMarker* markerAttribute = ::fbxsdk::FbxMarker::Create(scene, markerName.c_str());
847 markerAttribute->Look.Set(::fbxsdk::FbxMarker::ELook::eHardCross);
849 ::fbxsdk::FbxNode* markerNode = ::fbxsdk::FbxNode::Create(scene, markerName.c_str());
850 markerNode->SetNodeAttribute(markerAttribute);
855 markerNode->LclTranslation.Set(FbxVector4(0.0, 0.0, 0.0));
856 markersRootNode->AddChild(markerNode);
857 markerNodes.push_back(markerNode);
860 scene->GetRootNode()->AddChild(markersRootNode);
862 if (!timestamps.empty() && !timestamps[0].empty()) {
865 for (
size_t j = 0; j < markerNames.size(); ++j) {
866 if (timestamps[j].empty()) {
870 auto* markerNode = markerNodes.at(j);
872 markerNode->LclTranslation.GetCurveNode(animBaseLayer,
true);
873 ::fbxsdk::FbxAnimCurve* curveX =
874 markerNode->LclTranslation.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_X,
true);
875 ::fbxsdk::FbxAnimCurve* curveY =
876 markerNode->LclTranslation.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Y,
true);
877 ::fbxsdk::FbxAnimCurve* curveZ =
878 markerNode->LclTranslation.GetCurve(animBaseLayer, FBXSDK_CURVENODE_COMPONENT_Z,
true);
880 curveX->KeyModifyBegin();
881 curveY->KeyModifyBegin();
882 curveZ->KeyModifyBegin();
884 for (
size_t k = 0; k < timestamps[j].size(); ++k) {
886 j >= markerPositions.size() || k >= markerPositions[j].size(),
887 "Marker position index out of bounds: j={}, k={}",
890 ::fbxsdk::FbxTime time;
891 time.SetSecondDouble(timestamps[j][k]);
893 const auto& pos = markerPositions[j][k];
895 const auto keyIndexX = curveX->KeyAdd(time);
896 curveX->KeySet(keyIndexX, time,
static_cast<float>(pos.x()));
898 const auto keyIndexY = curveY->KeyAdd(time);
899 curveY->KeySet(keyIndexY, time,
static_cast<float>(pos.y()));
901 const auto keyIndexZ = curveZ->KeyAdd(time);
902 curveZ->KeySet(keyIndexZ, time,
static_cast<float>(pos.z()));
905 curveX->KeyModifyEnd();
906 curveY->KeyModifyEnd();
907 curveZ->KeyModifyEnd();
919 ::fbxsdk::FbxNode* node,
920 const std::string& namespacePrefix) {
921 if (namespacePrefix.empty() || node ==
nullptr) {
925 const std::string currentName = node->GetName();
926 const std::string newName = namespacePrefix + currentName;
927 node->SetName(newName.c_str());
929 for (
int i = 0; i < node->GetChildCount(); ++i) {
#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.
MatrixXf extractBlendShapeWeights(const Character &character, const MatrixXf &poses)
void addPhysicalProperties(const Character &character, const std::unordered_map< size_t, fbxsdk::FbxNode * > &jointToNodeMap)
void prependNamespaceToAllNodes(::fbxsdk::FbxNode *node, const std::string &namespacePrefix)
std::pair<::fbxsdk::FbxAnimStack *, ::fbxsdk::FbxAnimLayer * > getOrCreateAnimStackAndLayer(::fbxsdk::FbxScene *scene, const char *stackName)
constexpr const char * kMomentumMarkerProperty
void createAnimationCurves(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes, const MatrixXf &jointValues, const double framerate, const bool skipActiveJointParamCheck)
void setFrameRate(::fbxsdk::FbxScene *scene, const double framerate)
JointCurveSetup setupJointAnimCurves(const Character &character, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes, ::fbxsdk::FbxAnimLayer *animBaseLayer, const bool skipActiveJointParamCheck)
std::vector<::fbxsdk::FbxNode * > createMarkerNodes(::fbxsdk::FbxScene *scene, std::span< const std::vector< Marker > > markerSequence, const double framerate)
void saveSkinWeightsToFbx(const Character &character, ::fbxsdk::FbxScene *scene, ::fbxsdk::FbxMesh *mesh, const std::unordered_map< size_t, fbxsdk::FbxNode * > &jointToNodeMap)
void writeTextureUVIndicesToFbxMesh(const Mesh &mesh, ::fbxsdk::FbxMesh *lMesh, fbxsdk::FbxLayerElement::EType uvType)
::fbxsdk::FbxAxisSystem::EUpVector toFbx(const FbxUpVector upVector)
std::vector<::fbxsdk::FbxBlendShapeChannel * > saveBlendShapeGeometryToFbx(const BlendShapeBase &blendShape, ::fbxsdk::FbxScene *scene, ::fbxsdk::FbxMesh *mesh, const std::string &deformerName, const std::string &channelPrefix)
void createBlendShapeAnimationCurves(::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxBlendShapeChannel * > &channels, const MatrixXf &weights, const double framerate)
constexpr const char * kMomentumMarkersRootProperty
MatrixXf extractFaceExpressionWeights(const Character &character, const MatrixXf &poses)
void createLocatorNodes(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes)
float jointParamToFbx(float value, size_t curveOffset, const Joint &joint)
Convert a raw momentum joint parameter to the FBX-native value.
void createCollisionGeometryNodes(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes)
SkeletonNodeResult createSkeletonNodes(const Character &character, ::fbxsdk::FbxScene *scene)
MeshBlendShapeResult createMeshNode(const Character &character, ::fbxsdk::FbxScene *scene, ::fbxsdk::FbxNode *parentNode, const std::unordered_map< size_t, fbxsdk::FbxNode * > &jointToNodeMap, Permissive permissive, const std::string &meshName="body_mesh")
void writePolygonsToFbxMesh(const Mesh &mesh, ::fbxsdk::FbxMesh *lMesh)
void addMetaData(::fbxsdk::FbxNode *skeletonRootNode, const Character &character)
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
FbxFrontVector
Vector with origin at the screen pointing toward the camera.
Vector3< T > rotationMatrixToEulerXYZ(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 0, 1, 2, convention) or rotationMatrixToEuler(m,...
FbxCoordSystem
Specifies the third vector of the system.
constexpr T toDeg(T x=T(1)) noexcept
Converts the given angle x (in radians) to degrees.
Vector3< T > rotationMatrixToEulerZYX(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 2, 1, 0, convention) or rotationMatrixToEuler(m,...
@ Extrinsic
The extrinsic convention.
@ Intrinsic
The intrinsic convention.
FbxUpVector
Specifies which canonical axis represents up in the system (typically Y or Z).
constexpr size_t kParametersPerJoint
std::string jointPhysicalPropertiesToJsonString(const JointPhysicalProperties &jointProperties)
Serializes one joint's physical mass properties to its canonical on-disk JSON string.
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.
Vector3< float > Vector3f
MatrixX< float > MatrixXf
Skinning class that manages blend shape vectors/offsets.
const MatrixXf & getShapeVectors() const
const std::vector< std::string > & getShapeNames() const
Eigen::Index shapeSize() const
A character model with skeletal structure, mesh, and optional components.
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.
Mesh_u mesh
3D mesh representing the character's surface
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
std::string name
Character identifier.
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.
A struct containing the up, front vectors and coordinate system for FBX export.
FbxUpVector upVector
Default to the same orientations as FbxAxisSystem::eMayaYUp.
FbxFrontVector frontVector
FbxCoordSystem coordSystem
Vector3< T > translationOffset
Constant translation offset from the parent joint's origin to this joint's origin,...
std::vector< uint32_t > polyFaces
Packed polygon face vertex indices (all polygons concatenated back-to-back).
std::vector< Eigen::Vector3i > texcoord_faces
List of texture coordinate indices per face Maps each face to its corresponding texture coordinates.
std::vector< uint32_t > polyFaceSizes
Number of vertices in each polygon face.
std::vector< uint32_t > polyTexcoordFaces
Packed polygon face texture coordinate indices (same layout as polyFaces).
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
std::vector< size_t > animCurvesIndex
std::vector<::fbxsdk::FbxAnimCurve * > animCurves
std::vector<::fbxsdk::FbxBlendShapeChannel * > faceExprChannels
std::vector<::fbxsdk::FbxBlendShapeChannel * > blendShapeChannels
std::vector<::fbxsdk::FbxNode * > nodes
::fbxsdk::FbxNode * rootNode
std::unordered_map< size_t, fbxsdk::FbxNode * > jointToNodeMap