Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
fbx_io.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
13
14#ifdef MOMENTUM_WITH_FBX_SDK
22
23#include <gsl/gsl>
24
25#include <variant>
26#endif // MOMENTUM_WITH_FBX_SDK
27
28namespace momentum {
29
30#ifdef MOMENTUM_WITH_FBX_SDK
31
32namespace {
33
34using namespace fbx_internal; // NOLINT(google-build-using-namespace)
35
36void saveFbxCommon(
37 const filesystem::path& filename,
38 const Character& character,
39 const MatrixXf& jointValues,
40 const double framerate,
41 const bool saveMesh,
42 const bool skipActiveJointParamCheck,
43 const FbxCoordSystemInfo& coordSystemInfo,
44 Permissive permissive,
45 std::span<const std::vector<Marker>> markerSequence,
46 std::string_view fbxNamespace,
47 const MatrixXf& poses) {
48 // ---------------------------------------------
49 // initialize FBX SDK and prepare for export
50 // ---------------------------------------------
51 auto* manager = ::fbxsdk::FbxManager::Create();
52 // FBX SDK uses manual memory management. Use a scope guard so the manager — and the exporter,
53 // scene, and nodes it owns — are always destroyed, including when an exception is thrown mid-
54 // export (e.g. by addPhysicalProperties). Without it, a throw leaks the manager (flagged by
55 // ASAN).
56 const auto managerGuard = gsl::finally([manager]() { manager->Destroy(); });
57 auto* ios = ::fbxsdk::FbxIOSettings::Create(manager, IOSROOT);
58 manager->SetIOSettings(ios);
59
60 // Create an exporter.
61 ::fbxsdk::FbxExporter* lExporter = ::fbxsdk::FbxExporter::Create(manager, "");
62
63 // Declare the path and filename of the file containing the scene.
64 // In this case, we are assuming the file is in the same directory as the executable.
65 // Going through string() because on windows, wchar_t (native filesystem path) are different from
66 // char https://en.cppreference.com/w/cpp/language/types This avoids a build error on windows
67 // only.
68 std::string sFilename = filename.string();
69 const char* lFilename = sFilename.c_str();
70
71 // Initialize the exporter.
72 bool lExportStatus = lExporter->Initialize(lFilename, -1, manager->GetIOSettings());
73
75 !lExportStatus,
76 "Unable to initialize fbx exporter {}",
77 lExporter->GetStatus().GetErrorString());
78
79 // Normalize namespace: ensure it ends with ':' if not empty
80 std::string namespacePrefix(fbxNamespace);
81 if (!namespacePrefix.empty() && namespacePrefix.back() != ':') {
82 namespacePrefix += ":";
83 }
84
85 // ---------------------------------------------
86 // create the scene
87 // ---------------------------------------------
88 ::fbxsdk::FbxScene* scene = ::fbxsdk::FbxScene::Create(manager, "momentum_scene");
89 ::fbxsdk::FbxNode* root = scene->GetRootNode();
90 MT_THROW_IF(root == nullptr, "Unable to get root node from FBX scene");
91
92 // set the coordinate system
93 ::fbxsdk::FbxAxisSystem axis = toFbx(coordSystemInfo);
94 axis.ConvertScene(scene);
95
96 // Create skeleton hierarchy
97 auto skeletonResult = createSkeletonNodes(character, scene);
98 addMetaData(skeletonResult.rootNode, character);
99 addPhysicalProperties(character, skeletonResult.jointToNodeMap);
100 createLocatorNodes(character, scene, skeletonResult.nodes);
101 createCollisionGeometryNodes(character, scene, skeletonResult.nodes);
102
103 // Create mesh with blend shapes
104 MeshBlendShapeResult meshResult;
105 if (saveMesh && character.mesh != nullptr) {
106 meshResult = createMeshNode(character, scene, root, skeletonResult.jointToNodeMap, permissive);
107 }
108
109 // Add skeleton to scene root
110 if (!skeletonResult.nodes.empty()) {
111 root->AddChild(skeletonResult.rootNode);
112 }
113
114 // ---------------------------------------------
115 // create animation curves if we have motion
116 // ---------------------------------------------
117 if (jointValues.cols() != 0) {
118 if (jointValues.rows() == character.parameterTransform.numJointParameters()) {
120 character,
121 scene,
122 skeletonResult.nodes,
123 jointValues,
124 framerate,
125 skipActiveJointParamCheck);
126 } else {
127 MT_LOGE(
128 "Rows of joint values {} do not match joint parameter dimension {} so not saving any motion.",
129 jointValues.rows(),
130 character.parameterTransform.numJointParameters());
131 }
132 }
133
134 // ---------------------------------------------
135 // create marker nodes and animation
136 // ---------------------------------------------
137 if (!markerSequence.empty()) {
138 createMarkerNodes(scene, markerSequence, framerate);
139 }
140
141 // ---------------------------------------------
142 // create blend shape animation curves
143 // Auto-detect blend shapes from model parameters
144 // ---------------------------------------------
145 if (saveMesh) {
146 const MatrixXf blendShapeWeights = extractBlendShapeWeights(character, poses);
147 if (blendShapeWeights.cols() > 0 && !meshResult.blendShapeChannels.empty()) {
149 scene, meshResult.blendShapeChannels, blendShapeWeights, framerate);
150 }
151 const MatrixXf faceExpressionWeights = extractFaceExpressionWeights(character, poses);
152 if (faceExpressionWeights.cols() > 0 && !meshResult.faceExprChannels.empty()) {
154 scene, meshResult.faceExprChannels, faceExpressionWeights, framerate);
155 }
156 }
157
158 // ---------------------------------------------
159 // apply namespace prefix to all nodes
160 // ---------------------------------------------
161 if (!namespacePrefix.empty()) {
162 prependNamespaceToAllNodes(scene->GetRootNode(), namespacePrefix);
163 }
164
165 // ---------------------------------------------
166 // close the fbx exporter
167 // ---------------------------------------------
168
169 // finally export the scene; managerGuard destroys the exporter, scene, and manager (and
170 // everything they own) when this function returns or throws.
171 lExporter->Export(scene);
172}
173
174} // namespace
175
176#endif // MOMENTUM_WITH_FBX_SDK
177
179 const filesystem::path& inputPath,
180 KeepLocators keepLocators,
181 Permissive permissive,
182 LoadBlendShapes loadBlendShapes,
183 bool stripNamespaces) {
185 inputPath, keepLocators, permissive, loadBlendShapes, stripNamespaces);
186}
187
189 std::span<const std::byte> inputSpan,
190 KeepLocators keepLocators,
191 Permissive permissive,
192 LoadBlendShapes loadBlendShapes,
193 bool stripNamespaces) {
195 inputSpan, keepLocators, permissive, loadBlendShapes, stripNamespaces);
196}
197
198std::tuple<Character, std::vector<MatrixXf>, float> loadFbxCharacterWithMotion(
199 const filesystem::path& inputPath,
200 KeepLocators keepLocators,
201 Permissive permissive,
202 LoadBlendShapes loadBlendShapes,
203 bool stripNamespaces) {
205 inputPath, keepLocators, permissive, loadBlendShapes, stripNamespaces);
206}
207
208std::tuple<Character, std::vector<MatrixXf>, float> loadFbxCharacterWithMotion(
209 std::span<const std::byte> inputSpan,
210 KeepLocators keepLocators,
211 Permissive permissive,
212 LoadBlendShapes loadBlendShapes,
213 bool stripNamespaces) {
215 inputSpan, keepLocators, permissive, loadBlendShapes, stripNamespaces);
216}
217
218MarkerSequence loadFbxMarkerSequence(const filesystem::path& filename, bool stripNamespaces) {
219 return loadOpenFbxMarkerSequence(filename, stripNamespaces);
220}
221
222MarkerSequence loadFbxMarkerSequence(std::span<const std::byte> inputSpan, bool stripNamespaces) {
223 return loadOpenFbxMarkerSequence(inputSpan, stripNamespaces);
224}
225
226#ifdef MOMENTUM_WITH_FBX_SDK
227
228void saveFbx(
229 const filesystem::path& filename,
230 const Character& character,
231 const MatrixXf& poses,
232 const VectorXf& identity,
233 const double framerate,
234 std::span<const std::vector<Marker>> markerSequence,
235 const FileSaveOptions& options) {
236 CharacterParameters params;
237 if (identity.size() == character.parameterTransform.numJointParameters()) {
238 params.offsets = identity;
239 } else {
240 params.offsets = character.parameterTransform.bindPose();
241 }
242
243 CharacterState state;
244 MatrixXf jointValues;
245 if (poses.cols() > 0) {
246 params.pose = poses.col(0);
247 state.set(params, character, false, false, false);
248
249 jointValues.resize(state.skeletonState.jointParameters.v.size(), poses.cols());
250
251 jointValues.col(0) = state.skeletonState.jointParameters.v;
252
253 for (Eigen::Index f = 1; f < poses.cols(); f++) {
254 params.pose = poses.col(f);
255 state.set(params, character, false, false, false);
256 jointValues.col(f) = state.skeletonState.jointParameters.v;
257 }
258 }
259
260 saveFbxCommon(
261 filename,
262 character,
263 jointValues,
264 framerate,
265 options.mesh,
266 false,
267 options.coordSystemInfo,
268 options.permissive,
269 markerSequence,
270 options.fbxNamespace,
271 poses);
272}
273
275 const filesystem::path& filename,
276 const Character& character,
277 const MatrixXf& jointParams,
278 const double framerate,
279 std::span<const std::vector<Marker>> markerSequence,
280 const FileSaveOptions& options) {
281 saveFbxCommon(
282 filename,
283 character,
284 jointParams,
285 framerate,
286 options.mesh,
287 true,
288 options.coordSystemInfo,
289 options.permissive,
290 markerSequence,
291 options.fbxNamespace,
292 MatrixXf());
293}
294
296 const filesystem::path& filename,
297 const Character& character,
298 std::span<const SkeletonState> skeletonStates,
299 const double framerate,
300 std::span<const std::vector<Marker>> markerSequence,
301 const FileSaveOptions& options) {
302 const size_t nFrames = skeletonStates.size();
303 MatrixXf jointParams(character.parameterTransform.zero().v.size(), nFrames);
304 for (size_t iFrame = 0; iFrame < nFrames; ++iFrame) {
305 jointParams.col(iFrame) =
306 skeletonStateToJointParameters(skeletonStates[iFrame], character.skeleton).v;
307 }
308
309 saveFbxCommon(
310 filename,
311 character,
312 jointParams,
313 framerate,
314 options.mesh,
315 true,
316 options.coordSystemInfo,
317 options.permissive,
318 markerSequence,
319 options.fbxNamespace,
320 MatrixXf());
321}
322
323void saveFbxModel(
324 const filesystem::path& filename,
325 const Character& character,
326 const FileSaveOptions& options) {
327 saveFbx(filename, character, MatrixXf(), VectorXf(), 120.0, {}, options);
328}
329
330MatrixXf loadFbxBlendShapeWeights(const filesystem::path& filename) {
331 // Initialize FBX SDK
332 auto* manager = ::fbxsdk::FbxManager::Create();
333 auto* ios = ::fbxsdk::FbxIOSettings::Create(manager, IOSROOT);
334 manager->SetIOSettings(ios);
335
336 // RAII-like cleanup for FBX SDK objects
337 ::fbxsdk::FbxScene* scene = nullptr;
338 const auto cleanup = [&]() {
339 if (scene != nullptr) {
340 scene->Destroy();
341 }
342 manager->Destroy();
343 };
344
345 auto* importer = ::fbxsdk::FbxImporter::Create(manager, "");
346 const std::string sFilename = filename.string();
347 if (!importer->Initialize(sFilename.c_str(), -1, manager->GetIOSettings())) {
348 cleanup();
349 return {};
350 }
351
352 scene = ::fbxsdk::FbxScene::Create(manager, "scene");
353 importer->Import(scene);
354 importer->Destroy();
355
356 // Find the animation stack
357 if (scene->GetSrcObjectCount<::fbxsdk::FbxAnimStack>() == 0) {
358 cleanup();
359 return {};
360 }
361 auto* animStack = scene->GetSrcObject<::fbxsdk::FbxAnimStack>(0);
362 if (animStack->GetMemberCount<::fbxsdk::FbxAnimLayer>() == 0) {
363 cleanup();
364 return {};
365 }
366 auto* animLayer = animStack->GetMember<::fbxsdk::FbxAnimLayer>(0);
367
368 // Collect all blend shape channels from all meshes
369 std::vector<::fbxsdk::FbxBlendShapeChannel*> allChannels;
370 for (int iMesh = 0; iMesh < scene->GetSrcObjectCount<::fbxsdk::FbxMesh>(); ++iMesh) {
371 auto* mesh = scene->GetSrcObject<::fbxsdk::FbxMesh>(iMesh);
372 for (int iDeformer = 0; iDeformer < mesh->GetDeformerCount(::fbxsdk::FbxDeformer::eBlendShape);
373 ++iDeformer) {
374 auto* blendShape = static_cast<::fbxsdk::FbxBlendShape*>(
375 mesh->GetDeformer(iDeformer, ::fbxsdk::FbxDeformer::eBlendShape));
376 for (int iChannel = 0; iChannel < blendShape->GetBlendShapeChannelCount(); ++iChannel) {
377 allChannels.push_back(blendShape->GetBlendShapeChannel(iChannel));
378 }
379 }
380 }
381
382 if (allChannels.empty()) {
383 cleanup();
384 return {};
385 }
386
387 // Determine the number of frames from the first animated channel
388 Eigen::Index numFrames = 0;
389 for (auto* channel : allChannels) {
390 auto* curve = channel->DeformPercent.GetCurve(animLayer);
391 if (curve != nullptr) {
392 numFrames = std::max(numFrames, static_cast<Eigen::Index>(curve->KeyGetCount()));
393 }
394 }
395
396 if (numFrames == 0) {
397 cleanup();
398 return {};
399 }
400
401 // Read weights from animation curves
402 const auto numChannels = static_cast<Eigen::Index>(allChannels.size());
403 MatrixXf weights = MatrixXf::Zero(numChannels, numFrames);
404
405 for (Eigen::Index i = 0; i < numChannels; i++) {
406 auto* curve = allChannels[i]->DeformPercent.GetCurve(animLayer);
407 if (curve == nullptr) {
408 continue;
409 }
410
411 const int keyCount = curve->KeyGetCount();
412 for (int k = 0; k < keyCount && k < numFrames; k++) {
413 // FBX DeformPercent is in [0, 100], convert to [0, 1]
414 weights(i, k) = curve->KeyGetValue(k) / 100.0f;
415 }
416 }
417
418 cleanup();
419 return weights;
420}
421
422#else // !MOMENTUM_WITH_FBX_SDK
423
425 const filesystem::path& /* filename */,
426 const Character& /* character */,
427 const MatrixXf& /* poses */,
428 const VectorXf& /* identity */,
429 const double /* framerate */,
430 std::span<const std::vector<Marker>> /* markerSequence */,
431 const FileSaveOptions& /* options */) {
432 MT_THROW(
433 "FBX saving is not supported in OpenFBX-only mode. FBX loading is available via OpenFBX, but saving requires the full Autodesk FBX SDK.");
434}
435
437 const filesystem::path& /* filename */,
438 const Character& /* character */,
439 const MatrixXf& /* jointParams */,
440 const double /* framerate */,
441 std::span<const std::vector<Marker>> /* markerSequence */,
442 const FileSaveOptions& /* options */) {
443 MT_THROW(
444 "FBX saving is not supported in OpenFBX-only mode. FBX loading is available via OpenFBX, but saving requires the full Autodesk FBX SDK.");
445}
446
448 const filesystem::path& /* filename */,
449 const Character& /* character */,
450 std::span<const SkeletonState> /* skeletonStates */,
451 const double /* framerate */,
452 std::span<const std::vector<Marker>> /* markerSequence */,
453 const FileSaveOptions& /* options */) {
454 MT_THROW(
455 "FBX saving is not supported in OpenFBX-only mode. FBX loading is available via OpenFBX, but saving requires the full Autodesk FBX SDK.");
456}
457
459 const filesystem::path& /* filename */,
460 const Character& /* character */,
461 const FileSaveOptions& /* options */) {
462 MT_THROW(
463 "FBX saving is not supported in OpenFBX-only mode. FBX loading is available via OpenFBX, but saving requires the full Autodesk FBX SDK.");
464}
465
466MatrixXf loadFbxBlendShapeWeights(const filesystem::path& /* filename */) {
467 MT_THROW("Loading blend shape weights requires the full Autodesk FBX SDK.");
468}
469
470#endif // MOMENTUM_WITH_FBX_SDK
471
472} // namespace momentum
#define MT_THROW(...)
Throws a std::runtime_error with a formatted message.
Definition exception.h:31
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
#define MT_LOGE(...)
Definition log.h:181
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)
void createAnimationCurves(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes, const MatrixXf &jointValues, const double framerate, const bool skipActiveJointParamCheck)
std::vector<::fbxsdk::FbxNode * > createMarkerNodes(::fbxsdk::FbxScene *scene, std::span< const std::vector< Marker > > markerSequence, const double framerate)
::fbxsdk::FbxAxisSystem::EUpVector toFbx(const FbxUpVector upVector)
void createBlendShapeAnimationCurves(::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxBlendShapeChannel * > &channels, const MatrixXf &weights, const double framerate)
MatrixXf extractFaceExpressionWeights(const Character &character, const MatrixXf &poses)
void createLocatorNodes(const Character &character, ::fbxsdk::FbxScene *scene, const std::vector<::fbxsdk::FbxNode * > &skeletonNodes)
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 addMetaData(::fbxsdk::FbxNode *skeletonRootNode, const Character &character)
CharacterStateT< float > CharacterState
Definition fwd.h:92
void saveFbxWithJointParams(const filesystem::path &, const Character &, const MatrixXf &, const double, std::span< const std::vector< Marker > >, const FileSaveOptions &)
Save a character with animation using joint parameters directly.
Definition fbx_io.cpp:436
void saveFbxWithSkeletonStates(const filesystem::path &, const Character &, std::span< const SkeletonState >, const double, std::span< const std::vector< Marker > >, const FileSaveOptions &)
Save a character with animation using skeleton states directly.
Definition fbx_io.cpp:447
std::tuple< Character, std::vector< MatrixXf >, float > loadOpenFbxCharacterWithMotion(std::span< const std::byte > inputData, KeepLocators keepLocators, Permissive permissive, LoadBlendShapes loadBlendShapes, bool stripNamespaces)
MarkerSequence loadOpenFbxMarkerSequence(std::span< const std::byte > inputData, bool stripNamespaces)
Load a MarkerSequence from an in-memory FBX byte buffer.
void saveFbx(const filesystem::path &, const Character &, const MatrixXf &, const VectorXf &, const double, std::span< const std::vector< Marker > >, const FileSaveOptions &)
Save a character with animation to an FBX file.
Definition fbx_io.cpp:424
Character loadOpenFbxCharacter(const std::span< const std::byte > inputData, KeepLocators keepLocators, Permissive permissive, LoadBlendShapes loadBlendShapes, bool stripNamespaces)
Character loadFbxCharacter(const filesystem::path &inputPath, KeepLocators keepLocators, Permissive permissive, LoadBlendShapes loadBlendShapes, bool stripNamespaces)
Definition fbx_io.cpp:178
std::tuple< Character, std::vector< MatrixXf >, float > loadFbxCharacterWithMotion(const filesystem::path &inputPath, KeepLocators keepLocators, Permissive permissive, LoadBlendShapes loadBlendShapes, bool stripNamespaces)
Definition fbx_io.cpp:198
CharacterParametersT< float > CharacterParameters
Definition types.h:168
JointParametersT< T > skeletonStateToJointParameters(const SkeletonStateT< T > &state, const Skeleton &skeleton)
The "RespectingActiveParameters" variants use rotationMatrixToOneAxisEuler or rotationMatrixToTwoAxis...
MarkerSequence loadFbxMarkerSequence(const filesystem::path &filename, bool stripNamespaces)
Loads a MarkerSequence from an FBX file.
Definition fbx_io.cpp:218
LoadBlendShapes
Definition fbx_io.h:26
KeepLocators
Definition fbx_io.h:23
VectorX< float > VectorXf
Definition types.h:209
MatrixXf loadFbxBlendShapeWeights(const filesystem::path &)
Load per-frame blend shape animation weights from an FBX file.
Definition fbx_io.cpp:466
void saveFbxModel(const filesystem::path &, const Character &, const FileSaveOptions &)
Save a character model (skeleton and mesh) without animation.
Definition fbx_io.cpp:458
MatrixX< float > MatrixXf
Definition types.h:82
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
A struct containing the up, front vectors and coordinate system for FBX export.
Unified options for saving files in both FBX and GLTF formats.
All frames from a single motion capture sequence for one subject (actor).
Definition marker.h:37