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