]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/blockallocator.cpp
Split vehicle placement code to a separate class
[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
261         bool first_reserve = (cur_blocks_end==blocks.end());
262         if(first_reserve)
263                 --cur_blocks_end;
264
265         try
266         {
267                 if(!block->reserve(&train))
268                 {
269                         if(first_reserve)
270                                 cur_blocks_end = blocks.end();
271                         blocks.pop_back();
272                         return false;
273                 }
274
275                 return true;
276         }
277         catch(...)
278         {
279                 if(first_reserve)
280                         cur_blocks_end = blocks.end();
281                 blocks.pop_back();
282                 throw;
283         }
284 }
285
286 void BlockAllocator::advance_front(const Block *block, bool inclusive)
287 {
288         BlockList::iterator end;
289         if(block)
290         {
291                 end = cur_blocks_end;
292                 if(inclusive)
293                         --end;
294                 end = find_if(end, blocks.end(), BlockMatch(*block));
295                 if(inclusive && end!=blocks.end())
296                         ++end;
297         }
298         else
299                 end = blocks.end();
300
301         SetFlag setf(advancing);
302         BlockList::iterator i = cur_blocks_end;
303         // Update cur_blocks_end first to keep things consistent.
304         cur_blocks_end = end;
305         for(; i!=end; ++i)
306                 train.signal_advanced.emit(**i);
307 }
308
309 void BlockAllocator::advance_front(const Sensor *sensor)
310 {
311         if(sensor)
312                 advance_front(sensor->get_block(), dynamic_cast<const BeamGate *>(sensor));
313         else
314                 advance_front(0, false);
315 }
316
317 void BlockAllocator::advance_back()
318 {
319         bool rev = train.get_controller().get_reverse();
320         const Vehicle &veh = train.get_vehicle(rev ? 0 : train.get_n_vehicles()-1);
321         const Block &veh_block = veh.get_placement().get_position(rev ? VehiclePlacement::FRONT_AXLE : VehiclePlacement::BACK_AXLE)->get_block();
322
323         /* Sensors aren't guaranteed to be detriggered in order.  Go through the
324         block list and locate the first sensor that's still active. */
325         BlockList::iterator end = blocks.end();
326         for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
327         {
328                 Block *block = &**i;
329                 list<Sensor *> sensors;
330
331                 /* Collect all sensors from the block in the order they are expected to
332                 detrigger. */
333                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
334                         if(!j->get_attachments().empty())
335                         {
336                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
337                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
338                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
339                                                 sensors.push_back(gate);
340                         }
341
342                 if(Sensor *sensor = (*i)->get_sensor())
343                         sensors.push_back(sensor);
344
345                 /* See if any sensor is still active, and record the position of the
346                 last inactive sensor. */
347                 bool active_sensor = false;
348                 for(list<Sensor *>::const_iterator j=sensors.begin(); (!active_sensor && j!=sensors.end()); ++j)
349                 {
350                         if((*j)->get_state())
351                                 active_sensor = true;
352                         else
353                                 end = i;
354                 }
355
356                 // Stop if we encounter an active sensor or the train's last vehicle
357                 if(block==&veh_block || active_sensor)
358                 {
359                         if(end!=blocks.end())
360                         {
361                                 /* If the last inactive sensor was in an earlier block, release
362                                 that block as well. */
363                                 if(i!=end)
364                                         ++end;
365                                 release_blocks_begin(end);
366                         }
367                         return;
368                 }
369         }
370 }
371
372 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
373 {
374         for(BlockList::iterator i=blocks.begin(); i!=end; )
375                 release_block(i++);
376 }
377
378 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
379 {
380         // Guard against decrementing blocks.begin()
381         if(begin==blocks.begin())
382                 return release_blocks_begin(blocks.end());
383
384         if(begin==blocks.end())
385                 return;
386
387         /* Release the blocks in reverse order so that a consistent state is
388         presented in block_reserved signal. */
389         bool done = false;
390         for(BlockList::iterator i=--blocks.end(); !done; )
391         {
392                 done = (i==begin);
393                 release_block(i--);
394         }
395 }
396
397 void BlockAllocator::release_block(const BlockList::iterator &i)
398 {
399         if(advancing)
400                 throw logic_error("cannot release while advancing");
401         if(i==cur_blocks_end)
402                 ++cur_blocks_end;
403         if(next_sensor && &**i==next_sensor->get_block())
404                 next_sensor = 0;
405         if(&**i==pending_block)
406                 pending_block = 0;
407
408         Block &block = **i;
409         blocks.erase(i);
410         block.reserve(0);
411 }
412
413 void BlockAllocator::reverse()
414 {
415         release_blocks_end(cur_blocks_end);
416         blocks.reverse();
417         for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
418                 *i = i->reverse();
419
420         if(active)
421                 reserve_more();
422 }
423
424 void BlockAllocator::turnout_path_changing(Track &track)
425 {
426         BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(track.get_block()));
427         if(i!=blocks.end())
428         {
429                 ++i;
430                 release_blocks_end(i);
431                 pending_block = &track.get_block();
432         }
433 }
434
435 void BlockAllocator::turnout_path_changed(Track &track)
436 {
437         if(&track.get_block()==pending_block && !reserving)
438                 reserve_more();
439 }
440
441 void BlockAllocator::block_reserved(Block &block, const Train *tr)
442 {
443         if(&block==pending_block && !tr && !reserving)
444                 reserve_more();
445 }
446
447 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
448 {
449         Block *block = sensor.get_block();
450         if(!block || block->get_train()!=&train)
451                 return;
452
453         if(state==Sensor::MAYBE_ACTIVE)
454         {
455                 if(&sensor==next_sensor)
456                 {
457                         update_next_sensor(next_sensor);
458                         advance_front(next_sensor);
459
460                         if(active)
461                                 reserve_more();
462                 }
463                 else if(!is_block_current(*block))
464                         train.get_layout().emergency("Sensor for "+train.get_name()+" triggered out of order");
465         }
466         else if(state==Sensor::INACTIVE)
467                 advance_back();
468 }
469
470 void BlockAllocator::update_next_sensor(Sensor *after)
471 {
472         BeamGate *after_gate = dynamic_cast<BeamGate *>(after);
473
474         BlockList::iterator i = cur_blocks_end;
475         if(after)
476         {
477                 if(after_gate)
478                         --i;
479                 i = find_if(i, blocks.end(), BlockMatch(*after->get_block()));
480         }
481
482         for(; i!=blocks.end(); ++i)
483         {
484                 if(Sensor *sensor = (*i)->get_sensor())
485                 {
486                         if(!after_gate && sensor!=next_sensor)
487                         {
488                                 next_sensor = sensor;
489                                 return;
490                         }
491                 }
492
493                 Block *block = &**i;
494                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
495                         if(!j->get_attachments().empty())
496                         {
497                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
498                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
499                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
500                                         {
501                                                 if(after_gate)
502                                                 {
503                                                         if(gate==after_gate)
504                                                                 after_gate = 0;
505                                                 }
506                                                 else
507                                                 {
508                                                         next_sensor = gate;
509                                                         return;
510                                                 }
511                                         }
512                         }
513         }
514
515         next_sensor = 0;
516 }
517
518 void BlockAllocator::save(list<DataFile::Statement> &st) const
519 {
520         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
521         {
522                 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
523                 BlockIter prev;
524                 if(train.get_controller().get_reverse())
525                 {
526                         cur_blocks.reverse();
527                         prev = cur_blocks.front().next();
528                 }
529                 else
530                         prev = cur_blocks.front().flip();
531
532                 st.push_back((DataFile::Statement("hint"), prev->get_id()));
533
534                 for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
535                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
536         }
537 }
538
539
540 BlockAllocator::Loader::Loader(BlockAllocator &ba):
541         DataFile::ObjectLoader<BlockAllocator>(ba),
542         valid(true)
543 {
544         add("block", &Loader::block);
545         add("hint",  &Loader::hint);
546 }
547
548 void BlockAllocator::Loader::block(unsigned id)
549 {
550         if(!valid)
551                 return;
552
553         Block *blk;
554         try
555         {
556                 blk = &obj.train.get_layout().get_block(id);
557         }
558         catch(const key_error &)
559         {
560                 valid = false;
561                 return;
562         }
563
564         int entry = -1;
565         if(prev_block)
566                 entry = blk->get_endpoint_by_link(*prev_block);
567         if(entry<0)
568                 entry = 0;
569
570         obj.blocks.push_back(BlockIter(blk, entry));
571         blk->reserve(&obj.train);
572
573         if(blk->get_sensor_id())
574                 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_id(), true);
575
576         prev_block = blk;
577 }
578
579 void BlockAllocator::Loader::hint(unsigned id)
580 {
581         try
582         {
583                 prev_block = &obj.train.get_layout().get_block(id);
584         }
585         catch(const key_error &)
586         {
587                 valid = false;
588         }
589 }
590
591 } // namespace R2C2