Spring Network Model Implementation

See this page for the documentation of this contact model.

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

#include "contactmodel/src/contactmodelmechanical.h"

#ifdef RBSN_LIB
#  define RBSN_EXPORT EXPORT_TAG
#elif defined(NO_MODEL_IMPORT)
#  define RBSN_EXPORT
#else
#  define RBSN_EXPORT IMPORT_TAG
#endif

namespace cmodelsxd {
    using namespace itasca;

    class ContactModelRBSN : public ContactModelMechanical {
    public:
        // Constructor: Set default values for contact model properties.
        RBSN_EXPORT ContactModelRBSN();
        // Destructor, called when contact is deleted: free allocated memory, etc.
        RBSN_EXPORT virtual ~ContactModelRBSN();
        // Contact model name (used as keyword for commands and FISH).
        virtual QString  getName() const { return "springnetwork"; }
        // The index provides a quick way to determine the type of contact model.
        // Each type of contact model in PFC must have a unique index; this is assigned
        // by PFC when the contact model is loaded. This index should be set to -1
        virtual void     setIndex(int i) { index_=i;}
        virtual int      getIndex() const {return index_;}
        // Contact model version number (e.g., MyModel05_1). The version number can be
        // accessed during the save-restore operation (within the archive method,
        // testing {stream.getRestoreVersion() == getMinorVersion()} to allow for 
        // future modifications to the contact model data structure.
        virtual uint     getMinorVersion() const;
        // Copy the state information to a newly created contact model.
        // Provide access to state information, for use by copy method.
        virtual void     copy(const ContactModel *c) override;
        // Provide save-restore capability for the state information.
        virtual void     archive(ArchiveStream &); 
        // Enumerator for the properties.
        enum PropertyKeys { 
              kwKn=1
            , kwKs    
            , kwKrot
            , kwFric 
            , kwBMul
            , kwTMul
            , kwSNMode
            , kwSNF
            , kwSNM
            , kwSNS
            , kwSNBS
            , kwSNTS
            , kwSNRMul
            , kwSNRadius
            , kwEmod
            , kwKRatio
            , kwDpNRatio 
            , kwDpSRatio
            , kwDpMode 
            , kwDpF
            , kwSNState
            , kwSNTStr
            , kwSNSStr
            , kwSNCoh
            , kwSNFa
            , kwSNMCF
            , kwSNSig
            , kwSNTau
            , kwSNArea
            , kwUserArea
            , kwRGap
            , kwPForce
            , kwPois
            , kwPoisDiag
            , kwSnCohRes
            , kwSnDil
            , kwSnDilZ
            , kwSnNormDisp
            , kwSnShearDisp
            , kwSnCohDc
            , kwSnHeal
            , kwSnTenDc
            , kwTenTable
            , kwCohTable
            , kwTablePos
            , kwPorP
            , kwStressNorm
        };
        // Contact model property names in a comma separated list. The order corresponds with
        // the order of the PropertyKeys enumerator above. One can visualize any of these 
        // properties in PFC automatically. 
        virtual QString  getProperties() const { 
            return "kn"
                   ",ks"
                   ",krot"
                   ",fric"
                   ",sn_bmul"
                   ",sn_tmul"
                   ",sn_mode"
                   ",sn_force"
                   ",sn_moment"
                   ",sn_slip"
                   ",sn_slipb"
                   ",sn_slipt"
                   ",sn_rmul"
                   ",sn_radius"
                   ",emod"
                   ",kratio"
                   ",dp_nratio"
                   ",dp_sratio"
                   ",dp_mode"
                   ",dp_force"
                   ",sn_state"
                   ",sn_ten"
                   ",sn_shear"
                   ",sn_coh"
                   ",sn_fa"
                   ",sn_mcf"
                   ",sn_sigma"
                   ",sn_tau"
                   ",sn_area"
                   ",user_area"
                   ",rgap"
                   ",sn_pois_force"
                   ",sn_pois"
                   ",sn_non_diag"
                   ",sn_cohres"
                   ",sn_dil"
                   ",sn_dilzero"
                   ",sn_ndisp"
                   ",sn_sdisp"
                   ",sn_cohdc"
                   ",sn_heal"
                   ",sn_tendc"
                   ",sn_tentab"
                   ",sn_cohtab"
                   ",sn_tabpos"
                   ",sn_porp"
                   ",sn_esigma"
                ;
        }
        // Enumerator for the energies.
        enum EnergyKeys { 
            kwEStrain=1
          , kwESlip
          , kwEDashpot
        };
        // Contact model energy names in a comma separated list. The order corresponds with
        // the order of the EnergyKeys enumerator above. 
        virtual QString  getEnergies() const { 
            return "energy-strain"
                   ",energy-slip"
                   ",energy-dashpot";
        }
        // Returns the value of the energy (base 1 - getEnergy(1) returns the estrain energy).
        virtual double   getEnergy(uint i) const; 
        // Returns whether or not each energy is accumulated (base 1 - getEnergyAccumulate(1) 
        // returns wther or not the estrain energy is accumulated which is false).
        virtual bool     getEnergyAccumulate(uint i) const;
        // Set an energy value (base 1 - setEnergy(1) sets the estrain energy).
        virtual void     setEnergy(uint i,const double &d); // Base 1
        // Activate the energy. This is only called if the energy tracking is enabled. 
        virtual void     activateEnergy() { if (energies_) return; energies_ = NEWC(Energies());}
        // Returns whether or not the energy tracking has been enabled for this contact.
        virtual bool     getEnergyActivated() const {return (energies_ != 0);}

        // Enumerator for contact model related FISH callback events. 
        enum FishCallEvents {
             fActivated=0
            ,fSlipChange
            ,fBondBreak
        };
        // Contact model FISH callback event names in a comma separated list. The order corresponds with
        // the order of the FishCallEvents enumerator above. 
        virtual QString  getFishCallEvents() const { 
            return 
                "contact_activated"
                ",slip_change"
                ",bond_break"; 
        }

        // Return the specified contact model property.
        virtual QVariant getProperty(uint i,const IContact *) const;
        // The return value denotes whether or not the property corresponds to the global
        // or local coordinate system (TRUE: global system, FALSE: local system). The
        // local system is the contact-plane system (nst) defined as follows.
        // If a vector V is expressed in the local system as (Vn, Vs, Vt), then V is
        // expressed in the global system as {Vn*nc + Vs*sc + Vt*tc} where where nc, sc
        // and tc are unit vectors in directions of the nst axes.
        // This is used when rendering contact model properties that are vectors.
        virtual bool     getPropertyGlobal(uint i) const;
        // Set the specified contact model property, ensuring that it is of the correct type
        // and within the correct range --- if not, then throw an exception.
        // The return value denotes whether or not the update has affected the timestep
        // computation (by having modified the translational or rotational tangent stiffnesses).
        // If true is returned, then the timestep will be recomputed.
        virtual bool     setProperty(uint i,const QVariant &v,IContact *);
        // The return value denotes whether or not the property is read-only
        // (TRUE: read-only, FALSE: read-write).
        virtual bool     getPropertyReadOnly(uint i) const;

        // The return value denotes whether or not the property is inheritable
        // (TRUE: inheritable, FALSE: not inheritable). Inheritance is provided by
        // the endPropertyUpdated method.
        virtual bool     supportsInheritance(uint i) const; 
        // Return whether or not inheritance is enabled for the specified property.
        virtual bool     getInheritance(uint i) const { assert(i<32); quint32 mask = to<quint32>(1 << i);  return (inheritanceField_ & mask) ? true : false; }
        // Set the inheritance flag for the specified property.
        virtual void     setInheritance(uint i,bool b) { assert(i<32); quint32 mask = to<quint32>(1 << i);  if (b) inheritanceField_ |= mask;  else inheritanceField_ &= ~mask; }

        // Enumerator for contact model methods.
        enum MethodKeys { kwAssignStiffness=1, kwStiffness, kwBond, kwUnbond, kwArea, kwResetDisp};
        // Contact model methoid names in a comma separated list. The order corresponds with
        // the order of the MethodKeys enumerator above.  
        virtual QString  getMethods() const { return "assign-stiffness,compute-stiffness,bond,unbond,area,reset-disp";}
        // Return a comma seprated list of the contact model method arguments (base 1).
        virtual QString  getMethodArguments(uint i) const; 
        // Set contact model method arguments (base 1). 
        // The return value denotes whether or not the update has affected the timestep
        // computation (by having modified the translational or rotational tangent stiffnesses).
        // If true is returned, then the timestep will be recomputed.
        virtual bool     setMethod(uint i,const QVector<QVariant> &vl,IContact *con=0); 

        // Prepare for entry into ForceDispLaw. The validate function is called when:
        // (1) the contact is created, (2) a property of the contact that returns a true via
        // the setProperty method has been modified and (3) when a set of cycles is executed
        // via the {cycle N} command.
        // Return value indicates contact activity (TRUE: active, FALSE: inactive).
        virtual bool    validate(ContactModelMechanicalState *state,const double &timestep);
        // The endPropertyUpdated method is called whenever a surface property (with a name
        // that matches an inheritable contact model property name) of one of the contacting
        // pieces is modified. This allows the contact model to update its associated
        // properties. The return value denotes whether or not the update has affected
        // the time step computation (by having modified the translational or rotational
        // tangent stiffnesses). If true is returned, then the time step will be recomputed.  
        virtual bool    endPropertyUpdated(const QString &name,const IContactMechanical *c);
        // The forceDisplacementLaw function is called during each cycle. Given the relative
        // motion of the two contacting pieces (via
        //   state->relativeTranslationalIncrement_ (Ddn, Ddss, Ddst)
        //   state->relativeAngularIncrement_       (Dtt, Dtbs, Dtbt)
        //     Ddn  : relative normal-displacement increment, Ddn > 0 is opening
        //     Ddss : relative  shear-displacement increment (s-axis component)
        //     Ddst : relative  shear-displacement increment (t-axis component)
        //     Dtt  : relative twist-rotation increment
        //     Dtbs : relative  bend-rotation increment (s-axis component)
        //     Dtbt : relative  bend-rotation increment (t-axis component)
        //       The relative displacement and rotation increments:
        //         Dd = Ddn*nc + Ddss*sc + Ddst*tc
        //         Dt = Dtt*nc + Dtbs*sc + Dtbt*tc
        //       where nc, sc and tc are unit vectors in direc. of the nst axes, respectively.
        //       [see {Table 1: Contact State Variables} in PFC Model Components:
        //       Contacts and Contact Models: Contact Resolution]
        // ) and the contact properties, this function must update the contact force and
        // moment.
        //   The force_ is acting on piece 2, and is expressed in the local coordinate system
        //   (defined in getPropertyGlobal) such that the first component positive denotes
        //   compression. If we define the moment acting on piece 2 by Mc, and Mc is expressed
        //   in the local coordinate system (defined in getPropertyGlobal), then we must use the getMechanicalContact()->updateResultingTorquesLocal(...) method to 
        //   get the total moment. 
        // The return value indicates the contact activity status (TRUE: active, FALSE:
        // inactive) during the next cycle.
        // Additional information:
        //   * If state->activated() is true, then the contact has just become active (it was
        //     inactive during the previous time step).
        //   * Fully elastic behavior is enforced during the SOLVE ELASTIC command by having
        //     the forceDispLaw handle the case of {state->canFail_ == true}.
        virtual bool    forceDisplacementLaw(ContactModelMechanicalState *state,const double &timestep);
        virtual bool    thermalCoupling(ContactModelMechanicalState*, ContactModelThermalState* ts, IContactThermal*, const double&);
        // The getEffectiveXStiffness functions return the translational and rotational
        // tangent stiffnesses used to compute a stable time step. When a contact is sliding,
        // the translational tangent shear stiffness is zero (but this stiffness reduction
        // is typically ignored when computing a stable time step). If the contact model
        // includes a dashpot, then the translational stiffnesses must be increased (see
        // Potyondy (2009)).
        //   [Potyondy, D. 'Stiffness Matrix at a Contact Between Two Clumps,' Itasca
        //   Consulting Group, Inc., Minneapolis, MN, Technical Memorandum ICG6863-L,
        //   December 7, 2009.]
        virtual DVect2  getEffectiveTranslationalStiffness() const { return effectiveTranslationalStiffness_; }
        virtual DAVect  getEffectiveRotationalStiffness() const { return effectiveRotationalStiffness_;}

