]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Improve the block reservation algorithm
[r2c2.git] / source / libmarklin / train.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2009 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <cmath>
9 #include <msp/strings/formatter.h>
10 #include <msp/time/units.h>
11 #include <msp/time/utils.h>
12 #include "control.h"
13 #include "except.h"
14 #include "route.h"
15 #include "tracktype.h"
16 #include "trafficmanager.h"
17 #include "train.h"
18
19 using namespace std;
20 using namespace Msp;
21
22 namespace Marklin {
23
24 Train::Train(TrafficManager &tm, Locomotive &l):
25         trfc_mgr(tm),
26         loco(l),
27         pending_block(0),
28         target_speed(0),
29         route(0),
30         status("Unplaced"),
31         travel_dist(0),
32         travel_speed(0),
33         pure_speed(false),
34         real_speed(15),
35         cur_track(0)
36 {
37         trfc_mgr.add_train(this);
38
39         loco.signal_reverse_changed.connect(sigc::mem_fun(this, &Train::locomotive_reverse_changed));
40
41         const map<unsigned, Sensor *> &sensors = trfc_mgr.get_control().get_sensors();
42         for(map<unsigned, Sensor *>::const_iterator i=sensors.begin(); i!=sensors.end(); ++i)
43                 i->second->signal_state_changed.connect(sigc::bind(sigc::mem_fun(this, &Train::sensor_event), i->second));
44
45         const map<unsigned, Turnout *> &turnouts = trfc_mgr.get_control().get_turnouts();
46         for(map<unsigned, Turnout *>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
47         {
48                 i->second->signal_path_changing.connect(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changing), i->second));
49                 i->second->signal_path_changed.connect(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), i->second));
50         }
51 }
52
53 void Train::set_name(const string &n)
54 {
55         name = n;
56
57         signal_name_changed.emit(name);
58 }
59
60 void Train::set_speed(unsigned speed)
61 {
62         if(speed==target_speed)
63                 return;
64         travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
65
66         target_speed = speed;
67         if(!target_speed)
68         {
69                 trfc_mgr.get_control().set_timer(3*Time::sec).signal_timeout.connect(
70                         sigc::bind_return(sigc::mem_fun(this, &Train::release_reserved_blocks), false));
71         }
72         else
73                 reserve_more();
74
75         signal_target_speed_changed.emit(target_speed);
76
77         update_speed();
78         pure_speed = false;
79 }
80
81 void Train::set_reverse(bool rev)
82 {
83         loco.set_reverse(rev);
84 }
85
86 void Train::set_route(const Route *r)
87 {
88         route = r;
89         signal_route_changed.emit(route);
90 }
91
92 void Train::place(Block *block, unsigned entry)
93 {
94         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end();)
95         {
96                 i->block->reserve(0);
97                 i = rsv_blocks.erase(i);
98         }
99
100         for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end();)
101         {
102                 i->block->reserve(0);
103                 i = cur_blocks.erase(i);
104         }
105
106         if(!block->reserve(this))
107         {
108                 set_status("Unplaced");
109                 return;
110         }
111
112         cur_blocks.push_back(BlockRef(block, entry));
113         set_position(block->get_endpoints()[entry]);
114
115         set_status("Stopped");
116 }
117
118 bool Train::free_block(Block *block)
119 {
120         unsigned nsens = 0;
121         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
122         {
123                 if(i->block==block)
124                 {
125                         if(nsens<1)
126                                 return false;
127                         while(i!=rsv_blocks.end())
128                         {
129                                 i->block->reserve(0);
130                                 i = rsv_blocks.erase(i);
131                         }
132                         update_speed();
133                         return true;
134                 }
135                 else if(i->block->get_sensor_id())
136                         ++nsens;
137         }
138
139         return false;
140 }
141
142 int Train::get_entry_to_block(Block *block) const
143 {
144         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
145                 if(i->block==block)
146                         return i->entry;
147         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
148                 if(i->block==block)
149                         return i->entry;
150         return -1;
151 }
152
153 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
154 {
155         if(try_reserve && t>try_reserve)
156                 reserve_more();
157
158         if(cur_track)
159         {
160                 unsigned path = 0;
161                 if(cur_track->get_turnout_id())
162                         path = trfc_mgr.get_control().get_turnout(cur_track->get_turnout_id()).get_path();
163
164                 offset += get_real_speed(loco.get_speed())*(dt/Time::sec);
165                 if(offset>cur_track->get_type().get_path_length(path))
166                 {
167                         int out = cur_track->traverse(cur_track_ep, path);
168                         if(out>=0)
169                         {
170                                 Track *next = cur_track->get_link(out);
171                                 if(next)
172                                         cur_track_ep = next->get_endpoint_by_link(*cur_track);
173                                 cur_track = next;
174                                 offset = 0;
175                         }
176                         else
177                                 cur_track = 0;
178                 }
179
180                 if(cur_track)
181                         pos = cur_track->get_point(cur_track_ep, path, offset);
182         }
183 }
184
185 void Train::save(list<DataFile::Statement> &st) const
186 {
187         st.push_back((DataFile::Statement("name"), name));
188         for(unsigned i=0; i<=14; ++i)
189                 if(real_speed[i].weight)
190                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
191 }
192
193 void Train::locomotive_reverse_changed(bool)
194 {
195         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
196                 i->block->reserve(0);
197         rsv_blocks.clear();
198         cur_blocks.reverse();
199         for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
200                 i->entry = i->block->traverse(i->entry);
201         reserve_more();
202
203         if(cur_track)
204         {
205                 unsigned path = 0;
206                 if(unsigned turnout = cur_track->get_turnout_id())
207                         path = trfc_mgr.get_control().get_turnout(turnout).get_path();
208                 cur_track_ep = cur_track->traverse(cur_track_ep, path);
209                 offset = cur_track->get_type().get_path_length(path)-offset;
210         }
211 }
212
213 void Train::sensor_event(bool state, Sensor *sensor)
214 {
215         unsigned addr = sensor->get_address();
216
217         if(state)
218         {
219                 list<BlockRef>::iterator i;
220                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
221                         if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
222                                 break;
223
224                 if(i!=rsv_blocks.begin())
225                 {
226                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
227                         travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
228
229                         if(pure_speed)
230                         {
231                                 RealSpeed &rs = real_speed[loco.get_speed()];
232                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
233                         }
234
235                         travel_dist = 0;
236                         float block_len;
237                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
238                         {
239                                 j->block->traverse(j->entry, &block_len);
240                                 travel_dist += block_len;
241                         }
242                         last_entry_time = Time::now();
243                         pure_speed = true;
244
245                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
246                 }
247
248                 for(i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
249                         if(i->block->get_sensor_id()==addr)
250                                 set_position(i->block->get_endpoints()[i->entry]);
251
252                 if(target_speed && reserve_more()<2)
253                         update_speed();
254         }
255         else
256         {
257                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
258                         if(unsigned b_addr = i->block->get_sensor_id())
259                         {
260                                 if(b_addr==addr)
261                                 {
262                                         ++i;
263                                         for(list<BlockRef>::iterator j=cur_blocks.begin(); j!=i; ++j)
264                                                 j->block->reserve(0);
265                                         cur_blocks.erase(cur_blocks.begin(), i);
266                                 }
267                                 break;
268                         }
269
270                 if(target_speed && pending_block && addr==pending_block->get_sensor_id())
271                         reserve_more();
272         }
273 }
274
275 void Train::turnout_path_changing(unsigned, Turnout *turnout)
276 {
277         unsigned tid = turnout->get_address();
278         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
279                 if(i->block->get_turnout_id()==tid)
280                         throw TurnoutBusy(this);
281         
282         unsigned nsens = 0;
283         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
284         {
285                 if(i->block->get_turnout_id()==tid)
286                 {
287                         if(nsens<1)
288                                 throw TurnoutBusy(this);
289                         break;
290                 }
291                 else if(i->block->get_sensor_id())
292                         ++nsens;
293         }
294 }
295
296 void Train::turnout_path_changed(unsigned, Turnout *turnout)
297 {
298         unsigned tid = turnout->get_address();
299         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
300                 if(i->block->get_turnout_id()==tid)
301                 {
302                         while(i!=rsv_blocks.end())
303                         {
304                                 i->block->reserve(0);
305                                 i = rsv_blocks.erase(i);
306                         }
307                         reserve_more();
308                         return;
309                 }
310
311         if(pending_block && tid==pending_block->get_turnout_id())
312                 reserve_more();
313 }
314
315 unsigned Train::reserve_more()
316 {
317         BlockRef *last = 0;
318         if(!rsv_blocks.empty())
319                 last = &rsv_blocks.back();
320         else if(!cur_blocks.empty())
321                 last = &cur_blocks.back();
322         if(!last)
323                 return 0;
324
325         pending_block = 0;
326
327         // See how many blocks we already have
328         unsigned nsens = 0;
329         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
330                 if(i->block->get_sensor_id())
331                         ++nsens;
332
333         bool got_more = false;
334         BlockRef *good = last;
335         unsigned good_sens = nsens;
336         while(good_sens<3)
337         {
338                 // Traverse to the next block
339                 unsigned exit = last->block->traverse(last->entry);
340                 Block *link = last->block->get_link(exit);
341                 if(!link)
342                         break;
343
344                 int entry = link->get_endpoint_by_link(*last->block);
345                 if(!link->reserve(this))
346                 {
347                         // If we found another train going in the same direction as us, we can keep the blocks we got
348                         int other_entry = link->get_train()->get_entry_to_block(link);
349                         if(other_entry==entry || link->traverse(entry)==link->traverse(other_entry))
350                         {
351                                 good = last;
352                                 good_sens = nsens;
353                         }
354                         pending_block = link;
355                         break;
356                 }
357
358                 if(link->get_turnout_id())
359                 {
360                         const Block::Endpoint &ep = link->get_endpoints()[entry];
361                         const Endpoint &track_ep = ep.track->get_type().get_endpoints()[ep.track_ep];
362
363                         if(track_ep.paths&(track_ep.paths-1))
364                         {
365                                 // We're facing the points - keep the blocks reserved so far
366                                 good = last;
367                                 good_sens = nsens;
368                         }
369
370                         Turnout &turnout = trfc_mgr.get_control().get_turnout(link->get_turnout_id());
371
372                         // Figure out what path we'd like to take on the turnout
373                         int path = -1;
374                         if(route)
375                                 path = route->get_turnout(link->get_turnout_id());
376                         if(path<0)
377                                 path = turnout.get_path();
378                         if(!((track_ep.paths>>path)&1))
379                         {
380                                 for(unsigned i=0; track_ep.paths>>i; ++i)
381                                         if((track_ep.paths>>i)&1)
382                                                 path = i;
383                         }
384
385                         if(path!=turnout.get_path())
386                         {
387                                 // The turnout is set to wrong path - switch and wait for it
388                                 link->reserve(0);
389                                 pending_block = link;
390                                 turnout.set_path(path);
391                                 break;
392                         }
393                 }
394
395                 rsv_blocks.push_back(BlockRef(link, entry));
396                 last = &rsv_blocks.back();
397                 if(last->block->get_sensor_id())
398                 {
399                         ++nsens;
400                         got_more = true;
401                 }
402         }
403
404         // Unreserve blocks that were not good
405         while(!rsv_blocks.empty() && last!=good)
406         {
407                 last->block->reserve(0);
408                 rsv_blocks.erase(--rsv_blocks.end());
409                 if(!rsv_blocks.empty())
410                         last = &rsv_blocks.back();
411         }
412
413         if(got_more)
414                 update_speed();
415
416         return nsens;
417 }
418
419 void Train::update_speed()
420 {
421         if(!target_speed)
422         {
423                 loco.set_speed(0);
424                 try_reserve = Time::TimeStamp();
425                 set_status("Stopped");
426         }
427         else
428         {
429                 unsigned nsens = 0;
430                 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
431                         if(i->block->get_sensor_id())
432                                 ++nsens;
433
434                 unsigned slow_speed = find_speed(0.1);  // 31.3 km/h
435                 if(nsens==0)
436                 {
437                         loco.set_speed(0);
438                         pure_speed = false;
439                         try_reserve = Time::now()+2*Time::sec;
440                         set_status("Blocked");
441                 }
442                 else if(nsens==1 && target_speed>slow_speed)
443                 {
444                         loco.set_speed(slow_speed);
445                         pure_speed = false;
446                         try_reserve = Time::now()+2*Time::sec;
447                         set_status("Slow");
448                 }
449                 else
450                 {
451                         loco.set_speed(target_speed);
452                         try_reserve = Time::TimeStamp();
453                         set_status(format("Traveling %d kmh", travel_speed));
454                 }
455         }
456 }
457
458 float Train::get_real_speed(unsigned i) const
459 {
460         if(real_speed[i].weight)
461                 return real_speed[i].speed;
462
463         unsigned low;
464         unsigned high;
465         for(low=i; low>0; --low)
466                 if(real_speed[low].weight)
467                         break;
468         for(high=i; high<14; ++high)
469                 if(real_speed[high].weight)
470                         break;
471
472         if(real_speed[high].weight)
473         {
474                 if(real_speed[low].weight)
475                 {
476                         float f = float(i-low)/(high-low);
477                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
478                 }
479                 else
480                         return real_speed[high].speed*float(i)/high;
481         }
482         else if(real_speed[low].weight)
483                 return real_speed[low].speed*float(i)/low;
484         else
485                 return 0;
486 }
487
488 unsigned Train::find_speed(float real) const
489 {
490         if(real<=real_speed[0].speed)
491                 return 0;
492
493         unsigned low = 0;
494         unsigned high = 0;
495         for(unsigned i=0; (!high && i<=14); ++i)
496                 if(real_speed[i].weight)
497                 {
498                         if(real_speed[i].speed<real)
499                                 low = i;
500                         else
501                                 high = i;
502                 }
503         if(!high)
504         {
505                 if(!low)
506                         return 0;
507                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
508         }
509
510         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
511         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
512 }
513
514 void Train::set_status(const string &s)
515 {
516         status = s;
517         signal_status_changed.emit(s);
518 }
519
520 void Train::set_position(const Block::Endpoint &bep)
521 {
522         cur_track = bep.track;
523         cur_track_ep = bep.track_ep;
524         offset = 0;
525         pos = cur_track->get_endpoint_position(cur_track_ep);
526 }
527
528 void Train::release_reserved_blocks()
529 {
530         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
531                 i->block->reserve(0);
532         rsv_blocks.clear();
533 }
534
535
536 Train::RealSpeed::RealSpeed():
537         speed(0),
538         weight(0)
539 { }
540
541 void Train::RealSpeed::add(float s, float w)
542 {
543         speed = (speed*weight+s*w)/(weight+w);
544         weight = min(weight+w, 300.0f);
545 }
546
547
548 Train::Loader::Loader(Train &t):
549         DataFile::BasicLoader<Train>(t)
550 {
551         add("name",        &Train::name);
552         add("real_speed",  &Loader::real_speed);
553 }
554
555 void Train::Loader::real_speed(unsigned i, float speed, float weight)
556 {
557         obj.real_speed[i].speed = speed;
558         obj.real_speed[i].weight = weight;
559 }
560
561 } // namespace Marklin