Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
c3d_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"
14
15#include <ezc3d/ezc3d_all.h>
16
17#include <optional>
18#include <set>
19#include <unordered_map>
20
21namespace momentum {
22
23namespace {
24
25// Parse markerLabelIn and find the actor name string.
26// For a named actor, the marker label format can be actor:marker or actor_marker (could have more
27// possibilities); for an unnamed actor, it's simply the marker name. There could be multiple named
28// actor in a session and/or an unamed actor.
29std::string findSubjectName(const std::string& markerLabelIn) {
30 constexpr auto kNamespaceSep = ':';
31 auto sepPos = markerLabelIn.find(kNamespaceSep);
32 if (sepPos == std::string::npos) {
33 constexpr auto kUnderscoreSep = "_";
34 sepPos = markerLabelIn.find_last_of(kUnderscoreSep);
35 if (sepPos != std::string::npos) {
36 // If candidate name is side indicator, do not use as subject name.
37 auto candidateName = markerLabelIn.substr(0, sepPos);
38 std::transform(candidateName.begin(), candidateName.end(), candidateName.begin(), ::tolower);
39 const std::set<std::string> kSideStrSet = {"l", "r", "left", "right"};
40 if (kSideStrSet.find(candidateName) != kSideStrSet.end()) {
41 return {};
42 }
43 } else {
44 return {};
45 }
46 }
47
48 return markerLabelIn.substr(0, sepPos);
49}
50
51bool isMarkerValid(const std::string_view label, std::span<const std::string> validMarkerNames) {
52 // there might be dangling markers with suffix, eg.
53 // an official label "T10", but also "T10-1", "T10-2" for a few stray frames
54 // We will just ignore these because they probably have been interpolated to the official
55 // label #TODO: see if we still want to keep this
56 if ((label.size() >= 2 && label[label.size() - 2] == '-') ||
57 (label.size() >= 3 && label[label.size() - 3] == '-')) {
58 return false;
59 }
60
61 // check if the label is in the valid list
62 if (!validMarkerNames.empty()) {
63 if (std::find(validMarkerNames.begin(), validMarkerNames.end(), label) ==
64 validMarkerNames.end()) {
65 return false;
66 }
67 }
68
69 return true;
70}
71
72} // namespace
73
74namespace {
75
76// Returns the validated unit string from the c3d POINT group, or std::nullopt on error.
77std::optional<std::string> getValidatedUnit(const ezc3d::ParametersNS::GroupNS::Group& pointGroup) {
78 constexpr auto kUnitStr = "UNITS";
79 const auto& unit = pointGroup.parameter(kUnitStr).valuesAsString();
80 if (unit.size() != 1) {
81 MT_LOGE("{}: Invalid c3d file: no unit information found!", __func__);
82 return std::nullopt;
83 }
84 const auto& unitStr = unit[0];
85 if (unitStr != "mm" && unitStr != "m" && unitStr != "cm" && unitStr != "dm") {
86 MT_LOGE("{}: Unknown unit string '{}' found in the file.", __func__, unitStr);
87 return std::nullopt;
88 }
90 unitStr != "mm",
91 "{}: Unit '{}' is not mm. Translating a C3D file that contains 3D point data stored in any units other than millimeters is extremely complex and any mistakes will render the file invalid.",
92 __func__,
93 unitStr);
94 return unitStr;
95}
96
97// Load all point labels from POINT.LABELS plus the LABEL2/LABEL3/... overflow sections.
98// The c3d format limits LABELS to 255 entries per section.
99// Returns an empty vector if the total label count is inconsistent with the header.
100std::vector<std::string> loadPointLabels(
101 const ezc3d::ParametersNS::GroupNS::Group& pointGroup,
102 size_t kPointsPerFrame) {
103 constexpr auto kLabelStr = "LABELS";
104 constexpr auto kNumLabelsPerSection = 255;
105 constexpr size_t kAdditionSectionStartIndex = 2;
106
107 auto pointLabels = pointGroup.parameter(kLabelStr).valuesAsString();
108 const size_t numOfExtraSections = kPointsPerFrame / kNumLabelsPerSection;
109 pointLabels.reserve(kPointsPerFrame);
110 for (size_t sectionId = kAdditionSectionStartIndex;
111 sectionId < kAdditionSectionStartIndex + numOfExtraSections;
112 sectionId++) {
113 const auto labelStr = kLabelStr + std::to_string(sectionId);
114 const auto& additionalPointLabels = pointGroup.parameter(labelStr).valuesAsString();
115 pointLabels.insert(
116 pointLabels.end(), additionalPointLabels.begin(), additionalPointLabels.end());
117 }
118 if (pointLabels.size() < kPointsPerFrame) {
119 MT_LOGE("{}: Number of point labels loaded isn't consistent with the header! ", __func__);
120 return {};
121 }
122 pointLabels.resize(kPointsPerFrame);
123 return pointLabels;
124}
125
126// Group point indices by their parsed subject name.
127// A Subject is a collection of points that should be grouped together to represent an object.
128std::unordered_map<std::string, std::vector<size_t>> groupPointsBySubject(
129 std::span<const std::string> pointLabels) {
130 std::unordered_map<std::string, std::vector<size_t>> subjectNameMap;
131 subjectNameMap.reserve(pointLabels.size());
132 for (size_t iLabel = 0; iLabel < pointLabels.size(); ++iLabel) {
133 subjectNameMap[findSubjectName(pointLabels[iLabel])].push_back(iLabel);
134 }
135 return subjectNameMap;
136}
137
138// Initialize per-actor MarkerSequence/template-actor arrays and return the mapping from
139// each c3d point index to (actorId, markerId). Indices not mapped to any marker stay (-1, -1).
140// Resizes ``resultAnim`` and ``templateActors`` to ``subjectNameMap.size()``.
141std::vector<std::pair<int, int>> buildSubjectStructures(
142 const std::unordered_map<std::string, std::vector<size_t>>& subjectNameMap,
143 std::span<const std::string> pointLabels,
144 std::span<const std::string> validMarkerNames,
145 float fps,
146 std::vector<MarkerSequence>& resultAnim,
147 std::vector<std::vector<Marker>>& templateActors) {
148 resultAnim.assign(subjectNameMap.size(), {});
149 templateActors.assign(subjectNameMap.size(), {});
150 std::vector<std::pair<int, int>> markerMap(pointLabels.size(), {-1, -1});
151 size_t actorId = 0;
152 for (const auto& [subjectName, pointIndices] : subjectNameMap) {
153 int markerCount = 0;
154 // ``actorId`` is bounded by ``subjectNameMap.size()``, which we just used
155 // to size both vectors above; the analyzer cannot trace this through the
156 // range-based for loop counter.
157 auto& actorSequence = resultAnim.at(actorId);
158 actorSequence.fps = fps;
159 actorSequence.name = subjectName;
160 auto& templateActor = templateActors.at(actorId);
161 for (const auto kPointIdx : pointIndices) {
162 if (kPointIdx >= pointLabels.size()) {
163 continue;
164 }
165 auto pointLabel = pointLabels[kPointIdx];
166 if (!subjectName.empty()) {
167 pointLabel = pointLabel.substr(subjectName.size() + 1);
168 }
169 if (!isMarkerValid(pointLabel, validMarkerNames)) {
170 continue;
171 }
172 // ``kPointIdx`` is checked above against ``pointLabels.size()``, which
173 // also sizes ``markerMap``.
174 markerMap.at(kPointIdx) = {static_cast<int>(actorId), markerCount};
175 Marker marker;
176 marker.name = pointLabel;
177 marker.occluded = true;
178 templateActor.push_back(marker);
179 ++markerCount;
180 }
181 ++actorId;
182 }
183 return markerMap;
184}
185
186// Reset all template markers to occluded, then update them from one frame's c3d points.
187// Returns true if any marker was visible (residual >= 0, non-NaN, non-zero) in this frame.
188bool updateFrameMarkers(
189 const ezc3d::DataNS::Frame& frameData,
190 std::span<const std::pair<int, int>> markerMap,
191 UpVector up,
192 const std::string& unitStr,
193 std::vector<std::vector<Marker>>& templateActors) {
194 for (auto& templateActor : templateActors) {
195 for (auto& marker : templateActor) {
196 marker.occluded = true;
197 }
198 }
199
200 bool hasVisible = false;
201 const auto& framePoints = frameData.points().points();
202 for (size_t pointId = 0; pointId < markerMap.size(); ++pointId) {
203 const auto [kActorId, kMarkerId] = markerMap[pointId];
204 if (kActorId == -1 || kMarkerId == -1) {
205 continue;
206 }
207 const auto& pointData = framePoints[pointId];
208 Vector3d pos{pointData.x(), pointData.y(), pointData.z()};
209 if (std::isnan(pos[0]) || std::isnan(pos[1]) || std::isnan(pos[2])) {
210 continue;
211 }
212 if (pos == Eigen::Vector3d::Zero()) {
213 continue;
214 }
215 // residual < 0 indicates that the data is invalid;
216 // residual == 0 indicates that the data is generated.
217 if (pointData.residual() < 0) {
218 continue;
219 }
220 // ``kActorId`` / ``kMarkerId`` come from ``markerMap`` populated by
221 // ``buildSubjectStructures`` and are guaranteed to address the matching
222 // ``templateActors`` entry; bounds-checked accessors guard against any
223 // future divergence.
224 if (static_cast<size_t>(kActorId) >= templateActors.size() ||
225 static_cast<size_t>(kMarkerId) >= templateActors.at(kActorId).size()) {
226 continue;
227 }
228 auto& marker = templateActors.at(kActorId).at(kMarkerId);
229 marker.occluded = false;
230 marker.pos = toMomentumVector3(pos, up, unitStr);
231 hasVisible = true;
232 }
233 return hasVisible;
234}
235
236// Shared parsing logic, agnostic to whether the c3d came from a file path or an istream.
237std::vector<MarkerSequence>
238loadC3dFromObject(ezc3d::c3d& c3dFile, UpVector up, std::span<const std::string> validMarkerNames) {
239 try {
240 const auto& header = c3dFile.header();
241 const size_t kPointsPerFrame = header.nb3dPoints();
242 const auto kFrameCount = header.nbFrames();
243 const float fps = header.frameRate();
244 MT_LOGD("{}: Found {} frames", __func__, kFrameCount);
245 MT_LOGD("{}: Frame rate {}", __func__, fps);
246
247 constexpr auto kPointGroupStr = "POINT";
248 const auto& pointGroup = c3dFile.parameters().group(kPointGroupStr);
249
250 const auto unitStr = getValidatedUnit(pointGroup);
251 if (!unitStr.has_value()) {
252 return {};
253 }
254
255 const auto pointLabels = loadPointLabels(pointGroup, kPointsPerFrame);
256 if (pointLabels.empty()) {
257 return {};
258 }
259
260 const auto subjectNameMap = groupPointsBySubject(pointLabels);
261 const size_t kNumOfSubjects = subjectNameMap.size();
262 std::vector<MarkerSequence> resultAnim(kNumOfSubjects);
263 std::vector<std::vector<Marker>> templateActors(kNumOfSubjects);
264 const auto markerMap = buildSubjectStructures(
265 subjectNameMap, pointLabels, validMarkerNames, fps, resultAnim, templateActors);
266
267 bool hasAnim = false;
268 const auto& frames = c3dFile.data().frames();
269 for (int frameId = 0; frameId < kFrameCount; ++frameId) {
270 hasAnim |= updateFrameMarkers(frames[frameId], markerMap, up, *unitStr, templateActors);
271 for (size_t actorId = 0; actorId < templateActors.size(); ++actorId) {
272 resultAnim[actorId].frames.push_back(templateActors[actorId]);
273 }
274 }
275
276 if (!hasAnim) {
277 return {};
278 }
279 return resultAnim;
280 } catch (std::exception& e) {
281 MT_LOGE("{}: Exception: {}", __func__, e.what());
282 return {};
283 } catch (...) {
284 MT_LOGE("{}: Unknown c3d reading error", __func__);
285 return {};
286 }
287}
288
289} // namespace
290
291std::vector<MarkerSequence>
292loadC3d(const std::string& filename, UpVector up, std::span<const std::string> validMarkerNames) {
293 try {
294 ezc3d::c3d c3dFile(filename);
295 return loadC3dFromObject(c3dFile, up, validMarkerNames);
296 } catch (const std::exception& e) {
297 MT_LOGE("{}: failed to open {}: {}", __func__, filename, e.what());
298 return {};
299 }
300}
301
302#ifdef MOMENTUM_WITH_EZC3D_ISTREAM
303std::vector<MarkerSequence> loadC3d(
304 std::span<const std::byte> bytes,
305 UpVector up,
306 std::span<const std::string> validMarkerNames) {
307 try {
308 ispanstream stream(bytes);
309 ezc3d::c3d c3dFile(static_cast<std::istream&>(stream));
310 return loadC3dFromObject(c3dFile, up, validMarkerNames);
311 } catch (const std::exception& e) {
312 MT_LOGE("{}: failed to read c3d from buffer ({} bytes): {}", __func__, bytes.size(), e.what());
313 return {};
314 }
315}
316#endif
317
318} // namespace momentum
#define MT_LOGD(...)
Definition log.h:178
#define MT_LOGE(...)
Definition log.h:181
#define MT_LOGW_IF(condition,...)
Definition log.h:186
Vector3< double > Vector3d
Definition types.h:261
std::vector< MarkerSequence > loadC3d(const std::string &filename, UpVector up, std::span< const std::string > validMarkerNames)
Loads all the subjects from a C3D file into a vector of MarkerSequences.
Definition c3d_io.cpp:292
UpVector
This enumeration is used to define the primary up vector directions for various coordinate systems an...
Vector3< T > toMomentumVector3(const Vector3< T > &vec, UpVector up, Unit unit)
This function converts a 3D vector in the mocap marker coordinate system to the Momentum coordinate s...
A single motion capture marker observation (position, occlusion, confidence).
Definition marker.h:18
std::string name
The name of the marker.
Definition marker.h:20