]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/blockallocator.cpp
5a410ff20de0af908df94952d6d2bdb46348e14f
[r2c2.git] / source / libr2c2 / blockallocator.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/core/raii.h>
3 #include "beamgate.h"
4 #include "blockallocator.h"
5 #include "block.h"
6 #include "catalogue.h"
7 #include "driver.h"
8 #include "layout.h"
9 #include "trackcircuit.h"
10 #include "trackiter.h"
11 #include "train.h"
12 #include "vehicle.h"
13
14 using namespace std;
15 using namespace Msp;
16
17 namespace R2C2 {
18
19 struct BlockAllocator::BlockMatch
20 {
21         const Block &block;
22
23         BlockMatch(const Block &b): block(b) { }
24
25         bool operator()(const BlockIter &bi) const { return &*bi==&block; }
26 };
27
28
29 BlockAllocator::BlockAllocator(Train &t):
30         train(t),
31         active(false),
32         cur_blocks_end(blocks.end()),
33         next_sensor(0),
34         pending_block(0),
35         stop_at_block(0),
36         reserving(false),
37         advancing(false)
38 {
39         Layout &layout = train.get_layout();
40         layout.signal_block_reserved.connect(sigc::mem_fun(this, &BlockAllocator::block_reserved));
41         layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &BlockAllocator::sensor_state_changed));
42
43         const set<Track *> &tracks = layout.get_all<Track>();
44         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
45                 if((*i)->get_type().is_turnout())
46                 {
47                         (*i)->signal_path_changing.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changing), sigc::ref(**i))));
48                         (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changed), sigc::ref(**i))));
49                 }
50 }
51
52 void BlockAllocator::set_active(bool a)
53 {
54         active = a;
55         if(active)
56                 reserve_more();
57         else
58         {
59                 release_blocks_end(cur_blocks_end);
60                 pending_block = 0;
61         }
62 }
63
64 bool BlockAllocator::start_from(const BlockIter &block)
65 {
66         if(!block)
67                 throw invalid_argument("BlockAllocator::start_from");
68
69         float remaining_length = 0;
70         unsigned n_vehs = train.get_n_vehicles();
71         for(unsigned i=0; i<n_vehs; ++i)
72                 remaining_length += train.get_vehicle(i).get_type().get_length();
73
74         clear();
75
76         BlockList blocks_to_reserve;
77         for(BlockIter b=block; b; b=b.next())
78         {
79                 if(b->get_train())
80                         break;
81                 blocks_to_reserve.push_back(b);
82                 for(TrackIter t=b.track_iter(); (t && &t->get_block()==&*b); t=t.next())
83                         remaining_length -= t->get_path_length();
84                 if(remaining_length<=0)
85                         break;
86         }
87
88         if(remaining_length>0)
89                 return false;
90
91         for(BlockList::iterator i=blocks_to_reserve.begin(); i!=blocks_to_reserve.end(); ++i)
92         {
93                 blocks.push_back(*i);
94                 try
95                 {
96                         (*i)->reserve(&train);
97                 }
98                 catch(...)
99                 {
100                         blocks.pop_back();
101                         while(i!=blocks_to_reserve.begin())
102                         {
103                                 blocks.pop_back();
104                                 (*--i)->reserve(0);
105                         }
106                         throw;
107                 }
108         }
109
110         return true;
111 }
112
113 void BlockAllocator::rewind_to(const Block &block)
114 {
115         if(!active)
116                 return;
117
118         BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(block));
119         if(i!=blocks.end())
120         {
121                 release_blocks_end(i);
122                 reserve_more();
123         }
124 }
125
126 void BlockAllocator::clear()
127 {
128         release_blocks_begin(blocks.end());
129         active = false;
130         next_sensor = 0;
131         pending_block = 0;
132         stop_at_block = 0;
133 }
134
135 void BlockAllocator::stop_at(const Block *block)
136 {
137         stop_at_block = block;
138         if(active && !block)
139                 reserve_more();
140 }
141
142 const BlockIter &BlockAllocator::first() const
143 {
144         if(blocks.empty())
145                 throw logic_error("no blocks");
146         return blocks.front();
147 }
148
149 const BlockIter &BlockAllocator::last() const
150 {
151         if(blocks.empty())
152                 throw logic_error("no blocks");
153         BlockList::const_iterator i = --blocks.end();
154         if(i->block()==pending_block)
155                 --i;
156         return *i;
157 }
158
159 const BlockIter &BlockAllocator::last_current() const
160 {
161         if(blocks.empty())
162                 throw logic_error("no blocks");
163         if(cur_blocks_end==blocks.begin())
164                 throw logic_error("internal error (no current blocks)");
165         BlockList::const_iterator i = cur_blocks_end;
166         return *--i;
167 }
168
169 const BlockIter &BlockAllocator::iter_for(const Block &block) const
170 {
171         BlockList::const_iterator i = find_if(blocks.begin(), blocks.end(), BlockMatch(block));
172         if(i==blocks.end())
173                 throw key_error(&block);
174         return *i;
175 }
176
177 bool BlockAllocator::has_block(const Block &block) const
178 {
179         return find_if(blocks.begin(), blocks.end(), BlockMatch(block))!=blocks.end();
180 }
181
182 bool BlockAllocator::is_block_current(const Block &block) const
183 {
184         BlockList::const_iterator end = cur_blocks_end;
185         return find_if(blocks.begin(), end, BlockMatch(block))!=cur_blocks_end;
186 }
187
188 void BlockAllocator::reserve_more()
189 {
190         if(blocks.empty())
191                 throw logic_error("no blocks");
192
193         BlockIter start = blocks.back();
194         if(&*start==stop_at_block)
195                 return;
196         else if(&*start==pending_block)
197         {
198                 TrackIter track = start.track_iter();
199                 if(track->is_path_changing() || !track.endpoint().has_path(track->get_active_path()))
200                         return;
201         }
202
203         pending_block = 0;
204
205         // See how many sensor blocks and how much track we already have
206         unsigned nsens = 0;
207         float dist = 0;
208         for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
209         {
210                 if((*i)->get_sensor_address())
211                         ++nsens;
212                 if(nsens>0)
213                         dist += (*i)->get_path_length(i->entry());
214         }
215
216         float approach_margin = 50*train.get_layout().get_catalogue().get_scale();
217         float min_dist = train.get_controller().get_braking_distance()*1.3+approach_margin*2;
218
219         BlockIter block = start;
220
221         SetFlag setf(reserving);
222
223         while(1)
224         {
225                 BlockIter prev = block;
226                 block = block.next();
227                 if(!block || block->get_endpoints().size()<2)
228                         // The track ends here
229                         break;
230
231                 if(block->get_turnout_address() && !prev->get_turnout_address())
232                 {
233                         /* We are arriving at a turnout.  See if we have enough blocks and
234                         distance reserved. */
235                         if(nsens>=3 && dist>=min_dist)
236                                 break;
237                 }
238
239                 if(!reserve_block(block))
240                 {
241                         pending_block = &*block;
242                         break;
243                 }
244
245                 if(cur_blocks_end==blocks.end())
246                         --cur_blocks_end;
247
248                 TrackIter track = block.track_iter();
249                 if(track->is_path_changing())
250                 {
251                         pending_block = &*block;
252                         break;
253                 }
254                 else
255                 {
256                         const TrackType::Endpoint &entry_ep = track.endpoint();
257                         unsigned path = track->get_active_path();
258                         if(!entry_ep.has_path(path))
259                         {
260                                 const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
261                                 if(entry_ep.has_common_paths(exit_ep))
262                                 {
263                                         unsigned mask = entry_ep.paths&exit_ep.paths;
264                                         for(path=0; mask>1; ++path, mask>>=1) ;
265
266                                         track->set_active_path(path);
267                                         if(track->is_path_changing())
268                                         {
269                                                 pending_block = &*block;
270                                                 break;
271                                         }
272                                 }
273                                 else
274                                         // XXX Do something here
275                                         break;
276                         }
277                 }
278
279                 if(&*block==stop_at_block)
280                         break;
281
282                 if(block->get_sensor_address())
283                         ++nsens;
284                 if(nsens>0)
285                         dist += block->get_path_length(block.entry());
286         }
287
288         if(!next_sensor)
289         {
290                 update_next_sensor(0);
291                 // Immediately advance to just before the next sensor
292                 advance_front(next_sensor);
293         }
294 }
295
296 bool BlockAllocator::reserve_block(const BlockIter &block)
297 {
298         /* Add it to the list first to present a consistent state in block_reserved
299         signal. */
300         blocks.push_back(block);
301
302         bool first_reserve = (cur_blocks_end==blocks.end());
303         if(first_reserve)
304                 --cur_blocks_end;
305
306         try
307         {
308                 if(!block->reserve(&train))
309                 {
310                         if(first_reserve)
311                                 cur_blocks_end = blocks.end();
312                         blocks.pop_back();
313                         return false;
314                 }
315
316                 return true;
317         }
318         catch(...)
319         {
320                 if(first_reserve)
321                         cur_blocks_end = blocks.end();
322                 blocks.pop_back();
323                 throw;
324         }
325 }
326
327 void BlockAllocator::advance_front(const Block *block, bool inclusive)
328 {
329         BlockList::iterator end;
330         if(block)
331         {
332                 end = cur_blocks_end;
333                 if(inclusive)
334                         --end;
335                 end = find_if(end, blocks.end(), BlockMatch(*block));
336                 if(inclusive && end!=blocks.end())
337                         ++end;
338         }
339         else
340                 end = blocks.end();
341
342         if(end==blocks.end() && blocks.back().block()==pending_block)
343                 --end;
344
345         SetFlag setf(advancing);
346         BlockList::iterator i = cur_blocks_end;
347         // Update cur_blocks_end first to keep things consistent.
348         cur_blocks_end = end;
349         for(; i!=end; ++i)
350                 train.signal_advanced.emit(**i);
351 }
352
353 void BlockAllocator::advance_front(const Sensor *sensor)
354 {
355         if(sensor)
356                 advance_front(sensor->get_block(), dynamic_cast<const BeamGate *>(sensor));
357         else
358                 advance_front(0, false);
359 }
360
361 void BlockAllocator::advance_back()
362 {
363         bool rev = train.get_controller().get_reverse();
364         const Vehicle &veh = train.get_vehicle(rev ? 0 : train.get_n_vehicles()-1);
365         const Block &veh_block = veh.get_placement().get_position(rev ? VehiclePlacement::FRONT_AXLE : VehiclePlacement::BACK_AXLE)->get_block();
366
367         /* Sensors aren't guaranteed to be detriggered in order.  Go through the
368         block list and locate the first sensor that's still active. */
369         BlockList::iterator end = blocks.end();
370         for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
371         {
372                 Block *block = &**i;
373                 list<Sensor *> sensors;
374
375                 /* Collect all sensors from the block in the order they are expected to
376                 detrigger. */
377                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
378                         if(!j->get_attachments().empty())
379                         {
380                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
381                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
382                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
383                                                 sensors.push_back(gate);
384                         }
385
386                 if(Sensor *sensor = (*i)->get_sensor())
387                         sensors.push_back(sensor);
388
389                 /* See if any sensor is still active, and record the position of the
390                 last inactive sensor. */
391                 bool active_sensor = false;
392                 for(list<Sensor *>::const_iterator j=sensors.begin(); (!active_sensor && j!=sensors.end()); ++j)
393                 {
394                         if((*j)->get_state())
395                                 active_sensor = true;
396                         else
397                                 end = i;
398                 }
399
400                 // Stop if we encounter an active sensor or the train's last vehicle
401                 if(block==&veh_block || active_sensor)
402                 {
403                         if(end!=blocks.end())
404                         {
405                                 /* If the last inactive sensor was in an earlier block, release
406                                 that block as well. */
407                                 if(i!=end)
408                                         ++end;
409                                 release_blocks_begin(end);
410                         }
411                         return;
412                 }
413         }
414 }
415
416 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
417 {
418         for(BlockList::iterator i=blocks.begin(); i!=end; )
419                 release_block(i++);
420 }
421
422 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
423 {
424         // Guard against decrementing blocks.begin()
425         if(begin==blocks.begin())
426                 return release_blocks_begin(blocks.end());
427
428         if(begin==blocks.end())
429                 return;
430
431         /* Release the blocks in reverse order so that a consistent state is
432         presented in block_reserved signal. */
433         bool done = false;
434         for(BlockList::iterator i=--blocks.end(); !done; )
435         {
436                 done = (i==begin);
437                 release_block(i--);
438         }
439 }
440
441 void BlockAllocator::release_block(const BlockList::iterator &i)
442 {
443         if(advancing)
444                 throw logic_error("cannot release while advancing");
445         if(i==cur_blocks_end)
446                 ++cur_blocks_end;
447         if(next_sensor && &**i==next_sensor->get_block())
448                 next_sensor = 0;
449         if(&**i==pending_block)
450                 pending_block = 0;
451
452         Block &block = **i;
453         blocks.erase(i);
454         block.reserve(0);
455 }
456
457 void BlockAllocator::reverse()
458 {
459         release_blocks_end(cur_blocks_end);
460         blocks.reverse();
461         for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
462                 *i = i->reverse();
463
464         if(active)
465                 reserve_more();
466 }
467
468 void BlockAllocator::turnout_path_changing(Track &track)
469 {
470         BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(track.get_block()));
471         if(i!=blocks.end())
472         {
473                 ++i;
474                 release_blocks_end(i);
475                 pending_block = &track.get_block();
476         }
477 }
478
479 void BlockAllocator::turnout_path_changed(Track &track)
480 {
481         if(&track.get_block()==pending_block && !reserving)
482                 reserve_more();
483 }
484
485 void BlockAllocator::block_reserved(Block &block, const Train *tr)
486 {
487         if(&block==pending_block && !tr && !reserving)
488                 reserve_more();
489 }
490
491 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
492 {
493         Block *block = sensor.get_block();
494         if(!block || block->get_train()!=&train)
495                 return;
496
497         if(state==Sensor::MAYBE_ACTIVE)
498         {
499                 if(&sensor==next_sensor)
500                 {
501                         update_next_sensor(next_sensor);
502                         advance_front(next_sensor);
503
504                         if(active)
505                                 reserve_more();
506                 }
507                 else if(!is_block_current(*block))
508                         train.get_layout().emergency("Sensor for "+train.get_name()+" triggered out of order");
509         }
510         else if(state==Sensor::INACTIVE)
511                 advance_back();
512 }
513
514 void BlockAllocator::update_next_sensor(Sensor *after)
515 {
516         BeamGate *after_gate = dynamic_cast<BeamGate *>(after);
517
518         BlockList::iterator i = cur_blocks_end;
519         if(after)
520         {
521                 if(after_gate)
522                         --i;
523                 i = find_if(i, blocks.end(), BlockMatch(*after->get_block()));
524         }
525
526         for(; i!=blocks.end(); ++i)
527         {
528                 if(Sensor *sensor = (*i)->get_sensor())
529                 {
530                         if(!after_gate && sensor!=next_sensor)
531                         {
532                                 next_sensor = sensor;
533                                 return;
534                         }
535                 }
536
537                 Block *block = &**i;
538                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
539                         if(!j->get_attachments().empty())
540                         {
541                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
542                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
543                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
544                                         {
545                                                 if(after_gate)
546                                                 {
547                                                         if(gate==after_gate)
548                                                                 after_gate = 0;
549                                                 }
550                                                 else
551                                                 {
552                                                         next_sensor = gate;
553                                                         return;
554                                                 }
555                                         }
556                         }
557         }
558
559         next_sensor = 0;
560 }
561
562 void BlockAllocator::save(list<DataFile::Statement> &st) const
563 {
564         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
565         {
566                 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
567                 BlockIter prev;
568                 if(train.get_controller().get_reverse())
569                 {
570                         cur_blocks.reverse();
571                         prev = cur_blocks.front().next();
572                 }
573                 else
574                         prev = cur_blocks.front().flip();
575
576                 st.push_back((DataFile::Statement("hint"), prev->get_id()));
577
578                 for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
579                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
580         }
581 }
582
583
584 BlockAllocator::Loader::Loader(BlockAllocator &ba):
585         DataFile::ObjectLoader<BlockAllocator>(ba),
586         valid(true)
587 {
588         add("block", &Loader::block);
589         add("hint",  &Loader::hint);
590 }
591
592 void BlockAllocator::Loader::block(unsigned id)
593 {
594         if(!valid)
595                 return;
596
597         Block *blk;
598         try
599         {
600                 blk = &obj.train.get_layout().get_block(id);
601         }
602         catch(const key_error &)
603         {
604                 valid = false;
605                 return;
606         }
607
608         int entry = -1;
609         if(prev_block)
610                 entry = blk->get_endpoint_by_link(*prev_block);
611         if(entry<0)
612                 entry = 0;
613
614         obj.blocks.push_back(BlockIter(blk, entry));
615         blk->reserve(&obj.train);
616
617         if(blk->get_sensor_address())
618                 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_address(), true);
619
620         prev_block = blk;
621 }
622
623 void BlockAllocator::Loader::hint(unsigned id)
624 {
625         try
626         {
627                 prev_block = &obj.train.get_layout().get_block(id);
628         }
629         catch(const key_error &)
630         {
631                 valid = false;
632         }
633 }
634
635 } // namespace R2C2