        // Return a new instance of the contact model. This is used in the CMAT
        // when a new contact is created. 
        virtual ContactModelRBSN *clone() const override { return NEWC(ContactModelRBSN()); }
        // The getActivityDistance function is called by the contact-resolution logic when
        // the CMAT is modified. Return value is the activity distance used by the
        // checkActivity function.
        virtual double              getActivityDistance() const {return rgap_;}
        // The isOKToDelete function is called by the contact-resolution logic when...
        // Return value indicates whether or not the contact may be deleted.
        // If TRUE, then the contact may be deleted when it is inactive.
        // If FALSE, then the contact may not be deleted (under any condition).
        virtual bool                isOKToDelete() const { return !isBonded(); }
        // Zero the forces and moments stored in the contact model. This function is called
        // when the contact becomes inactive.
        virtual void                resetForcesAndMoments() { 
            sn_F_ = DVect(0.0);
            fictForce_ = DVect(0.0);
            sn_M_ = DAVect(0.0);
            dp_F(DVect(0.0)); 
            if (energies_) {
                energies_->estrain_ = 0.0;
            }
        }
        virtual void     setForce(const DVect &v,IContact *c);
        virtual void     setArea(const double &d) { userArea_ = d; }
        virtual double   getArea() const { return userArea_; }

        // The checkActivity function is called by the contact-resolution logic when...
        // Return value indicates contact activity (TRUE: active, FALSE: inactive).
        virtual bool     checkActivity(const double &gap) { return  gap <= rgap_ || isBonded();}

        // Returns the sliding state (FALSE is returned if not implemented).
        virtual bool     isSliding() const { return sn_S_; }
        // Returns the bonding state (FALSE is returned if not implemented).
        virtual bool     isBonded() const { return sn_state_ >= 3; }
        virtual void     unbond() { sn_state_ = 0; }

        // Both of these methods are called only for contacts with facets where the wall 
        // resolution scheme is set the full. In such cases one might wish to propagate 
        // contact state information (e.g., shear force) from one active contact to another. 
        // See the Faceted Wall section in the documentation. 
        virtual void     propagateStateInformation(IContactModelMechanical* oldCm,const CAxes &oldSystem=CAxes(),const CAxes &newSystem=CAxes());
        virtual void     setNonForcePropsFrom(IContactModel *oldCM);
           
        /// 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;

        // Methods to get and set properties. 
        double         sn_Ten() const { return tenTable_[0].x(); }
        void           sn_Ten(const double &d) { tenTable_[0].rx() = d; }
        double         sn_Coh() const { return cohTable_[0].x(); }
        void           sn_Coh(const double &d) { cohTable_[0].rx() = d; }
        void           sn_MCF(const double &d) { sn_mcf_=d;}
        double         sn_cohdc() const           {return cohTable_.back().y(); }
        double         sn_tendc() const           {return tenTable_.back().y(); }

        bool     hasDamping() const {return dpProps_ ? true : false;}
        double   dp_nratio() const {return (hasDamping() ? (dpProps_->dp_nratio_) : 0.0);}
        void     dp_nratio(const double &d) { if(!hasDamping()) return; dpProps_->dp_nratio_=d;}
        double   dp_sratio() const {return hasDamping() ? dpProps_->dp_sratio_: 0.0;}
        void     dp_sratio(const double &d) { if(!hasDamping()) return; dpProps_->dp_sratio_=d;}
        int      dp_mode() const {return hasDamping() ? dpProps_->dp_mode_: -1;}
        void     dp_mode(int i) { if(!hasDamping()) return; dpProps_->dp_mode_=i;}
        DVect    dp_F() const {return hasDamping() ? dpProps_->dp_F_: DVect(0.0);}
        void     dp_F(const DVect &f) { if(!hasDamping()) return; dpProps_->dp_F_=f;}

        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;}
        double  edashpot() const {return hasEnergies() ? energies_->edashpot_: 0.0;}
        void    edashpot(const double &d) { if(!hasEnergies()) return; energies_->edashpot_=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;}

    private:
        // Index - used internally by PFC. Should be set to -1 in the cpp file. 
        static int index_;

        bool  FDLawBonded(ContactModelMechanicalState *state, const double &timestep);
        bool  FDLawUnBonded(ContactModelMechanicalState *state, const double &timestep);

        // Structure to compute stiffness
        struct StiffData {
            DVect2 trans_ = DVect2(0.0);
            DAVect ang_   = DAVect(0.0);
            double reff_ = 0.0;
        };

        // Structure to store the energies. 
        struct Energies {
            double estrain_  = 0.0;   // elastic energy  
            double eslip_    = 0.0;   // work dissipated by friction 
            double edashpot_ = 0.0;   // work dissipated by dashpots
        };

        // Structure to store dashpot quantities. 
        struct dpProps {
            double dp_nratio_ = 0.0;         // normal viscous critical damping ratio
            double dp_sratio_ = 0.0;         // shear  viscous critical damping ratio
            int    dp_mode_   = 0;           // for viscous mode (0-4) 0 = dashpots, 1 = tensile limit, 2 = shear limit, 3 = limit both
            DVect  dp_F_      = DVect(0.0);  // Force in the dashpots
        };

        bool   updateKn(const IContactMechanical *con);
        bool   updateKs(const IContactMechanical *con);
        bool   updateFric(const IContactMechanical *con);

        StiffData computeStiffData(ContactModelMechanicalState *state) const;
        DVect3    computeGeomData(const IContactMechanical *c) const;
        DVect2    SMax(const IContactMechanical *con) const; // Maximum stress (tensile,shear) at bond periphery
        double    shearStrength(const double &pbArea) const;      // Bond shear strength
        double    strainEnergy(double kn, double ks, double kb, double kt) const;

        void      updateStiffness(ContactModelMechanicalState *state);

        // Contact model inheritance fields.
        quint32 inheritanceField_;

        // Effective translational stiffness.
        DVect2  effectiveTranslationalStiffness_ = DVect2(0.0); 
        DAVect  effectiveRotationalStiffness_ = DAVect(0.0);      // (Twisting,Bending,Bending) Rotational stiffness (twisting always 0)

        // linear model properties
        DVect       fictForce_ = DVect(0.0);// Ficticous force to be added 
        DVect       sn_F_ = DVect(0.0);     // Force carried in the model
        DVect2      sn_sdisp_ = DVect2(0.0); // Accumulated total shear displacement
                                            // The x component holds the current slip
        DAVect      sn_M_ = DAVect(0.0);    // moment (bending + twisting in 3D)         
        DAVect      kRot_ = DAVect(0.0);    // Translational degrees of freedom
        double      kTran_ = 0.0;           // Translational degrees of freedom
        double      kRatio_ = 1.0;          // Ratio of normal to shear stiffness
        double      E_ = 0.0;               // Young's modulus
        double      poisson_ = 0.0;         // Poisson ratio
        double      fric_ = 0.0;            // Coulomb friction coefficient
        double      sn_bmul_ = 1.0;         // Bending friction multiplier
        double      sn_tmul_ = 1.0;         // Twisting friction  multiplier
        double      sn_rmul_ = 1.0;         // Radius multiplier
        double      userArea_ = 0.0;        // Area as specified by the user 
        double      rgap_ = 0.0;            // Reference gap
        double      sn_fa_  = 0.0;          // friction angle (stored as tan(dDegrad*fa))
        double      sn_mcf_ = 1.0;          // moment contribution factor
        double      sn_dil_ = 0.0;          // Dilation (stored as tan(dDegrad*dil))
        double      sn_dilzero_ = 0.0;      // Dilation zero
        double      transTen_ = 0.0;        // Force for transition from tensile to compression
        double      sn_elong_ = 0.0;        // Elongation (or normal displacement since softening)
        double      sn_ndisp_ = 0.0;        // Accumulated normal displacement
        double      sn_cohres_ = 0.0;       // Residual cohesion
        double      sn_por_ = 0.0;          // Pore Pressure
        uint        sn_mode_ = 0;           // specifies absolute (0) or incremental (1) behavior for the the normal force
        uint        sn_state_  = 0;         // bond mode - 0 (NBNF), 1 (NBFT), 2 (NBFS), 3 (B)
        int         sn_tabPos_ = 0;         // Position in the table for query
        bool        poisOffDiag_ = false;   // Add the off diagonal terms 
        bool        sn_S_ = false;          // The current slip state
        bool        sn_BS_ = false;         // The bending  slip state
        bool        sn_TS_ = false;         // The twisting slip state
        bool        forceSet_ = false;      // About setting the force
        bool        sn_heal_ = false;       // Healing behavior

        std::vector<DVect2> tenTable_ = { DVect2(0) };     
        std::vector<DVect2> cohTable_ = { DVect2(0) };

        dpProps *   dpProps_ = nullptr;     // The viscous properties

        Energies *   energies_ = nullptr;   // The energies

    };
} // namespace cmodelsxd
// EoF

Top

contactmodelrbsn.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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
// contactmodelrbsn.cpp
#include "contactmodelrbsn.h"

#include "module/interface/icontactmechanical.h"
#include "module/interface/icontact.h"
#include "module/interface/ipiece.h"
#include "module/interface/ibody.h"
#include "module/interface/ifishcalllist.h"

#include "utility/src/tptr.h"
#include "shared/src/mathutil.h"

#include "kernel/interface/iprogram.h"
#include "module/interface/icontactthermal.h"
#include "contactmodel/src/contactmodelthermal.h"
#include "../version.txt"
#include "fish/src/parameter.h"

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

    extern "C" EXPORT_TAG const char *getName() {
#if DIM==3
        return "contactmodelmechanical3drbsn";
#else
        return "contactmodelmechanical2drbsn";
#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::ContactModelRBSN *m = NEWC(cmodelsxd::ContactModelRBSN());
        return (void *)m;
    }
#endif 

namespace cmodelsxd {
    static const quint32 KnMask      = 0x00000002; // Base 1!
    static const quint32 KsMask      = 0x00000004;
    static const quint32 FricMask    = 0x00000008;

    using namespace itasca;

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

    ContactModelRBSN::ContactModelRBSN() : inheritanceField_(KnMask|KsMask|FricMask) { 
    }

    ContactModelRBSN::~ContactModelRBSN() {
        // Make sure to clean up after yourself!
        if (dpProps_)
            delete dpProps_;
        if (energies_)
            delete energies_;
    }

    void ContactModelRBSN::archive(ArchiveStream &stream) {
        if (stream.getRestoreVersion() > 4) {
            // New version 
            stream & fictForce_;
            stream & sn_F_;
            stream & sn_sdisp_;
            stream & sn_M_;      
            stream & kRot_;
            stream & kTran_;
            stream & kRatio_;
            stream & E_;
            stream & poisson_;
            stream & fric_;
            stream & sn_bmul_;
            stream & sn_tmul_;
            stream & sn_rmul_;
            stream & userArea_;
            stream & rgap_;
            stream & sn_fa_;
            stream & sn_mcf_;
            stream & sn_dil_;
            stream & sn_dilzero_;
            stream & transTen_;
            stream & sn_elong_;
            stream & sn_ndisp_;
            stream & sn_mode_;
            stream & sn_state_;
            stream & poisOffDiag_;
            stream & sn_S_;
            stream & sn_BS_;
            stream & sn_TS_;
            stream & forceSet_;
            stream & sn_heal_;
            stream & tenTable_;
            stream & cohTable_;
            stream & inheritanceField_;
            stream & effectiveTranslationalStiffness_;
            stream & effectiveRotationalStiffness_;  
            if (stream.getArchiveState()==ArchiveStream::Save) {
                bool b = false;
                if (dpProps_) {
                    b = true;
                    stream & b;
                    stream & dpProps_->dp_nratio_; 
                    stream & dpProps_->dp_sratio_; 
                    stream & dpProps_->dp_mode_; 
                    stream & dpProps_->dp_F_; 
                }
                else
                    stream & b;
                b = false;
                if (energies_) {
                    b = true;
                    stream & b;
                    stream & energies_->estrain_;
                    stream & energies_->eslip_;
                    stream & energies_->edashpot_;
                }
                else
                    stream & b;
            } else {
                bool b(false);
                stream & b;
                if (b) {
                    if (!dpProps_)
                        dpProps_ = NEWC(dpProps());
                    stream & dpProps_->dp_nratio_; 
                    stream & dpProps_->dp_sratio_; 
                    stream & dpProps_->dp_mode_; 
                    stream & dpProps_->dp_F_; 
                }
                stream & b;
                if (b) {
                    if (!energies_)
                        energies_ = NEWC(Energies());
                    stream & energies_->estrain_;
                    stream & energies_->eslip_;
                    stream & energies_->edashpot_;
                }
            }

            if (stream.getArchiveState() == ArchiveStream::Save || stream.getRestoreVersion() > 5) {
                stream & sn_tabPos_;
                stream & sn_cohres_;
            }

            if (stream.getArchiveState() == ArchiveStream::Save || stream.getRestoreVersion() > 6)
                stream & sn_por_;
                
        } else {
            // Backward compatibility 
            stream & kTran_;
            stream & E_;
            stream & kRot_;
            stream & fictForce_;
            stream & poisson_;
            stream & fric_;
            stream & sn_mode_;
            stream & sn_F_;
            stream & sn_M_;
            stream & sn_S_;
            stream & sn_BS_;
            stream & sn_TS_;
            stream & sn_rmul_;

            bool b(false);
            stream & b;
            if (b) {
                if (!dpProps_)
                    dpProps_ = NEWC(dpProps());
                stream & dpProps_->dp_nratio_; 
                stream & dpProps_->dp_sratio_; 
                stream & dpProps_->dp_mode_; 
                stream & dpProps_->dp_F_; 
            }
            stream & b;
            if (b) {
                if (!energies_)
                    energies_ = NEWC(Energies());
                stream & energies_->estrain_;
                stream & energies_->eslip_;
                stream & energies_->edashpot_;
            }
            stream & b;
            if (b) {
                int vi = 0;
                stream & vi;
                sn_state_ = abs(vi);
                double val = 0.0;
                stream & val;
                tenTable_[0].rx() = val;
                val = 0.0;
                stream & val;
                cohTable_[0].rx() = val;
                stream & sn_fa_;
                stream & sn_mcf_;
                stream & val;
                stream & val;
                stream & val;
                stream & val;
                Quat q;
                stream & q;
                stream & val;
                stream & val;
            }

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

            stream & sn_bmul_;
            stream & sn_tmul_;
            stream & userArea_;
            stream & rgap_;

            if (stream.getRestoreVersion() > 1) 
                stream & kRatio_;

            if (stream.getRestoreVersion() > 2) {
                uint v;
                stream & v;
                poisOffDiag_ = v == 0 ? false : true;
            }

            if (stream.getArchiveState() == ArchiveStream::Save || stream.getRestoreVersion() > 3) 
                stream & forceSet_;

        }
    }

