Source

KODE / src / solvers / QuickStepCore.hpp

Full commit
  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
/*
  This file is part of the KODE.

    KODE Physics Library
    Copyright (C) 2013-2014  Daniel Kohler Osmari

    KODE is free software: you can redistribute it and/or modify it
    under the terms of EITHER:

        * the GNU Lesser General Public License as published by the
          Free Software Foundation, either version 3 of the License,
          or (at your option) any later version.

        * the Apache License, Version 2.0.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License and the Apache License for more
    details.

    You should have received a copy of the GNU Lesser General Public
    License along with this program.  If not, see
    <http://www.gnu.org/licenses/>.

    You may obtain a copy of the Apache License at
       http://www.apache.org/licenses/LICENSE-2.0
*/

#ifndef KODE_QUICKSTEP_CORE_H
#define KODE_QUICKSTEP_CORE_H

#include <vector>
#include <iostream>

#include <kode/World.hpp>
#include <kode/Body.hpp>
#include <kode/joints/Joint.hpp>

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif


#ifdef HAVE_EIGEN
#include <Eigen/Core>
#else
#include "MiniEigen.hpp"
#endif


#define ALIGN_VECTOR

using std::clog;
using std::endl;

namespace kode {

    namespace quickstep {

        using std::vector;



#ifdef HAVE_EIGEN

#ifdef ALIGN_VECTOR
        constexpr unsigned Dim = 4;
#else
        constexpr unsigned Dim = 3;
#endif

        // linear-angular vector
        using EVectorLA  = Eigen::Matrix<Real, Dim*2, 1>;
        using ERotMatrix = Eigen::Matrix<Real, Dim, Dim, Eigen::ColMajor>;

        using EVector3 = Eigen::Matrix<Real, 3, 1>;
        using EVector4 = Eigen::Matrix<Real, 4, 1>;
        using EMatrix3 = Eigen::Matrix<Real, 3, 3, Eigen::RowMajor>;

        using EM3Map = Eigen::Map<const EMatrix3>;

        template<class T, class U>
        Real
        dot(const T& a, const U& b) noexcept
        {
            return a.dot(b);
        }

        // Eize = Eigen-ize

        // Kize = KODE-ize

#ifdef ALIGN_VECTOR
        inline
        EVector4
        Eize(const Vector3& v) noexcept
        {
            return EVector4{v.x, v.y, v.z, 0};
        }

        inline
        Vector3
        Kize(const EVector4& v) noexcept
        {
            return Vector3{v(0), v(1), v(2)};
        }
#else
        inline
        EVector3
        Eize(const Vector3& v) noexcept
        {
            return EVector3{v.x, v.y, v.z};
        }

        inline
        Vector3
        Kize(const EVector3& v) noexcept
        {
            return Vector3{v(0), v(1), v(2)};
        }
#endif

        inline
        EM3Map
        Eize(const Matrix3& m) noexcept
        {
            return EM3Map(m.data());
        }

#else // not using Eigen

        // not point in aligning, it'll be slow anyways
        constexpr unsigned Dim = 3;

        using EVectorLA  = detail::Vector<Dim*2>;
        using ERotMatrix = detail::Matrix<Dim, Dim>;

        using EVector3 = detail::Vector<3>;
        using EMatrix3 = detail::Matrix<3, 3>;

        inline
        EVector3
        Eize(const Vector3& v) noexcept
        {
            return { v.x, v.y, v.z };
        }

        inline
        Vector3
        Kize(const EVector3& v) noexcept
        {
            return { v(0), v(1), v(2) };
        }

        inline
        EMatrix3
        Eize(const Matrix3& m) noexcept
        {
            EMatrix3 r;
            for (int i=0; i<3; ++i)
                for (int j=0; j<3; ++j)
                    r(i,j) = m(i,j);
            return r;
        }
#endif





        struct Wblock {
            ERotMatrix invI;
            Real invTotal;
        };

        struct Vblock {
            EVectorLA linang;
        };

        struct Jblock {
            EVectorLA linang1, linang2;
            int idx1, idx2;
        };



        class Core {
            vector<Jblock> G;
            vector<Vblock> ac;

