Flat-Joint Model Implementation

See this page for the documentation of this contact model.

contactmodelflatjoint.h

  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
#pragma once
// contactmodelflatjoint.h

#include "contactmodel/src/contactmodelmechanical.h"

#ifdef FLATJOINT_LIB
#  define FLATJOINT_EXPORT EXPORT_TAG
#elif defined(NO_MODEL_IMPORT)
#  define FLATJOINT_EXPORT
#else
#  define FLATJOINT_EXPORT IMPORT_TAG
#endif

namespace cmodelsxd {
    using namespace itasca;

    class ContactModelFlatJoint : public ContactModelMechanical {
    public:
        enum PropertyKeys { 
              kwFjNr=1
            , kwFjElem
            , kwFjKn
            , kwFjKs                            
            , kwFjFric   
            , kwFjEmod
            , kwFjKRatio                            
            , kwFjRmul
            , kwFjRadius
            , kwFjGap0
            , kwFjTen 
            , kwFjCoh
            , kwFjFa 
            , kwFjF
            , kwFjM
            , kwFjState
            , kwFjSlip
            , kwFjMType
            , kwFjA
            , kwFjEgap
            , kwFjGap
            , kwFjNstr
            , kwFjSstr
            , kwFjSs
#ifdef THREED
            , kwFjNa
#endif
            , kwFjRelBr
            , kwFjCen
            , kwFjTrack
            , kwUserArea
            , kwFjCohRes
            , kwFjResMode
        };
         
        FLATJOINT_EXPORT ContactModelFlatJoint();
        FLATJOINT_EXPORT virtual ~ContactModelFlatJoint();
        virtual void                copy(const ContactModel *c) override;
        virtual void                archive(ArchiveStream &); 
        virtual QString  getName() const { return "flatjoint"; }
        virtual void     setIndex(int i) { index_=i;}
        virtual int      getIndex() const {return index_;}
        virtual QString  getProperties() const { return "fj_nr"
                                                        ",fj_elem"
                                                        ",fj_kn"
                                                        ",fj_ks"
                                                        ",fj_fric"
                                                        ",fj_emod"
                                                        ",fj_kratio"
                                                        ",fj_rmul"
                                                        ",fj_radius"
                                                        ",fj_gap0"
                                                        ",fj_ten"
                                                        ",fj_coh"
                                                        ",fj_fa"
                                                        ",fj_force"
                                                        ",fj_moment"
                                                        ",fj_state"
                                                        ",fj_slip"
                                                        ",fj_mtype"
                                                        ",fj_area"
                                                        ",fj_egap"
                                                        ",fj_gap"
                                                        ",fj_sigma"
                                                        ",fj_tau"
                                                        ",fj_shear"
#ifdef THREED
                                                        ",fj_nal"
#endif
                                                        ",fj_relbr"
                                                        ",fj_cen"
                                                        ",fj_track"
                                                        ",user_area"
                                                        ",fj_cohres"
                                                        ",fj_resmode"
                                                        ;}

        enum EnergyKeys { kwEStrain=1,kwESlip};
        virtual QString  getEnergies() const { return "energy-strain,energy-slip";}
        virtual double   getEnergy(uint i) const;  // Base 1
        virtual bool     getEnergyAccumulate(uint i) const; // Base 1
        virtual void     setEnergy(uint i,const double &d); // Base 1
        virtual void     activateEnergy() { if (energies_) return; energies_ = NEWC(Energies());}
        virtual bool     getEnergyActivated() const {return (energies_ !=0);}

        enum FishCallEvents {fActivated=0,fBondBreak,fBroken,fSlipChange};
        virtual QString  getFishCallEvents() const { return "contact_activated,bond_break,broken,all_slip_change"; }
        virtual QVariant getProperty(uint i,const IContact *) const;
        virtual bool     getPropertyGlobal(uint i) const;
        virtual bool     setProperty(uint i,const QVariant &v,IContact *);
        virtual bool     getPropertyReadOnly(uint i) const;

        virtual bool     supportsInheritance(uint ) const { return false; }

        enum MethodKeys { kwBond=1, kwUnbond, KwDeformability, KwUpdateGeom, kwArea, kwInitialize};

        virtual QString  getMethods() const { return "bond"
                                                     ",unbond"
                                                     ",deformability"
                                                     ",update_geometry"
                                                     ",area"
                                                     ",initialize"
                                            ;}
        
        virtual QString  getMethodArguments(uint i) const; 
        
        virtual bool     setMethod(uint i,const QVector<QVariant> &vl,IContact *con=0); // Base 1 - returns true if timestep contributions need to be updated

        virtual uint     getMinorVersion() const;

        virtual bool    validate(ContactModelMechanicalState *state,const double &timestep);
        virtual bool    endPropertyUpdated(const QString &,const IContactMechanical *) { return false; }
        virtual bool    forceDisplacementLaw(ContactModelMechanicalState *state,const double &timestep);
        virtual bool    thermalCoupling(ContactModelMechanicalState*, ContactModelThermalState*, IContactThermal*, const double&);
        virtual DVect2  getEffectiveTranslationalStiffness() const { return effectiveTranslationalStiffness();}
        virtual DAVect  getEffectiveRotationalStiffness() const { return effectiveRotationalStiffness(); }

        virtual ContactModelFlatJoint *clone() const override { return NEWC(ContactModelFlatJoint()); }
        virtual double              getActivityDistance() const {return 0.0;}
        virtual bool                isOKToDelete() const { return !isBonded(); }
        virtual void                resetForcesAndMoments() { fj_f(DVect(0.0)); fj_m(DAVect(0.0)); for (int i=0; i<f_.size(); ++i) f_[i] = DVect(0.0); }
        virtual void                setForce(const DVect &v,IContact *);
        virtual void                setArea(const double &d) { userArea_ = d; }
        virtual double              getArea() const { return userArea_; }

        virtual bool    checkActivity(const double &inGap);

        //virtual bool     isSliding() const { return fj_s_; }
        virtual bool    isBonded() const { FOR(it,bmode_) if ((*it) == 3) return true; return false; }
        virtual void    unbond() { FOR(it,bmode_) *it = 0; }
        int             fj_nr() const               {return fj_nr_;}
        void            fj_nr(int d)                {       fj_nr_= d;}
#ifdef THREED
        int             fj_n() const                { return fj_na_ * fj_nr_; }
        int             fj_na() const               {return fj_na_;}
        void            fj_na(int d)                {       fj_na_= d;}
#else
        int             fj_n() const                { return fj_nr_; }
#endif
        int             fj_elem() const             {return fj_elem_;}
        void            fj_elem(int d)              {       fj_elem_= d;}
        const double &  fj_kn() const               {return fj_kn_;}
        void            fj_kn(const double &d)      {       fj_kn_ = d;}
        const double &  fj_ks() const               {return fj_ks_;}
        void            fj_ks(const double &d)      {       fj_ks_ = d;}
        const double &  fj_fric() const             {return fj_fric_;}
        void            fj_fric(const double &d)    {       fj_fric_ = d;}
        const double &  fj_rmul() const             {return fj_rmul_;}
        void            fj_rmul(const double &d)    {       fj_rmul_ = d;}
        const double &  fj_gap0() const             {return fj_gap0_;}
        void            fj_gap0(const double &d)    {       fj_gap0_ = d;}
        const double &  fj_ten() const              {return fj_ten_;}
        void            fj_ten(const double &d)     {       fj_ten_ = d;}
        const double &  fj_coh() const              {return fj_coh_;}
        void            fj_coh(const double &d)     {       fj_coh_ = d;}
        const double &  fj_cohres() const           {return fj_cohres_;}
        void            fj_cohres(const double &d)  {       fj_cohres_ = d;}
        const double &  fj_fa() const               {return fj_fa_;}
        void            fj_fa(const double &d)      {       fj_fa_ = d;}
        const DVect &   fj_f() const                {return fj_f_;}
        void            fj_f(const DVect &f)        {       fj_f_=f;}
        const DAVect &  fj_m() const                {return fj_m_;}
        void            fj_m(const DAVect &f)       {       fj_m_=f;}
        const DAVect &  fj_m_set() const            {return fj_m_set_;}
        void            fj_m_set(const DAVect &f)   {       fj_m_set_=f;}
        const double &  rmin() const                {return rmin_;}
        void            rmin(const double &d)       {       rmin_ = d;}
        const double &  rbar() const                {return rbar_;}
        void            rbar(const double &d)       {       rbar_ = d;}
        const int &     fj_resmode() const          {return fj_resmode_;}
        void            fj_resmode(const int &i)    {       fj_resmode_ = i;}
        const double &  atot() const                {return atot_;}
        void            atot(const double &d)       {       atot_ = d;}
        const bool      propsFixed() const          {return propsFixed_; }
        void            propsFixed(bool d)          {       propsFixed_ = d;}
        int             mType() const               {return mType_; }
        void            mType(int d)                {       mType_ = d;}
        const DVect &   gap() const                 {return gap_; }
        void            gap(const DVect &d)         {       gap_ = d;}
        const double &  theta() const               {return theta_; }
        void            theta(const double & d)     {       theta_ = d;}
#ifdef THREED
        const double &  thetaM() const              {return thetaM_; }
        void            thetaM(const double & d)    {       thetaM_ = d;}
#else
        double thetaM() const                       {return 0.0;}
#endif



