]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/aicontrol.cpp
Foundations of using physics simulation for trains
[r2c2.git] / source / libmarklin / aicontrol.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 "aicontrol.h"
9 #include "catalogue.h"
10 #include "layout.h"
11 #include "train.h"
12
13 using namespace std;
14 using namespace Msp;
15
16 namespace Marklin {
17
18 AIControl::AIControl(Train &t, ControlModel *n):
19         train(t),
20         next_model(n),
21         target_speed(TrainControl::continuous("speed", -1000, 1000)),
22         blocked(false)
23 {
24         target_speed.set(0);
25
26         train.signal_arrived.connect(sigc::mem_fun(this, &AIControl::arrived));
27 }
28
29 AIControl::~AIControl()
30 {
31         delete next_model;
32 }
33
34 void AIControl::set_control(const string &n, float v)
35 {
36         if(n=="speed")
37         {
38                 if(v && !train.is_active())
39                         train.set_active(true);
40
41                 target_speed.set(v);
42                 if(!blocked)
43                         next_model->set_control("speed", target_speed.value);
44         }
45         else
46                 next_model->set_control(n, v);
47 }
48
49 const TrainControl &AIControl::get_control(const string &n) const
50 {
51         if(n=="speed")
52                 return target_speed;
53         else
54                 return next_model->get_control(n);
55 }
56
57 float AIControl::get_speed() const
58 {
59         return next_model->get_speed();
60 }
61
62 float AIControl::get_braking_distance() const
63 {
64         return next_model->get_braking_distance();
65 }
66
67 void AIControl::tick(const Time::TimeDelta &dt)
68 {
69         float rsv_dist = train.get_reserved_distance();
70         float brake_dist = next_model->get_braking_distance()*1.15;
71         float margin = 25*train.get_layout().get_catalogue().get_scale();
72         if(!blocked && rsv_dist<brake_dist+margin)
73         {
74                 blocked = true;
75                 next_model->set_control("speed", 0);
76         }
77         else if(blocked && rsv_dist>brake_dist+margin*3)
78         {
79                 blocked = false;
80                 next_model->set_control("speed", target_speed.value);
81         }
82
83         next_model->tick(dt);
84
85         if(!target_speed.value && !next_model->get_speed() && train.is_active())
86                 train.set_active(false);
87 }
88
89 void AIControl::arrived()
90 {
91         set_control("speed", 0);
92 }
93
94 } // namespace Marklin