    void ContactModelRBSN::copy(const ContactModel *cm) {
        // Copy all of the contact model properties. Used in the CMAT 
        // when a new contact is created. 
        ContactModelMechanical::copy(cm);
        const ContactModelRBSN *in = dynamic_cast<const ContactModelRBSN*>(cm);
        if (!in) throw std::runtime_error("Internal error: contact model dynamic cast failed.");
        fictForce_ = in->fictForce_;
        sn_F_ = in->sn_F_;
        sn_sdisp_ = in->sn_sdisp_;
        sn_M_ = in->sn_M_;      
        kRot_ = in->kRot_;
        kTran_ = in->kTran_;
        kRatio_ = in->kRatio_;
        E_ = in->E_;
        poisson_ = in->poisson_;
        fric_ = in->fric_;
        sn_bmul_ = in->sn_bmul_;
        sn_tmul_ = in->sn_tmul_;
        sn_rmul_ = in->sn_rmul_;
        userArea_ = in->userArea_;
        rgap_ = in->rgap_;
        sn_fa_ = in->sn_fa_;
        sn_mcf_ = in->sn_mcf_;
        sn_dil_ = in->sn_dil_;
        sn_dilzero_ = in->sn_dilzero_;
        transTen_ = in->transTen_;
        sn_elong_ = in->sn_elong_;
        sn_ndisp_ = in->sn_ndisp_;
        sn_mode_ = in->sn_mode_;
        sn_state_ = in->sn_state_;
        poisOffDiag_ = in->poisOffDiag_;
        sn_S_ = in->sn_S_;
        sn_BS_ = in->sn_BS_;
        sn_TS_ = in->sn_TS_;
        forceSet_ = in->forceSet_;
        sn_heal_ = in->sn_heal_;
        tenTable_ = in->tenTable_;
        cohTable_ = in->cohTable_;
        sn_por_ = in->sn_por_;
        if (in->hasDamping()) {
            if (!dpProps_)
                dpProps_ = NEWC(dpProps());
            dp_nratio(in->dp_nratio()); 
            dp_sratio(in->dp_sratio()); 
            dp_mode(in->dp_mode()); 
            dp_F(in->dp_F()); 
        }
        if (in->hasEnergies()) {
            if (!energies_)
                energies_ = NEWC(Energies());
            estrain(in->estrain());
            eslip(in->eslip());
            edashpot(in->edashpot());
        }
        inheritanceField(in->inheritanceField());
        effectiveTranslationalStiffness(in->effectiveTranslationalStiffness());
        effectiveRotationalStiffness(in->effectiveRotationalStiffness());
    }


    QVariant ContactModelRBSN::getProperty(uint i,const IContact *con) const {
        // Return the property. The IContact pointer is provided so that 
        // more complicated properties, depending on contact characteristics,
        // can be calcualted. 
        QVariant var;
        switch (i) {
        case kwKn:       return kTran_;
        case kwKs:       return kTran_ / kRatio_;
        case kwKrot:     var.setValue(kRot_); return var;
        case kwFric:     return fric_;
        case kwBMul:     return sn_bmul_;
        case kwTMul:     return sn_tmul_;
        case kwSNMode:   return sn_mode_;
        case kwSNF:      var.setValue(sn_F_); return var;
        case kwSNM:      var.setValue(sn_M_); return var;
        case kwSNS:      return sn_S_;
        case kwSNBS:     return sn_BS_;
        case kwSNTS:     return sn_TS_;
        case kwPoisDiag: return poisOffDiag_ == false ? 0 : 1;
        case kwSNRMul:   return sn_rmul_;
        case kwSNRadius: {
            const IContactMechanical *c(convert_getcast<IContactMechanical>(con));
            if (!c) return 0.0;
            double Cmax1 = c->getEnd1Curvature().y();
            double Cmax2 = c->getEnd2Curvature().y();
            if (!userArea_)
                return sn_rmul_ * 1.0 / std::max(Cmax1, Cmax2);
            else {
#ifdef THREED
                double rad = std::sqrt(userArea_ / dPi);
#else
                double rad = userArea_ / 2.0;
#endif
                return rad;
            }
                
        }
        case kwEmod:      return E_;
        case kwKRatio:    return 1.0;
        case kwDpNRatio:  return dpProps_ ? dpProps_->dp_nratio_ : 0;
        case kwDpSRatio:  return dpProps_ ? dpProps_->dp_sratio_ : 0;
        case kwDpMode:    return dpProps_ ? dpProps_->dp_mode_ : 0;
        case kwDpF: {
                dpProps_ ? var.setValue(dpProps_->dp_F_) : var.setValue(DVect(0.0));
                return var;
            }
        case kwSNState:     return sn_state_;
        case kwSNTStr:      return sn_Ten();
        case kwSNSStr: {
            const IContactMechanical *c(convert_getcast<IContactMechanical>(con));
            if (!c) return 0.0;
            double area = computeGeomData(c).x();
            return shearStrength(area);
        }
        case kwSNCoh:       return cohTable_[0].x();
        case kwSNFa:        return std::atan(sn_fa_)/dDegrad;
        case kwSNMCF:       return sn_mcf_;
        case kwSNSig: {
            const IContactMechanical *c(convert_getcast<IContactMechanical>(con));
            if (!c) return 0.0;
            return SMax(c).x();
        }
        case kwSNTau: {
            const IContactMechanical *c(convert_getcast<IContactMechanical>(con));
            if (!c) return 0.0;
            return SMax(c).y();
        }
        case kwSNArea: {
                if (userArea_) return userArea_;
                const IContactMechanical *c(convert_getcast<IContactMechanical>(con));
                if (!c)
                    return 0.0;
                return computeGeomData(c).x();
            }
        case kwUserArea:
            return userArea_;
        case kwRGap:
            return rgap_;
        case kwPForce:  var.setValue(fictForce_); return var;
        case kwPois: return poisson_;
        case kwSnCohRes :   return sn_cohres_;
        //case kwSnTenRes :   return sn_tenres();
        case kwSnDil :      return std::atan(sn_dil_)/dDegrad;
        case kwSnDilZ :     return sn_dilzero_;
        case kwSnNormDisp:  return sn_ndisp_;
        case kwSnShearDisp:  var.setValue(sn_sdisp_); return var;
        case kwSnCohDc :    return sn_cohdc();
        case kwSnTenDc :    return sn_tendc();
        case kwSnHeal :     return sn_heal_;
        case kwTenTable:    
            if (sn_tabPos_ < tenTable_.size()) 
                if (sn_tabPos_ == 0)
                    var.setValue(DVect2(1,0));
                else
                    var.setValue(tenTable_[sn_tabPos_]);
            else
                var.setValue(DVect2(0,0));
            return var;
        case kwCohTable:
            if (sn_tabPos_ < cohTable_.size()) 
                if (sn_tabPos_ == 0)
                    var.setValue(DVect2(1,0));
                else
                    var.setValue(cohTable_[sn_tabPos_]);
            else
                var.setValue(DVect2(0,0));
            return var;
        case kwTablePos: return sn_tabPos_+1;
        case kwPorP: return sn_por_;
        case kwStressNorm: {
                const IContactMechanical* c(convert_getcast<IContactMechanical>(con));
                if (!c)
                    return 0.0;
                return SMax(c).x() + sn_por_;
            }
        }
        assert(0);
        return QVariant();
    }

    bool ContactModelRBSN::getPropertyGlobal(uint i) const {
        // Returns whether or not a property is held in the global axis system (TRUE)
        // or the local system (FALSE). Used by the plotting logic.
        switch (i) {
        case kwSNF:   
        case kwSNM:
        case kwDpF:
            return false;
        }
        return true;
    }

