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