]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/blockallocator.cpp
Don't continue reserving until the turnout is done changing its path
[r2c2.git] / source / libr2c2 / blockallocator.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/core/raii.h>
3 #include "blockallocator.h"
4 #include "block.h"
5 #include "catalogue.h"
6 #include "driver.h"
7 #include "layout.h"
8 #include "trackcircuit.h"
9 #include "trackiter.h"
10 #include "train.h"
11 #include "vehicle.h"
12
13 using namespace std;
14 using namespace Msp;
15
16 namespace R2C2 {
17
18 struct BlockAllocator::BlockMatch
19 {
20         const Block &block;
21
22         BlockMatch(const Block &b): block(b) { }
23
24         bool operator()(const BlockIter &bi) const { return &*bi==&block; }
25 };
26
27
28 BlockAllocator::BlockAllocator(Train &t):
29         train(t),
30         cur_blocks_end(blocks.end()),
31         pending_block(0),
32         stop_at_block(0),
33         reserving(false),
34         advancing(false)
35 {
36         Layout &layout = train.get_layout();
37         layout.signal_block_reserved.connect(sigc::mem_fun(this, &BlockAllocator::block_reserved));
38         layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &BlockAllocator::sensor_state_changed));
39
40         const set<Track *> &tracks = layout.get_all<Track>();
41         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
42                 if((*i)->get_turnout_id())
43                 {
44                         (*i)->signal_path_changing.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changing), sigc::ref(**i))));
45                         (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changed), sigc::ref(**i))));
46                 }
47 }
48
49 void BlockAllocator::set_active(bool a)
50 {
51         active = a;
52         if(active)
53                 reserve_more();
54         else
55         {
56                 release_blocks_end(cur_blocks_end);
57                 pending_block = 0;
58         }
59 }
60
61 void BlockAllocator::start_from(const BlockIter &block)
62 {
63         if(!block)
64                 throw invalid_argument("BlockAllocator::start_from");
65
66         clear();
67         reserve_block(block);
68 }
69
70 void BlockAllocator::rewind_to(const Block &block)
71 {
72         if(!active)
73                 return;
74
75         BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(block));
76         if(i!=blocks.end())
77         {
78                 release_blocks_end(i);
79                 reserve_more();
80         }
81 }
82
83 void BlockAllocator::clear()
84 {
85         release_blocks_begin(blocks.end());
86         active = false;
87         pending_block = 0;
88         stop_at_block = 0;
89 }
90
91 void BlockAllocator::stop_at(const Block *block)
92 {
93         stop_at_block = block;
94         if(active && !block)
95                 reserve_more();
96 }
97
98 const BlockIter &BlockAllocator::first() const
99 {
100         if(blocks.empty())
101                 throw logic_error("no blocks");
102         return blocks.front();
103 }
104
105 const BlockIter &BlockAllocator::last() const
106 {
107         if(blocks.empty())
108                 throw logic_error("no blocks");
109         BlockList::const_iterator i = --blocks.end();
110         if(i->block()==pending_block)
111                 --i;
112         return *i;
113 }
114
115 const BlockIter &BlockAllocator::last_current() const
116 {
117         if(blocks.empty())
118                 throw logic_error("no blocks");
119         if(cur_blocks_end==blocks.begin())
120                 throw logic_error("internal error (no current blocks)");
121         BlockList::const_iterator i = cur_blocks_end;
122         return *--i;
123 }
124
125 const BlockIter &BlockAllocator::iter_for(const Block &block) const
126 {
127         BlockList::const_iterator i = find_if(blocks.begin(), blocks.end(), BlockMatch(block));
128         if(i==blocks.end())
129                 throw key_error(&block);
130         return *i;
131 }
132
133 bool BlockAllocator::has_block(const Block &block) const
134 {
135         return find_if(blocks.begin(), blocks.end(), BlockMatch(block))!=blocks.end();
136 }
137
138 bool BlockAllocator::is_block_current(const Block &block) const
139 {
140         BlockList::const_iterator end = cur_blocks_end;
141         return find_if(blocks.begin(), end, BlockMatch(block))!=cur_blocks_end;
142 }
143
144 void BlockAllocator::reserve_more()
145 {
146         if(blocks.empty())
147                 throw logic_error("no blocks");
148
149         BlockIter start = blocks.back();
150         if(&*start==stop_at_block)
151                 return;
152         else if(&*start==pending_block)
153         {
154                 TrackIter track = start.track_iter();
155                 if(track->is_path_changing() || !track.endpoint().has_path(track->get_active_path()))
156                         return;
157         }
158
159         pending_block = 0;
160
161         // See how many sensor blocks and how much track we already have
162         unsigned nsens = 0;
163         float dist = 0;
164         for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
165         {
166                 if((*i)->get_sensor_id())
167                         ++nsens;
168                 if(nsens>0)
169                         dist += (*i)->get_path_length(i->entry());
170         }
171
172         float approach_margin = 50*train.get_layout().get_catalogue().get_scale();
173         float min_dist = train.get_controller().get_braking_distance()*1.3+approach_margin*2;
174
175         BlockIter block = start;
176
177         SetFlag setf(reserving);
178
179         while(1)
180         {
181                 BlockIter prev = block;
182                 block = block.next();
183                 if(!block || block->get_endpoints().size()<2)
184                         // The track ends here
185                         break;
186
187                 if(block->get_turnout_id() && !prev->get_turnout_id())
188                 {
189                         /* We are arriving at a turnout.  See if we have enough blocks and
190                         distance reserved. */
191                         if(nsens>=3 && dist>=min_dist)
192                                 break;
193                 }
194
195                 if(!reserve_block(block))
196                 {
197                         pending_block = &*block;
198                         break;
199                 }
200
201                 if(cur_blocks_end==blocks.end())
202                         --cur_blocks_end;
203
204                 TrackIter track = block.track_iter();
205                 if(track->is_path_changing())
206                 {
207                         pending_block = &*block;
208                         break;
209                 }
210                 else
211                 {
212                         const TrackType::Endpoint &entry_ep = track.endpoint();
213                         unsigned path = track->get_active_path();
214                         if(!entry_ep.has_path(path))
215                         {
216                                 const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
217                                 if(entry_ep.has_common_paths(exit_ep))
218                                 {
219                                         unsigned mask = entry_ep.paths&exit_ep.paths;
220                                         for(path=0; mask>1; ++path, mask>>=1) ;
221
222                                         track->set_active_path(path);
223                                         if(track->is_path_changing())
224                                         {
225                                                 pending_block = &*block;
226                                                 break;
227                                         }
228                                 }
229                                 else
230                                         // XXX Do something here
231                                         break;
232                         }
233                 }
234
235                 if(&*block==stop_at_block)
236                         break;
237
238                 if(block->get_sensor_id())
239                         ++nsens;
240                 if(nsens>0)
241                         dist += block->get_path_length(block.entry());
242         }
243
244         // Make any sensorless blocks at the beginning immediately current
245         while(cur_blocks_end!=blocks.end() && !(*cur_blocks_end)->get_sensor_id())
246                 ++cur_blocks_end;
247 }
248
249 bool BlockAllocator::reserve_block(const BlockIter &block)
250 {
251         /* Add it to the list first to present a consistent state in block_reserved
252         signal. */
253         blocks.push_back(block);
254         try
255         {
256                 if(!block->reserve(&train))
257                 {
258                         blocks.pop_back();
259                         return false;
260                 }
261
262                 return true;
263         }
264         catch(...)
265         {
266                 blocks.pop_back();
267                 throw;
268         }
269 }
270
271 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
272 {
273         for(BlockList::iterator i=blocks.begin(); i!=end; )
274                 release_block(i++);
275 }
276
277 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
278 {
279         // Guard against decrementing blocks.begin()
280         if(begin==blocks.begin())
281                 return release_blocks_begin(blocks.end());
282
283         if(begin==blocks.end())
284                 return;
285
286         /* Release the blocks in reverse order so that a consistent state is
287         presented in block_reserved signal. */
288         bool done = false;
289         for(BlockList::iterator i=--blocks.end(); !done; )
290         {
291                 done = (i==begin);
292                 release_block(i--);
293         }
294 }
295
296 void BlockAllocator::release_block(const BlockList::iterator &i)
297 {
298         if(advancing)
299                 throw logic_error("cannot release while advancing");
300         if(i==cur_blocks_end)
301                 ++cur_blocks_end;
302         if(&**i==pending_block)
303                 pending_block = 0;
304
305         Block &block = **i;
306         blocks.erase(i);
307         block.reserve(0);
308 }
309
310 void BlockAllocator::reverse()
311 {
312         release_blocks_end(cur_blocks_end);
313         blocks.reverse();
314         for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
315                 *i = i->reverse();
316
317         if(active)
318                 reserve_more();
319 }
320
321 void BlockAllocator::turnout_path_changing(Track &track)
322 {
323         BlockList::iterator i = find_if(blocks.begin(), blocks.end(), BlockMatch(track.get_block()));
324         if(i!=blocks.end())
325         {
326                 ++i;
327                 release_blocks_end(i);
328                 pending_block = &track.get_block();
329         }
330 }
331
332 void BlockAllocator::turnout_path_changed(Track &track)
333 {
334         if(&track.get_block()==pending_block && !reserving)
335                 reserve_more();
336 }
337
338 void BlockAllocator::block_reserved(Block &block, const Train *tr)
339 {
340         if(&block==pending_block && !tr && !reserving)
341                 reserve_more();
342 }
343
344 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
345 {
346         Block *block = 0;
347         if(TrackCircuit *tc = dynamic_cast<TrackCircuit *>(&sensor))
348                 block = &tc->get_block();
349         else
350                 return;
351
352         if(block->get_train()!=&train)
353                 return;
354
355         if(state==Sensor::MAYBE_ACTIVE)
356         {
357                 // Find the first sensor block from our reserved blocks that isn't this sensor
358                 BlockList::iterator end;
359                 unsigned result = 0;
360                 for(end=cur_blocks_end; end!=blocks.end(); ++end)
361                         if((*end)->get_sensor_id())
362                         {
363                                 if(&**end!=block)
364                                 {
365                                         if(result==0)
366                                                 result = 2;
367                                         else if(result==1)
368                                                 break;
369                                 }
370                                 else if(result==0)
371                                         result = 1;
372                                 else if(result==2)
373                                         result = 3;
374                         }
375
376                 if(result==1)
377                 {
378                         /* Advance the train to the new blocks.  Update cur_blocks_end first
379                         to keep things in sync. */
380                         SetFlag setf(advancing);
381                         BlockList::iterator i = cur_blocks_end;
382                         cur_blocks_end = end;
383                         for(; i!=end; ++i)
384                                 train.signal_advanced.emit(**i);
385                         advancing = false;
386
387                         if(active)
388                                 reserve_more();
389                 }
390                 else if(result==3)
391                         train.get_layout().emergency("Sensor for "+train.get_name()+" triggered out of order");
392         }
393         else if(state==Sensor::INACTIVE)
394         {
395                 const Vehicle &veh = train.get_vehicle(train.get_controller().get_reverse() ? 0 : train.get_n_vehicles()-1);
396                 const Block &veh_block = veh.get_track()->get_block();
397                 const Driver &driver = train.get_layout().get_driver();
398
399                 /* Sensors aren't guaranteed to be detriggered in order.  Go through the
400                 block list and locate the first sensor that's still active. */
401                 BlockList::iterator end = blocks.end();
402                 for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
403                 {
404                         // Avoid freeing blocks that still hold the train's vehicles
405                         if(&**i==&veh_block)
406                                 break;
407
408                         if((*i)->get_sensor_id())
409                         {
410                                 if(driver.get_sensor((*i)->get_sensor_id()))
411                                         break;
412                                 else
413                                         end = i;
414                         }
415                 }
416                 
417                 if(end!=blocks.end())
418                         // Free blocks up to the last inactive sensor
419                         release_blocks_begin(++end);
420         }
421 }
422
423 void BlockAllocator::save(list<DataFile::Statement> &st) const
424 {
425         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
426         {
427                 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
428                 BlockIter prev;
429                 if(train.get_controller().get_reverse())
430                 {
431                         cur_blocks.reverse();
432                         prev = cur_blocks.front().next();
433                 }
434                 else
435                         prev = cur_blocks.front().flip();
436
437                 st.push_back((DataFile::Statement("hint"), prev->get_id()));
438
439                 for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
440                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
441         }
442 }
443
444
445 BlockAllocator::Loader::Loader(BlockAllocator &ba):
446         DataFile::ObjectLoader<BlockAllocator>(ba),
447         valid(true)
448 {
449         add("block", &Loader::block);
450         add("hint",  &Loader::hint);
451 }
452
453 void BlockAllocator::Loader::block(unsigned id)
454 {
455         if(!valid)
456                 return;
457
458         Block *blk;
459         try
460         {
461                 blk = &obj.train.get_layout().get_block(id);
462         }
463         catch(const key_error &)
464         {
465                 valid = false;
466                 return;
467         }
468
469         int entry = -1;
470         if(prev_block)
471                 entry = blk->get_endpoint_by_link(*prev_block);
472         if(entry<0)
473                 entry = 0;
474
475         obj.blocks.push_back(BlockIter(blk, entry));
476         blk->reserve(&obj.train);
477
478         if(blk->get_sensor_id())
479                 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_id(), true);
480
481         prev_block = blk;
482 }
483
484 void BlockAllocator::Loader::hint(unsigned id)
485 {
486         try
487         {
488                 prev_block = &obj.train.get_layout().get_block(id);
489         }
490         catch(const key_error &)
491         {
492                 valid = false;
493         }
494 }
495
496 } // namespace R2C2