+#include <msp/core/maputils.h>
+#include <msp/core/raii.h>
+#include "blockallocator.h"
+#include "catalogue.h"
+#include "driver.h"
+#include "layout.h"
+#include "trackiter.h"
+#include "train.h"
+#include "vehicle.h"
+
+using namespace std;
+using namespace Msp;
+
+namespace R2C2 {
+
+BlockAllocator::BlockAllocator(Train &t):
+ train(t),
+ cur_blocks_end(blocks.end()),
+ pending_block(0),
+ stop_at_block(0),
+ reserving(false)
+{
+ Layout &layout = train.get_layout();
+ layout.signal_block_reserved.connect(sigc::mem_fun(this, &BlockAllocator::block_reserved));
+ layout.signal_block_state_changed.connect(sigc::mem_fun(this, &BlockAllocator::block_state_changed));
+
+ const set<Track *> &tracks = layout.get_tracks();
+ for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+ if((*i)->get_turnout_id())
+ (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changed), sigc::ref(**i))));
+}
+
+void BlockAllocator::start_from(Block &block, unsigned entry)
+{
+ release_blocks(blocks.begin(), blocks.end());
+
+ blocks.push_back(BlockIter(&block, entry));
+ if(!block.reserve(&train))
+ {
+ blocks.pop_back();
+ return;
+ }
+}
+
+void BlockAllocator::clear()
+{
+ release_blocks(blocks.begin(), blocks.end());
+ pending_block = 0;
+ stop_at_block = 0;
+}
+
+void BlockAllocator::stop_at(const Block *block)
+{
+ stop_at_block = block;
+}
+
+const BlockIter &BlockAllocator::first() const
+{
+ if(blocks.empty())
+ throw logic_error("no blocks");
+ return blocks.front();
+}
+
+const BlockIter &BlockAllocator::last() const
+{
+ if(blocks.empty())
+ throw logic_error("no blocks");
+ BlockList::const_iterator i = --blocks.end();
+ if(i->block()==pending_block)
+ --i;
+ return *i;
+}
+
+const BlockIter &BlockAllocator::last_current() const
+{
+ if(blocks.empty())
+ throw logic_error("no blocks");
+ if(cur_blocks_end==blocks.begin())
+ throw logic_error("internal error (no current blocks)");
+ BlockList::const_iterator i = cur_blocks_end;
+ return *--i;
+}
+
+int BlockAllocator::get_entry_to_block(const Block &block) const
+{
+ for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
+ if(i->block()==&block)
+ return i->entry();
+ return -1;
+}
+
+void BlockAllocator::reserve_more()
+{
+ if(blocks.empty())
+ throw logic_error("no blocks");
+
+ BlockIter start = blocks.back();
+ if(&*start==stop_at_block)
+ return;
+ else if(&*start==pending_block)
+ {
+ TrackIter track = start.track_iter();
+ if(!track.endpoint().has_path(track->get_active_path()))
+ return;
+ }
+
+ pending_block = 0;
+
+ // See how many sensor blocks and how much track we already have
+ unsigned nsens = 0;
+ float dist = 0;
+ for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
+ {
+ if((*i)->get_sensor_id())
+ ++nsens;
+ if(nsens>0)
+ dist += (*i)->get_path_length(i->entry());
+ }
+
+ float approach_margin = 50*train.get_layout().get_catalogue().get_scale();
+ float min_dist = train.get_controller().get_braking_distance()*1.3+approach_margin*2;
+
+ BlockIter block = start;
+
+ SetFlag setf(reserving);
+
+ while(1)
+ {
+ BlockIter prev = block;
+ block = block.next();
+ if(!block || block->get_endpoints().size()<2)
+ // The track ends here
+ break;
+
+ if(block->get_turnout_id() && !prev->get_turnout_id())
+ {
+ /* We are arriving at a turnout. See if we have enough blocks and
+ distance reserved. */
+ if(nsens>=3 && dist>=min_dist)
+ break;
+ }
+
+ blocks.push_back(block);
+ if(!block->reserve(&train))
+ {
+ blocks.pop_back();
+ pending_block = &*block;
+ break;
+ }
+
+ if(cur_blocks_end==blocks.end())
+ --cur_blocks_end;
+
+ TrackIter track = block.track_iter();
+ if(track->is_path_changing())
+ {
+ pending_block = &*block;
+ break;
+ }
+ else
+ {
+ const TrackType::Endpoint &entry_ep = track.endpoint();
+ unsigned path = track->get_active_path();
+ if(!entry_ep.has_path(path))
+ {
+ const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
+ if(entry_ep.has_common_paths(exit_ep))
+ {
+ unsigned mask = entry_ep.paths&exit_ep.paths;
+ for(path=0; mask>1; ++path, mask>>=1) ;
+
+ track->set_active_path(path);
+ if(track->is_path_changing())
+ {
+ pending_block = &*block;
+ break;
+ }
+ }
+ else
+ // XXX Do something here
+ break;
+ }
+ }
+
+ if(&*block==stop_at_block)
+ break;
+
+ if(block->get_sensor_id())
+ ++nsens;
+ if(nsens>0)
+ dist += block->get_path_length(block.entry());
+ }
+
+ // Make any sensorless blocks at the beginning immediately current
+ while(cur_blocks_end!=blocks.end() && !(*cur_blocks_end)->get_sensor_id())
+ ++cur_blocks_end;
+}
+
+void BlockAllocator::release_until(const Block &block)
+{
+ for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
+ if(i->block()==&block)
+ {
+ if(++i!=cur_blocks_end)
+ release_blocks(blocks.begin(), i);
+ return;
+ }
+}
+
+bool BlockAllocator::release_from(const Block &block)
+{
+ bool have_sensor = false;
+ for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i)
+ {
+ if(i->block()==&block)
+ {
+ if(have_sensor)
+ release_blocks(i, blocks.end());
+ return have_sensor;
+ }
+ else if((*i)->get_sensor_id())
+ have_sensor = true;
+ }
+
+ return false;
+}
+
+void BlockAllocator::release_noncurrent()
+{
+ release_blocks(cur_blocks_end, blocks.end());
+}
+
+void BlockAllocator::release_blocks(const BlockList::iterator &b, const BlockList::iterator &e)
+{
+ for(BlockList::iterator i=b; i!=e; )
+ {
+ if(cur_blocks_end==i)
+ cur_blocks_end = e;
+
+ Block &block = **i;
+ blocks.erase(i++);
+ block.reserve(0);
+ }
+}
+
+void BlockAllocator::reverse()
+{
+ release_noncurrent();
+ blocks.reverse();
+ for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
+ *i = i->reverse();
+}
+
+void BlockAllocator::turnout_path_changed(Track &track)
+{
+ for(list<BlockIter>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
+ if((*i)->get_turnout_id()==track.get_turnout_id() && !reserving && &**i==pending_block)
+ reserve_more();
+}
+
+void BlockAllocator::block_reserved(Block &block, const Train *tr)
+{
+ if(&block==pending_block && !tr && !reserving)
+ reserve_more();
+}
+
+void BlockAllocator::block_state_changed(Block &block, Block::State state)
+{
+ if(state==Block::MAYBE_ACTIVE)
+ {
+ // Find the first sensor block from our reserved blocks that isn't this sensor
+ BlockList::iterator end;
+ unsigned result = 0;
+ for(end=cur_blocks_end; end!=blocks.end(); ++end)
+ if((*end)->get_sensor_id())
+ {
+ if(&**end!=&block)
+ {
+ if(result==0)
+ result = 2;
+ else if(result==1)
+ break;
+ }
+ else if(result==0)
+ result = 1;
+ else if(result==2)
+ result = 3;
+ }
+
+ if(result==1)
+ {
+ // Move blocks up to the next sensor to our current blocks
+ for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
+ train.signal_advanced.emit(**j);
+ cur_blocks_end = end;
+ }
+ else if(result==3)
+ train.get_layout().emergency("Sensor for "+train.get_name()+" triggered out of order");
+ }
+ else if(state==Block::INACTIVE)
+ {
+ const Vehicle &veh = train.get_controller().get_reverse() ? train.get_vehicle(0) : train.get_vehicle(train.get_n_vehicles()-1);
+
+ // Find the first sensor in our current blocks that's still active
+ BlockList::iterator end = blocks.begin();
+ for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
+ {
+ if((*i)->has_track(*veh.get_track()))
+ break;
+ if((*i)->get_sensor_id())
+ {
+ if(train.get_layout().get_driver().get_sensor((*i)->get_sensor_id()))
+ break;
+ else
+ {
+ end = i;
+ ++end;
+ }
+ }
+ }
+
+ if(end!=blocks.begin() && end!=cur_blocks_end)
+ // Free blocks up to the last inactive sensor
+ release_blocks(blocks.begin(), end);
+ }
+}
+
+void BlockAllocator::save(list<DataFile::Statement> &st) const
+{
+ if(!blocks.empty() && cur_blocks_end!=blocks.begin())
+ {
+ BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
+ BlockIter prev;
+ if(train.get_controller().get_reverse())
+ {
+ cur_blocks.reverse();
+ prev = cur_blocks.front().next();
+ }
+ else
+ prev = cur_blocks.front().flip();
+
+ st.push_back((DataFile::Statement("hint"), prev->get_id()));
+
+ for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
+ st.push_back((DataFile::Statement("block"), (*i)->get_id()));
+ }
+}
+
+
+BlockAllocator::Loader::Loader(BlockAllocator &ba):
+ DataFile::ObjectLoader<BlockAllocator>(ba),
+ valid(true)
+{
+ add("block", &Loader::block);
+ add("hint", &Loader::hint);
+}
+
+void BlockAllocator::Loader::block(unsigned id)
+{
+ if(!valid)
+ return;
+
+ Block *blk;
+ try
+ {
+ blk = &obj.train.get_layout().get_block(id);
+ }
+ catch(const key_error &)
+ {
+ valid = false;
+ return;
+ }
+
+ int entry = -1;
+ if(prev_block)
+ entry = blk->get_endpoint_by_link(*prev_block);
+ if(entry<0)
+ entry = 0;
+
+ obj.blocks.push_back(BlockIter(blk, entry));
+ blk->reserve(&obj.train);
+
+ if(blk->get_sensor_id())
+ obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_id(), true);
+
+ prev_block = blk;
+}
+
+void BlockAllocator::Loader::hint(unsigned id)
+{
+ try
+ {
+ prev_block = &obj.train.get_layout().get_block(id);
+ }
+ catch(const key_error &)
+ {
+ valid = false;
+ }
+}
+
+} // namespace R2C2