        bool    hasEnergies() const {return energies_ ? true:false;}
        double  estrain() const {return hasEnergies() ? energies_->estrain_: 0.0;}
        void    estrain(const double &d) { if(!hasEnergies()) return; energies_->estrain_=d;}
        double  eslip() const {return hasEnergies() ? energies_->eslip_: 0.0;}
        void    eslip(const double &d) { if(!hasEnergies()) return; energies_->eslip_=d;}

        uint inheritanceField() const {return inheritanceField_;}
        void inheritanceField(uint i) {inheritanceField_ = i;}

        const DVect2 & effectiveTranslationalStiffness()  const             {return effectiveTranslationalStiffness_;}
        void           effectiveTranslationalStiffness(const DVect2 &v )    {effectiveTranslationalStiffness_=v;}
        const DAVect & effectiveRotationalStiffness()  const                {return effectiveRotationalStiffness_;}
        void           effectiveRotationalStiffness(const DAVect &v )       {effectiveRotationalStiffness_=v;}

        // For contact specific plotting
        virtual void getSphereList(const IContact *con,std::vector<DVect> *pos,std::vector<double> *rad,std::vector<double> *val);
#ifdef THREED
        virtual void getDiskList(const IContact *con,std::vector<DVect> *pos,std::vector<DVect> *normal,std::vector<double> *radius,std::vector<double> *val);
#endif
        virtual void getCylinderList(const IContact *con,std::vector<DVect> *bot,std::vector<DVect> *top,std::vector<double> *radlow,std::vector<double> *radhi,std::vector<double> *val);

        /// Return the total force that the contact model holds.
        virtual DVect    getForce(const IContactMechanical *) const;

        /// Return the total moment on 1 that the contact model holds
        virtual DAVect   getMomentOn1(const IContactMechanical *) const;

        /// Return the total moment on 1 that the contact model holds
        virtual DAVect   getMomentOn2(const IContactMechanical *) const;


    private:
        static int index_;

        struct Energies {
            Energies() : estrain_(0.0), eslip_(0.0) {}
            double estrain_;  // elastic energy stored in contact 
            double eslip_;    // work dissipated by friction 
        };

        void   updateEffectiveStiffness(ContactModelMechanicalState *state);

        // inheritance fields
        quint32 inheritanceField_;

        int                     fj_nr_;             // radial number of elements >= 1 (total in 2D)
#ifdef THREED
        int                     fj_na_;             // circumferential number of elements >= 3
#endif
        int                     fj_elem_;           // Element to be queried
        double                  fj_kn_;             // normal stiffness
        double                  fj_ks_;             // shear stiffness
        double                  fj_fric_;           // Coulomb friction coefficient
        double                  fj_rmul_;           // Radius multiplier
        double                  fj_gap0_;           // Initial gap
        double                  fj_ten_;            // Tensile strength 
        double                  fj_coh_;            // Cohesive strength
        double                  fj_cohres_;         // Residual cohesive strength
        double                  fj_fa_;             // Friction angle 
        DVect                   fj_f_;              // Force carried in the model
        DAVect                  fj_m_;              // Moment carried in the model
        DAVect                  fj_m_set_;          // When initializing forces then need an extra moment term
        // Area related quantities
        double                  rmin_;              // min(Ra,Rb) where Ra & Rb are particle radii
        double                  rbar_;              // flat-joint radius [m]
        double                  atot_;              // flat-joint area [m^2]
        std::vector<double>     a_;                 // cross-sectional area of elem[fj_elem-1] [m^2]
#ifdef THREED
        std::vector<DVect2>     rBarl_;             // centroid relative position of elem[fj_elem-1] [m] (3D)
#else
        std::vector<double>     rBarl_;             // centroid relative position of elem[fj_elem-1] [m] (2D)
#endif
        int                     fj_resmode_;         // Residual mode
        void setAreaQuantities();                   // Set Rbar, Atot and A[]
        DVect getRelElemPos(const IContact*,int ) const;   // Return the relative location of element i
        void setRelElemPos(const IContact*,int ,const DVect &);   // Set the relative location of element i

        bool                    propsFixed_;        // {Rmul, N, G, bstate, mType} fixed, cannot reset
        int                     mType_;             // initial microstructural type
        int getmType() const;                       // {1,2,3,4}={bonded, gapped, slit, other}
        
        std::vector<int>        bmode_;             // bond mode - 0 unbonded, 1 failed in tension, 2 failed in shear, 3 bonded
        std::vector<bool>       smode_;             // slip mode
        bool Bonded(int e) const { return bmode_[e-1] == 3 ? true : false; }

        // Set bstate and bmode (can only bond if fj_gap0_==0.0)
        void bondElem(int iSeg,bool bBond);
        // Set bstate & bmode 
        void breakBond(int iSeg,int fmode,ContactModelMechanicalState *state);
        void slipChange(int iSeg,bool smode,ContactModelMechanicalState *state);

        // For use in 2D only!
        double tauC(const double &dSig,bool bBonded) const; // shear strength (positive) [N/m^2]

        // INTERFACE RESPONSE QUANTITIES:
        DVect                   gap_;               // total relative displacement [m]
        double                  theta_;             // total relative rotation [rad]
#ifdef THREED
        double                  thetaM_;            // total relative rotation [rad]
        double thbMag() const   { return sqrt(theta_*theta_ + thetaM_*thetaM_); }
        // unit-vector xi of middle surface system xi-eta
        // (If both thb_l and thb_m are zero, then xi is undefined
        // and returns zero for both components.)
        double xi(int comp /* component (l,m) = (1,2) */) const;
#endif
        std::vector<double>     egap_;          // gap at centroid of elem[fj_elem-1] [N]
        std::vector<DVect>      f_;             // force on elem[fj_elem-1] [N]

        void   initVectors();                   // Resize and zero all vector types based on current value of N
#ifdef TWOD
        double gap(const double &x) const;      // Gap (g>0 is open) along the interface, x in [0, 2*Rbar]
#else
        double gap(const double &rl,const double &rm) const; // Gap (g>0 is open) gap at relative position (l,m) [m]
        double sigBar( int e /* element, e = 1,2,...,Nel */ ) const; // normal stress at centroid of elem[eN-1] [N/m^2]
        double tauBar( int e /* element, e = 1,2,...,Nel */ ) const; // shear  stress at centroid of elem[eN-1] [N/m^2]
#endif
        double computeStrainEnergy(int e /* element, e = 1,2,...,Nel */) const; // strain energy in elem[eN-1]
        // For use in 2D only! Segment normal stress
        double computeSig(const double &g0,   /* gap at left end  */
                          const double &g1,   /* gap at right end */
                          const double &rbar, /* length is 2*rbar */
                          const double &dA,   /* area             */
                          bool bBonded        /* bond state       */
                          ) const;
        // For use in 2D only! Segment moment
        double computeM(const double &g0,   /* gap at left end  */ 
                        const double &g1,   /* gap at right end */ 
                        const double &rbar, /* length is 2*rbar */
                        bool bBonded        /* bond state       */
                        ) const;
        // For use in 2D only! getCase used by ComputeSig and ComputeM
        int getCase(const double &g0, /* gap at left end  */ 
                 const double &g1  /* gap at right end */ 
                 ) const;
        // Segment elastic shear-displacement increment, which is portion of
        // increment that occurs while gap is negative.
        double delUse(const double &gapStart, /* gap at start of FDlaw  */
                      const double &gapEnd,   /* gap at end of FDlaw    */
                      bool bBonded,           /* bond state             */
                      const double &delUs     /* shear displ. increment */
                     ) const;
        double      userArea_;   // Area as specified by the user 
        Energies *   energies_;    // energies

        DVect2  effectiveTranslationalStiffness_;
        DAVect  effectiveRotationalStiffness_;