    bool ContactModelRBSN::setProperty(uint i,const QVariant &v,IContact *) {
        // Set a contact model property. Return value indicates that the timestep
        // should be recalculated. 
        dpProps dp;
        switch (i) {
        case kwKn: {
                if (!v.canConvert<double>())
                    throw Exception("kn must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative kn not allowed.");
                kTran_ = val;
                return true;
            }
        case kwKs: {
                if (!v.canConvert<double>())
                    throw Exception("ks must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative ks not allowed.");
                if (!kTran_)
                    kTran_ = val;  
                else
                    kRatio_ = kTran_ / val;
                return true;
            }
        case kwKrot: {
                DAVect val(0.0);
#ifdef TWOD               
                if (!v.canConvert<DAVect>() && !v.canConvert<double>())
                    throw Exception("krot must be an angular vector.");
                if (v.canConvert<DAVect>())
                    val = DAVect(v.value<DAVect>());
                else
                    val = DAVect(v.toDouble());
#else
                if (!v.canConvert<DAVect>() && !v.canConvert<DVect>())
                    throw Exception("krot must be an angular vector.");
                if (v.canConvert<DAVect>())
                    val = DAVect(v.value<DAVect>());
                else
                    val = DAVect(v.value<DVect>());
#endif
                kRot_ = val;
                return false;
            }
        case kwFric: {
                if (!v.canConvert<double>())
                    throw Exception("fric must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative fric not allowed.");
                fric_ = val;
                //if (!sn_fa_)
                //    sn_fa_ = fric_;
                return false;
            }
        case kwBMul: {
                if (!v.canConvert<double>())
                    throw Exception("sn_bmul must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative sn_bmul not allowed.");
                sn_bmul_ = val;
                return false;
            }
        case kwTMul: {
                if (!v.canConvert<double>())
                    throw Exception("sn_tmul must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative st_bmul not allowed.");
                sn_tmul_ = val;
                return false;
            }
        case kwSNMode: {
                if (!v.canConvert<uint>())
                    throw Exception("sn_mode must be 0 (absolute) or 1 (incremental).");
                double val(v.toUInt());
                if (val>1)
                    throw Exception("sn_mode must be 0 (absolute) or 1 (incremental).");
                sn_mode_ = val;
                return false;
            }
        case kwSNRMul: {
                if (!v.canConvert<double>())
                    throw Exception("rmul must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative rmul not allowed.");
                sn_rmul_ = val;
                return false;
            }
        case kwSNF: {
                if (!v.canConvert<DVect>())
                    throw Exception("sn_force must be a vector.");
                DVect val(v.value<DVect>());
                sn_F_ = val;
                return false;
            }
        case kwSNM: {
                DAVect val(0.0);
#ifdef TWOD               
                if (!v.canConvert<DAVect>() && !v.canConvert<double>())
                    throw Exception("res_moment must be an angular vector.");
                if (v.canConvert<DAVect>())
                    val = DAVect(v.value<DAVect>());
                else
                    val = DAVect(v.toDouble());
#else
                if (!v.canConvert<DAVect>() && !v.canConvert<DVect>())
                    throw Exception("res_moment must be an angular vector.");
                if (v.canConvert<DAVect>())
                    val = DAVect(v.value<DAVect>());
                else
                    val = DAVect(v.value<DVect>());
#endif
                sn_M_ = val;
                return false;
            }
        case kwDpNRatio: {
                if (!v.canConvert<double>())
                    throw Exception("dp_nratio must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative dp_nratio not allowed.");
                if (val == 0.0 && !dpProps_)
                    return false;
                if (!dpProps_)
                    dpProps_ = NEWC(dpProps());
                dpProps_->dp_nratio_ = val; 
                return true;
            }
        case kwDpSRatio: {
                if (!v.canConvert<double>())
                    throw Exception("dp_sratio must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative dp_sratio not allowed.");
                if (val == 0.0 && !dpProps_)
                    return false;
                if (!dpProps_)
                    dpProps_ = NEWC(dpProps());
                dpProps_->dp_sratio_ = val;
                return true;
            }
        case kwDpMode: {
                if (!v.canConvert<int>())
                    throw Exception("The viscous mode dp_mode must be 0, 1, 2, or 3.");
                int val(v.toInt());
                if (val == 0 && !dpProps_)
                    return false;
                if (val < 0 || val > 3)
                    throw Exception("The viscous mode dp_mode must be 0, 1, 2, or 3.");
                if (!dpProps_)
                    dpProps_ = NEWC(dpProps());
                dpProps_->dp_mode_ = val;
                return false;
            }
        case kwDpF: {
                if (!v.canConvert<DVect>())
                    throw Exception("dp_force must be a vector.");
                DVect val(v.value<DVect>());
                if (val.fsum() == 0.0 && !dpProps_)
                    return false;
                if (!dpProps_)
                    dpProps_ = NEWC(dpProps());
                dpProps_->dp_F_ = val;
                return false;
            }
        case kwSNTStr: {
                if (!v.canConvert<double>())
                    throw Exception("sn_ten must be a double.");
                double val(v.toDouble());
                if (val < 0.0)
                    throw Exception("Negative sn_ten not allowed.");
                tenTable_[0].rx() = val;
                return false;
            }
        case kwSNCoh: {
                if (!v.canConvert<double>())
                    throw Exception("sn_coh must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative pb_coh not allowed.");
                cohTable_[0].rx() = val;
                return false;
            }
        case kwSNFa: {
                if (!v.canConvert<double>())
                    throw Exception("sn_fa must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative sn_fa not allowed.");
                if (val >= 90.0)
                    throw Exception("sn_fa must be lower than 90.0 degrees.");
                sn_fa_ = std::tan(val*dDegrad);
                if (!fric_)
                    fric_ = sn_fa_;
                return false;
            }
        case kwSNMCF: {
                if (!v.canConvert<double>())
                    throw Exception("sn_mcf must be a double.");
                double val(v.toDouble());
                if (val<0.0)
                    throw Exception("Negative sn_mcf not allowed.");
                if (val > 1.0)
                    throw Exception("sn_mcf must be lower or equal to 1.0.");
                sn_mcf_ = val;
                return false;
            }
        case kwSNArea:
        case kwUserArea: {
                if (!v.canConvert<double>())
                    throw Exception("area must be a double.");
                double val(v.toDouble());
                if (val < 0.0)
                    throw Exception("Negative area not allowed.");
                if (userArea_ && val) {
                    double rat = userArea_ / val;
                    kTran_ *=  rat;
                    kRot_ *= rat;
                }
                userArea_ = val;
                return true;
            }
        case kwRGap: {
                if (!v.canConvert<double>())
                    throw Exception("Reference gap must be a double.");
                double val(v.toDouble());
                rgap_ = val;  
                return false;
            }
        case kwPois: {
                if (!v.canConvert<double>())
                    throw Exception("Reference poisson must be a double.");
                double val(v.toDouble());
                poisson_ = val;
                return false;
            }
        case kwPoisDiag: {
                if (!v.canConvert<uint>())
                    throw Exception("Reference diagonal must be an integer.");
                uint b(v.toUInt());
                if (b > 1)
                    throw Exception("diagonal must be 0 (diagonal terms only) or 1 (all terms).");
                poisOffDiag_ = b == 0 ? false : true;
                return false;
            }
        case kwSnCohRes: {
                bool ok;
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("sn_cohres must be a positive double.");
                sn_cohres_ = val;
                return false;
            }
        case kwSnDil: {
                bool ok;
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("sn_dil must be a positive double.");
                sn_dil_ = std::tan(val*dDegrad); 
                return false;
            }
        case kwSnDilZ: {
                bool ok;
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("sn_dil_zero must be a positive double.");
                sn_dilzero_ = val; 
                return false;
            }
        case kwSnNormDisp: {
                bool ok;
                double val(v.toDouble(&ok));
                if (!ok)
                    throw Exception("sn_ndisp must be a positive double.");
                sn_ndisp_ = val; 
                return false;
            }
        case kwSnShearDisp: {
                if (!v.canConvert<DVect2>())
                    throw Exception("sn_sdisp must be a vector.");
                DVect2 val(v.value<DVect2>());
                sn_sdisp_ = val;
                return false;
            }
        case kwSnCohDc: {
                bool ok;
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("sn_cohdc must be a positive double.");
                if (cohTable_.size() == 1)
                    cohTable_.push_back(DVect2(0,val));
                else {
                    cohTable_.back().ry() = val;
                    std::sort(cohTable_.begin(),cohTable_.end(), [](const DVect2& a, const DVect2& b) { return a.y() < b.y(); } );
                    while (cohTable_.back().y() > val)
                        cohTable_.pop_back();
                }
                if (sn_state_ == 0)
                    sn_state_ = 6;
                return false;
            }
        case kwSnTenDc: {
                bool ok;
                double val(v.toDouble(&ok));
                if (!ok || val<0.0)
                    throw Exception("sn_tendc must be a positive double.");
                if (tenTable_.size() == 1)
                    tenTable_.push_back(DVect2(0,val));
                else {
                    tenTable_.back().ry() = val;
                    std::sort(tenTable_.begin(),tenTable_.end(), [](const DVect2& a, const DVect2& b) { return a.y() < b.y(); } );
                    while (tenTable_.back().y() > val)
                        tenTable_.pop_back();
                }
                return false;
            }
        case kwSnHeal: {
                bool ok;
                int val(v.toInt(&ok));
                if (!ok || (val != 0 && val != 1))
                    throw Exception("sn_heal must be 0 or 1.");
                sn_heal_ = val == 0 ? false : true; 
                return false;
            }
        case kwTenTable: {
                if (!v.canConvert<DVect2>())
                    throw Exception("sn_tentab entry must be a strength and distance.");
                DVect2 vl(v.value<DVect2>());
                if (vl.x() < 0 || vl.y() < 0)
                    throw Exception("The sn_tentab entries must be positive.");
                if (vl.y() == 0)
                    throw Exception("Use sn_ten to set the tensile strength at 0 elongation.");
                tenTable_.push_back(vl);
                std::sort(tenTable_.begin(),tenTable_.end(), [](const DVect2& a, const DVect2& b) { return a.y() < b.y(); } );
            }
            return false;
        case kwCohTable: {
                if (!v.canConvert<DVect2>())
                    throw Exception("sn_cohtab entry must be a strength and distance.");
                DVect2 vl(v.value<DVect2>());
                if (vl.x() < 0 || vl.y() < 0)
                    throw Exception("The sn_cohtab entries must be positive.");
                if (vl.y() == 0)
                    throw Exception("Use sn_coh to set the cohesive strength at 0 elongation.");
                cohTable_.push_back(vl);
                std::sort(cohTable_.begin(),cohTable_.end(), [](const DVect2& a, const DVect2& b) { return a.y() < b.y(); } );
            }
            return false;
        case kwTablePos: {
                bool ok;
                int val(v.toInt(&ok));
                if (!ok || val < 1)
                    throw Exception("sn_tabpos must be 1 or greater.");
                sn_tabPos_ = val - 1;
                return false;
            }
        case kwPorP: {
                if (!v.canConvert<double>())
                    throw Exception("sn_porp must be a double.");
                double val = v.toDouble();
                sn_por_ = val;
                return true;
            }
        }
        return false;
    }

    bool ContactModelRBSN::getPropertyReadOnly(uint i) const {
        // Returns TRUE if a property is read only or FALSE otherwise. 
        switch (i) {
        case kwDpF:
        case kwSNS:
        case kwSNBS:
        case kwSNTS:
        case kwEmod:
        case kwKRatio:
        case kwSNState:
        case kwSNRadius:
        case kwSNSStr:
        case kwSNSig:
        case kwSNTau:
        case kwPForce:
        case kwStressNorm:
            return true;
        default:
            break;
        }
        return false;
    }

    bool ContactModelRBSN::supportsInheritance(uint i) const {
        // Returns TRUE if a property supports inheritance or FALSE otherwise. 
        switch (i) {
        case kwKn:
        case kwKs:
        case kwFric:
            return true;
        default:
            break;
        }
        return false;
    }

    QString  ContactModelRBSN::getMethodArguments(uint i) const {
        // Return a list of contact model method argument names. 
        switch (i) {
        case kwAssignStiffness:
            return "kn,kratio";
        case kwStiffness:
            return "emod,poisson";
        case kwBond:
            return "gap";
        case kwUnbond:
            return "gap";
        case kwArea:
        case kwResetDisp:
            return QString();
        }
        assert(0);
        return QString();
    }

    bool ContactModelRBSN::setMethod(uint i,const QVector<QVariant> &vl,IContact *con) {
        // Apply the specified method. 
        IContactMechanical *c(convert_getcast<IContactMechanical>(con));
        switch (i) {
        case kwAssignStiffness: {
                poisson_ = 0.0;
                if (vl.at(0).isNull()) 
                    throw Exception("Argument kn must be specified with method assign-stiffness in contact model %1.",getName());
                double knpa = vl.at(0).toDouble();
                if (knpa<=0.0)
                    throw Exception("Negative or zero kn not allowed in contact model %1.",getName());
                if (vl.at(1).isNull()) 
                    throw Exception("Argument kratio must be specified with method assign-stiffness in contact model %1.",getName());
                kRatio_ = vl.at(1).toDouble();
                if (kRatio_<0.0) {
                    kRatio_ = 0.0;
                    throw Exception("Negative kratio not allowed in contact model %1.",getName());
                }
                const IContactMechanical *mc = convert_getcast<IContactMechanical>(con);
                assert(mc);
                std::vector<DVect> pts;
                mc->getJointGeometry(&pts);
                double area = 0.0;
#ifdef THREED
                // Step 1: get centroid and area
                for (int i=1; i<pts.size()-1; ++i) {
                    double a = (pts[0] - pts[i]).mag();
                    double b = (pts[0] - pts[i+1]).mag();
                    double c = (pts[i] - pts[i+1]).mag();
                    double la = 0.0;
                    if (b > a)
                        std::swap(a,b);
                    if (c > a)
                        std::swap(a,c);
                    if (c > b)
                        std::swap(b,c);
                    if (c - (a - b) >= 0) 
                        la = 0.25 * sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c)));
                    area += la;
                }
#else               
                // Assume unit thickness in the out of plane direction
                area = (pts[1] - pts[0]).mag();
#endif
                userArea_ = area;
                kTran_ = knpa * area;
                E_ = kTran_ / area;
                kRot_ = DAVect(0.0);
                setInheritance(1,false);
                setInheritance(2,false);
                sn_mode_ = 1.0;
                return true;
            }
        case kwStiffness: {
                FP_S;
                poisson_ = 0.0;
                if (vl.at(0).isNull()) 
                    throw Exception("Argument emod must be specified with method compute-stiffness in contact model %1.",getName());
                E_ = vl.at(0).toDouble();
                if (E_<=0.0)
                    throw Exception("Negative or zero emod not allowed in contact model %1.",getName());
                if (vl.at(1).isNull()) 
                    throw Exception("Argument poisson must be specified with method compute-stiffness in contact model %1.",getName());
                poisson_ = vl.at(1).toDouble();
                if (poisson_ < 0.0) {
                    poisson_ = 0.0;
                    throw Exception("Negative poisson not allowed in contact model %1.",getName());
                }
                const IBody *b1 = con->getEnd1()->getIBody();
                const IBody *b2 = con->getEnd2()->getIBody();
                //double vol1 = b1->getVolume();
                //double vol2 = b2->getVolume();
                //if (std::max(vol1,vol2) > 10.*std::min(vol1,vol2))
                //    poisson_ = 0.0;
                DVect pos1 = toDVect(b1->getIThing()->getLocation());
                DVect pos2 = toDVect(b2->getIThing()->getLocation()) + con->getOffSet();
                double dist = (pos1-pos2).mag();
                if (con->withWall())
                    dist = (pos1 - con->getPosition()).mag();
                double tol = std::max(pos1.abs().maxComp(),pos2.abs().maxComp())*limits<double>::epsilon()*1000;
                if (dist < tol) {
                    poisson_ = 0;
                    userArea_ = 0;
                    kTran_ = 0;
                    kRot_.fill(0);
                    return true;
                }
                const IContactMechanical *mc = convert_getcast<IContactMechanical>(con);
                assert(mc);
                std::vector<DVect> pts;
                FP_S;
                mc->getJointGeometry(&pts);
                FP_S;
                double area = 0.0;
                DAVect inertia(0.0);
#ifdef THREED
                // Step 1: get centroid and area
                DVect cm(0.0);
                for (int i=1; i<pts.size()-1; ++i) {
                    DVect lcm = (pts[0] + pts[i] + pts[i+1])/3.0;
                    double a = (pts[0] - pts[i]).mag();
                    double b = (pts[0] - pts[i+1]).mag();
                    double c = (pts[i] - pts[i+1]).mag();
                    double la = 0.0;
                    if (b > a)
                        std::swap(a,b);
                    if (c > a)
                        std::swap(a,c);
                    if (c > b)
                        std::swap(b,c);
                    if (c - (a - b) >= 0) 
                        la = 0.25 * sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c)));
                    cm += lcm * la;
                    area += la;
                }
                FP_S;
                if (area == 0.0) {
                    poisson_ = 0;
                    userArea_ = 0;
                    kTran_ = 0;
                    kRot_.fill(0);
                    return true;
                }
                cm /= area;
                FP_S;
                // Step 2 - center it and put in the local system
                for (int i=0; i<pts.size(); ++i) {
                    pts[i] -= cm;
                    pts[i] = con->getLocalSystem().toLocal(pts[i]);
                }
                // Step 3: compute the polar inertia
                for (int i=0; i<pts.size(); ++i) {
                    int j = i < pts.size()-1 ? i+1 : 0;
                    double xi = pts[i].y();
                    double xip1 = pts[j].y();
                    double yi = pts[i].z();
                    double yip1 = pts[j].z();
                    double frnt = (xi*yip1-xip1*yi);
                    inertia.ry() += frnt*(xi*xi+xi*xip1+xip1*xip1);
                    inertia.rz() += frnt*(yi*yi+yi*yip1+yip1*yip1);
                }
                inertia.ry() = std::abs(inertia.y() / 12.);
                inertia.rz() = std::abs(inertia.z() / 12.);
                inertia.rx() = inertia.y() + inertia.z();

