matthias-research / pages

My web page containing all the demos from my youtube channel "Ten Minute Physics" www.youtube.com/c/TenMinutePhysics
649 stars 133 forks source link

energy conservation in XPBD soft body simulation #21

Open wdiestel opened 1 year ago

wdiestel commented 1 year ago

Not sure if it helps someone. To avoid too much loss of energy during collisions, in my particular implementation, I added an energy conservation restriction in the postSolve phase which scales all velocities with a factor, also it avoids invalid gain of energy in specific cases. Potential and kinetic energies are calculated as the sum over all particles using the well known formular. This simple approach is valid for a single moving object and would need to be modified if energy exchange happens between multiple moving objects though.

      const epot = this.obj.Epot(this.obj.akceleration); // potential ernergy in respect to gravity field
      const ekin = this.obj.Ekin();
      const E = epot + ekin;
      if (debugging) console.log(`E(pot|kin): ${epot/1000+ekin/1000} (${epot/1000}|${ekin/1000})`);
      const at = this.alpha*dt;
      if (E/this.E0 < (1-at) || E > this.E0) {
          const E1 = this.E0*(1-at); 
          const lambda = Math.sqrt((E1-E)/E+1);
          this.obj.vel.scale(lambda); // scale all velocities by a factor lambda
      }
Choons commented 1 year ago

thank you for sharing that!