Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
gltf_builder.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
19#include "momentum/common/log.h"
28#include "momentum/math/mesh.h"
29#include "momentum/math/mppca.h"
31
32#include <fx/gltf.h>
33
34#include <unordered_map>
35#include <variant>
36
37namespace {
38
39using namespace momentum;
40
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();
45 }
46 return extensionsAndExtras["extensions"]["FB_momentum"];
47}
48
49void initDefaultScene(fx::gltf::Document& model) {
50 model.scene = 0;
51 model.scenes.resize(1);
52}
53
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);
57}
58
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;
65 });
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;
70 return animation;
71 }
72 return *animationIter;
73}
74
75void setBufferView(
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());
82 // NOLINTNEXTLINE(facebook-hte-ParameterUncheckedArrayBounds)
83 auto& view = model.bufferViews[accessor.bufferView];
84 view.target = targetType;
85};
86
87// Add a mesh node with only one primitive (i.e. combined mesh)
88// Use a flag to decide if we should save the vertex color. If a mesh only has default color, we may
89// not want to save it.
90size_t addMeshToModel(fx::gltf::Document& model, const Mesh& mesh, const bool addColor = false) {
91 if (mesh.vertices.empty()) {
92 return std::numeric_limits<size_t>::max();
93 }
94
95 model.meshes.emplace_back();
96 auto& m = model.meshes.back();
97 m.primitives.emplace_back();
98 auto& prim = m.primitives.back();
99
100 // Add faces to mesh
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);
104 prim.indices = createAccessorBuffer<const int32_t>(model, faces);
105 setBufferView(model, prim.indices, fx::gltf::BufferView::TargetType::ElementArrayBuffer);
106 } else {
107 prim.mode = fx::gltf::Primitive::Mode::Points;
108 }
109
110 // Add vertices to mesh
111 std::vector<Vector3f> verts = mesh.vertices;
112 fromMomentumVec3f(verts);
113 MT_CHECK((!verts.empty()) && (verts[0].size() > 0));
114 prim.attributes["POSITION"] = createAccessorBuffer<const Vector3f>(model, verts, true);
115 setBufferView(model, prim.attributes["POSITION"], fx::gltf::BufferView::TargetType::ArrayBuffer);
116
117 // need min/max for position accessor
118 Box3f bbox;
119 for (const auto& v : verts) {
120 bbox.extend(v);
121 }
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]);
125 }
126
127 // add normal attribute
128 if (mesh.normals.size() == mesh.vertices.size()) {
129 prim.attributes["NORMAL"] = createAccessorBuffer<const Vector3f>(model, mesh.normals, true);
130 setBufferView(model, prim.attributes["NORMAL"], fx::gltf::BufferView::TargetType::ArrayBuffer);
131 }
132
133 // add texcoord attribute
134 if (!mesh.texcoords.empty()) {
135 // NOTE: GLTF doesn't support storing multiple texture coordinates per vertex, so instead of
136 // using the standard GLTF texture arrays we store the data in a custom location
137 auto& def = addMomentumExtension(prim.extensionsAndExtras);
138 def["texcoords"] = createAccessorBuffer<const Vector2f>(model, mesh.texcoords, true);
139 setBufferView(model, def["texcoords"], fx::gltf::BufferView::TargetType::ArrayBuffer);
140
141 MT_THROW_IF(mesh.texcoord_faces.empty(), "Mesh has texcoords but no texcoord_faces");
142 const std::span<const int32_t> texFaces(
143 &mesh.texcoord_faces[0][0], mesh.texcoord_faces.size() * 3);
144 def["texfaces"] = createAccessorBuffer<const int32_t>(model, texFaces);
145 setBufferView(model, def["texfaces"], fx::gltf::BufferView::TargetType::ArrayBuffer);
146 }
147
148 if (addColor && !mesh.colors.empty() && mesh.colors.size() != mesh.vertices.size()) {
149 MT_LOGW(
150 "Skipping vertex colors because color count ({}) does not match vertex count ({})",
151 mesh.colors.size(),
152 mesh.vertices.size());
153 }
154 if (mesh.colors.size() == mesh.vertices.size() && addColor) {
155 prim.attributes["COLOR_0"] =
156 createAccessorBuffer<const Vector3b>(model, mesh.colors, true, true);
157 setBufferView(model, prim.attributes["COLOR_0"], fx::gltf::BufferView::TargetType::ArrayBuffer);
158 }
159
160 return model.meshes.size() - 1;
161}
162
163void addMorphTargetsToModel(
164 fx::gltf::Document& model,
165 const BlendShape& shapes,
166 size_t numShapes,
167 size_t meshIndex) {
168 if (model.meshes.empty() || meshIndex == kInvalidIndex) {
169 MT_LOGW("No mesh is saved in the file when adding blendshapes");
170 return;
171 }
172
173 // assume there is only one primitive on the character mesh.
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) {
177 // enough shapes already exist; nothing to be done.
178 return;
179 }
180 auto& def = addMomentumExtension(prim.extensionsAndExtras);
181 def["shapeNames"] = shapes.getShapeNames();
182
183 const MatrixXf& shapeVecs = shapes.getShapeVectors();
184 for (size_t iShape = numShapesAdded; iShape < numShapes; ++iShape) {
185 // make a copy so we can scale it
186 VectorXf deltas = shapeVecs.col(iShape);
187 fromMomentumVec3f(deltas);
188 prim.targets.emplace_back();
189 auto& attr = prim.targets.back();
190
191 std::span<const Eigen::Vector3f> span(
192 reinterpret_cast<Eigen::Vector3f*>(deltas.data()), static_cast<size_t>(deltas.size() / 3));
193 attr["POSITION"] = createAccessorBuffer<const Vector3f>(model, span, true);
194 setBufferView(model, attr["POSITION"], fx::gltf::BufferView::TargetType::ArrayBuffer);
195
196 // set bbox
197 Box3f bbox;
198 for (const Vector3f& v : span) {
199 bbox.extend(v);
200 }
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]);
204 }
205 }
206}
207
208void addMorphWeightsToModel(
209 fx::gltf::Document& model,
210 const Character& character,
211 const float fps,
212 const MatrixXf& modelParams,
213 const size_t meshIndex,
214 const GltfAnimationInterpolation interpolation,
215 const std::string& motionName = "default") {
216 const size_t numFrames = modelParams.cols();
217 if (numFrames == 0) {
218 return;
219 }
220
221 const auto& pt = character.parameterTransform;
222 const size_t numWeights = pt.numBlendShapeParameters();
223 if (numWeights == 0) {
224 return;
225 }
226
227 // validate the mesh node - bounds checking
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: {})",
232 meshIndex,
233 model.nodes.size());
234
235 // validate the mesh node - original logic
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");
239 return;
240 }
241
242 // extract weight values
243 std::vector<float> timestamps(numFrames, 0);
244 bool useChannel = false;
245 // Important to make sure row vs col is what createSampler expects
246 MatrixXf weights(numWeights, numFrames);
247
248 for (size_t iFrame = 0; iFrame < numFrames; ++iFrame) {
249 const VectorXf& pose = modelParams.col(iFrame);
250 const VectorXf w = extractBlendWeights(pt, ModelParameters(pose)).v;
251 if (w.norm() > 1e-5f) {
252 useChannel = true;
253 }
254 weights.col(iFrame) = w;
255 timestamps[iFrame] = static_cast<float>(iFrame) / fps;
256 }
257 if (!useChannel) {
258 return;
259 }
260
261 // store weight values in gltf document
262 auto& animation = addMomentumAnimationToModel(model, motionName);
263 const auto timestampIdx = createAccessorBuffer<const float>(model, timestamps);
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());
267 }
268
269 animation.channels.emplace_back();
270 auto& channel = animation.channels.back();
271 channel.sampler = createSampler<const float>(
272 model,
273 animation,
274 std::span<const float>(weights.data(), numWeights * numFrames),
275 timestampIdx,
276 interpolation);
277 channel.target.node = static_cast<int32_t>(meshIndex);
278 channel.target.path = "weights";
279}
280
281Mesh createUnitCube(const Eigen::Vector3b& color) {
282 Mesh cube;
283 cube.vertices = {
284 Vector3f(-1.0f, -1.0f, 1.0f),
285 Vector3f(1.0f, -1.0f, 1.0f),
286 Vector3f(1.0f, 1.0f, 1.0f),
287 Vector3f(-1.0f, 1.0f, 1.0f),
288 Vector3f(-1.0f, -1.0f, -1.0f),
289 Vector3f(1.0f, -1.0f, -1.0f),
290 Vector3f(1.0f, 1.0f, -1.0f),
291 Vector3f(-1.0f, 1.0f, -1.0f)};
292 cube.faces = {
293 Vector3i(0, 1, 2),
294 Vector3i(2, 3, 0),
295 Vector3i(1, 5, 6),
296 Vector3i(6, 2, 1),
297 Vector3i(7, 6, 5),
298 Vector3i(5, 4, 7),
299 Vector3i(4, 0, 3),
300 Vector3i(3, 7, 4),
301 Vector3i(4, 5, 1),
302 Vector3i(1, 0, 4),
303 Vector3i(3, 2, 6),
304 Vector3i(6, 7, 3)};
305 cube.colors = std::vector<Eigen::Vector3b>(8, color);
306 return cube;
307}
308const auto kUnitCubeRed = createUnitCube(Eigen::Vector3b(255, 0, 0));
309const auto kUnitCubeGreen = createUnitCube(Eigen::Vector3b(0, 255, 0));
310
311void addActorAnimationToModel(
312 fx::gltf::Document& model,
313 const float fps,
314 std::span<const std::vector<momentum::Marker>> markerSequence,
315 const GltfBuilder::MarkerMesh markerMesh,
316 const std::string& animName) {
317 if (markerSequence.empty()) {
318 return;
319 }
320
321 // create arrays for data
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) {
332 continue;
333 }
334
335 // create new array if marker is unknown
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);
343 }
344
345 // get index
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",
351 index);
352 timestamps[index].push_back(timestamp);
353 markerPositions[index].push_back(fromMomentumVec3f(marker.pos.cast<float>()));
354 markerConf[index].push_back(Vector3f::Ones() * marker.confidence);
355 }
356 }
357
358 // add data to gltf document
359 auto& scene = getDefaultScene(model);
360 auto& animation = addMomentumAnimationToModel(model, animName);
361
362 MT_CHECK(
363 (markerNames.size() == timestamps.size()) && (markerNames.size() == markerPositions.size()) &&
364 (markerNames.size() == markerNameToIndex.size()) &&
365 (markerNames.size() == markerConf.size()));
366
367 for (size_t j = 0; j < markerConf.size(); j++) {
368 // create marker
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";
377 // for convenience, save confidence as a flat float array so we don't need to parse animation
378 // channels
379 {
380 std::vector<float> confValues;
381 confValues.reserve(markerConf[j].size());
382 for (const auto& v : markerConf[j]) {
383 confValues.push_back(v[0]);
384 }
385 node.extensionsAndExtras["extensions"]["FB_momentum"]["confidence"] = confValues;
386 }
387 switch (markerMesh) {
389 auto newMeshIdx = addMeshToModel(model, kUnitCubeRed, true);
390 if (newMeshIdx < model.meshes.size()) {
391 node.mesh = static_cast<int32_t>(newMeshIdx);
392 }
393 break;
394 }
396 break;
397 }
398
399 // create animation channel
400 const auto timestampIdx = createAccessorBuffer<const float>(model, timestamps[j]);
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());
405 }
406
407 // translation
408 animation.channels.emplace_back();
409 auto& tchannel = animation.channels.back();
410 tchannel.sampler =
411 // NOLINTNEXTLINE(facebook-hte-ParameterUncheckedArrayBounds)
413 model, animation, markerPositions[j], timestampIdx, GltfAnimationInterpolation::Step);
414 tchannel.target.node = nodeIndex;
415 tchannel.target.path = "translation";
416
417 // scale -- for visualization purpose only
418 animation.channels.emplace_back();
419 auto& schannel = animation.channels.back();
420 schannel.sampler = createSampler<const Vector3f>(
421 model, animation, markerConf[j], timestampIdx, GltfAnimationInterpolation::Step);
422 schannel.target.node = nodeIndex;
423 schannel.target.path = "scale";
424 }
425}
426
427size_t addMeshToModel(
428 fx::gltf::Document& model,
429 const Character& character,
430 const std::vector<size_t>& jointToNodeMap,
431 const size_t rootNodeIdx) {
432 // write mesh node/skinning data
433 if (character.mesh && character.skinWeights) {
434 // create new mesh node
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 {}",
441 rootNodeIdx,
442 model.nodes.size());
443 model.nodes[rootNodeIdx].children.push_back(static_cast<int32_t>(nodeIdx));
444
445 // create model mesh
446 const auto& mesh = *character.mesh;
447 auto newMeshIdx = addMeshToModel(model, mesh, !mesh.colors.empty());
448 if (newMeshIdx >= model.meshes.size()) {
449 // Mesh not valid, skip
450 return kInvalidIndex;
451 }
452 node.mesh = static_cast<int32_t>(newMeshIdx);
453 auto& m = model.meshes[node.mesh];
454 MT_CHECK(m.primitives.size() == 1);
455 auto& prim = m.primitives.back();
456
457 const auto& skin = *character.skinWeights;
458 model.skins.emplace_back();
459 auto& sk = model.skins.back();
460
461 // add skin node
462 for (const auto& ji : jointToNodeMap) {
463 sk.joints.push_back(static_cast<uint32_t>(ji));
464 }
465 sk.skeleton = sk.joints[0];
466
467 node.name = "mesh";
468 node.skin = static_cast<int32_t>(model.skins.size() - 1);
469
470 // add inverse bind matrix
471 std::vector<Matrix4f> ibm;
472 for (const auto& mat : character.inverseBindPose) {
473 auto data = mat;
474 data.translation() = fromMomentumVec3f(data.translation());
475 ibm.emplace_back(data.matrix());
476 }
477 sk.inverseBindMatrices = createAccessorBuffer<const Matrix4f>(model, ibm);
478
479 // add skinning data
480 int weightSets = 1;
481 if (skin.weight.block(0, 4, skin.weight.rows(), 4).maxCoeff() > 0.001f) {
482 // only export two sets of weights if more than one set is being used
483 // only one vertex on the second set would have to have more than 0.1% influence to qualify
484 weightSets = 2;
485 }
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++) {
490 indices[i] = Vector4s(
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));
495 // NOLINTNEXTLINE(facebook-hte-LocalUncheckedArrayBounds)
496 weights[i] = Vector4f(
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));
501 }
502
503 const auto kIndicesAttribute = std::string("JOINTS_") + std::to_string(b);
504 prim.attributes[kIndicesAttribute] = createAccessorBuffer<const Vector4s>(model, indices);
505 setBufferView(
506 model, prim.attributes[kIndicesAttribute], fx::gltf::BufferView::TargetType::ArrayBuffer);
507
508 const auto kWeightsAttribute = std::string("WEIGHTS_") + std::to_string(b);
509 prim.attributes[kWeightsAttribute] = createAccessorBuffer<const Vector4f>(model, weights);
510 setBufferView(
511 model, prim.attributes[kWeightsAttribute], fx::gltf::BufferView::TargetType::ArrayBuffer);
512 }
513 return nodeIdx;
514 }
515 return kInvalidIndex;
516}
517
518void addSkeletonStatesToModel(
519 fx::gltf::Document& model,
520 const Character& character,
521 const float fps,
522 std::span<const SkeletonState> skeletonStates,
523 std::span<const size_t> jointToNodeMap,
524 const GltfAnimationInterpolation interpolation,
525 const std::string& motionName = "default") {
526 const auto numFrames = skeletonStates.size();
527 if (numFrames == 0) {
528 return;
529 }
530
531 // check for valid character and stuff before adding things
533 character.skeleton.joints.empty() || character.parameterTransform.numJointParameters() == 0,
534 "Character is not valid when trying to add skeleton states to model");
535
536 // store parameterized motion into joints for actual animation
537 const auto numJoints = character.skeleton.joints.size();
538 std::vector<float> timestamps(numFrames);
539 std::vector<Vector3<bool>> useChannel(numJoints, Vector3<bool>::Constant(false));
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));
543
544 // create motion data using the mapped data
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;
552 }
553 translation[j][i] = fromMomentumVec3f(localT);
554
555 auto localR = skeletonStates[i].jointState[j].localRotation().cast<float>();
556 rotation[j][i] = {localR.x(), localR.y(), localR.z(), localR.w()};
557 // q and -q are the same rotation, but readers that interpolate the components
558 // (rather than slerp) would pass through the wrong rotation between keys with
559 // opposite signs, so keep consecutive keys in the same hemisphere.
560 if (interpolation == GltfAnimationInterpolation::Linear && i > 0 &&
561 rotation[j][i].dot(rotation[j][i - 1]) < 0.0f) {
562 rotation[j][i] = -rotation[j][i];
563 }
564 if (!(localR.toRotationMatrix() - character.skeleton.joints[j].preRotation.toRotationMatrix())
565 .isZero(1e-5f)) {
566 useChannel[j][1] = true;
567 foundAnyChannel = true;
568 }
569
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;
575 }
576 }
577 timestamps[i] = static_cast<float>(i) / fps;
578 }
579
580 // fx-gltf has a bug where if you write an animation that has no actual
581 // animated channels, it throws an error "Required field not found : channels".
582 // So we'll just make sure there is at least one channel in this case.
583 if (!foundAnyChannel && !useChannel.empty()) {
584 useChannel[0][0] = true;
585 }
586
587 // add data to gltf document
588 auto& animation = addMomentumAnimationToModel(model, motionName);
589 const auto timestampIdx = createAccessorBuffer<const float>(model, timestamps);
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());
593 }
594
595 // only save the animation channels that actually have any useful data
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();
600 tchannel.sampler = createSampler<const Vector3f>(
601 model, animation, translation[j], timestampIdx, interpolation);
602 tchannel.target.node = static_cast<int32_t>(jointToNodeMap[j]);
603 tchannel.target.path = "translation";
604 }
605
606 if (useChannel[j][1]) {
607 animation.channels.emplace_back();
608 auto& rchannel = animation.channels.back();
609 rchannel.sampler =
610 createSampler<const Vector4f>(model, animation, rotation[j], timestampIdx, interpolation);
611 rchannel.target.node = static_cast<int32_t>(jointToNodeMap[j]);
612 rchannel.target.path = "rotation";
613 }
614
615 if (useChannel[j][2]) {
616 animation.channels.emplace_back();
617 auto& schannel = animation.channels.back();
618 schannel.sampler =
619 createSampler<const Vector3f>(model, animation, scale[j], timestampIdx, interpolation);
620 schannel.target.node = static_cast<int32_t>(jointToNodeMap[j]);
621 schannel.target.path = "scale";
622 }
623 }
624}
625
626void addMotionToModel(
627 fx::gltf::Document& model,
628 const Character& character,
629 const float fps,
630 const MotionParameters& inputMotion,
631 const IdentityParameters& inputIdentity,
632 const std::vector<size_t>& jointToNodeMap,
633 const size_t meshIndex,
634 const GltfAnimationInterpolation interpolation,
635 const bool addExtension = true,
636 const std::string& motionName = "default") {
637 // disentangle input values for storage
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);
642
643 const auto numFrames = motion.cols();
644 if (numFrames == 0) {
645 return;
646 }
647
648 // **** Save animation to Momentum extension ****
649 // add motion if we have poses
650 bool fullAnimation = false;
651 if (addExtension) {
652 auto& def = addMomentumExtension(model.extensionsAndExtras);
653 // store motion array and offsets as metadata
654 def["motion"]["nframes"] = numFrames;
655 if (!parameterNames.empty() && motion.size() > 0) {
656 def["motion"]["parameterNames"] = parameterNames;
657 def["motion"]["poses"] = createAccessorBuffer<const float>(
658 model, std::span<const float>(motion.data(), motion.size()));
659 fullAnimation = true;
660 }
661
662 if (!jointNames.empty() && identity.v.size() > 0) {
663 def["motion"]["jointNames"] = jointNames;
664 def["motion"]["offsets"] = createAccessorBuffer<const float>(
665 model, std::span<const float>(identity.v.data(), identity.v.size()));
666 fullAnimation = true;
667 }
668 } else {
669 // There may be animation outside of the momentum machinery
670 fullAnimation = true;
671 }
672
673 // **** Save animation to gltf ****
674 // add blenshapes (that are used) if available
675 if (meshIndex != kInvalidIndex && character.blendShape != nullptr) {
676 addMorphTargetsToModel(
677 model,
678 *character.blendShape.get(),
680 meshIndex);
681
682 addMorphWeightsToModel(model, character, fps, motion, meshIndex, interpolation, motionName);
683 }
684
685 // check for valid character and motion before adding joint animation
686 if (!fullAnimation || character.skeleton.joints.empty()) {
687 return;
688 }
689
690 // map data to character
691 const auto inputPoses = mapMotionToCharacter(inputMotion, character);
692 const auto inputOffset = mapIdentityToCharacter(inputIdentity, character);
693
694 // create skeleton states from model params
695 std::vector<momentum::SkeletonState> skeletonStates(numFrames);
696 CharacterParameters params;
697 params.offsets = inputOffset;
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;
702 }
703
704 // add skeleton states to model
705 addSkeletonStatesToModel(
706 model, character, fps, skeletonStates, jointToNodeMap, interpolation, motionName);
707}
708
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();
713 node.name = name;
714 return nodeIdx;
715}
716
717std::vector<size_t> addSkeletonToModel(
718 fx::gltf::Document& model,
719 const Character& character,
720 const bool updateExtension = true,
721 size_t modelRootNodeIndex = kInvalidIndex) {
722 // add all joints to node list
723 std::vector<size_t> jointToNodeMap;
724 std::unordered_map<size_t, const JointPhysicalProperties*> physicalPropertiesByJoint;
725 if (updateExtension) {
726 physicalPropertiesByJoint.reserve(character.physicalProperties.size());
727 for (const JointPhysicalProperties& properties : character.physicalProperties) {
728 const size_t jointIndex = resolvePhysicalPropertiesJointIndex(properties, character.skeleton);
730 jointIndex == kInvalidIndex,
731 "Physical properties entry references unknown joint '{}'",
732 properties.jointName);
733 const auto emplaceResult = physicalPropertiesByJoint.emplace(jointIndex, &properties);
735 !emplaceResult.second,
736 "Multiple physical properties entries resolve to joint '{}' (index {})",
737 character.skeleton.joints.at(jointIndex).name,
738 jointIndex);
739 }
740 }
741
742 for (size_t i = 0; i < character.skeleton.joints.size(); i++) {
743 const auto& joint = character.skeleton.joints[i];
744
745 // create new node
746 const auto nodeIndex = appendNode(model, joint.name);
747 auto& node = model.nodes[nodeIndex];
748 if (i == 0) {
749 if (modelRootNodeIndex != kInvalidIndex && modelRootNodeIndex < model.nodes.size()) {
750 model.nodes[modelRootNodeIndex].children.push_back(static_cast<int32_t>(nodeIndex));
751 } else {
752 auto& scene = getDefaultScene(model);
753 scene.nodes.push_back(static_cast<uint32_t>(nodeIndex));
754 }
755 }
756
757 // set joint values in node
758 node.rotation = fromMomentumQuaternionf(joint.preRotation);
759 const auto translation = fromMomentumVec3f(joint.translationOffset);
760 node.translation = {translation[0], translation[1], translation[2]};
761
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()) {
767 jointPhysicalPropertiesToJson(*propertiesIt->second, extension["physicalProperties"]);
768 }
769 }
770
771 // add node as child to parent joint
772 if (joint.parent != kInvalidIndex) {
773 model.nodes.at(jointToNodeMap.at(joint.parent))
774 .children.push_back(static_cast<int32_t>(nodeIndex));
775 }
776
777 // add node to map
778 jointToNodeMap.push_back(nodeIndex);
779 }
780
781 return jointToNodeMap;
782}
783
784void addCollisionsToModel(
785 fx::gltf::Document& model,
786 const Character& character,
787 const std::vector<size_t>& jointToNodeMap,
788 bool addExtensions) {
789 // add all collision objects to node list
790 if (character.collision) {
791 for (size_t i = 0; i < character.collision->size(); i++) {
792 const auto& col = (*character.collision)[i];
793
794 MT_CHECK(col.parent != kInvalidIndex);
795
796 // create new node
797 const auto nodeIndex = model.nodes.size();
798 model.nodes.emplace_back();
799 auto& node = model.nodes.back();
800
801 // add node as child to parent joint
802 model.nodes.at(jointToNodeMap.at(col.parent))
803 .children.push_back(static_cast<int32_t>(nodeIndex));
804
805 // add values for the collision primitive
806 node.name = character.skeleton.joints.at(col.parent).name + "_col";
807
808 node.rotation = fromMomentumQuaternionf(col.transformation.rotation);
809 const auto translation = fromMomentumVec3f(col.transformation.translation);
810 node.translation = {translation[0], translation[1], translation[2]};
811
812 // add extra properties
813 if (addExtensions) {
814 auto& extension = addMomentumExtension(node.extensionsAndExtras);
816 extension["type"] = "collision_capsule";
817 extension["length"] = col.length;
818 extension["radius"] = col.radius;
819 } else if (col.type == CollisionPrimitiveType::Ellipsoid) {
820 extension["type"] = "collision_ellipsoid";
821 extension["radii"] = col.ellipsoidRadii;
822 } else if (col.type == CollisionPrimitiveType::Box) {
823 extension["type"] = "collision_box";
824 extension["halfExtents"] = col.boxHalfExtents;
825 } else {
826 MT_THROW(
827 "Unsupported collision primitive type {} while writing glTF collision geometry",
828 static_cast<int>(col.type));
829 }
830 }
831 }
832 }
833}
834
835void addLocatorsToModel(
836 fx::gltf::Document& model,
837 const Character& character,
838 const std::vector<size_t>& jointToNodeMap,
839 bool addExtensions) {
840 // add locators
841 for (const auto& loc : character.locators) {
842 MT_CHECK(loc.parent != kInvalidIndex);
843
844 // create new node
845 const auto nodeIndex = model.nodes.size();
846 model.nodes.emplace_back();
847 auto& node = model.nodes.back();
848
849 // add node as child to parent joint
851 loc.parent >= jointToNodeMap.size(),
852 "Locator parent index {} exceeds jointToNodeMap size {}",
853 loc.parent,
854 jointToNodeMap.size());
855 model.nodes.at(jointToNodeMap[loc.parent]).children.push_back(static_cast<int32_t>(nodeIndex));
856
857 // add values for the tapered capsule
858 node.name = loc.name;
859 const auto translation = fromMomentumVec3f(loc.offset);
860 node.translation = {translation[0], translation[1], translation[2]};
861
862 // add extra properties
863 if (addExtensions) {
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;
872 }
873 if (loc.skinOffset != 0.0f) {
874 extension["skinOffset"] = loc.skinOffset;
875 }
876 }
877
878 auto newMeshIdx = addMeshToModel(model, kUnitCubeGreen, true);
879 if (newMeshIdx < model.meshes.size()) {
880 node.mesh = static_cast<int32_t>(newMeshIdx);
881 }
882 }
883}
884
885void saveDocument(
886 const filesystem::path& filename,
887 fx::gltf::Document& model,
888 const GltfFileFormat fileFormat) {
889 // save model
890 auto deducedFileFormat = fileFormat;
891 if (fileFormat == GltfFileFormat::Auto && filename.extension() == filesystem::path(".gltf")) {
892 deducedFileFormat = GltfFileFormat::Ascii;
893 }
894
895 try {
896 // Check if the parent directory of the file exists. If the parent directory does not exist
897 // and is not an empty string (which means the file is in the current working directory),
898 // create it. This is necessary because fx::gltf::Save throws an exception if the directory
899 // does not exist.
900 const filesystem::path parentDir = filename.parent_path();
901 if (!parentDir.empty() && !filesystem::exists(parentDir)) {
902 filesystem::create_directories(parentDir);
903 }
904
905 switch (deducedFileFormat) {
907 // we can't embed binary if we writing to ascii format.
908 // so we need to provide exported with a uri name relative to json root.
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();
913 }
914
915 MT_LOGE(
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);
918 break;
919 }
921 [[fallthrough]];
923 fx::gltf::Save(model, filename.string(), true);
924 break;
925 }
926 } catch (const std::exception& e) {
927 MT_THROW("Failed to save file to: {}. Error: {}", filename.string(), e.what());
928 } catch (...) {
929 std::rethrow_exception(std::current_exception());
930 }
931
932 MT_THROW_IF(!filesystem::exists(filename), "Unable to save: {}", filename.string());
933}
934
935} // namespace
936
937namespace momentum {
938
941 std::vector<size_t> nodeMap = {};
943 // node index of the mesh node; needed for creating blendshape morph targets
945 std::vector<size_t> animationIndices = {};
946 };
947
948 Impl();
949 fx::gltf::Document document;
950 std::unordered_map<std::string, CharacterData> characterData;
953};
954
955GltfBuilder::Impl::Impl() : document(fx::gltf::Document()) {
956 document.extensionsUsed.emplace_back("FB_momentum");
957}
958
960 impl_ = std::make_unique<GltfBuilder::Impl>();
961 initDefaultScene(impl_->document);
962}
963
964GltfBuilder::~GltfBuilder() = default;
965
966GltfBuilder::GltfBuilder(GltfBuilder&&) noexcept = default;
967
968GltfBuilder& GltfBuilder::operator=(GltfBuilder&&) noexcept = default;
969
971 const Character& character,
972 const Vector3f& positionOffset /*= Vector3f::Zero()*/,
973 const Quaternionf& rotationOffset /*= Quaternionf::Identity()*/,
974 const FileSaveOptions& options) {
975 if (impl_->characterData.find(character.name) != impl_->characterData.end()) {
976 // Character already exist. Doesn't allow character with the same name to be saved.
977 // #TODO: proper warning
978 return;
979 }
980 auto& scene = getDefaultScene(impl_->document);
981
982 // Add character root node
983 const auto rootNodeIdx = appendNode(impl_->document, character.name);
984 MT_CHECK(
985 rootNodeIdx >= 0 && rootNodeIdx < impl_->document.nodes.size(),
986 "{}: {}",
987 rootNodeIdx,
988 impl_->document.nodes.size());
989 auto& node = impl_->document.nodes[rootNodeIdx];
990 const auto translation = fromMomentumVec3f(positionOffset);
991 node.translation = {translation[0], translation[1], translation[2]};
992 node.rotation = fromMomentumQuaternionf(rotationOffset);
993 scene.nodes.push_back(static_cast<uint32_t>(rootNodeIdx));
994 auto& characterData = impl_->characterData[character.name];
995 characterData.rootIndex = rootNodeIdx;
996
997 // fill with data
998 characterData.nodeMap =
999 addSkeletonToModel(impl_->document, character, options.extensions, rootNodeIdx);
1000 if (options.collisions) {
1001 addCollisionsToModel(impl_->document, character, characterData.nodeMap, options.extensions);
1002 }
1003 if (options.locators) {
1004 addLocatorsToModel(impl_->document, character, characterData.nodeMap, options.extensions);
1005 }
1006 if (options.mesh) {
1007 characterData.meshIndex =
1008 addMeshToModel(impl_->document, character, characterData.nodeMap, rootNodeIdx);
1009
1010 // Add blendshapes if both addMesh and addBlendShapes are true
1011 if (options.blendShapes && character.blendShape != nullptr) {
1012 addMorphTargetsToModel(
1013 impl_->document,
1014 *character.blendShape,
1015 character.blendShape->shapeSize(),
1016 characterData.meshIndex);
1017 }
1018 }
1019 if (options.extensions) {
1020 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1021 parameterTransformToJson(character, def["transform"]);
1022 parameterLimitsToJson(character, def["parameterLimits"]);
1023 parameterSetsToJson(character, def["parameterSet"]);
1024 poseConstraintsToJson(character, def["poseConstraints"]);
1025 // add metadata if it exists
1026 if (!character.metadata.empty()) {
1027 def["metadata"] = character.metadata;
1028 }
1029 }
1030}
1031
1032void GltfBuilder::addMesh(const Mesh& mesh, const std::string& name, bool addColor) {
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");
1037 return;
1038 }
1039
1040 const auto nodeIndex = model.nodes.size();
1041 model.nodes.emplace_back();
1042 auto& node = model.nodes.back();
1043 node.name = name;
1044 node.translation = {0.0f, 0.0f, 0.0f};
1045 node.mesh = static_cast<int32_t>(meshIdx);
1046
1047 auto& scene = getDefaultScene(model);
1048 scene.nodes.push_back(static_cast<uint32_t>(nodeIndex));
1049}
1050
1052 return impl_->characterData.size();
1053}
1054
1055size_t GltfBuilder::getCharacterRootIndex(const std::string& name) {
1056 if (impl_->characterData.count(name) == 0) {
1057 return kInvalidIndex;
1058 }
1059 return impl_->characterData[name].rootIndex;
1060}
1061
1062size_t GltfBuilder::getNumJoints(const std::string& name) {
1063 if (impl_->characterData.count(name) == 0) {
1064 return kInvalidIndex;
1065 }
1066 return impl_->characterData[name].nodeMap.size();
1067}
1068
1070 impl_->animationInterpolation = interpolation;
1071}
1072
1074 return impl_->animationInterpolation;
1075}
1076
1077void GltfBuilder::setFps(float fps) {
1078 // set frame-rate
1079 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1080 constexpr auto kFpsStr = "fps";
1081 if (!def.contains(kFpsStr)) {
1082 def[kFpsStr] = fps;
1083 } else if (def[kFpsStr] != fps) {
1084 MT_LOGW(
1085 "Attempting to set FPS to {} but it already exists as {}. Ignoring the new FPS.",
1086 fps,
1087 def[kFpsStr].get<float>());
1088 }
1089}
1090
1092 const Character& character,
1093 const float fps /*= 120.0f*/,
1094 const MotionParameters& motion /*= {}*/,
1095 const IdentityParameters& offsets /*= {}*/,
1096 const bool addExtensions /*= true*/,
1097 const std::string& customName /*= "default"*/,
1098 std::span<const int64_t> timestamps /*= {}*/) {
1099 setFps(fps);
1100 if (impl_->characterData.find(character.name) == impl_->characterData.end()) {
1101 // #TODO: Warn about this addition
1102 addCharacter(character);
1103 }
1104
1105 const auto& jointToNodeMap = impl_->characterData[character.name].nodeMap;
1106 const size_t meshIndex = impl_->characterData[character.name].meshIndex;
1107 // add motion
1108 addMotionToModel(
1109 impl_->document,
1110 character,
1111 fps,
1112 motion,
1113 offsets,
1114 jointToNodeMap,
1115 meshIndex,
1116 impl_->animationInterpolation,
1117 addExtensions,
1118 customName);
1119
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);
1127 }
1128
1129 // Add timestamps to the FB_momentum extension
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 {}",
1135 timestamps.size(),
1136 motionMatrix.cols());
1137 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1138 // Store timestamps as a JSON array in the motion section
1139 // The field definition follows the format of addMotionToModel above
1140 def["motion"]["timestamps"] = std::vector<int64_t>(timestamps.begin(), timestamps.end());
1141 }
1142}
1143
1145 return impl_->document.animations.size();
1146}
1147
1149 auto& def = addMomentumExtension(impl_->document.extensionsAndExtras);
1150 constexpr auto kFpsStr = "fps";
1151 if (!def.contains(kFpsStr)) {
1152 return 0.0f;
1153 }
1154 return def[kFpsStr];
1155}
1156
1157std::vector<size_t> GltfBuilder::getCharacterMotions(const std::string& characterName) {
1158 if (impl_->characterData.count(characterName) == 0) {
1159 return {};
1160 }
1161 return impl_->characterData[characterName].animationIndices;
1162}
1163
1165 const float fps,
1166 std::span<const std::vector<momentum::Marker>> markers,
1167 const MarkerMesh markerMesh,
1168 const std::string& animName) {
1169 setFps(fps);
1170 addActorAnimationToModel(impl_->document, fps, markers, markerMesh, animName);
1171}
1172
1174 const filesystem::path& filename,
1175 const GltfFileFormat fileFormat /*= GltfFileFormat::Extension*/,
1176 bool embedResources /*= false*/) {
1177 GltfBuilder::save(impl_->document, filename, fileFormat, embedResources);
1178}
1179
1180void GltfBuilder::forceEmbedResources(fx::gltf::Document& document) {
1181 for (auto& buffer : document.buffers) {
1182 buffer.SetEmbeddedResource();
1183 }
1184}
1185
1186const fx::gltf::Document& GltfBuilder::getDocument() {
1187 return impl_->document;
1188}
1189
1191 forceEmbedResources(impl_->document);
1192}
1193
1195 fx::gltf::Document& document,
1196 const filesystem::path& filename,
1197 const GltfFileFormat fileFormat /*= GltfFileFormat::Extension*/,
1198 bool embedResources /*= false*/) {
1199 if (embedResources) {
1200 forceEmbedResources(document);
1201 }
1202 saveDocument(filename, document, fileFormat);
1203}
1204
1206 const Character& character,
1207 const float fps,
1208 std::span<const SkeletonState> skeletonStates,
1209 const std::string& customName) {
1210 setFps(fps);
1211 if (impl_->characterData.find(character.name) == impl_->characterData.end()) {
1212 // #TODO: Warn about this addition
1213 addCharacter(character);
1214 }
1215
1216 const auto& jointToNodeMap = impl_->characterData[character.name].nodeMap;
1217
1218 // add motion from skeleton states
1219 addSkeletonStatesToModel(
1220 impl_->document,
1221 character,
1222 fps,
1223 skeletonStates,
1224 jointToNodeMap,
1225 impl_->animationInterpolation,
1226 customName);
1227
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);
1235 }
1236}
1237
1238} // namespace momentum
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:
Definition checks.h:36
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.
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.
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_LOGW(...)
Definition log.h:180
#define MT_LOGE(...)
Definition log.h:181
Vector3< uint8_t > Vector3b
3D vector of unsigned bytes; commonly used for RGB color storage in momentum (see ColorArray).
Definition types.h:30
std::tuple< std::vector< std::string >, JointParameters > IdentityParameters
A tuple of skeleton joint names and identity parameters.
Definition types.h:179
Quaternion< float > Quaternionf
Definition types.h:386
JointParameters mapIdentityToCharacter(const IdentityParameters &inputIdentity, const Character &targetCharacter)
Maps the input JointParameter vector to a target character by matching joint names.
CharacterStateT< float > CharacterState
Definition fwd.h:92
Vector4< std::uint16_t > Vector4s
Definition types.h:278
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.
Definition types.h:173
Box3< float > Box3f
Definition types.h:69
int32_t createAccessorBuffer(fx::gltf::Document &model, std::span< T > data, const bool align=false, const bool normalized=false)
MeshT< float > Mesh
Definition fwd.h:20
FloatP dot(const Eigen::MatrixBase< Derived > &v1, const Vector3P< S > &v2)
Computes dot product of Eigen::Vector3f and 3-vector of packets.
Definition simd.h:191
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
Definition types.h:252
void parameterSetsToJson(const Character &character, nlohmann::json &j)
void poseConstraintsToJson(const Character &character, nlohmann::json &j)
CharacterParametersT< float > CharacterParameters
Definition types.h:168
GltfFileFormat
File format in which the character is saved.
void parameterTransformToJson(const Character &character, nlohmann::json &j)
ModelParametersT< float > ModelParameters
Definition types.h:105
gsl::span< T > span
Span type alias using gsl::span (C++17 fallback).
Definition span_compat.h:54
Vector3< std::int32_t > Vector3i
Definition types.h:293
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.
Vector< T, 3 > Vector3
Definition types.h:236
Vector3< float > Vector3f
Definition types.h:251
VectorX< float > VectorXf
Definition types.h:209
void parameterLimitsToJson(const Character &character, nlohmann::json &j)
BlendWeightsT< T > extractBlendWeights(const ParameterTransform &paramTransform, const ModelParametersT< T > &modelParams)
Extracts blend shape weights from model parameters.
MatrixX< float > MatrixXf
Definition types.h:82
int32_t createSampler(fx::gltf::Document &model, fx::gltf::Animation &anim, std::span< T > data, const std::span< float > &timestamps, GltfAnimationInterpolation interpolation)
const MatrixXf & getShapeVectors() const
const std::vector< std::string > & getShapeNames() const
Skinning class that combines blend shape vectors with a base shape.
Definition blend_shape.h:19
JointParametersT< T > offsets
The joint parameter vector representing the unique bone lengths of the character, defining the charac...
Definition types.h:165
ModelParametersT< T > pose
The model parameter vector representing the pose of the character.
Definition types.h:161
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
TransformationList inverseBindPose
Inverse of the bind pose transformations for each joint.
Definition character.h:76
LocatorList locators
Points of interest attached to joints.
Definition character.h:49
SkinWeights_u skinWeights
Defines how mesh vertices are influenced by joints.
Definition character.h:58
PhysicalProperties physicalProperties
Joint-level physical mass and inertia data loaded from model assets.
Definition character.h:67
Mesh_u mesh
3D mesh representing the character's surface
Definition character.h:55
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
std::string name
Character identifier.
Definition character.h:82
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
BlendShape_const_p blendShape
Shape variations that can be blended.
Definition character.h:70
CollisionGeometry_u collision
Collision volumes for the character.
Definition character.h:64
Unified options for saving files in both FBX and GLTF formats.
std::unordered_map< std::string, CharacterData > characterData
fx::gltf::Document document
GltfAnimationInterpolation animationInterpolation
Physical mass properties attached to one skeleton joint.
Definition joint.h:88
std::string jointName
Skeleton joint that owns this physical body.
Definition joint.h:93
std::vector< Eigen::Vector3i > texcoord_faces
List of texture coordinate indices per face Maps each face to its corresponding texture coordinates.
Definition mesh.h:55
std::vector< Eigen::Vector2f > texcoords
List of texture coordinates (UV coordinates).
Definition mesh.h:51
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
std::vector< Eigen::Vector3< T > > normals
List of vertex normals (same size as vertices when computed).
Definition mesh.h:25
std::vector< Eigen::Vector3i > faces
List of triangular faces defined by vertex indices.
Definition mesh.h:28
std::vector< Eigen::Vector3b > colors
List of per-vertex RGB colors (0-255 for each channel).
Definition mesh.h:35
Eigen::Index numJointParameters() const
Dimension of the output jointParameters vector.
Eigen::Index numBlendShapeParameters() const
Dimension of identity blendshape parameters.
JointList joints
The list of joints in this skeleton, ordered such that every joint's parent appears earlier in the li...
Definition skeleton.h:25