        struct orientProps {
            orientProps() : origNormal_(DVect(0.0)) {}
            Quat    orient1_;
            Quat    orient2_;
            DVect   origNormal_;
        };

        orientProps *orientProps_;
    };
} // namespace itascaxd


// EoF

Top

contactmodelflatjoint.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
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
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
// contactmodelflatjoint.cpp
#include "contactmodelflatjoint.h"

#include "../version.txt"
#include "fish/src/parameter.h"
#include "utility/src/tptr.h"
#include "shared/src/mathutil.h"
#include "base/src/basetoqt.h"
#include "contactmodel/src/contactmodelthermal.h"

#include "kernel/interface/iprogram.h"
#include "module/interface/icontact.h"
#include "module/interface/icontactmechanical.h"
#include "module/interface/icontactthermal.h"
#include "module/interface/ifishcalllist.h"
#include "module/interface/ipiece.h"
#include "module/interface/ipiecemechanical.h"

#ifdef FLATJOINT_LIB
#ifdef _WIN32
  int __stdcall DllMain(void *,unsigned, void *)
  {
    return 1;
  }
#endif

  extern "C" EXPORT_TAG const char *getName() 
  {
#if DIM==3
    return "contactmodelmechanical3dflatjoint";
#else
    return "contactmodelmechanical2dflatjoint";
#endif
  }

  extern "C" EXPORT_TAG unsigned getMajorVersion()
  {
    return MAJOR_VERSION;
  }

  extern "C" EXPORT_TAG unsigned getMinorVersion()
  {
    return MINOR_VERSION;
  }

  extern "C" EXPORT_TAG void *createInstance() 
  {
    cmodelsxd::ContactModelFlatJoint *m = NEWC(cmodelsxd::ContactModelFlatJoint());
    return (void *)m;
  }
#endif // FLATJOINT_LIB

namespace cmodelsxd {
    static const quint32 fjKnMask      = 0x00002; // Base 1!
    static const quint32 fjKsMask      = 0x00004;
    static const quint32 fjFricMask    = 0x00008;

    using namespace itasca;

    int ContactModelFlatJoint::index_ = -1;
    UInt ContactModelFlatJoint::getMinorVersion() const { return MINOR_VERSION;}

    ContactModelFlatJoint::ContactModelFlatJoint() : inheritanceField_(fjKnMask|fjKsMask|fjFricMask) 
                                            , fj_nr_(2)
#ifdef THREED
                                            , fj_na_(4)
#endif
                                            , fj_elem_(1)        
                                            , fj_kn_(0.0)         
                                            , fj_ks_(0.0)         
                                            , fj_fric_(0.0)       
                                            , fj_rmul_(1.0)       
                                            , fj_gap0_(0.0)        
                                            , fj_ten_(0.0)        
                                            , fj_coh_(0.0)        
                                            , fj_cohres_(0.0)        
                                            , fj_fa_(0.0)         
                                            , fj_f_(0.0)
                                            , fj_m_(0.0)
                                            , fj_m_set_(0.0)
                                            , rmin_(1.0)
                                            , rbar_(0.0)
                                            , atot_(0.0)
                                            , a_(2)
                                            , rBarl_(2)
                                            , fj_resmode_(0)
                                            , propsFixed_(false)
                                            , mType_(3)
                                            , bmode_(2)
                                            , smode_(2)
                                            , gap_(0.0)
                                            , theta_(0.0)
#ifdef THREED
                                            , thetaM_(0.0)
#endif
                                            , egap_(2)
                                            , f_(2)
                                            , userArea_(0)
                                            , energies_(0)
                                            , effectiveTranslationalStiffness_(DVect2(0.0)) 
                                            , effectiveRotationalStiffness_(DAVect(0.0))
                                            , orientProps_(0)
    {
        initVectors();
        setAreaQuantities();
        //setFromParent(ContactModelMechanicalList::instance()->find(getName()));
    }

    ContactModelFlatJoint::~ContactModelFlatJoint() {
        if (orientProps_)
            delete orientProps_;
        if (energies_)
            delete energies_;
    }

    void ContactModelFlatJoint::archive(ArchiveStream &stream) {
        stream & fj_nr_;
#ifdef THREED
        stream & fj_na_;
#endif
        stream & fj_elem_;
        stream & fj_kn_;
        stream & fj_ks_;
        stream & fj_fric_;
        stream & fj_rmul_;
        stream & fj_gap0_;
        stream & fj_ten_;
        stream & fj_coh_;
        stream & fj_fa_; 
        stream & fj_f_;  
        stream & fj_m_;  
        stream & rmin_;
        stream & rbar_;
        stream & atot_;
        stream & a_; 
        stream & rBarl_;
        stream & propsFixed_;
        stream & mType_;     
        stream & bmode_;     
        stream & smode_;
        stream & gap_;
        stream & theta_;
#ifdef THREED
        stream & thetaM_;
#endif
        stream & egap_;
        stream & f_;

        if (stream.getArchiveState()==ArchiveStream::Save) {
            bool b = false;
            if (orientProps_) {
                b = true;
                stream & b;
                stream & orientProps_->orient1_;
                stream & orientProps_->orient2_;
                stream & orientProps_->origNormal_;
            } else
                stream & b;
            b = false;
            if (energies_) {
                b = true;
                stream & b;
                stream & energies_->estrain_;
                stream & energies_->eslip_;
            } else
                stream & b;
        } else {
            bool b(false);
            stream & b;
            if (b) {
                if (!orientProps_)
                    orientProps_ = NEWC(orientProps());
                stream & orientProps_->orient1_;
                stream & orientProps_->orient2_;
                stream & orientProps_->origNormal_;
            }
            stream & b;
            if (b) {
                if (!energies_)
                    energies_ = NEWC(Energies());
                stream & energies_->estrain_;
                stream & energies_->eslip_;
            }
        }

        stream & inheritanceField_;
        stream & effectiveTranslationalStiffness_;
        stream & effectiveRotationalStiffness_;

        if (stream.getArchiveState()==ArchiveStream::Save || stream.getRestoreVersion() > 1)
            stream & userArea_;

        if (stream.getArchiveState()==ArchiveStream::Save || stream.getRestoreVersion() > 2)
            stream & fj_m_set_;

        if (stream.getArchiveState()==ArchiveStream::Save || stream.getRestoreVersion() > 3) {
            stream & fj_cohres_;
            stream & fj_resmode_;
        }
    }

    void ContactModelFlatJoint::copy(const ContactModel *cm) {
        ContactModelMechanical::copy(cm);
        const ContactModelFlatJoint *in = dynamic_cast<const ContactModelFlatJoint*>(cm);
        if (!in) throw std::runtime_error("Internal error: contact model dynamic cast failed.");
        fj_nr(in->fj_nr());
#ifdef THREED
        fj_na(in->fj_na());
#endif
        fj_elem(in->fj_elem());
        fj_kn(in->fj_kn());
        fj_ks(in->fj_ks());
        fj_fric(in->fj_fric());
        fj_rmul(in->fj_rmul());
        fj_gap0(in->fj_gap0());
        fj_ten(in->fj_ten());
        fj_coh(in->fj_coh());
        fj_cohres(in->fj_cohres());
        fj_fa(in->fj_fa());
        fj_f(in->fj_f());
        fj_m(in->fj_m());
        fj_m_set(in->fj_m_set());
        rmin(in->rmin());
        rbar(in->rbar());
        fj_resmode(in->fj_resmode());
        atot(in->atot());
        a_ = in->a_;
        rBarl_ = in->rBarl_;
        propsFixed(in->propsFixed());
        mType(in->mType());
        bmode_ = in->bmode_;
        smode_ = in->smode_;
        gap(in->gap());
        theta(in->theta());
#ifdef THREED
        thetaM(in->thetaM());
#endif
        egap_ = in->egap_;
        f_ = in->f_;
        if (in->orientProps_) {
            if (!orientProps_)
                orientProps_ = NEWC(orientProps());
            orientProps_->orient1_ = in->orientProps_->orient1_;
            orientProps_->orient2_ = in->orientProps_->orient2_;
            orientProps_->origNormal_ =  in->orientProps_->origNormal_;
        }
        if (in->hasEnergies()) {
            if (!energies_)
                energies_ = NEWC(Energies());
            estrain(in->estrain());
            eslip(in->eslip());
        }
        userArea_ = in->userArea_;
        inheritanceField(in->inheritanceField());
        effectiveTranslationalStiffness(in->effectiveTranslationalStiffness());
        effectiveRotationalStiffness(in->effectiveRotationalStiffness());
    }


