Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
marker_tracker.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
10#include "momentum/camera/projection_utils.h"
32#include "momentum/common/log.h"
38#include "momentum/math/mesh.h"
40
41#include <optional>
42#include <unordered_set>
43
44using namespace momentum;
45
46namespace momentum {
47
48namespace {
49
50void validateCameraKeypointFrameCount(
51 std::span<const CameraKeypointData> cameraKeypointData,
52 size_t numFrames) {
53 for (size_t cam = 0; cam < cameraKeypointData.size(); ++cam) {
55 cameraKeypointData[cam].frameData.size() != numFrames,
56 "Camera keypoint data[{}] has {} frames but marker data has {} frames",
57 cam,
58 cameraKeypointData[cam].frameData.size(),
59 numFrames);
60 }
61}
62
66size_t computeSampleStride(size_t numFrames, size_t targetFrames, size_t greedyMax = 0) {
67 if (targetFrames == 0 || numFrames == 0) {
68 return 1;
69 }
70 size_t stride = (numFrames - 1) / targetFrames;
71 if (greedyMax > 0) {
72 stride = std::min(stride, greedyMax);
73 }
74 return std::max(size_t(1), stride);
75}
76
77} // namespace
78
93std::vector<size_t> sampleFrames(
94 momentum::Character& character,
95 const MatrixXf& initialMotion,
96 std::span<const std::vector<momentum::Marker>> markerData,
97 const ParameterSet& parameters,
98 const size_t frameStride,
99 const size_t numSamples) {
100 // sample frames so that we get the most variance from the initial input
101 const auto numFrames = static_cast<size_t>(initialMotion.cols());
102 if (numFrames == 0) {
103 return {};
104 }
105 MT_CHECK(frameStride > 0, "frameStride must be > 0.");
106 size_t solvedFrames = (numFrames - 1) / frameStride + 1;
107 std::vector<size_t> frameIndices;
108 const size_t numActualSamples = std::min(numSamples, solvedFrames);
109
110 // get the indices of the parameters to be used
111 std::vector<size_t> usedParameters;
112 for (size_t i = 0; i < static_cast<size_t>(initialMotion.rows()); ++i) {
113 if (parameters.test(i)) {
114 usedParameters.push_back(i);
115 }
116 }
117
118 // calculate per frame error
119 const ParameterTransform& pt = character.parameterTransform;
120
121 // map locator name to its index
122 std::map<std::string, size_t> locatorLookup;
123 for (size_t i = 0; i < character.locators.size(); i++) {
124 locatorLookup[character.locators[i].name] = i;
125 }
126
127 std::vector<double> frameErrors(solvedFrames, 0.0f);
128 SkeletonState state;
129 for (size_t iFrame = 0, fi = 0; iFrame < numFrames; iFrame += frameStride, fi++) {
130 const auto jointParams = pt.apply(initialMotion.col(iFrame));
131 state.set(jointParams, character.skeleton, false);
132
133 const auto& markerList = markerData[iFrame];
134 for (const auto& jMarker : markerList) {
135 if (jMarker.occluded) {
136 continue;
137 }
138 auto query = locatorLookup.find(jMarker.name);
139 if (query == locatorLookup.end()) {
140 continue;
141 }
142 size_t locatorIdx = query->second;
143 if (locatorIdx >= character.locators.size()) {
144 continue;
145 }
146 const auto& locator = character.locators[locatorIdx];
147 if (locator.parent >= state.jointState.size()) {
148 continue;
149 }
150 const Vector3f locatorPos = state.jointState[locator.parent].transform * locator.offset;
151 const Vector3f diff = locatorPos - jMarker.pos.cast<float>();
152 const float markerError = diff.norm();
153 frameErrors[fi] += markerError;
154 }
155 }
156 std::vector<double> sortedErrors = frameErrors;
157 std::sort(sortedErrors.begin(), sortedErrors.end());
158
159 // do not use the worst 1/4 of the fitted errors, there's likely to be some outliers and
160 // errors due to the initialization
161 const double threshold = sortedErrors[(sortedErrors.size() * 3) / 4];
162
163 // get the motion of only the used parameters and then normalize
164 // by the mean and variance
165 MatrixXf normalized;
166 {
167 const MatrixXf subMotion =
168 initialMotion(usedParameters, Eigen::seq(0, numFrames - 1, frameStride));
169 const VectorXf mean = subMotion.rowwise().mean();
170 const MatrixXf centered = subMotion.colwise() - mean;
171 const VectorXf std = centered.array().square().rowwise().sum() / (numFrames - 1);
172
173 // normalize the motion by the sqrt of the variance, i.e. leave a little bit of scale in
174 normalized = centered.array().colwise() / (std.array().sqrt().sqrt().cwiseMax(1e-5f));
175 }
176
177 for (size_t i = 0; i < frameErrors.size(); ++i) {
178 if (frameErrors[i] > threshold) {
179 normalized.col(i) = VectorXf::Ones(normalized.rows()) * 1000.0f;
180 }
181 }
182
183 // calculate the distances from each frame to the already selected indices
184 frameIndices.push_back(0);
185 VectorXf distances = VectorXf::Zero(solvedFrames);
186 for (size_t fi = 0; fi < solvedFrames; fi++) {
187 distances[fi] = (normalized.col(frameIndices[0]) - normalized.col(fi)).norm();
188 }
189
190 // finally add additional samples with the largest distance
191 for (size_t i = frameIndices.size(); i < numActualSamples; ++i) {
192 size_t maxFrame = 0;
193 const float maxval = distances.maxCoeff(&maxFrame);
194 if (maxval < 1e-5f) {
195 break;
196 }
197 frameIndices.push_back(maxFrame);
198
199 for (size_t fi = 0; fi < solvedFrames; fi++) {
200 const float dist = (normalized.col(maxFrame) - normalized.col(fi)).cwiseAbs().maxCoeff();
201 distances[fi] = std::min(distances[fi], dist);
202 }
203 }
204
205 for (auto&& fi : frameIndices) {
206 fi *= frameStride;
207 }
208
209 return frameIndices;
210}
211
228Eigen::MatrixXf trackSequence(
229 const std::span<const std::vector<Marker>> markerData,
230 const Character& character,
231 const ParameterSet& globalParams,
232 const MatrixXf& initialMotion,
233 const TrackingConfig& config,
234 float regularizer,
235 const size_t frameStride,
236 bool enforceFloorInFirstFrame,
237 const std::string& firstFramePoseConstraintSet,
238 float targetHeightCm,
239 std::span<const GloveFrameData> leftGloveData,
240 std::span<const GloveFrameData> rightGloveData,
241 const std::optional<GloveConfig>& gloveConfig,
242 std::span<const CameraKeypointData> cameraKeypointData) {
243 // sanity checks
244 const size_t numFrames = markerData.size();
245 MT_CHECK(numFrames > 0, "Input marker data is empty.");
246 MT_CHECK(frameStride > 0, "frameStride must be > 0.");
247 validateCameraKeypointFrameCount(cameraKeypointData, numFrames);
248 if (!leftGloveData.empty()) {
249 MT_CHECK(
250 leftGloveData.size() == numFrames,
251 "trackSequence: left glove data has {} frames but marker data has {} frames",
252 leftGloveData.size(),
253 numFrames);
254 }
255 if (!rightGloveData.empty()) {
256 MT_CHECK(
257 rightGloveData.size() == numFrames,
258 "trackSequence: right glove data has {} frames but marker data has {} frames",
259 rightGloveData.size(),
260 numFrames);
261 }
262 std::vector<size_t> frames;
263 for (size_t fi = 0; fi < numFrames; fi += frameStride) {
264 frames.emplace_back(fi);
265 }
266
267 return trackSequence(
268 markerData,
269 character,
270 globalParams,
271 initialMotion,
272 config,
273 frames,
274 regularizer,
275 enforceFloorInFirstFrame,
276 firstFramePoseConstraintSet,
277 targetHeightCm,
278 leftGloveData,
279 rightGloveData,
280 gloveConfig,
281 cameraKeypointData);
282}
283
288 size_t solverFrame,
289 size_t solvedFrames,
290 const Character& character) {
291 const ParameterTransform& pt = character.parameterTransform;
292 if (!pt.getBlendShapeParameters().any() || solverFrame != 0) {
293 return;
294 }
295 auto blendShapeConstrFunc = std::make_shared<ModelParametersErrorFunction>(character);
296 blendShapeConstrFunc->setWeight(solvedFrames * 0.1f);
297 Eigen::VectorXf weights = Eigen::VectorXf::Zero(pt.numAllModelParameters());
298 for (Eigen::Index i = 0; i < pt.blendShapeParameters.size(); ++i) {
299 if (pt.blendShapeParameters[i] >= 0) {
300 weights[pt.blendShapeParameters[i]] = 1.0f;
301 }
302 }
303 blendShapeConstrFunc->setTargetParameters(
305 solverFunc.addErrorFunction(solverFrame, blendShapeConstrFunc);
306}
307
314 size_t solverFrame,
315 size_t iFrame,
316 const Character& character,
317 float projectionWeight,
318 std::span<const CameraKeypointData> cameraKeypointData) {
319 if (projectionWeight <= 0.0f) {
320 return;
321 }
322 size_t totalProjectionConstraints = 0;
323 size_t totalInvalidProj = 0;
324 for (const auto& camData : cameraKeypointData) {
325 if (iFrame >= camData.frameData.size() || camData.frameData[iFrame].empty()) {
326 continue;
327 }
328 auto projFunc = std::make_shared<ProjectionErrorFunctionT<float>>(
329 character.skeleton, character.parameterTransform);
330 for (const auto& obs : camData.frameData[iFrame]) {
331 if (obs.confidence <= 0.0f || obs.locatorIndex >= character.locators.size()) {
332 continue;
333 }
334 const auto& locator = character.locators[obs.locatorIndex];
335 if (locator.parent >= character.skeleton.joints.size()) {
336 continue;
337 }
338 const auto [M, valid] = projectionMatrixRadians(camData.camera, obs.target);
339 if (!valid) {
340 totalInvalidProj++;
341 continue;
342 }
344 constr.projection = M;
345 constr.target = Eigen::Vector2f::Zero();
346 constr.parent = locator.parent;
347 constr.offset = locator.offset;
348 constr.weight = obs.confidence;
349 projFunc->addConstraint(constr);
350 }
351 if (!projFunc->empty()) {
352 totalProjectionConstraints += projFunc->getNumConstraints();
353 projFunc->setWeight(projectionWeight);
354 solverFunc.addErrorFunction(solverFrame, projFunc);
355 }
356 }
357 if (iFrame == 0) {
358 MT_LOGI(
359 "Frame 0: added {} projection constraints (radians, weight={}), "
360 "{} cameras, {} invalid projections",
361 totalProjectionConstraints,
362 projectionWeight,
363 cameraKeypointData.size(),
364 totalInvalidProj);
365 }
366}
367
372 size_t solverFrame,
373 size_t iFrame,
374 size_t solvedFrames,
375 const Character& character,
376 const TrackingConfig& config,
377 const std::vector<std::vector<PositionData>>& constrData,
378 const std::vector<std::vector<SkinnedLocatorConstraint>>& skinnedConstData,
379 const std::vector<SkinnedLocatorTriangleConstraintT<float>>& skinnedLocatorMeshContraints,
380 const std::vector<PlaneDataT<float>>& floorConstraints,
381 bool enforceFloorInFirstFrame,
382 const std::string& firstFramePoseConstraintSet,
383 float targetHeightCm,
384 const std::optional<GloveConfig>& gloveConfig,
385 const std::vector<std::vector<JointToJointPositionDataT<float>>>& leftGlovePosData,
386 const std::vector<std::vector<JointToJointOrientationDataT<float>>>& leftGloveOriData,
387 const std::vector<std::vector<JointToJointPositionDataT<float>>>& rightGlovePosData,
388 const std::vector<std::vector<JointToJointOrientationDataT<float>>>& rightGloveOriData,
389 std::span<const CameraKeypointData> cameraKeypointData = {},
390 std::span<const std::vector<PlaneDataT<float>>> perFrameFloorContacts = {}) {
391 auto posConstrWeight = PositionErrorFunction::kLegacyWeight * config.markerWeight;
392 if (solverFrame == 0 && (enforceFloorInFirstFrame || !firstFramePoseConstraintSet.empty())) {
393 posConstrWeight *= solvedFrames;
394 }
395
396 // prepare positional constraints
397 if (!constrData.at(iFrame).empty()) {
398 auto posConstrFunc = std::make_shared<PositionErrorFunction>(character, config.lossAlpha);
399 posConstrFunc->setConstraints(constrData.at(iFrame));
400 posConstrFunc->setWeight(posConstrWeight);
401 solverFunc.addErrorFunction(solverFrame, posConstrFunc);
402 }
403
404 if (!skinnedConstData.at(iFrame).empty()) {
405 auto skinnedConstrFunc = std::make_shared<SkinnedLocatorErrorFunction>(character);
406 skinnedConstrFunc->setConstraints(skinnedConstData.at(iFrame));
407 skinnedConstrFunc->setWeight(posConstrWeight);
408 solverFunc.addErrorFunction(solverFrame, skinnedConstrFunc);
409 }
410
411 if (!skinnedLocatorMeshContraints.empty() && solverFrame == 0) {
412 auto skinnedTriangleConstrFunc =
413 std::make_shared<SkinnedLocatorTriangleErrorFunctionT<float>>(character);
414 skinnedTriangleConstrFunc->setConstraints(skinnedLocatorMeshContraints);
415 skinnedTriangleConstrFunc->setWeight(
416 solvedFrames * posConstrWeight * config.meshConstraintWeight);
417 solverFunc.addErrorFunction(solverFrame, skinnedTriangleConstrFunc);
418 }
419
420 addBlendShapeRegularizer(solverFunc, solverFrame, solvedFrames, character);
421
422 if (targetHeightCm > 0.0f && solverFrame == 0) {
423 auto heightConstrFunc = std::make_shared<HeightErrorFunctionT<float>>(
424 character, targetHeightCm, Eigen::Vector3f::UnitY(), 10);
425 heightConstrFunc->setWeight(solvedFrames * 1.0f);
426 solverFunc.addErrorFunction(solverFrame, heightConstrFunc);
427 }
428
429 // Floor constraints
430 if (!floorConstraints.empty()) {
431 if (enforceFloorInFirstFrame && solverFrame == 0) {
432 // Legacy: full equality constraint on frame 0 with high weight
433 auto eqConstrFunc = std::make_shared<PlaneErrorFunction>(character, /*half plane*/ false);
434 eqConstrFunc->setConstraints(floorConstraints);
435 eqConstrFunc->setWeight(PlaneErrorFunction::kLegacyWeight * solvedFrames);
436 solverFunc.addErrorFunction(solverFrame, eqConstrFunc);
437 } else {
438 // Half-plane floor constraint (non-penetration) on all frames
439 auto halfPlaneConstrFunc =
440 std::make_shared<PlaneErrorFunction>(character, /*half plane*/ true);
441 halfPlaneConstrFunc->setConstraints(floorConstraints);
442 halfPlaneConstrFunc->setWeight(PlaneErrorFunction::kLegacyWeight);
443 solverFunc.addErrorFunction(solverFrame, halfPlaneConstrFunc);
444 }
445 }
446 // Soft equality floor constraint on detected contact frames (per-locator)
447 if (solverFrame < perFrameFloorContacts.size() && !perFrameFloorContacts[solverFrame].empty()) {
448 auto eqFunc = std::make_shared<PlaneErrorFunction>(character, /*half plane*/ false);
449 eqFunc->setConstraints(perFrameFloorContacts[solverFrame]);
450 eqFunc->setWeight(PlaneErrorFunction::kLegacyWeight * 3.0f);
451 solverFunc.addErrorFunction(solverFrame, eqFunc);
452 }
453
454 if (!firstFramePoseConstraintSet.empty() && solverFrame == 0) {
455 if (character.parameterTransform.poseConstraints.count(firstFramePoseConstraintSet) > 0) {
456 const auto poseLimits = getPoseConstraintParameterLimits(
457 firstFramePoseConstraintSet, character.parameterTransform);
458 auto limitConstrFunc = std::make_shared<LimitErrorFunction>(character, poseLimits);
459 limitConstrFunc->setWeight(solvedFrames);
460 solverFunc.addErrorFunction(solverFrame, limitConstrFunc);
461 }
462 }
463
464 // add glove constraints for this frame
465 if (gloveConfig) {
467 solverFunc,
468 solverFrame,
469 character,
470 leftGlovePosData,
471 leftGloveOriData,
472 iFrame,
473 gloveConfig->positionWeight,
474 gloveConfig->orientationWeight);
476 solverFunc,
477 solverFrame,
478 character,
479 rightGlovePosData,
480 rightGloveOriData,
481 iFrame,
482 gloveConfig->positionWeight,
483 gloveConfig->orientationWeight);
484 }
485
487 solverFunc, solverFrame, iFrame, character, config.projectionWeight, cameraKeypointData);
488}
489
506Eigen::MatrixXf trackSequence(
507 const std::span<const std::vector<Marker>> markerData,
508 const Character& character,
509 const ParameterSet& globalParams,
510 const MatrixXf& initialMotion,
511 const TrackingConfig& config,
512 const std::vector<size_t>& frames,
513 float regularizer,
514 bool enforceFloorInFirstFrame,
515 const std::string& firstFramePoseConstraintSet,
516 float targetHeightCm,
517 std::span<const GloveFrameData> leftGloveData,
518 std::span<const GloveFrameData> rightGloveData,
519 const std::optional<GloveConfig>& gloveConfig,
520 std::span<const CameraKeypointData> cameraKeypointData,
521 std::span<const std::vector<PlaneDataT<float>>> perFrameFloorContacts) {
522 // sanity checks
523 const size_t numFrames = markerData.size();
524 MT_CHECK(numFrames > 0, "Input marker data is empty.");
525 MT_CHECK(
526 initialMotion.cols() >= numFrames,
527 "Number of frames in data {} exceeds input motion columns {}",
528 numFrames,
529 initialMotion.cols());
530 MT_CHECK(
531 initialMotion.rows() == character.parameterTransform.numAllModelParameters(),
532 "Input motion parameters {} do not match character model parameters {}",
533 initialMotion.rows(),
535 MT_CHECK(
536 leftGloveData.empty() || leftGloveData.size() == numFrames,
537 "Left glove data has {} frames but marker data has {} frames",
538 leftGloveData.size(),
539 numFrames);
540 MT_CHECK(
541 rightGloveData.empty() || rightGloveData.size() == numFrames,
542 "Right glove data has {} frames but marker data has {} frames",
543 rightGloveData.size(),
544 numFrames);
545 validateCameraKeypointFrameCount(cameraKeypointData, numFrames);
546
547 const ParameterTransform& pt = character.parameterTransform;
548
549 // universal parameters include "scaling" and "locators" (if exists); pose parameters need to
550 // exclude "locators". universalParams is to indicate to the solver which parameters are "global"
551 // (ie. not time varying). The input globalParams indicate which parameters within universalParams
552 // we want to solve for. globalParams is either a subset or all of universalParams.
553 ParameterSet poseParams = pt.getPoseParameters();
554 ParameterSet universalParams = pt.getScalingParameters() | pt.getBlendShapeParameters();
555 const auto locatorSet =
556 pt.getParameterSet("locators", true) | pt.getParameterSet("skinnedLocators", true);
557 poseParams &= ~locatorSet;
558 universalParams |= locatorSet;
559
560 // Include glove DOFs as universal (not time-varying) parameters
561 if (gloveConfig) {
562 const auto gloveSet = pt.getParameterSet("gloves", true);
563 poseParams &= ~gloveSet;
564 universalParams |= gloveSet;
565 }
566
567 // Apply caller-specified parameter mask to pose parameters
568 if (config.activeParams) {
569 poseParams &= *config.activeParams;
570 }
571
572 std::vector<momentum::SkinnedLocatorTriangleConstraintT<float>> skinnedLocatorMeshContraints;
573 if (!character.skinnedLocators.empty() && character.mesh) {
574 skinnedLocatorMeshContraints = createSkinnedLocatorMeshConstraints(character);
575 MT_LOGI(
576 "Created {} mesh constraints for {} skinned locators",
577 skinnedLocatorMeshContraints.size(),
578 character.skinnedLocators.size());
579 }
580
581 // set up the solver function
582 std::vector<size_t> sortedFrames = frames;
583 std::sort(sortedFrames.begin(), sortedFrames.end());
584 size_t solvedFrames = sortedFrames.size();
585 auto solverFunc = SequenceSolverFunction(
586 character, character.parameterTransform, universalParams, solvedFrames);
587
588 // floor penetration constraints; we assume the world is y-up and floor is y=0 for mocap data.
589 const auto& floorConstraints = createFloorConstraints<float>(
590 "Floor_",
591 character.locators,
592 Vector3f::UnitY(),
593 /* y offset */ 0.0f,
594 /* weight */ 5.0f);
595
596 // marker constraints
597 const auto constrData = createConstraintData(markerData, character.locators);
598 const auto skinnedConstData = createSkinnedConstraintData(markerData, character.skinnedLocators);
599
600 // glove constraint data (one per hand × position/orientation)
601 std::vector<std::vector<JointToJointPositionDataT<float>>> leftGlovePosData, rightGlovePosData;
602 std::vector<std::vector<JointToJointOrientationDataT<float>>> leftGloveOriData, rightGloveOriData;
603 if (gloveConfig) {
604 leftGlovePosData = createGlovePositionConstraintData(leftGloveData, character, *gloveConfig, 0);
605 leftGloveOriData =
606 createGloveOrientationConstraintData(leftGloveData, character, *gloveConfig, 0);
607 rightGlovePosData =
608 createGlovePositionConstraintData(rightGloveData, character, *gloveConfig, 1);
609 rightGloveOriData =
610 createGloveOrientationConstraintData(rightGloveData, character, *gloveConfig, 1);
611 }
612
613 // add per-frame constraint data to the solver
614 for (size_t solverFrame = 0; solverFrame < solvedFrames; ++solverFrame) {
615 const size_t& iFrame = sortedFrames[solverFrame];
616 if ((constrData.at(iFrame).size() + skinnedConstData.at(iFrame).size()) >
617 markerData[iFrame].size() * config.minVisPercent) {
619 solverFunc,
620 solverFrame,
621 iFrame,
622 solvedFrames,
623 character,
624 config,
625 constrData,
626 skinnedConstData,
627 skinnedLocatorMeshContraints,
628 floorConstraints,
629 enforceFloorInFirstFrame,
630 firstFramePoseConstraintSet,
631 targetHeightCm,
632 gloveConfig,
633 leftGlovePosData,
634 leftGloveOriData,
635 rightGlovePosData,
636 rightGloveOriData,
637 cameraKeypointData,
638 perFrameFloorContacts);
639 }
640 // Set per-frame initial value
641 solverFunc.setFrameParameters(solverFrame, initialMotion.col(iFrame));
642 }
643
644 // add parameter limits
645 auto limitConstrFunc = std::make_shared<LimitErrorFunction>(character);
646 limitConstrFunc->setWeight(0.1);
647 solverFunc.addErrorFunction(kAllFrames, limitConstrFunc);
648
649 // add collision error
650 if (config.collisionErrorWeight != 0 && character.collision != nullptr) {
651 auto collisionConstrFunc = std::make_shared<CollisionErrorFunctionStateless>(character);
652 collisionConstrFunc->setWeight(config.collisionErrorWeight);
653 solverFunc.addErrorFunction(kAllFrames, collisionConstrFunc);
654 }
655
656 // add a smoothness constraint in parameter space
657 if (config.smoothing != 0) {
658 auto smoothConstrFunc = std::make_shared<ModelParametersSequenceErrorFunction>(character);
659 smoothConstrFunc->setWeight(config.smoothing);
660 solverFunc.addSequenceErrorFunction(kAllFrames, smoothConstrFunc);
661 }
662
663 // minimize the change to global params
664 if (globalParams.count() > 0 && regularizer != 0) {
665 auto regularizerFunc = std::make_shared<ModelParametersErrorFunction>(character);
666 Eigen::VectorXf universalMask(pt.numAllModelParameters());
667 for (size_t i = 0; i < universalMask.size(); ++i) {
668 if (globalParams.test(i)) {
669 universalMask[i] = regularizer;
670 } else {
671 universalMask[i] = 0.0;
672 }
673 }
674 regularizerFunc->setTargetParameters(initialMotion.col(0), universalMask);
675 // Sufficient to add to the first frame since it won't change.
676 solverFunc.addErrorFunction(0, regularizerFunc);
677 }
678
679 // solver configration
680 SequenceSolverOptions solverOptions;
681 solverOptions.maxIterations = config.maxIter;
682 solverOptions.minIterations = 2;
683 solverOptions.progressBar = config.debug;
684 solverOptions.doLineSearch = false;
685 solverOptions.multithreaded = true;
686 solverOptions.verbose = config.debug;
687 solverOptions.threshold = 1.f;
688 solverOptions.regularization = config.regularization;
689
690 // solve the problem
691 SequenceSolver solver = SequenceSolver(solverOptions, &solverFunc);
692 solver.setEnabledParameters(poseParams | globalParams);
693 // returns all the dofs with initial values nicely packed into a vector
694 VectorXf dofs = solverFunc.getJoinedParameterVector();
695 solver.solve(dofs);
696 double error = solverFunc.getError(dofs);
697 MT_LOGI_IF(config.debug, "Solver residual: {}", error);
698
699 // set results to output
700 size_t sortedIndex = 0;
701 MatrixXf outMotion(pt.numAllModelParameters(), numFrames);
702 for (size_t fi = 0; fi < numFrames; fi++) {
703 if (sortedIndex < sortedFrames.size() - 1 && fi == sortedFrames[sortedIndex + 1]) {
704 sortedIndex++;
705 }
706 outMotion.col(fi) = solverFunc.getFrameParameters(sortedIndex).v;
707 }
708 return outMotion;
709}
710
713 std::optional<GloveErrorFunctions>& left,
714 std::optional<GloveErrorFunctions>& right,
715 size_t iFrame) {
716 if (left) {
717 updateGloveConstraintsForFrame(*left, iFrame);
718 }
719 if (right) {
720 updateGloveConstraintsForFrame(*right, iFrame);
721 }
722}
723
732bool isGlobalTransformZero(const Eigen::VectorXf& dof, const ParameterSet& rigidParams) {
733 for (Eigen::Index i = 0; i < dof.size(); ++i) {
734 if (rigidParams.test(i) && dof[i] != 0.0f) {
735 return false;
736 }
737 }
738 return true;
739}
740
754Eigen::MatrixXf trackPosesPerframe(
755 const std::span<const std::vector<Marker>> markerData,
756 const Character& character,
757 const ModelParameters& globalParams,
758 const TrackingConfig& config,
759 const size_t frameStride,
760 std::span<const GloveFrameData> leftGloveData,
761 std::span<const GloveFrameData> rightGloveData,
762 const std::optional<GloveConfig>& gloveConfig) {
763 const size_t numFrames = markerData.size();
764 MT_CHECK(numFrames > 0, "Input marker data is empty.");
765 MT_CHECK(frameStride > 0, "frameStride must be > 0.");
766
767 // Generate frame indices from stride
768 std::vector<size_t> frameIndices;
769 for (size_t iFrame = 0; iFrame < numFrames; iFrame += frameStride) {
770 frameIndices.push_back(iFrame);
771 }
772
773 // Convert globalParams to initial motion matrix
774 MatrixXf initialMotion(globalParams.v.size(), numFrames);
775 for (size_t i = 0; i < numFrames; ++i) {
776 initialMotion.col(i) = globalParams.v;
777 }
778
779 // Determine if tracking should be continuous (temporal coherence)
780 bool isContinuous = (frameStride < 5);
781
782 return trackPosesForFrames(
783 markerData,
784 character,
785 initialMotion,
786 config,
787 frameIndices,
788 isContinuous,
789 leftGloveData,
790 rightGloveData,
791 gloveConfig);
792}
793
802 GaussNewtonSolverQR& solver,
803 GaussNewtonSolverQROptions& solverOptions,
804 Eigen::VectorXf& dof,
805 const ParameterTransform& pt,
806 const ParameterSet& poseParams,
807 const std::shared_ptr<ModelParametersErrorFunction>& smoothConstrFunc,
808 const TrackingConfig& config,
809 bool isContinuous,
810 size_t iFrame) {
811 MT_LOGI_IF(config.debug && isContinuous, "Solving for an initial rigid pose at frame {}", iFrame);
812
813 // Set up different config for initialization
814 solverOptions.maxIterations = 50; // make sure it converges
815 solver.setOptions(solverOptions);
817 if (smoothConstrFunc) {
818 smoothConstrFunc->setWeight(0.0); // turn off smoothing - it doesn't affect rigid dofs
819 }
820
821 solver.solve(dof);
822
823 // Recover solver config
824 solverOptions.maxIterations = config.maxIter;
825 solver.setOptions(solverOptions);
826 solver.setEnabledParameters(poseParams);
827 if (smoothConstrFunc) {
828 smoothConstrFunc->setWeight(config.smoothing);
829 }
830
831 return false;
832}
833
848Eigen::MatrixXf trackPosesForFrames(
849 const std::span<const std::vector<Marker>> markerData,
850 const Character& character,
851 const MatrixXf& initialMotion,
852 const TrackingConfig& config,
853 const std::vector<size_t>& frameIndices,
854 bool isContinuous,
855 std::span<const GloveFrameData> leftGloveData,
856 std::span<const GloveFrameData> rightGloveData,
857 const std::optional<GloveConfig>& gloveConfig,
858 const std::string& progressLabel) {
859 const size_t numFrames = markerData.size();
860 MT_CHECK(numFrames > 0, "Input marker data is empty.");
861 MT_CHECK(
862 initialMotion.cols() >= numFrames,
863 "Number of frames in data {} exceeds input motion columns {}",
864 numFrames,
865 initialMotion.cols());
866 MT_CHECK(
867 initialMotion.rows() == character.parameterTransform.numAllModelParameters(),
868 "Input motion parameters {} do not match character model parameters {}",
869 initialMotion.rows(),
871 MT_CHECK(
872 leftGloveData.empty() || leftGloveData.size() == numFrames,
873 "Left glove data has {} frames but marker data has {} frames",
874 leftGloveData.size(),
875 numFrames);
876 MT_CHECK(
877 rightGloveData.empty() || rightGloveData.size() == numFrames,
878 "Right glove data has {} frames but marker data has {} frames",
879 rightGloveData.size(),
880 numFrames);
881
882 const ParameterTransform& pt = character.parameterTransform;
883
884 std::vector<size_t> sortedFrames = frameIndices;
885 std::sort(sortedFrames.begin(), sortedFrames.end());
886
887 // pose parameters need to exclude "locators"
888 ParameterSet poseParams = pt.getPoseParameters();
889 const auto& locatorSet = pt.parameterSets.find("locators");
890 if (locatorSet != pt.parameterSets.end()) {
891 poseParams &= ~locatorSet->second;
892 }
893
894 // Exclude glove DOFs from per-frame pose solving
895 if (gloveConfig) {
896 poseParams &= ~pt.getParameterSet("gloves", true);
897 }
898
899 // Apply caller-specified parameter mask
900 if (config.activeParams) {
901 poseParams &= *config.activeParams;
902 }
903
904 // set up the solver
905 auto solverFunc = SkeletonSolverFunction(character, pt);
906 GaussNewtonSolverQROptions solverOptions;
907 solverOptions.maxIterations = config.maxIter;
908 solverOptions.minIterations = 2;
909 solverOptions.doLineSearch = false;
910 solverOptions.verbose = config.debug;
911 solverOptions.threshold = 1.f;
912 solverOptions.regularization = config.regularization;
913 auto solver = GaussNewtonSolverQR(solverOptions, &solverFunc);
914 solver.setEnabledParameters(poseParams);
915
916 // parameter limits constraint
917 auto limitConstrFunc = std::make_shared<LimitErrorFunction>(character);
918 limitConstrFunc->setWeight(0.1);
919 solverFunc.addErrorFunction(limitConstrFunc);
920
921 // positional constraint function for markers
922 auto posConstrFunc = std::make_shared<PositionErrorFunction>(character, config.lossAlpha);
923 posConstrFunc->setWeight(PositionErrorFunction::kLegacyWeight * config.markerWeight);
924 solverFunc.addErrorFunction(posConstrFunc);
925
926 auto skinnedLocatorPosConstrFunc = std::make_shared<SkinnedLocatorErrorFunction>(character);
927 skinnedLocatorPosConstrFunc->setWeight(
929 solverFunc.addErrorFunction(skinnedLocatorPosConstrFunc);
930
931 // floor penetration constraint data; we assume the world is y-up and floor is y=0 for mocap data.
932 const auto& floorConstraints = createFloorConstraints<float>(
933 "Floor_",
934 character.locators,
935 Vector3f::UnitY(),
936 /* y offset */ 0.0f,
937 /* weight */ 5.0f);
938 auto halfPlaneConstrFunc = std::make_shared<PlaneErrorFunction>(character, /*half plane*/ true);
939 halfPlaneConstrFunc->setConstraints(floorConstraints);
940 halfPlaneConstrFunc->setWeight(PlaneErrorFunction::kLegacyWeight);
941 solverFunc.addErrorFunction(halfPlaneConstrFunc);
942
943 // Pre-process marker gaps (interpolate temporary gaps, blend off permanent dropouts).
944 // Creates a mutable copy since the input span is const.
945 auto processedMarkerData = std::vector<std::vector<Marker>>(markerData.begin(), markerData.end());
946 preprocessMarkerGaps(processedMarkerData, config.gapFillConfig);
947
948 // marker constraint data (uses gap-filled markers)
949 auto constrData = createConstraintData(processedMarkerData, character.locators);
950 auto skinnedConstrData =
951 createSkinnedConstraintData(processedMarkerData, character.skinnedLocators);
952
953 // smoothness constraint only for the joints and exclude global dofs because the global transform
954 // needs to be accurate (may not matter in practice?)
955 // Only use temporal smoothness if isContinuous is true
956 std::shared_ptr<ModelParametersErrorFunction> smoothConstrFunc;
957 if (isContinuous) {
958 smoothConstrFunc = std::make_shared<ModelParametersErrorFunction>(
959 character, poseParams & ~pt.getRigidParameters());
960 smoothConstrFunc->setWeight(config.smoothing);
961 solverFunc.addErrorFunction(smoothConstrFunc);
962 }
963
964 // add collision error
965 std::shared_ptr<CollisionErrorFunction> collisionErrorFunction;
966 if (config.collisionErrorWeight != 0 && character.collision != nullptr) {
967 collisionErrorFunction = std::make_shared<CollisionErrorFunction>(character);
968 collisionErrorFunction->setWeight(config.collisionErrorWeight);
969 solverFunc.addErrorFunction(collisionErrorFunction);
970 }
971
972 // set up glove error functions (registered once, constraints swapped per frame)
973 std::optional<GloveErrorFunctions> leftGloveFuncs, rightGloveFuncs;
974 if (gloveConfig) {
975 leftGloveFuncs =
976 setupGloveErrorFunctions(solverFunc, character, leftGloveData, *gloveConfig, 0);
977 rightGloveFuncs =
978 setupGloveErrorFunctions(solverFunc, character, rightGloveData, *gloveConfig, 1);
979 }
980
981 // initialize parameters to contain identity information
982 // the identity fields will be used but untouched during optimization
983 // globalParams could also be repurposed to pass in initial pose value
984 Eigen::VectorXf dof = initialMotion.col(sortedFrames.empty() ? 0 : sortedFrames[0]);
985 size_t solverFrame = 0;
986 double priorError = 0.0;
987 double error = 0.0;
988
989 // Use the initial global transform if it's not zero
990 bool needsInit = isGlobalTransformZero(dof, pt.getRigidParameters());
991
992 MatrixXf outMotion = initialMotion;
993 Eigen::Index outputIndex = 0;
994 { // scope the ProgressBar so it returns
995 ProgressBar progress(progressLabel, sortedFrames.size());
996 for (const auto iFrame : sortedFrames) {
997 // For continuous tracking, keep the solved dof from previous frame (temporal coherence)
998 // For non-continuous tracking, always start from initial motion (independent solving)
999 if (!isContinuous) {
1000 dof = initialMotion.col(iFrame);
1001 needsInit = true;
1002 }
1003 // For continuous tracking, dof is preserved from previous iteration (or initial value)
1004
1005 if ((constrData.at(iFrame).size() + skinnedConstrData.at(iFrame).size()) >
1006 processedMarkerData[iFrame].size() * config.minVisPercent) {
1007 // add positional constraints
1008 posConstrFunc->clearConstraints(); // clear constraint data from the previous frame
1009 posConstrFunc->setConstraints(constrData.at(iFrame));
1010
1011 skinnedLocatorPosConstrFunc->clearConstraints();
1012 skinnedLocatorPosConstrFunc->setConstraints(skinnedConstrData.at(iFrame));
1013
1014 // update glove constraints for this frame
1015 updateGloveConstraintsForBothHands(leftGloveFuncs, rightGloveFuncs, iFrame);
1016
1017 // initialization: solve only for the rigid parameters as preprocessing
1018 if (needsInit) {
1019 needsInit = solveRigidInitialization(
1020 solver,
1021 solverOptions,
1022 dof,
1023 pt,
1024 poseParams,
1025 smoothConstrFunc,
1026 config,
1027 isContinuous,
1028 iFrame);
1029 }
1030
1031 // set smoothness target as the last pose for continuous tracking
1032 if (smoothConstrFunc) {
1033 smoothConstrFunc->setTargetParameters(dof, smoothConstrFunc->getTargetWeights());
1034 }
1035
1036 priorError += solverFunc.getError(dof);
1037 error += solver.solve(dof);
1038 ++solverFrame;
1039 }
1040
1041 // store result
1042 while (outputIndex <= iFrame) {
1043 outMotion.col(outputIndex++) = dof;
1044 }
1045 progress.increment();
1046 }
1047
1048 while (outputIndex < numFrames) {
1049 outMotion.col(outputIndex++) = dof;
1050 }
1051 }
1052 if (config.debug) {
1053 if (solverFrame > 0) {
1054 MT_LOGI("Pre optimization residual: {}", priorError / solverFrame);
1055 MT_LOGI("Average per-frame residual: {}", error / solverFrame);
1056 } else {
1057 MT_LOGW("no valid frames to solve");
1058 }
1059 }
1060 return outMotion;
1061}
1062
1063namespace {
1064
1076float computeCharacterHeight(const Character& character, const ModelParameters& identity) {
1077 if (!character.mesh) {
1078 MT_LOGW("Character has no mesh, cannot compute height");
1079 return 0.0f;
1080 }
1081
1082 const ParameterTransform& pt = character.parameterTransform;
1083
1084 // Create a model parameters vector with scale and shape, but zero pose
1085 ModelParameters neutralParams = identity;
1086
1087 // Zero out all pose parameters
1088 const ParameterSet poseParams = pt.getPoseParameters();
1089 for (size_t i = 0; i < neutralParams.v.size(); ++i) {
1090 if (poseParams.test(i)) {
1091 neutralParams.v[i] = 0.0f;
1092 }
1093 }
1094
1095 // Create skeleton state with the neutral (zero pose) parameters
1096 const auto jointParams = pt.apply(neutralParams.v);
1097 SkeletonState state;
1098 state.set(jointParams, character.skeleton, false);
1099
1100 // Apply blend shape skinning to get the deformed mesh
1101 Mesh skinnedMesh;
1102 skinWithBlendShapes(character, state, neutralParams, skinnedMesh);
1103
1104 // Find min and max Y values across all vertices
1105 if (skinnedMesh.vertices.empty()) {
1106 MT_LOGW("Skinned mesh has no vertices, cannot compute height");
1107 return 0.0f;
1108 }
1109
1110 float minY = std::numeric_limits<float>::max();
1111 float maxY = std::numeric_limits<float>::lowest();
1112
1113 for (const auto& vertex : skinnedMesh.vertices) {
1114 minY = std::min(minY, vertex.y());
1115 maxY = std::max(maxY, vertex.y());
1116 }
1117
1118 const float height = maxY - minY;
1119 return height;
1120}
1121
1122// Log per-locator mesh distances with skin offsets for debugging calibration.
1123void logSkinnedLocatorMeshDistances(const Character& character, const std::string& label) {
1124 if (character.skinnedLocators.empty() || !character.mesh) {
1125 return;
1126 }
1127 const auto distances = computeSkinnedLocatorMeshDistances(character);
1128 MT_LOGI("{} skinned locator mesh distances:", label);
1129 for (size_t i = 0; i < distances.size(); ++i) {
1130 const auto& [name, dist] = distances[i];
1131 const float skinOff = character.skinnedLocators[i].skinOffset;
1132 MT_LOGI(" {}: {:.4f} cm (skinOffset: {:.2f} cm)", name, dist, skinOff);
1133 }
1134}
1135
1136void logKeypointObservationSummary(
1137 std::span<const CameraKeypointData> cameraKeypointData,
1138 float projectionWeight) {
1139 if (cameraKeypointData.empty() || projectionWeight <= 0.0f) {
1140 return;
1141 }
1142 size_t totalObs = 0;
1143 for (const auto& camData : cameraKeypointData) {
1144 for (const auto& frame : camData.frameData) {
1145 totalObs += frame.size();
1146 }
1147 }
1148 MT_LOGI(
1149 "2D keypoint constraints: {} cameras, {} total observations, "
1150 "projectionWeight={}",
1151 cameraKeypointData.size(),
1152 totalObs,
1153 projectionWeight);
1154}
1155
1156} // namespace
1157
1159 if (character.skinnedLocators.empty()) {
1160 return character;
1161 }
1162
1163 std::vector<bool> activeSkinnedLocators(character.skinnedLocators.size(), true);
1164 std::vector<std::string> locatorNames;
1165 for (const auto& sl : character.skinnedLocators) {
1166 locatorNames.push_back(sl.name);
1167 }
1168 std::tie(character.parameterTransform, character.parameterLimits) = addSkinnedLocatorParameters(
1169 character.parameterTransform, character.parameterLimits, activeSkinnedLocators, locatorNames);
1170 return character;
1171}
1172
1173namespace {
1174
1175// Locator-index upper bounds (inclusive) used to group per-keypoint
1176// reprojection errors into body / hand / surface regions in the diagnostic log.
1177constexpr size_t kBodyMaxLocatorIdx = 20;
1178constexpr size_t kRightHandMaxLocatorIdx = 41;
1179constexpr size_t kLeftHandMaxLocatorIdx = 62;
1180
1182SkeletonState skeletonStateForFrame(
1183 const Character& character,
1184 const ParameterTransform& transform,
1185 const Eigen::MatrixXf& motion,
1186 size_t frame) {
1187 SkeletonState skelState;
1188 skelState.set(
1189 character.parameterTransform.apply(
1190 ModelParameters(motion.col(frame).head(transform.numAllModelParameters()))),
1191 character.skeleton);
1192 return skelState;
1193}
1194
1196struct KeypointReprojection {
1197 Eigen::Vector3f pWorld;
1198 float pxErr;
1199};
1200
1204std::optional<KeypointReprojection> keypointReprojection(
1205 const Character& character,
1206 const SkeletonState& skelState,
1207 const Camera& camera,
1208 const KeypointObservation& obs) {
1209 if (obs.confidence <= 0.0f || obs.locatorIndex >= character.locators.size()) {
1210 return std::nullopt;
1211 }
1212 const auto& locator = character.locators.at(obs.locatorIndex);
1213 if (locator.parent >= skelState.jointState.size()) {
1214 return std::nullopt;
1215 }
1216 const Eigen::Vector3f pWorld = skelState.jointState.at(locator.parent).transform * locator.offset;
1217 const auto [projected, valid] = camera.project(pWorld);
1218 if (!valid) {
1219 return std::nullopt;
1220 }
1221 return KeypointReprojection{pWorld, (projected.head<2>() - obs.target).norm()};
1222}
1223
1224} // namespace
1225
1227 const Character& character,
1228 const ParameterTransform& transform,
1229 const Eigen::MatrixXf& motion,
1230 std::span<const CameraKeypointData> cameraKeypointData,
1231 const CalibrationConfig& config,
1232 const std::string& label) {
1233 if (cameraKeypointData.empty() || config.projectionWeight <= 0.0f) {
1234 return;
1235 }
1236
1237 const size_t diagFrame = 0;
1238 const SkeletonState skelState = skeletonStateForFrame(character, transform, motion, diagFrame);
1239
1240 // Per-locator error accumulators: sum of pixel errors and observation count.
1241 std::unordered_map<size_t, std::pair<float, size_t>> locatorErrors;
1242
1243 MT_LOGI("=== Keypoint reprojection diagnostic (frame {}, {}) ===", diagFrame, label);
1244 for (size_t iCam = 0; iCam < cameraKeypointData.size(); ++iCam) {
1245 const auto& camData = cameraKeypointData[iCam];
1246 if (diagFrame >= camData.frameData.size() || camData.frameData[diagFrame].empty()) {
1247 continue;
1248 }
1249 size_t nObs = 0, nSkipped = 0;
1250 float sumPxErr = 0, maxPxErr = 0;
1251 float sumRadErr = 0, maxRadErr = 0;
1252 for (const auto& obs : camData.frameData[diagFrame]) {
1253 const auto reproj = keypointReprojection(character, skelState, camData.camera, obs);
1254 if (!reproj) {
1255 nSkipped++;
1256 continue;
1257 }
1258 const float pxErr = reproj->pxErr;
1259 sumPxErr += pxErr;
1260 maxPxErr = std::max(maxPxErr, pxErr);
1261
1262 auto& entry = locatorErrors[obs.locatorIndex];
1263 entry.first += pxErr;
1264 entry.second++;
1265
1266 const auto [M, mValid] = projectionMatrixRadians(camData.camera, obs.target);
1267 float radErr = 0;
1268 if (mValid) {
1269 const Eigen::Vector3f& pWorld = reproj->pWorld;
1270 const Eigen::Vector4f ph(pWorld[0], pWorld[1], pWorld[2], 1.0f);
1271 const Eigen::Vector3f h = M * ph;
1272 if (std::abs(h[2]) > 1e-6f) {
1273 radErr = Eigen::Vector2f(h[0] / h[2], h[1] / h[2]).norm();
1274 }
1275 }
1276 sumRadErr += radErr;
1277 maxRadErr = std::max(maxRadErr, radErr);
1278 nObs++;
1279 }
1280 MT_LOGI(
1281 "cam[{}]: {} obs, {} skip, mean={:.1f}px/{:.4f}rad, max={:.1f}px/{:.4f}rad",
1282 iCam,
1283 nObs,
1284 nSkipped,
1285 nObs > 0 ? sumPxErr / nObs : 0.0f,
1286 nObs > 0 ? sumRadErr / nObs : 0.0f,
1287 maxPxErr,
1288 maxRadErr);
1289 }
1290
1291 // Log per-locator errors grouped by region.
1292 struct RegionStats {
1293 float sumErr = 0;
1294 size_t count = 0;
1295 };
1296 RegionStats body, rightHand, leftHand, surface;
1297
1298 std::vector<size_t> sortedIndices;
1299 sortedIndices.reserve(locatorErrors.size());
1300 for (const auto& [idx, _] : locatorErrors) {
1301 sortedIndices.push_back(idx);
1302 }
1303 std::sort(sortedIndices.begin(), sortedIndices.end());
1304
1305 MT_LOGI("--- Per-keypoint errors ({}) ---", label);
1306 for (const auto idx : sortedIndices) {
1307 const auto& [sumErr, cnt] = locatorErrors[idx];
1308 const float meanErr = sumErr / cnt;
1309 const std::string name =
1310 idx < character.locators.size() ? character.locators.at(idx).name : "?";
1311 MT_LOGI(" [{:2d}] {:30s} {:7.1f}px ({} obs)", idx, name, meanErr, cnt);
1312
1313 RegionStats* region = &surface;
1314 if (idx <= kBodyMaxLocatorIdx) {
1315 region = &body;
1316 } else if (idx <= kRightHandMaxLocatorIdx) {
1317 region = &rightHand;
1318 } else if (idx <= kLeftHandMaxLocatorIdx) {
1319 region = &leftHand;
1320 }
1321 region->sumErr += meanErr;
1322 region->count++;
1323 }
1324 auto logRegion = [](const char* name, const RegionStats& r) {
1325 if (r.count > 0) {
1326 MT_LOGI(" {}: mean={:.1f}px ({} keypoints)", name, r.sumErr / r.count, r.count);
1327 }
1328 };
1329 logRegion("body", body);
1330 logRegion("right_hand", rightHand);
1331 logRegion("left_hand", leftHand);
1332 logRegion("surface", surface);
1333}
1334
1335// Build the parameter sets controlling which body parameters are calibrated.
1336std::pair<ParameterSet, ParameterSet> buildCalibBodySets(
1337 const CalibrationConfig& config,
1338 const ParameterTransform& transform,
1339 const ParameterTransform& transformExtended) {
1340 if (config.globalScaleOnly) {
1341 const size_t paramIndex = transform.getParameterIdByName("scale_global");
1342 const size_t paramIndexExt = transformExtended.getParameterIdByName("scale_global");
1344 paramIndex == kInvalidIndex || paramIndexExt == kInvalidIndex,
1345 "Can't calibrate global scale since it is not defined in the parameter list!");
1346 ParameterSet calibBodySet;
1347 ParameterSet calibBodySetExtended;
1348 calibBodySet.set(paramIndex);
1349 calibBodySetExtended.set(paramIndexExt);
1350 return {calibBodySet, calibBodySetExtended};
1351 }
1352
1353 ParameterSet calibBodySet = transform.getScalingParameters();
1354 ParameterSet calibBodySetExtended = transformExtended.getScalingParameters();
1355 if (config.calibShape) {
1356 calibBodySet |= transform.getBlendShapeParameters();
1357 calibBodySetExtended |= transformExtended.getBlendShapeParameters();
1358 }
1359 return {calibBodySet, calibBodySetExtended};
1360}
1361
1362namespace {
1363
1364struct FilteredKeypointData {
1365 std::vector<CameraKeypointData> storage;
1366 std::span<const CameraKeypointData> original;
1367
1368 [[nodiscard]] std::span<const CameraKeypointData> span() const {
1369 return storage.empty() ? original : std::span<const CameraKeypointData>(storage);
1370 }
1371};
1372
1377FilteredKeypointData filterKeypointOutliers(
1378 const Character& character,
1379 const ParameterTransform& transform,
1380 const Eigen::MatrixXf& motion,
1381 std::span<const CameraKeypointData> cameraKeypointData,
1382 const CalibrationConfig& config) {
1383 FilteredKeypointData result;
1384 result.original = cameraKeypointData;
1385 if (cameraKeypointData.empty() || config.projectionWeight <= 0.0f) {
1386 return result;
1387 }
1388
1389 // TODO: make configurable via CalibrationConfig
1390 const float outlierFraction = 0.05f;
1391
1392 const SkeletonState skelState = skeletonStateForFrame(character, transform, motion, 0);
1393
1394 struct ObservationError {
1395 float pxErr;
1396 size_t camIdx;
1397 size_t locIdx;
1398 };
1399 std::vector<ObservationError> obsErrors;
1400 for (size_t iCam = 0; iCam < cameraKeypointData.size(); ++iCam) {
1401 const auto& camData = cameraKeypointData[iCam];
1402 if (camData.frameData.empty() || camData.frameData[0].empty()) {
1403 continue;
1404 }
1405 for (const auto& obs : camData.frameData[0]) {
1406 const auto reproj = keypointReprojection(character, skelState, camData.camera, obs);
1407 if (!reproj) {
1408 continue;
1409 }
1410 obsErrors.push_back({reproj->pxErr, iCam, obs.locatorIndex});
1411 }
1412 }
1413
1414 if (obsErrors.empty()) {
1415 return result;
1416 }
1417
1418 // Keep the lowest (1 - outlierFraction) of observations and drop the rest.
1419 // `threshold` is the largest *kept* error; dropping everything strictly above
1420 // it removes the intended top fraction. (The original min(floor(0.95 N), N-1)
1421 // index left the threshold at the max value, so the strict `>` dropped nothing
1422 // whenever (1 - f) * N was integral, e.g. N = 20.)
1423 std::vector<float> sortedErrors;
1424 sortedErrors.reserve(obsErrors.size());
1425 for (const auto& obsError : obsErrors) {
1426 sortedErrors.push_back(obsError.pxErr);
1427 }
1428 const auto keepCount = static_cast<size_t>((1.0f - outlierFraction) * sortedErrors.size());
1429 if (keepCount == 0 || keepCount >= sortedErrors.size()) {
1430 return result; // too few observations to robustly identify outliers
1431 }
1432 const size_t threshIdx = keepCount - 1;
1433 std::nth_element(sortedErrors.begin(), sortedErrors.begin() + threshIdx, sortedErrors.end());
1434 const float threshold = sortedErrors[threshIdx];
1435
1436 const size_t maxLoc = character.locators.size();
1437 std::unordered_set<size_t> dropPairs;
1438 for (const auto& obsError : obsErrors) {
1439 if (obsError.pxErr > threshold) {
1440 dropPairs.insert(obsError.camIdx * maxLoc + obsError.locIdx);
1441 const std::string name = obsError.locIdx < character.locators.size()
1442 ? character.locators[obsError.locIdx].name
1443 : "?";
1444 MT_LOGI(
1445 "Filtering cam[{}] keypoint [{}] {} ({:.1f}px > {:.1f}px)",
1446 obsError.camIdx,
1447 obsError.locIdx,
1448 name,
1449 obsError.pxErr,
1450 threshold);
1451 }
1452 }
1453
1454 if (dropPairs.empty()) {
1455 return result;
1456 }
1457
1458 result.storage.reserve(cameraKeypointData.size());
1459 for (size_t iCam = 0; iCam < cameraKeypointData.size(); ++iCam) {
1460 const auto& camData = cameraKeypointData[iCam];
1461 CameraKeypointData filtered;
1462 filtered.camera = camData.camera;
1463 filtered.frameData.resize(camData.frameData.size());
1464 for (size_t f = 0; f < camData.frameData.size(); ++f) {
1465 for (const auto& obs : camData.frameData[f]) {
1466 if (!dropPairs.contains(iCam * maxLoc + obs.locatorIndex)) {
1467 filtered.frameData[f].push_back(obs);
1468 }
1469 }
1470 }
1471 result.storage.push_back(std::move(filtered));
1472 }
1473 MT_LOGI("Filtered {} camera-keypoint pairs (>{:.1f}px threshold)", dropPairs.size(), threshold);
1474 return result;
1475}
1476
1477} // namespace
1478
1480 const std::span<const std::vector<Marker>> markerData,
1481 const CalibrationConfig& config,
1482 Character& character,
1483 ModelParameters& identity,
1484 const std::array<float, 3>& regularizerWeights,
1485 std::span<const GloveFrameData> leftGloveData,
1486 std::span<const GloveFrameData> rightGloveData,
1487 const std::optional<GloveConfig>& gloveConfig,
1488 std::span<const CameraKeypointData> cameraKeypointData,
1489 std::vector<size_t>* selectedFrameIndices,
1490 Eigen::MatrixXf* selectedFrameMotion) {
1491 const size_t numFrames = markerData.size();
1492 MT_THROW_IF(numFrames < 2, "Calibration requires at least 2 frames, got {}.", numFrames);
1494 identity.v.size() != character.parameterTransform.numAllModelParameters(),
1495 "Input identity parameters {} do not match character parameters {}",
1496 identity.v.size(),
1499 !leftGloveData.empty() && leftGloveData.size() != numFrames,
1500 "Left glove data has {} frames but marker data has {} frames",
1501 leftGloveData.size(),
1502 numFrames);
1504 !rightGloveData.empty() && rightGloveData.size() != numFrames,
1505 "Right glove data has {} frames but marker data has {} frames",
1506 rightGloveData.size(),
1507 numFrames);
1508 validateCameraKeypointFrameCount(cameraKeypointData, numFrames);
1509
1512 "enforceFloorInFirstFrame and adaptiveFloorContact are mutually exclusive.");
1513 MT_THROW_IF(config.calibFrames == 0, "calibFrames must be > 0.");
1514 if (numFrames < config.calibFrames) {
1515 MT_LOGW(
1516 "Only {} frames available for calibration (requested {}); using all frames.",
1517 numFrames,
1518 config.calibFrames);
1519 }
1520
1521 logKeypointObservationSummary(cameraKeypointData, config.projectionWeight);
1522
1523 MT_LOGI(
1524 "calibrateModel: {} frames, {} locators, {} skinnedLocators, {} joints, "
1525 "leftGlove={}, rightGlove={}, keypoints={} cameras",
1526 numFrames,
1527 character.locators.size(),
1528 character.skinnedLocators.size(),
1529 character.skeleton.joints.size(),
1530 leftGloveData.size(),
1531 rightGloveData.size(),
1532 cameraKeypointData.size());
1533
1534 // uniformly sample frames for calibration
1535 const size_t frameStride = computeSampleStride(numFrames, config.calibFrames);
1536
1537 // create a solving character with markers as bones
1538 Character solvingCharacter = character;
1539 solvingCharacter = createLocatorCharacter(solvingCharacter, "locator_");
1540 if (!solvingCharacter.skinnedLocators.empty()) {
1541 solvingCharacter = addSkinnedLocatorParametersToTransform(solvingCharacter);
1542 }
1543
1544 // Add glove bones to the solving character if glove data is provided
1545 if (gloveConfig && (!leftGloveData.empty() || !rightGloveData.empty())) {
1546 solvingCharacter = createGloveCharacter(solvingCharacter, *gloveConfig);
1547 }
1548
1549 // Extended quantities are for the solvingCharacter, which includes locators as bones
1550 // w/o Extended quantities are for character with fixed locators
1551 const ParameterTransform& transformExtended = solvingCharacter.parameterTransform;
1552 const ParameterTransform& transform = character.parameterTransform;
1553
1554 ParameterSet locatorSet = transformExtended.getParameterSet("locators", true) |
1555 transformExtended.getParameterSet("skinnedLocators", true);
1556 ParameterSet gloveSet = transformExtended.getParameterSet("gloves", true);
1557 const auto [calibBodySet, calibBodySetExtended] =
1558 buildCalibBodySets(config, transform, transformExtended);
1559
1560 // special trackingConfig for initialization: zero out smoothness and collision
1561 TrackingConfig trackingConfig;
1562 trackingConfig.minVisPercent = config.minVisPercent;
1563 trackingConfig.lossAlpha = config.lossAlpha;
1564 trackingConfig.maxIter = config.maxIter;
1565 trackingConfig.regularization = config.regularization;
1566 trackingConfig.debug = config.debug;
1567 trackingConfig.meshConstraintWeight = config.meshConstraintWeight;
1568 trackingConfig.projectionWeight = config.projectionWeight;
1569
1570 // only keep one motion; no need to duplicate.
1571 // identity information will be initialized and updated in the motion matrix throughout all the
1572 // solves.
1573 MatrixXf motion = MatrixXf::Zero(transformExtended.numAllModelParameters(), numFrames);
1574 std::vector<size_t> frameIndices;
1575
1576 { // Initialization
1577 MT_LOGI_IF(config.debug, "Solving for an initial pose and skeleton");
1578
1579 // first solve for initial tracking poses with fixed identity and locators to default
1580 // Because we are solving for poses only, use character to save compute.
1581 if (config.greedySampling > 0) {
1582 // first only track the first frame
1583 MT_LOGI_IF(config.debug, "Pre-solving for the first frame");
1584 std::vector<size_t> firstFrame;
1585 firstFrame.push_back(0);
1586 motion.topRows(transform.numAllModelParameters()) = trackPosesForFrames(
1587 markerData,
1588 character,
1589 motion.topRows(transform.numAllModelParameters()),
1590 trackingConfig,
1591 firstFrame,
1592 false, // Not continuous for calibration keyframes
1593 {},
1594 {},
1595 std::nullopt,
1596 "Calibrating first frame");
1597 motion.topRows(transform.numAllModelParameters()) = trackSequence(
1598 markerData,
1599 character,
1600 calibBodySet,
1601 motion.topRows(transform.numAllModelParameters()),
1602 trackingConfig,
1603 firstFrame,
1604 regularizerWeights.at(0),
1607 config.targetHeightCm); // still solving a subset
1608 std::tie(identity.v, character.locators, character.skinnedLocators) =
1609 extractIdAndLocatorsFromParams(motion.col(0), solvingCharacter, character);
1610
1611 // track sequence with selected stride. we need to sample at least config.calibFrames frames
1612 // so make sure we have a stride that allows that
1613 const size_t sampleStride =
1614 computeSampleStride(numFrames, config.calibFrames, config.greedySampling);
1615
1616 motion.topRows(transform.numAllModelParameters()) =
1617 trackPosesPerframe(markerData, character, identity, trackingConfig, sampleStride);
1618
1619 const ParameterSet ps = transformExtended.getPoseParameters() &
1620 ~transformExtended.getRigidParameters() & ~locatorSet;
1621 frameIndices = sampleFrames(
1622 character,
1623 motion.topRows(transform.numAllModelParameters()),
1624 markerData,
1625 ps,
1626 sampleStride,
1627 config.calibFrames);
1628
1629 } else {
1630 motion.topRows(transform.numAllModelParameters()) =
1631 trackPosesPerframe(markerData, character, identity, trackingConfig, frameStride);
1632
1633 // Build uniform-stride frame indices.
1634 for (size_t i = 0; i < numFrames; i += frameStride) {
1635 frameIndices.push_back(i);
1636 }
1637 }
1638
1639 // Solve for identity and poses with fixed locators, initialized with solved poses.
1640 // This works using "character" because additional parameters for the locators are appended at
1641 // the end, so the indices work out using topRows() without special treatment.
1642 motion.topRows(transform.numAllModelParameters()) = trackSequence(
1643 markerData,
1644 character,
1645 calibBodySet,
1646 motion.topRows(transform.numAllModelParameters()),
1647 trackingConfig,
1648 frameIndices,
1649 regularizerWeights.at(0),
1652 config.targetHeightCm);
1653 }
1654
1655 if (selectedFrameIndices != nullptr) {
1656 *selectedFrameIndices = frameIndices;
1657 }
1658
1660 character, transform, motion, cameraKeypointData, config, "after Stage 0");
1661
1662 auto filteredKeypoints =
1663 filterKeypointOutliers(character, transform, motion, cameraKeypointData, config);
1664
1665 // Solve everything together for a few iterations
1666 const auto calibFloorConstraints =
1667 createFloorConstraints<float>("Floor_", character.locators, Vector3f::UnitY(), 0.0f, 5.0f);
1668 std::vector<std::vector<PlaneDataT<float>>> perFrameFloorContacts;
1669
1670 for (size_t iIter = 0; iIter < config.majorIter; ++iIter) {
1671 MT_LOGI_IF(config.debug, "Iteration {} of calibration", iIter);
1672
1673 motion = trackSequence(
1674 markerData,
1675 solvingCharacter,
1676 locatorSet | calibBodySetExtended | gloveSet,
1677 motion,
1678 trackingConfig,
1679 frameIndices,
1680 regularizerWeights.at(1),
1683 config.targetHeightCm,
1684 leftGloveData,
1685 rightGloveData,
1686 gloveConfig,
1687 filteredKeypoints.span(),
1688 perFrameFloorContacts);
1689 // extract solving results to identity and character so we can pass them to trackPosesPerframe
1690 // below.
1691 std::tie(identity.v, character.locators, character.skinnedLocators) =
1692 extractIdAndLocatorsFromParams(motion.col(0), solvingCharacter, character);
1693
1694 // Update per-locator floor contact constraints for the next iteration
1695 if (config.adaptiveFloorContact && !calibFloorConstraints.empty()) {
1696 perFrameFloorContacts = computeFloorContactConstraints(
1697 solvingCharacter,
1698 motion,
1699 calibFloorConstraints,
1700 frameIndices,
1701 config.floorContactPercentile);
1702 }
1703 if (config.calibShape && solvingCharacter.blendShape) {
1704 auto blendShapeParams =
1705 extractBlendWeights(solvingCharacter.parameterTransform, ModelParameters(motion.col(0)));
1706 MT_LOGI("Solved for blend shape coeffs: {}", blendShapeParams.v.transpose());
1707 // NOTE: We intentionally do NOT bake the mesh here. The caller
1708 // (Python) is responsible for calling bake_blend_shape() which
1709 // both updates the mesh and strips the blend shape parameters
1710 // from the parameter transform.
1711 }
1712
1713 // The sequence solve above could get stuck with euler singularity but per-frame solve could get
1714 // it out. Pass in the first frame from previous solve as a better initial guess than the zero
1715 // pose.
1716 motion.topRows(transform.numAllModelParameters()) = trackPosesForFrames(
1717 markerData,
1718 character,
1719 motion.topRows(transform.numAllModelParameters()),
1720 trackingConfig,
1721 frameIndices,
1722 false, // Not continuous for calibration keyframes
1723 {},
1724 {},
1725 std::nullopt,
1726 "Calibrating per-frame");
1727 }
1728
1729 // Finally, fine tune marker offsets with fix identity.
1730 MT_LOGI_IF(config.debug, "Fine-tune marker offsets");
1731
1732 motion = trackSequence(
1733 markerData,
1734 solvingCharacter,
1735 locatorSet | gloveSet,
1736 motion,
1737 trackingConfig,
1738 frameIndices,
1739 regularizerWeights.at(2),
1742 config.targetHeightCm,
1743 leftGloveData,
1744 rightGloveData,
1745 gloveConfig,
1746 filteredKeypoints.span());
1747 std::tie(identity.v, character.locators, character.skinnedLocators) =
1748 extractIdAndLocatorsFromParams(motion.col(0), solvingCharacter, character);
1749
1750 // Bake solved glove offsets into the character skeleton, following the same
1751 // pattern as locator extraction above. No-op if gloveConfig is nullopt.
1753 character, ModelParameters(motion.col(0)), solvingCharacter, gloveConfig);
1754
1755 // TODO: A hack to return the solved first frame as initialization for tracking later.
1756 identity.v = motion.col(0).head(transform.numAllModelParameters());
1757
1758 // Extract solved motion for the selected calibration frames.
1759 if (selectedFrameMotion != nullptr && !frameIndices.empty()) {
1760 const auto nParams = transform.numAllModelParameters();
1761 selectedFrameMotion->resize(nParams, frameIndices.size());
1762 for (size_t i = 0; i < frameIndices.size(); ++i) {
1763 selectedFrameMotion->col(i) = motion.col(frameIndices[i]).head(nParams);
1764 }
1765 }
1766
1767 // Log final per-locator mesh distances
1768 logSkinnedLocatorMeshDistances(character, "Final");
1769
1771 character, transform, motion, filteredKeypoints.span(), config, "after final stage");
1772
1773 // Log the calibrated character height
1774 const float height = computeCharacterHeight(character, identity);
1775 MT_LOGI("Calibrated character height: {:.4f} cm", height);
1776}
1777
1790 const std::span<const std::vector<Marker>> markerData,
1791 const CalibrationConfig& config,
1792 const ModelParameters& identity,
1793 Character& character) {
1794 const size_t numFrames = markerData.size();
1795 MT_THROW_IF(numFrames < 2, "Calibration requires at least 2 frames, got {}.", numFrames);
1797 identity.v.size() != character.parameterTransform.numAllModelParameters(),
1798 "Input identity parameters {} do not match character parameters {}",
1799 identity.v.size(),
1801
1804 "enforceFloorInFirstFrame and adaptiveFloorContact are mutually exclusive.");
1805 MT_THROW_IF(config.calibFrames == 0, "calibFrames must be > 0.");
1806 if (numFrames < config.calibFrames) {
1807 MT_LOGW(
1808 "Only {} frames available for calibration (requested {}); using all frames.",
1809 numFrames,
1810 config.calibFrames);
1811 }
1812
1813 // create a solving character with locators as bones
1814 Character solvingCharacter = createLocatorCharacter(character, "locator_");
1815
1816 // Extended quantities are for the solvingCharacter, which includes locators as bones
1817 // w/o Extended quantities are for character with fixed locators
1818 const ParameterTransform& transformExtended = solvingCharacter.parameterTransform;
1819 const ParameterTransform& transform = character.parameterTransform;
1820
1821 ParameterSet locatorSet = transformExtended.parameterSets.find("locators")->second;
1822
1823 // special trackingConfig for initialization: zero out smoothness and collision
1824 TrackingConfig trackingConfig;
1825 trackingConfig.minVisPercent = config.minVisPercent;
1826 trackingConfig.lossAlpha = config.lossAlpha;
1827 trackingConfig.maxIter = config.maxIter;
1828 trackingConfig.regularization = config.regularization;
1829 trackingConfig.debug = config.debug;
1830 trackingConfig.meshConstraintWeight = config.meshConstraintWeight;
1831
1832 // only keep one motion for both character and solvingCharacter; no need to duplicate.
1833 // identity information will be initialized and updated in the motion matrix throughout all the
1834 // solves.
1835 MatrixXf motion = MatrixXf::Zero(transformExtended.numAllModelParameters(), numFrames);
1836 CharacterParameters fullParams;
1837
1838 // pick frames to solve
1839 std::vector<size_t> frameIndices;
1840 if (config.greedySampling > 0) {
1841 // track sequence with selected stride. we need to sample at least config.calibFrames frames
1842 // so make sure we have a stride that allows that
1843 const size_t sampleStride =
1844 computeSampleStride(numFrames, config.calibFrames, config.greedySampling);
1845 motion.topRows(transform.numAllModelParameters()) =
1846 trackPosesPerframe(markerData, character, identity, trackingConfig, sampleStride);
1847
1848 const ParameterSet ps = transformExtended.getPoseParameters() &
1849 ~transformExtended.getRigidParameters() & ~locatorSet;
1850 frameIndices = sampleFrames(
1851 character,
1852 motion.topRows(transform.numAllModelParameters()),
1853 markerData,
1854 ps,
1855 sampleStride,
1856 config.calibFrames);
1857 } else {
1858 // uniformly sample frames for calibration
1859 const size_t frameStride = computeSampleStride(numFrames, config.calibFrames);
1860 for (size_t fi = 0; fi < numFrames; fi += frameStride) {
1861 frameIndices.emplace_back(fi);
1862 }
1863
1864 motion.topRows(transform.numAllModelParameters()) =
1865 trackPosesPerframe(markerData, character, identity, trackingConfig, frameStride);
1866 }
1867
1868 // Iterate for a few times
1869 for (size_t iIter = 0; iIter < config.majorIter; ++iIter) {
1870 MT_LOGI_IF(config.debug, "Iteration {} of locator calibration", iIter);
1871
1872 // Solve only for poses using solved locators; it helps to adjust poses to get out of bad
1873 // solutions.
1874 motion.topRows(transform.numAllModelParameters()) = trackPosesForFrames(
1875 markerData,
1876 character,
1877 motion.topRows(transform.numAllModelParameters()),
1878 trackingConfig,
1879 frameIndices,
1880 false, // Not continuous for calibration keyframes
1881 {},
1882 {},
1883 std::nullopt,
1884 "Calibrating locators per-frame");
1885
1886 // Solve for both markers and poses.
1887 // TODO: add a small regularization to prevent too large a change
1888 motion = trackSequence(
1889 markerData,
1890 solvingCharacter,
1891 locatorSet,
1892 motion,
1893 trackingConfig,
1894 frameIndices,
1895 0.0,
1898 // Extract solved locators
1899 fullParams.pose = motion.col(0);
1900 character.locators = extractLocatorsFromCharacter(solvingCharacter, fullParams);
1901 }
1902}
1903
1916 std::span<const std::vector<momentum::Marker>> markerData,
1917 const MatrixXf& motion,
1918 const RefineConfig& config,
1919 momentum::Character& character) {
1920 MT_THROW_IF(markerData.empty(), "Input marker data is empty.");
1922 markerData.size() != motion.cols(),
1923 "markers and motion frames mismatch: {} != {}",
1924 markerData.size(),
1925 motion.cols());
1926
1927 MatrixXf newMotion;
1928 const ParameterSet idParamSet = character.parameterTransform.getScalingParameters();
1929
1930 // use sequenceSolve to smooth out the input motion
1931 if (!config.calibLocators) {
1932 newMotion = trackSequence(
1933 markerData,
1934 character,
1935 config.calibId ? idParamSet : ParameterSet(),
1936 motion,
1937 config,
1938 config.regularizer);
1939 } else {
1940 // create a solving character with markers as bones
1941 Character solvingCharacter = createLocatorCharacter(character, "locator_");
1942 const ParameterTransform& transformExtended = solvingCharacter.parameterTransform;
1943 const ParameterSet locatorSet = transformExtended.parameterSets.find("locators")->second;
1944 ParameterSet calibrationSet = locatorSet;
1945 if (config.calibId) {
1946 calibrationSet |= transformExtended.getScalingParameters();
1947 }
1948
1949 const auto numParams = character.parameterTransform.numAllModelParameters();
1950 const auto numParamsExtended = transformExtended.numAllModelParameters();
1951 MatrixXf motionExtended(numParamsExtended, markerData.size());
1952 motionExtended.setZero();
1953 motionExtended.topRows(numParams) = motion;
1954 newMotion = trackSequence(
1955 markerData, solvingCharacter, calibrationSet, motionExtended, config, config.regularizer);
1956
1957 std::tie(std::ignore, character.locators, character.skinnedLocators) =
1958 extractIdAndLocatorsFromParams(newMotion.col(0), solvingCharacter, character);
1959 newMotion.conservativeResize(numParams, Eigen::NoChange_t::NoChange);
1960 }
1961
1962 return newMotion;
1963}
1964
1978std::pair<float, float> getLocatorError(
1979 std::span<const std::vector<momentum::Marker>> markerData,
1980 const MatrixXf& motion,
1981 momentum::Character& character) {
1982 const size_t numFrames = markerData.size();
1983 MT_CHECK(numFrames > 0, "Input marker data is empty.");
1984 MT_CHECK(
1985 motion.cols() >= numFrames,
1986 "Motion has {} columns but marker data has {} frames",
1987 motion.cols(),
1988 numFrames);
1989 MT_CHECK(
1990 motion.rows() == character.parameterTransform.numAllModelParameters(),
1991 "Input motion parameters {} do not match character model parameters {}",
1992 motion.rows(),
1994
1995 const ParameterTransform& pt = character.parameterTransform;
1996
1997 // map locator name to its index
1998 std::map<std::string, size_t> locatorLookup;
1999 for (size_t i = 0; i < character.locators.size(); i++) {
2000 locatorLookup[character.locators[i].name] = i;
2001 }
2002
2003 // map skinned locator name to its index
2004 std::unordered_map<std::string, size_t> skinnedLocatorLookup;
2005 for (size_t i = 0; i < character.skinnedLocators.size(); i++) {
2006 skinnedLocatorLookup[character.skinnedLocators[i].name] = i;
2007 }
2008
2009 SkeletonState state;
2010
2011 // go over all frames and pose the locators and compute the error
2012 double error = 0.0;
2013 double maxError = 0.0;
2014 size_t frameNum = 0.0;
2015 std::string markerName;
2016 for (size_t iFrame = 0; iFrame < numFrames; ++iFrame) {
2017 const auto jointParams = pt.apply(motion.col(iFrame));
2018 state.set(jointParams, character.skeleton, false);
2019
2020 double frameError = 0.0;
2021
2022 const auto& markerList = markerData[iFrame];
2023 size_t validMarkers = 0;
2024 for (const auto& jMarker : markerList) {
2025 if (jMarker.occluded) {
2026 continue;
2027 }
2028
2029 std::optional<Vector3f> locatorPos;
2030
2031 // First try regular locators
2032 auto query = locatorLookup.find(jMarker.name);
2033 if (query != locatorLookup.end()) {
2034 size_t locatorIdx = query->second;
2035 if (locatorIdx < character.locators.size()) {
2036 const auto& locator = character.locators[locatorIdx];
2037 if (locator.parent < state.jointState.size()) {
2038 locatorPos = state.jointState[locator.parent].transform * locator.offset;
2039 }
2040 }
2041 }
2042
2043 // If not found, try skinned locators
2044 if (!locatorPos.has_value()) {
2045 auto skinnedQuery = skinnedLocatorLookup.find(jMarker.name);
2046 if (skinnedQuery != skinnedLocatorLookup.end()) {
2047 size_t locatorIdx = skinnedQuery->second;
2048 if (locatorIdx < character.skinnedLocators.size()) {
2049 const auto& skinnedLocator = character.skinnedLocators[locatorIdx];
2050 locatorPos = getSkinnedLocatorPosition(
2051 skinnedLocator, skinnedLocator.position, character.inverseBindPose, state);
2052 }
2053 }
2054 }
2055
2056 if (!locatorPos.has_value()) {
2057 continue;
2058 }
2059
2060 const Vector3f diff = *locatorPos - jMarker.pos.cast<float>();
2061 const float markerError = diff.norm();
2062 frameError += markerError;
2063 if (markerError > maxError) {
2064 maxError = markerError;
2065 frameNum = iFrame;
2066 markerName = jMarker.name;
2067 }
2068 validMarkers++;
2069 }
2070
2071 if (validMarkers > 0) {
2072 error += frameError / validMarkers;
2073 }
2074 }
2075 MT_LOGI("Max marker error: {} at frame {} for marker {}", maxError, frameNum, markerName);
2076 return {static_cast<float>(error / numFrames), static_cast<float>(maxError)};
2077}
2078
2079} // 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
void setOptions(const SolverOptions &options) final
Updates solver configuration with new options.
A terminal progress bar rendered as Name [===> ] 60%.
void increment(size_t count=1)
Advances progress by count (default 1) and redraws the bar.
void setEnabledParameters(const ParameterSet &parameters) final
Specifies which parameters should be optimized.
const ModelParametersT< T > & getFrameParameters(size_t frame) const
void setFrameParameters(size_t frame, const ModelParametersT< T > &parameters)
Eigen::VectorX< T > getJoinedParameterVector() const
void addSequenceErrorFunction(size_t startFrame, std::shared_ptr< SequenceErrorFunctionT< T > > errorFunction)
double getError(const Eigen::VectorX< T > &parameters) final
void addErrorFunction(size_t frame, std::shared_ptr< SkeletonErrorFunctionT< T > > errorFunction)
double solve(Eigen::VectorX< T > &params)
Solves the optimization problem.
Definition solver.cpp:50
virtual void setEnabledParameters(const ParameterSet &parameters)
Specifies which parameters should be optimized.
Definition solver.cpp:40
#define MT_THROW_IF(Condition,...)
Conditionally throws a std::runtime_error with a formatted message if the condition is true.
Definition exception.h:55
libfmt formatter support for Eigen types.
Functions for linear blend skinning (Skeletal Subspace Deformation).
#define MT_LOGI(...)
Definition log.h:179
#define MT_LOGW(...)
Definition log.h:180
#define MT_LOGI_IF(condition,...)
Definition log.h:185
std::vector< size_t > sampleFrames(momentum::Character &character, const MatrixXf &initialMotion, std::span< const std::vector< momentum::Marker > > markerData, const ParameterSet &parameters, const size_t frameStride, const size_t numSamples)
Sample representative frames from motion data to maximize parameter variance.
void addKeypointProjectionConstraints(SequenceSolverFunctionT< float > &solverFunc, size_t solverFrame, size_t iFrame, const Character &character, float projectionWeight, std::span< const CameraKeypointData > cameraKeypointData)
Add 2D keypoint projection constraints from outside-in cameras for one solver frame.
void addBlendShapeRegularizer(SequenceSolverFunctionT< float > &solverFunc, size_t solverFrame, size_t solvedFrames, const Character &character)
Add a blend shape regularizer that penalizes deviations from zero for all blend shape parameters.
LocatorList extractLocatorsFromCharacter(const Character &locatorCharacter, const CharacterParameters &calibParams)
Eigen::MatrixXf trackSequence(const std::span< const std::vector< Marker > > markerData, const Character &character, const ParameterSet &globalParams, const MatrixXf &initialMotion, const TrackingConfig &config, float regularizer, const size_t frameStride, bool enforceFloorInFirstFrame, const std::string &firstFramePoseConstraintSet, float targetHeightCm, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig, std::span< const CameraKeypointData > cameraKeypointData)
Track motion across multiple frames simultaneously with temporal constraints.
void bakeGloveOffsetsFromParams(Character &character, const ModelParameters &solvedParams, const Character &solvingCharacter, const std::optional< GloveConfig > &cfg)
Bake solved glove offsets from calibration parameters into the skeleton.
std::pair< ParameterSet, ParameterSet > buildCalibBodySets(const CalibrationConfig &config, const ParameterTransform &transform, const ParameterTransform &transformExtended)
constexpr size_t kAllFrames
Eigen::MatrixXf trackPosesForFrames(const std::span< const std::vector< Marker > > markerData, const Character &character, const MatrixXf &initialMotion, const TrackingConfig &config, const std::vector< size_t > &frameIndices, bool isContinuous, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig, const std::string &progressLabel)
Track poses independently for specific frame indices with fixed character identity.
std::pair< float, float > getLocatorError(std::span< const std::vector< momentum::Marker > > markerData, const MatrixXf &motion, momentum::Character &character)
Compute average and maximum marker tracking errors across all frames.
void skinWithBlendShapes(const Character &character, const SkeletonStateT< T > &state, const ModelParametersT< T > &modelParams, MeshT< T > &outputMesh)
Applies blend shape deformations and skeletal transformations to a mesh.
void addGloveConstraintsToSequenceSolver(SequenceSolverFunctionT< float > &solverFunc, size_t solverFrame, const Character &character, const std::vector< std::vector< JointToJointPositionDataT< float > > > &posData, const std::vector< std::vector< JointToJointOrientationDataT< float > > > &oriData, size_t iFrame, float posWeight, float oriWeight)
Add glove error functions to a SequenceSolverFunction for one frame.
std::tuple< Eigen::VectorXf, LocatorList, SkinnedLocatorList > extractIdAndLocatorsFromParams(const ModelParameters &param, const Character &sourceCharacter, const Character &targetCharacter)
Vector3< T > getSkinnedLocatorPosition(const SkinnedLocator &locator, const Vector3< T > &restPosition, const TransformationList &inverseBindPose, const SkeletonStateT< T > &state)
Computes the world position of a skinned locator using linear blend skinning.
bool solveRigidInitialization(GaussNewtonSolverQR &solver, GaussNewtonSolverQROptions &solverOptions, Eigen::VectorXf &dof, const ParameterTransform &pt, const ParameterSet &poseParams, const std::shared_ptr< ModelParametersErrorFunction > &smoothConstrFunc, const TrackingConfig &config, bool isContinuous, size_t iFrame)
Solve for rigid parameters only as initialization for a frame.
MeshT< float > Mesh
Definition fwd.h:20
Eigen::MatrixXf trackPosesPerframe(const std::span< const std::vector< Marker > > markerData, const Character &character, const ModelParameters &globalParams, const TrackingConfig &config, const size_t frameStride, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig)
Track poses independently per frame with fixed character identity.
std::vector< std::vector< SkinnedLocatorConstraint > > createSkinnedConstraintData(const std::span< const std::vector< Marker > > markerData, const SkinnedLocatorList &locators)
std::vector< std::pair< std::string, float > > computeSkinnedLocatorMeshDistances(const Character &character)
Compute the distance from each skinned locator to the closest point on the mesh surface.
std::tuple< ParameterTransform, ParameterLimits > addSkinnedLocatorParameters(ParameterTransform paramTransform, ParameterLimits paramLimits, const std::vector< bool > &activeLocators, const std::vector< std::string > &locatorNames)
Add a set of parameters that control the rest-space positions of the skinned locators.
std::vector< std::vector< JointToJointOrientationDataT< float > > > createGloveOrientationConstraintData(std::span< const GloveFrameData > gloveData, const Character &character, const GloveConfig &cfg, size_t handIndex)
Convert per-frame glove observations to JointToJoint orientation constraints.
GaussNewtonSolverQRT< float > GaussNewtonSolverQR
Definition fwd.h:685
ParameterTransformT< float > ParameterTransform
Definition fwd.h:244
Character createLocatorCharacter(const Character &sourceCharacter, const std::string &prefix)
MatrixXf refineMotion(std::span< const std::vector< momentum::Marker > > markerData, const MatrixXf &motion, const RefineConfig &config, momentum::Character &character)
Refine existing motion by smoothing and optionally recalibrating identity/locators.
SkeletonStateT< float > SkeletonState
Definition fwd.h:282
std::vector< momentum::SkinnedLocatorTriangleConstraintT< float > > createSkinnedLocatorMeshConstraints(const momentum::Character &character, float cutoffWeight, float maxSearchDistanceCm, float maxNormalAngleDeg)
Character addSkinnedLocatorParametersToTransform(Character character)
Character createGloveCharacter(const Character &src, const GloveConfig &cfg, const std::string &prefix)
Add glove bones with 6-DOF model parameters (convenience wrapper).
bool isGlobalTransformZero(const Eigen::VectorXf &dof, const ParameterSet &rigidParams)
Check if the global transform is zero by checking if any rigid parameters are non-zero.
void calibrateLocators(const std::span< const std::vector< Marker > > markerData, const CalibrationConfig &config, const ModelParameters &identity, Character &character)
Calibrate only locator positions with fixed character identity parameters.
CharacterParametersT< float > CharacterParameters
Definition types.h:168
std::vector< std::vector< PositionData > > createConstraintData(const std::span< const std::vector< Marker > > markerData, const LocatorList &locators)
void calibrateModel(const std::span< const std::vector< Marker > > markerData, const CalibrationConfig &config, Character &character, ModelParameters &identity, const std::array< float, 3 > &regularizerWeights, std::span< const GloveFrameData > leftGloveData, std::span< const GloveFrameData > rightGloveData, const std::optional< GloveConfig > &gloveConfig, std::span< const CameraKeypointData > cameraKeypointData, std::vector< size_t > *selectedFrameIndices, Eigen::MatrixXf *selectedFrameMotion)
void addSequenceFrameConstraints(SequenceSolverFunctionT< float > &solverFunc, size_t solverFrame, size_t iFrame, size_t solvedFrames, const Character &character, const TrackingConfig &config, const std::vector< std::vector< PositionData > > &constrData, const std::vector< std::vector< SkinnedLocatorConstraint > > &skinnedConstData, const std::vector< SkinnedLocatorTriangleConstraintT< float > > &skinnedLocatorMeshContraints, const std::vector< PlaneDataT< float > > &floorConstraints, bool enforceFloorInFirstFrame, const std::string &firstFramePoseConstraintSet, float targetHeightCm, const std::optional< GloveConfig > &gloveConfig, const std::vector< std::vector< JointToJointPositionDataT< float > > > &leftGlovePosData, const std::vector< std::vector< JointToJointOrientationDataT< float > > > &leftGloveOriData, const std::vector< std::vector< JointToJointPositionDataT< float > > > &rightGlovePosData, const std::vector< std::vector< JointToJointOrientationDataT< float > > > &rightGloveOriData, std::span< const CameraKeypointData > cameraKeypointData={}, std::span< const std::vector< PlaneDataT< float > > > perFrameFloorContacts={})
Add per-frame marker, floor, and glove constraints for one frame of the sequence solver.
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
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
void updateGloveConstraintsForFrame(GloveErrorFunctions &funcs, size_t iFrame)
Swap per-frame glove constraint data on already-registered error functions.
Vector3< float > Vector3f
Definition types.h:251
VectorX< float > VectorXf
Definition types.h:209
std::vector< std::vector< PlaneDataT< float > > > computeFloorContactConstraints(const Character &character, const MatrixXf &motion, const std::vector< PlaneDataT< float > > &floorConstraints, const std::vector< size_t > &frameIndices, float percentile)
ParameterLimits getPoseConstraintParameterLimits(const std::string &name, const ParameterTransform &pt, const float weight)
Creates MinMax limits from a pose constraint.
void updateGloveConstraintsForBothHands(std::optional< GloveErrorFunctions > &left, std::optional< GloveErrorFunctions > &right, size_t iFrame)
Update glove constraints for both hands for a given frame.
SequenceSolverFunctionT< float > SequenceSolverFunction
Definition fwd.h:328
std::optional< GloveErrorFunctions > setupGloveErrorFunctions(SkeletonSolverFunctionT< float > &solverFunc, const Character &character, std::span< const GloveFrameData > gloveData, const GloveConfig &cfg, size_t handIndex)
Create and register glove error functions for the per-frame solver.
void preprocessMarkerGaps(std::vector< std::vector< Marker > > &markerData, const GapFillConfig &config)
Pre-process marker data to fill temporary gaps and blend off permanent dropouts.
std::bitset< kMaxModelParams > ParameterSet
Bitset for model parameter enablement.
Definition types.h:430
BlendWeightsT< T > extractBlendWeights(const ParameterTransform &paramTransform, const ModelParametersT< T > &modelParams)
Extracts blend shape weights from model parameters.
void logKeypointReprojectionDiagnostic(const Character &character, const ParameterTransform &transform, const Eigen::MatrixXf &motion, std::span< const CameraKeypointData > cameraKeypointData, const CalibrationConfig &config, const std::string &label)
MatrixX< float > MatrixXf
Definition types.h:82
std::vector< std::vector< JointToJointPositionDataT< float > > > createGlovePositionConstraintData(std::span< const GloveFrameData > gloveData, const Character &character, const GloveConfig &cfg, size_t handIndex)
Convert per-frame glove observations to JointToJoint position constraints.
SequenceSolverT< float > SequenceSolver
Definition fwd.h:309
template std::vector< PlaneDataT< float > > createFloorConstraints< float >(const std::string &prefix, const LocatorList &locators, const Vector3f &floorNormal, const float &floorOffset, const float weight)
SkeletonSolverFunctionT< float > SkeletonSolverFunction
Definition fwd.h:1103
float regularization
Regularization parameter (lambda) for Levenberg-Marquardt solver.
size_t maxIter
Max number of solver iterations to run.
float minVisPercent
Minimum percentage of visible markers in a frame to consider for tracking.
float lossAlpha
Parameter to control what loss function to use.
bool debug
True to print and save debug information.
Configuration for running body and/or locator calibration.
float floorContactPercentile
Percentile threshold for adaptive floor contact detection (0-1).
bool enforceFloorInFirstFrame
Force all floor locators to y=0 on frame 0 with high weight.
float meshConstraintWeight
Multiplier for the mesh surface constraint weight on skinned locators during shape calibration.
float projectionWeight
Base weight for 2D keypoint projection constraints. Set to 0 to disable.
std::string firstFramePoseConstraintSet
Name of a pose constraint set to use for the first frame.
size_t majorIter
Number of iterations to run the main calibration loop.
float targetHeightCm
Target height in cm for the character, if set to 0, no height constraint is applied.
size_t greedySampling
Sample uniformly or do a greedy importance sampling.
bool adaptiveFloorContact
Enable adaptive floor contact detection during calibration.
bool calibShape
Calibrate the character's shape.
size_t calibFrames
Number of frames used in calibration. It will be a uniform sample from the input.
bool globalScaleOnly
True to only solve for a global body scale without changing individual bone length.
Per-camera 2D keypoint data for all frames.
std::vector< std::vector< KeypointObservation > > frameData
Per-frame keypoint observations.
Camera camera
Camera intrinsics and extrinsics (world-space).
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
ParameterLimits parameterLimits
Constraints on model parameters.
Definition character.h:46
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
SkinnedLocatorList skinnedLocators
Points of interest attached to joints, with skinning weights.
Definition character.h:52
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
static EIGEN_DEVICE_FUNC Derived< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
float regularization
Damping parameter added to Hessian diagonal for numerical stability; see https://en....
bool doLineSearch
Enables backtracking line search to ensure error reduction at each step.
Gauss-Newton solver with QR decomposition specific options.
Constraint data for joint-to-joint orientation error between two joints.
Constraint data for joint-to-joint position error between two joints.
A single 2D keypoint observation from a camera view.
float confidence
Detection confidence, used as weight multiplier.
Eigen::Vector2f target
Target 2D pixel coordinates.
size_t locatorIndex
Index into the character's locator list.
std::vector< Eigen::Vector3< T > > vertices
List of mesh vertices in 3D space.
Definition mesh.h:22
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 ...
ParameterSet getBlendShapeParameters() const
Get a list of blend shape parameters.
ParameterSet getRigidParameters() const
Get a list of root parameters (with prefix "root_").
VectorXi blendShapeParameters
The indices of the parameters that influence blend shapes; blendShapeParameters(0) is the parameter t...
ParameterSets parameterSets
Convenience grouping of model parameters.
size_t getParameterIdByName(const std::string &nm) const
Return the index of a model parameter from its name.
ParameterSet getParameterSet(const std::string &parameterSetName, bool allowMissing=false) const
Get a parameter set, if allowMissing is set then it will return an empty parameter set if no such par...
ParameterSet getPoseParameters() const
Return all parameters used for posing the body (excludes scaling parameters, blend shape parameters,...
Point-on-plane or Point-in-half-plane constraint data.
Configuration for refining an already tracked motion, eg.
bool calibLocators
Calibrate locators when refining the motion.
bool calibId
Calibrate identity parameters when refining the motion.
float regularizer
Minimize changes to calibration parameters when in calibration mode, by regularizing towards the inpu...
bool progressBar
Flag to enable a progress bar during optimization.
bool doLineSearch
Flag to enable line search during optimization.
float regularization
Regularization parameter used by the linearized sequence solve.
bool multithreaded
Flag to enable multithreaded sequence processing.
Sequence solver specific options.
void set(const JointParametersT< T > &jointParameters, const Skeleton &referenceSkeleton, bool computeDeriv=true)
Updates the skeleton state with new joint parameters.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
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
size_t minIterations
Minimum number of iterations before checking convergence criteria.
Definition solver.h:21
bool verbose
Enable detailed logging during optimization.
Definition solver.h:30
size_t maxIterations
Maximum number of iterations before terminating.
Definition solver.h:24
float threshold
Convergence threshold for relative error change.
Definition solver.h:27
Configuration for pose tracking given a calibrated body and locators.
GapFillConfig gapFillConfig
Configuration for pre-processing marker gaps before constraint creation.
float markerWeight
Multiplier for the marker position constraint weight.
float projectionWeight
Base weight for 2D keypoint projection constraints. Default 0 (disabled).
float collisionErrorWeight
The weight for the collision error function.
float smoothing
The weight for the smoothness error function.
std::optional< ParameterSet > activeParams
Optional mask to restrict which parameters are optimized during tracking.
float meshConstraintWeight
Multiplier for the mesh surface constraint weight on skinned locators.