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