]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/layout.cpp
Add button_release handler to Tool
[r2c2.git] / source / libr2c2 / layout.cpp
1 #include <algorithm>
2 #include <msp/core/maputils.h>
3 #include <msp/core/refptr.h>
4 #include <msp/datafile/parser.h>
5 #include <msp/datafile/writer.h>
6 #include <msp/io/print.h>
7 #include <msp/time/utils.h>
8 #include "beamgate.h"
9 #include "block.h"
10 #include "catalogue.h"
11 #include "driver.h"
12 #include "layout.h"
13 #include "route.h"
14 #include "signal.h"
15 #include "signaltype.h"
16 #include "track.h"
17 #include "trackcircuit.h"
18 #include "tracktype.h"
19 #include "train.h"
20 #include "vehicle.h"
21 #include "vehicletype.h"
22 #include "zone.h"
23
24 using namespace std;
25 using namespace Msp;
26
27 namespace {
28
29 bool zone_order(const R2C2::Zone *z1, const R2C2::Zone *z2)
30 {
31         return z1->get_number()<z2->get_number();
32 }
33
34 }
35
36
37 namespace R2C2 {
38
39 Layout::Layout(Catalogue &c, Driver *d):
40         catalogue(c),
41         driver(d),
42         next_turnout_addr(0x800)
43 {
44         clock.set_rate(60);
45 }
46
47 Layout::~Layout()
48 {
49         delete driver;
50         driver = 0;
51
52         while(!trains.empty())
53                 delete trains.begin()->second;
54         track_chains.del<Route>();
55         track_chains.del<Zone>();
56         objects.del<Signal>();
57         objects.del<Track>();
58         track_chains.del<Block>();
59 }
60
61 Driver &Layout::get_driver() const
62 {
63         if(!driver)
64                 throw logic_error("!driver");
65         return *driver;
66 }
67
68 void Layout::add(Object &o)
69 {
70         if(objects.insert(o))
71                 signal_object_added.emit(o);
72 }
73
74 void Layout::add(Track &t)
75 {
76         if(objects.insert(t))
77         {
78                 // Blocks must be recreated first
79                 create_blocks();
80                 signal_object_added.emit(t);
81         }
82 }
83
84 void Layout::add(TrackChain &g)
85 {
86         if(track_chains.insert(g))
87                 signal_track_chain_added.emit(g);
88 }
89
90 void Layout::add(Block &b)
91 {
92         if(track_chains.insert(b))
93         {
94                 b.signal_reserved.connect(sigc::bind<0>(signal_block_reserved, sigc::ref(b)));
95                 signal_track_chain_added.emit(b);
96         }
97 }
98
99 void Layout::add(Sensor &s)
100 {
101         if(sensors.insert(s))
102         {
103                 s.signal_state_changed.connect(sigc::bind<0>(sigc::mem_fun(this, &Layout::sensor_state_changed), sigc::ref(s)));
104                 s.signal_state_changed.connect(sigc::bind<0>(signal_sensor_state_changed, sigc::ref(s)));
105         }
106 }
107
108 void Layout::add(BeamGate &g)
109 {
110         add(static_cast<Object &>(g));
111         add(static_cast<Sensor &>(g));
112 }
113
114 template<>
115 const set<Object *> &Layout::get_all<Object>() const
116 {
117         return objects.get();
118 }
119
120 template<>
121 const set<Track *> &Layout::get_all<Track>() const
122 {
123         return objects.get<Track>();
124 }
125
126 template<>
127 const set<Signal *> &Layout::get_all<Signal>() const
128 {
129         return objects.get<Signal>();
130 }
131
132 template<>
133 const set<Vehicle *> &Layout::get_all<Vehicle>() const
134 {
135         return objects.get<Vehicle>();
136 }
137
138 template<>
139 const set<TrackChain *> &Layout::get_all<TrackChain>() const
140 {
141         return track_chains.get();
142 }
143
144 template<>
145 const set<Block *> &Layout::get_all<Block>() const
146 {
147         return track_chains.get<Block>();
148 }
149
150 template<>
151 const set<Route *> &Layout::get_all<Route>() const
152 {
153         return track_chains.get<Route>();
154 }
155
156 template<>
157 const set<Zone *> &Layout::get_all<Zone>() const
158 {
159         return track_chains.get<Zone>();
160 }
161
162 template<>
163 const set<Sensor *> &Layout::get_all<Sensor>() const
164 {
165         return sensors.get<Sensor>();
166 }
167
168 template<>
169 const set<TrackCircuit *> &Layout::get_all<TrackCircuit>() const
170 {
171         return sensors.get<TrackCircuit>();
172 }
173
174 template<>
175 const set<BeamGate *> &Layout::get_all<BeamGate>() const
176 {
177         return sensors.get<BeamGate>();
178 }
179
180 template<typename T>
181 T *Layout::pick(const Ray &ray)
182 {
183         const set<Object *> &objs = objects.get();
184         for(set<Object *>::const_iterator i=objs.begin(); i!=objs.end(); ++i)
185                 if(T *t = dynamic_cast<T *>(*i))
186                         if(t->collide_ray(ray))
187                                 return t;
188
189         return 0;
190 }
191
192 template Object *Layout::pick<Object>(const Ray &);
193 template Track *Layout::pick<Track>(const Ray &);
194 template Signal *Layout::pick<Signal>(const Ray &);
195 template Vehicle *Layout::pick<Vehicle>(const Ray &);
196
197 void Layout::remove(Object &o)
198 {
199         if(objects.erase(o))
200                 signal_object_removed.emit(o);
201 }
202
203 void Layout::remove(Track &t)
204 {
205         if(objects.erase(t))
206         {
207                 // Blocks must be recreated first
208                 create_blocks(t);
209                 signal_object_removed.emit(t);
210         }
211 }
212
213 void Layout::remove(TrackChain &g)
214 {
215         if(track_chains.erase(g))
216                 signal_track_chain_removed.emit(g);
217 }
218
219 void Layout::remove(Sensor &s)
220 {
221         sensors.erase(s);
222 }
223
224 void Layout::remove(BeamGate &g)
225 {
226         remove(static_cast<Object &>(g));
227         remove(static_cast<Sensor &>(g));
228 }
229
230 unsigned Layout::allocate_turnout_address()
231 {
232         set<unsigned> used_addrs;
233         const set<Track *> &tracks = objects.get<Track>();
234         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
235                 if((*i)->get_turnout_address())
236                         used_addrs.insert((*i)->get_turnout_address());
237
238         unsigned result = next_turnout_addr;
239         while(used_addrs.count(result))
240                 ++result;
241         next_turnout_addr = result+1;
242
243         return result;
244 }
245
246 Block &Layout::get_block(unsigned id) const
247 {
248         const set<Block *> &blocks = track_chains.get<Block>();
249         for(set<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
250                 if((*i)->get_id()==id)
251                         return **i;
252
253         throw key_error(id);
254 }
255
256 void Layout::create_blocks()
257 {
258         set<Track *> loose_tracks = objects.get<Track>();
259         const set<Block *> *blocks = &track_chains.get<Block>();
260         for(set<Block *>::const_iterator i=blocks->begin(); i!=blocks->end(); ++i)
261         {
262                 const set<Track *> &btracks = (*i)->get_tracks();
263                 for(set<Track *>::const_iterator j=btracks.begin(); j!=btracks.end(); ++j)
264                         loose_tracks.erase(*j);
265         }
266
267         list<Block *> created_blocks;
268         while(!loose_tracks.empty())
269         {
270                 Block *block = new Block(*this, **loose_tracks.begin());
271                 created_blocks.push_back(block);
272
273                 const set<Track *> &btracks = block->get_tracks();
274                 for(set<Track *>::const_iterator i=btracks.begin(); i!=btracks.end(); ++i)
275                         loose_tracks.erase(*i);
276         }
277
278         // The previously obtained set has been invalidated by creating new blocks
279         blocks = &track_chains.get<Block>();
280         for(list<Block *>::iterator i=created_blocks.begin(); i!=created_blocks.end(); ++i)
281                 for(set<Block *>::const_iterator j=blocks->begin(); j!=blocks->end(); ++j)
282                         if(*j!=*i)
283                                 (*i)->check_link(**j);
284 }
285
286 void Layout::create_blocks(Track &track)
287 {
288         /* Must collect the blocks in a set first while all tracks are still
289         guaranteed to have blocks and to avoid duplicate deletes */
290         set<Block *> del_blocks;
291
292         del_blocks.insert(&track.get_block());
293
294         const vector<Track *> &links = track.get_links();
295         for(vector<Track *>::const_iterator i=links.begin(); i!=links.end(); ++i)
296                 if(*i)
297                         del_blocks.insert(&(*i)->get_block());
298
299         for(set<Block *>::iterator i=del_blocks.begin(); i!=del_blocks.end(); ++i)
300                 delete *i;
301
302         create_blocks();
303 }
304
305 Route &Layout::get_route(const string &name) const
306 {
307         const set<Route *> &routes = track_chains.get<Route>();
308         for(set<Route *>::const_iterator i=routes.begin(); i!=routes.end(); ++i)
309                 if((*i)->get_name()==name)
310                         return **i;
311         throw key_error(name);
312 }
313
314 void Layout::update_routes()
315 {
316         const set<Route *> &routes = track_chains.get<Route>();
317         for(set<Route *>::iterator i=routes.begin(); i!=routes.end(); ++i)
318                 (*i)->update_turnouts();
319 }
320
321 Layout::ZoneArray Layout::get_zones(const string &group) const
322 {
323         ZoneArray result;
324         const set<Zone *> &zones = track_chains.get<Zone>();
325         for(set<Zone *>::const_iterator i=zones.begin(); i!=zones.end(); ++i)
326                 if((*i)->get_group()==group)
327                         result.push_back(*i);
328
329         sort(result.begin(), result.end(), zone_order);
330
331         return result;
332 }
333
334 Zone &Layout::get_zone(const string &group, unsigned num) const
335 {
336         const set<Zone *> &zones = track_chains.get<Zone>();
337         for(set<Zone *>::const_iterator i=zones.begin(); i!=zones.end(); ++i)
338                 if((*i)->get_group()==group && (*i)->get_number()==num)
339                         return **i;
340
341         throw key_error(format("%s %d", group, num));
342 }
343
344 void Layout::add_train(Train &t)
345 {
346         insert_unique(trains, t.get_address(), &t);
347         signal_train_added.emit(t);
348 }
349
350 Train &Layout::get_train(unsigned addr) const
351 {
352         return *get_item(trains, addr);
353 }
354
355 void Layout::remove_train(Train &t)
356 {
357         if(trains.erase(t.get_address()))
358                 signal_train_removed.emit(t);
359 }
360
361 void Layout::tick()
362 {
363         if(driver)
364                 driver->tick();
365
366         Time::TimeStamp t = Time::now();
367         Time::TimeDelta dt;
368         if(last_tick)
369                 dt = t-last_tick;
370         last_tick = t;
371
372         clock.tick(dt);
373
374         for(set<Sensor *>::iterator i=sensors.get().begin(); i!=sensors.get().end(); ++i)
375                 (*i)->tick(dt);
376         const set<Signal *> &signals = objects.get<Signal>();
377         for(set<Signal *>::iterator i=signals.begin(); i!=signals.end(); ++i)
378                 (*i)->tick(dt);
379         for(map<unsigned, Train *>::iterator i=trains.begin(); i!=trains.end(); ++i)
380                 i->second->tick(dt);
381 }
382
383 void Layout::emergency(const string &msg)
384 {
385         if(driver)
386                 driver->halt(true);
387         IO::print("Emergency: %s\n", msg);
388         signal_emergency.emit(msg);
389 }
390
391 void Layout::save(const string &fn) const
392 {
393         IO::BufferedFile out(fn, IO::M_WRITE);
394         DataFile::Writer writer(out);
395
396         if(!base.empty())
397                 writer.write((DataFile::Statement("base"), base));
398
399         const set<Track *> &tracks = objects.get<Track>();
400         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
401         {
402                 DataFile::Statement st("track");
403                 st.append((*i)->get_type().get_article_number());
404                 (*i)->save(st.sub);
405                 writer.write(st);
406         }
407
408         const set<Signal *> &signals = objects.get<Signal>();
409         for(set<Signal *>::const_iterator i=signals.begin(); i!=signals.end(); ++i)
410         {
411                 DataFile::Statement st("signal");
412                 st.append((*i)->get_type().get_article_number());
413                 (*i)->save(st.sub);
414                 writer.write(st);
415         }
416
417         const set<BeamGate *> &gates = objects.get<BeamGate>();
418         for(set<BeamGate *>::const_iterator i=gates.begin(); i!=gates.end(); ++i)
419         {
420                 DataFile::Statement st("beamgate");
421                 (*i)->save(st.sub);
422                 writer.write(st);
423         }
424
425         const set<Route *> &routes = track_chains.get<Route>();
426         for(set<Route *>::const_iterator i=routes.begin(); i!=routes.end(); ++i)
427         {
428                 if((*i)->is_temporary())
429                         continue;
430
431                 DataFile::Statement st("route");
432                 (*i)->save(st.sub);
433                 writer.write(st);
434         }
435
436         const set<Zone *> &zones = track_chains.get<Zone>();
437         for(set<Zone *>::const_iterator i=zones.begin(); i!=zones.end(); ++i)
438         {
439                 DataFile::Statement st("zone");
440                 (*i)->save(st.sub);
441                 writer.write(st);
442         }
443 }
444
445 void Layout::save_dynamic(const string &fn) const
446 {
447         IO::BufferedFile out(fn, IO::M_WRITE);
448         DataFile::Writer writer(out);
449
450         const set<Track *> &tracks = objects.get<Track>();
451         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
452                 if(unsigned taddr = (*i)->get_turnout_address())
453                         writer.write((DataFile::Statement("turnout"), taddr, (*i)->get_active_path()));
454
455         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
456         {
457                 DataFile::Statement st("train");
458                 st.append(i->second->get_locomotive_type().get_article_number());
459                 st.append(i->second->get_address());
460                 st.append(i->second->get_protocol());
461                 i->second->save(st.sub);
462                 writer.write(st);
463         }
464 }
465
466 void Layout::sensor_state_changed(Sensor &sensor, Sensor::State state)
467 {
468         if(state==Sensor::ACTIVE)
469         {
470                 Block *block = sensor.get_block();
471                 if(block && !block->get_train())
472                         emergency(format("Unreserved sensor %d triggered", sensor.get_address()));
473         }
474 }
475
476
477 template<typename B>
478 Layout::Storage<B>::~Storage()
479 {
480         while(!base.empty())
481                 delete *base.begin();
482 }
483
484 template<typename B>
485 bool Layout::Storage<B>::insert(B &b)
486 {
487         bool result = base.insert(&b).second;
488         if(result)
489                 caches.clear();
490         return result;
491 }
492
493 template<typename B>
494 bool Layout::Storage<B>::erase(B &b)
495 {
496         bool result = base.erase(&b);
497         if(result)
498                 caches.clear();
499         return result;
500 }
501
502 template<typename B>
503 template<typename T>
504 const set<T *> &Layout::Storage<B>::get() const
505 {
506         for(list<Variant>::const_iterator i=caches.begin(); i!=caches.end(); ++i)
507                 if(i->check_type<set<T *> >())
508                         return i->value<set<T *> >();
509
510         caches.push_back(set<T *>());
511         set<T *> &result = caches.back().value<set<T *> >();
512         for(typename set<B *>::const_iterator i=base.begin(); i!=base.end(); ++i)
513                 if(T *t = dynamic_cast<T *>(*i))
514                         result.insert(t);
515
516         return result;
517 }
518
519 template<typename B>
520 template<typename T>
521 void Layout::Storage<B>::del()
522 {
523         set<T *> ts = get<T>();
524         for(typename set<T *>::iterator i=ts.begin(); i!=ts.end(); ++i)
525                 if(base.count(*i))
526                         delete *i;
527 }
528
529
530 Layout::Loader::Loader(Layout &l):
531         DataFile::ObjectLoader<Layout>(l)
532 {
533         add("base",  &Layout::base);
534         add("beamgate", &Loader::beamgate);
535         add("route", &Loader::route);
536         add("signal", &Loader::signal);
537         add("track", &Loader::track);
538         add("train", &Loader::train);
539         add("turnout", &Loader::turnout);
540         add("zone",  &Loader::zone);
541 }
542
543 void Layout::Loader::beamgate()
544 {
545         BeamGate *gate = new BeamGate(obj);
546         load_sub(*gate);
547 }
548
549 void Layout::Loader::route()
550 {
551         Route *rte = new Route(obj);
552         load_sub(*rte);
553 }
554
555 void Layout::Loader::signal(ArticleNumber art_nr)
556 {
557         Signal *sig = new Signal(obj, obj.catalogue.get<SignalType>(art_nr));
558         load_sub(*sig);
559 }
560
561 void Layout::Loader::track(ArticleNumber art_nr)
562 {
563         Track *trk = new Track(obj, obj.catalogue.get<TrackType>(art_nr));
564         load_sub(*trk);
565         const set<Track *> &tracks = obj.objects.get<Track>();
566         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
567                 if(*i!=trk)
568                         trk->link_to(**i);
569 }
570
571 void Layout::Loader::train(ArticleNumber art_nr, unsigned addr, const std::string &proto)
572 {
573         Train *trn = new Train(obj, obj.catalogue.get<VehicleType>(art_nr), addr, proto);
574         load_sub(*trn);
575 }
576
577 void Layout::Loader::turnout(unsigned addr, unsigned path)
578 {
579         if(obj.driver)
580                 obj.driver->set_turnout(addr, path);
581 }
582
583 void Layout::Loader::zone()
584 {
585         Zone *zne = new Zone(obj);
586         load_sub(*zne);
587 }
588
589 } // namespace R2C2