34#include <unordered_map>
41nlohmann::json& addMomentumExtension(nlohmann::json& extensionsAndExtras) {
42 if (extensionsAndExtras.count(
"extensions") == 0 ||
43 extensionsAndExtras[
"extensions"].count(
"FB_momentum") == 0) {
44 extensionsAndExtras[
"extensions"][
"FB_momentum"] = nlohmann::json::object();
46 return extensionsAndExtras[
"extensions"][
"FB_momentum"];
49void initDefaultScene(fx::gltf::Document& model) {
51 model.scenes.resize(1);
54[[nodiscard]] fx::gltf::Scene& getDefaultScene(fx::gltf::Document& model) {
55 MT_CHECK(model.scenes.size() == 1,
"{}", model.scenes.size());
56 return model.scenes.at(0);
59fx::gltf::Animation& addMomentumAnimationToModel(
60 fx::gltf::Document& model,
61 const std::string& nameIn =
"default") {
62 auto animationIter = std::find_if(
63 model.animations.begin(), model.animations.end(), [nameIn](
const fx::gltf::Animation& anim) {
64 return nameIn == anim.name;
66 if (animationIter == model.animations.end()) {
67 model.animations.emplace_back();
68 auto& animation = model.animations.at(model.animations.size() - 1);
69 animation.name = nameIn;
72 return *animationIter;
76 fx::gltf::Document& model,
77 const uint32_t accessorId,
78 fx::gltf::BufferView::TargetType targetType) {
79 MT_CHECK(accessorId < model.accessors.size());
80 const auto accessor = model.accessors[accessorId];
81 MT_CHECK(accessor.bufferView < model.bufferViews.size());
83 auto& view = model.bufferViews[accessor.bufferView];
84 view.target = targetType;
90size_t addMeshToModel(fx::gltf::Document& model,
const Mesh& mesh,
const bool addColor =
false) {
92 return std::numeric_limits<size_t>::max();
95 model.meshes.emplace_back();
96 auto& m = model.meshes.back();
97 m.primitives.emplace_back();
98 auto& prim = m.primitives.back();
101 if ((!mesh.
faces.empty()) && (mesh.
faces[0].size() > 0)) {
102 prim.mode = fx::gltf::Primitive::Mode::Triangles;
103 const std::span<const int32_t> faces(&mesh.
faces[0][0], mesh.
faces.size() * 3);
105 setBufferView(model, prim.indices, fx::gltf::BufferView::TargetType::ElementArrayBuffer);
107 prim.mode = fx::gltf::Primitive::Mode::Points;
111 std::vector<Vector3f> verts = mesh.
vertices;
113 MT_CHECK((!verts.empty()) && (verts[0].size() > 0));
115 setBufferView(model, prim.attributes[
"POSITION"], fx::gltf::BufferView::TargetType::ArrayBuffer);
119 for (
const auto& v : verts) {
122 for (
size_t d = 0; d < 3; d++) {
123 model.accessors.at(prim.attributes[
"POSITION"]).min.emplace_back(bbox.min()[d]);
124 model.accessors.at(prim.attributes[
"POSITION"]).max.emplace_back(bbox.max()[d]);
130 setBufferView(model, prim.attributes[
"NORMAL"], fx::gltf::BufferView::TargetType::ArrayBuffer);
137 auto& def = addMomentumExtension(prim.extensionsAndExtras);
139 setBufferView(model, def[
"texcoords"], fx::gltf::BufferView::TargetType::ArrayBuffer);
142 const std::span<const int32_t> texFaces(
145 setBufferView(model, def[
"texfaces"], fx::gltf::BufferView::TargetType::ArrayBuffer);
150 "Skipping vertex colors because color count ({}) does not match vertex count ({})",
155 prim.attributes[
"COLOR_0"] =
157 setBufferView(model, prim.attributes[
"COLOR_0"], fx::gltf::BufferView::TargetType::ArrayBuffer);
160 return model.meshes.size() - 1;
163void addMorphTargetsToModel(
164 fx::gltf::Document& model,
169 MT_LOGW(
"No mesh is saved in the file when adding blendshapes");
174 auto& prim = model.meshes.at(model.nodes.at(meshIndex).mesh).primitives.at(0);
175 size_t numShapesAdded = prim.targets.size();
176 if (numShapesAdded >= numShapes) {
180 auto& def = addMomentumExtension(prim.extensionsAndExtras);
184 for (
size_t iShape = numShapesAdded; iShape < numShapes; ++iShape) {
186 VectorXf deltas = shapeVecs.col(iShape);
188 prim.targets.emplace_back();
189 auto& attr = prim.targets.back();
191 std::span<const Eigen::Vector3f>
span(
192 reinterpret_cast<Eigen::Vector3f*
>(deltas.data()),
static_cast<size_t>(deltas.size() / 3));
194 setBufferView(model, attr[
"POSITION"], fx::gltf::BufferView::TargetType::ArrayBuffer);
201 for (
size_t d = 0; d < 3; ++d) {
202 model.accessors.at(attr[
"POSITION"]).min.emplace_back(bbox.min()[d]);
203 model.accessors.at(attr[
"POSITION"]).max.emplace_back(bbox.max()[d]);
208void addMorphWeightsToModel(
209 fx::gltf::Document& model,
213 const size_t meshIndex,
215 const std::string& motionName =
"default") {
216 const size_t numFrames = modelParams.cols();
217 if (numFrames == 0) {
223 if (numWeights == 0) {
229 meshIndex >= model.nodes.size() || model.nodes[meshIndex].mesh < 0 ||
230 static_cast<size_t>(model.nodes[meshIndex].mesh) >= model.meshes.size(),
231 "Invalid mesh index for blendshape animation (meshIndex: {}, nodes size: {})",
236 if (model.meshes[model.nodes[meshIndex].mesh].primitives.size() != 1 ||
237 model.meshes[model.nodes[meshIndex].mesh].primitives.at(0).targets.size() != numWeights) {
238 MT_LOGW(
"No valid mesh to add blendshape animation for");
243 std::vector<float> timestamps(numFrames, 0);
244 bool useChannel =
false;
246 MatrixXf weights(numWeights, numFrames);
248 for (
size_t iFrame = 0; iFrame < numFrames; ++iFrame) {
249 const VectorXf& pose = modelParams.col(iFrame);
251 if (w.norm() > 1e-5f) {
254 weights.col(iFrame) = w;
255 timestamps[iFrame] =
static_cast<float>(iFrame) / fps;
262 auto& animation = addMomentumAnimationToModel(model, motionName);
264 if (!timestamps.empty() && !model.accessors.empty() && timestampIdx < model.accessors.size()) {
265 model.accessors[timestampIdx].min.emplace_back(timestamps.front());
266 model.accessors[timestampIdx].max.emplace_back(timestamps.back());
269 animation.channels.emplace_back();
270 auto& channel = animation.channels.back();
274 std::span<const float>(weights.data(), numWeights * numFrames),
277 channel.target.node =
static_cast<int32_t
>(meshIndex);
278 channel.target.path =
"weights";
305 cube.
colors = std::vector<Eigen::Vector3b>(8, color);
311void addActorAnimationToModel(
312 fx::gltf::Document& model,
314 std::span<
const std::vector<momentum::Marker>> markerSequence,
316 const std::string& animName) {
317 if (markerSequence.empty()) {
322 const float kLowConfidence = 1e-3;
323 std::map<std::string, size_t> markerNameToIndex;
324 std::vector<std::string> markerNames;
325 std::vector<std::vector<float>> timestamps;
326 std::vector<std::vector<Vector3f>> markerPositions;
327 std::vector<std::vector<Vector3f>> markerConf;
328 for (
size_t i = 0; i < markerSequence.size(); i++) {
329 const float timestamp =
static_cast<float>(i) / fps;
330 for (
const auto& marker : markerSequence[i]) {
331 if (marker.occluded || marker.confidence < kLowConfidence) {
336 if (markerNameToIndex.count(marker.name) == 0) {
337 const auto index = timestamps.size();
338 timestamps.emplace_back();
339 markerPositions.emplace_back();
340 markerConf.emplace_back();
341 markerNameToIndex[marker.name] = index;
342 markerNames.emplace_back(marker.name);
346 const auto& index = markerNameToIndex.at(marker.name);
348 index >= timestamps.size() || index >= markerPositions.size() ||
349 index >= markerConf.size(),
350 "Marker index {} exceeds container size",
352 timestamps[index].push_back(timestamp);
354 markerConf[index].push_back(Vector3f::Ones() * marker.confidence);
359 auto& scene = getDefaultScene(model);
360 auto& animation = addMomentumAnimationToModel(model, animName);
363 (markerNames.size() == timestamps.size()) && (markerNames.size() == markerPositions.size()) &&
364 (markerNames.size() == markerNameToIndex.size()) &&
365 (markerNames.size() == markerConf.size()));
367 for (
size_t j = 0; j < markerConf.size(); j++) {
369 const auto nodeIndex =
static_cast<int32_t
>(model.nodes.size());
370 model.nodes.emplace_back();
371 auto& node = model.nodes.back();
372 scene.nodes.push_back(nodeIndex);
373 node.name = markerNames[j];
374 node.translation = {0.0f, 0.0f, 0.0f};
375 node.scale = {1.0f, 1.0f, 1.0f};
376 node.extensionsAndExtras[
"extensions"][
"FB_momentum"][
"type"] =
"marker";
380 std::vector<float> confValues;
381 confValues.reserve(markerConf[j].size());
382 for (
const auto& v : markerConf[j]) {
383 confValues.push_back(v[0]);
385 node.extensionsAndExtras[
"extensions"][
"FB_momentum"][
"confidence"] = confValues;
387 switch (markerMesh) {
389 auto newMeshIdx = addMeshToModel(model, kUnitCubeRed,
true);
390 if (newMeshIdx < model.meshes.size()) {
391 node.mesh =
static_cast<int32_t
>(newMeshIdx);
401 if (!timestamps[j].empty() && !model.accessors.empty() &&
402 timestampIdx < model.accessors.size()) {
403 model.accessors[timestampIdx].min.emplace_back(timestamps[j].front());
404 model.accessors[timestampIdx].max.emplace_back(timestamps[j].back());
408 animation.channels.emplace_back();
409 auto& tchannel = animation.channels.back();
414 tchannel.target.node = nodeIndex;
415 tchannel.target.path =
"translation";
418 animation.channels.emplace_back();
419 auto& schannel = animation.channels.back();
422 schannel.target.node = nodeIndex;
423 schannel.target.path =
"scale";
427size_t addMeshToModel(
428 fx::gltf::Document& model,
430 const std::vector<size_t>& jointToNodeMap,
431 const size_t rootNodeIdx) {
435 const auto nodeIdx = model.nodes.size();
436 model.nodes.emplace_back();
437 auto& node = model.nodes.back();
439 rootNodeIdx >= model.nodes.size(),
440 "Root node index {} exceeds model.nodes size {}",
443 model.nodes[rootNodeIdx].children.push_back(
static_cast<int32_t
>(nodeIdx));
446 const auto& mesh = *character.
mesh;
447 auto newMeshIdx = addMeshToModel(model, mesh, !mesh.
colors.empty());
448 if (newMeshIdx >= model.meshes.size()) {
452 node.mesh =
static_cast<int32_t
>(newMeshIdx);
453 auto& m = model.meshes[node.mesh];
455 auto& prim = m.primitives.back();
458 model.skins.emplace_back();
459 auto& sk = model.skins.back();
462 for (
const auto& ji : jointToNodeMap) {
463 sk.joints.push_back(
static_cast<uint32_t
>(ji));
465 sk.skeleton = sk.joints[0];
468 node.skin =
static_cast<int32_t
>(model.skins.size() - 1);
471 std::vector<Matrix4f> ibm;
475 ibm.emplace_back(data.matrix());
481 if (skin.weight.block(0, 4, skin.weight.rows(), 4).maxCoeff() > 0.001f) {
486 for (
size_t b = 0; b < weightSets; b++) {
487 std::vector<Vector4s> indices(skin.index.rows());
488 std::vector<Vector4f> weights(skin.index.rows());
489 for (
size_t i = 0; i < indices.size(); i++) {
491 skin.index(i, b * 4 + 0),
492 skin.index(i, b * 4 + 1),
493 skin.index(i, b * 4 + 2),
494 skin.index(i, b * 4 + 3));
497 skin.weight(i, b * 4 + 0),
498 skin.weight(i, b * 4 + 1),
499 skin.weight(i, b * 4 + 2),
500 skin.weight(i, b * 4 + 3));
503 const auto kIndicesAttribute = std::string(
"JOINTS_") + std::to_string(b);
506 model, prim.attributes[kIndicesAttribute], fx::gltf::BufferView::TargetType::ArrayBuffer);
508 const auto kWeightsAttribute = std::string(
"WEIGHTS_") + std::to_string(b);
511 model, prim.attributes[kWeightsAttribute], fx::gltf::BufferView::TargetType::ArrayBuffer);
518void addSkeletonStatesToModel(
519 fx::gltf::Document& model,
522 std::span<const SkeletonState> skeletonStates,
523 std::span<const size_t> jointToNodeMap,
525 const std::string& motionName =
"default") {
526 const auto numFrames = skeletonStates.size();
527 if (numFrames == 0) {
534 "Character is not valid when trying to add skeleton states to model");
538 std::vector<float> timestamps(numFrames);
540 std::vector<std::vector<Vector3f>> translation(numJoints, std::vector<Vector3f>(numFrames));
541 std::vector<std::vector<Vector4f>> rotation(numJoints, std::vector<Vector4f>(numFrames));
542 std::vector<std::vector<Vector3f>> scale(numJoints, std::vector<Vector3f>(numFrames));
545 bool foundAnyChannel =
false;
546 for (Eigen::Index i = 0; i < static_cast<Eigen::Index>(numFrames); i++) {
547 for (
size_t j = 0; j < numJoints; j++) {
548 auto localT = skeletonStates[i].jointState[j].localTranslation().cast<
float>();
549 if (!(localT - character.
skeleton.
joints[j].translationOffset).isZero(1e-5f)) {
550 useChannel[j][0] =
true;
551 foundAnyChannel =
true;
555 auto localR = skeletonStates[i].jointState[j].localRotation().cast<
float>();
556 rotation[j][i] = {localR.x(), localR.y(), localR.z(), localR.w()};
561 rotation[j][i].
dot(rotation[j][i - 1]) < 0.0f) {
562 rotation[j][i] = -rotation[j][i];
564 if (!(localR.toRotationMatrix() - character.
skeleton.
joints[j].preRotation.toRotationMatrix())
566 useChannel[j][1] =
true;
567 foundAnyChannel =
true;
570 float localScale = skeletonStates[i].jointState[j].localScale();
571 scale[j][i] = Vector3f::Ones() * localScale;
572 if (std::fabs(localScale - 1.0f) > 1e-5f) {
573 useChannel[j][2] =
true;
574 foundAnyChannel =
true;
577 timestamps[i] =
static_cast<float>(i) / fps;
583 if (!foundAnyChannel && !useChannel.empty()) {
584 useChannel[0][0] =
true;
588 auto& animation = addMomentumAnimationToModel(model, motionName);
590 if (!timestamps.empty() && !model.accessors.empty() && timestampIdx < model.accessors.size()) {
591 model.accessors[timestampIdx].min.emplace_back(timestamps.front());
592 model.accessors[timestampIdx].max.emplace_back(timestamps.back());
596 for (
size_t j = 0; j < numJoints; j++) {
597 if (useChannel[j][0]) {
598 animation.channels.emplace_back();
599 auto& tchannel = animation.channels.back();
601 model, animation, translation[j], timestampIdx, interpolation);
602 tchannel.target.node =
static_cast<int32_t
>(jointToNodeMap[j]);
603 tchannel.target.path =
"translation";
606 if (useChannel[j][1]) {
607 animation.channels.emplace_back();
608 auto& rchannel = animation.channels.back();
611 rchannel.target.node =
static_cast<int32_t
>(jointToNodeMap[j]);
612 rchannel.target.path =
"rotation";
615 if (useChannel[j][2]) {
616 animation.channels.emplace_back();
617 auto& schannel = animation.channels.back();
620 schannel.target.node =
static_cast<int32_t
>(jointToNodeMap[j]);
621 schannel.target.path =
"scale";
626void addMotionToModel(
627 fx::gltf::Document& model,
632 const std::vector<size_t>& jointToNodeMap,
633 const size_t meshIndex,
635 const bool addExtension =
true,
636 const std::string& motionName =
"default") {
638 const auto& parameterNames = std::get<0>(inputMotion);
639 const auto& motion = std::get<1>(inputMotion);
640 const auto& jointNames = std::get<0>(inputIdentity);
641 const auto& identity = std::get<1>(inputIdentity);
643 const auto numFrames = motion.cols();
644 if (numFrames == 0) {
650 bool fullAnimation =
false;
652 auto& def = addMomentumExtension(model.extensionsAndExtras);
654 def[
"motion"][
"nframes"] = numFrames;
655 if (!parameterNames.empty() && motion.size() > 0) {
656 def[
"motion"][
"parameterNames"] = parameterNames;
658 model, std::span<const float>(motion.data(), motion.size()));
659 fullAnimation =
true;
662 if (!jointNames.empty() && identity.v.size() > 0) {
663 def[
"motion"][
"jointNames"] = jointNames;
665 model, std::span<const float>(identity.v.data(), identity.v.size()));
666 fullAnimation =
true;
670 fullAnimation =
true;
676 addMorphTargetsToModel(
682 addMorphWeightsToModel(model, character, fps, motion, meshIndex, interpolation, motionName);
695 std::vector<momentum::SkeletonState> skeletonStates(numFrames);
698 for (Eigen::Index i = 0; i < numFrames; i++) {
699 params.
pose = inputPoses.col(i);
700 const CharacterState state(params, character,
false,
false,
false);
701 skeletonStates[i] = state.skeletonState;
705 addSkeletonStatesToModel(
706 model, character, fps, skeletonStates, jointToNodeMap, interpolation, motionName);
709size_t appendNode(fx::gltf::Document& document,
const std::string& name) {
710 auto nodeIdx = document.nodes.size();
711 document.nodes.emplace_back();
712 auto& node = document.nodes.back();
717std::vector<size_t> addSkeletonToModel(
718 fx::gltf::Document& model,
720 const bool updateExtension =
true,
723 std::vector<size_t> jointToNodeMap;
724 std::unordered_map<size_t, const JointPhysicalProperties*> physicalPropertiesByJoint;
725 if (updateExtension) {
731 "Physical properties entry references unknown joint '{}'",
733 const auto emplaceResult = physicalPropertiesByJoint.emplace(jointIndex, &properties);
735 !emplaceResult.second,
736 "Multiple physical properties entries resolve to joint '{}' (index {})",
746 const auto nodeIndex = appendNode(model, joint.name);
747 auto& node = model.nodes[nodeIndex];
749 if (modelRootNodeIndex !=
kInvalidIndex && modelRootNodeIndex < model.nodes.size()) {
750 model.nodes[modelRootNodeIndex].children.push_back(
static_cast<int32_t
>(nodeIndex));
752 auto& scene = getDefaultScene(model);
753 scene.nodes.push_back(
static_cast<uint32_t
>(nodeIndex));
760 node.translation = {translation[0], translation[1], translation[2]};
762 if (updateExtension) {
763 auto& extension = addMomentumExtension(node.extensionsAndExtras);
764 extension[
"type"] = std::string(
"skeleton_joint");
765 const auto propertiesIt = physicalPropertiesByJoint.find(i);
766 if (propertiesIt != physicalPropertiesByJoint.end()) {
773 model.nodes.at(jointToNodeMap.at(joint.parent))
774 .children.push_back(
static_cast<int32_t
>(nodeIndex));
778 jointToNodeMap.push_back(nodeIndex);
781 return jointToNodeMap;
784void addCollisionsToModel(
785 fx::gltf::Document& model,
787 const std::vector<size_t>& jointToNodeMap,
788 bool addExtensions) {
791 for (
size_t i = 0; i < character.
collision->size(); i++) {
792 const auto& col = (*character.
collision)[i];
797 const auto nodeIndex = model.nodes.size();
798 model.nodes.emplace_back();
799 auto& node = model.nodes.back();
802 model.nodes.at(jointToNodeMap.at(col.parent))
803 .children.push_back(
static_cast<int32_t
>(nodeIndex));
806 node.name = character.
skeleton.
joints.at(col.parent).name +
"_col";
810 node.translation = {translation[0], translation[1], translation[2]};
814 auto& extension = addMomentumExtension(node.extensionsAndExtras);
816 extension[
"type"] =
"collision_capsule";
817 extension[
"length"] = col.length;
818 extension[
"radius"] = col.radius;
820 extension[
"type"] =
"collision_ellipsoid";
821 extension[
"radii"] = col.ellipsoidRadii;
823 extension[
"type"] =
"collision_box";
824 extension[
"halfExtents"] = col.boxHalfExtents;
827 "Unsupported collision primitive type {} while writing glTF collision geometry",
828 static_cast<int>(col.type));
835void addLocatorsToModel(
836 fx::gltf::Document& model,
838 const std::vector<size_t>& jointToNodeMap,
839 bool addExtensions) {
841 for (
const auto& loc : character.
locators) {
845 const auto nodeIndex = model.nodes.size();
846 model.nodes.emplace_back();
847 auto& node = model.nodes.back();
851 loc.parent >= jointToNodeMap.size(),
852 "Locator parent index {} exceeds jointToNodeMap size {}",
854 jointToNodeMap.size());
855 model.nodes.at(jointToNodeMap[loc.parent]).children.push_back(
static_cast<int32_t
>(nodeIndex));
858 node.name = loc.name;
860 node.translation = {translation[0], translation[1], translation[2]};
864 auto& extension = addMomentumExtension(node.extensionsAndExtras);
865 extension[
"type"] =
"locator";
866 extension[
"weight"] = loc.weight;
867 extension[
"limitWeight"] = loc.limitWeight;
868 extension[
"limitOrigin"] = loc.limitOrigin;
869 extension[
"locked"] = loc.locked;
870 if (loc.attachedToSkin) {
871 extension[
"attachedToSkin"] = loc.attachedToSkin;
873 if (loc.skinOffset != 0.0f) {
874 extension[
"skinOffset"] = loc.skinOffset;
878 auto newMeshIdx = addMeshToModel(model, kUnitCubeGreen,
true);
879 if (newMeshIdx < model.meshes.size()) {
880 node.mesh =
static_cast<int32_t
>(newMeshIdx);
886 const filesystem::path& filename,
887 fx::gltf::Document& model,
890 auto deducedFileFormat = fileFormat;
900 const filesystem::path parentDir = filename.parent_path();
901 if (!parentDir.empty() && !filesystem::exists(parentDir)) {
902 filesystem::create_directories(parentDir);
905 switch (deducedFileFormat) {
909 filesystem::path new_filename = filename;
910 new_filename.replace_extension(filesystem::path(
"glbin"));
911 if (!model.buffers.empty()) {
912 model.buffers.front().uri = new_filename.filename().string();
916 "There are some compatibility issues with .gltf files. Not all extension data might be exported correctly.");
917 fx::gltf::Save(model, filename.string(),
false);
923 fx::gltf::Save(model, filename.string(),
true);
926 }
catch (
const std::exception& e) {
927 MT_THROW(
"Failed to save file to: {}. Error: {}", filename.string(), e.what());
929 std::rethrow_exception(std::current_exception());
932 MT_THROW_IF(!filesystem::exists(filename),
"Unable to save: {}", filename.string());
956 document.extensionsUsed.emplace_back(
"FB_momentum");
960 impl_ = std::make_unique<GltfBuilder::Impl>();
961 initDefaultScene(impl_->document);
975 if (impl_->characterData.find(character.name) != impl_->characterData.end()) {
980 auto& scene = getDefaultScene(impl_->document);
983 const auto rootNodeIdx = appendNode(impl_->document, character.name);
985 rootNodeIdx >= 0 && rootNodeIdx < impl_->document.nodes.size(),
988 impl_->document.nodes.size());
989 auto& node = impl_->document.nodes[rootNodeIdx];
991 node.translation = {translation[0], translation[1], translation[2]};
993 scene.nodes.push_back(
static_cast<uint32_t
>(rootNodeIdx));
994 auto& characterData = impl_->characterData[character.name];
995 characterData.rootIndex = rootNodeIdx;
998 characterData.nodeMap =
999 addSkeletonToModel(impl_->document, character, options.extensions, rootNodeIdx);
1000 if (options.collisions) {
1001 addCollisionsToModel(impl_->document, character, characterData.nodeMap, options.extensions);
1003 if (options.locators) {
1004 addLocatorsToModel(impl_->document, character, characterData.nodeMap, options.extensions);
1007 characterData.meshIndex =
1008 addMeshToModel(impl_->document, character, characterData.nodeMap, rootNodeIdx);
1011 if (options.blendShapes && character.blendShape !=
nullptr) {
1012 addMorphTargetsToModel(
1014 *character.blendShape,
1015 character.blendShape->shapeSize(),
1016 characterData.meshIndex);
1019 if (options.extensions) {
1020 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1026 if (!character.metadata.empty()) {
1027 def[
"metadata"] = character.metadata;
1033 auto& model = impl_->document;
1034 auto meshIdx = addMeshToModel(model, mesh, addColor);
1035 if (meshIdx >= model.meshes.size()) {
1036 MT_LOGW(
"Failed to add mesh");
1040 const auto nodeIndex = model.nodes.size();
1041 model.nodes.emplace_back();
1042 auto& node = model.nodes.back();
1044 node.translation = {0.0f, 0.0f, 0.0f};
1045 node.mesh =
static_cast<int32_t
>(meshIdx);
1047 auto& scene = getDefaultScene(model);
1048 scene.nodes.push_back(
static_cast<uint32_t
>(nodeIndex));
1052 return impl_->characterData.size();
1056 if (impl_->characterData.count(name) == 0) {
1059 return impl_->characterData[name].rootIndex;
1063 if (impl_->characterData.count(name) == 0) {
1066 return impl_->characterData[name].nodeMap.size();
1070 impl_->animationInterpolation = interpolation;
1074 return impl_->animationInterpolation;
1079 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1080 constexpr auto kFpsStr =
"fps";
1081 if (!def.contains(kFpsStr)) {
1083 }
else if (def[kFpsStr] != fps) {
1085 "Attempting to set FPS to {} but it already exists as {}. Ignoring the new FPS.",
1087 def[kFpsStr].get<float>());
1096 const bool addExtensions ,
1097 const std::string& customName ,
1098 std::span<const int64_t> timestamps ) {
1100 if (impl_->characterData.find(character.
name) == impl_->characterData.end()) {
1105 const auto& jointToNodeMap = impl_->characterData[character.
name].nodeMap;
1106 const size_t meshIndex = impl_->characterData[character.
name].meshIndex;
1116 impl_->animationInterpolation,
1120 auto animIter = std::find_if(
1121 impl_->document.animations.begin(),
1122 impl_->document.animations.end(),
1123 [&customName](
const fx::gltf::Animation& anim) { return anim.name == customName; });
1124 if (animIter != impl_->document.animations.end()) {
1125 const auto animIdx =
static_cast<size_t>(animIter - impl_->document.animations.begin());
1126 impl_->characterData[character.
name].animationIndices.push_back(animIdx);
1130 if (!timestamps.empty()) {
1131 const auto& motionMatrix = std::get<1>(motion);
1133 timestamps.size() != motionMatrix.cols(),
1134 "Timestamps size {} does not match motion size {}",
1136 motionMatrix.cols());
1137 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1140 def[
"motion"][
"timestamps"] = std::vector<int64_t>(timestamps.begin(), timestamps.end());
1145 return impl_->document.animations.size();
1149 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1150 constexpr auto kFpsStr =
"fps";
1151 if (!def.contains(kFpsStr)) {
1154 return def[kFpsStr];
1158 if (impl_->characterData.count(characterName) == 0) {
1161 return impl_->characterData[characterName].animationIndices;
1166 std::span<
const std::vector<momentum::Marker>> markers,
1168 const std::string& animName) {
1170 addActorAnimationToModel(impl_->document, fps, markers, markerMesh, animName);
1174 const filesystem::path& filename,
1176 bool embedResources ) {
1181 for (
auto& buffer : document.buffers) {
1182 buffer.SetEmbeddedResource();
1187 return impl_->document;
1195 fx::gltf::Document& document,
1196 const filesystem::path& filename,
1198 bool embedResources ) {
1199 if (embedResources) {
1202 saveDocument(filename, document, fileFormat);
1208 std::span<const SkeletonState> skeletonStates,
1209 const std::string& customName) {
1211 if (impl_->characterData.find(character.
name) == impl_->characterData.end()) {
1216 const auto& jointToNodeMap = impl_->characterData[character.
name].nodeMap;
1219 addSkeletonStatesToModel(
1225 impl_->animationInterpolation,
1228 auto animIter = std::find_if(
1229 impl_->document.animations.begin(),
1230 impl_->document.animations.end(),
1231 [&customName](
const fx::gltf::Animation& anim) { return anim.name == customName; });
1232 if (animIter != impl_->document.animations.end()) {
1233 const auto animIdx =
static_cast<size_t>(animIter - impl_->document.animations.begin());
1234 impl_->characterData[character.
name].animationIndices.push_back(animIdx);
This file provides functions for applying blend shape deformations and skeletal transformations to ch...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Helper class to build a glb scene.
void setAnimationInterpolation(GltfAnimationInterpolation interpolation)
Set how the joint and blend shape animation samplers added afterwards interpolate between their keys ...
const fx::gltf::Document & getDocument()
Allow copy the document, but do not allow modify the file outside of the builder to keep metadata con...
void addMotion(const Character &character, float fps=120.0f, const MotionParameters &motion={}, const IdentityParameters &offsets={}, bool addExtensions=true, const std::string &customName="default", std::span< const int64_t > timestamps={})
Add a motion to the provided character.
void addMarkerSequence(float fps, std::span< const std::vector< momentum::Marker > > markerSequence, MarkerMesh markerMesh=MarkerMesh::UnitCube, const std::string &animName="default")
Add marker data to the file.
size_t getNumCharacters()
std::vector< size_t > getCharacterMotions(const std::string &characterName)
void addCharacter(const Character &character, const Vector3f &positionOffset=Vector3f::Zero(), const Quaternionf &rotationOffset=Quaternionf::Identity(), const FileSaveOptions &options=FileSaveOptions())
Add a character to the scene.
void addMesh(const Mesh &mesh, const std::string &name, bool addColor=false)
Add a static mesh, such as an environment or a target scan.
void save(const filesystem::path &filename, GltfFileFormat fileFormat=GltfFileFormat::Auto, bool embedResources=false)
MarkerMesh
Specify how marker mesh is represented in the glb file.
size_t getCharacterRootIndex(const std::string &name)
size_t getNumJoints(const std::string &name)
void addSkeletonStates(const Character &character, float fps, std::span< const SkeletonState > skeletonStates, const std::string &customName="default")
Add a skeleton states to the provided character.
GltfAnimationInterpolation getAnimationInterpolation() const
void forceEmbedResources()
Set all existing buffers to embed resources.
#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.
Vector3< uint8_t > Vector3b
3D vector of unsigned bytes; commonly used for RGB color storage in momentum (see ColorArray).
std::tuple< std::vector< std::string >, JointParameters > IdentityParameters
A tuple of skeleton joint names and identity parameters.
Quaternion< float > Quaternionf
JointParameters mapIdentityToCharacter(const IdentityParameters &inputIdentity, const Character &targetCharacter)
Maps the input JointParameter vector to a target character by matching joint names.
CharacterStateT< float > CharacterState
Vector4< std::uint16_t > Vector4s
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.
int32_t createAccessorBuffer(fx::gltf::Document &model, std::span< T > data, const bool align=false, const bool normalized=false)
FloatP dot(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes dot product of Eigen::Vector3f and 3-vector of packets.
Vector3f fromMomentumVec3f(const Vector3f &vec) noexcept
void jointPhysicalPropertiesToJson(const JointPhysicalProperties &jointProperties, nlohmann::json &j)
Serializes one joint's physical mass properties.
GltfAnimationInterpolation
How animation samplers written to a GLTF file interpolate between their keys.
@ Linear
Interpolate between keys (GLTF "LINEAR"; slerp for rotations).
@ Step
Hold each key until the next one (GLTF "STEP").
std::array< float, 4 > fromMomentumQuaternionf(const Quaternionf &quat) noexcept
Vector4< float > Vector4f
void parameterSetsToJson(const Character &character, nlohmann::json &j)
void poseConstraintsToJson(const Character &character, nlohmann::json &j)
CharacterParametersT< float > CharacterParameters
GltfFileFormat
File format in which the character is saved.
void parameterTransformToJson(const Character &character, nlohmann::json &j)
ModelParametersT< float > ModelParameters
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Vector3< std::int32_t > Vector3i
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
VectorX< float > VectorXf
void parameterLimitsToJson(const Character &character, nlohmann::json &j)
BlendWeightsT< T > extractBlendWeights(const ParameterTransform ¶mTransform, const ModelParametersT< T > &modelParams)
Extracts blend shape weights from model parameters.
MatrixX< float > MatrixXf
int32_t createSampler(fx::gltf::Document &model, fx::gltf::Animation &anim, std::span< T > data, const std::span< float > ×tamps, GltfAnimationInterpolation interpolation)
const MatrixXf & getShapeVectors() const
const std::vector< std::string > & getShapeNames() const
Skinning class that combines blend shape vectors with a base shape.
JointParametersT< T > offsets
The joint parameter vector representing the unique bone lengths of the character, defining the charac...
ModelParametersT< T > pose
The model parameter vector representing the pose of the character.
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.
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.
CollisionGeometry_u collision
Collision volumes for the character.
Unified options for saving files in both FBX and GLTF formats.
std::vector< size_t > animationIndices
std::vector< size_t > nodeMap
std::unordered_map< std::string, CharacterData > characterData
fx::gltf::Document document
GltfAnimationInterpolation animationInterpolation
Physical mass properties attached to one skeleton joint.
std::string jointName
Skeleton joint that owns this physical body.
std::vector< Eigen::Vector3i > texcoord_faces
List of texture coordinate indices per face Maps each face to its corresponding texture coordinates.
std::vector< Eigen::Vector2f > texcoords
List of texture coordinates (UV coordinates).
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
std::vector< Eigen::Vector3< T > > normals
List of vertex normals (same size as vertices when computed).
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
std::vector< Eigen::Vector3b > colors
List of per-vertex RGB colors (0-255 for each channel).
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...