]> git.tdb.fi Git - r2c2.git/blob - libr2c2/zone.cpp
Don't crash if a train has no router
[r2c2.git] / libr2c2 / zone.cpp
1 #include <msp/strings/format.h>
2 #include <msp/strings/regex.h>
3 #include "block.h"
4 #include "layout.h"
5 #include "track.h"
6 #include "zone.h"
7
8 using namespace std;
9 using namespace Msp;
10
11 namespace R2C2 {
12
13 Zone::Zone(Layout &l):
14         TrackChain(l),
15         number(0)
16 {
17         layout.add(*this);
18 }
19
20 Zone::~Zone()
21 {
22         layout.remove(*this);
23 }
24
25 void Zone::set_name(const string &n)
26 {
27         Regex r_name("(.+) ([^ ]+) ([1-9][0-9]*)");
28         RegMatch m = r_name.match(n);
29         if(!m)
30                 throw invalid_argument("Zone::set_name");
31
32         set_name(m[1].str, m[2].str, lexical_cast<unsigned>(m[3].str));
33 }
34
35 void Zone::set_name(const string &g, const string &q, unsigned n)
36 {
37         group = g;
38         qualifier = q;
39         number = n;
40
41         string full_name = group;
42         if(!qualifier.empty())
43         {
44                 full_name += ' ';
45                 full_name += qualifier;
46         }
47         if(number)
48                 full_name += format(" %d", number);
49         TrackChain::set_name(full_name);
50 }
51
52 void Zone::save(list<DataFile::Statement> &st) const
53 {
54         st.push_back((DataFile::Statement("group"), group));
55         if(!qualifier.empty())
56                 st.push_back((DataFile::Statement("qualifier"), qualifier));
57         if(number)
58                 st.push_back((DataFile::Statement("number"), number));
59
60         set<unsigned> block_ids;
61         for(TrackSet::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
62                 block_ids.insert((*i)->get_block().get_id());
63
64         for(set<unsigned>::const_iterator i=block_ids.begin(); i!=block_ids.end(); ++i)
65                 st.push_back((DataFile::Statement("block"), *i));
66 }
67
68
69 Zone::Loader::Loader(Zone &z):
70         DataFile::ObjectLoader<Zone>(z)
71 {
72         add("block",     &Loader::block);
73         add("group",     &Zone::group);
74         add("number",    &Zone::number);
75         add("qualifier", &Zone::qualifier);
76 }
77
78 void Zone::Loader::block(unsigned b)
79 {
80         Block &blk = obj.layout.get_block(b);
81         const set<Track *> &btracks = blk.get_tracks();
82         obj.tracks.insert(btracks.begin(), btracks.end());
83 }
84
85 } // namespace R2C2