Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
usd_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
20#include "momentum/common/log.h"
27#include "momentum/math/mesh.h"
28
29#include <nlohmann/json.hpp>
30
31#include <pxr/base/tf/diagnosticMgr.h>
32#include <pxr/base/tf/errorMark.h>
33#include <pxr/base/tf/staticTokens.h>
34#include <pxr/pxr.h>
35#include <pxr/usd/sdf/layer.h>
36#include <pxr/usd/sdf/valueTypeName.h>
37#include <pxr/usd/usd/primRange.h>
38#include <pxr/usd/usd/stage.h>
39#include <pxr/usd/usdGeom/scope.h>
40#include <pxr/usd/usdSkel/root.h>
41
42#include <tbb/global_control.h>
43
44// TBB version compatibility:
45// - TBB 2019 and older: uses task_scheduler_init.h
46// - TBB 2020.3 and newer: uses global_control.h only (task_scheduler_init is deprecated)
47// - TBB 2021 and newer: task_scheduler_init.h completely removed
48#ifdef TBB_INTERFACE_VERSION
49#if TBB_INTERFACE_VERSION < 12000 // TBB 2020.3 has interface version 12000
50#include <tbb/task_scheduler_init.h>
51#define MOMENTUM_USE_TBB_TASK_SCHEDULER_INIT 1
52#endif
53#else
54// Try to include the header and define if successful
55#if __has_include(<tbb/task_scheduler_init.h>)
56#include <tbb/task_scheduler_init.h>
57#define MOMENTUM_USE_TBB_TASK_SCHEDULER_INIT 1
58#endif
59#endif
60
61// Conditional include for internal Meta environment vs open source
62// In open source builds, this header won't exist and MOMENTUM_WITH_USD_PLUGIN_INIT will be
63// undefined
64#ifdef MOMENTUM_WITH_USD_PLUGIN_INIT
65#include <UsdPluginInit.h>
66#endif
67
68#include <atomic>
69#include <ctime>
70#include <fstream>
71#include <iostream>
72#include <memory>
73#include <mutex>
74#include <span>
75#include <thread>
76#include <unordered_set>
77#include <vector>
78
79// Import USD namespace
80PXR_NAMESPACE_USING_DIRECTIVE
81
83 _tokens,
84 ((momentumCharacterName,
85 "momentum:characterName"))((momentumParameterTransform, "momentum:parameterTransform"))(
86 (momentumParameterLimits,
87 "momentum:parameterLimits"))((momentumParameterSets, "momentum:parameterSets"))(
88 (momentumPoseConstraints,
89 "momentum:poseConstraints"))(PhysicalProperties)((momentumJoint, "momentum:joint"))(
90 (momentumPhysicalProperties, "momentum:physicalProperties")));
91
92namespace momentum {
93
94namespace {
95
96class ResolverWarningsSuppressor : public TfDiagnosticMgr::Delegate {
97 public:
98 void IssueError(TfError const& err) override {
99 const std::string& msg = err.GetCommentary();
100 if (msg.find("Failed to manufacture asset resolver") != std::string::npos) {
101 return;
102 }
103 std::cerr << "USD Error: " << msg << std::endl;
104 }
105
106 void IssueWarning(TfWarning const& warning) override {
107 const std::string& msg = warning.GetCommentary();
108 if (msg.find("Failed to manufacture asset resolver") != std::string::npos) {
109 return;
110 }
111 std::cerr << "USD Warning: " << msg << std::endl;
112 }
113
114 void IssueStatus(TfStatus const& status) override {
115 std::cerr << "USD Status: " << status.GetCommentary() << std::endl;
116 }
117
118 void IssueFatalError(TfCallContext const& /*context*/, std::string const& msg) override {
119 std::cerr << "USD Fatal Error: " << msg << std::endl;
120 }
121};
122
123std::mutex g_usdInitMutex;
124// Serializes all USD operations. USD has internal global state (SdfLayer registry,
125// ArResolver, TfDiagnosticMgr) that may not be fully thread-safe for concurrent
126// stage open/close. This mutex provides a simple correctness guarantee at the
127// cost of preventing concurrent USD I/O. If concurrent USD I/O is needed, this
128// should be revisited and thoroughly tested with independent stages.
129std::mutex g_usdOperationMutex;
130bool g_usdInitialized = false;
131std::unique_ptr<ResolverWarningsSuppressor> g_suppressor;
132#ifdef MOMENTUM_WITH_USD_PLUGIN_INIT
133std::unique_ptr<UsdPluginInit> g_usdPluginInit;
134#endif
135std::unique_ptr<tbb::global_control> g_tbbControl;
136
137// TBB compatibility variables for older versions
138#ifdef MOMENTUM_USE_TBB_TASK_SCHEDULER_INIT
139std::unique_ptr<tbb::task_scheduler_init> g_tbbTaskScheduler;
140#endif
141
142void initializeUsdWithSuppressedWarnings() {
143 std::lock_guard<std::mutex> lock(g_usdInitMutex);
144
145 if (g_usdInitialized) {
146 return;
147 }
148
149 // Initialize TBB with the appropriate method based on version
150#ifdef MOMENTUM_USE_TBB_TASK_SCHEDULER_INIT
151 // Use legacy task_scheduler_init for older TBB versions
152 g_tbbTaskScheduler = std::make_unique<tbb::task_scheduler_init>(1);
153#else
154 // Use modern global_control for newer TBB versions
155 g_tbbControl =
156 std::make_unique<tbb::global_control>(tbb::global_control::max_allowed_parallelism, 1);
157#endif
158
159 g_suppressor = std::make_unique<ResolverWarningsSuppressor>();
160 TfDiagnosticMgr::GetInstance().AddDelegate(g_suppressor.get());
161
162#ifdef MOMENTUM_WITH_USD_PLUGIN_INIT
163 // Internal Meta environment: Use UsdPluginInit for embedded plugins
164 auto tempDir = filesystem::temp_directory_path();
165
166 // Try a few fixed paths to avoid accumulating many plugin folders
167 std::vector<std::string> fixedPaths = {"usd_plugin", "usd_momentum_plugin"};
168
169 bool pluginDirCreated = false;
170 filesystem::path pluginDir;
171
172 for (const auto& pathName : fixedPaths) {
173 pluginDir = tempDir / pathName;
174 std::error_code ec;
175 // Use create_directory (not create_directories) to fail if directory exists
176 if (filesystem::create_directory(pluginDir, ec) && !ec) {
177 pluginDirCreated = true;
178 break;
179 }
180 }
181
182 if (pluginDirCreated) {
183 g_usdPluginInit = std::make_unique<UsdPluginInit>(pluginDir);
184 } else {
185 g_usdPluginInit = std::make_unique<UsdPluginInit>();
186 }
187#else
188 // Open source environment: USD is already initialized via standard discovery
189 // The pxr package config automatically handles plugin paths via PXR_PLUGINPATH_NAME
190 MT_LOGI("USD I/O initialized with system USD installation");
191#endif
192
193 g_usdInitialized = true;
194}
195
196void saveMomentumMetadata(const Character& character, const UsdPrim& skelRootPrim) {
197 // Save character name
198 if (!character.name.empty()) {
199 auto nameAttr =
200 skelRootPrim.CreateAttribute(_tokens->momentumCharacterName, SdfValueTypeNames->String);
201 nameAttr.Set(std::string(character.name));
202 }
203
204 // Save parameter transform as JSON
205 if (!character.parameterTransform.name.empty()) {
206 nlohmann::json ptJson;
207 parameterTransformToJson(character, ptJson);
208 auto ptAttr = skelRootPrim.CreateAttribute(
209 _tokens->momentumParameterTransform, SdfValueTypeNames->String);
210 ptAttr.Set(ptJson.dump());
211 }
212
213 // Save parameter limits as JSON
214 if (!character.parameterLimits.empty()) {
215 nlohmann::json limJson;
216 parameterLimitsToJson(character, limJson);
217 auto limAttr =
218 skelRootPrim.CreateAttribute(_tokens->momentumParameterLimits, SdfValueTypeNames->String);
219 limAttr.Set(limJson.dump());
220 }
221
222 // Save parameter sets as JSON
223 if (!character.parameterTransform.parameterSets.empty()) {
224 nlohmann::json setsJson;
225 parameterSetsToJson(character, setsJson);
226 auto setsAttr =
227 skelRootPrim.CreateAttribute(_tokens->momentumParameterSets, SdfValueTypeNames->String);
228 setsAttr.Set(setsJson.dump());
229 }
230
231 // Save pose constraints as JSON
232 if (!character.parameterTransform.poseConstraints.empty()) {
233 nlohmann::json pcJson;
234 poseConstraintsToJson(character, pcJson);
235 auto pcAttr =
236 skelRootPrim.CreateAttribute(_tokens->momentumPoseConstraints, SdfValueTypeNames->String);
237 pcAttr.Set(pcJson.dump());
238 }
239}
240
241void savePhysicalPropertiesToUsd(
242 const Character& character,
243 const UsdStageRefPtr& stage,
244 const SdfPath& skelRootPath) {
245 if (character.physicalProperties.empty()) {
246 return;
247 }
248
249 auto physicalPropertiesScope =
250 UsdGeomScope::Define(stage, skelRootPath.AppendChild(_tokens->PhysicalProperties));
252 !physicalPropertiesScope.GetPrim().IsValid(),
253 "Failed to define physical properties scope on USD stage");
254
255 std::unordered_set<size_t> seenJoints;
256 for (const auto& jointProperties : character.physicalProperties) {
257 const size_t jointIndex =
258 resolvePhysicalPropertiesJointIndex(jointProperties, character.skeleton);
259
261 jointIndex == kInvalidIndex || jointIndex >= character.skeleton.joints.size(),
262 "Physical properties entry references unknown joint '{}'",
263 jointProperties.jointName);
265 !seenJoints.insert(jointIndex).second,
266 "Multiple physical properties entries resolve to joint '{}' (index {})",
267 character.skeleton.joints.at(jointIndex).name,
268 jointIndex);
269
270 const std::string& jointName = character.skeleton.joints.at(jointIndex).name;
271 const std::string primName =
272 sanitizePrimName(jointName + "_physical_properties_" + std::to_string(jointIndex));
273 auto prim = stage->DefinePrim(physicalPropertiesScope.GetPath().AppendChild(TfToken(primName)));
275 !prim.IsValid(),
276 "Failed to define physical properties prim '{}' for joint '{}'",
277 primName,
278 jointName);
279
280 prim.CreateAttribute(_tokens->momentumJoint, SdfValueTypeNames->String).Set(jointName);
281 prim.CreateAttribute(_tokens->momentumPhysicalProperties, SdfValueTypeNames->String)
282 .Set(jointPhysicalPropertiesToJsonString(jointProperties));
283 }
284}
285
286void loadMomentumMetadata(Character& character, const UsdPrim& skelRootPrim) {
287 // Load character name
288 auto nameAttr = skelRootPrim.GetAttribute(_tokens->momentumCharacterName);
289 if (nameAttr) {
290 std::string name;
291 if (nameAttr.Get(&name)) {
292 character.name = name;
293 }
294 }
295
296 // Load parameter transform from JSON
297 auto ptAttr = skelRootPrim.GetAttribute(_tokens->momentumParameterTransform);
298 if (ptAttr) {
299 std::string ptStr;
300 if (ptAttr.Get(&ptStr)) {
301 try {
302 auto ptJson = nlohmann::json::parse(ptStr);
303 character.parameterTransform = parameterTransformFromJson(character, ptJson);
304 } catch (const nlohmann::json::exception& e) {
305 MT_LOGW("Failed to parse momentum:parameterTransform: {}", e.what());
306 }
307 }
308 }
309
310 // Load parameter limits from JSON
311 auto limAttr = skelRootPrim.GetAttribute(_tokens->momentumParameterLimits);
312 if (limAttr) {
313 std::string limStr;
314 if (limAttr.Get(&limStr)) {
315 try {
316 auto limJson = nlohmann::json::parse(limStr);
317 character.parameterLimits = parameterLimitsFromJson(character, limJson);
318 } catch (const nlohmann::json::exception& e) {
319 MT_LOGW("Failed to parse momentum:parameterLimits: {}", e.what());
320 }
321 }
322 }
323
324 // Load parameter sets from JSON
325 auto setsAttr = skelRootPrim.GetAttribute(_tokens->momentumParameterSets);
326 if (setsAttr) {
327 std::string setsStr;
328 if (setsAttr.Get(&setsStr)) {
329 try {
330 auto setsJson = nlohmann::json::parse(setsStr);
331 character.parameterTransform.parameterSets = parameterSetsFromJson(character, setsJson);
332 } catch (const nlohmann::json::exception& e) {
333 MT_LOGW("Failed to parse momentum:parameterSets: {}", e.what());
334 }
335 }
336 }
337
338 // Load pose constraints from JSON
339 auto pcAttr = skelRootPrim.GetAttribute(_tokens->momentumPoseConstraints);
340 if (pcAttr) {
341 std::string pcStr;
342 if (pcAttr.Get(&pcStr)) {
343 try {
344 auto pcJson = nlohmann::json::parse(pcStr);
345 character.parameterTransform.poseConstraints = poseConstraintsFromJson(character, pcJson);
346 } catch (const nlohmann::json::exception& e) {
347 MT_LOGW("Failed to parse momentum:poseConstraints: {}", e.what());
348 }
349 }
350 }
351}
352
353PhysicalProperties loadPhysicalPropertiesFromUsd(
354 const UsdStageRefPtr& stage,
355 const Skeleton& skeleton) {
356 PhysicalProperties result;
357
358 // Physical properties are authored under <SkelRoot>/PhysicalProperties (see
359 // savePhysicalPropertiesToUsd); resolve that scope and iterate only its children instead of
360 // scanning every prim on the stage.
361 UsdPrim physicalPropertiesScope;
362 for (const auto& prim : stage->Traverse()) {
363 if (prim.IsA<UsdSkelRoot>()) {
364 physicalPropertiesScope =
365 stage->GetPrimAtPath(prim.GetPath().AppendChild(_tokens->PhysicalProperties));
366 break;
367 }
368 }
369 if (!physicalPropertiesScope) {
370 return result;
371 }
372
373 for (const auto& prim : physicalPropertiesScope.GetChildren()) {
374 auto jointAttr = prim.GetAttribute(_tokens->momentumJoint);
375 auto physicalAttr = prim.GetAttribute(_tokens->momentumPhysicalProperties);
376 if (!jointAttr || !physicalAttr) {
377 continue;
378 }
379
380 std::string jointName;
381 std::string physicalStr;
382 if (!jointAttr.Get(&jointName) || !physicalAttr.Get(&physicalStr)) {
383 continue;
384 }
385
386 const size_t jointIndex = skeleton.getJointIdByName(jointName);
387 if (jointIndex == kInvalidIndex) {
388 MT_LOGW("Skipping USD physical properties for unknown joint '{}'", jointName);
389 continue;
390 }
391
392 if (auto jointProperties =
393 jointPhysicalPropertiesFromJsonString(physicalStr, jointName, jointIndex)) {
394 result.push_back(std::move(*jointProperties));
395 }
396 }
397
398 return result;
399}
400
401Character loadUsdCharacterFromStage(const UsdStageRefPtr& stage) {
402 Character character;
403
404 character.skeleton = loadSkeletonFromUsd(stage);
405
406 auto mesh = loadMeshFromUsd(stage);
407 character.mesh = std::make_unique<Mesh>(std::move(mesh));
408
409 if (!character.mesh->vertices.empty()) {
410 auto skinWeights = loadSkinWeightsFromUsd(stage, character.mesh->vertices.size());
411 character.skinWeights = std::make_unique<SkinWeights>(std::move(skinWeights));
412
413 auto blendShapes = loadBlendShapesFromUsd(stage, character.mesh->vertices.size());
414 if (blendShapes) {
415 character.blendShape = std::move(blendShapes);
416 }
417 }
418
419 if (!character.skeleton.joints.empty()) {
420 const size_t numJoints = character.skeleton.joints.size();
421 const size_t numJointParams = numJoints * kParametersPerJoint;
422
423 character.parameterTransform = ParameterTransform::empty(numJointParams);
424
425 character.parameterTransform.name.reserve(numJointParams);
426 for (const auto& joint : character.skeleton.joints) {
427 for (const auto& paramName : kJointParameterNames) {
428 character.parameterTransform.name.push_back(joint.name + "_" + paramName);
429 }
430 }
431
432 std::vector<Eigen::Triplet<float>> triplets;
433 triplets.reserve(numJointParams);
434 for (size_t i = 0; i < numJointParams; ++i) {
435 triplets.emplace_back(i, i, 1.0f);
436 }
437
438 character.parameterTransform.transform.resize(numJointParams, numJointParams);
439 character.parameterTransform.transform.setFromTriplets(triplets.begin(), triplets.end());
440
441 character.parameterTransform.activeJointParams = VectorX<bool>::Constant(numJointParams, true);
442 }
443
444 character.resetJointMap();
445 character.initInverseBindPose();
446
447 // Load collision geometry and locators
448 auto collision = loadCollisionGeometryFromUsd(stage, character.skeleton);
449 if (!collision.empty()) {
450 character.collision = std::make_unique<CollisionGeometry>(std::move(collision));
451 }
452
453 character.locators = loadLocatorsFromUsd(stage, character.skeleton);
454 character.physicalProperties = loadPhysicalPropertiesFromUsd(stage, character.skeleton);
455
456 // Load momentum-specific metadata from SkelRoot prim
457 for (const auto& prim : stage->Traverse()) {
458 if (prim.IsA<UsdSkelRoot>()) {
459 loadMomentumMetadata(character, prim);
460 break;
461 }
462 }
463
464 return character;
465}
466
468struct TempFileGuard {
469 filesystem::path path;
470 explicit TempFileGuard(filesystem::path p) : path(std::move(p)) {}
471 ~TempFileGuard() {
472 if (!path.empty()) {
473 std::error_code ec;
474 filesystem::remove(path, ec);
475 }
476 }
477 TempFileGuard(const TempFileGuard&) = delete;
478 TempFileGuard& operator=(const TempFileGuard&) = delete;
479 TempFileGuard(TempFileGuard&& other) noexcept : path(std::move(other.path)) {
480 other.path.clear();
481 }
482 TempFileGuard& operator=(TempFileGuard&&) = delete;
483};
484
487std::pair<UsdStageRefPtr, TempFileGuard> openStageFromBuffer(std::span<const std::byte> inputSpan) {
488 static std::atomic<uint64_t> tempFileCounter{0};
489 auto tempDir = filesystem::temp_directory_path();
490 auto tempPath = tempDir /
491 ("momentum_usd_" + std::to_string(std::hash<std::thread::id>{}(std::this_thread::get_id())) +
492 "_" + std::to_string(std::time(nullptr)) + "_" +
493 std::to_string(tempFileCounter.fetch_add(1, std::memory_order_relaxed)) + ".usd");
494
495 TempFileGuard tempGuard(tempPath);
496
497 {
498 std::ofstream tempFile(tempPath, std::ios::binary);
499 MT_THROW_IF(!tempFile.is_open(), "Failed to create temporary file: {}", tempPath.string());
500 tempFile.write(reinterpret_cast<const char*>(inputSpan.data()), inputSpan.size());
501 MT_THROW_IF(!tempFile.good(), "Failed to write to temporary file: {}", tempPath.string());
502 }
503
504 auto stage = UsdStage::Open(tempPath.string());
505 MT_THROW_IF(!stage, "Failed to open USD stage from buffer");
506
507 return {stage, std::move(tempGuard)};
508}
509
510std::tuple<Character, MotionParameters, IdentityParameters, float>
511loadUsdCharacterWithMotionFromStage(const UsdStageRefPtr& stage) {
512 auto character = loadUsdCharacterFromStage(stage);
513
514 MotionParameters motion;
515 IdentityParameters identity;
516 float fps = 120.0f;
517
518 for (const auto& prim : stage->Traverse()) {
519 if (prim.IsA<UsdSkelRoot>()) {
520 std::tie(motion, identity, fps) = loadMotionFromUsd(prim);
521 break;
522 }
523 }
524
525 return {std::move(character), std::move(motion), std::move(identity), fps};
526}
527
528struct UsdSaveContext {
529 UsdStageRefPtr stage;
530 UsdSkelRoot skelRoot;
531 UsdSkelSkeleton skeleton;
532};
533
534// Populates a USD stage with SkelRoot, Skeleton, and Mesh prims, and saves
535// the common character components (skeleton, mesh, skin weights, blend shapes,
536// collision geometry, locators) according to the provided options.
537UsdSaveContext createUsdSaveContextFromStage(
538 const UsdStageRefPtr& stage,
539 const Character& character,
540 const FileSaveOptions& options) {
541 auto skelRoot = UsdSkelRoot::Define(stage, SdfPath("/SkelRoot"));
542 MT_THROW_IF(!skelRoot.GetPrim().IsValid(), "Failed to define SkelRoot prim on USD stage");
543 auto skeleton = UsdSkelSkeleton::Define(stage, SdfPath("/SkelRoot/Skeleton"));
544 MT_THROW_IF(!skeleton.GetPrim().IsValid(), "Failed to define Skeleton prim on USD stage");
545
546 saveSkeletonToUsd(character.skeleton, skeleton);
547
548 if (options.mesh) {
549 auto mesh = UsdGeomMesh::Define(stage, SdfPath("/SkelRoot/Mesh"));
550 MT_THROW_IF(!mesh.GetPrim().IsValid(), "Failed to define Mesh prim on USD stage");
551
552 if (character.mesh) {
553 saveMeshToUsd(*character.mesh, mesh);
554 }
555
556 if (character.skinWeights) {
557 saveSkinWeightsToUsd(*character.skinWeights, mesh, skeleton);
558 }
559
560 if (options.blendShapes && character.blendShape) {
561 saveBlendShapesToUsd(*character.blendShape, mesh);
562 }
563 }
564
565 if (options.collisions && character.collision) {
567 *character.collision, character.skeleton, stage, SdfPath("/SkelRoot"));
568 }
569
570 if (options.locators && !character.locators.empty()) {
571 saveLocatorsToUsd(character.locators, character.skeleton, stage, SdfPath("/SkelRoot"));
572 }
573
574 return {stage, skelRoot, skeleton};
575}
576
577// Creates a new USD stage from a file path and populates it with common character components.
578UsdSaveContext createUsdSaveContext(
579 const filesystem::path& filename,
580 const Character& character,
581 const FileSaveOptions& options) {
582 auto stage = UsdStage::CreateNew(filename.string());
583 MT_THROW_IF(!stage, "Failed to create USD stage: {}", filename.string());
584 return createUsdSaveContextFromStage(stage, character, options);
585}
586
587void finalizeUsdSave(const UsdSaveContext& ctx, const Character& character) {
588 saveMomentumMetadata(character, ctx.skelRoot.GetPrim());
589 savePhysicalPropertiesToUsd(character, ctx.stage, ctx.skelRoot.GetPath());
590 ctx.stage->GetRootLayer()->Save();
591}
592
593} // namespace
594
595Character loadUsdCharacter(const filesystem::path& inputPath) {
596 initializeUsdWithSuppressedWarnings();
597 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
598
599 auto stage = UsdStage::Open(inputPath.string());
600 MT_THROW_IF(!stage, "Failed to open USD stage: {}", inputPath.string());
601
602 return loadUsdCharacterFromStage(stage);
603}
604
605Character loadUsdCharacter(std::span<const std::byte> inputSpan) {
606 initializeUsdWithSuppressedWarnings();
607 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
608
609 auto [stage, tempGuard] = openStageFromBuffer(inputSpan);
610 return loadUsdCharacterFromStage(stage);
611}
612
614 const filesystem::path& filename,
615 const Character& character,
616 const FileSaveOptions& options) {
617 initializeUsdWithSuppressedWarnings();
618 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
619
620 auto ctx = createUsdSaveContext(filename, character, options);
621 finalizeUsdSave(ctx, character);
622}
623
624std::tuple<Character, std::vector<SkeletonState>, std::vector<float>>
625loadUsdCharacterWithSkeletonStates(const filesystem::path& inputPath) {
626 initializeUsdWithSuppressedWarnings();
627 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
628
629 auto stage = UsdStage::Open(inputPath.string());
630 MT_THROW_IF(!stage, "Failed to open USD stage: {}", inputPath.string());
631
632 auto character = loadUsdCharacterFromStage(stage);
633 auto [states, frameTimes] = loadSkeletonStatesFromUsd(stage, character.skeleton);
634
635 return {std::move(character), std::move(states), std::move(frameTimes)};
636}
637
638std::tuple<Character, std::vector<SkeletonState>, std::vector<float>>
639loadUsdCharacterWithSkeletonStates(std::span<const std::byte> inputSpan) {
640 initializeUsdWithSuppressedWarnings();
641 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
642
643 auto [stage, tempGuard] = openStageFromBuffer(inputSpan);
644
645 auto character = loadUsdCharacterFromStage(stage);
646 auto [states, frameTimes] = loadSkeletonStatesFromUsd(stage, character.skeleton);
647
648 return {std::move(character), std::move(states), std::move(frameTimes)};
649}
650
652 const filesystem::path& filename,
653 const Character& character,
654 float fps,
655 std::span<const SkeletonState> skeletonStates,
656 std::span<const std::vector<Marker>> markerSequence,
657 const FileSaveOptions& options) {
658 initializeUsdWithSuppressedWarnings();
659 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
660
661 auto ctx = createUsdSaveContext(filename, character, options);
662
663 if (!skeletonStates.empty()) {
664 saveSkeletonStatesToUsd(ctx.stage, ctx.skeleton, character.skeleton, skeletonStates, fps);
665 }
666
667 if (!markerSequence.empty()) {
668 saveMarkerSequenceToUsd(ctx.stage, SdfPath("/SkelRoot"), fps, markerSequence);
669 }
670
671 finalizeUsdSave(ctx, character);
672}
673
675 const filesystem::path& filename,
676 const Character& character,
677 float fps,
678 const MotionParameters& motion,
679 const IdentityParameters& offsets,
680 std::span<const std::vector<Marker>> markerSequence,
681 const FileSaveOptions& options) {
682 initializeUsdWithSuppressedWarnings();
683 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
684
685 auto ctx = createUsdSaveContext(filename, character, options);
686
687 const auto& [paramNames, poses] = motion;
688 if (!paramNames.empty() && poses.cols() > 0) {
689 saveMotionToUsd(ctx.skelRoot.GetPrim(), fps, motion, offsets);
690
691 const auto numFrames = poses.cols();
692 std::vector<SkeletonState> skeletonStates;
693 skeletonStates.reserve(numFrames);
694
695 for (Eigen::Index f = 0; f < numFrames; ++f) {
696 JointParameters jointParams =
697 character.parameterTransform.apply(ModelParameters(poses.col(f)));
698 skeletonStates.emplace_back(jointParams, character.skeleton, false);
699 }
700
701 saveSkeletonStatesToUsd(ctx.stage, ctx.skeleton, character.skeleton, skeletonStates, fps);
702 }
703
704 if (!markerSequence.empty()) {
705 saveMarkerSequenceToUsd(ctx.stage, SdfPath("/SkelRoot"), fps, markerSequence);
706 }
707
708 finalizeUsdSave(ctx, character);
709}
710
711std::tuple<Character, MotionParameters, IdentityParameters, float> loadUsdCharacterWithMotion(
712 const filesystem::path& inputPath) {
713 initializeUsdWithSuppressedWarnings();
714 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
715
716 auto stage = UsdStage::Open(inputPath.string());
717 MT_THROW_IF(!stage, "Failed to open USD stage: {}", inputPath.string());
718
719 return loadUsdCharacterWithMotionFromStage(stage);
720}
721
722std::tuple<Character, MotionParameters, IdentityParameters, float> loadUsdCharacterWithMotion(
723 std::span<const std::byte> inputSpan) {
724 initializeUsdWithSuppressedWarnings();
725 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
726
727 auto [stage, tempGuard] = openStageFromBuffer(inputSpan);
728
729 return loadUsdCharacterWithMotionFromStage(stage);
730}
731
732namespace {
733
734std::tuple<Character, MatrixXf, ModelParameters, float> applyModelParameterScalesToUsdMotion(
735 std::tuple<Character, MotionParameters, IdentityParameters, float>&& loaded) {
736 auto& [character, motionParams, identityParams, fps] = loaded;
737 auto& motion = std::get<1>(motionParams);
738 const auto& jointIdentity = std::get<1>(identityParams);
739
741 motion.rows() != character.parameterTransform.numAllModelParameters(),
742 "Mismatch between character and motion; character has {} model parameters while motion has {}.",
743 character.parameterTransform.numAllModelParameters(),
744 motion.rows());
745
746 auto modelIdentity =
747 applyModelParameterScales(character.parameterTransform, motion, jointIdentity);
748 return {std::move(character), std::move(motion), std::move(modelIdentity), fps};
749}
750
751} // namespace
752
753std::tuple<Character, MatrixXf, ModelParameters, float>
754loadUsdCharacterWithMotionModelParameterScales(const filesystem::path& inputPath) {
755 return applyModelParameterScalesToUsdMotion(loadUsdCharacterWithMotion(inputPath));
756}
757
758std::tuple<Character, MatrixXf, ModelParameters, float>
759loadUsdCharacterWithMotionModelParameterScales(std::span<const std::byte> inputSpan) {
760 return applyModelParameterScalesToUsdMotion(loadUsdCharacterWithMotion(inputSpan));
761}
762
763MarkerSequence loadUsdMarkerSequence(const filesystem::path& inputPath) {
764 initializeUsdWithSuppressedWarnings();
765 std::lock_guard<std::mutex> lock(g_usdOperationMutex);
766
767 auto stage = UsdStage::Open(inputPath.string());
768 MT_THROW_IF(!stage, "Failed to open USD stage: {}", inputPath.string());
769
770 return loadMarkerSequenceFromUsd(stage);
771}
772
773} // namespace momentum
#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_LOGI(...)
Definition log.h:179
#define MT_LOGW(...)
Definition log.h:180
Skeleton loadSkeletonFromUsd(const UsdStageRefPtr &stage)
Load a skeleton from a USD stage.
ParameterLimits parameterLimitsFromJson(const Character &character, const nlohmann::json &j)
void saveMeshToUsd(const Mesh &mesh, UsdGeomMesh &meshPrim)
Save a mesh to a USD stage.
SkeletonT< float > Skeleton
Definition fwd.h:263
std::tuple< std::vector< std::string >, JointParameters > IdentityParameters
A tuple of skeleton joint names and identity parameters.
Definition types.h:179
std::shared_ptr< BlendShape > loadBlendShapesFromUsd(const UsdStageRefPtr &stage, size_t numVertices)
Load blend shapes from a USD stage.
std::tuple< Character, MatrixXf, ModelParameters, float > loadUsdCharacterWithMotionModelParameterScales(const filesystem::path &inputPath)
Load a USD character with motion and apply scale parameters to the motion.
Definition usd_io.cpp:754
void saveUsdCharacter(const filesystem::path &filename, const Character &character, float fps, std::span< const SkeletonState > skeletonStates, std::span< const std::vector< Marker > > markerSequence, const FileSaveOptions &options)
Save a character with skeleton state animation to a USD file.
Definition usd_io.cpp:651
void saveSkeletonToUsd(const Skeleton &skeleton, UsdSkelSkeleton &skelPrim)
Save a skeleton to a USD stage.
ModelParameters applyModelParameterScales(const ParameterTransform &parameterTransform, MatrixXf &motion, const JointParameters &jointIdentity)
Apply model parameter scale conversion to motion data.
std::tuple< Character, std::vector< SkeletonState >, std::vector< float > > loadUsdCharacterWithSkeletonStates(const filesystem::path &inputPath)
Load a USD character with skeleton states from a local file path.
Definition usd_io.cpp:625
void saveUsd(const filesystem::path &filename, const Character &character, const FileSaveOptions &options)
Save a character to a USD file.
Definition usd_io.cpp:613
void saveBlendShapesToUsd(const BlendShape &blendShape, UsdGeomMesh &meshPrim)
Save blend shapes to a USD stage.
void saveCollisionGeometryToUsd(const CollisionGeometry &collision, const Skeleton &skeleton, const UsdStageRefPtr &stage, const SdfPath &skelRootPath)
Save collision geometry as child prims under the skeleton.
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.
Definition types.h:173
std::string sanitizePrimName(const std::string &name)
Sanitize a string for use as a USD SDF prim name.
Definition usd_utils.cpp:14
void saveSkeletonStatesToUsd(const UsdStageRefPtr &stage, UsdSkelSkeleton &skelPrim, const Skeleton &skeleton, std::span< const SkeletonState > skeletonStates, float fps)
Save skeleton states as a UsdSkelAnimation on the stage.
std::tuple< Character, MotionParameters, IdentityParameters, float > loadUsdCharacterWithMotion(const filesystem::path &inputPath)
Load a USD character with model-parameter motion from a local file path.
Definition usd_io.cpp:711
constexpr std::array< const char *, kParametersPerJoint > kJointParameterNames
Definition types.h:24
LocatorList loadLocatorsFromUsd(const UsdStageRefPtr &stage, const Skeleton &skeleton)
Load locators from child prims.
std::optional< JointPhysicalProperties > jointPhysicalPropertiesFromJsonString(const std::string &json, const std::string &jointName, const size_t jointIndex)
Parses one joint's physical mass properties from its canonical on-disk JSON string.
void saveUsdCharacterWithMotion(const filesystem::path &filename, const Character &character, float fps, const MotionParameters &motion, const IdentityParameters &offsets, std::span< const std::vector< Marker > > markerSequence, const FileSaveOptions &options)
Save a character with model-parameter motion to a USD file.
Definition usd_io.cpp:674
std::vector< JointPhysicalProperties > PhysicalProperties
Optional physical mass properties for a character.
Definition joint.h:114
Character loadUsdCharacter(const filesystem::path &inputPath)
Load a USD character from a local file path.
Definition usd_io.cpp:595
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
JointParametersT< float > JointParameters
Definition types.h:135
void parameterSetsToJson(const Character &character, nlohmann::json &j)
MarkerSequence loadUsdMarkerSequence(const filesystem::path &inputPath)
Load a marker sequence from a USD file.
Definition usd_io.cpp:763
void poseConstraintsToJson(const Character &character, nlohmann::json &j)
void saveMotionToUsd(const UsdPrim &prim, float fps, const MotionParameters &motion, const IdentityParameters &offsets)
Save model-parameter motion as custom attributes on a USD prim.
constexpr size_t kParametersPerJoint
Definition types.h:21
void saveMarkerSequenceToUsd(const UsdStageRefPtr &stage, const SdfPath &skelRootPath, float fps, std::span< const std::vector< Marker > > markerSequence)
Save marker sequence as animated Xform prims under a Markers scope.
ParameterTransform parameterTransformFromJson(const Character &character, const nlohmann::json &j)
std::string jointPhysicalPropertiesToJsonString(const JointPhysicalProperties &jointProperties)
Serializes one joint's physical mass properties to its canonical on-disk JSON string.
std::tuple< MotionParameters, IdentityParameters, float > loadMotionFromUsd(const UsdPrim &prim)
Load model-parameter motion from custom attributes on a USD prim.
void saveLocatorsToUsd(const LocatorList &locators, const Skeleton &skeleton, const UsdStageRefPtr &stage, const SdfPath &skelRootPath)
Save locators as child prims under the skeleton.
SkinWeights loadSkinWeightsFromUsd(const UsdStageRefPtr &stage, size_t numVertices)
Load skin weights from a USD stage.
void parameterTransformToJson(const Character &character, nlohmann::json &j)
MarkerSequence loadMarkerSequenceFromUsd(const UsdStageRefPtr &stage)
Load marker sequence from animated Xform prims.
ModelParametersT< float > ModelParameters
Definition types.h:105
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.
ParameterSets parameterSetsFromJson(const Character &character, const nlohmann::json &j)
std::tuple< std::vector< SkeletonState >, std::vector< float > > loadSkeletonStatesFromUsd(const UsdStageRefPtr &stage, const Skeleton &skeleton)
Load skeleton states from a USD stage.
CollisionGeometry loadCollisionGeometryFromUsd(const UsdStageRefPtr &stage, const Skeleton &skeleton)
Load collision geometry from child prims.
void saveSkinWeightsToUsd(const SkinWeights &skinWeights, UsdGeomMesh &meshPrim, const UsdSkelSkeleton &skelPrim)
Save skin weights to a USD stage.
void parameterLimitsToJson(const Character &character, nlohmann::json &j)
PoseConstraints poseConstraintsFromJson(const Character &character, const nlohmann::json &j)
Mesh loadMeshFromUsd(const UsdStageRefPtr &stage)
Load a mesh from a USD stage.
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
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
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.
PXR_NAMESPACE_USING_DIRECTIVE TF_DEFINE_PRIVATE_TOKENS(_tokens,((momentumCharacterName, "momentum:characterName"))((momentumParameterTransform, "momentum:parameterTransform"))((momentumParameterLimits, "momentum:parameterLimits"))((momentumParameterSets, "momentum:parameterSets"))((momentumPoseConstraints, "momentum:poseConstraints"))(PhysicalProperties)((momentumJoint, "momentum:joint"))((momentumPhysicalProperties, "momentum:physicalProperties")))