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