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