]> git.tdb.fi Git - r2c2.git/blob - engineer/engineer.cpp
Don't crash if a train has no router
[r2c2.git] / engineer / engineer.cpp
1 #include <algorithm>
2 #include <cmath>
3 #include <cstdlib>
4 #include <limits>
5 #include <signal.h>
6 #include <msp/fs/stat.h>
7 #include <msp/fs/utils.h>
8 #include <msp/graphics/display.h>
9 #include <msp/graphics/window.h>
10 #include <msp/gl/blend.h>
11 #include <msp/gl/framebuffer.h>
12 #include <msp/gl/matrix.h>
13 #include <msp/gl/misc.h>
14 #include <msp/gl/tests.h>
15 #include <msp/gltk/floatingarrangement.h>
16 #include <msp/io/print.h>
17 #include <msp/strings/format.h>
18 #include <msp/time/units.h>
19 #include <msp/time/utils.h>
20 #include "libr2c2/driver.h"
21 #include "libr2c2/trackcircuit.h"
22 #include "libr2c2/tracktype.h"
23 #include "3d/allocation.h"
24 #include "3d/path.h"
25 #include "3d/track.h"
26 #include "3d/trackcircuit.h"
27 #include "3d/vehicle.h"
28 #include "engineer.h"
29 #include "mainwindow.h"
30 #include "newtraindialog.h"
31 #include "traindialog.h"
32 #include "trainview.h"
33
34 using namespace std;
35 using namespace R2C2;
36 using namespace Msp;
37
38 Engineer::Engineer(int argc, char **argv):
39         options(argc, argv),
40         window(options.screen_w, options.screen_h, options.fullscreen),
41         keyboard(window),
42         mouse(window),
43         ui_res("r2c2.res"),
44         import_active(false),
45         layout(catalogue, (options.driver.empty() ? 0 : Driver::create(options.driver))),
46         layout_3d(layout),
47         server(0),
48         main_view(layout_3d, window.get_width(), window.get_height())
49 {
50         // Setup GUI
51         window.set_title("Railroad Engineer");
52         window.signal_close.connect(sigc::bind(sigc::mem_fun(this, &Engineer::exit), 0));
53
54         root = new GLtk::Root(ui_res, &window, &keyboard, &mouse);
55         GLtk::Layout *root_layout = new GLtk::Layout;
56         root->set_layout(root_layout);
57         root_layout->set_margin(GLtk::Sides());
58         root_arrangement = new GLtk::FloatingArrangement(*root_layout);
59         mouse.signal_button_press.connect(sigc::bind_return(sigc::mem_fun(this, &Engineer::button_press), false));
60         mouse.signal_axis_motion.connect(sigc::bind_return(sigc::mem_fun(this, &Engineer::axis_motion), false));
61         root->set_visible(true);
62
63         main_wnd = new MainWindow(*this);
64         root->add(*main_wnd);
65         main_wnd->autosize();
66         main_wnd->set_position(0, window.get_height()-main_wnd->get_geometry().h);
67
68         overlay = new Overlay3D(ui_res.get_default_font());
69
70         // Setup railroad control
71         DataFile::load(catalogue, "tracks.dat");
72         DataFile::load(catalogue, "locos.dat");
73         DataFile::load(catalogue, "wagons.dat");
74         DataFile::load(catalogue, "terrain.dat");
75         DataFile::load(layout, options.layout_fn);
76
77         if(layout.has_driver())
78                 layout.get_driver().signal_locomotive_detected.connect(sigc::mem_fun(this, &Engineer::locomotive_detected));
79         layout.signal_train_added.connect(sigc::mem_fun(this, &Engineer::train_added));
80         layout.signal_emergency.connect(sigc::mem_fun(this, &Engineer::set_status));
81         const set<Block *> &blocks = layout.get_all<Block>();
82         for(set<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
83                 if(TrackCircuit *tc = (*i)->get_sensor())
84                         new TrackCircuit3D(layout_3d, *tc);
85
86         const set<Track *> &tracks = layout.get_all<Track>();
87         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
88                 if((*i)->get_type().is_turnout())
89                         new Path3D(layout_3d.get_3d(**i));
90
91         if(FS::exists(options.state_fn))
92                 DataFile::load(layout, options.state_fn);
93
94         if(options.network)
95         {
96                 server = new Server(layout);
97                 server->use_event_dispatcher(event_disp);
98         }
99
100         // Setup 3D view
101         GL::Pipeline &pipeline = main_view.get_pipeline();
102
103         GL::Pipeline::Pass *pass = &pipeline.add_pass("unlit");
104         pass->set_depth_test(&GL::DepthTest::lequal());
105         pipeline.add_renderable_for_pass(layout_3d.get_path_scene(), "unlit");
106
107         pass = &pipeline.add_pass("overlay");
108         pass->set_blend(&GL::Blend::alpha());
109         pipeline.add_renderable_for_pass(*overlay, "overlay");
110
111         view_all();
112
113         // Catch various signals so we can stop the trains in case we get terminated
114         catch_signal(SIGINT);
115         catch_signal(SIGTERM);
116         catch_signal(SIGSEGV);
117         catch_signal(SIGILL);
118         catch_signal(SIGFPE);
119         catch_signal(SIGABRT);
120 }
121
122 Engineer::~Engineer()
123 {
124         const map<unsigned, Train *> &trains = layout.get_trains();
125         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
126                 layout.get_driver().set_loco_speed(i->first, 0);
127         layout.get_driver().flush();
128
129         if(!options.simulate)
130         {
131                 layout.save_dynamic(options.state_fn+".tmp");
132                 FS::rename(options.state_fn+".tmp", options.state_fn);
133         }
134
135         delete overlay;
136         delete root_arrangement;
137         delete root;
138
139         delete server;
140 }
141
142 void Engineer::set_status(const string &text)
143 {
144         main_wnd->set_status_text(text);
145         status_timeout = Time::now()+10*Time::sec;
146 }
147
148 void Engineer::add_train_view(TrainView &tv)
149 {
150         train_views.push_back(&tv);
151 }
152
153 void Engineer::remove_train_view(TrainView &tv)
154 {
155         train_views.erase(remove(train_views.begin(), train_views.end(), &tv), train_views.end());
156 }
157
158 int Engineer::main()
159 {
160         window.show();
161
162         return Application::main();
163 }
164
165 void Engineer::tick()
166 {
167         window.get_display().tick();
168
169         for(list<Train *>::iterator i=new_trains.begin(); i!=new_trains.end(); ++i)
170                 process_new_train(**i);
171         new_trains.clear();
172
173         layout.tick();
174         event_disp.tick(Time::zero);
175
176         for(list<TrainView *>::iterator i=train_views.begin(); i!=train_views.end(); ++i)
177                 (*i)->prepare();
178
179         if(status_timeout && Time::now()>status_timeout)
180         {
181                 main_wnd->set_status_text(string());
182                 status_timeout = Time::TimeStamp();
183         }
184
185         GL::Framebuffer::system().clear(GL::COLOR_BUFFER_BIT|GL::DEPTH_BUFFER_BIT);
186
187         main_view.render();
188
189         root->render();
190
191         window.swap_buffers();
192 }
193
194 void Engineer::button_press(unsigned btn)
195 {
196         if(btn==1)
197         {
198                 Object *obj = pick_object(pointer);
199                 if(Track *track = dynamic_cast<Track *>(obj))
200                 {
201                         if(track->get_turnout_address())
202                         {
203                                 Block &block = track->get_block();
204                                 if(block.get_train() && block.get_train()->is_block_critical(block))
205                                         set_status("Turnout is busy");
206                                 else
207                                 {
208                                         unsigned paths = track->get_type().get_paths();
209                                         unsigned i = track->get_active_path()+1;
210                                         while(!(paths&(1<<i)))
211                                         {
212                                                 if(!(paths>>i))
213                                                         i = 0;
214                                                 else
215                                                         ++i;
216                                         }
217                                         track->set_active_path(i);
218                                         set_status(format("Turnout %d", track->get_turnout_address()));
219                                 }
220                         }
221                         if(unsigned saddr = track->get_sensor_address())
222                         {
223                                 if(options.simulate)
224                                         layout.get_driver().set_sensor(saddr, !layout.get_driver().get_sensor(saddr));
225                                 set_status(format("Sensor %d", saddr));
226                         }
227                 }
228                 else if(Vehicle *veh = dynamic_cast<Vehicle *>(obj))
229                 {
230                         TrainDialog *dlg = new TrainDialog(*this, *veh->get_train());
231                         root->add(*dlg);
232                         dlg->autosize();
233                 }
234         }
235 }
236
237 void Engineer::axis_motion(unsigned axis, float value, float)
238 {
239         if(axis==0)
240                 pointer.x = value;
241         if(axis==1)
242                 pointer.y = value;
243 }
244
245 void Engineer::view_all()
246 {
247         const Layout3D::ObjectMap &objects = layout_3d.get_all();
248
249         float view_aspect = float(window.get_width())/window.get_height();
250         float view_height = tan(main_view.get_camera().get_field_of_view()/2.0f)*2.0f;
251         float best_score = 0;
252         GL::Vector3 pos;
253         GL::Vector3 up;
254         for(Angle angle; angle<Angle::half_turn(); angle+=Angle::from_radians(0.01))
255         {
256                 Transform trans = Transform::rotation(-angle, Vector(0, 0, 1));
257                 BoundingBox bbox;
258                 for(Layout3D::ObjectMap::const_iterator i=objects.begin(); i!=objects.end(); ++i)
259                         bbox = bbox|trans.transform(i->second->get_object().get_bounding_box());
260
261                 const Vector &minp = bbox.get_minimum_point();
262                 const Vector &maxp = bbox.get_maximum_point();
263
264                 float width = maxp.x-minp.x;
265                 float height = maxp.y-minp.y;
266                 float aspect = width/height;
267                 float score = min(aspect/view_aspect, view_aspect/aspect);
268
269                 if(score>best_score)
270                 {
271                         best_score = score;
272
273                         float size = max(width/view_aspect, height);
274                         float c = cos(angle);
275                         float s = sin(angle);
276                         float x = (minp.x+maxp.x)/2;
277                         float y = (minp.y+maxp.y)/2;
278                         float z = max(size*1.05/view_height, 0.15);
279
280                         pos = GL::Vector3(c*x-s*y, s*x+c*y, z);
281                         up = GL::Vector3(-s, c, 0);
282                 }
283         }
284
285         GL::Camera &camera = main_view.get_camera();
286         camera.set_position(pos);
287         camera.set_up_direction(up);
288         camera.set_look_direction(GL::Vector3(0, 0, -1));
289         camera.set_aspect(float(window.get_width())/window.get_height());
290         camera.set_depth_clip(pos.z*0.5, pos.z*1.5);
291 }
292
293 Object *Engineer::pick_object(const Vector &p)
294 {
295         const GL::Vector3 &start = main_view.get_camera().get_position();
296         GL::Vector4 ray = main_view.get_camera().unproject(GL::Vector4(p.x, p.y, 0, 0));
297
298         // XXX Do this better; make this function a template?
299         if(Vehicle *veh = layout.pick<Vehicle>(Ray(start, Vector(ray))))
300                 return veh;
301         return layout.pick<Track>(Ray(start, Vector(ray)));
302 }
303
304 void Engineer::locomotive_detected(const Driver::DetectedLocomotive &loco)
305 {
306         if(!import_active)
307         {
308                 NewTrainDialog *dlg = new NewTrainDialog(*this);
309                 dlg->prefill(loco);
310                 dlg->signal_response.connect(sigc::mem_fun(this, &Engineer::import_finished));
311                 root->add(*dlg);
312                 import_active = true;
313         }
314 }
315
316 void Engineer::import_finished(int)
317 {
318         import_active = false;
319 }
320
321 void Engineer::process_new_train(Train &train)
322 {
323         Vehicle3D &loco3d = layout_3d.get_3d(train.get_vehicle(0));
324         overlay->set_label(loco3d, train.get_name());
325         train.signal_name_changed.connect(sigc::bind<0>(sigc::mem_fun(overlay, &Overlay3D::set_label), sigc::ref(loco3d)));
326 }
327
328 void Engineer::train_added(Train &train)
329 {
330         new_trains.push_back(&train);
331
332         GL::Color best_color;
333         float best_d_sq = 0;
334         for(unsigned i=0; i<10; ++i)
335         {
336                 GL::Color color;
337                 unsigned h = rand()%3;
338                 color.r = (h==0 ? 0.0 : rand()*1.0/RAND_MAX);
339                 color.g = (h==1 ? 0.0 : rand()*1.0/RAND_MAX);
340                 color.b = (h==2 ? 0.0 : rand()*1.0/RAND_MAX);
341                 color = color*(1/max(max(color.r, color.g), color.b));
342                 float min_d_sq = 3;
343                 for(map<Train *, GL::Color>::const_iterator j=train_colors.begin(); j!=train_colors.end(); ++j)
344                 {
345                         float dr = color.r-j->second.r;
346                         float dg = color.g-j->second.g;
347                         float db = color.b-j->second.b;
348                         float d_sq = dr*dr+dg*dg+db*db;
349                         if(d_sq<min_d_sq)
350                                 min_d_sq = d_sq;
351                 }
352                 if(min_d_sq>best_d_sq)
353                 {
354                         best_color = color;
355                         best_d_sq = min_d_sq;
356                 }
357         }
358         train_colors[&train] = best_color;
359
360         Allocation3D *alloc = new Allocation3D(layout_3d, train);
361         alloc->set_color(best_color);
362 }
363
364 void Engineer::sighandler(int sig)
365 {
366         if(sig==SIGSEGV || sig==SIGILL || sig==SIGFPE || sig==SIGABRT)
367         {
368                 signal(sig, SIG_DFL);
369                 IO::print(IO::cerr, "Fatal signal received, terminating\n");
370                 const map<unsigned, Train *> &trains = layout.get_trains();
371                 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
372                         layout.get_driver().set_loco_speed(i->first, 0);
373                 layout.get_driver().flush();
374                 raise(sig);
375         }
376         else if(sig==SIGTERM || sig==SIGINT)
377                 exit(0);
378 }