]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/blockallocator.cpp
Basic support for beam gate sensors
[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         Sensor *last_inactive = 0;
316         for(BlockList::iterator i=blocks.begin(); (i!=cur_blocks_end && i->block()!=&veh_block); ++i)
317         {
318                 list<Sensor *> sensors;
319                 if(Sensor *sensor = (*i)->get_sensor())
320                         sensors.push_back(sensor);
321
322                 Block *block = &**i;
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                 for(list<Sensor *>::const_iterator j=sensors.begin(); j!=sensors.end(); ++j)
333                 {
334                         if((*j)->get_state())
335                         {
336                                 if(last_inactive)
337                                 {
338                                         if(dynamic_cast<BeamGate *>(*j))
339                                                 ++i;
340                                         release_blocks_begin(i);
341                                 }
342                                 return;
343                         }
344                         else
345                                 last_inactive = *j;
346                 }
347         }
348 }
349
350 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
351 {
352         for(BlockList::iterator i=blocks.begin(); i!=end; )
353                 release_block(i++);
354 }
355
356 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
357 {
358         // Guard against decrementing blocks.begin()
359         if(begin==blocks.begin())
360                 return release_blocks_begin(blocks.end());
361
362         if(begin==blocks.end())
363                 return;
364
365         /* Release the blocks in reverse order so that a consistent state is
366         presented in block_reserved signal. */
367         bool done = false;
368         for(BlockList::iterator i=--blocks.end(); !done; )
369         {
370                 done = (i==begin);
371                 release_block(i--);
372         }
373 }
374
375 void BlockAllocator::release_block(const BlockList::iterator &i)
376 {
377         if(advancing)
378                 throw logic_error("cannot release while advancing");
379         if(i==cur_blocks_end)
380                 ++cur_blocks_end;
381         if(next_sensor && &**i==next_sensor->get_block())
382                 next_sensor = 0;
383         if(&**i==pending_block)
384                 pending_block = 0;
385
386         Block &block = **i;
387         blocks.erase(i);
388         block.reserve(0);
389 }
390
391 void BlockAllocator::reverse()
392 {
393         release_blocks_end(cur_blocks_end);
394         blocks.reverse();
395         for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
396                 *i = i->reverse();
397
398         if(active)
399                 reserve_more();
400 }
401
402 void BlockAllocator::turnout_path_changing(Track &track)
403 {
404         BlockList::iterator i = find_if(blocks.begin(), blocks.end(), BlockMatch(track.get_block()));
405         if(i!=blocks.end())
406         {
407                 ++i;
408                 release_blocks_end(i);
409                 pending_block = &track.get_block();
410         }
411 }
412
413 void BlockAllocator::turnout_path_changed(Track &track)
414 {
415         if(&track.get_block()==pending_block && !reserving)
416                 reserve_more();
417 }
418
419 void BlockAllocator::block_reserved(Block &block, const Train *tr)
420 {
421         if(&block==pending_block && !tr && !reserving)
422                 reserve_more();
423 }
424
425 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
426 {
427         Block *block = sensor.get_block();
428         if(!block || block->get_train()!=&train)
429                 return;
430
431         if(state==Sensor::MAYBE_ACTIVE)
432         {
433                 if(&sensor==next_sensor)
434                 {
435                         update_next_sensor(next_sensor);
436                         advance_front(next_sensor);
437
438                         if(active)
439                                 reserve_more();
440                 }
441                 else if(!is_block_current(*block))
442                         train.get_layout().emergency("Sensor for "+train.get_name()+" triggered out of order");
443         }
444         else if(state==Sensor::INACTIVE)
445                 advance_back();
446 }
447
448 void BlockAllocator::update_next_sensor(Sensor *after)
449 {
450         BeamGate *after_gate = dynamic_cast<BeamGate *>(after);
451
452         BlockList::iterator i = cur_blocks_end;
453         if(after)
454         {
455                 if(after_gate)
456                         --i;
457                 i = find_if(i, blocks.end(), BlockMatch(*after->get_block()));
458         }
459
460         for(; i!=blocks.end(); ++i)
461         {
462                 if(Sensor *sensor = (*i)->get_sensor())
463                 {
464                         if(!after_gate && sensor!=next_sensor)
465                         {
466                                 next_sensor = sensor;
467                                 return;
468                         }
469                 }
470
471                 Block *block = &**i;
472                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
473                         if(!j->get_attachments().empty())
474                         {
475                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
476                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
477                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
478                                         {
479                                                 if(after_gate)
480                                                 {
481                                                         if(gate==after_gate)
482                                                                 after_gate = 0;
483                                                 }
484                                                 else
485                                                 {
486                                                         next_sensor = gate;
487                                                         return;
488                                                 }
489                                         }
490                         }
491         }
492
493         next_sensor = 0;
494 }
495
496 void BlockAllocator::save(list<DataFile::Statement> &st) const
497 {
498         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
499         {
500                 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
501                 BlockIter prev;
502                 if(train.get_controller().get_reverse())
503                 {
504                         cur_blocks.reverse();
505                         prev = cur_blocks.front().next();
506                 }
507                 else
508                         prev = cur_blocks.front().flip();
509
510                 st.push_back((DataFile::Statement("hint"), prev->get_id()));
511
512                 for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
513                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
514         }
515 }
516
517
518 BlockAllocator::Loader::Loader(BlockAllocator &ba):
519         DataFile::ObjectLoader<BlockAllocator>(ba),
520         valid(true)
521 {
522         add("block", &Loader::block);
523         add("hint",  &Loader::hint);
524 }
525
526 void BlockAllocator::Loader::block(unsigned id)
527 {
528         if(!valid)
529                 return;
530
531         Block *blk;
532         try
533         {
534                 blk = &obj.train.get_layout().get_block(id);
535         }
536         catch(const key_error &)
537         {
538                 valid = false;
539                 return;
540         }
541
542         int entry = -1;
543         if(prev_block)
544                 entry = blk->get_endpoint_by_link(*prev_block);
545         if(entry<0)
546                 entry = 0;
547
548         obj.blocks.push_back(BlockIter(blk, entry));
549         blk->reserve(&obj.train);
550
551         if(blk->get_sensor_id())
552                 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_id(), true);
553
554         prev_block = blk;
555 }
556
557 void BlockAllocator::Loader::hint(unsigned id)
558 {
559         try
560         {
561                 prev_block = &obj.train.get_layout().get_block(id);
562         }
563         catch(const key_error &)
564         {
565                 valid = false;
566         }
567 }
568
569 } // namespace R2C2