Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
app_utils.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
20#include <CLI/CLI.hpp>
21
22using namespace momentum;
23
24namespace momentum {
25
26void addIOOptions(CLI::App& app, std::shared_ptr<IOOptions> ioOptions) {
27 auto* inputOption =
28 app.add_option("-i,--input", ioOptions->inputFile, "Marker data file (.kbd/.glb/.c3d/.trc)");
29 inputOption->required()->check(CLI::ExistingFile);
30
31 auto* outputOption = app.add_option("-o,--output", ioOptions->outputFile, "Output glb file");
32 outputOption->required();
33}
34
35void addModelOptions(CLI::App& app, std::shared_ptr<ModelOptions> modelOptions) {
36 auto* modelOption = app.add_option(
37 "-m,--model", modelOptions->model, "Model file (.fbx/.glb -- may contain calibrated model)");
38 modelOption->required()->check(CLI::ExistingFile);
39
40 app.add_option("-p,--parameters", modelOptions->parameters, "Model parameter file (.model)");
41 app.add_option("-l,--locators", modelOptions->locators, "Marker definitions (.locators)");
42}
43
44void addCalibrationOptions(CLI::App& app, std::shared_ptr<CalibrationConfig> config) {
45 auto* debugOption =
46 app.add_option("--calib-debug", config->debug, "Save debug info for calibration");
47 debugOption->default_val(config->debug);
48
49 auto* calibFramesOption = app.add_option(
50 "--calib-frames", config->calibFrames, "Number of frames used for model calibration");
51 calibFramesOption->default_val(config->calibFrames)->check(CLI::PositiveNumber);
52
53 auto* majorIterOption =
54 app.add_option("--major-iter", config->majorIter, "Number of calibration loops to run");
55 majorIterOption->default_val(config->majorIter)->check(CLI::PositiveNumber);
56
57 auto* maxCalibIterOption = app.add_option(
58 "--max-calib-iter", config->maxIter, "Max (minor) iterations in one calibration solve");
59 maxCalibIterOption->default_val(config->maxIter)->check(CLI::PositiveNumber);
60
61 auto* minVisPercentOption = app.add_option(
62 "--min-calib-vis-percent",
63 config->minVisPercent,
64 "Minimum percentage of visible markers used for calibration");
65 minVisPercentOption->default_val(config->minVisPercent)->check(CLI::Range(0.0, 1.0));
66
67 auto* alphaOption =
68 app.add_option("--calib-loss-alpha", config->lossAlpha, "Alpha value of calibration loss");
69 alphaOption->default_val(config->lossAlpha);
70
71 auto* scaleOnlyOption = app.add_option(
72 "--global-scale-only",
73 config->globalScaleOnly,
74 "Calibrate only the global scale and not all proportions");
75 scaleOnlyOption->default_val(config->globalScaleOnly);
76
77 auto* locatorsOnlyOption =
78 app.add_option("--locators-only", config->locatorsOnly, "Calibrate only the locator offsets");
79 locatorsOnlyOption->default_val(config->locatorsOnly);
80
81 auto* greedySamplingOption = app.add_option(
82 "--greedy-sampling",
83 config->greedySampling,
84 "Use greedy sampling to select calibration frames");
85 greedySamplingOption->default_val(config->greedySampling)->check(CLI::NonNegativeNumber);
86
87 auto* enforceFloorOption = app.add_flag(
88 "--enforce-floor-in-first-frame",
89 config->enforceFloorInFirstFrame,
90 "Force all floor locators to y=0 on frame 0 with high weight");
91 enforceFloorOption->default_val(config->enforceFloorInFirstFrame);
92
93 auto* adaptiveFloorContactOption = app.add_flag(
94 "--adaptive-floor-contact",
95 config->adaptiveFloorContact,
96 "Enable adaptive per-locator floor contact detection during calibration");
97 adaptiveFloorContactOption->default_val(config->adaptiveFloorContact);
98
99 auto* poseOption = app.add_option(
100 "--init-pose",
101 config->firstFramePoseConstraintSet,
102 "Enforce pose constraints from named pose constraint set in first frame");
103 poseOption->default_val(config->firstFramePoseConstraintSet);
104}
105
106void addTrackingOptions(CLI::App& app, std::shared_ptr<TrackingConfig> config) {
107 auto* debugOption =
108 app.add_option("--tracking-debug", config->debug, "Save debug info for tracking");
109 debugOption->default_val(config->debug);
110
111 auto* alphaOption =
112 app.add_option("--tracking-loss-alpha", config->lossAlpha, "Alpha value of tracking loss");
113 alphaOption->default_val(config->lossAlpha);
114
115 auto* smoothOption =
116 app.add_option("--smoothing", config->smoothing, "Smoothing weight; 0 to disable");
117 smoothOption->default_val(config->smoothing)->check(CLI::NonNegativeNumber);
118
119 auto* collisionErrorWeightOption = app.add_option(
120 "--collision-error-weight",
121 config->collisionErrorWeight,
122 "Collision error weight, default is 0.0");
123 collisionErrorWeightOption->default_val(config->collisionErrorWeight)
124 ->check(CLI::NonNegativeNumber);
125
126 auto* maxTrackingIterOption = app.add_option(
127 "--max-tracking-iter", config->maxIter, "Max iterations for motion tracking solve");
128 maxTrackingIterOption->default_val(config->maxIter)->check(CLI::PositiveNumber);
129
130 auto* minVisPercentOption = app.add_option(
131 "--min-tracking-vis-percent",
132 config->minVisPercent,
133 "Minimum percentage of visible markers used for tracking");
134 minVisPercentOption->default_val(config->minVisPercent)->check(CLI::Range(0.0, 1.0));
135}
136
137void addRefineOptions(CLI::App& app, std::shared_ptr<RefineConfig> config) {
138 addTrackingOptions(app, config);
139
140 auto* regOption = app.add_option(
141 "--regularizer",
142 config->regularizer,
143 "Regularize time-invariant parameters to prevent large change");
144 regOption->default_val(config->regularizer)->check(CLI::NonNegativeNumber);
145
146 auto* calibIdOption =
147 app.add_option("--calib-id", config->calibId, "Calibrate identity parameters");
148 calibIdOption->default_val(config->calibId);
149
150 auto* calibLocatorsOption =
151 app.add_option("--calib-locators", config->calibLocators, "Calibrate locator offsets");
152 calibLocatorsOption->default_val(config->calibLocators);
153}
154
155std::tuple<momentum::Character, momentum::ModelParameters> loadCalibratedModel(
156 const std::string& modelFile) {
157 auto [c, m, id, fps] = loadCharacterWithMotion(modelFile);
158
159 // make sure we actually only convert joint id back to scale id parameters
160 const ModelParameters identity =
161 jointIdentityToModelIdentity(c, c.parameterTransform.getScalingParameters(), id);
162
163 return {c, identity};
164}
165
166std::tuple<momentum::Character, momentum::ModelParameters> loadCharacterWithIdentity(
167 const ModelOptions& modelFiles) {
168 Character character;
169 ModelParameters identity;
170
171 // TODO: Very hacky!
172 if (modelFiles.model.find(".glb") != std::string::npos &&
173 modelFiles.parameters
174 .empty()) { // Assume input has precomputed proportions and marker offsets etc.
175 auto [c, m, id, fps] = loadCharacterWithMotion(modelFiles.model);
176 character = c;
177 if (id.v.size() > 0) {
178 identity = jointIdentityToModelIdentity(c, c.parameterTransform.getScalingParameters(), id);
179 } else {
181 }
182
183 if (!modelFiles.locators.empty()) {
184 character.locators =
185 loadLocators(modelFiles.locators, character.skeleton, character.parameterTransform);
186 }
187 } else { // Assume input is the template
188 character = loadFullCharacter(modelFiles.model, modelFiles.parameters, modelFiles.locators);
190 }
191
192 return {character, identity};
193}
194
196 const std::string& outFile,
197 const momentum::Character& character,
198 const momentum::ModelParameters& identity,
199 Eigen::MatrixXf& finalMotion,
200 std::span<const std::vector<momentum::Marker>> markerData,
201 const double fps,
202 const bool saveMarkerMesh /*= true*/,
203 std::span<const int64_t> timestamps /*= {}*/) {
204 const filesystem::path output(outFile);
205 const auto ext = output.extension();
206
207 ModelParameters id =
209
210 // gltf io assumes the identity info is removed from the motion matrix
211 removeIdentity(character.parameterTransform.getScalingParameters(), id, finalMotion);
212 const VectorXf idVec = character.parameterTransform.apply(id).v;
213
214 if (ext == ".fbx") {
215 saveFbx(output, character, finalMotion, idVec, fps);
216 } else if (ext == ".glb" || ext == ".gltf") {
217 GltfBuilder fileBuilder;
218 fileBuilder.addMotion(
219 character,
220 fps,
221 std::make_tuple(character.parameterTransform.name, finalMotion),
222 std::make_tuple(character.skeleton.getJointNames(), idVec),
223 /*addExtensions*/ true,
224 /*customName*/ "default",
225 timestamps);
226 fileBuilder.addMarkerSequence(
227 fps,
228 markerData,
230 fileBuilder.save(outFile);
231 }
232}
233
234} // namespace momentum
Helper class to build a glb scene.
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.
void save(const filesystem::path &filename, GltfFileFormat fileFormat=GltfFileFormat::Auto, bool embedResources=false)
std::tuple< momentum::Character, momentum::ModelParameters > loadCalibratedModel(const std::string &modelFile)
void addRefineOptions(CLI::App &app, std::shared_ptr< RefineConfig > config)
void addTrackingOptions(CLI::App &app, std::shared_ptr< TrackingConfig > config)
void addIOOptions(CLI::App &app, std::shared_ptr< IOOptions > ioOptions)
Definition app_utils.cpp:26
void addCalibrationOptions(CLI::App &app, std::shared_ptr< CalibrationConfig > config)
Definition app_utils.cpp:44
Character loadFullCharacter(const std::string &characterPath, const std::string &parametersPath, const std::string &locatorsPath, LoadBlendShapes loadBlendShapes)
High level function to load a character of any type, with a local path.
void saveMotion(const std::string &outFile, const momentum::Character &character, const momentum::ModelParameters &identity, Eigen::MatrixXf &finalMotion, std::span< const std::vector< momentum::Marker > > markerData, const double fps, const bool saveMarkerMesh, std::span< const int64_t > timestamps)
Save the given character and motion to a GLB or FBX file.
void saveFbx(const filesystem::path &, const Character &, const MatrixXf &, const VectorXf &, const double, std::span< const std::vector< Marker > >, const FileSaveOptions &)
Save a character with animation to an FBX file.
Definition fbx_io.cpp:424
void removeIdentity(const ParameterSet &idSet, const ModelParameters &identity, Eigen::MatrixXf &motionWithId)
ModelParameters jointIdentityToModelIdentity(const Character &c, const ParameterSet &idSet, const JointParameters &jointIdentity)
ModelParameters extractParameters(const ModelParameters &params, const ParameterSet &parameterSet)
LocatorList loadLocators(const filesystem::path &filename, const Skeleton &skeleton, const ParameterTransform &parameterTransform)
ModelParametersT< float > ModelParameters
Definition types.h:105
std::tuple< momentum::Character, momentum::ModelParameters > loadCharacterWithIdentity(const ModelOptions &modelFiles)
VectorX< float > VectorXf
Definition types.h:209
std::tuple< Character, MatrixXf, JointParameters, float > loadCharacterWithMotion(const filesystem::path &gltfFilename)
Load a glTF character with motion from a file path.
Definition gltf_io.cpp:309
void addModelOptions(CLI::App &app, std::shared_ptr< ModelOptions > modelOptions)
Definition app_utils.cpp:35
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
LocatorList locators
Points of interest attached to joints.
Definition character.h:49
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
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
std::string locators
Definition app_utils.h:26
std::string parameters
Definition app_utils.h:25
ParameterSet getScalingParameters() const
Get a list of scaling parameters (with prefix "scale_").
JointParametersT< T > apply(const ModelParametersT< T > &parameters) const
Map model parameters to joint parameters using a linear transformation.
Eigen::Index numAllModelParameters() const
Dimension of all model parameters, including pose, scaling, marker joints, and blendshape parameters ...
std::vector< std::string > name
The list of model parameter names.
std::vector< std::string > getJointNames() const
Definition skeleton.cpp:35