    QVariant ContactModelFlatJoint::getProperty(uint i,const IContact *con) const {
        QVariant var;
        switch (i) {
        case kwFjNr     :   return fj_nr();
        case kwFjElem   :   return fj_elem();
        case kwFjKn     :   return fj_kn();
        case kwFjKs     :   return fj_ks();
        case kwFjFric   :   return fj_fric();
        case kwFjEmod   :  {
                                const IContactMechanical *c(convert_getcast<IContactMechanical>(con));
                                if (c ==nullptr) return 0.0;
                                double rsum(0.0);
                                if (c->getEnd1Curvature().y())
                                    rsum += 1.0/c->getEnd1Curvature().y();
                                if (c->getEnd2Curvature().y())
                                    rsum += 1.0/c->getEnd2Curvature().y();
                                if (userArea_) {
#ifdef THREED
                                    rsum = std::sqrt(userArea_ / dPi);
#else
                                    rsum = userArea_ / 2.0;
#endif        
                                    rsum += rsum;
                                }
                                return (fj_kn_ * rsum);
                           }
        case kwFjKRatio :  return (fj_ks_ == 0.0 ) ? 0.0 : (fj_kn_/fj_ks_);
        case kwFjRmul   :   return fj_rmul();
        case kwFjRadius :   return rbar();
        case kwFjGap0   :   return fj_gap0();
        case kwFjTen    :   return fj_ten();
        case kwFjCoh    :   return fj_coh();
        case kwFjFa     :   return fj_fa();
        case kwFjF      :   var.setValue(fj_f()); return var;
        case kwFjM      :   var.setValue(fj_m()); return var;
        case kwFjState  :   return bmode_[fj_elem()-1];
        case kwFjSlip   :   return smode_[fj_elem()-1];
        case kwFjMType  :   return getmType();
        case kwFjA      :   return a_[fj_elem()-1];
        case kwFjEgap   :   return egap_[fj_elem()-1];
        case kwFjGap    :   return gap().x();
        case kwFjNstr   :   return -f_[fj_elem()-1].x() / a_[fj_elem()-1];
        case kwFjSstr   :   return f_[fj_elem()-1].y() / a_[fj_elem()-1];
        case kwFjSs     :   return tauC((-f_[fj_elem()-1].x() / a_[fj_elem()-1]),(bmode_[fj_elem()-1]==3));
        case kwFjRelBr  :   var.setValue(DVect2(theta(),thetaM())); return var;
        case kwFjCen    :   var.setValue(getRelElemPos(con,fj_elem()-1)); return var;
#ifdef THREED
        case kwFjNa     :   return fj_na();
#endif
        case kwFjTrack  :   var.setValue(orientProps_ ? true : false); return var;
        case kwUserArea :   return userArea_;
        case kwFjCohRes :   return fj_cohres();
        case kwFjResMode:   return fj_resmode();
        }
        assert(0);
        return QVariant();
    }

    bool ContactModelFlatJoint::getPropertyGlobal(uint i) const {
        switch (i) {
        case kwFjF:   
            return false;
        }
        return true;
    }

    bool ContactModelFlatJoint::setProperty(uint i,const QVariant &v,IContact *c) {
        bool ok(true);
        switch (i) {
        case kwFjNr: {
                if (!propsFixed()) {
                    int val(v.toInt(&ok));
                    if (!ok || val < 1)
                        throw Exception("fj_nr must be an integer greater than 0.");
                    fj_nr(val);
                    if (fj_elem() > fj_n())
                        fj_elem(fj_n());
                    initVectors();
                    setAreaQuantities();
                } else
                    throw Exception("fj_nr cannot be modified.");
                return true;
            }

        case kwFjElem: {  
               int val(v.toInt(&ok));
               if (!ok || val < 1 || val > fj_n())
                   throw Exception("fj_elem must be an integer between 1 and %1.",fj_n());
               fj_elem(val);
               return false;
           }
        case kwFjKn: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_kn must be a positive double.");
                fj_kn(val);
                return true;
            }
        case kwFjKs: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_ks must be a positive double.");
                fj_ks(val);  
                return true;
            }
        case kwFjFric: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_fric must be a positive double.");
                fj_fric(val);  
                return false;
            }
        case kwFjRmul: {
                if (!propsFixed()) {
                    double val(v.toDouble(&ok));
                    if (!ok || val<0.01)
                        throw Exception("fj_rmul must be a double greater than or equal to 0.01.");
                    fj_rmul(val);
                    setAreaQuantities();
                    return true;
                } else
                    throw Exception("fj_rmul cannot be modified.");

                return false;
            }
        case kwFjGap0: {
                if (!propsFixed()) {
                    double val(v.toDouble(&ok));
                    if (!ok || val<0.0)
                        throw Exception("fj_gap0 must be a positive double.");
                    fj_gap0(val);
                    if (fj_gap0() > 0.0) {
                        for(int i=1; i<=fj_n(); ++i) 
                            bondElem(i,false);
                        // surfaces are parallel w/ gap G
                        DVect temp(0.0);
                        temp.rx() = fj_gap0();
                        gap(temp);
                        theta(0.0);
                    }
                } else
                    throw Exception("fj_gap0 cannot be modified.");
                return true;
            }
        case kwFjTen: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_ten must be a positive double.");
                fj_ten(val); 
                return false;
            }
        case kwFjFa: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_fa must be a positive double.");
                fj_fa(val); 
                return false;
            }
        case kwFjCoh: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_coh must be a positive double.");
                fj_coh(val); 
                return false;
            }
        case kwFjA: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_area must be a positive double.");
                a_[fj_elem()-1] = val; 
                return false;
            }
        case kwFjNstr: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_sigma must be a positive double.");
                f_[fj_elem()-1].rx() = -val * a_[fj_elem()-1];
                return false;
            }
        case kwFjSstr: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_tau must be a positive double.");
                f_[fj_elem()-1].ry() = val * a_[fj_elem()-1];
                return false;
            }
#ifdef THREED
        case kwFjNa: {
                if (!propsFixed()) {
                    int val(v.toInt(&ok));
                    if (!ok || val < 1)
                        throw Exception("fj_na must be an integer greater than 0.");
                    fj_na(val);
                    if (fj_elem() > fj_n())
                        fj_elem(fj_n());
                    initVectors();
                    setAreaQuantities();
                } else
                    throw Exception("fj_na cannot be modified.");
                return true;
            }
