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
//! Numerical integration

use {component, object};

/// Interface trait for integrators of objects with time derivatives
pub trait Integrator {
  // required
  fn integrate_dt          <O : object::Temporal> (object : &mut O, dt : f64);
  fn integrate_position_dt <O : object::Temporal> (object : &mut O, dt : f64);
  fn integrate_velocity_dt <O : object::Temporal> (object : &mut O, dt : f64);
  // provided
  fn integrate             <O : object::Temporal> (object : &mut O) {
    Self::integrate_dt (object, 1.0)
  }
  fn integrate_position    <O : object::Temporal> (object : &mut O) {
    Self::integrate_position_dt (object, 1.0)
  }
  fn integrate_velocity    <O : object::Temporal> (object : &mut O) {
    Self::integrate_velocity_dt (object, 1.0)
  }
}

/// Semi-implicit Euler integrator
#[derive(Clone,Debug,Default,Eq,PartialEq)]
pub struct SemiImplicitEuler;
impl Integrator for SemiImplicitEuler {
  fn integrate_velocity_dt <O : object::Temporal> (object : &mut O, dt : f64) {
    // second order: accelerate
    let acceleration = object.derivatives().acceleration;
    object.derivatives_mut().velocity += dt * acceleration;
  }
  fn integrate_position_dt <O : object::Temporal> (object : &mut O, dt : f64) {
    // first order: translate
    let velocity = object.derivatives().velocity;
    let component::Position (ref mut position) = object.position_mut();
    *position += dt * velocity;
  }
  /// Integrate with a step size of *dt*
  fn integrate_dt <O : object::Temporal> (object : &mut O, dt : f64) {
    Self::integrate_velocity_dt (object, dt);
    Self::integrate_position_dt (object, dt);
  }
}