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