#else           
                // Assume unit thickness in the out of plane direction
                area = (pts[1] - pts[0]).mag();
                inertia.rz() = area*area*area/12.;
#endif
                userArea_ = area;
                kTran_ = E_ * area / dist;
                kRot_ = inertia *E_ / dist;
                setInheritance(1,false);
                setInheritance(2,false);
                sn_mode_ = 1.0;
                return true;
            }
        case kwBond: {
                if (sn_state_ == 3) return false;
                double mingap = -1.0 * limits<double>::max();
                double maxgap = 0;
                if (vl.at(0).canConvert<Double>())
                    maxgap = vl.at(0).toDouble();
                else if (vl.at(0).canConvert<DVect2>()) {
                    DVect2 value = vl.at(0).value<DVect2>();
                    mingap = value.minComp();
                    maxgap = value.maxComp();
                }
                else if (!vl.at(0).isNull())
                    throw Exception("gap value %1 not recognized in method bond in contact model %2.", vl.at(1), getName());
                double gap = c->getGap();
                if (gap >= mingap && gap <= maxgap) {
                    sn_state_ = 3;
                    sn_mode_ = 1;
                    return true;
                }
                return false;
            }
        case kwUnbond: {
                if (sn_state_ == 0) return false;
                double mingap = -1.0 * limits<double>::max();
                double maxgap = 0;
                if (vl.at(0).canConvert<double>())
                    maxgap = vl.at(0).toDouble();
                else if (vl.at(0).canConvert<DVect2>()) {
                    DVect2 value = vl.at(0).value<DVect2>();
                    mingap = value.minComp();
                    maxgap = value.maxComp();
                }
                else if (!vl.at(0).isNull())
                    throw Exception("gap value %1 not recognized in method unbond in contact model %2.", vl.at(0), getName());
                double gap = c->getGap();
                if (gap >= mingap && gap <= maxgap) {
                    sn_state_ = 0;
                    return true;
                }
                return false;
            }
        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 kwResetDisp:
            sn_ndisp_ = 0.0;
            for (int i=1; i<dim; ++i)
                sn_sdisp_.rdof(i) = 0;
            break;
        }
        return false;
    }

    double ContactModelRBSN::getEnergy(uint i) const {
        // Return an energy value. 
        double ret(0.0);
        if (!energies_)
            return ret;
        switch (i) {
        case kwEStrain:    return energies_->estrain_;
        case kwESlip:      return energies_->eslip_;
        case kwEDashpot:   return energies_->edashpot_;
        }
        assert(0);
        return ret;
    }

    bool ContactModelRBSN::getEnergyAccumulate(uint i) const {
        // Returns TRUE if the corresponding energy is accumulated or FALSE otherwise.
        switch (i) {
        case kwEStrain:   return false;
        case kwESlip:     return true;
        case kwEDashpot:  return true;
        }
        assert(0);
        return false;
    }

    void ContactModelRBSN::setEnergy(uint i,const double &d) {
        // Set an energy value. 
        if (!energies_) return;
        switch (i) {
        case kwEStrain:    energies_->estrain_ = d;   return;  
        case kwESlip:      energies_->eslip_   = d;   return;
        case kwEDashpot:   energies_->edashpot_= d;   return;
        }
        assert(0);
        return;
    }

    bool ContactModelRBSN::validate(ContactModelMechanicalState *state,const double &) {
        // Validate the / Prepare for entry into ForceDispLaw. The validate function is called when:
        // (1) the contact is created, (2) a property of the contact that returns a true via
        // the setProperty method has been modified and (3) when a set of cycles is executed
        // via the {cycle N} command.
        // Return value indicates contact activity (TRUE: active, FALSE: inactive).
        assert(state);
        const IContactMechanical *c = state->getMechanicalContact(); 
        assert(c);

        if (state->trackEnergy_)
            activateEnergy();

        if (inheritanceField_ & KnMask)
            updateKn(c);
        if (inheritanceField_ & KsMask)
            updateKs(c);
        if (inheritanceField_ & FricMask)
            updateFric(c);

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

    static const QString knstr("kn");
    bool ContactModelRBSN::updateKn(const IContactMechanical *con) {
        assert(con);
        QVariant v1 = con->getEnd1()->getProperty(knstr);
        QVariant v2 = con->getEnd2()->getProperty(knstr);
        if (!v1.isValid() || !v2.isValid())
            return false;
        double kn1 = v1.toDouble();
        double kn2 = v2.toDouble();
        double val = kTran_;
        if (kn1 && kn2)
            kTran_ = kn1*kn2/(kn1+kn2);
        else if (kn1)
            kTran_ = kn1;
        else if (kn2)
            kTran_ = kn2;
        return ( (kTran_ != val) );
    }

    static const QString ksstr("ks");
    bool ContactModelRBSN::updateKs(const IContactMechanical *con) {
        assert(con);
        QVariant v1 = con->getEnd1()->getProperty(ksstr);
        QVariant v2 = con->getEnd2()->getProperty(ksstr);
        if (!v1.isValid() || !v2.isValid())
            return false;
        double ks1 = v1.toDouble();
        double ks2 = v2.toDouble();
        double val = kTran_;
        if (ks1 && ks2)
            kTran_ = ks1*ks2/(ks1+ks2);
        else if (ks1)
            kTran_ = ks1;
        else if (ks2)
            kTran_ = ks2;
        return ( (kTran_ != val) );
    }

    static const QString fricstr("fric");
    bool ContactModelRBSN::updateFric(const IContactMechanical *con) {
        assert(con);
        QVariant v1 = con->getEnd1()->getProperty(fricstr);
        QVariant v2 = con->getEnd2()->getProperty(fricstr);
        if (!v1.isValid() || !v2.isValid())
            return false;
        double fric1 = std::max(0.0,v1.toDouble());
        double fric2 = std::max(0.0,v2.toDouble());
        double val = fric_;
        fric_ = std::min(fric1,fric2);
        return ( (fric_ != val) );
    }

    bool ContactModelRBSN::endPropertyUpdated(const QString &name,const IContactMechanical *c) {
        // The endPropertyUpdated method is called whenever a surface property (with a name
        // that matches an inheritable contact model property name) of one of the contacting
        // pieces is modified. This allows the contact model to update its associated
        // properties. The return value denotes whether or not the update has affected
        // the time step computation (by having modified the translational or rotational
        // tangent stiffnesses). If true is returned, then the time step will be recomputed.  
        assert(c);
        QStringList availableProperties = getProperties().simplified().replace(" ","").split(",",QString::SkipEmptyParts);
        QRegExp rx(name,Qt::CaseInsensitive);
        int idx = availableProperties.indexOf(rx)+1;
        bool ret=false;

        if (idx<=0)
            return ret;
         
        switch(idx) {
        case kwKn:  { //kn
                if (inheritanceField_ & KnMask)
                    ret = updateKn(c);
                break;
            }
        case kwKs:  { //ks
                if (inheritanceField_ & KsMask)
                    ret =updateKs(c);
                break;
            }
        case kwFric:  { //fric
                if (inheritanceField_ & FricMask)
                    updateFric(c);
                break;
            }
        }
        return ret;
    }

    ContactModelRBSN::StiffData ContactModelRBSN::computeStiffData(ContactModelMechanicalState *state) const {
        // Update contact data
        //double Cmin1 = state->end1Curvature_.x();
        double Cmax1 = state->end1Curvature_.y();
        double Cmax2 = state->end2Curvature_.y();
        double br = sn_rmul_ * 1.0 / std::max(Cmax1, Cmax2);
        if (userArea_)
#ifdef THREED
            br = std::sqrt(userArea_ / dPi);
#else
            br = userArea_ / 2.0;
#endif
        StiffData ret;
        ret.reff_ = br;
        ret.trans_ = DVect2(kTran_,kTran_/kRatio_);
        ret.ang_ = kRot_;
        return ret;
    }

    void ContactModelRBSN::updateStiffness(ContactModelMechanicalState *state) {
        // first compute stiffness data
        StiffData stiff = computeStiffData(state);
        // Now calculate effective stiffness
        DVect2 retT = stiff.trans_;
        // correction if viscous damping active
        if (dpProps_) {
            DVect2 correct(1.0);
            if (dpProps_->dp_nratio_)
                correct.rx() = sqrt(1.0+dpProps_->dp_nratio_*dpProps_->dp_nratio_) - dpProps_->dp_nratio_;
            if (dpProps_->dp_sratio_)
                correct.ry() = sqrt(1.0+dpProps_->dp_sratio_*dpProps_->dp_sratio_) - dpProps_->dp_sratio_;
            retT /= (correct*correct);
        }
        effectiveTranslationalStiffness_ = retT;
        // Effective rotational stiffness (bending and twisting)
        effectiveRotationalStiffness_ = stiff.ang_;
    }
     
    bool ContactModelRBSN::forceDisplacementLaw(ContactModelMechanicalState *state,const double &timestep) {
        assert(state);

        if (state->activated()) {
            // The contact was just activated from an inactive state
            // Trigger the FISH callback if one is hooked up to the 
            // contact_activated event.
            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]);
            }
        }
        updateStiffness(state);
        // accumulate shear displacement for dilation
        sn_ndisp_ += state->relativeTranslationalIncrement_.x();
        DVect shearInc =  state->relativeTranslationalIncrement_;
        shearInc.rx() = 0;
        sn_sdisp_.ry() += shearInc.mag();

        if (isBonded()) return FDLawBonded(state, timestep);
        else return FDLawUnBonded(state, timestep);
            
    }
    
    bool ContactModelRBSN::thermalCoupling(ContactModelMechanicalState*, ContactModelThermalState* ts, IContactThermal*, const double&) {
        // Account for thermal expansion in incremental mode
        if (sn_mode_ == 0 || ts->gapInc_ == 0.0) return false;
        DVect finc(0.0);
        finc.rx() = kTran_ * ts->gapInc_;
        sn_F_ -= finc;
        return true;
    }

    bool ContactModelRBSN::FDLawBonded(ContactModelMechanicalState *state, const double &timestep) {
        // initialize ... get the geometry information 
        DVect3 geom = computeGeomData(state->getMechanicalContact());
        double area = geom.x();
        double bi = geom.y();
        double br = geom.z();
        double kn = kTran_;
        double ks = kn / kRatio_;
        double kb = kRot_.z();
#if DIM==3
        kb = std::sqrt(kb*kb + kRot_.y()*kRot_.y());
        double kt = kRot_.x();
#else
        double kt = 0.0;
#endif

        DVect totalForce = sn_F_ + fictForce_;
        
        //double nsmax0 = -(totalForce.x() / area) + sn_mcf_* sqrt(sn_M_.y()*sn_M_.y() + sn_M_.z()*sn_M_.z()) * br / bi;
        
        // Relative translational/rotational displacement increments
        DVect  trans = state->relativeTranslationalIncrement_;
        DAVect ang = state->relativeAngularIncrement_;

        // Store previous force and moment
        DVect  sn_F_old = totalForce;
        sn_F_old.rx() -= sn_por_ * area;
        DAVect sn_M_old = sn_M_;

        DVect theStiff(ks);
        theStiff.rx() = kn;
        sn_F_ -= trans * theStiff;
        sn_M_ -= ang * kRot_;
        if (poisson_ != 0.0) {
            const IContact *con = state->getContact();
            const IBody *b1 = con->getEnd1()->getIBody();
            const IBody *b2 = con->getEnd2()->getIBody();
#ifdef THREED
            std::array<double,6> stress11 = {0,0,0,0,0,0};
            std::array<double,6> stress22 = {0,0,0,0,0,0};
#else
            std::array<double,3> stress11 = {0,0,0};
            std::array<double,3> stress22 = {0,0,0};
#endif
            
            double vol1 = b1->getVolume();
            double vol2 = b2->getVolume();
            b1->getOldStress(stress11);
            b2->getOldStress(stress22);
            double ms = 0.0;
            for (int i=0; i<stress11.size(); ++i)  {
                stress11[i] = (stress11[i]*vol1 + stress22[i]*vol2)/(vol1 + vol2);
                ms = std::max(ms,abs(stress11[i]));
            }
            DMatrix<dim,dim> stresst(0.0);
#ifdef THREED
            stresst.get(0,0) = -poisson_*stress11[1] - poisson_*stress11[2];
            stresst.get(1,1) = -poisson_*stress11[0] - poisson_*stress11[2];
#else
            stresst.get(0,0) = -poisson_*stress11[1];
            stresst.get(1,1) = -poisson_*stress11[0];
#endif
#ifdef THREED
            stresst.get(2,2) = -poisson_*stress11[0] - poisson_*stress11[1];
#endif
            if (poisOffDiag_) {
#ifdef THREED
                double sxy = stress11[3];
                double szx = stress11[4];
                double syz = stress11[5];
                stresst.get(0,1) = poisson_ * sxy;
                stresst.get(1,0) = stresst.get(0,1);
                stresst.get(0,2) = poisson_ * szx;
                stresst.get(2,0) = stresst.get(0,2);
                stresst.get(1,2) = poisson_ * syz;
                stresst.get(2,1) = stresst.get(1,2);
#else
                double sxy = stress11[2];
                stresst.get(0,1) = poisson_ * sxy;
                stresst.get(1,0) = stresst.get(0,1);
#endif
            }
            

            DVect norm = toVect(con->getNormal());
            DVect traction = stresst * norm * userArea_;
            DVect shear(0.0);
            shear.ry() = 1.0;
            shear = con->getLocalSystem().toGlobal(shear);
#ifdef THREED
            DVect ns = con->getLocalSystem().toGlobal(DVect(0.,0.,1.));
            fictForce_ = DVect(norm|traction,shear|traction,ns|traction);
#else
            fictForce_ = DVect(norm|traction,shear|traction);
#endif
            if (forceSet_ && ms) {
                forceSet_ = false;
                sn_F_ -= fictForce_;
            }
        }
        FP_S;
        double porForce = sn_por_ * area;
        sn_F_.rx() -= porForce;
        totalForce = sn_F_ + fictForce_;

        if (state->canFail_) {
            double dbend = sqrt(sn_M_.y()*sn_M_.y() + sn_M_.z()*sn_M_.z());
            double nsmax = -(totalForce.x() / area) + sn_mcf_*dbend * br / bi;
            bool failed = false;
            if (sn_state_ == 3 || sn_state_ == 5) {
                double compVal = sn_state_ == 3 ? tenTable_[0].x() : transTen_;
                if (nsmax >= compVal ) {
                    if (tenTable_.back().y() < limits<double>::epsilon()*100)
                        failed = true;
                    else {
                        if (sn_state_ == 3)
                            sn_elong_ = 0;
                        transTen_ = compVal;
                        sn_state_ = 4;
                    }
                } 
            }
            FP_S;

            if (sn_state_ == 4) {
                sn_elong_ += trans.x();
                sn_elong_ = std::max(0.0,sn_elong_);
                int ww = -1;
                if (sn_elong_ <= tenTable_.back().y()) {
                    for (int i=0; i<tenTable_.size(); ++i) {
                        if (tenTable_[i].y() >= sn_elong_) {
                            ww = i;
                            break;
                        }
                    }
                } else
                    ww = tenTable_.size() - 1;
                if (ww > 0) {
                    //double factor = std::min(1.0, sn_elong_ / tenTable_[ww].y());
                    double prevVal = ww == 1 ? 1 : tenTable_[ww-1].x();
                    double curVal =  tenTable_[ww].x();
                    double prevElong = tenTable_[ww-1].y();
                    double curElong = tenTable_[ww].y();
                    double slope = (curVal - prevVal)/(curElong - prevElong);
                    FP_S;
                    //y-y0 = m(x-x0)
                    double nstren = slope * (sn_elong_ - prevElong) + prevVal;
                    if (nstren <= 0)
                        failed = true;
                    else {
                        nstren *= tenTable_[0].x();
                        if (nsmax >= nstren || slope > 0) {
                            double fac = nstren / nsmax;
                            sn_F_.rx() *= fac;
#if DIM==3  
                            sn_M_.ry() *= fac;
#endif  
                            sn_M_.rz() *= fac;
                            fictForce_.rx() *= fac;
                        } else {
                            sn_state_ = 5;
                            transTen_ = -(sn_F_old.x() / area) + sn_mcf_* sqrt(sn_M_old.y()*sn_M_old.y() + sn_M_old.z()*sn_M_old.z()) * br / bi;
                        }
                    }
                }
            }
            if (sn_state_ == 6 && nsmax >= 0)
                failed = true;
            FP_S;
            if (failed) {
                // Failed in tension
                double se = strainEnergy(kn, ks, kb, kt); // bond strain energy at the onset of failure
                sn_state_ = 1;
                sn_F_.fill(0.0);
                sn_M_.fill(0.0);
                failed = true;
                fictForce_ = DVect(0.0);
                //sn_F_.rx() = -sn_tenres_ * area;
                if (cmEvents_[fBondBreak] >= 0) {
                    auto c = state->getContact();
                    std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()),
                                                         fish::Parameter((qint64)sn_state_),
                                                         fish::Parameter(nsmax),
                                                         fish::Parameter(se)
                                                       };
                    IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
                    fi->setCMFishCallArguments(c,arg,cmEvents_[fBondBreak]);
                }
            }
            FP_S;

            if (!failed) {
                /* check for shear failure */
                double dtwist = sn_M_.x();
                DVect bfs(totalForce);
                bfs.rx() = 0.0;
                double dbfs = bfs.mag();
                double ssmax = dbfs / area + sn_mcf_*std::abs(dtwist) * 0.5* br / bi;
                double ss = shearStrength(area);
                FP_S;
                if (ss < 0)
                    ss = 0;
                if (ss <= ssmax) {
                    // strength when it breaks for 
                    // Failed in shear
                    double se = strainEnergy(kn, ks, kb, kt); // bond strain energy at the onset of failure
                    sn_state_ = 2;
                    fictForce_ = DVect(0.0);
                    FP_S;
                    sn_F_ = totalForce;
                    if (cmEvents_[fBondBreak] >= 0) {
                        auto c = state->getContact();
                        std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()),
                                                             fish::Parameter((qint64)sn_state_),
                                                             fish::Parameter(ss),
                                                             fish::Parameter(se)
                                                           };
                        IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
                        fi->setCMFishCallArguments(c,arg,cmEvents_[fBondBreak]);
                    }
                    double mm = 0.0;
                    for (int i=1; i<dim; ++i)
                        mm += trans[i]*trans[i];
                    sn_sdisp_.rx() = std::sqrt(mm);
                    double crit = sn_F_.x() * fric_ + sn_cohres_ * area;
                    if (sn_cohdc() > std::numeric_limits<double>::epsilon()) { 
                        int ww = -1;
                        if (sn_sdisp_.x() <= sn_cohdc()) {
                            for (int i=0; i<cohTable_.size(); ++i) {
                                if (cohTable_[i].y() >= sn_sdisp_.x()) {
                                    ww = i;
                                    break;
                                }
                            }
                        } else 
                            ww = cohTable_.size() - 1;
                        if (ww > 0) {
                            double prevVal = ww == 1 ? 1: cohTable_[ww-1].x() ;//critBreak_ : cohTable_[ww-1].x() + sn_F_.x() * fric_;
                            double curVal =  cohTable_[ww].x();//cohTable_[ww].x() + sn_F_.x() * fric_;
                            double prevShear = cohTable_[ww-1].y();
                            double curShear = cohTable_[ww].y();
                            double slope = (curVal - prevVal)/(curShear - prevShear);
                            // should go from 0 to 1
                            double mval = slope * (sn_sdisp_.x() - prevShear) + prevVal;
                            double fact = std::max(0.,std::min(1.0,1.0 - mval));
                            assert(fact >= 0 && fact <= 1.0);
                            double theFric = fric_;
                            if (sn_fa_)
                                theFric = sn_fa_ + (fric_ - sn_fa_)*fact;
                            double theCoh = sn_Coh();
                            if (theCoh) 
                                theCoh = sn_Coh() + (sn_cohres_ - sn_Coh())*fact;
                            crit = sn_F_.x() * theFric + theCoh * geom.x();
                        }
                    }

                    // Resolve sliding. 
                    FP_S;
                    if (crit < 0)
                        crit = 0;
                    DVect sforce = sn_F_; sforce.rx() = 0.0;
                    // The is the magnitude of the shear force.
                    double sfmag = sforce.mag();
                    // Sliding occurs when the magnitude of the shear force is greater than the 
                    // critical value.
                    if (sfmag > crit) {
                        // Lower the shear force to the critical value for sliding.
                        double rat = crit / sfmag;
                        sforce *= rat;
                        sforce.rx() = sn_F_.x();
                        sn_F_ = sforce;
                        sn_S_ = true;
                    }
                    if (sn_S_) {
                        if (sn_dil_ > 0) {
                            double zdd = sn_dilzero_ != 0 ? sn_dilzero_ : limits<double>::max();
                            double usm = sn_sdisp_.y();
                            if (usm < zdd) {
                                double sInc = 0.0;
                                for (int i=1; i<dim; ++i)
                                    sInc += trans.dof(i)*trans.dof(i);
                                sInc = std::sqrt(sInc);
                                sn_F_.rx() += kTran_ * sn_dil_ * sInc; 
                            }
                        }
                    }

                    // Resolve bending
                    crit = sn_bmul_*2.1*0.25*br*std::abs(sn_F_.x()); // Jiang 2015
                    FP_S;
                    DAVect test = sn_M_;
