Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
sdf_collision_error_function.h
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
8#pragma once
9
22#include <momentum/math/fwd.h>
23#include <momentum/math/mesh.h>
25
26#include <axel/BoundingBox.h>
27
28#include <algorithm>
29#include <memory>
30#include <span>
31#include <unordered_set>
32#include <vector>
33
34namespace momentum {
35
39 size_t start;
40 size_t end;
41
43 [[nodiscard]] size_t size() const {
44 return end - start;
45 }
46
48 [[nodiscard]] bool empty() const {
49 return start == end;
50 }
51};
52
54template <typename T>
59
75template <typename T, typename SdfColliderType = SDFColliderT<float>>
77 public:
85 const Character& character,
86 const std::vector<SdfColliderType>& sdfColliders,
87 const std::vector<int>& participatingVertices = {},
88 const std::vector<T>& vertexWeights = {},
89 bool filterRestPoseIntersections = true,
90 uint8_t maxCollisionsPerVertex = 1);
91
96 ~SDFCollisionErrorFunctionT() override = default;
97
98 [[nodiscard]] double getError(
99 const ModelParametersT<T>& params,
100 const SkeletonStateT<T>& state,
101 const MeshStateT<T>& meshState) override;
102
104 const ModelParametersT<T>& params,
105 const SkeletonStateT<T>& state,
106 const MeshStateT<T>& meshState,
107 Eigen::Ref<Eigen::VectorX<T>> gradient) override;
108
110 const ModelParametersT<T>& params,
111 const SkeletonStateT<T>& state,
112 const MeshStateT<T>& meshState,
113 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
114 Eigen::Ref<Eigen::VectorX<T>> residual,
115 int& usedRows) override;
116
117 [[nodiscard]] size_t getJacobianSize() const override;
118
119 [[nodiscard]] bool needsMesh() const override {
120 return true;
121 }
122
124 [[nodiscard]] const Character* getCharacter() const override {
125 return &character_;
126 }
127
128 [[nodiscard]] size_t getNumActiveVertices() const {
129 return activeVertexIndices_.size();
130 }
131
132 [[nodiscard]] size_t getNumCollisionPairs() const {
133 return boneCollisionPairs_.size();
134 }
135
136 static constexpr T kSDFCollisionWeight = T(5e-3);
137
138 private:
139 void organizeVerticesByBone(
140 const std::vector<int>& participatingVertices,
141 const std::vector<T>& weights);
142
143 void initializeBoneCollisionPairs(bool filterRestPoseIntersections);
144
145 [[nodiscard]] bool testRestPoseIntersection(
146 size_t boneIndex,
147 size_t sdfColliderIndex,
148 const SkeletonStateT<T>& restState) const;
149
150 void computeActivePairs(const MeshStateT<T>& meshState, const SkeletonStateT<T>& state);
151
152 void updateColliders(const ModelParametersT<T>& params);
153
154 [[nodiscard]] TransformT<T> computeWorldToColliderTransform(
155 size_t sdfColliderIndex,
156 const SkeletonStateT<T>& state) const;
157
158 [[nodiscard]] axel::BoundingBox<T> computeBoneBoundingBox(
159 size_t boneIndex,
160 const MeshT<T>& posedMesh) const;
161
162 [[nodiscard]] axel::BoundingBox<T> computeColliderWorldBoundingBox(
163 size_t sdfColliderIndex,
164 const SkeletonStateT<T>& state) const;
165
166 void accumulateJointGradient(
167 const JointStateT<T>& jointState,
168 size_t paramIndex,
169 const Eigen::Vector3<T>& posd,
170 const Eigen::Vector3<T>& direction,
171 Eigen::Ref<Eigen::VectorX<T>> gradient) const;
172
173 void accumulateJointJacobian(
174 const JointStateT<T>& jointState,
175 size_t paramIndex,
176 const Eigen::Vector3<T>& posd,
177 const Eigen::Vector3<T>& direction,
178 Eigen::Ref<Eigen::MatrixX<T>> jacobianRow) const;
179
180 void accumulateColliderHierarchyGradient(
181 const SkeletonStateT<T>& state,
182 size_t colliderParent,
183 size_t commonAncestor,
184 const Eigen::Vector3<T>& sdfSurfacePoint,
185 const Eigen::Vector3<T>& direction,
186 Eigen::Ref<Eigen::VectorX<T>> gradient) const;
187
188 void accumulateColliderHierarchyJacobian(
189 const SkeletonStateT<T>& state,
190 size_t colliderParent,
191 size_t commonAncestor,
192 const Eigen::Vector3<T>& sdfSurfacePoint,
193 const Eigen::Vector3<T>& direction,
194 Eigen::Ref<Eigen::MatrixX<T>> jacobianRow) const;
195
196 const Character& character_;
197 std::vector<SdfColliderType> sdfColliders_;
198
199 std::vector<size_t> activeVertexIndices_;
200 std::vector<BoneVertexRange> boneVertexRanges_;
201 std::vector<T> vertexWeights_;
202
203 std::vector<BoneCollisionPairT<T>> boneCollisionPairs_;
204
205 uint8_t maxCollisionsPerVertex_ = 1;
206
207 std::vector<bool> activePairs_;
208 std::vector<uint8_t> collisionCounts_;
209 std::vector<axel::BoundingBox<T>> boneBBoxCache_;
210 std::vector<bool> boneBBoxValid_;
211 std::vector<axel::BoundingBox<T>> sdfBBoxCache_;
212};
213
216
217// ============================================================================
218// Template implementation
219// ============================================================================
220//
221// Shared, stateless helpers (collider transforms, bounding boxes, joint chain-rule accumulation,
222// common-ancestor lookup) live in the `detail_sdf_collision` namespace in sdf_collision_utility.h
223// so they can be reused by the cross-frame (sequence) collision error functions. The member
224// functions below forward to those helpers, supplying this error function's skeleton, parameter
225// transform, active joints, and collider list.
226
227template <typename T, typename SdfColliderType>
229 const Character& character,
230 const std::vector<SdfColliderType>& sdfColliders,
231 const std::vector<int>& participatingVertices,
232 const std::vector<T>& vertexWeights,
233 bool filterRestPoseIntersections,
234 uint8_t maxCollisionsPerVertex)
235 : SkeletonErrorFunctionT<T>(character.skeleton, character.parameterTransform),
236 character_(character),
237 sdfColliders_(sdfColliders),
238 maxCollisionsPerVertex_(maxCollisionsPerVertex) {
239 MT_CHECK_NOTNULL(character_.mesh, "Character must have a mesh for SDF collision detection");
241 character_.skinWeights, "Character must have skin weights for SDF collision detection");
242 MT_CHECK(!sdfColliders_.empty(), "Must provide at least one SDF collider");
243 MT_CHECK(maxCollisionsPerVertex_ > 0, "maxCollisionsPerVertex must be positive");
244 MT_CHECK(maxCollisionsPerVertex_ <= 255, "maxCollisionsPerVertex must be <= 255");
245 organizeVerticesByBone(participatingVertices, vertexWeights);
246 initializeBoneCollisionPairs(filterRestPoseIntersections);
247}
248
249template <typename T, typename SdfColliderType>
250void SDFCollisionErrorFunctionT<T, SdfColliderType>::organizeVerticesByBone(
251 const std::vector<int>& participatingVertices,
252 const std::vector<T>& weights) {
253 std::vector<int> vertices;
254 if (participatingVertices.empty()) {
255 vertices.reserve(character_.mesh->vertices.size());
256 for (int i = 0; i < static_cast<int>(character_.mesh->vertices.size()); ++i) {
257 vertices.push_back(i);
258 }
259 } else {
260 vertices = participatingVertices;
261 }
262
263 for (int vertexIndex : vertices) {
264 MT_CHECK(
265 vertexIndex >= 0 && vertexIndex < static_cast<int>(character_.mesh->vertices.size()),
266 "Invalid vertex index: {} (mesh has {} vertices)",
267 vertexIndex,
268 character_.mesh->vertices.size());
269 }
270
271 std::vector<T> vertexWeights;
272 if (weights.empty()) {
273 vertexWeights.assign(vertices.size(), T(1));
274 } else {
275 MT_CHECK(
276 weights.size() == vertices.size(),
277 "Weight count ({}) must match vertex count ({})",
278 weights.size(),
279 vertices.size());
280 vertexWeights = weights;
281 }
282
283 struct VertexInfo {
284 size_t vertexIndex;
285 T weight;
286 size_t primaryBone;
287 };
288
289 std::vector<VertexInfo> vertexInfos;
290 vertexInfos.reserve(vertices.size());
291
292 MT_CHECK_NOTNULL(character_.skinWeights);
293 const auto& skinWeights = *character_.skinWeights;
294
295 for (size_t i = 0; i < vertices.size(); ++i) {
296 const int vertexIndex = vertices[i];
297 const T weight = vertexWeights[i];
298 const size_t primaryBone = skinWeights.index(vertexIndex, 0);
299 MT_CHECK(primaryBone < character_.skeleton.joints.size());
300 vertexInfos.push_back({static_cast<size_t>(vertexIndex), weight, primaryBone});
301 }
302
303 std::sort(vertexInfos.begin(), vertexInfos.end(), [](const VertexInfo& a, const VertexInfo& b) {
304 return a.primaryBone < b.primaryBone;
305 });
306
307 boneVertexRanges_.resize(character_.skeleton.joints.size());
308 activeVertexIndices_.reserve(vertices.size());
309 vertexWeights_.reserve(vertices.size());
310
311 size_t currentBone = 0;
312 for (size_t i = 0; i < vertexInfos.size(); ++i) {
313 const auto& info = vertexInfos[i];
314 while (currentBone < info.primaryBone) {
315 boneVertexRanges_[currentBone].end = i;
316 ++currentBone;
317 boneVertexRanges_[currentBone].start = i;
318 }
319 activeVertexIndices_.push_back(info.vertexIndex);
320 vertexWeights_.push_back(info.weight);
321 }
322
323 boneVertexRanges_[currentBone].end = activeVertexIndices_.size();
324 ++currentBone;
325 while (currentBone < boneVertexRanges_.size()) {
326 boneVertexRanges_[currentBone++] =
327 BoneVertexRange{activeVertexIndices_.size(), activeVertexIndices_.size()};
328 }
329}
330
331template <typename T, typename SdfColliderType>
332void SDFCollisionErrorFunctionT<T, SdfColliderType>::initializeBoneCollisionPairs(
333 bool filterRestPoseIntersections) {
334 std::unordered_set<size_t> activeBones;
335 for (size_t boneIndex = 0; boneIndex < boneVertexRanges_.size(); ++boneIndex) {
336 if (!boneVertexRanges_[boneIndex].empty()) {
337 activeBones.insert(boneIndex);
338 }
339 }
340
341 const SkeletonStateT<T> restState(
342 this->parameterTransform_.zero().template cast<T>(), this->skeleton_);
343 const ModelParametersT<T> restParams =
344 ModelParametersT<T>::Zero(this->parameterTransform_.numAllModelParameters());
345 updateColliders(restParams);
346
347 boneCollisionPairs_.clear();
348 boneCollisionPairs_.reserve(activeBones.size() * sdfColliders_.size());
349
350 for (size_t boneIndex : activeBones) {
351 if (boneVertexRanges_[boneIndex].empty()) {
352 continue;
353 }
354 for (size_t sdfIndex = 0; sdfIndex < sdfColliders_.size(); ++sdfIndex) {
355 const auto& collider = sdfColliders_[sdfIndex];
356 if (collider.parentJoint() != kInvalidIndex && filterRestPoseIntersections &&
357 testRestPoseIntersection(boneIndex, sdfIndex, restState)) {
358 continue;
359 }
360 boneCollisionPairs_.emplace_back(BoneCollisionPairT<T>{boneIndex, sdfIndex});
361 }
362 }
363}
364
365template <typename T, typename SdfColliderType>
366bool SDFCollisionErrorFunctionT<T, SdfColliderType>::testRestPoseIntersection(
367 size_t boneIndex,
368 size_t sdfColliderIndex,
369 const SkeletonStateT<T>& restState) const {
370 const auto& range = boneVertexRanges_[boneIndex];
371 if (range.empty()) {
372 return false;
373 }
374
375 const auto& collider = sdfColliders_[sdfColliderIndex];
376 if (!collider.isValid()) {
377 return false;
378 }
379
380 const auto worldToCollider = computeWorldToColliderTransform(sdfColliderIndex, restState);
381
382 for (size_t i = range.start; i < range.end; ++i) {
383 const size_t vertexIndex = activeVertexIndices_[i];
384 const auto& restPos = character_.mesh->vertices[vertexIndex].template cast<T>();
385 const Vector3<T> localPos = worldToCollider * restPos;
386 const T distance = collider.evaluate(localPos);
387 if (distance < T(0)) {
388 return true;
389 }
390 }
391 return false;
392}
393
394template <typename T, typename SdfColliderType>
395void SDFCollisionErrorFunctionT<T, SdfColliderType>::updateColliders(
396 const ModelParametersT<T>& params) {
397 for (auto& collider : sdfColliders_) {
398 collider.update(params.v);
399 }
400}
401
402template <typename T, typename SdfColliderType>
403TransformT<T> SDFCollisionErrorFunctionT<T, SdfColliderType>::computeWorldToColliderTransform(
404 size_t sdfColliderIndex,
405 const SkeletonStateT<T>& state) const {
407 sdfColliders_[sdfColliderIndex], state);
408}
409
410template <typename T, typename SdfColliderType>
412 const ModelParametersT<T>& params,
413 const SkeletonStateT<T>& state,
414 const MeshStateT<T>& meshState) {
416 MT_CHECK_NOTNULL(meshState.posedMesh_);
417 updateColliders(params);
418 computeActivePairs(meshState, state);
419
420 double totalError = 0.0;
421 collisionCounts_.assign(activeVertexIndices_.size(), 0);
422
423 for (size_t pairIndex = 0; pairIndex < boneCollisionPairs_.size(); ++pairIndex) {
424 if (!activePairs_[pairIndex]) {
425 continue;
426 }
427 const auto& pair = boneCollisionPairs_[pairIndex];
428 const auto& range = boneVertexRanges_[pair.boneIndex];
429 if (range.empty()) {
430 continue;
431 }
432 const auto& collider = sdfColliders_[pair.sdfColliderIndex];
433 if (!collider.isValid()) {
434 continue;
435 }
436 const auto worldToCollider = computeWorldToColliderTransform(pair.sdfColliderIndex, state);
437
438 for (size_t i = range.start; i < range.end; ++i) {
439 if (collisionCounts_[i] >= maxCollisionsPerVertex_) {
440 continue;
441 }
442 const size_t vertexIndex = activeVertexIndices_[i];
443 const T vertexWeight = vertexWeights_[i];
444 const auto& worldPos = meshState.posedMesh_->vertices[vertexIndex];
445 const Vector3<T> localPos = worldToCollider * worldPos;
446 const T distance = collider.evaluate(localPos);
447
448 if (distance < T(0)) {
449 collisionCounts_[i]++;
450 const T penetrationDepth = -distance;
451 totalError += static_cast<double>(
452 vertexWeight * penetrationDepth * penetrationDepth * kSDFCollisionWeight *
453 this->weight_);
454 }
455 }
456 }
457 return totalError;
458}
459
460template <typename T, typename SdfColliderType>
461void SDFCollisionErrorFunctionT<T, SdfColliderType>::accumulateJointGradient(
462 const JointStateT<T>& jointState,
463 size_t paramIndex,
464 const Eigen::Vector3<T>& posd,
465 const Eigen::Vector3<T>& direction,
466 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
468 jointState,
469 paramIndex,
470 posd,
471 direction,
472 this->activeJointParams_,
473 this->parameterTransform_,
474 gradient);
475}
476
477template <typename T, typename SdfColliderType>
478void SDFCollisionErrorFunctionT<T, SdfColliderType>::accumulateJointJacobian(
479 const JointStateT<T>& jointState,
480 size_t paramIndex,
481 const Eigen::Vector3<T>& posd,
482 const Eigen::Vector3<T>& direction,
483 Eigen::Ref<Eigen::MatrixX<T>> jacobianRow) const {
485 jointState,
486 paramIndex,
487 posd,
488 direction,
489 this->activeJointParams_,
490 this->parameterTransform_,
491 jacobianRow);
492}
493
494template <typename T, typename SdfColliderType>
495void SDFCollisionErrorFunctionT<T, SdfColliderType>::accumulateColliderHierarchyGradient(
496 const SkeletonStateT<T>& state,
497 size_t colliderParent,
498 size_t commonAncestor,
499 const Eigen::Vector3<T>& sdfSurfacePoint,
500 const Eigen::Vector3<T>& direction,
501 Eigen::Ref<Eigen::VectorX<T>> gradient) const {
503 state,
504 colliderParent,
505 commonAncestor,
506 sdfSurfacePoint,
507 direction,
508 this->skeleton_,
509 this->activeJointParams_,
510 this->parameterTransform_,
511 gradient);
512}
513
514template <typename T, typename SdfColliderType>
515void SDFCollisionErrorFunctionT<T, SdfColliderType>::accumulateColliderHierarchyJacobian(
516 const SkeletonStateT<T>& state,
517 size_t colliderParent,
518 size_t commonAncestor,
519 const Eigen::Vector3<T>& sdfSurfacePoint,
520 const Eigen::Vector3<T>& direction,
521 Eigen::Ref<Eigen::MatrixX<T>> jacobianRow) const {
523 state,
524 colliderParent,
525 commonAncestor,
526 sdfSurfacePoint,
527 direction,
528 this->skeleton_,
529 this->activeJointParams_,
530 this->parameterTransform_,
531 jacobianRow);
532}
533
534template <typename T, typename SdfColliderType>
536 const ModelParametersT<T>& params,
537 const SkeletonStateT<T>& state,
538 const MeshStateT<T>& meshState,
539 Eigen::Ref<Eigen::VectorX<T>> gradient) {
541 MT_CHECK_NOTNULL(meshState.posedMesh_);
542 MT_CHECK_NOTNULL(meshState.restMesh_);
543 updateColliders(params);
544 computeActivePairs(meshState, state);
545
546 double totalError = 0.0;
547 collisionCounts_.assign(activeVertexIndices_.size(), 0);
548
549 for (size_t pairIndex = 0; pairIndex < boneCollisionPairs_.size(); ++pairIndex) {
550 if (!activePairs_[pairIndex]) {
551 continue;
552 }
553 const auto& pair = boneCollisionPairs_[pairIndex];
554 const auto& range = boneVertexRanges_[pair.boneIndex];
555 if (range.empty()) {
556 continue;
557 }
558 const auto& collider = sdfColliders_[pair.sdfColliderIndex];
559 if (!collider.isValid()) {
560 continue;
561 }
562 const auto worldToCollider = computeWorldToColliderTransform(pair.sdfColliderIndex, state);
563 const auto colliderToWorld = worldToCollider.inverse();
564
565 for (size_t i = range.start; i < range.end; ++i) {
566 if (collisionCounts_[i] >= maxCollisionsPerVertex_) {
567 continue;
568 }
569 const size_t vertexIndex = activeVertexIndices_[i];
570 const T vertexWeight = vertexWeights_[i];
571 const auto& worldPos = meshState.posedMesh_->vertices[vertexIndex];
572 const Vector3<T> localPos = worldToCollider * worldPos;
573 const auto [distance, localGradient] = collider.evaluateWithGradient(localPos);
574
575 if (distance < T(0)) {
576 const T penetrationDepth = -distance;
577 totalError += static_cast<double>(
578 vertexWeight * penetrationDepth * penetrationDepth * kSDFCollisionWeight *
579 this->weight_);
580 collisionCounts_[i]++;
581
582 // Transform gradient from collider local space to world space
583 const Eigen::Vector3<T> sdfGradient = colliderToWorld.rotation * localGradient;
584
585 const T wgt = vertexWeight * 2.0f * kSDFCollisionWeight * this->weight_;
586 const Eigen::Vector3<T> diff = -penetrationDepth * sdfGradient;
587 const Eigen::Vector3<T> sdfSurfacePoint = worldPos + penetrationDepth * sdfGradient;
588
589 const size_t commonAncestor = detail_sdf_collision::findCommonAncestorForVertex(
590 *character_.skinWeights, this->skeleton_, vertexIndex, collider.parentJoint());
591
592 SkinningWeightIteratorT<T> skinningIter(
593 character_, *meshState.restMesh_, state, vertexIndex);
594 while (!skinningIter.finished()) {
595 const auto [jointIndex, boneWeight, transformedVertex] = skinningIter.next();
596 if (jointIndex == commonAncestor) {
597 break;
598 }
599 if (std::abs(boneWeight) < std::numeric_limits<T>::epsilon()) {
600 continue;
601 }
602 MT_CHECK(jointIndex < this->skeleton_.joints.size());
603 const auto& jointState = state.jointState[jointIndex];
604 const size_t paramIndex = jointIndex * kParametersPerJoint;
605 const Eigen::Vector3<T> posd = transformedVertex - jointState.translation();
606 accumulateJointGradient(jointState, paramIndex, posd, boneWeight * wgt * diff, gradient);
607 }
608
609 if (collider.parentJoint() != kInvalidIndex) {
610 accumulateColliderHierarchyGradient(
611 state,
612 collider.parentJoint(),
613 commonAncestor,
614 sdfSurfacePoint,
615 -wgt * diff,
616 gradient);
617 }
618 }
619 }
620 }
621 return totalError;
622}
623
624template <typename T, typename SdfColliderType>
626 const ModelParametersT<T>& params,
627 const SkeletonStateT<T>& state,
628 const MeshStateT<T>& meshState,
629 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
630 Eigen::Ref<Eigen::VectorX<T>> residual,
631 int& usedRows) {
633 MT_CHECK(
634 jacobian.cols() == static_cast<Eigen::Index>(this->parameterTransform_.transform.cols()),
635 "Jacobian column count mismatch");
636 MT_CHECK_NOTNULL(meshState.posedMesh_);
637 MT_CHECK_NOTNULL(meshState.restMesh_);
638 updateColliders(params);
639 computeActivePairs(meshState, state);
640
641 double totalError = 0.0;
642 int currentRow = 0;
643 collisionCounts_.assign(activeVertexIndices_.size(), 0);
644
645 for (size_t pairIndex = 0; pairIndex < boneCollisionPairs_.size(); ++pairIndex) {
646 if (!activePairs_[pairIndex]) {
647 continue;
648 }
649 const auto& pair = boneCollisionPairs_[pairIndex];
650 const auto& range = boneVertexRanges_[pair.boneIndex];
651 if (range.empty()) {
652 continue;
653 }
654 const auto& collider = sdfColliders_[pair.sdfColliderIndex];
655 if (!collider.isValid()) {
656 continue;
657 }
658 const auto worldToCollider = computeWorldToColliderTransform(pair.sdfColliderIndex, state);
659 const auto colliderToWorld = worldToCollider.inverse();
660
661 for (size_t i = range.start; i < range.end; ++i) {
662 if (collisionCounts_[i] >= maxCollisionsPerVertex_) {
663 continue;
664 }
665 const size_t vertexIndex = activeVertexIndices_[i];
666 const T vertexWeight = vertexWeights_[i];
667 const auto& worldPos = meshState.posedMesh_->vertices[vertexIndex];
668 const Vector3<T> localPos = worldToCollider * worldPos;
669 const auto [distance, localGradient] = collider.evaluateWithGradient(localPos);
670
671 if (distance < T(0)) {
672 const T penetrationDepth = -distance;
673 MT_CHECK(
674 currentRow < jacobian.rows() && currentRow < residual.rows(),
675 "Insufficient Jacobian/residual rows");
676
677 const T wgt = std::sqrt(vertexWeight * kSDFCollisionWeight * this->weight_);
678 residual[currentRow] = wgt * penetrationDepth;
679 totalError += static_cast<double>(
680 vertexWeight * penetrationDepth * penetrationDepth * kSDFCollisionWeight *
681 this->weight_);
682 ++collisionCounts_[i];
683
684 jacobian.row(currentRow).setZero();
685
686 // Transform gradient from collider local space to world space
687 const Eigen::Vector3<T> sdfGradient = colliderToWorld.rotation * localGradient;
688
689 const T jacobianMagnitude = -wgt;
690 const Eigen::Vector3<T> worldJacobianContribution = jacobianMagnitude * sdfGradient;
691 const Eigen::Vector3<T> sdfSurfacePoint = worldPos + penetrationDepth * sdfGradient;
692
693 const size_t commonAncestor = detail_sdf_collision::findCommonAncestorForVertex(
694 *character_.skinWeights, this->skeleton_, vertexIndex, collider.parentJoint());
695
696 SkinningWeightIteratorT<T> skinningIter(
697 character_, *meshState.restMesh_, state, vertexIndex);
698 while (!skinningIter.finished()) {
699 const auto [jointIndex, boneWeight, transformedVertex] = skinningIter.next();
700 if (jointIndex == commonAncestor) {
701 break;
702 }
703 if (std::abs(boneWeight) < std::numeric_limits<T>::epsilon()) {
704 continue;
705 }
706 MT_CHECK(jointIndex < this->skeleton_.joints.size());
707 const auto& jointState = state.jointState[jointIndex];
708 const size_t paramIndex = jointIndex * kParametersPerJoint;
709 const Eigen::Vector3<T> posd = transformedVertex - jointState.translation();
710 accumulateJointJacobian(
711 jointState,
712 paramIndex,
713 posd,
714 boneWeight * worldJacobianContribution,
715 jacobian.middleRows(currentRow, 1));
716 }
717
718 if (collider.parentJoint() != kInvalidIndex) {
719 accumulateColliderHierarchyJacobian(
720 state,
721 collider.parentJoint(),
722 commonAncestor,
723 sdfSurfacePoint,
724 -worldJacobianContribution,
725 jacobian.middleRows(currentRow, 1));
726 }
727 currentRow++;
728 }
729 }
730 }
731
732 usedRows = currentRow;
733 return totalError;
734}
735
736template <typename T, typename SdfColliderType>
738 return static_cast<size_t>(maxCollisionsPerVertex_) * activeVertexIndices_.size();
739}
740
741template <typename T, typename SdfColliderType>
742void SDFCollisionErrorFunctionT<T, SdfColliderType>::computeActivePairs(
743 const MeshStateT<T>& meshState,
744 const SkeletonStateT<T>& state) {
746 activePairs_.assign(boneCollisionPairs_.size(), false);
747
748 boneBBoxCache_.resize(boneVertexRanges_.size());
749 boneBBoxValid_.assign(boneVertexRanges_.size(), false);
750 for (size_t boneIndex = 0; boneIndex < boneVertexRanges_.size(); ++boneIndex) {
751 if (!boneVertexRanges_[boneIndex].empty()) {
752 boneBBoxCache_[boneIndex] = computeBoneBoundingBox(boneIndex, *meshState.posedMesh_);
753 boneBBoxValid_[boneIndex] = true;
754 }
755 }
756
757 sdfBBoxCache_.resize(sdfColliders_.size());
758 for (size_t sdfIndex = 0; sdfIndex < sdfColliders_.size(); ++sdfIndex) {
759 sdfBBoxCache_[sdfIndex] = computeColliderWorldBoundingBox(sdfIndex, state);
760 }
761
762 for (size_t pairIndex = 0; pairIndex < boneCollisionPairs_.size(); ++pairIndex) {
763 const auto& pair = boneCollisionPairs_[pairIndex];
764 if (!boneBBoxValid_[pair.boneIndex]) {
765 continue;
766 }
767 activePairs_[pairIndex] =
768 boneBBoxCache_[pair.boneIndex].intersects(sdfBBoxCache_[pair.sdfColliderIndex]);
769 }
770}
771
772template <typename T, typename SdfColliderType>
773axel::BoundingBox<T> SDFCollisionErrorFunctionT<T, SdfColliderType>::computeBoneBoundingBox(
774 size_t boneIndex,
775 const MeshT<T>& posedMesh) const {
776 const auto& range = boneVertexRanges_[boneIndex];
778 std::span<const size_t>(activeVertexIndices_).subspan(range.start, range.size()), posedMesh);
779}
780
781template <typename T, typename SdfColliderType>
782axel::BoundingBox<T>
783SDFCollisionErrorFunctionT<T, SdfColliderType>::computeColliderWorldBoundingBox(
784 size_t sdfColliderIndex,
785 const SkeletonStateT<T>& state) const {
787 sdfColliders_[sdfColliderIndex], state);
788}
789
790} // namespace momentum
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
Definition checks.h:45
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Definition checks.h:36
SDF-based collision error function that penalizes vertex penetration into SDF colliders.
const Character * getCharacter() const override
Returns the character used to update mesh state for SDF collision evaluation.
double getError(const ModelParametersT< float > &params, const SkeletonStateT< float > &state, const MeshStateT< float > &meshState) override
double getJacobian(const ModelParametersT< float > &params, const SkeletonStateT< float > &state, const MeshStateT< float > &meshState, Eigen::Ref< Eigen::MatrixX< float > > jacobian, Eigen::Ref< Eigen::VectorX< float > > residual, int &usedRows) override
SDFCollisionErrorFunctionT(SDFCollisionErrorFunctionT &&) noexcept=default
SDFCollisionErrorFunctionT(const Character &character, const std::vector< SdfColliderType > &sdfColliders, const std::vector< int > &participatingVertices={}, const std::vector< T > &vertexWeights={}, bool filterRestPoseIntersections=true, uint8_t maxCollisionsPerVertex=1)
Constructor with vertex index list and uniform weights.
double getGradient(const ModelParametersT< float > &params, const SkeletonStateT< float > &state, const MeshStateT< float > &meshState, Eigen::Ref< Eigen::VectorX< float > > gradient) override
SDFCollisionErrorFunctionT & operator=(const SDFCollisionErrorFunctionT &)=delete
SDFCollisionErrorFunctionT(const SDFCollisionErrorFunctionT &)=default
SkeletonErrorFunctionT(const Skeleton &skel, const ParameterTransform &pt)
std::tuple< size_t, T, Eigen::Vector3< T > > next()
Definition types.h:28
TransformT< T > computeWorldToColliderTransform(const SdfColliderType &collider, const SkeletonStateT< T > &state)
Returns the world-to-collider transform for a collider given a skeleton state.
void accumulateColliderHierarchyGradient(const SkeletonStateT< T > &state, size_t colliderParent, size_t commonAncestor, const Eigen::Vector3< T > &sdfSurfacePoint, const Eigen::Vector3< T > &direction, const Skeleton &skeleton, const VectorX< bool > &activeJointParams, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
Accumulates the gradient contribution of a collider's joint hierarchy onto the gradient.
void accumulateJointJacobian(const JointStateT< T > &jointState, size_t paramIndex, const Eigen::Vector3< T > &posd, const Eigen::Vector3< T > &direction, const VectorX< bool > &activeJointParams, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobianRow)
Accumulates the Jacobian contribution of a single joint onto one residual row.
axel::BoundingBox< T > computeColliderWorldBoundingBox(const SdfColliderType &collider, const SkeletonStateT< T > &state)
Returns the world-space axis-aligned bounding box of a collider given a skeleton state.
void accumulateJointGradient(const JointStateT< T > &jointState, size_t paramIndex, const Eigen::Vector3< T > &posd, const Eigen::Vector3< T > &direction, const VectorX< bool > &activeJointParams, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::VectorX< T > > gradient)
Accumulates the gradient contribution of a single joint onto the model-parameter gradient.
void accumulateColliderHierarchyJacobian(const SkeletonStateT< T > &state, size_t colliderParent, size_t commonAncestor, const Eigen::Vector3< T > &sdfSurfacePoint, const Eigen::Vector3< T > &direction, const Skeleton &skeleton, const VectorX< bool > &activeJointParams, const ParameterTransform &parameterTransform, Eigen::Ref< Eigen::MatrixX< T > > jacobianRow)
Accumulates the Jacobian contribution of a collider's joint hierarchy onto one residual row.
axel::BoundingBox< T > computeBoneBoundingBox(std::span< const size_t > vertexIndices, const MeshT< T > &posedMesh)
Returns the world-space axis-aligned bounding box enclosing the given posed-mesh vertices.
size_t findCommonAncestorForVertex(const SkinWeights &skinWeights, const Skeleton &skeleton, size_t vertexIndex, size_t sdfParent)
Shared, stateless helpers for SDF-collision error functions.
SDFCollisionErrorFunctionT< double > SDFCollisionErrorFunctiond
Eigen::Ref< T > Ref
Definition types.h:43
SDFCollisionErrorFunctionT< float > SDFCollisionErrorFunction
Eigen::Matrix< T, Dynamic, Dynamic > MatrixX
Dynamic-size, column-major dense matrix.
Definition types.h:80
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
Definition types.h:207
constexpr size_t kParametersPerJoint
Definition types.h:21
constexpr size_t kInvalidIndex
Sentinel value indicating an invalid or unset size_t index.
Definition types.h:182
Vector< T, 3 > Vector3
Definition types.h:236
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
Definition types.h:466
Profiling macros that dispatch to one of three backends, selected at compile time:
#define MT_PROFILE_FUNCTION()
Definition profile.h:110
Collision pair information for bone-SDF collider combinations.
size_t sdfColliderIndex
Index into SDFCollisionGeometry.
Range structure for efficiently storing vertex indices per bone.
size_t size() const
Returns the number of vertices for this bone.
size_t end
End index in activeVertexIndices_ (exclusive).
bool empty() const
Returns true if this bone has no vertices.
size_t start
Start index in activeVertexIndices_.
A character model with skeletal structure, mesh, and optional components.
Definition character.h:32
static EIGEN_DEVICE_FUNC ModelParametersT< Scalar > Zero(::Eigen::Index size)
Definition types.h:92
Represents the state of a joint with local and global transformations.
Definition joint_state.h:50
Represents the complete state of a model's mesh.
Definition mesh_state.h:24
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
Definition mesh_state.h:32
std::unique_ptr< MeshT< T > > restMesh_
Rest positions of the mesh after the shape basis (and potentially facial expression basis) has been a...
Definition mesh_state.h:30
A generic mesh representation with support for vertices, faces, lines, and texture coordinates.
Definition mesh.h:20
A vector of size numModelParams holding the values of all model parameters for a character.
Definition types.h:99
Represents the complete state of a skeleton.
JointStateListT< T > jointState
Computed joint states for all joints in the skeleton.
Lightweight transform with separate rotation, translation, and uniform scaling.
Definition transform.h:36