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