Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
mmo_io.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
9
11#include "momentum/common/log.h"
12
13#include <fstream>
14#include <limits>
15
16namespace momentum {
17
19 const std::string& filename,
20 std::span<const VectorXf> poses,
21 const VectorXf& scale,
22 const Character& character) {
23 if (poses.empty() ||
24 poses[0].size() !=
25 gsl::narrow<Eigen::Index>(character.parameterTransform.numAllModelParameters())) {
26 MT_LOGW("{}: Cannot save data: motion data is either empty or of wrong dimension", __func__);
27 return;
28 }
29
30 // make sure all poses have the right size
31 MatrixXf data(poses[0].size(), poses.size());
32 for (size_t i = 0; i < poses.size(); i++) {
33 if (poses[i].size() != poses[0].size()) {
34 MT_LOGW("{}: Cannot save data: not all poses are of the same dimension", __func__);
35 return;
36 }
37
38 data.col(i) = poses[i];
39 }
40
41 saveMmo(filename, data, scale, character);
42}
43
45 const std::string& filename,
46 const MatrixXf& poses,
47 const VectorXf& scale,
48 const Character& character,
49 const MatrixXf& additionalParameters,
50 std::span<const std::string> additionalParameterNames) {
51 if (poses.rows() !=
52 gsl::narrow<Eigen::Index>(character.parameterTransform.numAllModelParameters())) {
53 MT_LOGW(
54 "{}: Cannot save data: poses are of wrong dimension. Expected: {}, actual: {}",
55 __func__,
57 poses.rows());
58 return;
59 }
60 if (scale.size() !=
61 gsl::narrow<Eigen::Index>(character.skeleton.joints.size() * kParametersPerJoint)) {
62 MT_LOGW(
63 "{}: Cannot save data: model scale is of wrong dimension. Expected: {}, actual: {}",
64 __func__,
65 character.skeleton.joints.size() * kParametersPerJoint,
66 scale.size());
67 return;
68 }
69 if (additionalParameters.rows() != gsl::narrow<Eigen::Index>(additionalParameterNames.size())) {
70 MT_LOGW(
71 "{}: Cannot save data: number of additional parameters don't match. Names: {}, data: {}",
72 __func__,
73 additionalParameterNames.size(),
74 additionalParameters.rows());
75 return;
76 }
77 if (additionalParameters.cols() != 0 && additionalParameters.cols() != poses.cols()) {
78 MT_LOGW(
79 "{}: Cannot save data: additional parameters don't match pose dimensions. Expected: {}, actual {}",
80 __func__,
81 poses.cols(),
82 additionalParameters.cols());
83 return;
84 }
85
86 // create enhance parameter list;
87 std::vector<std::string> parameterNames;
88 parameterNames.reserve(
89 character.parameterTransform.name.size() + additionalParameterNames.size());
90 for (const auto& name : character.parameterTransform.name) {
91 parameterNames.emplace_back(name);
92 }
93 for (const auto& name : additionalParameterNames) {
94 parameterNames.emplace_back("__" + name + "__");
95 }
96
97 // write out joint names
98 std::vector<std::string> jointNames;
99 for (const auto& joint : character.skeleton.joints) {
100 jointNames.emplace_back(joint.name);
101 }
102
103 // create joined pose matrix
104 MatrixXf pc = MatrixXf(poses.rows() + additionalParameters.rows(), poses.cols());
105 pc.topRows(poses.rows()) = poses;
106
107 if (additionalParameters.rows() > 0) {
108 pc.bottomRows(additionalParameters.rows()) = additionalParameters;
109 }
110
111 saveMmo(filename, pc, scale, parameterNames, jointNames);
112}
113
115 const std::string& filename,
116 const MatrixXf& poses,
117 const VectorXf& scale,
118 std::span<const std::string> parameterNames,
119 std::span<const std::string> jointNames) {
120 if (poses.rows() != gsl::narrow<Eigen::Index>(parameterNames.size())) {
121 MT_LOGW(
122 "{}: Cannot save data: poses are of wrong dimension. Expected: {}, actual: {}",
123 __func__,
124 parameterNames.size(),
125 poses.rows());
126 return;
127 }
128 if (scale.size() != gsl::narrow<Eigen::Index>(jointNames.size() * kParametersPerJoint)) {
129 MT_LOGW(
130 "{}: Cannot save data: model scale is of wrong dimension. Expected: {}, actual: {}",
131 __func__,
132 jointNames.size() * kParametersPerJoint,
133 scale.size());
134 return;
135 }
136
137 std::ofstream fs(filename, std::ios::out | std::ios::binary);
138 if (!fs.is_open()) {
139 MT_LOGW("{}: Failed to open file for writing: {}", __func__, filename);
140 return;
141 }
142 // write out sizes
143 size_t data = 0;
144 data = parameterNames.size(); // number of parameters
145 fs.write((const char*)&data, sizeof(size_t));
146
147 data = jointNames.size(); // number of joints
148 fs.write((const char*)&data, sizeof(size_t));
149
150 data = poses.cols(); // number of frames
151 fs.write((const char*)&data, sizeof(size_t));
152
153 // write out parameters names
154 for (const auto& name : parameterNames) {
155 data = name.size();
156 fs.write((const char*)&data, sizeof(size_t));
157 fs.write((const char*)name.data(), data);
158 }
159
160 // write out joint names
161 for (const auto& name : jointNames) {
162 data = name.size();
163 fs.write((const char*)&data, sizeof(size_t));
164 fs.write((const char*)name.data(), data);
165 }
166
167 // write out offsets
168 fs.write((const char*)scale.data(), scale.size() * sizeof(float));
169
170 // write out frames
171 fs.write((const char*)poses.data(), poses.size() * sizeof(float));
172}
173
174std::tuple<MatrixXf, VectorXf> mapMotionToCharacter(
175 const MatrixXf& poses,
176 const VectorXf& offsets,
177 std::span<const std::string> parameterNames,
178 std::span<const std::string> jointNames,
179 const Character& character) {
180 std::tuple<MatrixXf, VectorXf> result;
181 auto& outPoses = std::get<0>(result);
182 auto& outOffset = std::get<1>(result);
183
184 // create mapping for parameters
185 std::vector<size_t> pMap;
186 for (const auto& name : parameterNames) {
187 auto iter = std::find(
188 character.parameterTransform.name.begin(), character.parameterTransform.name.end(), name);
189 size_t index = std::distance(character.parameterTransform.name.begin(), iter);
190 if (index >= character.parameterTransform.name.size()) {
191 index = kInvalidIndex;
192 }
193 pMap.push_back(index);
194 }
195
196 // create mapping for joints
197 std::vector<size_t> jMap;
198 jMap.reserve(jointNames.size());
199 for (const auto& name : jointNames) {
200 jMap.push_back(character.skeleton.getJointIdByName(name));
201 }
202
203 // read offsets and re-arrange them according to the map
204 outOffset.setZero(character.skeleton.joints.size() * kParametersPerJoint);
205 for (size_t i = 0; i < jMap.size(); i++) {
206 if (jMap[i] != kInvalidIndex) {
207 outOffset.middleRows<kParametersPerJoint>(jMap[i] * kParametersPerJoint) =
208 offsets.middleRows<kParametersPerJoint>(i * kParametersPerJoint);
209 }
210 }
211
212 // read frames and re-arrange them according to the map
213 outPoses.setZero(character.parameterTransform.numAllModelParameters(), poses.cols());
214 for (size_t i = 0; i < pMap.size(); i++) {
215 if (pMap[i] != kInvalidIndex) {
216 outPoses.row(pMap[i]) = poses.row(i);
217 }
218 }
219
220 return result;
221}
222
223std::tuple<MatrixXf, VectorXf> loadMmo(const std::string& filename, const Character& character) {
224 const auto [iposes, iscale, pNames, jNames] = loadMmo(filename);
225 return mapMotionToCharacter(iposes, iscale, pNames, jNames, character);
226}
227
228// get auxiliary data from motion
229std::tuple<MatrixXf, std::vector<std::string>> getAuxiliaryDataFromMotion(
230 const MatrixXf& poses,
231 std::span<const std::string> parameterNames) {
232 std::tuple<MatrixXf, std::vector<std::string>> result;
233 auto& values = std::get<0>(result);
234 auto& names = std::get<1>(result);
235
236 std::vector<size_t> map;
237 for (size_t i = 0; i < parameterNames.size(); i++) {
238 const auto& n = parameterNames[i];
239 const auto l = n.length();
240 if (n.size() > 4 && n[0] == '_' && n[1] == '_' && n[l - 1] == '_' && n[l - 2] == '_') {
241 map.push_back(i);
242 names.push_back(n.substr(2, l - 4));
243 }
244 }
245
246 values.resize(gsl::narrow<Eigen::Index>(names.size()), poses.cols());
247 for (size_t i = 0; i < map.size(); i++) {
248 values.row(i) = poses.row(map[i]);
249 }
250
251 return result;
252}
253
254std::tuple<MatrixXf, VectorXf, std::vector<std::string>, std::vector<std::string>> loadMmo(
255 const std::string& filename) {
256 std::tuple<MatrixXf, VectorXf, std::vector<std::string>, std::vector<std::string>> result;
257 auto& poses = std::get<0>(result);
258 auto& scale = std::get<1>(result);
259 auto& parameterNames = std::get<2>(result);
260 auto& jointNames = std::get<3>(result);
261
262 std::ifstream fs(filename, std::ios::in | std::ios::binary);
263
264 if (!fs.is_open()) {
265 MT_LOGW("{}: Failed to open file {}", __func__, filename);
266 return result;
267 }
268
269 // read total number frames/joints/offsets
270 size_t nParams = 0;
271 size_t nJoints = 0;
272 size_t nFrames = 0;
273 fs.read((char*)&nParams, sizeof(size_t));
274 fs.read((char*)&nJoints, sizeof(size_t));
275 fs.read((char*)&nFrames, sizeof(size_t));
276
277 if (!fs.good()) {
278 MT_LOGW("{}: Failed to read header from file {}", __func__, filename);
279 return result;
280 }
281
282 // Validate sizes to prevent excessive allocation from malformed files
283 constexpr size_t kMaxDimension = 10'000'000;
284 constexpr size_t kMaxStringLength = 10'000;
285 if (nParams > kMaxDimension || nJoints > kMaxDimension || nFrames > kMaxDimension) {
286 MT_LOGW(
287 "{}: Unreasonable dimensions in file {}: nParams={}, nJoints={}, nFrames={}",
288 __func__,
289 filename,
290 nParams,
291 nJoints,
292 nFrames);
293 return result;
294 }
295
296 // Guard against integer overflow in size calculations
297 if (nJoints > std::numeric_limits<size_t>::max() / kParametersPerJoint) {
298 MT_LOGW("{}: Integer overflow in scale size for file {}", __func__, filename);
299 return result;
300 }
301 if (nParams != 0 && nFrames != 0 && nParams > std::numeric_limits<size_t>::max() / nFrames) {
302 MT_LOGW("{}: Integer overflow in pose matrix size for file {}", __func__, filename);
303 return result;
304 }
305
306 // load parameter names
307 for (size_t i = 0; i < nParams; i++) {
308 // read parameter name
309 size_t count = 0;
310 fs.read((char*)&count, sizeof(size_t));
311 if (!fs.good() || count > kMaxStringLength) {
312 MT_LOGW("{}: Invalid parameter name length in file {}", __func__, filename);
313 return result;
314 }
315 std::string name;
316 name.resize(count);
317 fs.read((char*)name.data(), count);
318 if (!fs.good()) {
319 MT_LOGW("{}: Failed to read parameter name data from file {}", __func__, filename);
320 return result;
321 }
322 parameterNames.push_back(name);
323 }
324
325 // load joint names
326 for (size_t i = 0; i < nJoints; i++) {
327 // read joint name
328 size_t count = 0;
329 fs.read((char*)&count, sizeof(size_t));
330 if (!fs.good() || count > kMaxStringLength) {
331 MT_LOGW("{}: Invalid joint name length in file {}", __func__, filename);
332 return result;
333 }
334 std::string name;
335 name.resize(count);
336 fs.read((char*)name.data(), count);
337 if (!fs.good()) {
338 MT_LOGW("{}: Failed to read joint name data from file {}", __func__, filename);
339 return result;
340 }
341 jointNames.push_back(name);
342 }
343
344 // read offsets and re-arrange them according to the map
345 scale = VectorXf(nJoints * kParametersPerJoint);
346 fs.read((char*)scale.data(), scale.size() * sizeof(float));
347 if (!fs.good()) {
348 MT_LOGW("{}: Failed to read scale data from file {}", __func__, filename);
349 return result;
350 }
351
352 // read frames and re-arrange them according to the map
353 poses = MatrixXf(nParams, nFrames);
354 fs.read((char*)poses.data(), poses.size() * sizeof(float));
355 if (!fs.good()) {
356 MT_LOGW("{}: Failed to read pose data from file {}", __func__, filename);
357 return result;
358 }
359
360 return result;
361}
362
363} // namespace momentum
#define MT_LOGW(...)
Definition log.h:180
std::tuple< MatrixXf, VectorXf > loadMmo(const std::string &filename, const Character &character)
Load motion data and map to character parameter space.
Definition mmo_io.cpp:223
std::tuple< MatrixXf, std::vector< std::string > > getAuxiliaryDataFromMotion(const MatrixXf &poses, std::span< const std::string > parameterNames)
Extract auxiliary data from motion parameters.
Definition mmo_io.cpp:229
void saveMmo(const std::string &filename, std::span< const VectorXf > poses, const VectorXf &scale, const Character &character)
Save motion data using character parameter mapping.
Definition mmo_io.cpp:18
MatrixXf mapMotionToCharacter(const MotionParameters &inputMotion, const Character &targetCharacter)
Maps the input ModelParameter motion to a target character by matching model parameter names.
constexpr size_t kParametersPerJoint
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
VectorX< float > VectorXf
Definition types.h:209
MatrixX< float > MatrixXf
Definition types.h:82
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
Skeleton skeleton
Skeletal structure defining the character's joints and hierarchy.
Definition character.h:36
ParameterTransform parameterTransform
Maps model parameters to joint parameters.
Definition character.h:39
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.
size_t getJointIdByName(std::string_view name) const
Returns the index of a joint with the given name, or kInvalidIndex if not found.
Definition skeleton.cpp:25
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