]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Handle reversing in a way that allows backing out of a dead end
[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(control->get_reverse()!=reverse)
326         {
327                 reverse = control->get_reverse();
328                 driver.set_loco_reverse(address, reverse);
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         if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
377         {
378                 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
379
380                 list<BlockRef>::iterator i = cur_blocks.begin();
381                 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
382
383                 Track *track = bep.track;
384                 unsigned entry = bep.track_ep;
385
386                 bool found = false;
387                 float dist = veh.get_offset()-veh.get_type().get_length()/2;
388                 while(1)
389                 {
390                         if(track==veh.get_track())
391                         {
392                                 found = true;
393                                 break;
394                         }
395
396                         if(i!=cur_blocks.begin())
397                         {
398                                 float path_len = track->get_type().get_path_length(track->get_active_path());
399                                 dist += path_len;
400                         }
401
402                         unsigned exit = track->traverse(entry);
403                         Track *next = track->get_link(exit);
404                         entry = next->get_endpoint_by_link(*track);
405                         track = next;
406
407                         if(!i->block->get_tracks().count(track))
408                         {
409                                 ++i;
410                                 if(i==cur_blocks.end())
411                                         break;
412                         }
413                 }
414
415                 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
416                 {
417                         cur_blocks.front().block->reserve(0);
418                         cur_blocks.erase(cur_blocks.begin());
419                 }
420         }
421 }
422
423 void Train::save(list<DataFile::Statement> &st) const
424 {
425         st.push_back((DataFile::Statement("name"), name));
426
427         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
428                 if(i!=vehicles.begin())
429                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
430
431         for(unsigned i=0; i<=14; ++i)
432                 if(real_speed[i].weight)
433                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
434
435         if(!cur_blocks.empty())
436         {
437                 list<BlockRef> blocks = cur_blocks;
438                 if(reverse)
439                         reverse_blocks(blocks);
440
441                 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
442                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
443
444                 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
445                         st.push_back((DataFile::Statement("block"), i->block->get_id()));
446         }
447
448         if(route)
449         {
450                 if(!route->is_temporary())
451                         st.push_back((DataFile::Statement("route"), route->get_name()));
452                 else if(next_route && !next_route->is_temporary())
453                         st.push_back((DataFile::Statement("route"), next_route->get_name()));
454         }
455
456         if(timetable)
457         {
458                 DataFile::Statement ss("timetable");
459                 timetable->save(ss.sub);
460                 st.push_back(ss);
461         }
462 }
463
464 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
465 {
466         if(addr==address)
467         {
468                 current_speed = speed;
469                 speed_changing = false;
470                 pure_speed = false;
471         }
472 }
473
474 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
475 {
476         if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
477         {
478                 if(addr==address+1)
479                         func += 4;
480                 if(state)
481                         functions |= 1<<func;
482                 else
483                         functions &= ~(1<<func);
484
485                 signal_function_changed.emit(func, state);
486         }
487 }
488
489 void Train::sensor_event(unsigned addr, bool state)
490 {
491         if(state)
492         {
493                 // Find the first sensor block from our reserved blocks that isn't this sensor
494                 list<BlockRef>::iterator i;
495                 unsigned result = 0;
496                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
497                         if(i->block->get_sensor_id())
498                         {
499                                 if(i->block->get_sensor_id()!=addr)
500                                 {
501                                         if(result==0)
502                                                 result = 2;
503                                         else if(result==1)
504                                                 break;
505                                 }
506                                 else if(result==0)
507                                         result = 1;
508                                 else if(result==2)
509                                         result = 3;
510                         }
511
512                 if(result==1 && i!=rsv_blocks.begin())
513                 {
514                         // Compute speed and update related state
515                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
516
517                         if(pure_speed)
518                         {
519                                 RealSpeed &rs = real_speed[current_speed];
520                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
521                                 set_status(format("Traveling %d kmh", get_travel_speed()));
522                         }
523
524                         travel_dist = 0;
525                         float block_len;
526                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
527                         {
528                                 j->block->traverse(j->entry, &block_len);
529                                 travel_dist += block_len;
530
531                                 if(j->block->get_sensor_id()==addr)
532                                 {
533                                         const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
534                                         if(reverse)
535                                         {
536                                                 Track *track = bep.track->get_link(bep.track_ep);
537                                                 unsigned ep = track->get_endpoint_by_link(*bep.track);
538                                                 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
539                                         }
540                                         else
541                                                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
542                                 }
543                         }
544                         last_entry_time = Time::now();
545                         pure_speed = true;
546                         accurate_position = true;
547                         overshoot_dist = 0;
548
549                         // Check if we've reached the next route
550                         if(next_route)
551                         {
552                                 const set<const Track *> &rtracks = next_route->get_tracks();
553                                 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
554                                         if(rtracks.count(j->block->get_endpoints()[j->entry].track))
555                                         {
556                                                 route = next_route;
557                                                 next_route = 0;
558                                                 // XXX Exceptions?
559                                                 signal_route_changed.emit(route);
560                                                 break;
561                                         }
562                         }
563
564                         // Move blocks up to the next sensor to our current blocks
565                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
566
567                         // Try to get more blocks if we're moving
568                         if(active)
569                         {
570                                 unsigned nsens = reserve_more();
571                                 if(!nsens && end_of_route)
572                                         signal_arrived.emit();
573                         }
574                 }
575                 else if(result==3)
576                         layout.emergency("Sensor for "+name+" triggered out of order");
577         }
578         else
579         {
580                 // Find the first sensor in our current blocks that's still active
581                 list<BlockRef>::iterator end = cur_blocks.begin();
582                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
583                         if(i->block->get_sensor_id())
584                         {
585                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
586                                         break;
587                                 else
588                                 {
589                                         end = i;
590                                         ++end;
591                                 }
592                         }
593                 
594                 if(end!=cur_blocks.begin())
595                         // Free blocks up to the last inactive sensor
596                         release_blocks(cur_blocks, cur_blocks.begin(), end);
597         }
598 }
599
600 void Train::turnout_event(unsigned addr, bool)
601 {
602         if(pending_block)
603         {
604                 unsigned pending_addr = pending_block->get_turnout_id();
605                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
606                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
607                         reserve_more();
608         }
609 }
610
611 void Train::halt_event(bool h)
612 {
613         if(h)
614                 accurate_position = false;
615 }
616
617 void Train::block_reserved(const Block &block, const Train *train)
618 {
619         if(&block==pending_block && !train)
620                 reserve_more();
621 }
622
623 unsigned Train::reserve_more()
624 {
625         BlockRef *last = 0;
626         if(!rsv_blocks.empty())
627                 last = &rsv_blocks.back();
628         else if(!cur_blocks.empty())
629                 last = &cur_blocks.back();
630         if(!last)
631                 return 0;
632
633         pending_block = 0;
634
635         // See how many sensor blocks we already have
636         unsigned nsens = 0;
637         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
638                 if(i->block->get_sensor_id())
639                         ++nsens;
640         
641         if(end_of_route)
642                 return nsens;
643
644         const Route *cur_route = 0;
645         if(route)
646         {
647                 const set<Track *> &tracks = last->block->get_tracks();
648                 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
649                 {
650                         if(route->get_tracks().count(*i))
651                                 cur_route = route;
652                         else if(next_route && next_route->get_tracks().count(*i))
653                                 cur_route = next_route;
654                 }
655         }
656
657         bool got_more = false;
658         BlockRef *good = last;
659         unsigned good_sens = nsens;
660         while(good_sens<3)
661         {
662                 if(last->block->get_endpoints().size()<2)
663                 {
664                         good = last;
665                         good_sens = nsens;
666                         break;
667                 }
668
669                 // Traverse to the next block
670                 unsigned exit = last->block->traverse(last->entry);
671                 Block *link = last->block->get_link(exit);
672                 if(!link)
673                         break;
674
675                 int entry = link->get_endpoint_by_link(*last->block);
676                 if(entry<0)
677                         throw LogicError("Block links are inconsistent!");
678
679                 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
680
681                 if(cur_route)
682                 {
683                         if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
684                                 cur_route = next_route;
685                         else if(!cur_route->get_tracks().count(entry_ep.track))
686                         {
687                                 // Keep the blocks if we arrived at the end of the route
688                                 good = last;
689                                 good_sens = nsens;
690                                 end_of_route = true;
691                                 break;
692                         }
693                 }
694                 else if(route && route->get_tracks().count(entry_ep.track))
695                         cur_route = route;
696
697                 if(!link->reserve(this))
698                 {
699                         // If we found another train and it's not headed straight for us, we can keep the blocks we got
700                         int other_entry = link->get_train()->get_entry_to_block(*link);
701                         if(other_entry<0)
702                                 throw LogicError("Block reservation inconsistency");
703                         if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
704                         {
705                                 good = last;
706                                 good_sens = nsens;
707                         }
708                         pending_block = link;
709                         break;
710                 }
711
712                 if(link->get_turnout_id())
713                 {
714                         const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
715
716                         // Keep the blocks reserved so far, as either us or the other train can diverge
717                         good = last;
718                         good_sens = nsens;
719
720                         // Figure out what path we'd like to take on the turnout
721                         int path = -1;
722                         if(cur_route)
723                                 path = cur_route->get_turnout(link->get_turnout_id());
724                         if(path<0)
725                                 path = entry_ep.track->get_active_path();
726                         if(!((track_ep.paths>>path)&1))
727                         {
728                                 for(unsigned i=0; track_ep.paths>>i; ++i)
729                                         if((track_ep.paths>>i)&1)
730                                                 path = i;
731                         }
732
733                         if(path!=static_cast<int>(entry_ep.track->get_active_path()))
734                         {
735                                 // The turnout is set to wrong path - switch and wait for it
736                                 link->reserve(0);
737                                 pending_block = link;
738                                 entry_ep.track->set_active_path(path);
739                                 break;
740                         }
741                 }
742
743                 rsv_blocks.push_back(BlockRef(link, entry));
744                 last = &rsv_blocks.back();
745                 if(last->block->get_sensor_id())
746                 {
747                         ++nsens;
748                         got_more = true;
749                 }
750         }
751
752         // Unreserve blocks that were not good
753         while(!rsv_blocks.empty() && last!=good)
754         {
755                 last->block->reserve(0);
756                 rsv_blocks.erase(--rsv_blocks.end());
757                 if(!rsv_blocks.empty())
758                         last = &rsv_blocks.back();
759         }
760
761         // Make any sensorless blocks at the beginning immediately current
762         list<BlockRef>::iterator i;
763         for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
764         if(i!=rsv_blocks.begin())
765                 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
766
767         return good_sens;
768 }
769
770 float Train::get_real_speed(unsigned i) const
771 {
772         if(real_speed[i].weight)
773                 return real_speed[i].speed;
774
775         unsigned low;
776         unsigned high;
777         for(low=i; low>0; --low)
778                 if(real_speed[low].weight)
779                         break;
780         for(high=i; high<14; ++high)
781                 if(real_speed[high].weight)
782                         break;
783
784         if(real_speed[high].weight)
785         {
786                 if(real_speed[low].weight)
787                 {
788                         float f = float(i-low)/(high-low);
789                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
790                 }
791                 else
792                         return real_speed[high].speed*float(i)/high;
793         }
794         else if(real_speed[low].weight)
795                 return real_speed[low].speed*float(i)/low;
796         else
797                 return 0;
798 }
799
800 unsigned Train::find_speed(float real) const
801 {
802         if(real<=real_speed[0].speed)
803                 return 0;
804
805         unsigned low = 0;
806         unsigned high = 0;
807         for(unsigned i=0; (!high && i<=14); ++i)
808                 if(real_speed[i].weight)
809                 {
810                         if(real_speed[i].speed<real)
811                                 low = i;
812                         else
813                                 high = i;
814                 }
815         if(!high)
816         {
817                 if(!low)
818                         return 0;
819                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
820         }
821
822         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
823         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
824 }
825
826 float Train::get_travel_speed() const
827 {
828         float speed = get_real_speed(current_speed);
829         float scale = layout.get_catalogue().get_scale();
830         return static_cast<int>(round(speed/scale*3.6/5))*5;
831 }
832
833 void Train::set_status(const string &s)
834 {
835         status = s;
836         signal_status_changed.emit(s);
837 }
838
839 void Train::release_blocks(list<BlockRef> &blocks)
840 {
841         release_blocks(blocks, blocks.begin(), blocks.end());
842 }
843
844 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
845 {
846         while(begin!=end)
847         {
848                 Block *block = begin->block;
849                 blocks.erase(begin++);
850                 block->reserve(0);
851         }
852 }
853
854 void Train::reverse_blocks(list<BlockRef> &blocks) const
855 {
856         blocks.reverse();
857         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
858                 i->entry = i->block->traverse(i->entry);
859 }
860
861
862 Train::BlockRef::BlockRef(Block *b, unsigned e):
863         block(b),
864         entry(e)
865 { }
866
867 Train::BlockRef Train::BlockRef::next() const
868 {
869         Block *blk = block->get_endpoints()[block->traverse(entry)].link;
870         if(!blk)
871                 throw InvalidState("At end of line");
872
873         int ep = blk->get_endpoint_by_link(*block);
874         if(ep<0)
875                 throw LogicError("Block links are inconsistent");
876
877         return BlockRef(blk, ep);
878 }
879
880
881 Train::RealSpeed::RealSpeed():
882         speed(0),
883         weight(0)
884 { }
885
886 void Train::RealSpeed::add(float s, float w)
887 {
888         speed = (speed*weight+s*w)/(weight+w);
889         weight = min(weight+w, 300.0f);
890 }
891
892
893 Train::Loader::Loader(Train &t):
894         DataFile::BasicLoader<Train>(t),
895         prev_block(0)
896 {
897         add("block",       &Loader::block);
898         add("block_hint",  &Loader::block_hint);
899         add("name",        &Loader::name);
900         add("real_speed",  &Loader::real_speed);
901         add("route",       &Loader::route);
902         add("timetable",   &Loader::timetable);
903         add("vehicle",     &Loader::vehicle);
904 }
905
906 void Train::Loader::block(unsigned id)
907 {
908         Block &blk = obj.layout.get_block(id);
909         int entry = -1;
910         if(prev_block)
911                 entry = blk.get_endpoint_by_link(*prev_block);
912         if(entry<0)
913                 entry = 0;
914
915         blk.reserve(&obj);
916         obj.cur_blocks.push_back(BlockRef(&blk, entry));
917         obj.set_status("Stopped");
918         const Block::Endpoint &bep = blk.get_endpoints()[entry];
919         obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
920
921         if(blk.get_sensor_id())
922                 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
923
924         prev_block = &blk;
925 }
926
927 void Train::Loader::block_hint(unsigned id)
928 {
929         prev_block = &obj.layout.get_block(id);
930 }
931
932 void Train::Loader::name(const string &n)
933 {
934         obj.set_name(n);
935 }
936
937 void Train::Loader::real_speed(unsigned i, float speed, float weight)
938 {
939         obj.real_speed[i].speed = speed;
940         obj.real_speed[i].weight = weight;
941 }
942
943 void Train::Loader::route(const string &n)
944 {
945         obj.set_route(&obj.layout.get_route(n));
946 }
947
948 void Train::Loader::timetable()
949 {
950         if(obj.timetable)
951                 throw InvalidState("A timetable has already been loaded");
952
953         obj.timetable = new Timetable(obj);
954         load_sub(*obj.timetable);
955 }
956
957 void Train::Loader::vehicle(unsigned n)
958 {
959         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
960         Vehicle *veh = new Vehicle(obj.layout, vtype);
961         obj.vehicles.back()->attach_back(*veh);
962         obj.vehicles.push_back(veh);
963 }
964
965 } // namespace Marklin