#if DIM==3
                    test.rx() = 0.0;
#endif
                    double tmag = test.mag();
                    if (tmag > crit) {
                        // Lower the bending moment to the critical value for sliding.
                        double rat = crit / tmag;
                        test *= rat;
                        sn_BS_ = true;
                    }
                    sn_M_.rz() = test.z();
#if DIM==3
                    sn_M_.ry() = test.y();
                    // Resolve twisting
                    crit = sn_tmul_ * 0.65*fric_* br*std::abs(sn_F_.x()) ; // Jiang 2015
                    tmag = std::abs(sn_M_.x());
                    if (tmag > crit) {
                        // Lower the shear force to the critical value for sliding.
                        double rat = crit / tmag;
                        tmag = sn_M_.x() * rat;
                        sn_TS_ = true;
                    }
                    sn_M_.rx() = tmag;
                    FP_S;
#endif
                }
            }
        }
        sn_F_old.rx() += porForce;
        sn_F_.rx() += porForce;
        totalForce = sn_F_ + fictForce_;
        FP_S;

        // Account for dashpot forces if the dashpot structure has been defined. 
        if (dpProps_) {
            dpProps_->dp_F_.fill(0.0);
            double vcn(0.0), vcs(0.0);
            // Calculate the damping coefficients. 
            vcn = dpProps_->dp_nratio_ * 2.0 * sqrt((state->inertialMass_*(kn)));
            vcs = dpProps_->dp_sratio_ * 2.0 * sqrt((state->inertialMass_*(ks)));
            // First damp the shear components
            for (int i = 1; i<dim; ++i)
                dpProps_->dp_F_.rdof(i) = trans.dof(i) * (-1.0* vcs) / timestep;
            // Damp the normal component
            dpProps_->dp_F_.rx() -= trans.x() * vcn / timestep;
            // Need to change behavior based on the dp_mode.
            if ((dpProps_->dp_mode_ == 1 || dpProps_->dp_mode_ == 3)) {
                // Limit in tension if not bonded.
                if (sn_state_ < 3 && (dpProps_->dp_F_.x() + totalForce.x() < 0))
                    dpProps_->dp_F_.rx() = -totalForce.rx();
            }
            if (sn_S_ && dpProps_->dp_mode_ > 1) {
                // Limit in shear if sliding.
                double dfn = dpProps_->dp_F_.rx();
                dpProps_->dp_F_.fill(0.0);
                dpProps_->dp_F_.rx() = dfn;
            }
        }
        FP_S;

        //Compute energies if energy tracking has been enabled. 
        if (state->trackEnergy_) {
            assert(energies_);
            energies_->estrain_ = 0.0;
            if (kn)
                // Calculate the strain energy. 
                energies_->estrain_ = 0.5*totalForce.x()*totalForce.x() / kn;
            if (ks) {
                DVect s = totalForce;
                s.rx() = 0.0;
                double smag2 = s.mag2();
                // Add the shear component of the strain energy.
                energies_->estrain_ += 0.5*smag2 / ks;

                if (sn_S_) {
                    // If sliding calculate the slip energy and accumulate it.
                    sn_F_old.rx() = 0.0;
                    DVect avg_F_s = (s + sn_F_old)*0.5;
                    DVect u_s_el = (s - sn_F_old) / ks;
                    DVect u_s(0.0);
                    for (int i = 1; i < dim; ++i)
                        u_s.rdof(i) = trans.dof(i);
                    energies_->eslip_ -= std::min(0.0, (avg_F_s | (u_s + u_s_el)));
                }
            }
            // Add the bending/twisting resistance energy contributions.
            if (kb) {
                DAVect tmp = sn_M_;
#ifdef THREED                
                tmp.rx() = 0.0;
#endif
                energies_->estrain_ += 0.5*tmp.mag2() / kb;
                if (sn_BS_) {
                    //  accumulate bending slip energy.
                    DAVect tmp_old = sn_M_old;
#ifdef THREED                
                    tmp_old.rx() = 0.0;
#endif
                    DAVect avg_M = (tmp + tmp_old)*0.5;
                    DAVect t_s_el = (tmp - tmp_old) / kb;
                    energies_->eslip_ -= std::min(0.0, (avg_M | (ang + t_s_el)));
                }
            }
#ifdef THREED                
            if (kt) {
                double mt = std::abs(sn_M_.x());
                energies_->estrain_ += 0.5*mt*mt / kt;
                if (sn_TS_) {
                    //  accumulate twisting slip energy.
                    DAVect tmp(0.0);
                    DAVect tmp_old(0.0);
                    tmp.rx() = sn_M_.x();
                    tmp_old.rx() = sn_M_old.x();
                    DAVect avg_M = (tmp + tmp_old)*0.5;
                    DAVect t_s_el = (tmp - tmp_old) / kt;
                    energies_->eslip_ -= std::min(0.0, (avg_M | (ang + t_s_el)));
                }
            }
#endif                

            if (dpProps_) {
                // Calculate damping energy (accumulated) if the dashpots are active. 
                energies_->edashpot_ -= dpProps_->dp_F_ | trans;
            }
        }

        // This is just a sanity check to ensure, in debug mode, that the force/moment aren't wonky. 
        assert(sn_F_ == sn_F_);
        assert(sn_M_ == sn_M_);
        assert(fictForce_ == fictForce_);
        FP_S;
        return true;
    }

    bool ContactModelRBSN::FDLawUnBonded(ContactModelMechanicalState *state, const double &timestep) {
        DVect3 geom = computeGeomData(state->getMechanicalContact());
        double br = geom.z();
        // Relative translational/rotational displacement increments
        DVect  trans = state->relativeTranslationalIncrement_;
        DAVect ang   = state->relativeAngularIncrement_;
        double overlap = rgap_ - state->gap_;
        double correction = 1.0;
        if (state->activated() && sn_mode_ == 0 && trans.x()) {
                correction = -1.0*overlap / trans.x();
                if (correction < 0)
                    correction = 1.0;
        }

        // Store previous force and moment
        DVect  sn_F_old = sn_F_;
        double porForce = sn_por_ * geom.x();
        sn_F_old.rx() -= porForce;
        DAVect sn_M_old = sn_M_;

        double kb = kRot_.z();
#if DIM==3
        double kt = kRot_.x();
        //kb = std::sqrt(kb * kb + kRot_.y() * kRot_.y());
#endif
        // absolute/incremental normal force calculation
        DVect theStiff(kTran_/kRatio_);
        theStiff.rx() = kTran_;

        if (sn_mode_==0)
            sn_F_.rx() = overlap * theStiff.x();
        else
            sn_F_.rx() -= trans.x() * theStiff.x();
        // Normal force can only be positive if unbonded
        sn_F_.rx() = std::max(0.0, sn_F_.x()) - porForce;

        // Calculate the trial shear force.
        DVect sforce(0.0);
        // dim holds the dimension (e.g., 2 for 2D and 3 for 3D)
        // Loop over the shear components (note: the 0 component is the normal component)
        // and calculate the shear force.
        for (int i = 1; i<dim; ++i)
            sforce.rdof(i) = sn_F_.dof(i) - trans.dof(i) * theStiff.dof(i);

        // Calculate the trial moment.
        DAVect mom = sn_M_ - ang*kRot_;

        // If the SOLVE ELASTIC command is given then the 
        // canFail state is set to FALSE. Otherwise it is always TRUE. 
        if (state->canFail_) {
            bool changed = false;
            // Resolve sliding. This is the normal force multiplied by the coefficient of friction.
            bool slip_changed = false;
            
            double crit = sn_F_.x() * fric_ + sn_cohres_ * geom.x();
            if (sn_state_ != 0) {
                if (!sn_S_) {
                    if (sn_heal_) {
                        sn_sdisp_.rx() = 0;
                        crit = sn_F_.x() * sn_fa_ + cohTable_[0].x() * geom.x();
                    } 
                } else {
                    double mm = 0.0;
                    for (int i=1; i<dim; ++i)
                        mm += trans[i]*trans[i];
                    sn_sdisp_.rx() += std::sqrt(mm);
                    if (sn_cohdc() > std::numeric_limits<double>::epsilon()) { 
                        int ww = -1;
                        if (sn_sdisp_.x() <= sn_cohdc()) {
                            for (int i=0; i<cohTable_.size(); ++i) {
                                if (cohTable_[i].y() >= sn_sdisp_.x()) {
                                    ww = i;
                                    break;
                                }
                            }
                        } else
                            ww = cohTable_.size() - 1;
                        if (ww > 0) {
                            double prevVal = ww == 1 ? 1: cohTable_[ww-1].x() ;//critBreak_ : cohTable_[ww-1].x() + sn_F_.x() * fric_;
                            double curVal =  cohTable_[ww].x();//cohTable_[ww].x() + sn_F_.x() * fric_;
                            double prevShear = cohTable_[ww-1].y();
                            double curShear = cohTable_[ww].y();
                            double slope = (curVal - prevVal)/(curShear - prevShear);
                            // should go from 0 to 1
                            double mval = slope * (sn_sdisp_.x() - prevShear) + prevVal;
                            double fact = std::max(0.,std::min(1.0,1.0 - mval));
                            assert(fact >= 0 && fact <= 1.0);
                            double theFric = fric_;
                            if (sn_fa_)
                                theFric = sn_fa_ + (fric_ - sn_fa_)*fact;
                            double theCoh = sn_Coh();
                            if (theCoh) 
                                theCoh = sn_Coh() + (sn_cohres_ - sn_Coh())*fact;
                            crit = sn_F_.x() * theFric + theCoh * geom.x();
                        }
                    }
                }
            }

            // Resolve sliding. 
            if (crit < 0)
                crit = 0.0;
            // The is the magnitude of the shear force.
            double sfmag = sforce.mag();
            if (sfmag > crit) {
                // Lower the shear force to the critical value for sliding.
                double rat = crit / sfmag;
                sforce *= rat;
                if (!sn_S_) {
                    slip_changed = true;
                    changed = true;
                }
                sn_S_ = true;
            } else {
                if (sn_S_) {
                    slip_changed = true;
                    changed = true;
                }
                sn_S_ = false;
            }
            if (sn_S_) {
                if (sn_dil_ > 0) {
                    double zdd = sn_dilzero_ != 0 ? sn_dilzero_ : limits<double>::max();
                    double usm = sn_sdisp_.y();
                    if (usm < zdd) {
                        double sInc = 0.0;
                        for (int i=1; i<dim; ++i)
                            sInc += trans.dof(i)*trans.dof(i);
                        sInc = std::sqrt(sInc);
                        sn_F_.rx() += kTran_ * sn_dil_ * sInc; 
                    }
                }
            } else {
                if (sn_heal_) {
                    if (shearStrength(geom.x()))
                        sn_state_ = 6;
                }
            } 
            // Resolve bending
            bool bslip_changed = false;
            crit = sn_bmul_ * 2.1*0.25*sn_F_.x() * br; // Jiang 2015
            DAVect test = mom;
#if DIM==3
            test.rx() = 0.0;
#endif
            double tmag = test.mag();
            if (tmag > crit) {
                // Lower the bending moment to the critical value for sliding.
                double rat = crit / tmag;
                test *= rat;
                if (!sn_BS_) {
                    bslip_changed = true;
                    changed = true;
                }
                sn_BS_ = true;
            }
            else {
                if (sn_BS_) {
                    bslip_changed = true;
                    changed = true;
                }
                sn_BS_ = false;
            }
            mom.rz() = test.z();
#if DIM==3
            mom.ry() = test.y();
            // Resolve twisting
            bool tslip_changed = false;
            crit = sn_tmul_ * 0.65*fric_*sn_F_.x() * br; // Jiang 2015
            tmag = std::abs(mom.x());
            if (tmag > crit) {
                // Lower the twisting moment to the critical value for sliding.
                double rat = crit / tmag;
                mom.rx() *= rat;
                if (!sn_TS_) {
                    tslip_changed = true;
                    changed = true;
                }
                sn_TS_ = true;
            }
            else {
                if (sn_TS_) {
                    tslip_changed = true;
                    changed = true;
                }
                sn_TS_ = false;
            }
#endif
            if (changed && cmEvents_[fSlipChange] >= 0) {
                qint64 code = 0;
                if (slip_changed) {
                    code = 1;
                    if (bslip_changed) {
                        code = 4;
#if DIM==3
                        if (tslip_changed)
                            code = 7;
#endif
                    }
                }
                else if (bslip_changed) {
                    code = 2;
#if DIM==3
                    if (tslip_changed)
                        code = 6;
#endif
                }
#if DIM==3
                else if (tslip_changed) {
                    code = 3;
                    if (slip_changed)
                        code = 5;
                }
#endif
                auto c = state->getContact();
                std::vector<fish::Parameter> arg = { fish::Parameter(c->getIThing()), 
                                                     fish::Parameter(code),
                                                     fish::Parameter(sn_S_),
                                                     fish::Parameter(sn_BS_)
#ifdef THREED
                                                     ,fish::Parameter(sn_TS_)
#endif
                                                   };
                IFishCallList *fi = const_cast<IFishCallList*>(state->getProgram()->findInterface<IFishCallList>());
                fi->setCMFishCallArguments(c,arg,cmEvents_[fSlipChange]);
            }
        }

        sn_F_.rx() += porForce;
        sn_F_old.rx() += porForce;

        // Set the shear components of the total force.
        for (int i = 1; i<dim; ++i)
            sn_F_.rdof(i) = sforce.dof(i);

        // Set the moment.
        sn_M_ = mom;

        // Account for dashpot forces if the dashpot structure has been defined. 
        if (dpProps_) {
            dpProps_->dp_F_.fill(0.0);
            double vcn(0.0), vcs(0.0);
            // Calculate the damping coefficients. 
            vcn = dpProps_->dp_nratio_ * 2.0 * sqrt((state->inertialMass_*(kTran_)));
            vcs = dpProps_->dp_sratio_ * 2.0 * sqrt((state->inertialMass_*(kTran_/kRatio_)));
            // First damp the shear components
            for (int i = 1; i<dim; ++i)
                dpProps_->dp_F_.rdof(i) = trans.dof(i) * (-1.0* vcs) / timestep;
            // Damp the normal component
            dpProps_->dp_F_.rx() -= trans.x() * vcn / timestep;
            // Need to change behavior based on the dp_mode.
            if ((dpProps_->dp_mode_ == 1 || dpProps_->dp_mode_ == 3)) {
                // Limit in tension if not bonded.
                if (dpProps_->dp_F_.x() + sn_F_.x() < 0)
                    dpProps_->dp_F_.rx() = -sn_F_.rx();
            }
            if (sn_S_ && dpProps_->dp_mode_ > 1) {
                // Limit in shear if not sliding.
                double dfn = dpProps_->dp_F_.rx();
                dpProps_->dp_F_.fill(0.0);
                dpProps_->dp_F_.rx() = dfn;
            }
        }

        //Compute energies if energy tracking has been enabled. 
        if (state->trackEnergy_) {
            assert(energies_);
            energies_->estrain_ = 0.0;
            if (kTran_)
                // Calculate the strain energy. 
                energies_->estrain_ = 0.5*sn_F_.x()*sn_F_.x() / kTran_;
            if (kTran_) {
                DVect s = sn_F_;
                s.rx() = 0.0;
                double smag2 = s.mag2();
                // Add the shear component of the strain energy.
                energies_->estrain_ += 0.5*smag2 / (kTran_/kRatio_);

                if (sn_S_) {
                    // If sliding calculate the slip energy and accumulate it.
                    sn_F_old.rx() = 0.0;
                    DVect avg_F_s = (s + sn_F_old)*0.5;
                    DVect u_s_el = (s - sn_F_old) / (kTran_/kRatio_);
                    DVect u_s(0.0);
                    for (int i = 1; i < dim; ++i)
                        u_s.rdof(i) = trans.dof(i);
                    energies_->eslip_ -= std::min(0.0, (avg_F_s | (u_s + u_s_el)));
                }
            }
            // Add the bending/twisting resistance energy contributions.
            if (kb) {
                DAVect tmp = sn_M_;
#ifdef THREED                
                tmp.rx() = 0.0;
#endif
                energies_->estrain_ += 0.5*tmp.mag2() / kb;
                if (sn_BS_) {
                    //  accumulate bending slip energy.
                    DAVect tmp_old = sn_M_old;
#ifdef THREED                
                    tmp_old.rx() = 0.0;
#endif
                    DAVect avg_M = (tmp + tmp_old)*0.5;
                    DAVect t_s_el = (tmp - tmp_old) / kb;
                    energies_->eslip_ -= std::min(0.0, (avg_M | (ang + t_s_el)));
                }
            }
#ifdef THREED                
            if (kt) {
                double mt = std::abs(sn_M_.x());
                energies_->estrain_ += 0.5*mt*mt / kt;
                if (sn_TS_) {
                    //  accumulate twisting slip energy.
                    DAVect tmp(0.0);
                    DAVect tmp_old(0.0);
                    tmp.rx() = sn_M_.x();
                    tmp_old.rx() = sn_M_old.x();
                    DAVect avg_M = (tmp + tmp_old)*0.5;
                    DAVect t_s_el = (tmp - tmp_old) / kt;
                    energies_->eslip_ -= std::min(0.0, (avg_M | (ang + t_s_el)));
                }
            }
#endif                

            if (dpProps_) {
                // Calculate damping energy (accumulated) if the dashpots are active. 
                energies_->edashpot_ -= dpProps_->dp_F_ | trans;
            }
        }

        // This is just a sanity check to ensure, in debug mode, that the force/moment aren't wonky. 
        assert(sn_F_ == sn_F_);
        assert(fictForce_ == fictForce_);
        assert(sn_M_ == sn_M_);
        return true;
    }

    void ContactModelRBSN::setForce(const DVect &v,IContact *c) { 
        sn_F_ = v; 
        fictForce_ = DVect(0.0);
        forceSet_ = true;
        if (v.x() > 0) 
            rgap_ = c->getGap() + v.x() / kTran_;
    }

    void ContactModelRBSN::propagateStateInformation(IContactModelMechanical* old,const CAxes &oldSystem,const CAxes &newSystem) {
        // Only called for contacts with wall facets when the wall resolution scheme
        // is set to full!
        // Only do something if the contact model is of the same type
        if (old->getContactModel()->getName().compare("springnetwork",Qt::CaseInsensitive) == 0 && !isBonded()) {
            ContactModelRBSN *oldCm = (ContactModelRBSN *)old;
#ifdef THREED
            // Need to rotate just the shear component from oldSystem to newSystem

            // Step 1 - rotate oldSystem so that the normal is the same as the normal of newSystem
            DVect axis = oldSystem.e1() & newSystem.e1();
            double c, ang, s;
            DVect re2;
            if (!checktol(axis.abs().maxComp(),0.0,1.0,1000)) {
                axis = axis.unit();
                c = oldSystem.e1()|newSystem.e1();
                if (c > 0)
                    c = std::min(c,1.0);
                else
                    c = std::max(c,-1.0);
                ang = acos(c);
                s = sin(ang);
                double t = 1. - c;
                DMatrix<3,3> rm;
                rm.get(0,0) = t*axis.x()*axis.x() + c;
                rm.get(0,1) = t*axis.x()*axis.y() - axis.z()*s;
                rm.get(0,2) = t*axis.x()*axis.z() + axis.y()*s;
                rm.get(1,0) = t*axis.x()*axis.y() + axis.z()*s;
                rm.get(1,1) = t*axis.y()*axis.y() + c;
                rm.get(1,2) = t*axis.y()*axis.z() - axis.x()*s;
                rm.get(2,0) = t*axis.x()*axis.z() - axis.y()*s;
                rm.get(2,1) = t*axis.y()*axis.z() + axis.x()*s;
                rm.get(2,2) = t*axis.z()*axis.z() + c;
                re2 = rm*oldSystem.e2();
            }
            else
                re2 = oldSystem.e2();
            // Step 2 - get the angle between the oldSystem rotated shear and newSystem shear
            axis = re2 & newSystem.e2();
            DVect2 tpf;
            DVect2 tpm;
            DMatrix<2,2> m;
            if (!checktol(axis.abs().maxComp(),0.0,1.0,1000)) {
                axis = axis.unit();
                c = re2|newSystem.e2();
                if (c > 0)
                    c = std::min(c,1.0);
                else
                    c = std::max(c,-1.0);
                ang = acos(c);
                if (!checktol(axis.x(),newSystem.e1().x(),1.0,100))
                    ang *= -1;
                s = sin(ang);
                m.get(0,0) = c;
                m.get(1,0) = s;
                m.get(0,1) = -m.get(1,0);
                m.get(1,1) = m.get(0,0);
                tpf = m*DVect2(oldCm->sn_F_.y(),oldCm->sn_F_.z());
                tpm = m*DVect2(oldCm->sn_M_.y(),oldCm->sn_M_.z());
            } else {
                m.get(0,0) = 1.;
                m.get(0,1) = 0.;
                m.get(1,0) = 0.;
                m.get(1,1) = 1.;
                tpf = DVect2(oldCm->sn_F_.y(),oldCm->sn_F_.z());
                tpm = DVect2(oldCm->sn_M_.y(),oldCm->sn_M_.z());
            }
            DVect pforce = DVect(0,tpf.x(),tpf.y());
            DVect pm     = DVect(0,tpm.x(),tpm.y());
#else
            oldSystem;
            newSystem;
            DVect pforce = DVect(0,oldCm->sn_F_.y());
            DVect pm     = DVect(0,oldCm->sn_M_.y());
#endif
            for (int i=1; i<dim; ++i)
                sn_F_.rdof(i) += pforce.dof(i);
            if (sn_mode_ && oldCm->sn_mode_)
                sn_F_.rx() = oldCm->sn_F_.x();
            oldCm->sn_F_ = DVect(0.0);
            oldCm->sn_M_ = DAVect(0.0);
            if (dpProps_ && oldCm->dpProps_) {
#ifdef THREED
                tpf = m*DVect2(oldCm->dpProps_->dp_F_.y(),oldCm->dpProps_->dp_F_.z());
                pforce = DVect(oldCm->dpProps_->dp_F_.x(),tpf.x(),tpf.y());
#else
                pforce = oldCm->dpProps_->dp_F_;
#endif
                dpProps_->dp_F_ += pforce;
                oldCm->dpProps_->dp_F_ = DVect(0.0);
            }
            if(oldCm->getEnergyActivated()) {
                activateEnergy();
                energies_->estrain_ = oldCm->energies_->estrain_;
                energies_->edashpot_ = oldCm->energies_->edashpot_;
                energies_->eslip_ = oldCm->energies_->eslip_;
                oldCm->energies_->estrain_ = 0.0;
                oldCm->energies_->edashpot_ = 0.0;
                oldCm->energies_->eslip_ = 0.0;
            }
            rgap_ = oldCm->rgap_;
        }
        assert(sn_F_ == sn_F_);
    }

    void ContactModelRBSN::setNonForcePropsFrom(IContactModel *old) {
        // Only called for contacts with wall facets when the wall resolution scheme
        // is set to full!
        // Only do something if the contact model is of the same type
        if (old->getName().compare("springnetwork",Qt::CaseInsensitive) == 0 && !isBonded()) {
            ContactModelRBSN *oldCm = (ContactModelRBSN *)old;

            fictForce_ = oldCm->fictForce_;
            sn_F_ = oldCm->sn_F_;
            sn_sdisp_ = oldCm->sn_sdisp_;
            sn_M_ = oldCm->sn_M_;      
            kRot_ = oldCm->kRot_;
            kTran_ = oldCm->kTran_;
            kRatio_ = oldCm->kRatio_;
            E_ = oldCm->E_;
            poisson_ = oldCm->poisson_;
            fric_ = oldCm->fric_;
            sn_bmul_ = oldCm->sn_bmul_;
            sn_tmul_ = oldCm->sn_tmul_;
            sn_rmul_ = oldCm->sn_rmul_;
            userArea_ = oldCm->userArea_;
            rgap_ = oldCm->rgap_;
            sn_fa_ = oldCm->sn_fa_;
            sn_mcf_ = oldCm->sn_mcf_;
            sn_dil_ = oldCm->sn_dil_;
            sn_dilzero_ = oldCm->sn_dilzero_;
            transTen_ = oldCm->transTen_;
            sn_elong_ = oldCm->sn_elong_;
            sn_ndisp_ = oldCm->sn_ndisp_;
            sn_mode_ = oldCm->sn_mode_;
            sn_state_ = oldCm->sn_state_;
            poisOffDiag_ = oldCm->poisOffDiag_;
            sn_S_ = oldCm->sn_S_;
            sn_BS_ = oldCm->sn_BS_;
            sn_TS_ = oldCm->sn_TS_;
            forceSet_ = oldCm->forceSet_;
            sn_heal_ = oldCm->sn_heal_;
            tenTable_ = oldCm->tenTable_;
            cohTable_ = oldCm->cohTable_;
            if (oldCm->hasDamping()) {
                if (!dpProps_)
                    dpProps_ = NEWC(dpProps());
                dp_nratio(oldCm->dp_nratio()); 
                dp_sratio(oldCm->dp_sratio()); 
                dp_mode(oldCm->dp_mode()); 
                dp_F(oldCm->dp_F()); 
            }
        }
    }

    DVect ContactModelRBSN::getForce(const IContactMechanical *) const {
        DVect ret(sn_F_);
        ret += fictForce_;
        if (dpProps_)
            ret += dpProps_->dp_F_;
        return ret;
    }

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

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

    DVect3 ContactModelRBSN::computeGeomData(const IContactMechanical *c) const {
        double Cmax1 = c->getEnd1Curvature().y();
        double Cmax2 = c->getEnd2Curvature().y();
        double br = sn_rmul_ * 1.0 / std::max(Cmax1, Cmax2);
        if (userArea_)
#ifdef THREED
            br = std::sqrt(userArea_ / dPi);
#else
            br = userArea_ / 2.0;
#endif        
        double br2 = br * br;
#ifdef THREED
        double area = dPi * br2;
        double bi = 0.25*area*br2;
#else
        double area = 2.0*br;
        double bi = 2.0*br*br2 / 3.0;
#endif
        return DVect3(area, bi, br);
    }

    DVect2 ContactModelRBSN::SMax(const IContactMechanical *c) const {
        DVect3 data = computeGeomData(c);
        double area = data.x();
        double bi = data.y();
        double br = data.z();
        /* maximum stresses */
        //double nsmax0 = -(totalForce.x() / area) + sn_mcf_* sqrt(sn_M_.y()*sn_M_.y() + sn_M_.z()*sn_M_.z()) * br / bi;
        double dbend = sqrt(sn_M_.y()*sn_M_.y() + sn_M_.z()*sn_M_.z());
        dbend *= sn_mcf_;
        double dtwist = sn_M_.x();
        DVect bfs(sn_F_);
        bfs.rx() = 0.0;
        double dbfs = bfs.mag();
        double nsmax = -((sn_F_.x()+fictForce_.x()) / area) + dbend * br / bi;
        double ssmax = dbfs / area + std::abs(dtwist) * 0.5* br / bi;
        return DVect2(nsmax, ssmax);
    }

    double ContactModelRBSN::shearStrength(const double &area) const {
        double sig = -1.0*(sn_F_.x() + fictForce_.x()) / area;
        double nstr = (sn_state_ > 2 && sn_state_ != 6) ? tenTable_[0].x() : 0.0;
        return sig <= nstr ? cohTable_[0].x() - sn_fa_*sig
            : cohTable_[0].x() - sn_fa_*nstr;
    }


    double ContactModelRBSN::strainEnergy(double kn,double ks,double kb,double kt) const {
        double ret(0.0);
        if (kn)
            ret = 0.5 * (sn_F_.x()+fictForce_.x()) * (sn_F_.x()+fictForce_.x()) / kn;
        if (ks) {
            DVect tmp = sn_F_ + fictForce_;
            tmp.rx() = 0.0;
            double smag2 = tmp.mag2();
            ret += 0.5 * smag2 / ks;
        }

        if (kt)
            ret += 0.5 * sn_M_.x() * sn_M_.x() / kt;
        if (kb) {
            DAVect tmp = sn_M_;
#ifdef THREED
            tmp.rx() = 0.0;
            double smag2 = tmp.mag2();
#else
            double smag2 = tmp.z() * tmp.z();
#endif
            ret += 0.5 * smag2 / kb;
        }
        return ret;
    }

} // namespace cmodelsxd
// EoF

Top