            vector<Wblock> W;
            vector<Vblock> vh_WFext; // = v/h + W Fext

            vector<Real> low;
            vector<Real> high;
            vector<Real> cfm;

            vector<unsigned> findex;

            vector<Jblock> J;
            //vector<Jblock> Jt;

            vector<Real> b; // the right-hand side
            vector<Real> lambda;

            vector<unsigned> order;

            size_t nBodies;
            size_t nConstraints;

            Real relaxation;
            unsigned maxIterations;


            /*
             * Solves the LCP:
             *     š€ š›Œ = š›
             *         s.t: loįµ¢ ā‰¤ š›Œįµ¢ ā‰¤ hiįµ¢
             *
             * Implementation notes:
             *
             * A is not stored explicitly, as it's a dense matrix.
             * Its factors (š€ = š‰ šŒā»Ā¹ š‰' + CFM) are sparse, so we work
             * on them. In particular, š† = šŒā»Ā¹ š‰' is still sparse.
             *
             * Updating š›Œ needs š€įµ¢įµ¢, so it's pre-computed.
             *
             * The update for š›Œ on iteration n+1 is:
             *
             *     š›æ = šœ”/(š€įµ¢įµ¢ + CFMįµ¢įµ¢) ( š›įµ¢ - (š€įµ¢ + CFMįµ¢) š›Œāæ )
             *     š›Œįµ¢āæāŗĀ¹ = š›Œįµ¢āæ + šœ” š›æ
             *
             * We maintain acāæ = š† š›Œāæ every time we update š›Œ, as it helps computing
             * the value of š›Œ. The update then becomes:
             *
             *     š›æ = šœ”/(š€įµ¢įµ¢ + CFMįµ¢įµ¢) ( š›įµ¢ - š‰įµ¢ acāæ - CFMįµ¢įµ¢ š›Œāæįµ¢ )
             *     š›Œįµ¢āæāŗĀ¹ = š›Œįµ¢āæ + šœ” š›æ
             *     acāæāŗĀ¹ = acāæ + š›æ š†.įµ¢
             *
             * which can be rewritten as:
             *
             *     š›‹įµ¢ = šœ”/(š€įµ¢įµ¢ + CFMįµ¢įµ¢)
             *     š›æ = (š›‹įµ¢ š›įµ¢) - (š›‹' š‰)įµ¢ acāæ - (š›‹' CFM)įµ¢ š›Œāæįµ¢
             *     š›ŒāæāŗĀ¹įµ¢ = š›Œāæįµ¢ + šœ” š›æ
             *     acāæāŗĀ¹ = acāæ + š›æ š†.įµ¢
             *
             * This makes the optimizations obvious:
             *  - (š›‹įµ¢ š›įµ¢), (š›‹' š‰) and (š›‹' CFM) are precomputed outside
             *    the loop, in-place; that's why those arguments are
             *    non-const references.
             *  - š‰ (and š›‹' š‰) is sparse, stored in row-major; so the
             *    product (š›‹' š‰)įµ¢ acāæ is constant-time.
             *  - š† is sparse, and column-major; so adding a multiple of
             *    one of its columns (š›æ š†.įµ¢) to a vector is constant-time.
             */
            inline
            void solveLCP_SOR()
            {
                //G = W * Jt;
                G.resize(J.size());

                // compute ac=G*lambda. we will incrementally maintain ac
                // as we change lambda.
                ac.resize(nBodies);
                for (auto& a : ac)
                    a.linang.setZero();

                for (unsigned i=0; i<G.size(); ++i) {
                    const auto& j = J[i];
                    auto& g = G[i];
                    if (j.idx1 != -1) {
                        g.linang1.head<Dim>() = W[j.idx1].invTotal * j.linang1.head<Dim>();
                        g.linang1.tail<Dim>() = W[j.idx1].invI     * j.linang1.tail<Dim>();
                        ac[j.idx1].linang += lambda[i] * g.linang1;
                    }
                    if (j.idx2 != -1) {
                        g.linang2.head<Dim>() = W[j.idx2].invTotal * j.linang2.head<Dim>();
                        g.linang2.tail<Dim>() = W[j.idx2].invI     * j.linang2.tail<Dim>();
                        ac[j.idx2].linang += lambda[i] * g.linang2;
                    }
                    g.idx1 = j.idx1;
                    g.idx2 = j.idx2;
                }

                // precompute šœ”/(š€įµ¢įµ¢ + CFMįµ¢)
                for (unsigned i=0; i<nConstraints; ++i) {
                    auto& j = J[i];
                    const auto& g = G[i];

                    // const Real d = J.row(i).dot(G.col(i)) + cfm(i);
                    Real d = cfm[i];
                    if (j.idx1 != -1)
                        d += dot(j.linang1, g.linang1);
                    if (j.idx2 != -1)
                        d += dot(j.linang2, g.linang2);

                    const Real kappa = relaxation / d;
                    // Optimization: scale š›įµ¢ now, not inside the loop
                    b[i] *= kappa;
                    // Optimization: scale š‰įµ¢ now, not inside the loop
                    j.linang1 *= kappa;
                    j.linang2 *= kappa;
                    // Optimization: scale CFMįµ¢įµ¢ now, not inside the loop
                    cfm[i] *= kappa;
                }

                // ensure independent constraints come first
                order.resize(nConstraints);
                unsigned front = 0;
                unsigned back = nConstraints;
                for (unsigned i=0; i<nConstraints; ++i) {
                    if (findex[i] == i)
                        order[front++] = i;
                    else
                        order[--back] = i;
                }

                std::random_shuffle(order.begin(), order.begin()+front);
                std::random_shuffle(order.begin()+front, order.end());
                doIterations();
            }




