]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Fix a compile error
[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                                 if(current_speed)
527                                 {
528                                         RealSpeed &rs = real_speed[current_speed];
529                                         rs.add(travel_dist/travel_time_secs, travel_time_secs);
530                                 }
531                                 set_status(format("Traveling %d kmh", get_travel_speed()));
532                         }
533
534                         travel_dist = 0;
535                         float block_len;
536                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
537                         {
538                                 j->block->traverse(j->entry, &block_len);
539                                 travel_dist += block_len;
540
541                                 if(j->block->get_sensor_id()==addr)
542                                 {
543                                         const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
544                                         if(reverse)
545                                         {
546                                                 Track *track = bep.track->get_link(bep.track_ep);
547                                                 unsigned ep = track->get_endpoint_by_link(*bep.track);
548                                                 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
549                                         }
550                                         else
551                                                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
552                                 }
553                         }
554                         last_entry_time = Time::now();
555                         pure_speed = true;
556                         accurate_position = true;
557                         overshoot_dist = 0;
558
559                         // Check if we've reached the next route
560                         if(next_route)
561                         {
562                                 const set<const Track *> &rtracks = next_route->get_tracks();
563                                 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
564                                         if(rtracks.count(j->block->get_endpoints()[j->entry].track))
565                                         {
566                                                 route = next_route;
567                                                 next_route = 0;
568                                                 // XXX Exceptions?
569                                                 signal_route_changed.emit(route);
570                                                 break;
571                                         }
572                         }
573
574                         // Move blocks up to the next sensor to our current blocks
575                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
576
577                         // Try to get more blocks if we're moving
578                         if(active)
579                         {
580                                 unsigned nsens = reserve_more();
581                                 if(!nsens && end_of_route)
582                                         signal_arrived.emit();
583                         }
584                 }
585                 else if(result==3)
586                         layout.emergency("Sensor for "+name+" triggered out of order");
587         }
588         else
589         {
590                 // Find the first sensor in our current blocks that's still active
591                 list<BlockRef>::iterator end = cur_blocks.begin();
592                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
593                         if(i->block->get_sensor_id())
594                         {
595                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
596                                         break;
597                                 else
598                                 {
599                                         end = i;
600                                         ++end;
601                                 }
602                         }
603                 
604                 if(end!=cur_blocks.begin())
605                         // Free blocks up to the last inactive sensor
606                         release_blocks(cur_blocks, cur_blocks.begin(), end);
607         }
608 }
609
610 void Train::turnout_event(unsigned addr, bool)
611 {
612         if(pending_block)
613         {
614                 unsigned pending_addr = pending_block->get_turnout_id();
615                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
616                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
617                         reserve_more();
618         }
619 }
620
621 void Train::halt_event(bool h)
622 {
623         if(h)
624                 accurate_position = false;
625 }
626
627 void Train::block_reserved(const Block &block, const Train *train)
628 {
629         if(&block==pending_block && !train)
630                 reserve_more();
631 }
632
633 unsigned Train::reserve_more()
634 {
635         if(!active)
636                 return 0;
637
638         BlockRef *last = 0;
639         if(!rsv_blocks.empty())
640                 last = &rsv_blocks.back();
641         else if(!cur_blocks.empty())
642                 last = &cur_blocks.back();
643         if(!last)
644                 return 0;
645
646         pending_block = 0;
647
648         // See how many sensor blocks we already have
649         unsigned nsens = 0;
650         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
651                 if(i->block->get_sensor_id())
652                         ++nsens;
653         
654         if(end_of_route)
655                 return nsens;
656
657         const Route *cur_route = 0;
658         if(route)
659         {
660                 const set<Track *> &tracks = last->block->get_tracks();
661                 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
662                 {
663                         if(route->get_tracks().count(*i))
664                                 cur_route = route;
665                         else if(next_route && next_route->get_tracks().count(*i))
666                                 cur_route = next_route;
667                 }
668         }
669
670         bool got_more = false;
671         BlockRef *good = last;
672         unsigned good_sens = nsens;
673         while(good_sens<3)
674         {
675                 if(last->block->get_endpoints().size()<2)
676                 {
677                         good = last;
678                         good_sens = nsens;
679                         break;
680                 }
681
682                 // Traverse to the next block
683                 unsigned exit = last->block->traverse(last->entry);
684                 Block *link = last->block->get_link(exit);
685                 if(!link)
686                         break;
687
688                 int entry = link->get_endpoint_by_link(*last->block);
689                 if(entry<0)
690                         throw LogicError("Block links are inconsistent!");
691
692                 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
693
694                 if(cur_route)
695                 {
696                         if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
697                                 cur_route = next_route;
698                         else if(!cur_route->get_tracks().count(entry_ep.track))
699                         {
700                                 // Keep the blocks if we arrived at the end of the route
701                                 good = last;
702                                 good_sens = nsens;
703                                 end_of_route = true;
704                                 break;
705                         }
706                 }
707                 else if(route && route->get_tracks().count(entry_ep.track))
708                         cur_route = route;
709
710                 bool reserved = link->reserve(this);
711                 if(!reserved)
712                 {
713                         // Ask a lesser priority train to free the block for us
714                         if(link->get_train()->get_priority()<priority)
715                                 if(link->get_train()->free_block(*link))
716                                         reserved = link->reserve(this);
717
718                         if(!reserved)
719                         {
720                                 // If we found another train and it's not headed straight for us, we can keep the blocks we got
721                                 int other_entry = link->get_train()->get_entry_to_block(*link);
722                                 if(other_entry<0)
723                                         throw LogicError("Block reservation inconsistency");
724                                 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
725                                 {
726                                         good = last;
727                                         good_sens = nsens;
728                                 }
729                                 pending_block = link;
730                                 break;
731                         }
732                 }
733
734                 if(link->get_turnout_id())
735                 {
736                         const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
737
738                         // Keep the blocks reserved so far, as either us or the other train can diverge
739                         good = last;
740                         good_sens = nsens;
741
742                         // Figure out what path we'd like to take on the turnout
743                         int path = -1;
744                         if(cur_route)
745                                 path = cur_route->get_turnout(link->get_turnout_id());
746                         if(path<0)
747                                 path = entry_ep.track->get_active_path();
748                         if(!((track_ep.paths>>path)&1))
749                         {
750                                 for(unsigned i=0; track_ep.paths>>i; ++i)
751                                         if((track_ep.paths>>i)&1)
752                                                 path = i;
753                         }
754
755                         if(path!=static_cast<int>(entry_ep.track->get_active_path()))
756                         {
757                                 // The turnout is set to wrong path - switch and wait for it
758                                 link->reserve(0);
759                                 pending_block = link;
760                                 entry_ep.track->set_active_path(path);
761                                 break;
762                         }
763                 }
764
765                 rsv_blocks.push_back(BlockRef(link, entry));
766                 last = &rsv_blocks.back();
767                 if(last->block->get_sensor_id())
768                 {
769                         ++nsens;
770                         got_more = true;
771                 }
772         }
773
774         // Unreserve blocks that were not good
775         while(!rsv_blocks.empty() && last!=good)
776         {
777                 last->block->reserve(0);
778                 rsv_blocks.erase(--rsv_blocks.end());
779                 if(!rsv_blocks.empty())
780                         last = &rsv_blocks.back();
781         }
782
783         // Make any sensorless blocks at the beginning immediately current
784         list<BlockRef>::iterator i;
785         for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
786         if(i!=rsv_blocks.begin())
787                 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
788
789         return good_sens;
790 }
791
792 float Train::get_real_speed(unsigned i) const
793 {
794         if(real_speed[i].weight)
795                 return real_speed[i].speed;
796
797         unsigned low;
798         unsigned high;
799         for(low=i; low>0; --low)
800                 if(real_speed[low].weight)
801                         break;
802         for(high=i; high<14; ++high)
803                 if(real_speed[high].weight)
804                         break;
805
806         if(real_speed[high].weight)
807         {
808                 if(real_speed[low].weight)
809                 {
810                         float f = float(i-low)/(high-low);
811                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
812                 }
813                 else
814                         return real_speed[high].speed*float(i)/high;
815         }
816         else if(real_speed[low].weight)
817                 return real_speed[low].speed*float(i)/low;
818         else
819                 return 0;
820 }
821
822 unsigned Train::find_speed(float real) const
823 {
824         if(real<=real_speed[0].speed)
825                 return 0;
826
827         unsigned low = 0;
828         unsigned high = 0;
829         for(unsigned i=0; (!high && i<=14); ++i)
830                 if(real_speed[i].weight)
831                 {
832                         if(real_speed[i].speed<real)
833                                 low = i;
834                         else
835                                 high = i;
836                 }
837         if(!high)
838         {
839                 if(!low)
840                 {
841                         if(real)
842                                 return 3;
843                         else
844                                 return 0;
845                 }
846                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
847         }
848
849         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
850         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
851 }
852
853 float Train::get_travel_speed() const
854 {
855         float speed = get_real_speed(current_speed);
856         float scale = layout.get_catalogue().get_scale();
857         return static_cast<int>(round(speed/scale*3.6/5))*5;
858 }
859
860 void Train::set_status(const string &s)
861 {
862         status = s;
863         signal_status_changed.emit(s);
864 }
865
866 void Train::release_blocks(list<BlockRef> &blocks)
867 {
868         release_blocks(blocks, blocks.begin(), blocks.end());
869 }
870
871 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
872 {
873         while(begin!=end)
874         {
875                 Block *block = begin->block;
876                 blocks.erase(begin++);
877                 block->reserve(0);
878         }
879 }
880
881 void Train::reverse_blocks(list<BlockRef> &blocks) const
882 {
883         blocks.reverse();
884         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
885                 i->entry = i->block->traverse(i->entry);
886 }
887
888
889 Train::BlockRef::BlockRef(Block *b, unsigned e):
890         block(b),
891         entry(e)
892 { }
893
894 Train::BlockRef Train::BlockRef::next() const
895 {
896         Block *blk = block->get_endpoints()[block->traverse(entry)].link;
897         if(!blk)
898                 throw InvalidState("At end of line");
899
900         int ep = blk->get_endpoint_by_link(*block);
901         if(ep<0)
902                 throw LogicError("Block links are inconsistent");
903
904         return BlockRef(blk, ep);
905 }
906
907
908 Train::RealSpeed::RealSpeed():
909         speed(0),
910         weight(0)
911 { }
912
913 void Train::RealSpeed::add(float s, float w)
914 {
915         speed = (speed*weight+s*w)/(weight+w);
916         weight = min(weight+w, 300.0f);
917 }
918
919
920 Train::Loader::Loader(Train &t):
921         DataFile::BasicLoader<Train>(t),
922         prev_block(0)
923 {
924         add("block",       &Loader::block);
925         add("block_hint",  &Loader::block_hint);
926         add("name",        &Loader::name);
927         add("priority",    &Train::priority);
928         add("real_speed",  &Loader::real_speed);
929         add("route",       &Loader::route);
930         add("timetable",   &Loader::timetable);
931         add("vehicle",     &Loader::vehicle);
932 }
933
934 void Train::Loader::block(unsigned id)
935 {
936         Block &blk = obj.layout.get_block(id);
937         int entry = -1;
938         if(prev_block)
939                 entry = blk.get_endpoint_by_link(*prev_block);
940         if(entry<0)
941                 entry = 0;
942
943         blk.reserve(&obj);
944         obj.cur_blocks.push_back(BlockRef(&blk, entry));
945         obj.set_status("Stopped");
946         const Block::Endpoint &bep = blk.get_endpoints()[entry];
947         obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
948
949         if(blk.get_sensor_id())
950                 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
951
952         prev_block = &blk;
953 }
954
955 void Train::Loader::block_hint(unsigned id)
956 {
957         prev_block = &obj.layout.get_block(id);
958 }
959
960 void Train::Loader::name(const string &n)
961 {
962         obj.set_name(n);
963 }
964
965 void Train::Loader::real_speed(unsigned i, float speed, float weight)
966 {
967         obj.real_speed[i].speed = speed;
968         obj.real_speed[i].weight = weight;
969 }
970
971 void Train::Loader::route(const string &n)
972 {
973         obj.set_route(&obj.layout.get_route(n));
974 }
975
976 void Train::Loader::timetable()
977 {
978         if(obj.timetable)
979                 throw InvalidState("A timetable has already been loaded");
980
981         obj.timetable = new Timetable(obj);
982         load_sub(*obj.timetable);
983 }
984
985 void Train::Loader::vehicle(unsigned n)
986 {
987         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
988         Vehicle *veh = new Vehicle(obj.layout, vtype);
989         obj.vehicles.back()->attach_back(*veh);
990         obj.vehicles.push_back(veh);
991 }
992
993 } // namespace Marklin