#endif
        case kwFjCen: {
                if (!v.canConvert<DVect>())
                    throw Exception("fj_cen cannot be modified.");
                DVect val(v.value<DVect>());
                int el = fj_elem()-1;
                setRelElemPos(c,el,val);
                return false;
            }
        case kwFjTrack: {
                if (!v.canConvert<bool>())
                    throw Exception("fj_track must be a boolean.");
                bool b = v.toBool();
                if (b) {
                    if (!orientProps_)
                        orientProps_ = NEWC(orientProps());
                } else {
                    if (orientProps_) {
                        delete orientProps_;
                        orientProps_ = 0;
                    }
                }
                return true;
            }
        case kwUserArea: {
                if (!v.canConvert<double>())
                    throw Exception("user_area must be a double.");
                double val(v.toDouble());
                if (val < 0.0)
                    throw Exception("Negative user_area not allowed.");
                userArea_ = val;
                propsFixed_ = false;
                return true;
            }
        case kwFjCohRes: {
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("fj_cohres must be a positive double.");
                fj_cohres(val); 
                return false;
            }
        case kwFjResMode: {
                int val(v.toInt(&ok));
                if (!ok || (val != 0 && val != 1))
                    throw Exception("fj_resmode must be 0 or 1.");
                fj_resmode(val); 
                return false;
            }
        }
        return false;
    }

    bool ContactModelFlatJoint::getPropertyReadOnly(uint i) const {
        switch (i) {
        case kwFjF:
        case kwFjM:
        case kwFjGap:
        case kwFjRelBr:
        case kwFjState:
        case kwFjSlip:
        case kwFjEgap:
        case kwFjNstr:
        case kwFjSstr:
        case kwFjSs:
        case kwFjRadius:
            return true;
        default:
            break;
        }
        return false;
    }

    QString  ContactModelFlatJoint::getMethodArguments(uint i) const {
        switch (i) {
        case kwBond:
        case kwUnbond:
            return "gap,element";
        case KwDeformability:
            return "emod,kratio";
        case kwInitialize:
            return "force,moment";
        }
        return QString();
    }

    bool ContactModelFlatJoint::setMethod(uint i,const QVector<QVariant> &vl,IContact *con) {
        IContactMechanical *c(convert_getcast<IContactMechanical>(con));
        bool bond(false);
        switch (i) {
        case kwBond:
            bond = true;
        case kwUnbond: {
                int seg(0);
                double mingap = -1.0 * limits<double>::max();
                double maxgap = 0;
                if (vl.size()==2) {
                    // The first is the gap
                    QVariant arg = vl.at(0);
                    if (!arg.isNull()) {
                        if (arg.canConvert<Double>()) 
                            maxgap = vl.at(0).toDouble();
                        else if (arg.canConvert<DVect2>()) {
                            DVect2 value = vl.at(0).value<DVect2>();
                            mingap = value.minComp();
                            maxgap = value.maxComp();
                        } else
                            throw Exception("Argument %1 not recognized in method %2 in contact model %3.",vl.at(0),bond ? "bond":"unbond",getName());
                    }
                    arg = vl.at(1);
                    if (!arg.isNull()) {
                        seg = vl.at(1).toUInt();
                        if (seg < 1)
                            throw Exception("Element indices start at 1 in method %1 in contact model %2.",bond ? "bond":"unbond",getName());
                        if (seg > fj_n())
                            throw Exception("Element index %1 exceeds segments number (%2) in method %3 in contact model %4.",seg,fj_n(),bond ? "bond":"unbond",getName());
                    }
                }
                double gap = c->getGap(); 
                if (gap >= mingap && gap <= maxgap) {
                    if (!seg) { 
                        for(int iSeg=1; iSeg<=fj_n(); ++iSeg) 
                            bondElem(iSeg,bond);
                    } else {
                        bondElem(seg,bond);
                    }
                    // If have installed bonds and tracking is enabled then set the contact normal appropriately
                    if (orientProps_) {
                        orientProps_->orient1_ = Quat::identity();
                        orientProps_->orient2_ = Quat::identity();
                        orientProps_->origNormal_ = toVect(con->getNormal());
                    }
                }
                return true;
             }
        case KwDeformability:
            {
                double emod;
                double krat;
                if (vl.at(0).isNull()) 
                    throw Exception("Argument emod must be specified with method deformability in contact model %1.",getName());
                emod = vl.at(0).toDouble();
                if (emod<0.0)
                    throw Exception("Negative emod not allowed in contact model %1.",getName());
                if (vl.at(1).isNull()) 
                    throw Exception("Argument kratio must be specified with method deformability in contact model %1.",getName());
                krat = vl.at(1).toDouble();
                if (krat<0.0)
                    throw Exception("Negative stiffness ratio not allowed in contact model %1.",getName());
                double rsum(0.0);
                if (c->getEnd1Curvature().y())
                    rsum += 1.0/c->getEnd1Curvature().y();
                if (c->getEnd2Curvature().y())
                    rsum += 1.0/c->getEnd2Curvature().y();
                if (userArea_) {
#ifdef THREED
                    rsum = std::sqrt(userArea_ / dPi);
#else
                    rsum = userArea_ / 2.0;
#endif        
                    rsum += rsum;
                }
                fj_kn_ = emod / rsum;
                fj_ks_ = (krat == 0.0) ? 0.0 : fj_kn_ / krat;
                return true;
            }
        case KwUpdateGeom: {
                // go through and update the total area (atot) and the 
                // radius rbar
                double at = 0.0;
                for (int i=1; i<=fj_n(); ++i)
                    at += a_[i-1];
                atot(at);
                //get the equivalent radius
#ifdef THREED
                rbar(sqrt(at/dPi));
#else   
                rbar(at/2.0);
#endif
                return true;
            }
        case kwArea: {
                if (!userArea_) {
                    double rsq(1./std::max(c->getEnd1Curvature().y(),c->getEnd2Curvature().y()));
#ifdef THREED
                    userArea_ = rsq * rsq * dPi;
#else
                    userArea_ = rsq * 2.0;
#endif                            
                }
                return true;
            }
        case kwInitialize: {
                DVect force;
                DAVect moment;
                if (vl.at(0).isNull()) 
                    throw Exception("Argument force must be specified with method initialize in contact model %1.",getName());
                force = vl.at(0).value<DVect>();
                if (vl.at(1).isNull()) 
                    throw Exception("Argument moment must be specified with method initialize in contact model %1.",getName());
#ifdef THREED
                moment = vl.at(1).value<DVect>();
#else
                moment.rz() = vl.at(1).toDouble();
#endif
                // Set the gap accordingly to get the correct force
                setForce(force,con);
                fj_m_set(moment);
                return true;
            }
        }
        return false;
    }

    double ContactModelFlatJoint::getEnergy(uint i) const {
        double ret(0.0);
        if (!energies_)
            return ret;
        switch (i) {
        case kwEStrain:  return energies_->estrain_;
        case kwESlip:    return energies_->eslip_;
        }
        assert(0);
        return ret;
    }

    bool ContactModelFlatJoint::getEnergyAccumulate(uint i) const {
        switch (i) {
        case kwEStrain:  return false;
        case kwESlip:    return true;
        }
        assert(0);
        return false;
    }

    void ContactModelFlatJoint::setEnergy(uint i,const double &d) {
        if (!energies_) return;
        switch (i) {
        case kwEStrain:  energies_->estrain_ = d; return;  
        case kwESlip:    energies_->eslip_   = d; return;
        }
        assert(0);
        return;
    }

    bool ContactModelFlatJoint::validate(ContactModelMechanicalState *state,const double &) {
        assert(state);
        const IContactMechanical *c = state->getMechanicalContact(); 
        assert(c);
        // This presumes that one of the ends has a non-zero curvature
        rmin(1.0/std::max(c->getEnd1Curvature().y(),c->getEnd2Curvature().y()));
        if (userArea_) {
#ifdef THREED
            rmin(std::sqrt(userArea_ / dPi));
#else
            rmin(userArea_ / 2.0);
#endif        
        }
        if (!propsFixed()) {
            setAreaQuantities();                    
            mType(getmType());
        }
        
        // Initialize the tracking if not initialized
        if (orientProps_ && orientProps_->origNormal_ == DVect(0.0)) {
            orientProps_->origNormal_ = toVect(c->getContact()->getNormal());
            orientProps_->orient1_ = Quat::identity();
            orientProps_->orient2_ = Quat::identity();
        }

        if (state->trackEnergy_)
            activateEnergy();

        updateEffectiveStiffness(state);
        return checkActivity(state->gap_);
    }

    void ContactModelFlatJoint::updateEffectiveStiffness(ContactModelMechanicalState *) {
        DVect2 ret(fj_kn_,fj_ks_);
        ret *= atot();
        effectiveTranslationalStiffness(ret);
#ifdef TWOD
        effectiveRotationalStiffness(DAVect(fj_kn() * (2.0/3.0)*rbar()*rbar()*rbar()));
#else
        double piR4 = dPi * rbar() * rbar() * rbar() * rbar();
        double t = fj_kn() * 0.25 * piR4;
        effectiveRotationalStiffness(DAVect(fj_ks() * 0.50 * piR4,t,t)); 
#endif
    }
     
    bool ContactModelFlatJoint::forceDisplacementLaw(ContactModelMechanicalState *state,const double &timestep) {
        if (!propsFixed())
            propsFixed(true);
        timestep;
        assert(state);

        if (state->activated()) {
            if (cmEvents_[fActivated] >= 0) {
                auto c = state->getContact();
                std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()) };
                IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
                fi->setCMFishCallArguments(c,arg,cmEvents_[fActivated]);
            }
        }

        // Update the orientations
        if (orientProps_) {
            orientProps_->orient1_.increment(state->getMechanicalContact()->getEnd1Mechanical()->getAngVelocity()*timestep);
            orientProps_->orient2_.increment(state->getMechanicalContact()->getEnd2Mechanical()->getAngVelocity()*timestep);
        }

