-
Notifications
You must be signed in to change notification settings - Fork 25
/
AvatarOptimizer.cpp
1518 lines (1382 loc) · 58.7 KB
/
AvatarOptimizer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "AvatarOptimizer.h"
#include <Eigen/StdVector>
#include <atomic>
#include <boost/thread.hpp>
#include <ceres/ceres.h>
#include <iostream>
#include <mutex>
#include <nanoflann.hpp>
#include <thread>
#include <vector>
#include "Avatar.h"
#include "AvatarRenderer.h"
#include "Util.h"
#include "Version.h"
// #define PCL_DEBUG_VISUALIZE
#ifndef OPENARK_PCL_ENABLED
// If PCL not available then cannot visualize
#undef PCL_DEBUG_VISUALIZE
#endif
#ifdef PCL_DEBUG_VISUALIZE
#include <pcl/visualization/pcl_visualizer.h>
#endif
#define BEGIN_PROFILE // auto start = std::chrono::high_resolution_clock::now()
#define PROFILE( \
x) // do{printf("%s: %f ms\n", #x, std::chrono::duration<double,
// std::milli>(std::chrono::high_resolution_clock::now() -
// start).count()); start =
// std::chrono::high_resolution_clock::now(); }while(false)
// Uncomment below line to compare analytic diff results to auto diff
//#define TEST_COMPARE_AUTO_DIFF
namespace nanoflann {
/// KD-tree adaptor for working with data directly stored in a column-major
/// Eigen Matrix, without duplicating the data storage. This code is adapted
/// from the KDTreeEigenMatrixAdaptor class of nanoflann.hpp
template <class MatrixType, int DIM = -1,
class Distance = nanoflann::metric_L2_Simple,
typename IndexType = int>
struct KDTreeEigenColMajorMatrixAdaptor {
typedef KDTreeEigenColMajorMatrixAdaptor<MatrixType, DIM, Distance> self_t;
typedef typename MatrixType::Scalar num_t;
typedef
typename Distance::template traits<num_t, self_t>::distance_t metric_t;
typedef KDTreeSingleIndexAdaptor<metric_t, self_t, DIM, IndexType> index_t;
index_t *index;
KDTreeEigenColMajorMatrixAdaptor(const MatrixType &mat,
const int leaf_max_size = 10)
: m_data_matrix(mat) {
const size_t dims = mat.rows();
index = new index_t(
dims, *this,
nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size));
index->buildIndex();
}
~KDTreeEigenColMajorMatrixAdaptor() { delete index; }
const MatrixType &m_data_matrix;
/// Query for the num_closest closest points to a given point (entered as
/// query_point[0:dim-1]).
inline void query(const num_t *query_point, const size_t num_closest,
IndexType *out_indices, num_t *out_distances_sq) const {
nanoflann::KNNResultSet<typename MatrixType::Scalar, IndexType>
resultSet(num_closest);
resultSet.init(out_indices, out_distances_sq);
index->findNeighbors(resultSet, query_point, nanoflann::SearchParams());
}
/// Query for the closest points to a given point (entered as
/// query_point[0:dim-1]).
inline IndexType closest(const num_t *query_point) const {
IndexType out_indices;
num_t out_distances_sq;
query(query_point, 1, &out_indices, &out_distances_sq);
return out_indices;
}
const self_t &derived() const { return *this; }
self_t &derived() { return *this; }
inline size_t kdtree_get_point_count() const {
return m_data_matrix.cols();
}
/// Returns the distance between the vector "p1[0:size-1]" and the data
/// point with index "idx_p2" stored in the class:
inline num_t kdtree_distance(const num_t *p1, const size_t idx_p2,
size_t size) const {
num_t s = 0;
for (size_t i = 0; i < size; i++) {
const num_t d = p1[i] - m_data_matrix.coeff(i, idx_p2);
s += d * d;
}
return s;
}
/// Returns the dim'th component of the idx'th point in the class:
inline num_t kdtree_get_pt(const size_t idx, int dim) const {
return m_data_matrix.coeff(dim, idx);
}
/// Optional bounding-box computation: return false to default to a standard
/// bbox computation loop.
template <class BBOX>
bool kdtree_get_bbox(BBOX &) const {
return false;
}
};
} // namespace nanoflann
namespace ceres {
/** WHY THIS? For our use case it is desirable to pre-compute the full Jacobian
* at an earlier stage but make use of the special addition operator for local
* parameterization. This is because some Jacobians are easier to compute wrt
* the local 'error' vector than the state. This is a known Ceres limitation,
* see
* https://groups.google.com/forum/#!msg/ceres-solver/fs8iNI9_F7Q/gv0R4NGLAwAJ
* Here, we set Jacobian to a dummy identity matrix, as suggested by a post on
* that page. The local Jacobian is multiplied manually in
* AvatarEvaluationCommonData where required. */
class FakeQuaternionParameterization : public ceres::LocalParameterization {
public:
~FakeQuaternionParameterization() {}
bool Plus(const double *x_ptr, const double *delta,
double *x_plus_delta_ptr) const {
// Copied from EigenQuaternionParameterization
Eigen::Map<Eigen::Quaterniond> x_plus_delta(x_plus_delta_ptr);
Eigen::Map<const Eigen::Quaterniond> x(x_ptr);
const double norm_delta = sqrt(
delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2]);
if (norm_delta > 0.0) {
const double sin_delta_by_delta = sin(norm_delta) / norm_delta;
// Note, in the constructor w is first.
Eigen::Quaterniond delta_q(
cos(norm_delta), sin_delta_by_delta * delta[0],
sin_delta_by_delta * delta[1], sin_delta_by_delta * delta[2]);
x_plus_delta = delta_q * x;
} else {
x_plus_delta = x;
}
return true;
}
bool ComputeJacobian(const double *x, double *jacobian) const {
Eigen::Map<Eigen::Matrix<double, 4, 3, Eigen::RowMajor>> J(jacobian);
J.topLeftCorner<3, 3>().setIdentity();
J.bottomRows<1>().setZero();
return true;
}
int GlobalSize() const { return 4; }
int LocalSize() const { return 3; }
};
} // namespace ceres
namespace ark {
namespace {
using MatAlloc = Eigen::aligned_allocator<Eigen::Matrix3d>;
using VecAlloc = Eigen::aligned_allocator<Eigen::Vector3d>;
/** Evaluation callback for Ceres */
template <class Cache>
struct AvatarEvaluationCommonData : public ceres::EvaluationCallback {
/** Max number of joint assignments to consider for each joint */
static const int MAX_ASSIGN = 4;
/** If true, will recalculate shape every update */
const bool shapeEnabled;
AvatarEvaluationCommonData(AvatarOptimizer &opt, bool shape_enabled = false)
: opt(opt),
ava(opt.ava),
numJointSpaces(opt.ava.model.numJoints() + 1),
shapeEnabled(shape_enabled) {
// _L.resize(nJoints * AvatarOptimizer::ROT_SIZE);
localJacobian.resize(numJointSpaces);
if (shape_enabled) {
S.resize(ava.model.numJoints());
Sp.resize(ava.model.numJoints());
H.resize(ava.model.numJoints());
}
_R.resize(numJointSpaces * numJointSpaces);
_t.resize(_R.size());
shapedCloud.resize(3, ava.model.numPoints());
CalcShape();
// Make a list of deduplicated ancestor joints for each point
ancestor.resize(ava.model.numPoints());
for (int point = 0; point < ava.model.numPoints(); ++point) {
auto &ances = ancestor[point];
for (auto &weight_joint : ava.model.assignedJoints[point]) {
double weight = weight_joint.first;
int joint = weight_joint.second;
ances.emplace_back(joint, joint, weight);
for (int j = ava.model.parent[joint]; j != -1;
j = ava.model.parent[j]) {
ances.emplace_back(j, joint, weight);
}
}
std::sort(ances.begin(), ances.end());
int last = 0;
for (size_t i = 1; i < ances.size(); ++i) {
if (ances[last].jid == ances[i].jid) {
ances[last].merge(ances[i]);
} else {
++last;
if (last < i) {
ances[last] = std::move(ances[i]);
}
}
}
ances.resize(last + 1);
}
if (shape_enabled) {
for (int j = 0; j < ava.model.numJoints(); ++j) {
Sp[j].resize(3, ava.model.numShapeKeys());
S[j].resize(3, ava.model.numShapeKeys());
H[j].resize(3, ava.model.numShapeKeys());
}
if (ava.model.useJointShapeRegressor) {
for (int j = 0; j < ava.model.numJoints(); ++j) {
S[j].noalias() =
ava.model.jointShapeReg.middleRows<3>(3 * j);
}
} else {
for (int i = 0; i < ava.model.numShapeKeys(); ++i) {
Eigen::MatrixXd::Scalar d;
Eigen::Map<const CloudType> keyCloud(
ava.model.keyClouds.data() +
i * ava.model.numPoints() * 3,
3, ava.model.numPoints());
for (int j = 0; j < ava.model.numJoints(); ++j) {
S[j].col(i).noalias() =
keyCloud * ava.model.jointRegressor.col(j);
}
}
}
for (int j = 1; j < ava.model.numJoints(); ++j) {
if (j) Sp[j].noalias() = S[j] - S[ava.model.parent[j]];
}
Sp[0].setZero();
H[0].setZero();
}
}
/** Compute joint and point positions after applying shape keys*/
void CalcShape() {
Eigen::Map<Eigen::VectorXd> shapedCloudVec(shapedCloud.data(),
3 * shapedCloud.cols());
/** Apply shape keys */
shapedCloudVec.noalias() =
ava.model.keyClouds * ava.w + ava.model.baseCloud;
/** Apply joint [shape] regressor */
// TODO: use dense joint regressor with compressed cloud
if (ava.model.useJointShapeRegressor) {
jointPosInit.resize(3, ava.model.numJoints());
Eigen::Map<Eigen::VectorXd> jointPosVec(jointPosInit.data(),
3 * ava.model.numJoints());
jointPosVec.noalias() =
ava.model.jointShapeRegBase + ava.model.jointShapeReg * ava.w;
} else {
jointPosInit.noalias() = shapedCloud * ava.model.jointRegressor;
}
/** Ensure root is at origin*/
Eigen::Vector3d offset = jointPosInit.col(0);
shapedCloud.colwise() -= offset;
jointPosInit.colwise() -= offset;
/** Find relative positions of each joint */
jointVecInit.noalias() = jointPosInit;
for (int i = ava.model.numJoints() - 1; i >= 1; --i) {
jointVecInit.col(i).noalias() -=
jointVecInit.col(ava.model.parent[i]);
}
shapeComputed = true;
}
void PrepareForEvaluation(bool evaluate_jacobians,
bool new_evaluation_point) final {
// std::cerr << "PREP " << evaluate_jacobians << ", " <<
// new_evaluation_point << "\n";
if (new_evaluation_point) {
// BEGIN_PROFILE;
if (shapeEnabled || !shapeComputed) CalcShape();
// PROFILE(CalcShape);
jointVecInit.col(0).noalias() = ava.p;
for (int i = 0; i < numJointSpaces - 1; ++i) {
// double * jacobian = localJacobian[i].data();
auto &x = opt.r[i].coeffs();
/** Jacobian of local parameterization '+' function at 0 */
localJacobian[i] << x(3), x(2), -x(1), -x(2), x(3), x(0), x(1),
-x(0), x(3), -x(0), -x(1), -x(2);
}
// PROFILE(lojac);
// Compute relative rotations and translations
R(-1, -1).setIdentity(); // -1 means 'to global'
t(-1, -1).setZero();
for (int i = 0; i < numJointSpaces - 1; ++i) {
R(i, i).setIdentity();
Eigen::Matrix3d rot = opt.r[i].toRotationMatrix();
t(i, i).setZero();
int p = ava.model.parent[i];
for (int j = p;; j = ava.model.parent[j]) {
R(j, i).noalias() = R(j, p) * rot;
t(j, i).noalias() = R(j, p) * jointVecInit.col(i) + t(j, p);
if (j == -1) break;
}
}
// PROFILE(RT);
if (shapeEnabled) {
// Compute joint-to-parent accumulated shape differences
for (int j = 1; j < numJointSpaces - 1; ++j) {
H[j].noalias() = R(-1, ava.model.parent[j]) * Sp[j] +
H[ava.model.parent[j]];
}
}
// PROFILE(H);
std::atomic<size_t> cacheId(0);
auto worker = [evaluate_jacobians, &cacheId, this](int workerId) {
size_t workerCacheId;
while (true) {
workerCacheId = cacheId++;
if (workerCacheId >= caches.size()) break;
caches[workerCacheId].updateData(evaluate_jacobians);
}
};
std::vector<std::thread> threadPool;
for (int i = 0; i < numThreads; ++i) {
threadPool.emplace_back(worker, i);
}
for (auto &thread : threadPool) {
thread.join();
}
// PROFILE(Caches);
// PROFILE(ALL Prepare);
}
}
/** Joint-to-ancestor joint rotation (j_ances=-1 is global) */
inline Eigen::Matrix3d &R(int j_ancestor, int j) {
return _R[numJointSpaces * (j_ancestor + 1) + j + 1];
}
/** Joint-to-ancestor joint relative position (j_ances=-1 is global) */
inline Eigen::Vector3d &t(int j_ancestor, int j) {
return _t[numJointSpaces * (j_ancestor + 1) + j + 1];
}
/** Combined left-side matrix to multiply into Jacobians for joint j,
* component t */
// inline Eigen::Matrix3d& L(int j, int t) {
// return _L[j * AvatarOptimizer::ROT_SIZE + t];
// }
AvatarOptimizer &opt;
Avatar &ava;
/** WARNING: is actual number of joints + 1 */
int numJointSpaces;
struct Ancestor {
Ancestor() {}
explicit Ancestor(int jid, int assigned = -1,
double assign_weight = 0.0)
: jid(jid) {
if (assigned >= 0) {
assign[0] = assigned;
weight[0] = assign_weight;
num_assign = 1;
} else {
num_assign = 0;
}
}
/** Joint ID */
int jid;
/** Assigned joints of the skin point corresponding to the joint */
int assign[MAX_ASSIGN];
/** Assignment weight */
double weight[MAX_ASSIGN];
/** Number of assigned joints. */
int num_assign;
/** Compare by joint id */
bool operator<(const Ancestor &other) const { return jid < other.jid; }
/** Merge another ancestor joint */
void merge(const Ancestor &other) {
for (int i = 0; i < other.num_assign; ++i) {
weight[num_assign] = other.weight[i];
assign[num_assign++] = other.assign[i];
}
}
};
/** Max number of threads to use during common pre-evaluation computations
*/
int numThreads = 1;
/** INTERNAL: Scaled versions of betaPose, betaShape actually
* used in the optimization. This accounts for
* variations in the number of ICP-type residuals. */
double scaledBetaPose, scaledBetaShape;
/** Deduped, topo sorted ancestor joints for each skin point,
* combining all joint assignments for the point */
std::vector<std::vector<Ancestor>> ancestor;
/** Joint initial relative/absolute positions */
CloudType jointVecInit, jointPosInit;
/** baseCloud after applying shape keys (3 * num points) */
CloudType shapedCloud;
/** List of point-specific caches */
std::vector<Cache> caches;
/** Local parameterization jacobian */
std::vector<
Eigen::Matrix<double, 4, 3, Eigen::RowMajor>,
Eigen::aligned_allocator<Eigen::Matrix<double, 4, 3, Eigen::RowMajor>>>
localJacobian;
/** Joint-to-parent 'shape deltas' */
std::vector<CloudType, Eigen::aligned_allocator<CloudType>> S;
/** Joint-to-parent 'shape delta difference' */
std::vector<CloudType, Eigen::aligned_allocator<CloudType>> Sp;
/** Accumulated joint-to-parent 'shape delta difference' */
std::vector<CloudType, Eigen::aligned_allocator<CloudType>> H;
private:
/** Joint-to-ancestor joint rotation (j_ances=-1 is global) */
std::vector<Eigen::Matrix3d, MatAlloc> _R;
/** Joint-to-ancestor joint relative position (j_ances=-1 is global) */
std::vector<Eigen::Vector3d, VecAlloc> _t;
/** Combined left-side matrix to use for Jacobians for joint j, component t
*/
// std::vector<Eigen::Matrix3d, MatAlloc> _L;
/** True if CalcShape() has been called, to avoid further calls */
bool shapeComputed;
};
/** Common method for each model point */
struct AvatarCostFunctorCache {
AvatarCostFunctorCache(
AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data,
int point_id)
: commonData(common_data),
opt(common_data.opt),
ava(common_data.opt.ava),
pointId(point_id) {
icpJacobian.resize(commonData.ancestor[pointId].size());
if (commonData.shapeEnabled) {
icpShapeJacobian.resize(3, ava.model.numShapeKeys());
}
}
bool getICPJacobians(double *residuals, double **jacobians) const {
Eigen::Map<Eigen::Vector3d> residualMap(residuals);
residualMap.noalias() = resid;
if (jacobians != nullptr) {
if (jacobians[0] != nullptr) {
Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> J(
jacobians[0]);
J.setIdentity();
}
size_t i = 0;
for (; i < commonData.ancestor[pointId].size(); ++i) {
if (jacobians[i + 1] != nullptr) {
Eigen::Map<Eigen::Matrix<double, 3, 4, Eigen::RowMajor>> J(
jacobians[i + 1]);
#ifdef TEST_COMPARE_AUTO_DIFF
J.noalias() = icpJacobian[i];
#else
J.topLeftCorner<3, 3>().noalias() = icpJacobian[i];
J.rightCols<1>().setZero();
#endif
}
}
if (commonData.shapeEnabled && jacobians[i + 1] != nullptr) {
Eigen::Map<
Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor>>
J(jacobians[i + 1], 3, ava.model.numShapeKeys());
J.noalias() = icpShapeJacobian;
}
}
return true;
}
void updateData(bool compute_jacobians) {
auto pointPosInit = commonData.shapedCloud.col(pointId);
resid.setZero();
for (auto &assign : ava.model.assignedJoints[pointId]) {
int k = assign.second;
resid += assign.first *
(commonData.R(-1, k) *
(pointPosInit - commonData.jointPosInit.col(k)) +
commonData.t(-1, k));
}
if (compute_jacobians) {
// Root position derivative is always identity
// TODO: precompute point-to-assigned-joint vector, reduce 3 flops
// CloudType pointVecs;
Eigen::Matrix<double, 3, 4> dRot;
// Eigen::Matrix3d vCross;
Eigen::Vector3d v;
for (size_t i = 0; i < commonData.ancestor[pointId].size(); ++i) {
// Set derivative for each parent rotation
auto &ances = commonData.ancestor[pointId][i];
int j = ances.jid; // 'middle' joint we are differenting wrt
v.setZero();
for (int assign = 0; assign < ances.num_assign; ++assign) {
// up to 4 inner loops
int k = ances.assign[assign]; // 'outer' joint assigned to
// the point
v += ances.weight[assign] *
(commonData.R(j, k) *
(pointPosInit - commonData.jointPosInit.col(k)) +
commonData.t(j, k));
}
// std::cerr <<v.transpose<< "\n"
Eigen::Quaterniond &q = opt.r[j];
Eigen::Vector3d u = q.vec() * 2;
// Quaternion-vector rotation (pseudo-)Jacobian
double w = q.w() * 2;
dRot.setZero();
dRot << u(1) * v(1) + v(2) * u(2),
w * v(2) + u(0) * v(1) - 2 * u(1) * v(0),
-w * v(1) - 2 * v(0) * u(2) + u(0) * v(2),
u(1) * v(2) - v(1) * u(2),
-w * v(2) - 2 * u(0) * v(1) + v(0) * u(1),
v(2) * u(2) + u(0) * v(0),
w * v(0) + u(1) * v(2) - 2 * v(1) * u(2),
v(0) * u(2) - u(0) * v(2),
w * v(1) + v(0) * u(2) - 2 * u(0) * v(2),
-w * v(0) - 2 * u(1) * v(2) + v(1) * u(2),
u(0) * v(0) + v(1) * u(1), u(0) * v(1) - v(0) * u(1);
icpJacobian[i].setZero();
icpJacobian[i].noalias() =
commonData.R(-1, ava.model.parent[j]) * dRot
#ifndef TEST_COMPARE_AUTO_DIFF
* commonData.localJacobian[j]
#endif
;
}
if (commonData.shapeEnabled) {
icpShapeJacobian.setZero();
for (const std::pair<double, int> &assign :
ava.model.assignedJoints[pointId]) {
const int j = assign.second;
auto pointDeltas =
ava.model.keyClouds.middleRows<3>(pointId * 3);
icpShapeJacobian +=
(commonData.R(-1, j) * (pointDeltas - commonData.S[j]) +
commonData.H[j]) *
assign.first;
}
}
}
}
Eigen::Vector3d resid;
#ifdef TEST_COMPARE_AUTO_DIFF
// For comparing with auto diff, we cannot multiply by the
// local param jacobian or result would not be comparable
std::vector<
Eigen::Matrix<double, 3, 4, Eigen::RowMajor>,
Eigen::aligned_allocator<Eigen::Matrix<double, 3, 4, Eigen::RowMajor>>>
icpJacobian;
#else
std::vector<
Eigen::Matrix<double, 3, 3, Eigen::RowMajor>,
Eigen::aligned_allocator<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>>>
icpJacobian;
#endif
Eigen::Matrix<double, 3, Eigen::Dynamic, Eigen::RowMajor> icpShapeJacobian;
Avatar &ava;
AvatarOptimizer &opt;
AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;
int pointId;
};
/** Ceres analytic derivative cost function for ICP error.
* Works for pose parameters only. */
struct AvatarICPCostFunctor : ceres::CostFunction {
AvatarICPCostFunctor(
AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data,
size_t cache_id, const CloudType &data_cloud, int data_point_id)
: commonData(common_data),
cacheId(cache_id),
dataCloud(data_cloud),
dataPointId(data_point_id) {
set_num_residuals(3);
auto &cache = common_data.caches[cache_id];
std::vector<int> *paramBlockSizes = mutable_parameter_block_sizes();
paramBlockSizes->push_back(3); // Root position
for (size_t i = 0; i < cache.commonData.ancestor[cache.pointId].size();
++i) {
paramBlockSizes->push_back(
4); // Add rotation block for each ancestor
}
if (commonData.shapeEnabled)
paramBlockSizes->push_back(
cache.ava.model.numShapeKeys()); // Shape key weights?
}
bool Evaluate(double const *const *parameters, double *residuals,
double **jacobians) const final {
if (!commonData.caches[cacheId].getICPJacobians(residuals, jacobians))
return false;
Eigen::Map<Eigen::Vector3d> resid(residuals);
resid -= dataCloud.col(dataPointId);
return true;
}
const CloudType &dataCloud;
int dataPointId;
size_t cacheId;
AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;
};
/** Ceres analytic derivative cost function for pose prior error */
struct AvatarPosePriorCostFunctor : ceres::CostFunction {
AvatarPosePriorCostFunctor(
AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data)
: commonData(common_data),
posePrior(commonData.ava.model.posePrior),
nSmplJoints(commonData.ava.model.numJoints() - 1) {
set_num_residuals(nSmplJoints * 3 + 1); // 3 for each joint + 1 extra
std::vector<int> *paramBlockSizes = mutable_parameter_block_sizes();
for (int i = 0; i < nSmplJoints; ++i) {
paramBlockSizes->push_back(
4); // Add rotation block for each non-root joint
}
}
bool Evaluate(double const *const *parameters, double *residuals,
double **jacobians) const final {
const int nResids = nSmplJoints * 3 + 1;
Eigen::VectorXd smplParams(nSmplJoints * 3);
for (int i = 0; i < nSmplJoints; ++i) {
Eigen::Map<const Eigen::Quaterniond> q(parameters[i]);
Eigen::AngleAxisd aa(q);
smplParams.segment<3>(i * 3) = aa.axis() * aa.angle();
}
Eigen::Map<Eigen::VectorXd> resid(residuals, nResids);
int compIdx;
resid.noalias() = posePrior.residual(smplParams, &compIdx) *
commonData.scaledBetaPose;
if (jacobians != nullptr) {
const Eigen::MatrixXd &L = posePrior.prec_cho[compIdx];
// precision = L L^T
for (int i = 0; i < nSmplJoints; ++i) {
if (jacobians[i] != nullptr) {
Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, 4,
Eigen::RowMajor>>
J(jacobians[i], nResids, 4);
J.topLeftCorner<Eigen::Dynamic, 3>(nResids - 1, 3)
.noalias() = L.middleRows<3>(i * 3).transpose() *
0.707106781186548 *
commonData.scaledBetaPose;
J.rightCols<1>().setZero();
J.bottomLeftCorner<1, 3>().setZero();
}
}
}
return true;
}
AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;
const GaussianMixture &posePrior;
const int nSmplJoints;
};
/** Ceres analytic derivative cost function for shape prior error
* (This is extremely simple, just the squared l2-norm of w!) */
struct AvatarShapePriorCostFunctor : ceres::CostFunction {
AvatarShapePriorCostFunctor(int num_shape_keys, double beta_shape)
: numShapeKeys(num_shape_keys), betaShape(beta_shape) {
set_num_residuals(numShapeKeys); // 1 for each shape key
std::vector<int> *paramBlockSizes = mutable_parameter_block_sizes();
paramBlockSizes->push_back(numShapeKeys); // 1 for each shape key
}
bool Evaluate(double const *const *parameters, double *residuals,
double **jacobians) const final {
Eigen::Map<Eigen::VectorXd> resid(residuals, numShapeKeys);
Eigen::Map<const Eigen::VectorXd> w(parameters[0], numShapeKeys);
resid.noalias() = w * betaShape;
if (jacobians != nullptr) {
if (jacobians[0] != nullptr) {
Eigen::Map<Eigen::MatrixXd> J(jacobians[0], numShapeKeys,
numShapeKeys);
J.noalias() =
Eigen::MatrixXd::Identity(numShapeKeys, numShapeKeys) *
betaShape;
}
}
return true;
}
const int numShapeKeys;
const double betaShape;
};
#ifdef TEST_COMPARE_AUTO_DIFF
/** Auto diff cost function w/ derivative for Ceres
* (Extremely poorly optimized, used for checking correctness of analytic
* derivative) */
struct AvatarICPAutoDiffCostFunctor {
AvatarICPAutoDiffCostFunctor(
AvatarEvaluationCommonData<AvatarCostFunctorCache> &common_data,
size_t cache_id, const CloudType &data_cloud, int data_point_id)
: commonData(common_data),
cacheId(cache_id),
dataCloud(data_cloud),
dataPointId(data_point_id) {
pointId = commonData.caches[cacheId].pointId;
}
template <class T>
bool operator()(T const *const *params, T *residual) const {
using VecMap = Eigen::Map<Eigen::Matrix<T, 3, 1>>;
using ConstVecMap = Eigen::Map<const Eigen::Matrix<T, 3, 1>>;
using ConstQuatMap = Eigen::Map<const Eigen::Quaternion<T>>;
Eigen::Matrix<T, 3, Eigen::Dynamic> cloud(
3, commonData.ava.model.numPoints());
Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> cloudVec(
cloud.data(), cloud.rows() * cloud.cols());
if (commonData.shapeEnabled) {
Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> wMap(
params[commonData.ava.model.numJoints() + 1],
commonData.ava.model.numShapeKeys(), 1);
cloudVec.noalias() =
commonData.ava.model.keyClouds.cast<T>() * wMap +
commonData.ava.model.baseCloud;
} else {
cloudVec.noalias() = commonData.ava.model.keyClouds.cast<T>() *
commonData.ava.w.cast<T>() +
commonData.ava.model.baseCloud;
}
Eigen::Matrix<T, 3, Eigen::Dynamic> jointPos =
cloud * commonData.ava.model.jointRegressor.cast<T>();
if (commonData.ava.model.useJointShapeRegressor) {
jointPos.resize(3, commonData.ava.model.numJoints());
Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1>> jointPosVec(
jointPos.data(), 3 * commonData.ava.model.numJoints());
if (commonData.shapeEnabled) {
Eigen::Map<const Eigen::Matrix<T, Eigen::Dynamic, 1>> wMap(
params[commonData.ava.model.numJoints() + 1],
commonData.ava.model.numShapeKeys(), 1);
jointPosVec.noalias() =
commonData.ava.model.jointShapeRegBase.cast<T>() +
commonData.ava.model.jointShapeReg.cast<T>() * wMap;
} else {
jointPosVec.noalias() =
commonData.ava.model.jointShapeRegBase.cast<T>() +
commonData.ava.model.jointShapeReg.cast<T>() *
commonData.ava.w.cast<T>();
}
} else {
jointPos.noalias() =
cloud * commonData.ava.model.jointRegressor.cast<T>();
}
Eigen::Matrix<T, 3, 1> offset = jointPos.col(0);
cloud.colwise() -= offset;
jointPos.colwise() -= offset;
VecMap resid(residual);
resid.setZero();
ConstVecMap rootPos(params[0]);
for (auto &assign : commonData.ava.model.assignedJoints[pointId]) {
Eigen::Matrix<T, 3, 1> vec =
(cloud.col(pointId) - jointPos.col(assign.second))
.template cast<T>();
for (int p = assign.second; p != -1;
p = commonData.ava.model.parent[p]) {
vec = ConstQuatMap(params[p + 1]).toRotationMatrix() * vec;
// Do not add if root joint since we want to add the rootPos
// instead in autodiff case
if (p)
vec.noalias() +=
jointPos.col(p) -
jointPos.col(commonData.ava.model.parent[p]);
}
resid.noalias() += assign.first * vec;
}
resid.noalias() += rootPos;
resid.noalias() -= dataCloud.col(dataPointId);
return true;
}
const CloudType &dataCloud;
int dataPointId, pointId;
size_t cacheId;
AvatarEvaluationCommonData<AvatarCostFunctorCache> &commonData;
};
#endif // TEST_COMPARE_AUTO_DIFF
typedef nanoflann::KDTreeEigenColMajorMatrixAdaptor<CloudType, 3,
nanoflann::metric_L2_Simple>
KdTree;
void findNN(const CloudType &data_cloud,
const Eigen::VectorXi &data_part_labels,
const std::vector<Eigen::VectorXi> &data_part_indices,
const CloudType &model_cloud,
const Eigen::VectorXi &model_part_labels,
const std::vector<Eigen::VectorXi> &model_part_indices,
std::vector<CloudType> &model_part_clouds,
std::vector<bool> &point_visible,
std::vector<std::vector<int>> &correspondences,
std::vector<std::unique_ptr<KdTree>> &part_kd, int nn_step,
int num_threads, bool invert = false) {
if (invert) {
size_t index;
double dist;
nanoflann::KNNResultSet<double> resultSet(1);
// match each data point to a model point
typedef nanoflann::KDTreeEigenColMajorMatrixAdaptor<
CloudType, 3, nanoflann::metric_L2_Simple>
KdTree;
const size_t numParts = model_part_indices.size();
std::vector<KdTree *> modelPartKD(numParts);
std::vector<std::vector<int>> newModelPartIndices(numParts);
{
std::atomic<int> part(0);
auto worker = [&]() {
int i = 0;
while (true) {
i = part++;
if (i >= numParts) break;
const auto &indices = model_part_indices[i];
int cnt = 0;
for (int j = 0; j < indices.rows(); ++j) {
int k = indices[j];
if (point_visible[k]) ++cnt;
}
auto &partCloud = model_part_clouds[i];
if (cnt == 0) {
modelPartKD[i] = nullptr;
continue;
}
partCloud.resize(3, cnt);
cnt = 0;
for (int j = 0; j < indices.rows(); ++j) {
int k = indices[j];
if (!point_visible[k]) continue;
partCloud.col(cnt++).noalias() = model_cloud.col(k);
newModelPartIndices[i].push_back(k);
}
modelPartKD[i] = new KdTree(model_part_clouds[i], 10);
modelPartKD[i]->index->buildIndex();
}
};
std::vector<std::thread> thds;
for (int i = 0; i < num_threads; ++i) {
thds.emplace_back(worker);
}
for (int i = 0; i < num_threads; ++i) {
thds[i].join();
}
}
correspondences.resize(model_cloud.cols());
for (int i = 0; i < model_cloud.cols(); ++i) {
correspondences[i].clear();
}
for (int i = 0; i < data_cloud.cols(); ++i) {
resultSet.init(&index, &dist);
const int partId = data_part_labels[i];
if (modelPartKD[partId] == nullptr) continue;
modelPartKD[partId]->index->findNeighbors(
resultSet, data_cloud.data() + i * 3,
nanoflann::SearchParams(10));
correspondences[newModelPartIndices[partId][index]].push_back(i);
}
for (int i = 0; i < numParts; ++i) {
delete modelPartKD[i];
}
// const int MAX_CORRES_PER_POINT = 1;
// for (int i = 0; i < model_cloud.cols(); ++i) {
// if (correspondences[i].size() > MAX_CORRES_PER_POINT) {
// //std::cerr << correspondences[i].size() << "SZ\n";
// for (int j = 0; j < MAX_CORRES_PER_POINT; ++j) {
// int r = random_util::randint<int>(j,
// correspondences[i].size()-1);
// std::swap(correspondences[i][j], correspondences[i][r]);
// }
// correspondences[i].resize(MAX_CORRES_PER_POINT);
// }
// }
} else {
size_t index;
double dist;
nanoflann::KNNResultSet<double> resultSet(1);
// match each model point to a data point
correspondences.resize(model_cloud.cols());
for (int i = 0; i < model_cloud.cols(); ++i) {
correspondences[i].clear();
}
Eigen::VectorXi perPart(part_kd.size());
perPart.setZero();
for (int i = 0; i < model_cloud.cols(); i += nn_step) {
if (!point_visible[i]) continue;
resultSet.init(&index, &dist);
int partId = model_part_labels[i];
auto *kd_tree = part_kd[partId].get();
if (kd_tree) {
kd_tree->index->findNeighbors(resultSet,
model_cloud.data() + i * 3,
nanoflann::SearchParams(10));
correspondences[i].push_back(data_part_indices[partId][index]);
++perPart[partId];
}
}
for (int i = 0; i < perPart.rows(); ++i) {
std::cout << perPart(i) << " ";
}
std::cout << "!!\n";
// if (ownTree) {
// delete kd_tree;
// }
/*
const int MAX_CORRES_PER_POINT = 200;
for (int i = 0; i < model_cloud.cols(); ++i) {
if (correspondences[i].size() > MAX_CORRES_PER_POINT) {
//std::cerr << correspondences[i].size() << "SZ\n";
for (int j = 0; j < MAX_CORRES_PER_POINT; ++j) {
int r = random_util::randint<int>(j, correspondences[i].size()-1);
std::swap(correspondences[i][j], correspondences[i][r]);
}
correspondences[i].resize(MAX_CORRES_PER_POINT);
}
}
*/
}
}
#ifdef PCL_DEBUG_VISUALIZE
void debugVisualize(
const pcl::visualization::PCLVisualizer::Ptr &viewer,
const CloudType &data_cloud, std::vector<std::vector<int>> correspondences,
const std::vector<bool> &point_visible,
AvatarEvaluationCommonData<AvatarCostFunctorCache> &common) {
auto modelPclCloud = pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(
new pcl::PointCloud<pcl::PointXYZRGBA>());
auto dataPclCloud = pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(
new pcl::PointCloud<pcl::PointXYZRGBA>());
// auto matchedModelPointsCloud =
// pcl::PointCloud<pcl::PointXYZRGBA>::Ptr(new
// pcl::PointCloud<pcl::PointXYZRGBA>());
modelPclCloud->reserve(common.ava.cloud.cols());
for (int i = 0; i < common.ava.cloud.cols(); ++i) {
pcl::PointXYZRGBA pt;
pt.getVector3fMap() = common.ava.cloud.col(i).cast<float>();
if (!point_visible[i]) {
// pt.r = pt.g = pt.b = 100;
continue;
} else {
pt.r = 255;
pt.g = 0;
pt.b = 0;
}
pt.a = 255;
modelPclCloud->push_back(std::move(pt));
}
dataPclCloud->reserve(data_cloud.cols());
for (int i = 0; i < data_cloud.cols(); ++i) {
pcl::PointXYZRGBA pt;