]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/simplephysics.cpp
Emit signal for control changes initiated by the control model itself
[r2c2.git] / source / libmarklin / simplephysics.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2010  Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <msp/core/except.h>
9 #include <msp/time/units.h>
10 #include "simplephysics.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace Marklin {
16
17 SimplePhysics::SimplePhysics():
18         target_speed(TrainControl::continuous("speed", -1000, 1000)),
19         accel(0.07),
20         speed(0)
21 {
22         target_speed.set(0);
23 }
24
25 void SimplePhysics::set_control(const string &name, float v)
26 {
27         if(name=="speed")
28         {
29                 target_speed.set(v);
30                 signal_control_changed.emit(name, target_speed.value);
31         }
32 }
33
34 const TrainControl &SimplePhysics::get_control(const string &name) const
35 {
36         if(name=="speed")
37                 return target_speed;
38         else
39                 throw KeyError("Unknown control", name);
40 }
41
42 float SimplePhysics::get_braking_distance() const
43 {
44         return speed*speed/(2*accel);
45 }
46
47 void SimplePhysics::tick(const Time::TimeDelta &dt)
48 {
49         float secs = dt/Time::sec;
50         if(speed<target_speed.value)
51         {
52                 speed += secs*accel;
53                 if(speed>target_speed.value)
54                         speed = target_speed.value;
55         }
56         else if(speed>target_speed.value)
57         {
58                 speed -= secs*accel;
59                 if(speed<target_speed.value)
60                         speed = target_speed.value;
61         }
62 }
63
64 } // namespace Marklin