#ifdef TWOD
        // Translational increment in local coordinates
        DVect del_U = state->relativeTranslationalIncrement_;
        double del_theta  = state->relativeAngularIncrement_.z();
        gap(gap() + del_U); // in normal and shear direction in 2D
        theta(theta() + del_theta);
        double dSig, dTau;
        double delX = 2*rbar() / fj_n();
        double rbar2 = rbar() / fj_n();
        DVect dFSum(0.0);
        double dMSum = 0.0;
        if (state->trackEnergy_) {
            assert(energies_);
            energies_->estrain_ =  0.0;
        }
        bool oneBonded = false;
        for(int i=0; i<fj_n(); ++i) {
            double g0 = gap((i  )*delX);
            double g1 = gap((i+1)*delX);
            double gMid = 0.5*(g0 + g1);
            if (bmode_[i] != 3 && gMid > 0) {
                egap_[i] = gMid;
                f_[i] = DVect(0.0);
                continue;
            }
            dSig = computeSig(g0,g1,rbar2,a_[i],(bmode_[i]==3));
            bool tensileBreak = false;
            if (bmode_[i]==3) {
                if (state->canFail_ && dSig >= fj_ten()) {
                    breakBond(i+1,1,state);
                    dSig = dTau = 0.0;
                    tensileBreak = true;
                }
            }
            if (!tensileBreak) {
                dTau = f_[i].y() / a_[i];
                double dUse = delUse(egap_[i],gMid,(bmode_[i]==3),del_U.y());
                double dtauP = dTau - fj_ks()*dUse;
                double dtauPabs = abs(dtauP);
                if (bmode_[i]==3) { // bonded
                    if (dtauPabs < tauC(dSig,true)) 
                        dTau = dtauP;         
                    else { 
                        if (state->canFail_) {
                            breakBond(i+1,2,state);
                            if (fj_resmode() == 0)
                                dSig = dTau = 0.0;     
                            else 
                                dTau = fj_cohres() - dSig * fj_fric();
                        }
                    }
                } else {             // unbonded
                    double dtauC = tauC(dSig,false);
                    if (dtauPabs <= dtauC) {
                        dTau = dtauP;    
                        slipChange(i+1,false,state);
                    } else {
                        dTau = dtauP * ( dtauC / dtauPabs );
                        slipChange(i+1,true,state);
                        if (state->trackEnergy_) { energies_->eslip_ += dtauC*a_[i]*abs(dUse);}
                    }
                }
            }
            oneBonded = true;
            egap_[i] = gMid;
            f_[i] = DVect(-dSig*a_[i],dTau*a_[i]);
            dFSum += f_[i];
            double m = computeM(g0,g1,rbar2,(bmode_[i]==3)) + fj_m_set().z()/fj_n();
            dMSum  += m - rBarl_[i]*f_[i].x();
            if (state->trackEnergy_) {
                if (fj_kn_) {
                    double ie = 2.0*rBarl_[i]*rBarl_[i]*rBarl_[i] / 3.0;
                    energies_->estrain_ += 0.5*(dSig*dSig*a_[i] + m*m/ie) / fj_kn_;
                }
                if (fj_ks_) {
                    energies_->estrain_ += 0.5 * dTau*dTau*a_[i] / fj_ks_;
                }
            }
        }
        //
        fj_f(dFSum);
        fj_m(DAVect(dMSum));
        if (!oneBonded)
            fj_m_set(DAVect(0.0));
#else
        CAxes localSys = state->getMechanicalContact()->getContact()->getLocalSystem();
        DVect trans = state->relativeTranslationalIncrement_; // translation increment in local coordinates
        DAVect ang = state->relativeAngularIncrement_; // rotational increment in local coordinates
        DVect shear(0.0,trans.y(),trans.z());
        DVect del_Us = localSys.toGlobal(shear); // In global coordinates 
        // What is the twist in global coordinates?
        DVect del_Theta_t = localSys.e1()*ang.x();
        theta_ += ang.y();
        thetaM_ += ang.z();

        gap(gap() + trans);
        if (state->trackEnergy_) {
            assert(energies_);
            energies_->estrain_ =  0.0;
        }
        DVect force(0.0);
        DAVect mom(0.0);
        bool oneBonded = false;
        for (int e=1,i=0; e<=fj_n(); ++e, ++i) {  
            double gBar1 = gap( rBarl_[i].x(),rBarl_[i].y());
            if (!Bonded(e) && gBar1 > 0) {
                egap_[i] = gBar1;
                f_[i] = DVect(0.0);
                continue;
            }
            DVect r = localSys.e2()*rBarl_[i].x() + localSys.e3()*rBarl_[i].y(); // location of element point
            double sigBar_e = sigBar(e);
            f_[i].rx() = -sigBar_e * a_[i]; // Step 1...
            if (Bonded(e) && (sigBar_e >= fj_ten())) { // break bond in tension
                if (state->canFail_) { 
                    breakBond(e,1,state);
                    f_[i] = DVect(0.0);
                }
            } else {
                DVect del_us  = del_Us + (del_Theta_t & r); // In global - has the twist in there
                double  del_usl = delUse(egap_[i],gBar1,Bonded(e),(del_us | localSys.e2()));
                double  del_usm = delUse(egap_[i],gBar1,Bonded(e),(del_us | localSys.e3()));
                double Fs_lP = f_[i].y() - fj_ks() * a_[i] * del_usl;
                double Fs_mP = f_[i].z() - fj_ks() * a_[i] * del_usm;
                double FsPMag = sqrt( Fs_lP*Fs_lP + Fs_mP*Fs_mP );
                double tauBarP = FsPMag / a_[i];
                if ( !Bonded(e) ) {
                    double tau_c = sigBar_e < 0.0 ? fj_cohres()-fj_fric()*sigBar_e : 0.0;
                    if ( tauBarP <= tau_c ) {
                        f_[i].ry() = Fs_lP;
                        f_[i].rz() = Fs_mP;
                        slipChange(e,false,state);
                    } else { // enforce sliding
                        double sFac = tau_c * a_[i] / FsPMag;
                        f_[i].ry() = Fs_lP * sFac;
                        f_[i].rz() = Fs_mP * sFac;
                        slipChange(e,true,state);
                        if (state->trackEnergy_) { energies_->eslip_ += tau_c*a_[i]*sqrt(del_usl*del_usl+del_usm*del_usm);}
                    }
                } else { // Bonded(e)
                    double tau_c = fj_coh() - sigBar_e * tan(dDegrad*fj_fa());
                    if ( tauBarP <= tau_c ) {
                        f_[i].ry() = Fs_lP;
                        f_[i].rz() = Fs_mP;
                    } else { // break bond in shear
                        if (state->canFail_) {
                            breakBond(e,2,state);
                            if (fj_resmode() == 0)
                                f_[i] = DVect(0.0);
                            else {
                                double newForce = fj_cohres() - sigBar_e * fj_fric();
                                if (!userArea_)
                                    newForce *= a_[i];
                                else
                                    newForce *= userArea_ / fj_n();
                                newForce /= std::sqrt(f_[i].y()*f_[i].y() + f_[i].z()*f_[i].z());
                                f_[i].ry() *= newForce;
                                f_[i].rz() *= newForce;
                            }
                        }
                    }
                }
            }
            oneBonded = true;
            force += f_[i];
            mom += localSys.toLocal(r) & f_[i] + fj_m_set()/fj_n();
            egap_[i] = gBar1;
            if (state->trackEnergy_) {
                energies_->estrain_ += computeStrainEnergy(e);
            }
        }
        fj_f(force);
        fj_m(mom);
        if (!oneBonded)
            fj_m_set(DAVect(0.0));
