Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
bvh_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
17
18#include <Eigen/Geometry>
19
20#include <cstring>
21#include <fstream>
22#include <iomanip>
23#include <sstream>
24#include <stack>
25#include <string>
26#include <vector>
27
28namespace momentum {
29
30namespace {
31
32// Represents a BVH channel type
33enum class BvhChannel { Xposition, Yposition, Zposition, Xrotation, Yrotation, Zrotation };
34
35// Internal representation of a BVH joint during parsing
36struct BvhJointData {
37 std::string name;
38 size_t parentIndex{0};
39 Vector3f offset;
40 std::vector<BvhChannel> channels;
41 size_t channelOffset{0}; // Starting index in the motion data row
42};
43
44// Trim leading and trailing whitespace from a string
45std::string trim(const std::string& s) {
46 const auto start = s.find_first_not_of(" \t\r\n");
47 if (start == std::string::npos) {
48 return "";
49 }
50 const auto end = s.find_last_not_of(" \t\r\n");
51 return s.substr(start, end - start + 1);
52}
53
54// Parse the BVH channel type from a string
55BvhChannel parseChannelType(const std::string& token) {
56 if (token == "Xposition") {
57 return BvhChannel::Xposition;
58 } else if (token == "Yposition") {
59 return BvhChannel::Yposition;
60 } else if (token == "Zposition") {
61 return BvhChannel::Zposition;
62 } else if (token == "Xrotation") {
63 return BvhChannel::Xrotation;
64 } else if (token == "Yrotation") {
65 return BvhChannel::Yrotation;
66 } else if (token == "Zrotation") {
67 return BvhChannel::Zrotation;
68 } else {
69 MT_THROW("Unknown BVH channel type: {}", token);
70 }
71}
72
73// Returns the BVH channel name string
74const char* channelTypeName(BvhChannel ch) {
75 switch (ch) {
76 case BvhChannel::Xposition:
77 return "Xposition";
78 case BvhChannel::Yposition:
79 return "Yposition";
80 case BvhChannel::Zposition:
81 return "Zposition";
82 case BvhChannel::Xrotation:
83 return "Xrotation";
84 case BvhChannel::Yrotation:
85 return "Yrotation";
86 case BvhChannel::Zrotation:
87 return "Zrotation";
88 }
89 MT_THROW("Invalid BVH channel: {}", static_cast<int>(ch));
90}
91
92// Returns the Eigen axis index for a rotation channel (0=X, 1=Y, 2=Z)
93int rotationAxisIndex(BvhChannel ch) {
94 switch (ch) {
95 case BvhChannel::Xrotation:
96 return 0;
97 case BvhChannel::Yrotation:
98 return 1;
99 case BvhChannel::Zrotation:
100 return 2;
101 case BvhChannel::Xposition:
102 case BvhChannel::Yposition:
103 case BvhChannel::Zposition:
104 MT_THROW("Not a rotation channel");
105 }
106 MT_THROW("Invalid BVH channel: {}", static_cast<int>(ch));
107}
108
109// Returns the joint parameter index for a position channel (TX=0, TY=1, TZ=2)
110int positionParameterIndex(BvhChannel ch) {
111 switch (ch) {
112 case BvhChannel::Xposition:
113 return TX;
114 case BvhChannel::Yposition:
115 return TY;
116 case BvhChannel::Zposition:
117 return TZ;
118 case BvhChannel::Xrotation:
119 case BvhChannel::Yrotation:
120 case BvhChannel::Zrotation:
121 MT_THROW("Not a position channel");
122 }
123 MT_THROW("Invalid BVH channel: {}", static_cast<int>(ch));
124}
125
126bool isRotationChannel(BvhChannel ch) {
127 return ch == BvhChannel::Xrotation || ch == BvhChannel::Yrotation || ch == BvhChannel::Zrotation;
128}
129
130bool isPositionChannel(BvhChannel ch) {
131 return ch == BvhChannel::Xposition || ch == BvhChannel::Yposition || ch == BvhChannel::Zposition;
132}
133
134struct BvhParseResult {
135 std::vector<BvhJointData> joints;
136 size_t totalChannels{0};
137 std::vector<VectorXf> frames;
138 float fps{30.0f};
139};
140
141// ---------------------------------------------------------------------------
142// Hierarchy parsing helpers
143// ---------------------------------------------------------------------------
144
145// Process a joint definition line (ROOT or JOINT keyword)
146void parseJointDefinition(
147 std::istringstream& iss,
148 std::stack<size_t>& jointStack,
149 BvhParseResult& result) {
150 std::string jointName;
151 iss >> jointName;
152 MT_THROW_IF(jointName.empty(), "BVH joint name is empty");
153
154 BvhJointData joint;
155 joint.name = jointName;
156 joint.parentIndex = jointStack.empty() ? kInvalidIndex : jointStack.top();
157 joint.offset = Vector3f::Zero();
158 joint.channelOffset = result.totalChannels;
159
160 const size_t jointIndex = result.joints.size();
161 result.joints.push_back(joint);
162 jointStack.push(jointIndex);
163}
164
165// Process an OFFSET line
166void parseOffset(std::istringstream& iss, std::stack<size_t>& jointStack, BvhParseResult& result) {
167 float x = 0.0f;
168 float y = 0.0f;
169 float z = 0.0f;
170 iss >> x >> y >> z;
171 // Only apply offset to real joints (not End Sites)
172 if (jointStack.empty() || jointStack.top() == kInvalidIndex) {
173 return;
174 }
175 const auto topIdx = jointStack.top();
176 if (topIdx < result.joints.size()) {
177 result.joints[topIdx].offset = Vector3f(x, y, z);
178 }
179}
180
181// Process a CHANNELS line
182void parseChannels(
183 std::istringstream& iss,
184 std::stack<size_t>& jointStack,
185 BvhParseResult& result) {
186 int numChannels = 0;
187 iss >> numChannels;
189 jointStack.empty() || jointStack.top() == kInvalidIndex ||
190 jointStack.top() >= result.joints.size(),
191 "CHANNELS found outside of a joint definition");
192 const auto topIdx = jointStack.top();
193 MT_THROW_IF(topIdx >= result.joints.size(), "Joint index out of range");
194 auto& joint = result.joints[topIdx];
195 for (int i = 0; i < numChannels; ++i) {
196 std::string channelName;
197 iss >> channelName;
198 joint.channels.push_back(parseChannelType(channelName));
199 result.totalChannels++;
200 }
201}
202
203// Parse the HIERARCHY section of a BVH stream
204void parseBvhHierarchy(std::istream& stream, BvhParseResult& result) {
205 std::string line;
206 std::stack<size_t> jointStack;
207
208 while (stream) {
209 GetLineCrossPlatform(stream, line);
210 const std::string trimmedLine = trim(line);
211 if (trimmedLine.empty()) {
212 continue;
213 }
214
215 std::istringstream iss(trimmedLine);
216 std::string keyword;
217 iss >> keyword;
218
219 if (keyword == "ROOT" || keyword == "JOINT") {
220 parseJointDefinition(iss, jointStack, result);
221 } else if (keyword == "End") {
222 // End Site - push a sentinel value
223 jointStack.push(kInvalidIndex);
224 } else if (keyword == "OFFSET") {
225 parseOffset(iss, jointStack, result);
226 } else if (keyword == "CHANNELS") {
227 parseChannels(iss, jointStack, result);
228 } else if (keyword == "{") {
229 continue;
230 } else if (keyword == "}") {
231 MT_THROW_IF(jointStack.empty(), "Unexpected closing brace in BVH hierarchy");
232 jointStack.pop();
233 } else if (keyword == "MOTION") {
234 // Transition to motion section
235 return;
236 }
237 }
238}
239
240// Parse the MOTION section of a BVH stream
241void parseBvhMotion(std::istream& stream, BvhParseResult& result) {
242 std::string line;
243
244 while (stream) {
245 GetLineCrossPlatform(stream, line);
246 const std::string trimmedLine = trim(line);
247 if (trimmedLine.empty()) {
248 continue;
249 }
250
251 std::istringstream iss(trimmedLine);
252 std::string keyword;
253 iss >> keyword;
254
255 if (keyword == "Frames:") {
256 size_t numFrames = 0;
257 iss >> numFrames;
258 result.frames.reserve(numFrames);
259 } else if (keyword == "Frame") {
260 // "Frame Time: X.XXXX"
261 std::string timeKeyword;
262 float frameTime = 0.0f;
263 iss >> timeKeyword >> frameTime;
264 if (frameTime > 0.0f) {
265 result.fps = 1.0f / frameTime;
266 }
267 } else {
268 // Motion data line - parse all channel values
269 std::istringstream dataIss(trimmedLine);
270 VectorXf frameData(result.totalChannels);
271 for (size_t i = 0; i < result.totalChannels; ++i) {
272 MT_THROW_IF(!dataIss, "Unexpected end of motion data line");
273 dataIss >> frameData[i];
274 }
275 result.frames.push_back(frameData);
276 }
277 }
278}
279
280// Parse the hierarchy and motion sections from a BVH stream
281BvhParseResult parseBvhStream(std::istream& stream) {
282 BvhParseResult result;
283
284 // Find the HIERARCHY keyword
285 std::string line;
286 while (stream) {
287 GetLineCrossPlatform(stream, line);
288 const std::string trimmedLine = trim(line);
289 if (trimmedLine == "HIERARCHY") {
290 break;
291 }
292 }
293
294 parseBvhHierarchy(stream, result);
295 parseBvhMotion(stream, result);
296
297 MT_THROW_IF(result.joints.empty(), "No joints found in BVH file");
298
299 return result;
300}
301
302// ---------------------------------------------------------------------------
303// Motion conversion helpers (load direction: BVH -> Momentum)
304// ---------------------------------------------------------------------------
305
306// Convert BVH channel values to a Momentum rotation quaternion for a single joint
307Quaternionf convertBvhRotationToQuaternion(
308 const BvhJointData& bvhJoint,
309 const VectorXf& frameData) {
310 Quaternionf q = Quaternionf::Identity();
311 for (size_t chIdx = 0; chIdx < bvhJoint.channels.size(); ++chIdx) {
312 const auto ch = bvhJoint.channels[chIdx];
313 if (!isRotationChannel(ch)) {
314 continue;
315 }
316 const auto dataIdx = static_cast<Eigen::Index>(bvhJoint.channelOffset + chIdx);
317 const float angleRad = frameData[dataIdx] * pi<float>() / 180.0f;
318 q = q * Quaternionf(Eigen::AngleAxisf(angleRad, Vector3f::Unit(rotationAxisIndex(ch))));
319 }
320 return q;
321}
322
323// Map a single BVH joint's channel values to Momentum model parameters for one frame
324void mapBvhJointToModelParams(
325 const BvhJointData& bvhJoint,
326 const VectorXf& frameData,
327 Eigen::Index jointParamBase,
328 Eigen::Index frameIdx,
329 MatrixXf& motion) {
330 // Map position channels directly
331 for (size_t chIdx = 0; chIdx < bvhJoint.channels.size(); ++chIdx) {
332 const auto ch = bvhJoint.channels[chIdx];
333 if (!isPositionChannel(ch)) {
334 continue;
335 }
336 const auto dataIdx = static_cast<Eigen::Index>(bvhJoint.channelOffset + chIdx);
337 motion(jointParamBase + positionParameterIndex(ch), frameIdx) = frameData[dataIdx];
338 }
339
340 // Convert BVH rotation to Momentum's ZYX convention
341 const Quaternionf q = convertBvhRotationToQuaternion(bvhJoint, frameData);
342 if (!q.isApprox(Quaternionf::Identity())) {
343 // Decompose into Momentum's Extrinsic XYZ convention: [rx, ry, rz]
344 const Vector3f eulerAngles =
346 motion(jointParamBase + RX, frameIdx) = eulerAngles[0];
347 motion(jointParamBase + RY, frameIdx) = eulerAngles[1];
348 motion(jointParamBase + RZ, frameIdx) = eulerAngles[2];
349 }
350}
351
352// Build a Character from BVH joint data using an identity ParameterTransform
353Character buildCharacterFromBvh(const std::vector<BvhJointData>& bvhJoints) {
354 Skeleton skeleton;
355 skeleton.joints.reserve(bvhJoints.size());
356
357 std::vector<std::string> jointNames;
358 jointNames.reserve(bvhJoints.size());
359
360 for (const auto& bvhJoint : bvhJoints) {
361 Joint joint;
362 joint.name = bvhJoint.name;
363 joint.parent = bvhJoint.parentIndex;
364 joint.preRotation = Quaternionf::Identity();
365 joint.translationOffset = bvhJoint.offset;
366 skeleton.joints.push_back(joint);
367 jointNames.push_back(bvhJoint.name);
368 }
369
370 auto parameterTransform = ParameterTransform::identity(jointNames);
371
372 return {skeleton, parameterTransform};
373}
374
375// Map BVH motion frames to model parameters
376// Each frame is converted to a vector of 7*numJoints parameters
377MatrixXf mapBvhMotion(
378 const std::vector<BvhJointData>& bvhJoints,
379 const std::vector<VectorXf>& frames,
380 size_t numJoints) {
381 const auto numModelParams = static_cast<Eigen::Index>(numJoints * kParametersPerJoint);
382 const auto numFrames = static_cast<Eigen::Index>(frames.size());
383
384 MatrixXf motion = MatrixXf::Zero(numModelParams, numFrames);
385
386 for (Eigen::Index frameIdx = 0; frameIdx < numFrames; ++frameIdx) {
387 for (size_t jointIdx = 0; jointIdx < bvhJoints.size(); ++jointIdx) {
388 const auto jointParamBase = static_cast<Eigen::Index>(jointIdx * kParametersPerJoint);
389 mapBvhJointToModelParams(
390 bvhJoints[jointIdx], frames[frameIdx], jointParamBase, frameIdx, motion);
391 }
392 }
393
394 return motion;
395}
396
397std::tuple<Character, MotionParameters, float> loadBvhFromStream(std::istream& stream) {
398 auto parseResult = parseBvhStream(stream);
399
400 Character character = buildCharacterFromBvh(parseResult.joints);
401
402 MatrixXf motion = mapBvhMotion(parseResult.joints, parseResult.frames, parseResult.joints.size());
403
404 MotionParameters motionParams = std::make_tuple(character.parameterTransform.name, motion);
405
406 return std::make_tuple(std::move(character), std::move(motionParams), parseResult.fps);
407}
408
409// ---------------------------------------------------------------------------
410// Save helpers (Momentum -> BVH)
411// ---------------------------------------------------------------------------
412
413// Build BvhJointData from a Character's skeleton, using the standard BVH channel layout:
414// Root joint gets 6 channels (Xposition, Yposition, Zposition, Zrotation, Xrotation, Yrotation),
415// non-root joints get 3 rotation channels (Zrotation, Xrotation, Yrotation).
416std::vector<BvhJointData> buildBvhJointsFromCharacter(const Character& character) {
417 const auto& skeleton = character.skeleton;
418 std::vector<BvhJointData> bvhJoints;
419 bvhJoints.reserve(skeleton.joints.size());
420
421 size_t channelOffset = 0;
422 for (const auto& joint : skeleton.joints) {
423 BvhJointData bvhJoint;
424 bvhJoint.name = joint.name;
425 bvhJoint.parentIndex = joint.parent;
426 bvhJoint.offset = joint.translationOffset;
427 bvhJoint.channelOffset = channelOffset;
428
429 if (joint.parent == kInvalidIndex) {
430 // Root joint: position + rotation channels
431 bvhJoint.channels = {
432 BvhChannel::Xposition,
433 BvhChannel::Yposition,
434 BvhChannel::Zposition,
435 BvhChannel::Zrotation,
436 BvhChannel::Xrotation,
437 BvhChannel::Yrotation};
438 channelOffset += 6;
439 } else {
440 // Non-root joint: rotation channels only
441 bvhJoint.channels = {BvhChannel::Zrotation, BvhChannel::Xrotation, BvhChannel::Yrotation};
442 channelOffset += 3;
443 }
444
445 bvhJoints.push_back(std::move(bvhJoint));
446 }
447
448 return bvhJoints;
449}
450
451// Collect children for each joint in the skeleton
452std::vector<std::vector<size_t>> buildChildMap(const Skeleton& skeleton) {
453 const auto numJoints = skeleton.joints.size();
454 std::vector<std::vector<size_t>> children(numJoints);
455 for (size_t i = 0; i < numJoints; ++i) {
456 const auto parent = skeleton.joints[i].parent;
457 if (parent != kInvalidIndex && parent < numJoints) {
458 children[parent].push_back(i);
459 }
460 }
461 return children;
462}
463
464// Write a single joint and its subtree recursively
465void writeBvhJoint(
466 std::ostream& stream,
467 const Skeleton& skeleton,
468 const std::vector<BvhJointData>& bvhJoints,
469 const std::vector<std::vector<size_t>>& children,
470 size_t jointIdx,
471 int depth) {
472 MT_THROW_IF(jointIdx >= skeleton.joints.size(), "Joint index out of range");
473 const auto depthSz = static_cast<std::string::size_type>(depth);
474 const auto indent = std::string(depthSz * 2, ' ');
475 const auto innerIndent = std::string((depthSz + 1) * 2, ' ');
476
477 // Write joint header
478 if (skeleton.joints[jointIdx].parent == kInvalidIndex) {
479 stream << "ROOT " << skeleton.joints[jointIdx].name << "\n";
480 } else {
481 stream << indent << "JOINT " << skeleton.joints[jointIdx].name << "\n";
482 }
483 stream << indent << "{\n";
484
485 // Write offset
486 const auto& offset = bvhJoints[jointIdx].offset;
487 stream << innerIndent << "OFFSET " << std::fixed << std::setprecision(4) << offset[0] << " "
488 << offset[1] << " " << offset[2] << "\n";
489
490 // Write channels
491 const auto& channels = bvhJoints[jointIdx].channels;
492 stream << innerIndent << "CHANNELS " << channels.size();
493 for (const auto& ch : channels) {
494 stream << " " << channelTypeName(ch);
495 }
496 stream << "\n";
497
498 if (children[jointIdx].empty()) {
499 // Leaf joint: write an End Site with zero offset
500 stream << innerIndent << "End Site\n";
501 stream << innerIndent << "{\n";
502 stream << std::string((depthSz + 2) * 2, ' ') << "OFFSET 0.0000 0.0000 0.0000\n";
503 stream << innerIndent << "}\n";
504 } else {
505 // Recurse into children
506 for (const auto childIdx : children[jointIdx]) {
507 writeBvhJoint(stream, skeleton, bvhJoints, children, childIdx, depth + 1);
508 }
509 }
510
511 stream << indent << "}\n";
512}
513
514// Write the HIERARCHY section of a BVH file to a stream
515void writeBvhHierarchy(
516 std::ostream& stream,
517 const Character& character,
518 const std::vector<BvhJointData>& bvhJoints) {
519 const auto& skeleton = character.skeleton;
520 stream << "HIERARCHY\n";
521
522 const auto children = buildChildMap(skeleton);
523
524 // Find and write root joints
525 for (size_t i = 0; i < skeleton.joints.size(); ++i) {
526 if (skeleton.joints[i].parent == kInvalidIndex) {
527 writeBvhJoint(stream, skeleton, bvhJoints, children, i, 0);
528 }
529 }
530}
531
532// Convert Momentum model parameters to BVH channel values for one frame
533VectorXf convertModelParamsToBvhFrame(
534 const std::vector<BvhJointData>& bvhJoints,
535 const MatrixXf& motion,
536 Eigen::Index frameIdx) {
537 // Count total channels
538 size_t totalChannels = 0;
539 for (const auto& joint : bvhJoints) {
540 totalChannels += joint.channels.size();
541 }
542
543 VectorXf frameData = VectorXf::Zero(totalChannels);
544
545 for (size_t jointIdx = 0; jointIdx < bvhJoints.size(); ++jointIdx) {
546 const auto& bvhJoint = bvhJoints[jointIdx];
547 const auto jointParamBase = static_cast<Eigen::Index>(jointIdx * kParametersPerJoint);
548
549 // Get Momentum rotation values (rx, ry, rz in radians)
550 const float rx = motion(jointParamBase + RX, frameIdx);
551 const float ry = motion(jointParamBase + RY, frameIdx);
552 const float rz = motion(jointParamBase + RZ, frameIdx);
553
554 // Convert Momentum ZYX rotation to quaternion: R = Rz(rz) * Ry(ry) * Rx(rx)
555 const Quaternionf q = Quaternionf(Eigen::AngleAxisf(rz, Vector3f::UnitZ())) *
556 Quaternionf(Eigen::AngleAxisf(ry, Vector3f::UnitY())) *
557 Quaternionf(Eigen::AngleAxisf(rx, Vector3f::UnitX()));
558
559 // Collect rotation and position channel indices
560 std::vector<int> rotAxes;
561 std::vector<size_t> rotChannelIndices;
562 for (size_t chIdx = 0; chIdx < bvhJoint.channels.size(); ++chIdx) {
563 const auto ch = bvhJoint.channels[chIdx];
564 if (isRotationChannel(ch)) {
565 rotAxes.push_back(rotationAxisIndex(ch));
566 rotChannelIndices.push_back(bvhJoint.channelOffset + chIdx);
567 } else if (isPositionChannel(ch)) {
568 const auto dataIdx = static_cast<Eigen::Index>(bvhJoint.channelOffset + chIdx);
569 frameData[dataIdx] = motion(jointParamBase + positionParameterIndex(ch), frameIdx);
570 }
571 }
572
573 if (rotAxes.size() == 3 && rotChannelIndices.size() == 3) {
574 // Decompose the quaternion into Euler angles matching the BVH channel order
575 const Vector3f angles = rotationMatrixToEuler(
576 q.toRotationMatrix(), rotAxes[0], rotAxes[1], rotAxes[2], EulerConvention::Intrinsic);
577
578 const float rad2deg = 180.0f / pi<float>();
579 for (size_t k = 0; k < 3; ++k) {
580 frameData[rotChannelIndices[k]] = angles[k] * rad2deg;
581 }
582 }
583 }
584
585 return frameData;
586}
587
588// Write the MOTION section of a BVH file to a stream
589void writeBvhMotion(
590 std::ostream& stream,
591 const std::vector<BvhJointData>& bvhJoints,
592 const MatrixXf& motion,
593 float fps) {
594 MT_THROW_IF(fps <= 0.0f, "fps must be positive for BVH export");
595
596 const auto numFrames = motion.cols();
597
598 stream << "MOTION\n";
599 stream << "Frames: " << numFrames << "\n";
600 stream << "Frame Time: " << std::fixed << std::setprecision(6) << (1.0f / fps) << "\n";
601
602 for (Eigen::Index frameIdx = 0; frameIdx < numFrames; ++frameIdx) {
603 const VectorXf frameData = convertModelParamsToBvhFrame(bvhJoints, motion, frameIdx);
604
605 for (Eigen::Index i = 0; i < frameData.size(); ++i) {
606 if (i > 0) {
607 stream << " ";
608 }
609 stream << std::fixed << std::setprecision(4) << frameData[i];
610 }
611 stream << "\n";
612 }
613}
614
615// Write a Character with motion to a BVH stream
616void saveBvhToStream(
617 std::ostream& stream,
618 const Character& character,
619 const MatrixXf& motion,
620 float fps) {
621 const auto bvhJoints = buildBvhJointsFromCharacter(character);
622
623 writeBvhHierarchy(stream, character, bvhJoints);
624 writeBvhMotion(stream, bvhJoints, motion, fps);
625}
626
627} // namespace
628
629Character loadBvhCharacter(const filesystem::path& filepath) {
630 std::ifstream stream(filepath);
631 MT_THROW_IF(!stream.is_open(), "Failed to open BVH file: {}", filepath.string());
632 auto [character, motionParams, fps] = loadBvhFromStream(stream);
633 return character;
634}
635
636Character loadBvhCharacter(std::span<const std::byte> bytes) {
637 ispanstream stream(bytes);
638 auto [character, motionParams, fps] = loadBvhFromStream(stream);
639 return character;
640}
641
642std::tuple<Character, MotionParameters, float> loadBvhCharacterWithMotion(
643 const filesystem::path& filepath) {
644 std::ifstream stream(filepath);
645 MT_THROW_IF(!stream.is_open(), "Failed to open BVH file: {}", filepath.string());
646 return loadBvhFromStream(stream);
647}
648
649std::tuple<Character, MotionParameters, float> loadBvhCharacterWithMotion(
650 std::span<const std::byte> bytes) {
651 ispanstream stream(bytes);
652 return loadBvhFromStream(stream);
653}
654
655void saveBvhCharacter(const filesystem::path& filepath, const Character& character) {
656 std::ofstream stream(filepath);
657 MT_THROW_IF(!stream.is_open(), "Failed to open BVH file for writing: {}", filepath.string());
658
659 // Write with zero motion (single frame, all zeros)
660 const auto numParams =
661 static_cast<Eigen::Index>(character.skeleton.joints.size() * kParametersPerJoint);
662 MatrixXf motion = MatrixXf::Zero(numParams, 1);
663 saveBvhToStream(stream, character, motion, 30.0f);
664}
665
667 const filesystem::path& filepath,
668 const Character& character,
669 const MotionParameters& motionParams,
670 float fps) {
671 std::ofstream stream(filepath);
672 MT_THROW_IF(!stream.is_open(), "Failed to open BVH file for writing: {}", filepath.string());
673
674 const auto& [paramNames, motion] = motionParams;
675 saveBvhToStream(stream, character, motion, fps);
676}
677
678std::vector<std::byte> saveBvhCharacterWithMotion(
679 const Character& character,
680 const MotionParameters& motionParams,
681 float fps) {
682 const auto& [paramNames, motion] = motionParams;
683
684 std::ostringstream oss;
685 saveBvhToStream(oss, character, motion, fps);
686
687 const std::string str = oss.str();
688 std::vector<std::byte> bytes(str.size());
689 std::memcpy(bytes.data(), str.data(), str.size());
690 return bytes;
691}
692
693} // namespace momentum
#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
void saveBvhCharacter(const filesystem::path &filepath, const Character &character)
Saves a character to a BVH file with a single rest-pose frame.
Definition bvh_io.cpp:655
SkeletonT< float > Skeleton
Definition fwd.h:263
Vector3< T > rotationMatrixToEuler(const Matrix3< T > &m, int axis0, int axis1, int axis2, EulerConvention convention)
Converts rotation matrix to Euler angles.
Definition utility.cpp:187
StringType trim(const StringType &text, const char *whiteChars)
Returns a copy of the string with leading and trailing characters in whiteChars removed.
Definition string.cpp:16
Quaternion< float > Quaternionf
Definition types.h:386
Vector3< T > rotationMatrixToEulerXYZ(const Matrix3< T > &m, EulerConvention convention)
An optimized version of rotationMatrixToEuler(m, 0, 1, 2, convention) or rotationMatrixToEuler(m,...
Definition utility.cpp:201
Character loadBvhCharacter(const filesystem::path &filepath)
Loads a character from a BVH (BioVision Hierarchy) file.
Definition bvh_io.cpp:629
@ TY
Definition types.h:22
@ TZ
Definition types.h:22
@ TX
Definition types.h:22
@ RX
Definition types.h:22
@ RZ
Definition types.h:22
@ RY
Definition types.h:22
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
@ Extrinsic
The extrinsic convention.
Definition utility.h:178
@ Intrinsic
The intrinsic convention.
Definition utility.h:169
std::istream & GetLineCrossPlatform(std::istream &is, std::string &line)
Reads a line from the input stream, handling line endings for different platforms.
constexpr size_t kParametersPerJoint
Definition types.h:21
JointT< float > Joint
Definition fwd.h:206
void saveBvhCharacterWithMotion(const filesystem::path &filepath, const Character &character, const MotionParameters &motionParams, float fps)
Saves a character with motion data to a BVH file.
Definition bvh_io.cpp:666
std::tuple< Character, MotionParameters, float > loadBvhCharacterWithMotion(const filesystem::path &filepath)
Loads a character with motion data from a BVH (BioVision Hierarchy) file.
Definition bvh_io.cpp:642
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector3< float > Vector3f
Definition types.h:251
VectorX< float > VectorXf
Definition types.h:209
constexpr T pi() noexcept
Returns the mathematical constant pi.
Definition constants.h:50
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
static ParameterTransformT< float > identity(momentum::span< const std::string > jointNames)
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
istream that takes a span of const bytes as input.