]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Add a pathfinder function to Route
[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 "driver.h"
13 #include "layout.h"
14 #include "locotype.h"
15 #include "route.h"
16 #include "tracktype.h"
17 #include "train.h"
18
19 using namespace std;
20 using namespace Msp;
21
22 namespace Marklin {
23
24 Train::Train(Layout &l, const LocoType &t, unsigned a):
25         layout(l),
26         loco_type(t),
27         address(a),
28         pending_block(0),
29         target_speed(0),
30         current_speed(0),
31         reverse(false),
32         functions(0),
33         route(0),
34         end_of_route(false),
35         status("Unplaced"),
36         travel_dist(0),
37         travel_speed(0),
38         pure_speed(false),
39         real_speed(15),
40         cur_track(0)
41 {
42         layout.add_train(*this);
43
44         layout.get_driver().add_loco(address);
45         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
46         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
47
48         layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
49         layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
50         layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
51 }
52
53 Train::~Train()
54 {
55         layout.remove_train(*this);
56 }
57
58 void Train::set_name(const string &n)
59 {
60         name = n;
61
62         signal_name_changed.emit(name);
63 }
64
65 void Train::set_speed(unsigned speed)
66 {
67         if(speed==target_speed)
68                 return;
69         travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
70
71         target_speed = speed;
72         if(!target_speed)
73         {
74                 pending_block = 0;
75                 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
76         }
77         else
78                 reserve_more();
79
80         signal_target_speed_changed.emit(target_speed);
81
82         update_speed();
83         pure_speed = false;
84 }
85
86 void Train::set_reverse(bool rev)
87 {
88         if(rev==reverse)
89                 return;
90
91         if(target_speed)
92         {
93                 set_speed(0);
94                 return;
95         }
96         else if(stop_timeout)
97                 return;
98
99         layout.get_driver().set_loco_reverse(address, rev);
100
101         release_blocks(rsv_blocks);
102         reverse_blocks(cur_blocks);
103
104         if(cur_track)
105         {
106                 unsigned path = cur_track->get_active_path();
107                 cur_track_ep = cur_track->traverse(cur_track_ep, path);
108                 offset = cur_track->get_type().get_path_length(path)-offset;
109         }
110 }
111
112 void Train::set_function(unsigned func, bool state)
113 {
114         if(!loco_type.get_functions().count(func))
115                 throw InvalidParameterValue("Invalid function");
116         if(func<5)
117                 layout.get_driver().set_loco_function(address, func, state);
118         else
119                 layout.get_driver().set_loco_function(address+1, func-4, state);
120 }
121
122 bool Train::get_function(unsigned func) const
123 {
124         return (functions>>func)&1;
125 }
126
127 void Train::set_route(const Route *r)
128 {
129         if(!rsv_blocks.empty())
130         {
131                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
132                         if(i->block->get_sensor_id())
133                         {
134                                 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
135                                 break;
136                         }
137         }
138
139         route = r;
140         end_of_route = false;
141
142         if(target_speed && reserve_more()<2)
143                 update_speed();
144
145         signal_route_changed.emit(route);
146 }
147
148 void Train::go_to(const Track &to)
149 {
150         BlockRef *last = 0;
151         if(rsv_blocks.empty())
152                 last = &cur_blocks.back();
153         else
154         {
155                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
156                         if(i->block->get_sensor_id())
157                                 last = &*i;
158         }
159
160         Block *next = last->block->get_endpoints()[last->block->traverse(last->entry)].link;
161         if(!next)
162                 throw InvalidState("At end of line");
163
164         int entry = next->get_endpoint_by_link(*last->block);
165         if(entry<0)
166                 throw LogicError("Block links are inconsistent");
167
168         const Block::Endpoint &ep = next->get_endpoints()[entry];
169
170         set_route(Route::find(*ep.track, ep.track_ep, to));
171 }
172
173 void Train::place(Block &block, unsigned entry)
174 {
175         if(target_speed)
176                 set_speed(0);
177
178         release_blocks(rsv_blocks);
179         release_blocks(cur_blocks);
180
181         if(!block.reserve(this))
182         {
183                 set_status("Unplaced");
184                 return;
185         }
186
187         cur_blocks.push_back(BlockRef(&block, entry));
188         set_position(block.get_endpoints()[entry]);
189
190         set_status("Stopped");
191 }
192
193 bool Train::free_block(Block &block)
194 {
195         unsigned nsens = 0;
196         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
197         {
198                 if(i->block==&block)
199                 {
200                         if(nsens<1)
201                                 return false;
202                         release_blocks(rsv_blocks, i, rsv_blocks.end());
203                         update_speed();
204                         return true;
205                 }
206                 else if(i->block->get_sensor_id())
207                         ++nsens;
208         }
209
210         return false;
211 }
212
213 int Train::get_entry_to_block(Block &block) const
214 {
215         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
216                 if(i->block==&block)
217                         return i->entry;
218         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
219                 if(i->block==&block)
220                         return i->entry;
221         return -1;
222 }
223
224 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
225 {
226         if(stop_timeout && t>=stop_timeout)
227         {
228                 release_blocks(rsv_blocks);
229                 end_of_route = false;
230                 stop_timeout = Time::TimeStamp();
231         }
232
233         if(cur_track)
234         {
235                 unsigned path = cur_track->get_active_path();
236
237                 offset += get_real_speed(current_speed)*(dt/Time::sec);
238                 float path_len = cur_track->get_type().get_path_length(path);
239                 if(offset>path_len)
240                 {
241                         unsigned out = cur_track->traverse(cur_track_ep, path);
242                         Track *next = cur_track->get_link(out);
243
244                         bool ok = false;
245                         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
246                                 ok = i->block->get_tracks().count(next);
247
248                         if(ok)
249                         {
250                                 if(next)
251                                         cur_track_ep = next->get_endpoint_by_link(*cur_track);
252                                 cur_track = next;
253                                 offset = 0;
254                         }
255                         else
256                                 offset = path_len-0.001;
257                 }
258
259                 if(cur_track)
260                         pos = cur_track->get_point(cur_track_ep, path, offset).pos;
261         }
262 }
263
264 void Train::save(list<DataFile::Statement> &st) const
265 {
266         st.push_back((DataFile::Statement("name"), name));
267         for(unsigned i=0; i<=14; ++i)
268                 if(real_speed[i].weight)
269                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
270         if(route)
271                 st.push_back((DataFile::Statement("route"), route->get_name()));
272
273         if(!cur_blocks.empty())
274         {
275                 list<BlockRef> blocks = cur_blocks;
276                 if(reverse)
277                         reverse_blocks(blocks);
278
279                 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
280                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
281
282                 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
283                         st.push_back((DataFile::Statement("block"), i->block->get_id()));
284         }
285 }
286
287 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
288 {
289         if(addr==address)
290         {
291                 current_speed = speed;
292                 reverse = rev;
293
294                 signal_speed_changed.emit(current_speed);
295                 signal_reverse_changed.emit(reverse);
296         }
297 }
298
299 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
300 {
301         if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
302         {
303                 if(addr==address+1)
304                         func += 4;
305                 if(state)
306                         functions |= 1<<func;
307                 else
308                         functions &= ~(1<<func);
309
310                 signal_function_changed.emit(func, state);
311         }
312 }
313
314 void Train::sensor_event(unsigned addr, bool state)
315 {
316         if(state)
317         {
318                 // Find the first sensor block from our reserved blocks that isn't this sensor
319                 list<BlockRef>::iterator i;
320                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
321                         if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
322                                 break;
323
324                 if(i!=rsv_blocks.begin())
325                 {
326                         // Compute speed and update related state
327                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
328                         travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
329
330                         if(pure_speed)
331                         {
332                                 RealSpeed &rs = real_speed[current_speed];
333                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
334                         }
335
336                         travel_dist = 0;
337                         float block_len;
338                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
339                         {
340                                 j->block->traverse(j->entry, &block_len);
341                                 travel_dist += block_len;
342
343                                 if(j->block->get_sensor_id()==addr)
344                                         set_position(j->block->get_endpoints()[j->entry]);
345                         }
346                         last_entry_time = Time::now();
347                         pure_speed = true;
348
349                         // Move blocks up to the next sensor to our current blocks
350                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
351
352                         // Try to get more blocks if we're moving
353                         if(target_speed)
354                         {
355                                 unsigned nsens = reserve_more();
356                                 if(!nsens && end_of_route)
357                                 {
358                                         set_speed(0);
359                                         set_route(0);
360                                 }
361                                 else if(nsens<2)
362                                         update_speed();
363                         }
364                 }
365         }
366         else
367         {
368                 // Find the first sensor in our current blocks that's still active
369                 list<BlockRef>::iterator end = cur_blocks.begin();
370                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
371                         if(i->block->get_sensor_id())
372                         {
373                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
374                                         break;
375                                 else
376                                         end = i;
377                         }
378                 
379                 if(end!=cur_blocks.begin())
380                 {
381                         // Free blocks up to the last inactive sensor
382                         ++end;
383                         release_blocks(cur_blocks, cur_blocks.begin(), end);
384                 }
385         }
386 }
387
388 void Train::turnout_event(unsigned addr, bool)
389 {
390         if(pending_block)
391         {
392                 unsigned pending_addr = pending_block->get_turnout_id();
393                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
394                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
395                         reserve_more();
396         }
397 }
398
399 void Train::block_reserved(const Block &block, const Train *train)
400 {
401         if(&block==pending_block && !train)
402                 reserve_more();
403 }
404
405 unsigned Train::reserve_more()
406 {
407         BlockRef *last = 0;
408         if(!rsv_blocks.empty())
409                 last = &rsv_blocks.back();
410         else if(!cur_blocks.empty())
411                 last = &cur_blocks.back();
412         if(!last)
413                 return 0;
414
415         pending_block = 0;
416
417         // See how many sensor blocks we already have
418         unsigned nsens = 0;
419         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
420                 if(i->block->get_sensor_id())
421                         ++nsens;
422
423         bool on_route = (route && route->get_tracks().count(last->block->get_endpoints()[last->entry].track));
424         bool got_more = false;
425         BlockRef *good = last;
426         unsigned good_sens = nsens;
427         while(good_sens<3)
428         {
429                 // Traverse to the next block
430                 unsigned exit = last->block->traverse(last->entry);
431                 Block *link = last->block->get_link(exit);
432                 if(!link)
433                         break;
434
435                 int entry = link->get_endpoint_by_link(*last->block);
436                 if(entry<0)
437                         throw LogicError("Block links are inconsistent!");
438
439                 if(on_route && !route->get_tracks().count(link->get_endpoints()[entry].track))
440                 {
441                         // Keep the blocks if we arrived at the end of the route
442                         good = last;
443                         good_sens = nsens;
444                         end_of_route = true;
445                         break;
446                 }
447
448                 if(!link->reserve(this))
449                 {
450                         // If we found another train and it's not headed straight for us, we can keep the blocks we got
451                         int other_entry = link->get_train()->get_entry_to_block(*link);
452                         if(other_entry<0)
453                                 throw LogicError("Block reservation inconsistency");
454                         if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
455                         {
456                                 good = last;
457                                 good_sens = nsens;
458                         }
459                         pending_block = link;
460                         break;
461                 }
462
463                 if(link->get_turnout_id())
464                 {
465                         const Block::Endpoint &ep = link->get_endpoints()[entry];
466                         const Endpoint &track_ep = ep.track->get_type().get_endpoints()[ep.track_ep];
467
468                         // Keep the blocks reserved so far, as either us or the other train can diverge
469                         good = last;
470                         good_sens = nsens;
471
472                         // Figure out what path we'd like to take on the turnout
473                         int path = -1;
474                         if(route)
475                                 path = route->get_turnout(link->get_turnout_id());
476                         if(path<0)
477                                 path = ep.track->get_active_path();
478                         if(!((track_ep.paths>>path)&1))
479                         {
480                                 for(unsigned i=0; track_ep.paths>>i; ++i)
481                                         if((track_ep.paths>>i)&1)
482                                                 path = i;
483                         }
484
485                         if(path!=static_cast<int>(ep.track->get_active_path()))
486                         {
487                                 // The turnout is set to wrong path - switch and wait for it
488                                 link->reserve(0);
489                                 pending_block = link;
490                                 ep.track->set_active_path(path);
491                                 break;
492                         }
493                 }
494
495                 rsv_blocks.push_back(BlockRef(link, entry));
496                 last = &rsv_blocks.back();
497                 if(last->block->get_sensor_id())
498                 {
499                         ++nsens;
500                         got_more = true;
501                 }
502
503                 if(route && !on_route)
504                         on_route = route->get_tracks().count(link->get_endpoints()[entry].track);
505         }
506
507         // Unreserve blocks that were not good
508         while(!rsv_blocks.empty() && last!=good)
509         {
510                 last->block->reserve(0);
511                 rsv_blocks.erase(--rsv_blocks.end());
512                 if(!rsv_blocks.empty())
513                         last = &rsv_blocks.back();
514         }
515
516         if(got_more)
517                 update_speed();
518
519         return good_sens;
520 }
521
522 void Train::update_speed()
523 {
524         Driver &driver = layout.get_driver();
525
526         unsigned speed;
527         if(!target_speed)
528         {
529                 speed = 0;
530                 set_status("Stopped");
531         }
532         else
533         {
534                 unsigned nsens = 0;
535                 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
536                         if(i->block->get_sensor_id())
537                                 ++nsens;
538
539                 unsigned slow_speed = find_speed(0.1);  // 31.3 km/h
540                 if(nsens==0)
541                 {
542                         speed = 0;
543                         pure_speed = false;
544                         set_status("Blocked");
545                 }
546                 else if(nsens==1 && target_speed>slow_speed)
547                 {
548                         speed = slow_speed;
549                         pure_speed = false;
550                         set_status("Slow");
551                 }
552                 else
553                 {
554                         speed = target_speed;
555                         set_status(format("Traveling %d kmh", travel_speed));
556                 }
557         }
558
559         driver.set_loco_speed(address, speed);
560 }
561
562 float Train::get_real_speed(unsigned i) const
563 {
564         if(real_speed[i].weight)
565                 return real_speed[i].speed;
566
567         unsigned low;
568         unsigned high;
569         for(low=i; low>0; --low)
570                 if(real_speed[low].weight)
571                         break;
572         for(high=i; high<14; ++high)
573                 if(real_speed[high].weight)
574                         break;
575
576         if(real_speed[high].weight)
577         {
578                 if(real_speed[low].weight)
579                 {
580                         float f = float(i-low)/(high-low);
581                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
582                 }
583                 else
584                         return real_speed[high].speed*float(i)/high;
585         }
586         else if(real_speed[low].weight)
587                 return real_speed[low].speed*float(i)/low;
588         else
589                 return 0;
590 }
591
592 unsigned Train::find_speed(float real) const
593 {
594         if(real<=real_speed[0].speed)
595                 return 0;
596
597         unsigned low = 0;
598         unsigned high = 0;
599         for(unsigned i=0; (!high && i<=14); ++i)
600                 if(real_speed[i].weight)
601                 {
602                         if(real_speed[i].speed<real)
603                                 low = i;
604                         else
605                                 high = i;
606                 }
607         if(!high)
608         {
609                 if(!low)
610                         return 0;
611                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
612         }
613
614         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
615         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
616 }
617
618 void Train::set_status(const string &s)
619 {
620         status = s;
621         signal_status_changed.emit(s);
622 }
623
624 void Train::set_position(const Block::Endpoint &bep)
625 {
626         cur_track = bep.track;
627         cur_track_ep = bep.track_ep;
628         offset = 0;
629         pos = cur_track->get_endpoint_position(cur_track_ep);
630 }
631
632 void Train::release_blocks(list<BlockRef> &blocks)
633 {
634         release_blocks(blocks, blocks.begin(), blocks.end());
635 }
636
637 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
638 {
639         while(begin!=end)
640         {
641                 Block *block = begin->block;
642                 blocks.erase(begin++);
643                 block->reserve(0);
644         }
645 }
646
647 void Train::reverse_blocks(list<BlockRef> &blocks) const
648 {
649         blocks.reverse();
650         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
651                 i->entry = i->block->traverse(i->entry);
652 }
653
654
655 Train::RealSpeed::RealSpeed():
656         speed(0),
657         weight(0)
658 { }
659
660 void Train::RealSpeed::add(float s, float w)
661 {
662         speed = (speed*weight+s*w)/(weight+w);
663         weight = min(weight+w, 300.0f);
664 }
665
666
667 Train::Loader::Loader(Train &t):
668         DataFile::BasicLoader<Train>(t),
669         prev_block(0)
670 {
671         add("block",       &Loader::block);
672         add("block_hint",  &Loader::block_hint);
673         add("name",        &Loader::name);
674         add("real_speed",  &Loader::real_speed);
675         add("route",       &Loader::route);
676 }
677
678 void Train::Loader::block(unsigned id)
679 {
680         Block &blk = obj.layout.get_block(id);
681         int entry = -1;
682         if(prev_block)
683                 entry = blk.get_endpoint_by_link(*prev_block);
684         if(entry<0)
685                 entry = 0;
686
687         blk.reserve(&obj);
688         obj.cur_blocks.push_back(BlockRef(&blk, entry));
689         obj.set_status("Stopped");
690         obj.set_position(blk.get_endpoints()[entry]);
691
692         prev_block = &blk;
693 }
694
695 void Train::Loader::block_hint(unsigned id)
696 {
697         prev_block = &obj.layout.get_block(id);
698 }
699
700 void Train::Loader::name(const string &n)
701 {
702         obj.set_name(n);
703 }
704
705 void Train::Loader::real_speed(unsigned i, float speed, float weight)
706 {
707         obj.real_speed[i].speed = speed;
708         obj.real_speed[i].weight = weight;
709 }
710
711 void Train::Loader::route(const string &n)
712 {
713         obj.set_route(&obj.layout.get_route(n));
714 }
715
716 } // namespace Marklin