File size: 46,388 Bytes
7b853a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
/*
 * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "TrajectoryCorrector.h"
#include "InverseKinematics.h"

#include "Utility.h"

#include <map>
#include <array>
#include <cmath>
#include <cstdlib>
#include <iostream>
using Pose = std::vector<Math::Transform>;

static const float pos_weight = 0.001f;
static const float vel_weight = 1.0f;
static const float acc_weight = 10.0f;


namespace {

    // Enable with: MOTIONCORRECTION_DEBUG_INTERVALS=1
    // Default: off (no Interval printing).
    bool DebugPrintIntervalsEnabled()
    {
        const char* v = std::getenv("MOTIONCORRECTION_DEBUG_INTERVALS");
        if (v == nullptr || v[0] == '\0')
        {
            return false;
        }
        // Treat "0" as false; any other non-empty value enables.
        return v[0] != '0';
    }


    void FilterContactIntervals(
        std::vector<std::pair<int, int>>& contactIntervals,
        const std::vector<float>& mask,
        bool one_bone_contact = false)
    {
        std::vector<uint32_t> keepIntervals;
        for (size_t i = 0; i < contactIntervals.size(); ++i)
        {
            const auto& interval = contactIntervals[i];

            bool startConstrained = (interval.first != 0 && mask[interval.first - 1]);
            bool endConstrained;

            endConstrained = (interval.second != mask.size() && mask[interval.second]);

            if (one_bone_contact)
            {
                if (startConstrained || endConstrained)
                {
                    continue;
                }
            }
            else
            {
                // If both the start and end of the contact interval are masked,
                // there's no way we can correct the contact without popping, so
                // let's filter these out:
                if (startConstrained && endConstrained)
                {
                    continue;
                }
            }

            keepIntervals.push_back(i);
        }

        for (size_t i = 0; i < keepIntervals.size(); ++i)
        {
            contactIntervals[i] = contactIntervals[keepIntervals[i]];
        }
        contactIntervals.resize(keepIntervals.size());
    }

    std::vector<std::pair<int, int>> ComputeContactIntervals(
        const std::vector<float>& contacts,
        const std::vector<float>& mask,
        float contactThreshold)
    {
        // turn off the contacts for all frames that are constrained/masked:
        std::vector<float> contactsNoMask = contacts;
        for (size_t i = 0; i < mask.size(); ++i)
        {
            if (mask[i])
            {
                contactsNoMask[i] = 0;
            }
        }

        // Find intervals that are in contact:
        std::vector<std::pair<int, int>> contactIntervals;
        int start = -1;
        for (int frame = 0; frame < mask.size(); ++frame)
        {
            bool isContact = contactsNoMask[frame] > contactThreshold;
            if (isContact && start == -1)
            {
                start = frame;
            }
            else if (!isContact && start != -1)
            {
                contactIntervals.emplace_back(start, frame);
                start = -1;
            }
        }

        // Close the final interval if needed:
        if (start != -1)
        {
            contactIntervals.emplace_back(start, mask.size());
        }
        return contactIntervals;
    }

    void FindContactPoints(
        std::vector<Math::Vector> &points,
        std::vector<int> &inContact,
        const std::vector<int>& joint_parents_vec,
        int32_t jointIndex,
        const std::vector<Pose> &poses,
        const std::vector<std::pair<int, int>>& contactIntervals,
        const std::vector<float>& mask,
        size_t frameCount,
        float minHeight)
    {
        // Find a representative frame for each interval.
        // If the interval starts after a masked frame, use the start
        // of the interval, if it ends before a mask use the end,
        // otherwise use the middle frame.
        inContact.clear();
        inContact.resize(frameCount, 0);
        points.clear();
        points.resize(frameCount);
        for (size_t i = 0; i < contactIntervals.size(); ++i)
        {
            const auto& interval = contactIntervals[i];
            int frame = -1;
            bool startConstrained = (interval.first != 0 && mask[interval.first - 1]);
            bool endConstrained;

            endConstrained = (interval.second != mask.size() && mask[interval.second]);

            // Debug output (opt-in via env var)
            if (DebugPrintIntervalsEnabled())
            {
                std::cout << "Interval " << i << ": start=" << interval.first
                          << ", end=" << interval.second
                          << ", startConstrained=" << startConstrained
                          << ", endConstrained=" << endConstrained << std::endl;
            }

            if(startConstrained)
            {
                // If the interval starts on a constraint, use the constrained frame
                // as a target (doing this modulo mask.size() in case we're looping)
                frame = interval.first - 1;
            }
            else if (endConstrained)
            {
                // If the interval ends on a constraint, use the constrained frame
                // as a target:
                frame = interval.second;
            }
            else
            {
                // Otherwise use the midpoint of the interval:
                frame = (interval.first + interval.second) / 2;
            }

            // get the target point:
            Math::Vector target = Animation::JointLocalToGlobal(joint_parents_vec, jointIndex, poses[frame]).GetTranslation();
            for(int i = interval.first; i < interval.second; ++i)
            {
                Math::Vector framePt = Animation::JointLocalToGlobal(joint_parents_vec, jointIndex, poses[i]).GetTranslation();
                inContact[i] = 1;
                points[i] = target;
                if (!startConstrained && !endConstrained)
                {
                    points[i].SetY(std::max(framePt.GetY(), minHeight));
                    // std::cout << "  Frame " << i << ": SetY with framePt.GetY()=" << framePt.GetY()
                    //           << ", minHeight=" << minHeight << std::endl;
                }
            }
        }
    }

    float TargetReachFalloff(
        const std::vector<int>& joint_parents_vec,
        const Pose& defaultPose,
        int32_t jointIndex,
        Animation::IKType ikType,
        const Math::Vector& target,
        const Pose& pose,
        const Math::Transform& rootTx = Math::Transform::Identity)
    {
        float maxReach = defaultPose[jointIndex].GetTranslation().GetLength3();
        if (ikType == Animation::IKType::kTwoBone)
        {
            jointIndex = joint_parents_vec[jointIndex];
            ASSERT(jointIndex > -1);
            maxReach += defaultPose[jointIndex].GetTranslation().GetLength3();
        }
        // Get base joint world Tx
        jointIndex = joint_parents_vec[jointIndex];
        ASSERT(jointIndex > -1);
        const auto worldTx = Animation::JointLocalToGlobal(joint_parents_vec, jointIndex, pose, rootTx);

        // Gaussian falloff
        float targetDist = target.GetDistance3(worldTx.GetTranslation());
        float tmp = Math::Max(targetDist / maxReach - 0.99f, 0.f) / 0.01f;
        tmp = tmp * tmp;
        return std::exp(-2.f * tmp * tmp);
    }

    void CorrectHipsY(
        std::vector<Pose>& poses,
        const std::vector<Pose>& targetPoses,
        const std::vector<float>& fullBodyMask,
        const std::vector<Animation::ContactInfo>& contacts,
        float contactThreshold
    )
    {
        // Correct the y coordinates of the root.
        auto N = poses.size();
        Eigen::MatrixXd x(N, 1);
        Eigen::MatrixXd observations(N, 1);
        Eigen::MatrixXd xfixed(N, 1);

        // Fill in the initial trajectory (x) and the values we want to hit when we
        // warp it (observations):
        Eigen::VectorXd yCorrectMargins(N);
        for(size_t frame = 0; frame < N; ++frame)
        {
            yCorrectMargins[frame] = fullBodyMask[frame] ? 0.0f : -1.0f;
            x(frame, 0) = ((float*)&poses[frame][0].GetTranslation())[1];
            observations(frame, 0) = ((float*)&targetPoses[frame][0].GetTranslation())[1];
        }

        TrajectoryCorrector ycorrector(
            yCorrectMargins,
            pos_weight * 10,
            vel_weight,
            acc_weight * 0.1f
        );
        ycorrector.Interpolate(
            xfixed,
            observations,
            x
        );

        // fill channel again:
        for (uint32_t frame = 0; frame < N; ++frame)
        {
            ((float*)&poses[frame][0].GetTranslation())[1] = float(xfixed(frame, 0));
        }
    }

    void SmoothChannels(
        Eigen::MatrixXd &x,
        const std::vector<float>& mask
    )
    {
        for( uint32_t i=0; i < mask.size(); ++i)
        {
            uint32_t i_prev = i == 0 ? 0 : i-1;
            uint32_t i_next = std::min(uint32_t(i+1), uint32_t(mask.size()-1));
            if(i > 0 && mask[i] > 0 && mask[i_prev] == 0)
            {
                // if the previous frame is unconstrained and the current frame is constrained,
                // replace the current frame with the average of its neighbors:
                for(long j=0; j < x.cols(); ++j)
                {
                    x(i, j) = 0.5f * (x(i_prev, j) + x(i_next, j));
                }
            }
            if(mask[i] > 0 && mask[i_next] == 0)
            {
                // if the next frame is unconstrained and the current frame is constrained,
                // replace the current frame with the average of its neighbors:
                for(long j=0; j < x.cols(); ++j)
                {
                    x(i, j) = 0.5f * (x(i_prev, j) + x(i_next, j));
                }
            }
        }
    }


    void CorrectHipsXZ(
        std::vector<Pose>& poses,
        const std::vector<Pose>& targetPoses,
        const std::vector<float>& fullBodyMask,
        const std::vector<float>& rootMask,
        const std::vector<Animation::ContactInfo>& endEffectorPins,
        const Eigen::VectorXd& velocity_weights,
        float root_margin
    )
    {
        auto N = poses.size();
        Eigen::VectorXd margins(N);
        for( size_t i = 0; i < N; ++i )
        {
            margins[i] = fullBodyMask[i] ? 0.0f : -1.0f;
        }

        std::vector<float> rootCombinedMask(N, 0.0f);
        for(size_t i = 0; i < N; ++i)
        {
            rootCombinedMask[i] = (fullBodyMask[i] > 0) || (rootMask[i] > 0);
            if(rootMask[i] > 0 && margins[i] != 0)
            {
                margins[i] = root_margin;
            }
            for (auto& c : endEffectorPins)
            {
                if (c.contactMask[i] && margins[i] != 0)
                {
                    margins[i] = root_margin;
                }
            }
        }
        TrajectoryCorrector xzcorrector(
            margins,
            pos_weight,
            vel_weight,
            acc_weight,
            velocity_weights
        );

        // Enforce pose constraints on root xz trajectory:
        Eigen::MatrixXd x(N, 2);
        Eigen::MatrixXd observations(N, 2);
        Eigen::MatrixXd x_fixed(N, 2);

        observations.setZero();
        for (uint32_t frame = 0; frame < N; ++frame)
        {
            x(frame, 0) = ((float*)&poses[frame][0].GetTranslation())[0];
            x(frame, 1) = ((float*)&poses[frame][0].GetTranslation())[2];

            observations(frame, 0) = ((float*)&targetPoses[frame][0].GetTranslation())[0];
            observations(frame, 1) = ((float*)&targetPoses[frame][0].GetTranslation())[2];
        }

        SmoothChannels(x, rootCombinedMask);

        xzcorrector.Interpolate(
            x_fixed,
            observations,
            x
        );

        // fill channels again:
        for (uint32_t frame = 0; frame < N; ++frame)
        {
            ((float*)&poses[frame][0].GetTranslation())[0] = float(x_fixed(frame, 0));
            ((float*)&poses[frame][0].GetTranslation())[2] = float(x_fixed(frame, 1));
        }
    }

    void CorrectRotationsForBone(
        std::vector<Pose>& poses,
        const std::vector<Pose>& targetPoses,
        const std::vector<float>& mask,
        const TrajectoryCorrector& corrector,
        int boneIdx,
        bool performChannelSmoothing)
    {
        auto N = poses.size();
        Eigen::MatrixXd x(N, 1);
        Eigen::MatrixXd observations(N, 1);
        observations.setZero();
        Eigen::MatrixXd x_fixed(N, 1);

        // Quaternion components can flip when they pass through 180 degree
        // rotations, so let's convert all the quaternions in this channel to
        // the forward/up vector representation, modify them, then convert back
        // to quaternions:

        // convert time series to 6d forward/up:
        std::vector<float> forwardUp(6 * N);
        std::vector<float> targetForwardUp(6 * N);
        for (uint32_t frame = 0; frame < N; ++frame)
        {
            auto q = poses[frame][boneIdx].GetRotation();
            auto forward = q.ZAxis();
            auto up = q.YAxis();
            forwardUp[N * 0 + frame] = forward.GetX();
            forwardUp[N * 1 + frame] = forward.GetY();
            forwardUp[N * 2 + frame] = forward.GetZ();
            forwardUp[N * 3 + frame] = up.GetX();
            forwardUp[N * 4 + frame] = up.GetY();
            forwardUp[N * 5 + frame] = up.GetZ();

            q = targetPoses[frame][boneIdx].GetRotation();
            forward = q.ZAxis();
            up = q.YAxis();
            targetForwardUp[N * 0 + frame] = forward.GetX();
            targetForwardUp[N * 1 + frame] = forward.GetY();
            targetForwardUp[N * 2 + frame] = forward.GetZ();
            targetForwardUp[N * 3 + frame] = up.GetX();
            targetForwardUp[N * 4 + frame] = up.GetY();
            targetForwardUp[N * 5 + frame] = up.GetZ();
        }

        // correct trajectories:
        for (uint32_t dim = 0; dim < 6; ++dim)
        {
            for (uint32_t frame = 0; frame < N; ++frame)
            {
                x(frame, 0) = forwardUp[N * dim + frame];
                observations(frame, 0) = mask[frame] * targetForwardUp[N * dim + frame];
            }

            if (performChannelSmoothing)
            {
                SmoothChannels(x, mask);
            }

            corrector.Interpolate(
                x_fixed,
                observations,
                x
            );

            // fill channel again:
            for (uint32_t frame = 0; frame < N; ++frame)
            {
                forwardUp[N * dim + frame] = float(x_fixed(frame, 0));
            }
        }

        for (uint32_t frame = 0; frame < N; ++frame)
        {
            Math::Vector forward = { forwardUp[N * 0 + frame] ,forwardUp[N * 1 + frame] ,forwardUp[N * 2 + frame] };
            Math::Vector up = { forwardUp[N * 3 + frame] ,forwardUp[N * 4 + frame] ,forwardUp[N * 5 + frame] };

            forward.Normalize3();
            up.Normalize3();

            poses[frame][boneIdx].SetRotation(Math::Quaternion::LookRotation(forward, up));
        }
    }

    void CorrectJointRotations(
        std::vector<Pose>& poses,
        const std::vector<Pose>& targetPoses,
        const std::vector<float>& fullBodyMask,
        const Eigen::VectorXd& velocity_weights
    )
    {
        auto N = poses.size();

        // Create a trajectory corrector for fixing the full body fullBodyMask positions:
        Eigen::VectorXd margins(N);
        for( size_t i = 0; i < N; ++i )
        {
            margins[i] = fullBodyMask[i] ? 0.0f : -1.0f;
        }
        TrajectoryCorrector corrector(
            margins,
            pos_weight * 10,
            vel_weight,
            acc_weight,
            velocity_weights
        );

        for (uint32_t boneIdx = 0; boneIdx < poses[0].size(); ++boneIdx)
        {
            CorrectRotationsForBone(
                poses,
                targetPoses,
                fullBodyMask,
                corrector,
                boneIdx,
                true
            );
        }
    }

    void DoEffectorIK(
        std::vector<Pose>& poses,
        const std::vector<Pose>& targetPoses,
        const std::vector<float>& fullBodyMask,
        const std::vector<Animation::ContactInfo>& endEffectorPins,
        const std::vector<int>& joint_parents_vec,
        const std::vector<Math::Transform>& defaultPose
    )
    {
        // Apply IK for effector pins
        auto N = poses.size();
        std::map<uint32_t, std::vector<float>> jointCorrectionMasks;
        std::vector<Pose> ikFixedPoses = poses;
        for (auto& c : endEffectorPins)
        {
            auto jointIdx = c.jointIndex;

            if(jointCorrectionMasks[jointIdx].empty())
            {
                // initialize to the full body constraint mask because we
                // want to constrain that anyway:
                jointCorrectionMasks[jointIdx] = fullBodyMask;
            }

            // Add a trajectory correction mask for the parent joint:
            auto parentIdx = joint_parents_vec[jointIdx];
            if(jointCorrectionMasks[parentIdx].empty())
            {
                // initialize to the full body constraint mask because we
                // want to constrain that anyway:
                jointCorrectionMasks[parentIdx] = fullBodyMask;
            }

            // Add a trajectory correction mask for its parent if this is
            // 2 bone IK:
            auto parentParentIdx = joint_parents_vec[parentIdx];
            if(c.contactType == Animation::kTwoBone)
            {
                if(jointCorrectionMasks[parentParentIdx].empty())
                {
                    // initialize to the full body constraint mask because we
                    // want to constrain that anyway:
                    jointCorrectionMasks[parentParentIdx] = fullBodyMask;
                }
            }

            for (uint32_t fixFrame = 0; fixFrame < fullBodyMask.size(); ++fixFrame)
            {
                if (c.contactMask[fixFrame])
                {
                    const auto targetGlobalTransform = Animation::JointLocalToGlobal(joint_parents_vec, jointIdx, targetPoses[fixFrame]);

                    // flag the parent joint as fixed in its correction mask:
                    jointCorrectionMasks[parentIdx][fixFrame] = 1;
                    switch(c.contactType)
                    {
                        case Animation::kOneBone:
                        {
                            IK::OneBoneIk(
                                ikFixedPoses[fixFrame],
                                Math::Transform::Identity,
                                jointIdx,
                                1.0,
                                targetGlobalTransform.GetTranslation(),
                                joint_parents_vec
                            );
                            break;
                        }
                        case Animation::kTwoBone:
                        {
                            // flag the parent parent joint as fixed in its correction mask:
                            jointCorrectionMasks[parentParentIdx][fixFrame] = 1;
                            IK::TwoBoneIk(
                                ikFixedPoses[fixFrame],
                                Math::Transform::Identity,
                                jointIdx,
                                1.0,
                                targetGlobalTransform.GetTranslation(),
                                joint_parents_vec,
                                c.hintOffset
                            );
                            break;
                        }
                    }

                    // now we need to fix things so the global rotation of the joint
                    // matches the input:
                    jointCorrectionMasks[jointIdx][fixFrame] = 1;
                    auto parentGlobalTransform = Animation::JointLocalToGlobal(joint_parents_vec, parentIdx, ikFixedPoses[fixFrame]);
                    ikFixedPoses[fixFrame][jointIdx].SetRotation(
                        targetGlobalTransform.GetRotation() * parentGlobalTransform.GetRotation().GetConjugate()
                    );

                }
            }
        }

        // Applying the effector pin IK introduces popping into the animation,
        // so let's apply the interpolator to all the joints we modified so as to
        // line the trajectory up properly again:
        Eigen::VectorXd margins(N);
        for( auto &kv : jointCorrectionMasks)
        {
            for( size_t i = 0; i < N; ++i )
            {
                margins[i] = kv.second[i] ? 0.0f : -1.0f;
            }
            TrajectoryCorrector corrector(margins, pos_weight * 10, vel_weight, acc_weight);

            CorrectRotationsForBone(
                poses,
                ikFixedPoses,
                kv.second,
                corrector,
                kv.first,
                false
            );
        }
    }

    void DoContactIK(
        std::vector<Pose>& poses,
        const std::vector<float>& fullBodyMask,
        const std::vector<Animation::ContactInfo>& contacts,
        const std::vector<Animation::ContactInfo>& endEffectorPins,
        const std::vector<int>& joint_parents_vec,
        const std::vector<Math::Transform>& defaultPose,
        float contactThreshold,
        bool has_double_ankle_joints
    )
    {
        auto N = poses.size();
        Eigen::VectorXd margins = Eigen::VectorXd::Zero(N);

        // Apply IK to stabilize limbs on contacts
        std::map<uint32_t, std::vector<float>> jointCorrectionMasks;
        std::vector<Pose> ikFixedPoses = poses;

        // Save original poses before any modifications (for double ankle correction later)
        const std::vector<Pose> originalPoses = poses;

        // Track which frames were corrected for each 2-bone contact (for double ankle correction later)
        std::map<uint32_t, std::vector<bool>> twoBoneContactFrames;

        auto addEndEffectorMask = [&](uint32_t jointIdx, uint32_t parentIdx, std::vector<float>& jointMask)
        {
            auto it = std::find_if(
                endEffectorPins.begin(), endEffectorPins.end(),
                [&](const auto &c)
                {
                    if(jointIdx == c.jointIndex)
                    {
                        return true;
                    }
                    return false;
                }
            );
            if(it == endEffectorPins.end())
            {
                // We could be correcting the toe joint, in which case we need to use
                // the parent joint instead:
                it = std::find_if(
                    endEffectorPins.begin(), endEffectorPins.end(),
                    [&](const auto &c)
                    {
                        if(parentIdx == c.jointIndex)
                        {
                            return true;
                        }
                        return false;
                    }
                );
            }
            if(it != endEffectorPins.end())
            {
                const auto &msk = it->contactMask;
                for(size_t i=0; i < msk.size(); ++i)
                {
                    if(msk[i])
                    {
                        jointMask[i] = 1.0f;
                    }
                }
            }
        };

        // Process two bone contacts first:
        for (auto& c : contacts)
        {
            if(c.contactType != Animation::kTwoBone)
            {
                continue;
            }
            const auto jointIdx = c.jointIndex;
            auto parentIdx = joint_parents_vec[jointIdx];
            auto parentParentIdx = joint_parents_vec[parentIdx];

            auto jointMask = fullBodyMask;
            addEndEffectorMask(jointIdx, parentIdx, jointMask);

            // We'll actually be modifying 3 joints here:
            // * The two joints immediately up in the hierarchy because of the 2 bone IK
            // * The joint itself because we restore its original global rotation
            if(jointCorrectionMasks[parentIdx].empty())
            {
                jointCorrectionMasks[parentIdx] = jointMask;
            }
            if(jointCorrectionMasks[parentParentIdx].empty())
            {
                jointCorrectionMasks[parentParentIdx] = jointMask;
            }
            if(jointCorrectionMasks[jointIdx].empty())
            {
                jointCorrectionMasks[jointIdx] = jointMask;
            }

            // Compute the intervals in which the joint is in contact with the floor:
            auto contactIntervals = ComputeContactIntervals(c.contactMask, jointMask, contactThreshold);
            FilterContactIntervals(contactIntervals, jointMask);

            std::vector<Math::Vector> contactPoints;
            std::vector<int> inContact;
            FindContactPoints(
                contactPoints,
                inContact,
                joint_parents_vec,
                jointIdx,
                poses,
                contactIntervals,
                jointMask,
                c.contactMask.size(),
                c.minHeight
            );

            for (uint32_t fixFrame = 0; fixFrame < fullBodyMask.size(); ++fixFrame)
            {
                if (inContact[fixFrame])
                {
                    auto target = contactPoints[fixFrame];
                    jointCorrectionMasks[parentIdx][fixFrame] = 1.0f;
                    jointCorrectionMasks[parentParentIdx][fixFrame] = 1.0f;
                    jointCorrectionMasks[jointIdx][fixFrame] = 1.0f;

                    // Track this frame for double ankle correction later
                    if (has_double_ankle_joints)
                    {
                        if (twoBoneContactFrames[jointIdx].empty())
                            twoBoneContactFrames[jointIdx].resize(fullBodyMask.size(), false);
                        twoBoneContactFrames[jointIdx][fixFrame] = true;
                    }

                    // save the original global rotation of the joint:
                    auto jointGlobalRotation = Animation::JointLocalToGlobal(
                        joint_parents_vec,
                        jointIdx,
                        ikFixedPoses[fixFrame]
                    ).GetRotation();

                    const float w = TargetReachFalloff(
                        joint_parents_vec,
                        defaultPose,
                        jointIdx,
                        c.contactType,
                        target,
                        ikFixedPoses[fixFrame]
                    );
                    // std::cout << "Frame " << fixFrame << ": w=" << w << std::endl;

                    // apply the 2 bone IK:
                    auto origParentRotation = ikFixedPoses[fixFrame][parentIdx].GetRotation();
                    auto origParentParentRotation = ikFixedPoses[fixFrame][parentParentIdx].GetRotation();
                    IK::TwoBoneIk(
                        ikFixedPoses[fixFrame],
                        Math::Transform::Identity,
                        jointIdx,
                        1.0f,
                        target,
                        joint_parents_vec,
                        c.hintOffset
                    );
                    ikFixedPoses[fixFrame][parentIdx].SetRotation(Math::Quaternion::SLerp(origParentRotation, ikFixedPoses[fixFrame][parentIdx].GetRotation(), w));
                    ikFixedPoses[fixFrame][parentParentIdx].SetRotation(Math::Quaternion::SLerp(origParentParentRotation, ikFixedPoses[fixFrame][parentParentIdx].GetRotation(), w));

                    // restore previous global rotation of this joint:
                    auto parentGloblalRotation = Animation::JointLocalToGlobal(
                        joint_parents_vec,
                        parentIdx,
                        ikFixedPoses[fixFrame]
                    ).GetRotation();

                    jointCorrectionMasks[jointIdx][fixFrame] = 1.0f;
                    ikFixedPoses[fixFrame][jointIdx].SetRotation(
                        jointGlobalRotation * parentGloblalRotation.GetConjugate()
                    );

                    auto result = Animation::JointLocalToGlobal(
                        joint_parents_vec,
                        jointIdx,
                        ikFixedPoses[fixFrame]
                    ).GetTranslation();
                }
            }

        }

        for( auto &kv : jointCorrectionMasks)
        {
            for( size_t i = 0; i < N; ++i )
            {
                margins[i] = kv.second[i] ? 0.0f : -1.0f;
            }
            TrajectoryCorrector corrector(margins, pos_weight * 10, vel_weight, acc_weight);
            CorrectRotationsForBone(
                poses,
                ikFixedPoses,
                kv.second,
                corrector,
                kv.first,
                false
            );
        }
        jointCorrectionMasks.clear();

        // Then process one bone contacts:
        for(auto &c : contacts)
        {
            if(c.contactType != Animation::kOneBone)
            {
                continue;
            }
            const auto jointIdx = c.jointIndex;
            auto parentIdx = joint_parents_vec[jointIdx];

            // We can't touch frames that have been constrained with full body constraints
            // or the end effector constraints for this joint, so let's combine fullBodyMask
            // with the end effector mask for this joint if it exists so we can use that
            // information later:
            auto jointMask = fullBodyMask;
            addEndEffectorMask(jointIdx, parentIdx, jointMask);

            // Add a trajectory correction mask for the parent joint:
            if(jointCorrectionMasks[parentIdx].empty())
            {
                jointCorrectionMasks[parentIdx] = jointMask;
            }

            // Compute the intervals in which the joint is in contact with the floor:
            auto contactIntervals = ComputeContactIntervals(c.contactMask, jointMask, contactThreshold);
            FilterContactIntervals(contactIntervals, jointMask, true);
            for(const auto &interval : contactIntervals)
            {
                for (int fixFrame = interval.first; fixFrame < interval.second; ++fixFrame)
                {
                    // All we're going to do here is stick the joint to the floor -
                    // we're going to allow it to slide from side to side.

                    // Find a target position that lies on the floor by iteratively
                    // projecting the joint to the floor (pure laziness really, this could
                    // be done analytically):
                    Math::Vector parentPos = Animation::JointLocalToGlobal(joint_parents_vec, parentIdx, ikFixedPoses[fixFrame]).GetTranslation();
                    Math::Vector target = Animation::JointLocalToGlobal(joint_parents_vec, jointIdx, ikFixedPoses[fixFrame]).GetTranslation();
                    float jointLength = (target - parentPos).GetLength3();
                    for(int32_t i = 0; i < 10; ++i)
                    {
                        target.SetY(c.minHeight);
                        auto dir = (target - parentPos).GetNormalized3();
                        target = parentPos + dir * jointLength;
                    }

                    IK::OneBoneIk(
                        ikFixedPoses[fixFrame],
                        Math::Transform::Identity,
                        jointIdx,
                        1.0f,
                        target,
                        joint_parents_vec
                    );
                    jointCorrectionMasks[parentIdx][fixFrame] = 1.0f;
                }
            }

        }

        // Fixing the contacts with IK will introduce popping into the animation,
        // so let's apply the interpolator to all the joints we modified so as to
        // line the trajectory up properly again:
        for( auto &kv : jointCorrectionMasks)
        {
            for( size_t i = 0; i < N; ++i )
            {
                margins[i] = kv.second[i] ? 0.0f : -1.0f;
            }
            TrajectoryCorrector corrector(margins, pos_weight * 10, vel_weight, acc_weight);
            CorrectRotationsForBone(
                poses,
                ikFixedPoses,
                kv.second,
                corrector,
                kv.first,
                false
            );
        }

        if (has_double_ankle_joints)
        {
            // Maps to save target positions BEFORE 2-bone IK modifies them
            std::map<uint32_t, std::map<uint32_t, Math::Vector>> savedFirstAnkleTargets;  // [firstAnkleIdx][frame] -> position
            std::map<uint32_t, std::map<uint32_t, Math::Vector>> savedToeTargets;         // [firstAnkleIdx][frame] -> position
            std::map<uint32_t, uint32_t> contactToToeIdx;  // firstAnkleIdx -> toeIdx

            // Find toe joints for each leg
            for (const auto& tc : contacts)
            {
                if (tc.contactType == Animation::kOneBone)
                {
                    // The parent of the toe is the 1st ankle
                    int parentIdx = joint_parents_vec[tc.jointIndex];
                    if (parentIdx >= 0)
                    {
                        contactToToeIdx[parentIdx] = tc.jointIndex;
                    }
                }
            }

            // For each 2-bone contact, correct the parent (2nd ankle) joint
            for (auto& c : contacts)
            {
                if (c.contactType != Animation::kTwoBone)
                    continue;

                const auto firstAnkleIdx = c.jointIndex;
                const auto secondAnkleIdx = joint_parents_vec[firstAnkleIdx];
                const auto kneeIdx = joint_parents_vec[secondAnkleIdx];
                const auto hipIdx = joint_parents_vec[kneeIdx];

                if (hipIdx < 0) continue;  // safety check

                // Get saved contact frames for this ankle
                auto it = twoBoneContactFrames.find(firstAnkleIdx);
                if (it == twoBoneContactFrames.end())
                    continue;
                const auto& contactFrames = it->second;

                // Add correction mask for knee and hip
                auto jointMask = fullBodyMask;
                addEndEffectorMask(firstAnkleIdx, secondAnkleIdx, jointMask);

                if (jointCorrectionMasks[kneeIdx].empty())
                    jointCorrectionMasks[kneeIdx] = jointMask;
                if (jointCorrectionMasks[hipIdx].empty())
                    jointCorrectionMasks[hipIdx] = jointMask;

                for (uint32_t fixFrame = 0; fixFrame < fullBodyMask.size(); ++fixFrame)
                {
                    // Only correct frames where the 1st ankle was corrected
                    if (!contactFrames[fixFrame])
                        continue;

                    // *** SAVE TARGET POSITIONS BEFORE 2-BONE IK ***
                    savedFirstAnkleTargets[firstAnkleIdx][fixFrame] = Animation::JointLocalToGlobal(
                        joint_parents_vec, firstAnkleIdx, ikFixedPoses[fixFrame]).GetTranslation();

                    if (contactToToeIdx.count(firstAnkleIdx))
                    {
                        savedToeTargets[firstAnkleIdx][fixFrame] = Animation::JointLocalToGlobal(
                            joint_parents_vec, contactToToeIdx[firstAnkleIdx], ikFixedPoses[fixFrame]).GetTranslation();
                    }

                    // Get original global transforms (before any IK corrections)
                    auto originalFirstAnkleGlobal = Animation::JointLocalToGlobal(
                        joint_parents_vec, firstAnkleIdx, originalPoses[fixFrame]);
                    auto originalSecondAnkleGlobal = Animation::JointLocalToGlobal(
                        joint_parents_vec, secondAnkleIdx, originalPoses[fixFrame]);

                    // Compute delta from 1st ankle to 2nd ankle in original animation
                    auto deltaFirstToSecond = originalFirstAnkleGlobal.GetDeltaToOther(originalSecondAnkleGlobal);

                    // Get corrected 1st ankle global transform
                    auto correctedFirstAnkleGlobal = Animation::JointLocalToGlobal(
                        joint_parents_vec, firstAnkleIdx, ikFixedPoses[fixFrame]);

                    // Apply the original delta to the corrected 1st ankle to get target for 2nd ankle
                    auto target = (deltaFirstToSecond * correctedFirstAnkleGlobal).GetTranslation();

                    // print current and target second ankle positions
                    auto currPos = Animation::JointLocalToGlobal(
                        joint_parents_vec, secondAnkleIdx, ikFixedPoses[fixFrame]).GetTranslation();

                    // Apply 2-bone IK: Hip -> Knee -> 2nd Ankle
                    IK::TwoBoneIk(
                        ikFixedPoses[fixFrame],
                        Math::Transform::Identity,
                        secondAnkleIdx,
                        1.0f,
                        target,
                        joint_parents_vec,
                        c.hintOffset
                    );

                    // auto correctedPos = Animation::JointLocalToGlobal(
                    //     joint_parents_vec, secondAnkleIdx, ikFixedPoses[fixFrame]).GetTranslation();
                    // std::cout << "Frame " << fixFrame << ": target second ankle=(" << target.GetX() << ", " << target.GetY() << ", " << target.GetZ() << "), corrected second ankle position=(" << correctedPos.GetX() << ", " << correctedPos.GetY() << ", " << correctedPos.GetZ() << ")" << std::endl;

                    jointCorrectionMasks[kneeIdx][fixFrame] = 1.0f;
                    jointCorrectionMasks[hipIdx][fixFrame] = 1.0f;
                }
            }

            // Smooth the corrected joints
            for (auto& kv : jointCorrectionMasks)
            {
                for (size_t i = 0; i < N; ++i)
                    margins[i] = kv.second[i] ? 0.0f : -1.0f;

                TrajectoryCorrector corrector(margins, pos_weight * 10, vel_weight, acc_weight);
                CorrectRotationsForBone(poses, ikFixedPoses, kv.second, corrector, kv.first, false);
            }

            // *** PHASE 2: 1-bone IKs to restore 1st ankle and toe ***
            jointCorrectionMasks.clear();

            for (auto& c : contacts)
            {
                if (c.contactType != Animation::kTwoBone)
                    continue;

                const auto firstAnkleIdx = c.jointIndex;
                const auto secondAnkleIdx = joint_parents_vec[firstAnkleIdx];

                auto it = twoBoneContactFrames.find(firstAnkleIdx);
                if (it == twoBoneContactFrames.end())
                    continue;

                // Setup correction masks
                auto jointMask = fullBodyMask;
                addEndEffectorMask(firstAnkleIdx, secondAnkleIdx, jointMask);

                if (jointCorrectionMasks[secondAnkleIdx].empty())
                    jointCorrectionMasks[secondAnkleIdx] = jointMask;
                if (jointCorrectionMasks[firstAnkleIdx].empty())
                    jointCorrectionMasks[firstAnkleIdx] = jointMask;

                for (uint32_t fixFrame = 0; fixFrame < fullBodyMask.size(); ++fixFrame)
                {
                    if (!it->second[fixFrame])
                        continue;

                    // 1-bone IK: Rotate 2nd ankle so 1st ankle reaches saved target
                    IK::OneBoneIk(
                        ikFixedPoses[fixFrame],
                        Math::Transform::Identity,
                        firstAnkleIdx,
                        1.0f,
                        savedFirstAnkleTargets[firstAnkleIdx][fixFrame],
                        joint_parents_vec
                    );
                    jointCorrectionMasks[secondAnkleIdx][fixFrame] = 1.0f;

                    // auto target = savedFirstAnkleTargets[firstAnkleIdx][fixFrame];
                    // auto corrected = Animation::JointLocalToGlobal(
                    //     joint_parents_vec, firstAnkleIdx, ikFixedPoses[fixFrame]).GetTranslation();
                    // std::cout << "Frame " << fixFrame << ": target first ankle=(" << target.GetX() << ", " << target.GetY() << ", " << target.GetZ() << "), corrected first ankle=(" << corrected.GetX() << ", " << corrected.GetY() << ", " << corrected.GetZ() << ")" << std::endl;

                    // 1-bone IK: Rotate 1st ankle so toe reaches saved target
                    if (contactToToeIdx.count(firstAnkleIdx) && savedToeTargets[firstAnkleIdx].count(fixFrame))
                    {
                        IK::OneBoneIk(
                            ikFixedPoses[fixFrame],
                            Math::Transform::Identity,
                            contactToToeIdx[firstAnkleIdx],
                            1.0f,
                            savedToeTargets[firstAnkleIdx][fixFrame],
                            joint_parents_vec
                        );
                        jointCorrectionMasks[firstAnkleIdx][fixFrame] = 1.0f;
                    }

                    // target = savedToeTargets[firstAnkleIdx][fixFrame];
                    // corrected = Animation::JointLocalToGlobal(
                    //     joint_parents_vec, contactToToeIdx[firstAnkleIdx], ikFixedPoses[fixFrame]).GetTranslation();
                    // std::cout << "Frame " << fixFrame << ": target toe=(" << target.GetX() << ", " << target.GetY() << ", " << target.GetZ() << "), corrected toe=(" << corrected.GetX() << ", " << corrected.GetY() << ", " << corrected.GetZ() << ")" << std::endl;
                }
            }

            // Smooth 2nd ankle and 1st ankle
            for (auto& kv : jointCorrectionMasks)
            {
                for (size_t i = 0; i < N; ++i)
                    margins[i] = kv.second[i] ? 0.0f : -1.0f;

                TrajectoryCorrector corrector(margins, pos_weight * 10, vel_weight, acc_weight);
                CorrectRotationsForBone(poses, ikFixedPoses, kv.second, corrector, kv.first, false);
            }
        }
    }

}


Math::Transform Animation::JointLocalToGlobal(
    const std::vector<int>& joint_parents_vec,
    int32_t index,
    const Pose& localPose,
    const Math::Transform& rootTx)
{
    Math::Transform worldTx = Math::Transform::Identity;
    while (index > -1)
    {
        worldTx = worldTx * localPose[index];
        index = joint_parents_vec[index];
    }

    return worldTx * rootTx;
}

void Animation::CorrectMotion(
    std::vector<Pose>& poses,
    const std::vector<Pose>& targetPoses,
    const std::vector<float>& fullBodyMask,
    const std::vector<float>& rootMask,
    const std::vector<ContactInfo>& contacts,
    const std::vector<ContactInfo>& endEffectorPins,
    const std::vector<int>& joint_parents_vec,
    const std::vector<Math::Transform>& defaultPose,
    float contactThreshold,
    float root_margin,
    bool has_double_ankle_joints
)
{

    // Calculate some weights so we can preserve velocities more strongly on frames where
    // the root velocity is low
    const uint32_t N = poses.size();
    Eigen::VectorXd velocity_weights(N);
    for (uint32_t frame = 1; frame < N; ++frame)
    {
        // work out xz velocity for this frame:
        float xdiff = poses[frame][0].GetTranslation()[0] - poses[frame - 1][0].GetTranslation()[0];
        float zdiff = poses[frame][0].GetTranslation()[2] - poses[frame - 1][0].GetTranslation()[2];

        // find velocity magnitude, divided by a typical walking speed:
        float v_mag = sqrtf(xdiff*xdiff + zdiff*zdiff) / 0.05f;

        // weight lower velocities higher so that the corrector doesn't make the character drift around
        // when it's supposed to stand still:
        v_mag = std::max(v_mag, 1.0f/1000.0f);
        velocity_weights(frame) = 1.0f / v_mag;
    }
    velocity_weights[0] = velocity_weights[1];

    // Correct root y coordinates.
    // This will warp the root y coordinates in "poses" so they match the root y coordinates
    // in "targetPoses", on frames where the root y coordinates are constrained, ie the frames
    // where fullBodyMask = 1.
    // In addition to this, it preserves the root y coordinates in "pose" on frames where foot
    // contacts are active, to avoid mushiness when characters are jumping.
    CorrectHipsY(
        poses,
        targetPoses,
        fullBodyMask,
        contacts,
        contactThreshold
    );

    // Correct root xz coordinates:
    // This will warp the root xz coordinates in "poses" so they match the xz coordinates
    // in "targetPoses" on frames where fullBodyMask = 1, and warp them so they're within
    // "root_margin" units of targetPoses on frames where rootMask = 1.
    CorrectHipsXZ(
        poses,
        targetPoses,
        fullBodyMask,
        rootMask,
        endEffectorPins,
        velocity_weights,
        root_margin
    );

    // Correct joint rotations by warping the rotations so they match targetPoses on frames
    // where fullBodyMask = 1:
    CorrectJointRotations(
        poses,
        targetPoses,
        fullBodyMask,
        velocity_weights
    );

    // Apply IK for end effector pins
    DoEffectorIK(
        poses,
        targetPoses,
        fullBodyMask,
        endEffectorPins,
        joint_parents_vec,
        defaultPose
    );

    // Apply IK to stabilize limbs on contacts
    DoContactIK(
        poses,
        fullBodyMask,
        contacts,
        endEffectorPins,
        joint_parents_vec,
        defaultPose,
        contactThreshold,
        has_double_ankle_joints
    );
    // std::cout << "Running post processing." << std::endl;
}