#endif
        assert(fj_f_ == fj_f_);
        return checkActivity(0.0);
    }
    
    bool ContactModelFlatJoint::thermalCoupling(ContactModelMechanicalState*, ContactModelThermalState* ts, IContactThermal*, const double&) {
        // Account for thermal expansion in incremental mode
        if (ts->gapInc_ == 0.0) return false;
        DVect dg(0.0);
        dg.rx() = ts->gapInc_;
        gap(gap() + dg);
        return true;
    }

    void ContactModelFlatJoint::setAreaQuantities() {
        rbar(fj_rmul() * rmin());
#ifdef TWOD
        atot(2.0 * rbar());
        double v = atot()/fj_n();
        for (int i=1; i<=fj_n(); ++i) {
            a_[i-1] = v;
            rBarl_[i-1] = rbar() * (double(-2*i + 1 + fj_n()) / fj_n());
        }
#else
        atot(dPi * rbar() * rbar());
        double del_r  = rbar() / fj_nr();
        double del_al = 2.0*dPi / fj_na();
        double fac = 2.0/3.0;
        for (int i=0; i < fj_n(); ++i) {
            double dVal = i / fj_na();
            int I = (int)floor( dVal );
            int J = i - I*fj_na();
            double r1  =  I      * del_r;
            double r2  = (I + 1) * del_r;
            double al1 =  J      * del_al;
            double al2 = (J + 1) * del_al;
            a_[i] = 0.5 * (al2 - al1) * (r2*r2 - r1*r1);
            rBarl_[i] = DVect2(((sin(al2) - sin(al1)) / (al2 - al1))*((r2*r2*r2 - r1*r1*r1)/(r2*r2 - r1*r1)),
                               ((cos(al1) - cos(al2)) / (al2 - al1))*((r2*r2*r2 - r1*r1*r1)/(r2*r2 - r1*r1)))*fac;
        }
#endif
        updateEffectiveStiffness(0);
    }

    DVect ContactModelFlatJoint::getRelElemPos(const IContact* c,int i) const {
        DVect ret(0.0);
        if (c) {
            ret = c->getPosition();
            CAxes localSys = c->getLocalSystem();
#ifdef TWOD
            ret += localSys.e2()*rBarl_[i];
#else
            ret += localSys.e2()*rBarl_[i].x() + localSys.e3()*rBarl_[i].y();
#endif
        }
        return ret;
    }

    void ContactModelFlatJoint::setRelElemPos(const IContact* c,int i,const DVect &pos) {
        // pos is a position in space in global coordinates
        propsFixed(true);
        if (c) {
            // project onto the plane
            DVect cp = c->getPosition();
            DVect norm = toVect(c->getNormal());
            double sd = norm|(cp - pos);
            // np is the point on the plane 
            DVect np = pos+norm*sd;
            np = np-cp;
            CAxes localSys = c->getLocalSystem();
            np = localSys.toLocal(np);
#ifdef TWOD
            rBarl_[i] = np.y();
#else
            rBarl_[i] = DVect2(np.y(),np.z());
#endif
        }
    }

    int ContactModelFlatJoint::getmType() const {
        if (propsFixed()) return mType();
        //  
        if (fj_gap0() > 0.0)   return 2;
        //
        // If we get to here, then G == 0.0.
        bool AllBonded = true;
        bool AllSlit = true;
        for(int i=0; i<fj_n(); ++i) {
            if (bmode_[i] != 3) AllBonded = false;
            else AllSlit = false;
        }
        if (AllBonded) return 1;
        if (AllSlit)   return 3;
        //
        return 4;
    }

    void ContactModelFlatJoint::bondElem(int iSeg,bool bBond ) {
        if (bBond) {
            if (fj_gap0() == 0.0) {
                bmode_[iSeg-1]  = 3;
            } else
                bmode_[iSeg-1] = 0;
        } else 
            bmode_[iSeg-1] = 0;
    }

    void ContactModelFlatJoint::breakBond(int iSeg,int fmode,ContactModelMechanicalState *state) {
        bmode_[iSeg-1]  = fmode;
        if (cmEvents_[fBondBreak] >= 0) {
            auto c = state->getContact();
            std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()),
                                                 fish::Parameter((qint64)iSeg),
                                                 fish::Parameter((qint64)fmode),
                                                 fish::Parameter(computeStrainEnergy(iSeg)) 
                                               };
            IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
            fi->setCMFishCallArguments(c,arg,cmEvents_[fBondBreak]);
        }
        if (!isBonded() && cmEvents_[fBroken] >= 0) {
            auto c = state->getContact();
            std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()) };
            IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
            fi->setCMFishCallArguments(c,arg,cmEvents_[fBroken]);
        }
    }

    void ContactModelFlatJoint::slipChange(int iSeg,bool smode,ContactModelMechanicalState *state) {
        bool emitEvent = false;
        if (smode) {
            if (!smode_[iSeg-1]) {
                emitEvent = true;
                smode_[iSeg-1] = smode;
            }
        } else {
            if (smode_[iSeg-1]) {
                emitEvent = true;
                smode_[iSeg-1] = smode;
            }
        }
        if (emitEvent && cmEvents_[fSlipChange] >= 0) {
            auto c = state->getContact();
            std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()),
                                                 fish::Parameter((qint64)iSeg),
                                                 fish::Parameter(smode) };
            IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
            fi->setCMFishCallArguments(c,arg,cmEvents_[fSlipChange]);
        }
    }

    double ContactModelFlatJoint::tauC(const double &dSig,bool bBonded) const {
        if (bBonded) return (fj_coh() + (tan(dDegrad*fj_fa()) * (-dSig)) );
        else 
            return (dSig < 0.0 ? fj_cohres() - fj_fric() * dSig : 0.0 );
    }

#ifdef THREED
    double ContactModelFlatJoint::xi(int comp) const {
        if (comp == 1) return abs(theta_) <= 1e-12 ? 0.0 : theta_/thbMag();
        else           return abs(thetaM_) <= 1e-12 ? 0.0 : thetaM_/thbMag();
    }
#endif

    void ContactModelFlatJoint::initVectors() {
        a_.resize(fj_n());
        rBarl_.resize(fj_n());
        bmode_.resize(fj_n());
        smode_.resize(fj_n());
        egap_.resize(fj_n());
        f_.resize(fj_n());
        for (int i=0; i<fj_n(); ++i) {
            a_[i] = egap_[i] = 0.0;
#ifdef THREED
            rBarl_[i] = DVect2(0.0);
#else
            rBarl_[i] = 0.0;
#endif
            f_[i] = DVect(0.0);
            bmode_[i] = 0;
            smode_[i] = false;
        }
    }

#ifdef TWOD
    double ContactModelFlatJoint::gap(const double &x) const {
        return gap().x() + theta()*(x - rbar());
    }
#else
    double ContactModelFlatJoint::gap(const double &r_l,const double &r_m ) const {
       return gap().x() + ( r_m*xi(1) - r_l*xi(2) ) * thbMag();
    }

    double ContactModelFlatJoint::sigBar(int e) const {
        if (!Bonded(e)&& gap(rBarl_[e-1].x(),rBarl_[e-1].y()) >= 0.0)
            return 0.0;
        else
            return fj_kn() * gap(rBarl_[e-1].x(),rBarl_[e-1].y());
    }

    double ContactModelFlatJoint::tauBar(int e) const {
        return a_[e-1] <= 1e-12 ?
        0.0 : sqrt(f_[e-1].y()*f_[e-1].y() + f_[e-1].z()*f_[e-1].z())/a_[e-1] ;
    }