            inline
            void doIterations() noexcept
            {
                for (unsigned iter=0; iter < maxIterations; ++iter) {
                    for (unsigned i=0; i<order.size(); ++i) {
                        const unsigned index = order[i];

                        Real& thisLambda = lambda[index];
                        const Real oldLambda = thisLambda;

                        // Note: b = š›‹įµ¢ š›įµ¢
                        // Note: J = š›‹' š‰
                        // Note: cfm = diag(š›‹' CFM)

                        //const Real Jrow_ac = J.row(index).dot(ac);
                        Real Jrow_ac = 0;
                        const Jblock& jb = J[index];
                        if (jb.idx1 != -1)
                            Jrow_ac += dot(jb.linang1, ac[jb.idx1].linang);

                        if (jb.idx2 != -1)
                            Jrow_ac += dot(jb.linang2, ac[jb.idx2].linang);

                        Real delta = b[index] - Jrow_ac - cfm[index];

                        Real hi, lo;

                        if (findex[index] != index) {
                            hi = Math::abs(high[index] * lambda[findex[index]]);
                            lo = -hi;
                        } else {
                            hi = high[index];
                            lo = low [index];
                        }

                        // compute lambda and clamp it to [lo,hi].
                        // also clamp delta
                        const Real newLambda = oldLambda + delta;

                        if (newLambda < lo) {
                            delta = lo-oldLambda;
                            thisLambda = lo;
                        } else if (newLambda > hi) {
                            delta = hi-oldLambda;
                            thisLambda = hi;
                        } else {
                            thisLambda = newLambda;
                        }

                        // update ac
                        const Jblock& g = G[index];
                        if (g.idx1 != -1)
                            ac[g.idx1].linang += delta * g.linang1;
                        if (g.idx2 != -1)
                            ac[g.idx2].linang += delta * g.linang2;

                    }
                }
            }



        public:

