]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Mark train positions as inaccurate on halt
[r2c2.git] / source / libmarklin / train.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2010  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 "aicontrol.h"
13 #include "catalogue.h"
14 #include "driver.h"
15 #include "layout.h"
16 #include "locotype.h"
17 #include "route.h"
18 #include "simplephysics.h"
19 #include "timetable.h"
20 #include "tracktype.h"
21 #include "train.h"
22 #include "vehicle.h"
23
24 using namespace std;
25 using namespace Msp;
26
27 namespace Marklin {
28
29 Train::Train(Layout &l, const LocoType &t, unsigned a):
30         layout(l),
31         loco_type(t),
32         address(a),
33         pending_block(0),
34         control(new AIControl(*this, new SimplePhysics)),
35         timetable(0),
36         active(false),
37         current_speed(0),
38         speed_changing(false),
39         reverse(false),
40         functions(0),
41         route(0),
42         next_route(0),
43         end_of_route(false),
44         status("Unplaced"),
45         travel_dist(0),
46         pure_speed(false),
47         real_speed(15),
48         accurate_position(false),
49         overshoot_dist(false)
50 {
51         vehicles.push_back(new Vehicle(layout, loco_type));
52
53         layout.add_train(*this);
54
55         layout.get_driver().add_loco(address);
56         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
57         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
58
59         layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
60         layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
61         layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
62
63         layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
64
65         control->signal_control_changed.connect(signal_control_changed);
66 }
67
68 Train::~Train()
69 {
70         delete control;
71         delete timetable;
72         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
73                 delete *i;
74         layout.remove_train(*this);
75 }
76
77 void Train::set_name(const string &n)
78 {
79         name = n;
80
81         signal_name_changed.emit(name);
82 }
83
84 Vehicle &Train::get_vehicle(unsigned i)
85 {
86         if(i>=vehicles.size())
87                 throw InvalidParameterValue("Vehicle index out of range");
88         return *vehicles[i];
89 }
90
91 const Vehicle &Train::get_vehicle(unsigned i) const
92 {
93         if(i>=vehicles.size())
94                 throw InvalidParameterValue("Vehicle index out of range");
95         return *vehicles[i];
96 }
97
98 void Train::set_control(const string &n, float v)
99 {
100         control->set_control(n, v);
101 }
102
103 void Train::set_active(bool a)
104 {
105         if(a==active)
106                 return;
107         if(!a && control->get_speed())
108                 throw InvalidState("Can't deactivate while moving");
109
110         active = a;
111         if(active)
112         {
113                 stop_timeout = Time::TimeStamp();
114                 reserve_more();
115         }
116         else
117         {
118                 stop_timeout = Time::now()+2*Time::sec;
119                 set_status("Stopped");
120         }
121 }
122
123 void Train::set_function(unsigned func, bool state)
124 {
125         if(!loco_type.get_functions().count(func))
126                 throw InvalidParameterValue("Invalid function");
127         if(func<5)
128                 layout.get_driver().set_loco_function(address, func, state);
129         else
130                 layout.get_driver().set_loco_function(address+1, func-4, state);
131 }
132
133 bool Train::get_function(unsigned func) const
134 {
135         return (functions>>func)&1;
136 }
137
138 void Train::set_route(const Route *r)
139 {
140         if(!rsv_blocks.empty())
141         {
142                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
143                         if(i->block->get_sensor_id())
144                         {
145                                 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
146                                 break;
147                         }
148         }
149
150         route = r;
151         next_route = 0;
152         end_of_route = false;
153
154         if(route)
155         {
156                 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
157                 BlockRef next = last.next();
158                 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
159                 if(!route->get_tracks().count(ep.track))
160                 {
161                         next_route = route;
162                         route = Route::find(*ep.track, ep.track_ep, *next_route);
163                 }
164         }
165
166         if(active)
167                 reserve_more();
168
169         signal_route_changed.emit(route);
170 }
171
172 void Train::go_to(const Track &to)
173 {
174         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
175                 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
176                 {
177                         signal_arrived.emit();
178                         set_route(0);
179                         return;
180                 }
181
182         BlockRef *last = 0;
183         if(rsv_blocks.empty())
184                 last = &cur_blocks.back();
185         else
186         {
187                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
188                         if(i->block->get_sensor_id())
189                                 last = &*i;
190         }
191
192         BlockRef next = last->next();
193         const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
194
195         set_route(Route::find(*ep.track, ep.track_ep, to));
196 }
197
198 void Train::place(Block &block, unsigned entry)
199 {
200         if(control->get_speed())
201                 throw InvalidState("Must be stopped before placing");
202
203         release_blocks(rsv_blocks);
204         release_blocks(cur_blocks);
205
206         set_active(false);
207         accurate_position = false;
208
209         if(!block.reserve(this))
210         {
211                 set_status("Unplaced");
212                 return;
213         }
214
215         cur_blocks.push_back(BlockRef(&block, entry));
216         if(reverse)
217         {
218                 unsigned exit = block.traverse(entry);
219                 const Block::Endpoint &bep = block.get_endpoints()[exit];
220                 Track *track = bep.track->get_link(bep.track_ep);
221                 unsigned ep = track->get_endpoint_by_link(*bep.track);
222                 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
223         }
224         else
225         {
226                 const Block::Endpoint &bep = block.get_endpoints()[entry];
227                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
228         }
229 }
230
231 bool Train::free_block(Block &block)
232 {
233         unsigned nsens = 0;
234         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
235         {
236                 if(i->block==&block)
237                 {
238                         if(nsens<1)
239                                 return false;
240                         release_blocks(rsv_blocks, i, rsv_blocks.end());
241                         return true;
242                 }
243                 else if(i->block->get_sensor_id())
244                         ++nsens;
245         }
246
247         return false;
248 }
249
250 int Train::get_entry_to_block(Block &block) const
251 {
252         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
253                 if(i->block==&block)
254                         return i->entry;
255         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
256                 if(i->block==&block)
257                         return i->entry;
258         return -1;
259 }
260
261 float Train::get_reserved_distance() const
262 {
263         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
264         const VehicleType &vtype = veh.get_type();
265
266         Track *track = veh.get_track();
267         if(!track)
268                 return 0;
269         unsigned entry = veh.get_entry();
270
271         float result = -vtype.get_length()/2;
272         if(reverse)
273         {
274                 entry = track->traverse(entry);
275                 result += veh.get_offset();
276         }
277         else
278                 result -= veh.get_offset();
279
280         bool first = true;
281         list<BlockRef>::const_iterator block = cur_blocks.begin();
282         while(1)
283         {
284                 if(!first || !reverse)
285                         result += track->get_type().get_path_length(track->get_active_path());
286                 first = false;
287
288                 if(track->get_type().get_endpoints().size()<2)
289                         return result;
290
291                 unsigned exit = track->traverse(entry);
292                 Track *next = track->get_link(exit);
293
294                 while(!block->block->get_tracks().count(next))
295                 {
296                         ++block;
297                         if(block==cur_blocks.end())
298                                 block = rsv_blocks.begin();
299                         if(block==rsv_blocks.end())
300                                 return result;
301                 }
302
303                 entry = next->get_endpoint_by_link(*track);
304                 track = next;
305         }
306 }
307
308 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
309 {
310         if(!active && stop_timeout && t>=stop_timeout)
311         {
312                 release_blocks(rsv_blocks);
313                 end_of_route = false;
314                 stop_timeout = Time::TimeStamp();
315         }
316
317         Driver &driver = layout.get_driver();
318
319         if(timetable)
320                 timetable->tick(t);
321         control->tick(dt);
322         float speed = control->get_speed();
323         unsigned speed_notch = find_speed(abs(speed));
324
325         if(speed && (speed<0)!=reverse)
326         {
327                 driver.set_loco_reverse(address, speed<0);
328                 reverse = speed<0;
329
330                 release_blocks(rsv_blocks);
331                 reverse_blocks(cur_blocks);
332
333                 reserve_more();
334         }
335         if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
336         {
337                 speed_changing = true;
338                 driver.set_loco_speed(address, speed_notch);
339
340                 pure_speed = false;
341
342                 if(speed_notch)
343                         set_status(format("Traveling %d kmh", get_travel_speed()));
344                 else
345                         set_status("Waiting");
346         }
347
348         if(speed)
349         {
350                 if(!active)
351                         set_active(true);
352
353                 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
354                 Track *track = vehicle.get_track();
355
356                 bool ok = false;
357                 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
358                         ok = i->block->get_tracks().count(track);
359
360                 float d = get_real_speed(current_speed)*(dt/Time::sec);
361                 if(ok)
362                         vehicle.advance(reverse ? -d : d);
363                 else if(accurate_position)
364                 {
365                         overshoot_dist += d;
366                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
367                         {
368                                 layout.emergency(name+" has not arrived at sensor");
369                                 accurate_position = false;
370                         }
371                 }
372         }
373         else if(end_of_route)
374                 set_route(0);
375 }
376
377 void Train::save(list<DataFile::Statement> &st) const
378 {
379         st.push_back((DataFile::Statement("name"), name));
380
381         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
382                 if(i!=vehicles.begin())
383                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
384
385         for(unsigned i=0; i<=14; ++i)
386                 if(real_speed[i].weight)
387                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
388
389         if(!cur_blocks.empty())
390         {
391                 list<BlockRef> blocks = cur_blocks;
392                 if(reverse)
393                         reverse_blocks(blocks);
394
395                 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
396                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
397
398                 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
399                         st.push_back((DataFile::Statement("block"), i->block->get_id()));
400         }
401
402         if(route)
403         {
404                 if(!route->is_temporary())
405                         st.push_back((DataFile::Statement("route"), route->get_name()));
406                 else if(next_route && !next_route->is_temporary())
407                         st.push_back((DataFile::Statement("route"), next_route->get_name()));
408         }
409
410         if(timetable)
411         {
412                 DataFile::Statement ss("timetable");
413                 timetable->save(ss.sub);
414                 st.push_back(ss);
415         }
416 }
417
418 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
419 {
420         if(addr==address)
421         {
422                 current_speed = speed;
423                 speed_changing = false;
424                 pure_speed = false;
425         }
426 }
427
428 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
429 {
430         if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
431         {
432                 if(addr==address+1)
433                         func += 4;
434                 if(state)
435                         functions |= 1<<func;
436                 else
437                         functions &= ~(1<<func);
438
439                 signal_function_changed.emit(func, state);
440         }
441 }
442
443 void Train::sensor_event(unsigned addr, bool state)
444 {
445         if(state)
446         {
447                 // Find the first sensor block from our reserved blocks that isn't this sensor
448                 list<BlockRef>::iterator i;
449                 unsigned result = 0;
450                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
451                         if(i->block->get_sensor_id())
452                         {
453                                 if(i->block->get_sensor_id()!=addr)
454                                 {
455                                         if(result==0)
456                                                 result = 2;
457                                         else if(result==1)
458                                                 break;
459                                 }
460                                 else if(result==0)
461                                         result = 1;
462                                 else if(result==2)
463                                         result = 3;
464                         }
465
466                 if(result==1 && i!=rsv_blocks.begin())
467                 {
468                         // Compute speed and update related state
469                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
470
471                         if(pure_speed)
472                         {
473                                 RealSpeed &rs = real_speed[current_speed];
474                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
475                                 set_status(format("Traveling %d kmh", get_travel_speed()));
476                         }
477
478                         travel_dist = 0;
479                         float block_len;
480                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
481                         {
482                                 j->block->traverse(j->entry, &block_len);
483                                 travel_dist += block_len;
484
485                                 if(j->block->get_sensor_id()==addr)
486                                 {
487                                         const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
488                                         if(reverse)
489                                         {
490                                                 Track *track = bep.track->get_link(bep.track_ep);
491                                                 unsigned ep = track->get_endpoint_by_link(*bep.track);
492                                                 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
493                                         }
494                                         else
495                                                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
496                                 }
497                         }
498                         last_entry_time = Time::now();
499                         pure_speed = true;
500                         accurate_position = true;
501                         overshoot_dist = 0;
502
503                         // Check if we've reached the next route
504                         if(next_route)
505                         {
506                                 const set<const Track *> &rtracks = next_route->get_tracks();
507                                 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
508                                         if(rtracks.count(j->block->get_endpoints()[j->entry].track))
509                                         {
510                                                 route = next_route;
511                                                 next_route = 0;
512                                                 // XXX Exceptions?
513                                                 signal_route_changed.emit(route);
514                                                 break;
515                                         }
516                         }
517
518                         // Move blocks up to the next sensor to our current blocks
519                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
520
521                         // Try to get more blocks if we're moving
522                         if(active)
523                         {
524                                 unsigned nsens = reserve_more();
525                                 if(!nsens && end_of_route)
526                                         signal_arrived.emit();
527                         }
528                 }
529                 else if(result==3)
530                         layout.emergency("Sensor for "+name+" triggered out of order");
531         }
532         else
533         {
534                 // Find the first sensor in our current blocks that's still active
535                 list<BlockRef>::iterator end = cur_blocks.begin();
536                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
537                         if(i->block->get_sensor_id())
538                         {
539                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
540                                         break;
541                                 else
542                                         end = i;
543                         }
544                 
545                 if(end!=cur_blocks.begin())
546                 {
547                         // Free blocks up to the last inactive sensor
548                         ++end;
549                         release_blocks(cur_blocks, cur_blocks.begin(), end);
550                 }
551         }
552 }
553
554 void Train::turnout_event(unsigned addr, bool)
555 {
556         if(pending_block)
557         {
558                 unsigned pending_addr = pending_block->get_turnout_id();
559                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
560                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
561                         reserve_more();
562         }
563 }
564
565 void Train::halt_event(bool h)
566 {
567         if(h)
568                 accurate_position = false;
569 }
570
571 void Train::block_reserved(const Block &block, const Train *train)
572 {
573         if(&block==pending_block && !train)
574                 reserve_more();
575 }
576
577 unsigned Train::reserve_more()
578 {
579         BlockRef *last = 0;
580         if(!rsv_blocks.empty())
581                 last = &rsv_blocks.back();
582         else if(!cur_blocks.empty())
583                 last = &cur_blocks.back();
584         if(!last)
585                 return 0;
586
587         pending_block = 0;
588
589         // See how many sensor blocks we already have
590         unsigned nsens = 0;
591         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
592                 if(i->block->get_sensor_id())
593                         ++nsens;
594         
595         if(end_of_route)
596                 return nsens;
597
598         const Route *cur_route = 0;
599         if(route)
600         {
601                 const set<Track *> &tracks = last->block->get_tracks();
602                 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
603                 {
604                         if(route->get_tracks().count(*i))
605                                 cur_route = route;
606                         else if(next_route && next_route->get_tracks().count(*i))
607                                 cur_route = next_route;
608                 }
609         }
610
611         bool got_more = false;
612         BlockRef *good = last;
613         unsigned good_sens = nsens;
614         while(good_sens<3)
615         {
616                 if(last->block->get_endpoints().size()<2)
617                 {
618                         good = last;
619                         good_sens = nsens;
620                         break;
621                 }
622
623                 // Traverse to the next block
624                 unsigned exit = last->block->traverse(last->entry);
625                 Block *link = last->block->get_link(exit);
626                 if(!link)
627                         break;
628
629                 int entry = link->get_endpoint_by_link(*last->block);
630                 if(entry<0)
631                         throw LogicError("Block links are inconsistent!");
632
633                 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
634
635                 if(cur_route)
636                 {
637                         if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
638                                 cur_route = next_route;
639                         else if(!cur_route->get_tracks().count(entry_ep.track))
640                         {
641                                 // Keep the blocks if we arrived at the end of the route
642                                 good = last;
643                                 good_sens = nsens;
644                                 end_of_route = true;
645                                 break;
646                         }
647                 }
648                 else if(route && route->get_tracks().count(entry_ep.track))
649                         cur_route = route;
650
651                 if(!link->reserve(this))
652                 {
653                         // If we found another train and it's not headed straight for us, we can keep the blocks we got
654                         int other_entry = link->get_train()->get_entry_to_block(*link);
655                         if(other_entry<0)
656                                 throw LogicError("Block reservation inconsistency");
657                         if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
658                         {
659                                 good = last;
660                                 good_sens = nsens;
661                         }
662                         pending_block = link;
663                         break;
664                 }
665
666                 if(link->get_turnout_id())
667                 {
668                         const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
669
670                         // Keep the blocks reserved so far, as either us or the other train can diverge
671                         good = last;
672                         good_sens = nsens;
673
674                         // Figure out what path we'd like to take on the turnout
675                         int path = -1;
676                         if(cur_route)
677                                 path = cur_route->get_turnout(link->get_turnout_id());
678                         if(path<0)
679                                 path = entry_ep.track->get_active_path();
680                         if(!((track_ep.paths>>path)&1))
681                         {
682                                 for(unsigned i=0; track_ep.paths>>i; ++i)
683                                         if((track_ep.paths>>i)&1)
684                                                 path = i;
685                         }
686
687                         if(path!=static_cast<int>(entry_ep.track->get_active_path()))
688                         {
689                                 // The turnout is set to wrong path - switch and wait for it
690                                 link->reserve(0);
691                                 pending_block = link;
692                                 entry_ep.track->set_active_path(path);
693                                 break;
694                         }
695                 }
696
697                 rsv_blocks.push_back(BlockRef(link, entry));
698                 last = &rsv_blocks.back();
699                 if(last->block->get_sensor_id())
700                 {
701                         ++nsens;
702                         got_more = true;
703                 }
704         }
705
706         // Unreserve blocks that were not good
707         while(!rsv_blocks.empty() && last!=good)
708         {
709                 last->block->reserve(0);
710                 rsv_blocks.erase(--rsv_blocks.end());
711                 if(!rsv_blocks.empty())
712                         last = &rsv_blocks.back();
713         }
714
715         // Make any sensorless blocks at the beginning immediately current
716         list<BlockRef>::iterator i;
717         for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
718         if(i!=rsv_blocks.begin())
719                 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
720
721         return good_sens;
722 }
723
724 float Train::get_real_speed(unsigned i) const
725 {
726         if(real_speed[i].weight)
727                 return real_speed[i].speed;
728
729         unsigned low;
730         unsigned high;
731         for(low=i; low>0; --low)
732                 if(real_speed[low].weight)
733                         break;
734         for(high=i; high<14; ++high)
735                 if(real_speed[high].weight)
736                         break;
737
738         if(real_speed[high].weight)
739         {
740                 if(real_speed[low].weight)
741                 {
742                         float f = float(i-low)/(high-low);
743                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
744                 }
745                 else
746                         return real_speed[high].speed*float(i)/high;
747         }
748         else if(real_speed[low].weight)
749                 return real_speed[low].speed*float(i)/low;
750         else
751                 return 0;
752 }
753
754 unsigned Train::find_speed(float real) const
755 {
756         if(real<=real_speed[0].speed)
757                 return 0;
758
759         unsigned low = 0;
760         unsigned high = 0;
761         for(unsigned i=0; (!high && i<=14); ++i)
762                 if(real_speed[i].weight)
763                 {
764                         if(real_speed[i].speed<real)
765                                 low = i;
766                         else
767                                 high = i;
768                 }
769         if(!high)
770         {
771                 if(!low)
772                         return 0;
773                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
774         }
775
776         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
777         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
778 }
779
780 float Train::get_travel_speed() const
781 {
782         float speed = get_real_speed(current_speed);
783         float scale = layout.get_catalogue().get_scale();
784         return static_cast<int>(round(speed/scale*3.6/5))*5;
785 }
786
787 void Train::set_status(const string &s)
788 {
789         status = s;
790         signal_status_changed.emit(s);
791 }
792
793 void Train::release_blocks(list<BlockRef> &blocks)
794 {
795         release_blocks(blocks, blocks.begin(), blocks.end());
796 }
797
798 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
799 {
800         while(begin!=end)
801         {
802                 Block *block = begin->block;
803                 blocks.erase(begin++);
804                 block->reserve(0);
805         }
806 }
807
808 void Train::reverse_blocks(list<BlockRef> &blocks) const
809 {
810         blocks.reverse();
811         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
812                 i->entry = i->block->traverse(i->entry);
813 }
814
815
816 Train::BlockRef::BlockRef(Block *b, unsigned e):
817         block(b),
818         entry(e)
819 { }
820
821 Train::BlockRef Train::BlockRef::next() const
822 {
823         Block *blk = block->get_endpoints()[block->traverse(entry)].link;
824         if(!blk)
825                 throw InvalidState("At end of line");
826
827         int ep = blk->get_endpoint_by_link(*block);
828         if(ep<0)
829                 throw LogicError("Block links are inconsistent");
830
831         return BlockRef(blk, ep);
832 }
833
834
835 Train::RealSpeed::RealSpeed():
836         speed(0),
837         weight(0)
838 { }
839
840 void Train::RealSpeed::add(float s, float w)
841 {
842         speed = (speed*weight+s*w)/(weight+w);
843         weight = min(weight+w, 300.0f);
844 }
845
846
847 Train::Loader::Loader(Train &t):
848         DataFile::BasicLoader<Train>(t),
849         prev_block(0)
850 {
851         add("block",       &Loader::block);
852         add("block_hint",  &Loader::block_hint);
853         add("name",        &Loader::name);
854         add("real_speed",  &Loader::real_speed);
855         add("route",       &Loader::route);
856         add("timetable",   &Loader::timetable);
857         add("vehicle",     &Loader::vehicle);
858 }
859
860 void Train::Loader::block(unsigned id)
861 {
862         Block &blk = obj.layout.get_block(id);
863         int entry = -1;
864         if(prev_block)
865                 entry = blk.get_endpoint_by_link(*prev_block);
866         if(entry<0)
867                 entry = 0;
868
869         blk.reserve(&obj);
870         obj.cur_blocks.push_back(BlockRef(&blk, entry));
871         obj.set_status("Stopped");
872         const Block::Endpoint &bep = blk.get_endpoints()[entry];
873         obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
874
875         if(blk.get_sensor_id())
876                 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
877
878         prev_block = &blk;
879 }
880
881 void Train::Loader::block_hint(unsigned id)
882 {
883         prev_block = &obj.layout.get_block(id);
884 }
885
886 void Train::Loader::name(const string &n)
887 {
888         obj.set_name(n);
889 }
890
891 void Train::Loader::real_speed(unsigned i, float speed, float weight)
892 {
893         obj.real_speed[i].speed = speed;
894         obj.real_speed[i].weight = weight;
895 }
896
897 void Train::Loader::route(const string &n)
898 {
899         obj.set_route(&obj.layout.get_route(n));
900 }
901
902 void Train::Loader::timetable()
903 {
904         if(obj.timetable)
905                 throw InvalidState("A timetable has already been loaded");
906
907         obj.timetable = new Timetable(obj);
908         load_sub(*obj.timetable);
909 }
910
911 void Train::Loader::vehicle(unsigned n)
912 {
913         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
914         Vehicle *veh = new Vehicle(obj.layout, vtype);
915         obj.vehicles.back()->attach_back(*veh);
916         obj.vehicles.push_back(veh);
917 }
918
919 } // namespace Marklin