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