#endif

    double ContactModelFlatJoint::computeStrainEnergy(int e) const {
        double ret(0.0);
        int i = e - 1;
#ifdef TWOD
        double delX = 2 * rbar() / fj_n();
        double g0 = gap((i)*delX);
        double g1 = gap((i + 1)*delX);
        double rbar2 = rbar() / fj_n();
        double dSig = computeSig(g0, g1, rbar2, a_[i], (bmode_[i] == 3));
        double m = computeM(g0, g1, rbar2, (bmode_[i] == 3));
        double dTau = f_[i].y() / a_[i]; // only valid before failure
        if (fj_kn_) {
            double ie = 2.0*rBarl_[i] * rBarl_[i] * rBarl_[i] / 3.0;
            ret += 0.5*(dSig*dSig*a_[i] + m * m / ie) / fj_kn_;
        }
        if (fj_ks_) {
            ret += 0.5 * dTau*dTau*a_[i] / fj_ks_;
        }
#else
        if (fj_kn_) {
            ret += 0.5*(sigBar(e)*sigBar(e)*a_[i]) / fj_kn_;
        }
        if (fj_ks_) {
            ret += 0.5 * (f_[i].y()*f_[i].y() + f_[i].z()*f_[i].z()) / (fj_ks_*a_[i]);
        }
#endif
        return ret;
    }

    double ContactModelFlatJoint::computeSig(const double &g0,const double &g1,const double &rbar,
                                             const double &dA,bool bBonded ) const {
        double gTerm;
        switch (getCase(g0, g1)) {
            case 1:
                if (bBonded)       gTerm =  (g0 + g1);            
                else if (g0 < 0.0) gTerm = -( g0*g0 / (g1 - g0) );
                else               gTerm =  ( g1*g1 / (g1 - g0) );
                break;
            case 2:
                if (bBonded) gTerm = (g0 + g1); 
                else         gTerm = 0.0;       
                break;
            case 3:
                gTerm = (g0 + g1);
                break;
        }
        return (fj_kn() * gTerm * rbar) / dA;
    }

    double ContactModelFlatJoint::computeM(const double &g0,const double &g1,const double &rbar,
                                           bool bBonded) const {
        double gTerm;
        switch (getCase(g0,g1)) {
            case 1:
                if (bBonded)       gTerm = -((g1 - g0) / 3.0);                                   
                else if (g0 < 0.0) gTerm = g0*g0*(g0 - 3.0*g1) / (3.0*(g1-g0)*(g1-g0));          
                else               gTerm = -(((g1-g0)*(g1-g0)*(g1-g0) + g0*g0*(g0 - 3.0*g1))
                                            / (3.0*(g1-g0)*(g1-g0)));                                                   
            break;
          case 2:
                if (bBonded) gTerm = -((g1 - g0) / 3.0); 
                else         gTerm = 0.0;       
                break;
          case 3:
                gTerm = -((g1 - g0) / 3.0);
                break;
        }
        return fj_kn() * gTerm * rbar*rbar;
    }

    int ContactModelFlatJoint::getCase(const double &g0,const double &g1) const {
        if (g0 * g1 < 0.0) // Case 1: gap changes sign       
            return 1; 
        else if (g0 >= 0.0 && g1 >= 0.0) // Case 2: gap remains positive or zero
            return 2; 
        else // Case 3: gap remains negative
            return 3;  
    }

    double ContactModelFlatJoint::delUse(const double &gapStart,const double &gapEnd,bool bBonded,
                                         const double &delUs) const {
        if ( bBonded ) return delUs;
        if ( gapStart <= 0.0 ) {
            if ( gapEnd <= 0.0 )
                return delUs;
            else { // gapEnd > 0.0
                double xi = -gapStart / (gapEnd - gapStart);
                return delUs * xi;
            }
        } else { // gapStart > 0.0
            if ( gapEnd >= 0.0 )
                return 0.0;
            else { // gapEnd < 0.0
                double xi = -gapStart / (gapEnd - gapStart);
                return delUs * (1.0 - xi);
            }
        }
    }
    
    bool ContactModelFlatJoint::checkActivity(const double &inGap) {
        // If any subcontact is bonded return true
        FOR(it,bmode_) if ((*it) == 3) 
            return true; 
        // If the normal gap is less than 2*rbar return true
        if (gap().x() < 2.0*rbar())
            return true;
        // check to see if there is overlap (based on the initial gap) to reset activity if the contact has been previously deactivated 
        if (inGap < 0) {
            // reset the relative rotation
            theta(0.0);    
#ifdef THREED
            thetaM(0.0);
#endif
            // set the gap to be the current gap, removing the shear displacement
            DVect inp(inGap,0.0);
            gap(inp);
            return true;
        }
        return false;
    }

    void ContactModelFlatJoint::setForce(const DVect &v,IContact *) {
        fj_f_ = v;
        DVect df = v / f_.size();
        for (int i=0; i<f_.size(); ++i)
            f_[i] = df;
        // Set gap consistent with normal force
        double at = userArea_;
        if (!userArea_) {
            for (int i = 1; i <= fj_n(); ++i)
                at += a_[i - 1];
        } 
        gap_.rx() = -1.0 * v.x() / (fj_kn_ * at);
    }

    void ContactModelFlatJoint::getSphereList(const IContact *con,std::vector<DVect> *pos,std::vector<double> *rad,std::vector<double> *val) {
        assert(pos);
        assert(rad);
        assert(val);
        if (!orientProps_)
            return;
        // find minimal radii for end1
        double br = convert_getcast<IContactMechanical>(con)->getEnd1Curvature().y();
        if (br) {
            const IPiece *p = con->getEnd1();
            FArray<const IContact*> arr;
            p->getContactList(&arr);
            double maxgap = 0.0;
            FOR(ic,arr) {
                const IContactMechanical *mc = convert_getcast<IContactMechanical>(*ic);
                const IContactModelMechanical *mcm = mc->getModelMechanical();
                if (mcm->getContactModel()->getIndex() == ContactModelFlatJoint::getIndex()) {
                    const ContactModelFlatJoint *in = dynamic_cast<const ContactModelFlatJoint*>(mcm);
                    maxgap = std::max<double>(maxgap,in->gap().x()- mc->getGap());
                }
            }
            br = 1.0 / br - 0.5*maxgap;
            const IContactMechanical *mc = convert_getcast<IContactMechanical>(con);
            pos->push_back(convert_getcast<IPieceMechanical>(mc->getEnd1())->getPosition());
            rad->push_back(br);
            val->push_back(mc->getEnd1()->getIThing()->getID());
        }

        // Give the end2 sphere - bummer
        br = convert_getcast<IContactMechanical>(con)->getEnd2Curvature().y();
        if (br) {
            const IPiece *p = con->getEnd2();
            FArray<const IContact*> arr;
            p->getContactList(&arr);
            double maxgap = 0.0;
            FOR(ic,arr) {
                const IContactMechanical *mc = convert_getcast<IContactMechanical>(*ic);
                const IContactModelMechanical *mcm = mc->getModelMechanical();
                if (mcm->getContactModel()->getIndex() == ContactModelFlatJoint::getIndex()) {
                    const ContactModelFlatJoint *in = dynamic_cast<const ContactModelFlatJoint*>(mcm);
                    maxgap = std::max<double>(maxgap,in->gap().x()- mc->getGap());
                }
            }
            br = 1.0 / br - 0.5*maxgap;
            const IContactMechanical *mc = convert_getcast<IContactMechanical>(con);
            pos->push_back(convert_getcast<IPieceMechanical>(mc->getEnd2())->getPosition());
            rad->push_back(br);
            val->push_back(mc->getEnd2()->getIThing()->getID());
        }
    }

#ifdef THREED

    void ContactModelFlatJoint::getDiskList(const IContact *con,std::vector<DVect> *pos,std::vector<DVect> *normal,std::vector<double> *radius,std::vector<double> *val) {
        assert(pos);
        assert(normal);
        assert(radius);
        assert(val);
        if (!orientProps_)
            return;
        // plot the contact plane right in the middle of the 2 normals
        double rad = fj_rmul()*rmin();
        DVect axis1 = orientProps_->orient1_.rotate(orientProps_->origNormal_);
        DVect axis2 = orientProps_->orient2_.rotate(orientProps_->origNormal_);
        DVect norm = ((axis1.unit()+axis2.unit())*0.5).unit();
        pos->push_back(con->getPosition());
        normal->push_back(norm);
        radius->push_back(rad);
        const IContactMechanical *mc = convert_getcast<IContactMechanical>(con);
        val->push_back(mc->getLocalForce().mag());
    }

#endif

    void ContactModelFlatJoint::getCylinderList(const IContact *con,std::vector<DVect> *bot,std::vector<DVect> *top,std::vector<double> *radlow,std::vector<double> *radhi,std::vector<double> *val) {
        assert(bot);
        assert(top);
        assert(radlow);
        assert(radhi);
        assert(val);
        if (!orientProps_)
            return;
        const IContactMechanical *mc = convert_getcast<IContactMechanical>(con);
        double br = mc->getEnd1Curvature().y(), br2 = mc->getEnd2Curvature().y();
        if (userArea_) {
#ifdef THREED
            br = std::sqrt(userArea_ / dPi);
#else
            br = userArea_ / 2.0;
#endif        
            br = 1. / br;
            br2 = br;
        }

        double cgap = mc->getGap();
        if (br > 0 && br2 > 0) {
            br = 1.0 / br;
            br2 = 1.0 / br2;
            double rad = fj_rmul()*rmin();
            DVect bp = convert_getcast<IPieceMechanical>(mc->getEnd1())->getPosition();
            DVect axis = orientProps_->orient1_.rotate(orientProps_->origNormal_);
            bot->push_back(axis.unit()*(br-0.5*(gap().x()- cgap))+bp);
            top->push_back(bp);
            radlow->push_back(rad);
            radhi->push_back(0.0);
            val->push_back(mc->getEnd1()->getIThing()->getID());
            bp = convert_getcast<IPieceMechanical>(mc->getEnd2())->getPosition();
            axis = orientProps_->orient2_.rotate(orientProps_->origNormal_);
            bot->push_back(axis.unit()*(br2-0.5*(gap().x()-cgap))*(-1.0)+bp);
            top->push_back(bp);
            radlow->push_back(rad);
            radhi->push_back(0.0);
            val->push_back(mc->getEnd2()->getIThing()->getID());
        }
    }

    DVect ContactModelFlatJoint::getForce(const IContactMechanical *) const {
        DVect ret(fj_f_);
        return ret;
    }

    DAVect ContactModelFlatJoint::getMomentOn1(const IContactMechanical *c) const {
        DVect force = getForce(c);
        DAVect ret(fj_m_);
        c->updateResultingTorqueOn1Local(force,&ret);
        return ret;
    }

    DAVect ContactModelFlatJoint::getMomentOn2(const IContactMechanical *c) const {
        DVect force = getForce(c);
        DAVect ret(fj_m_);
        c->updateResultingTorqueOn2Local(force,&ret);
        return ret;
    }

} // namespace itascaxd

// EoF

Top