            inline
            void solve(const World& world,
                       vector<Body*>& bodies,
                       vector<Joint*>& joints,
                       Real r,
                       unsigned maxI)
            {
                relaxation = r;
                maxIterations = maxI;

                nBodies = bodies.size();

                W.resize(nBodies);
                vh_WFext.resize(nBodies);

                for (const Body* bd : bodies) {
                    const Matrix3& R = bd->getLocalAxes();
                    const Mass& invMass = bd->getInvMass();
                    const Matrix3 invI = R * (invMass.inertia * R.transposed());
                    ERotMatrix EinvI;
                    for (int i=0; i<3; ++i)
                        for (int j=0; j<3; ++j)
                            EinvI(i,j) = invI(i,j);
#if defined(HAVE_EIGEN) && defined(ALIGN_VECTOR)
                    // rotmatrix is actually 4x4, pad it with zeroes
                    for (int i=0; i<4; ++i) {
                        EinvI(i,3) = 0;
                        EinvI(3,i) = 0;
                    }
#endif

                    const auto idx = bd->idx;
                    W[idx].invTotal = invMass.total;
                    W[idx].invI = EinvI;

                    vh_WFext[idx].linang.head<Dim>() =
                        world.getFPS() * Eize(bd->getLinearVel())
                        +
                        invMass.total * Eize(bd->getTotalForce());

                    vh_WFext[idx].linang.tail<Dim>() =
                        world.getFPS() * Eize(bd->getAngularVel())
                        +
                        EinvI * Eize(bd->getTotalTorque());
                }

                // now build J

                nConstraints = 0;
                for (const Joint* j : joints)
                    nConstraints += j->size();

                b.resize(nConstraints);
                low.resize(nConstraints);
                high.resize(nConstraints);
                cfm.resize(nConstraints);
                findex.resize(nConstraints);
                lambda.resize(nConstraints);
                J.resize(nConstraints);

                size_t Jrow = 0;
                for (const Joint* j : joints) {
                    unsigned conIdx = 0;
                    for (const Constraint& con : *j) {
                        Real c = con.c * world.getFPS();

                        // fill in body1 part
                        if (const Body *b1 = j->getBody1()) {
                            J[Jrow].idx1 = b1->idx;
                            EVectorLA conlinang;
                            conlinang.head<Dim>() = Eize(con.lin1);
                            conlinang.tail<Dim>() = Eize(con.ang1);
                            J[Jrow].linang1 = conlinang;
                            c -= dot(conlinang, vh_WFext[b1->idx].linang);
                        } else {
                            J[Jrow].idx1 = -1;
                        }

                        if (const Body* b2 = j->getBody2()) {
                            J[Jrow].idx2 = b2->idx;
                            EVectorLA conlinang;
                            conlinang.head<Dim>() = Eize(con.lin2);
                            conlinang.tail<Dim>() = Eize(con.ang2);
                            J[Jrow].linang2 = conlinang;
                            c -= dot(conlinang, vh_WFext[b2->idx].linang);
                        } else {
                            J[Jrow].idx2 = -1;
                        }

                        b[Jrow] = c;
                        low[Jrow]  = con.low;
                        high[Jrow] = con.high;
                        cfm[Jrow] = con.cfm;

                        if (con.findex && con.findex <= conIdx)
                            findex[Jrow] = Jrow - con.findex;
                        else
                            findex[Jrow] = Jrow;


                        lambda[Jrow] = con.lambda; // warm-start

                        ++Jrow;
                        ++conIdx;
                    }
                }

                //Jt = J; // we will modify J in place, so we keep a copy

                solveLCP_SOR();

                // write down the lambdas, useful for warm-starting and to retrieve
                // joint feedbacks
                Jrow = 0;
                for (Joint* j : joints) {
                    Body* b1 = j->getBody1();
                    Body* b2 = j->getBody2();
                    for (Constraint& con : *j) {
                        con.lambda = lambda[Jrow++];
                        if (b1) {
                            b1->addForce (con.lambda * con.lin1);
                            b1->addTorque(con.lambda * con.ang1);
                        }
                        if (b2) {
                            b2->addForce (con.lambda * con.lin2);
                            b2->addTorque(con.lambda * con.ang2);
                        }
                    }
                }
/*
                for (Body* bd : bodies) {
                    bd->setLinearVel (bd->getLinearVel()  + world.getStepSize() * Kize(ac[bd->idx].linang.head<Dim>()));
                    bd->setAngularVel(bd->getAngularVel() + world.getStepSize() * Kize(ac[bd->idx].linang.tail<Dim>()));
                }
*/
            }


        }; // class Core

    } // namespace quickstep
} // namespace kode

#endif