16#include <dispenso/parallel_for.h>
36 sourceNormalWeight_(sourceNormalWeight),
37 targetNormalWeight_(targetNormalWeight),
47 std::span<
const Eigen::Vector3<T>> worldVecs,
49 std::span<DfdvType> dfdv)
const {
51 MT_CHECK(!worldVecs.empty(),
"World vectors must not be empty");
55 const Eigen::Vector3<T>& worldPos = worldVecs[0];
58 const Eigen::Vector3<T> sourceNormal =
60 Eigen::Vector3<T> targetNormal = constr.targetNormal.template
cast<T>();
63 if (sourceNormal.dot(targetNormal) < T(0)) {
64 targetNormal *= T(-1);
67 const Eigen::Vector3<T>
normal =
68 sourceNormalWeight_ * sourceNormal + targetNormalWeight_ * targetNormal;
70 const Eigen::Vector3<T> diff = worldPos - constr.targetPosition.template
cast<T>();
77 dfdv[0] =
normal.transpose();
82void VertexNormalErrorFunctionT<T>::buildVertexToFaceAdjacency(
84 if (vertexToFaceAdjacencyValid_) {
90 const auto& faces = meshState.
posedMesh_->faces;
91 const size_t numVertices = meshState.
posedMesh_->vertices.size();
93 vertexToFaceAdjacency_.clear();
94 vertexToFaceAdjacency_.resize(numVertices);
96 for (
size_t fIdx = 0; fIdx < faces.size(); ++fIdx) {
97 const auto& face = faces[fIdx];
98 vertexToFaceAdjacency_[face[0]].push_back(fIdx);
99 vertexToFaceAdjacency_[face[1]].push_back(fIdx);
100 vertexToFaceAdjacency_[face[2]].push_back(fIdx);
103 vertexToFaceAdjacencyValid_ =
true;
111 Eigen::Ref<Eigen::VectorX<T>> gradient) {
112 const size_t numConstraints = this->
constraints_.size();
113 if (numConstraints == 0) {
124 auto dispensoOptions = dispenso::ParForOptions();
125 dispensoOptions.maxThreads =
static_cast<uint32_t
>(this->
maxThreads_);
128 const bool isL2 = this->
loss_.isL2();
129 const T lossInvC2 = this->
loss_.invC2();
133 const bool hasBlendShapesForAccurate = (this->
character_.blendShape !=
nullptr) ||
134 (this->
character_.faceExpressionBlendShape !=
nullptr);
135 const bool doAccurateNormal =
136 computeAccurateNormalDerivatives_ && sourceNormalWeight_ != T(0) && hasBlendShapesForAccurate;
139 if (doAccurateNormal) {
140 buildVertexToFaceAdjacency(meshState);
143 std::vector<std::tuple<double, VectorX<T>>> errorGradThread;
144 dispenso::parallel_for(
151 [&](std::tuple<double, VectorX<T>>& errorGradLocal,
const size_t i) {
152 double& errorLocal = std::get<0>(errorGradLocal);
153 auto& gradLocal = std::get<1>(errorGradLocal);
155 const T constrWeight =
static_cast<T
>(this->
constraints_[i].weight);
156 if (constrWeight == T(0)) {
161 const size_t vertexIndex = constr.vertexIndex;
162 const Eigen::Vector3<T> worldPos =
166 const Eigen::Vector3<T> sourceNormal =
168 Eigen::Vector3<T> targetNormal = constr.targetNormal.template
cast<T>();
169 if (sourceNormal.dot(targetNormal) < T(0)) {
170 targetNormal *= T(-1);
172 const Eigen::Vector3<T>
normal =
173 sourceNormalWeight_ * sourceNormal + targetNormalWeight_ * targetNormal;
174 const Eigen::Vector3<T> diff = worldPos - constr.targetPosition.template
cast<T>();
175 const T f =
normal.dot(diff);
181 const T sqrError = f * f;
184 T weightedResidualScalar;
186 errorLocal += w * sqrError * lossInvC2;
187 weightedResidualScalar = T(2) * w * lossInvC2 * f;
189 errorLocal += w * this->
loss_.value(sqrError);
190 weightedResidualScalar = T(2) * w * this->
loss_.deriv(sqrError) * f;
194 if (sourceNormalWeight_ != T(0)) {
195 const T normalScale = weightedResidualScalar * sourceNormalWeight_;
200 weightedResidualScalar,
202 constr.targetPosition,
212 wr[0] = weightedResidualScalar;
213 skeletonDerivative.template accumulateVertexGradient<1>(
214 vertexIndex, worldPos, dfdv, wr, state, meshState, this->
character_, gradLocal);
218 if (doAccurateNormal) {
219 const T normalScale = weightedResidualScalar * sourceNormalWeight_;
220 const Eigen::Vector3<T> leverArm = worldPos - constr.targetPosition;
225 std::span<const size_t>(vertexToFaceAdjacency_[vertexIndex]),
234 if (!errorGradThread.empty()) {
235 errorGradThread[0] = std::accumulate(
236 errorGradThread.begin() + 1,
237 errorGradThread.end(),
239 [](
const auto& a,
const auto& b) -> std::tuple<
double,
VectorX<T>> {
240 return {std::get<0>(a) + std::get<0>(b), std::get<1>(a) + std::get<1>(b)};
243 gradient += std::get<1>(errorGradThread[0]);
244 return std::get<0>(errorGradThread[0]);
255 Eigen::Ref<Eigen::MatrixX<T>> jacobian,
256 Eigen::Ref<Eigen::VectorX<T>> residual,
258 const size_t numConstraints = this->
constraints_.size();
260 if (numConstraints == 0) {
271 auto dispensoOptions = dispenso::ParForOptions();
272 dispensoOptions.maxThreads =
static_cast<uint32_t
>(this->
maxThreads_);
275 const bool isL2Jac = this->
loss_.isL2();
276 const T lossInvC2Jac = this->
loss_.invC2();
279 const bool hasBlendShapesForAccurate = (this->
character_.blendShape !=
nullptr) ||
280 (this->
character_.faceExpressionBlendShape !=
nullptr);
281 const bool doAccurateNormal =
282 computeAccurateNormalDerivatives_ && sourceNormalWeight_ != T(0) && hasBlendShapesForAccurate;
285 if (doAccurateNormal) {
286 buildVertexToFaceAdjacency(meshState);
289 std::vector<double> errorThread;
290 dispenso::parallel_for(
292 [&]() ->
double {
return 0.0; },
295 [&](
double& errorLocal,
const size_t i) {
296 const T constrWeight =
static_cast<T
>(this->
constraints_[i].weight);
297 if (constrWeight == T(0)) {
302 const size_t vertexIndex = constr.vertexIndex;
303 const Eigen::Vector3<T> worldPos =
307 const Eigen::Vector3<T> sourceNormal =
309 Eigen::Vector3<T> targetNormal = constr.targetNormal.template
cast<T>();
310 if (sourceNormal.dot(targetNormal) < T(0)) {
311 targetNormal *= T(-1);
313 const Eigen::Vector3<T>
normal =
314 sourceNormalWeight_ * sourceNormal + targetNormalWeight_ * targetNormal;
315 const Eigen::Vector3<T> diff = worldPos - constr.targetPosition.template
cast<T>();
316 const T f =
normal.dot(diff);
318 const size_t rowIndex = i;
319 const T sqrError = f * f;
324 errorLocal += w * sqrError * lossInvC2Jac;
325 deriv = std::sqrt(w * lossInvC2Jac);
327 errorLocal += w * this->
loss_.value(sqrError);
328 deriv = std::sqrt(w * this->
loss_.deriv(sqrError));
331 residual[rowIndex] = deriv * f;
338 if (sourceNormalWeight_ != T(0)) {
339 const T normalScale = deriv * sourceNormalWeight_;
347 constr.targetPosition,
356 if (doAccurateNormal) {
357 const Eigen::Vector3<T> leverArm = worldPos - constr.targetPosition;
362 std::span<const size_t>(vertexToFaceAdjacency_[vertexIndex]),
371 skeletonDerivative.template accumulateVertexJacobian<1>(
385 usedRows =
static_cast<int>(numConstraints);
387 if (!errorThread.empty()) {
388 return std::accumulate(errorThread.begin() + 1, errorThread.end(), errorThread[0]);
#define MT_CHECK_NOTNULL(ptr,...)
Asserts that ptr is not null; on failure, throws std::runtime_error with the optional fmt-style messa...
#define MT_CHECK(condition,...)
Runtime check macros with two interchangeable backends:
Shared utility for derivative computation in error functions.
void accumulateVertexNormalBlendShapeJacobian(size_t vertexIndex, const Eigen::Vector3< T > &leverArm, T scale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::MatrixX< T > > jacobian, size_t rowIndex) const
Jacobian version of accumulateVertexNormalBlendShapeGradient.
void accumulateVertexGradientWithNormalCorrectionDirect(size_t vertexIndex, const Eigen::Vector3< T > &worldPos, const Eigen::Vector3< T > &normal, T weightedResidual, const Eigen::Vector3< T > &sourceNormal, const Eigen::Vector3< T > &targetPosition, T normalCorrectionScale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::VectorX< T > > gradient) const
Scalar-specialized combined vertex gradient + normal rotation correction.
void accumulateVertexJacobianWithNormalCorrectionDirect(size_t vertexIndex, const Eigen::Vector3< T > &worldPos, const Eigen::Vector3< T > &normal, T scale, const Eigen::Vector3< T > &sourceNormal, const Eigen::Vector3< T > &targetPosition, T normalCorrectionScale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::MatrixX< T > > jacobian, size_t rowIndex) const
Scalar-specialized combined vertex Jacobian + normal rotation correction.
void accumulateVertexNormalBlendShapeGradient(size_t vertexIndex, const Eigen::Vector3< T > &leverArm, T scale, const SkeletonStateT< T > &skeletonState, const MeshStateT< T > &meshState, const Character &character, Eigen::Ref< Eigen::VectorX< T > > gradient) const
Accumulates the gradient contribution from how mesh normals change with blend shape weights.
const Skeleton & skeleton_
VectorX< bool > activeJointParams_
const ParameterTransform & parameterTransform_
ParameterSet enabledParameters_
VertexErrorFunctionT(const Character &character, const ParameterTransform ¶meterTransform, const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1))
GeneralizedLossT< T > loss_
std::vector< VertexNormalDataT< T > > constraints_
Eigen::Matrix< T, FuncDim, 1 > FuncType
Eigen::Matrix< T, FuncDim, 3 > DfdvType
const Character & character_
static constexpr T kLegacyWeight
Error function for vertex Normal and SymmetricNormal constraints.
bool computeAccurateNormalDerivatives() const
Returns whether accurate normal blend shape derivatives are enabled.
double getGradient(const ModelParametersT< T > ¶ms, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::VectorX< T > > gradient) override
Override to handle normal rotation correction terms via SkeletonDerivativeT.
double getJacobian(const ModelParametersT< T > ¶ms, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, Eigen::Ref< Eigen::MatrixX< T > > jacobian, Eigen::Ref< Eigen::VectorX< T > > residual, int &usedRows) override
Override to handle normal rotation correction terms via SkeletonDerivativeT.
VertexNormalErrorFunctionT(const Character &character, const ParameterTransform ¶meterTransform, T sourceNormalWeight=T(1), T targetNormalWeight=T(0), const T &lossAlpha=GeneralizedLossT< T >::kL2, const T &lossC=T(1), bool computeAccurateNormalDerivatives=false)
Constructor.
void evalFunction(size_t constrIndex, const SkeletonStateT< T > &state, const MeshStateT< T > &meshState, std::span< const Eigen::Vector3< T > > worldVecs, FuncType &f, std::span< DfdvType > dfdv) const final
Computes the residual and derivatives.
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
ParameterTransformT< float > ParameterTransform
Vector< T, Dynamic > VectorX
Dynamic-size column vector. Common return type for solver residuals and parameter vectors.
decltype(auto) cast(const ContainerType< ObjectType > &originalContainer)
Casts the scalar type of objects in a container that support the cast<>() method.
A character model with skeletal structure, mesh, and optional components.
Represents the complete state of a model's mesh.
std::unique_ptr< MeshT< T > > posedMesh_
Posed mesh after the skeleton transforms have been applied.
A vector of size numModelParams holding the values of all model parameters for a character.
Represents the complete state of a skeleton.
Constraint data for a vertex normal constraint.