]> git.tdb.fi Git - r2c2.git/blob - source/engineer/engineer.cpp
87a4d6d3afa6c4a75f424ce804e4c3b49491e3e4
[r2c2.git] / source / engineer / engineer.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <cmath>
9 #include <limits>
10 #include <signal.h>
11 #include <msp/core/except.h>
12 #include <msp/core/getopt.h>
13 #include <msp/fs/stat.h>
14 #include <msp/gbase/display.h>
15 #include <msp/gbase/window.h>
16 #include <msp/gl/blend.h>
17 #include <msp/gl/framebuffer.h>
18 #include <msp/gl/immediate.h>
19 #include <msp/gl/matrix.h>
20 #include <msp/gl/misc.h>
21 #include <msp/gl/projection.h>
22 #include <msp/gl/tests.h>
23 #include <msp/gl/transform.h>
24 #include <msp/io/print.h>
25 #include <msp/strings/formatter.h>
26 #include <msp/strings/lexicalcast.h>
27 #include <msp/strings/regex.h>
28 #include <msp/time/units.h>
29 #include "libmarklin/except.h"
30 #include "libmarklin/tracktype.h"
31 #include "engineer.h"
32 #include "mainpanel.h"
33 #include "trainpanel.h"
34 #include "trainproperties.h"
35
36 using namespace std;
37 using namespace Marklin;
38 using namespace Msp;
39
40 Engineer::Engineer(int argc, char **argv):
41         layout(catalogue),
42         layout_3d(layout),
43         server(0),
44         placing_train(0),
45         placing_block(0),
46         placing_entry(0),
47         simulate(false)
48 {
49         // Parse options
50         unsigned screen_w = 1280;
51         unsigned screen_h = 960;
52         bool fullscreen = false;
53         string res;
54         bool debug = false;
55         string device = "/dev/ttyS0";
56         bool network = false;
57
58         GetOpt getopt;
59         getopt.add_option('r', "resolution",  res,         GetOpt::REQUIRED_ARG);
60         getopt.add_option('f', "fullscreen",  fullscreen,  GetOpt::NO_ARG);
61         getopt.add_option('g', "debug",       debug,       GetOpt::NO_ARG);
62         getopt.add_option('d', "device",      device,      GetOpt::REQUIRED_ARG);
63         getopt.add_option('s', "simulate",    simulate,    GetOpt::NO_ARG);
64         getopt.add_option('n', "network",     network,     GetOpt::NO_ARG);
65         getopt(argc, argv);
66
67         const vector<string> &args = getopt.get_args();
68         if(args.empty())
69                 throw UsageError("No layout given");
70
71         if(!res.empty())
72         {
73                 if(RegMatch m=Regex("([1-9][0-9]*)x([1-9][0-9]*)").match(res))
74                 {
75                         screen_w = lexical_cast<unsigned>(m[1].str);
76                         screen_h = lexical_cast<unsigned>(m[2].str);
77                 }
78                 else
79                         throw UsageError("Invalid resolution");
80         }
81
82         // Setup GUI
83         window = new Graphics::SimpleGLWindow(screen_w, screen_h, fullscreen);
84         window->set_title("Railroad Engineer");
85         window->signal_close.connect(sigc::bind(sigc::mem_fun(this, &Engineer::exit), 0));
86
87         DataFile::load(ui_res, "marklin.res");
88         root = new GLtk::Root(ui_res, *window);
89         root->signal_button_press.connect(sigc::mem_fun(this, &Engineer::button_press));
90         root->signal_pointer_motion.connect(sigc::mem_fun(this, &Engineer::pointer_motion));
91         root->set_visible(true);
92
93         main_panel = new MainPanel(*this, ui_res);
94         root->add(*main_panel);
95         main_panel->set_position(0, window->get_height()-main_panel->get_geometry().h);
96         main_panel->set_visible(true);
97
98         // Setup railroad control
99         DataFile::load(catalogue, "tracks.dat");
100         DataFile::load(catalogue, "locos.dat");
101         DataFile::load(layout, args.front());
102
103         if(device!="none")
104                 control.open(device);
105
106         control.set_debug(debug);
107
108         trfc_mgr = new TrafficManager(control, layout);
109         layout_3d.set_traffic_manager(*trfc_mgr);
110         trfc_mgr->signal_train_added.connect(sigc::mem_fun(this, &Engineer::train_added));
111         trfc_mgr->signal_block_reserved.connect(sigc::mem_fun(this, &Engineer::block_reserved));
112         if(FS::exists("engineer.state"))
113                 DataFile::load(*trfc_mgr, "engineer.state");
114
115         if(network)
116         {
117                 server = new Server(*trfc_mgr);
118                 server->use_event_dispatcher(event_disp);
119         }
120
121         const map<unsigned, Sensor *> &sensors = control.get_sensors();
122         for(map<unsigned, Sensor *>::const_iterator i=sensors.begin(); i!=sensors.end(); ++i)
123                 i->second->signal_state_changed.connect(sigc::bind(sigc::mem_fun(this, &Engineer::sensor_event), i->second));
124
125         // Setup 3D view
126         DataFile::load(arrow_mesh, "arrow.mesh");
127
128         overlay = new Overlay3D(*window, camera, ui_res.get_default_font());
129
130         pipeline = new GL::Pipeline(window->get_width(), window->get_height(), false);
131         pipeline->set_camera(&camera);
132         pipeline->add_renderable(layout_3d.get_scene());
133
134         light.set_position(0, -0.259, 0.966, 0);
135         lighting.attach(0, light);
136
137         GL::PipelinePass &pass = pipeline->add_pass(0);
138         pass.depth_test = &GL::DepthTest::lequal();
139         pass.lighting = &lighting;
140
141         view_all();
142
143         // Catch various signals so we can stop the trains in case we get terminated
144         catch_signal(SIGINT);
145         catch_signal(SIGTERM);
146         catch_signal(SIGSEGV);
147         catch_signal(SIGILL);
148         catch_signal(SIGFPE);
149         catch_signal(SIGABRT);
150 }
151
152 Engineer::~Engineer()
153 {
154         const list<Train *> &trains = trfc_mgr->get_trains();
155         for(list<Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
156                 (*i)->set_speed(0);
157
158         while(control.get_queue_length())
159                 control.tick();
160
161         if(!simulate)
162                 trfc_mgr->save("engineer.state");
163
164         delete pipeline;
165         delete overlay;
166         delete root;
167         delete window;
168
169         delete trfc_mgr;
170         delete server;
171 }
172
173 void Engineer::place_train(Train &train)
174 {
175         placing_train = &train;
176         placing_block = 0;
177         main_panel->set_status_text("Select location");
178 }
179
180 int Engineer::main()
181 {
182         window->show();
183
184         return Application::main();
185 }
186
187 void Engineer::tick()
188 {
189         window->get_display().tick();
190
191         control.tick();
192         trfc_mgr->tick();
193         event_disp.tick(Time::zero);
194
195         for(list<Train *>::iterator i=new_trains.begin(); i!=new_trains.end(); ++i)
196                 overlay->set_label(layout_3d.get_train(**i), (*i)->get_name());
197         new_trains.clear();
198
199         GL::clear(GL::COLOR_BUFFER_BIT|GL::DEPTH_BUFFER_BIT);
200
201         pipeline->render_all();
202         {
203                 GL::Bind blend(GL::Blend::alpha());
204                 overlay->render(0);
205         }
206
207         if(placing_train && placing_block)
208         {
209                 GL::PushMatrix push_mat;
210
211                 const Marklin::Block::Endpoint &bep = placing_block->get_endpoints()[placing_entry];
212                 float rot = bep.track->get_endpoint_direction(bep.track_ep);
213                 Point pos = bep.track->get_endpoint_position(bep.track_ep);
214
215                 GL::translate(pos.x, pos.y, pos.z+0.03);
216                 GL::rotate(rot*180/M_PI+180, 0, 0, 1);
217
218                 arrow_mesh.draw();
219         }
220
221         const GLtk::Geometry &rgeom = root->get_geometry();
222         GL::matrix_mode(GL::PROJECTION);
223         GL::load_identity();
224         GL::ortho_bottomleft(rgeom.w, rgeom.h);
225         GL::matrix_mode(GL::MODELVIEW);
226         GL::load_identity();
227
228         {
229                 GL::Bind blend(GL::Blend::alpha());
230                 root->render();
231                 GL::Texture::unbind();
232         }
233
234         window->swap_buffers();
235 }
236
237 void Engineer::button_press(int x, int y, unsigned btn, unsigned)
238 {
239         if(placing_train)
240         {
241                 if(btn==1 && placing_block && !placing_block->get_train())
242                 {
243                         reset_block_color(*placing_block);
244
245                         placing_train->place(*placing_block, placing_entry);
246                         placing_train = 0;
247                         main_panel->set_status_text(string());
248                 }
249                 else if(btn==3)
250                 {
251                         const vector<Block::Endpoint> &endpoints = placing_block->get_endpoints();
252                         placing_entry = (placing_entry+1)%endpoints.size();
253                 }
254         }
255         else
256         {
257                 Track3D *track = pick_track(x, window->get_height()-y-1);
258                 if(track)
259                 {
260                         if(unsigned tid=track->get_track().get_turnout_id())
261                         {
262                                 Turnout &turnout = control.get_turnout(tid);
263                                 try
264                                 {
265                                         turnout.set_path((turnout.get_path()+1)%track->get_track().get_type().get_n_paths());
266                                         main_panel->set_status_text(format("Turnout %d switched", turnout.get_address()));
267                                 }
268                                 catch(const TurnoutBusy &e)
269                                 {
270                                         main_panel->set_status_text(e.what());
271                                 }
272                         }
273                         else if(simulate)
274                         {
275                                 if(unsigned sid=track->get_track().get_sensor_id())
276                                 {
277                                         Sensor &sensor = control.get_sensor(sid);
278                                         control.signal_sensor_event.emit(sid, !sensor.get_state());
279                                 }
280                         }
281                 }
282         }
283 }
284
285 void Engineer::pointer_motion(int x, int y)
286 {
287         if(placing_train)
288         {
289                 Track3D *track = pick_track(x, window->get_height()-y-1);
290                 if(track)
291                 {
292                         Block &block = trfc_mgr->get_block_by_track(track->get_track());
293                         if(&block!=placing_block)
294                         {
295                                 if(placing_block)
296                                         reset_block_color(*placing_block);
297                                 placing_block = &block;
298                                 placing_entry = 0;
299                                 set_block_color(*placing_block, GL::Color(0.5, 1, 0.7));
300                         }
301                 }
302         }
303 }
304
305 void Engineer::view_all()
306 {
307         const list<Track3D *> &tracks = layout_3d.get_tracks();
308
309         float view_aspect = float(window->get_width()-200)/window->get_height();
310         float view_height = tan(camera.get_field_of_view()/2)*2;
311         float best_score = 0;
312         GL::Vector3 pos;
313         GL::Vector3 up;
314         for(float angle=0; angle<M_PI; angle+=0.01)
315         {
316                 float min_x = 0;
317                 float max_x = 0;
318                 float min_y = 0;
319                 float max_y = 0;
320                 for(list<Track3D *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
321                 {
322                         Point minp, maxp;
323                         (*i)->get_bounds(angle, minp, maxp);
324                         min_x = min(min_x, minp.x);
325                         max_x = max(max_x, maxp.x);
326                         min_y = min(min_y, minp.y);
327                         max_y = max(max_y, maxp.y);
328                 }
329
330                 float width = max_x-min_x;
331                 float height = max_y-min_y;
332                 float aspect = width/height;
333                 float score = min(aspect/view_aspect, view_aspect/aspect);
334
335                 if(score>best_score)
336                 {
337                         best_score = score;
338
339                         float size = max(width/view_aspect, height);
340                         float c = cos(angle);
341                         float s = sin(angle);
342                         float x = (min_x+max_x)/2-size*105/window->get_height();
343                         float y = (min_y+max_y)/2;
344                         float z = max(size*1.05/view_height, 0.15);
345
346                         pos = GL::Vector3(c*x-s*y, s*x+c*y, z);
347                         up = GL::Vector3(-s, c, 0);
348                 }
349         }
350
351         camera.set_position(pos);
352         camera.set_up_direction(up);
353         camera.set_look_direction(GL::Vector3(0, 0, -1));
354 }
355
356 void Engineer::set_block_color(const Block &block, const GL::Color &color)
357 {
358         (void)block;
359         (void)color;
360 }
361
362 void Engineer::reset_block_color(const Block &block)
363 {
364         if(unsigned sid=block.get_sensor_id())
365         {
366                 Sensor &sensor = control.get_sensor(sid);
367                 if(sensor.get_state())
368                 {
369                         set_block_color(block, GL::Color(1, 0.5, 0.3));
370                         return;
371                 }
372         }
373
374         if(block.get_train())
375                 set_block_color(block, GL::Color(1, 1, 0.3));
376         else
377                 set_block_color(block, GL::Color(1, 1, 1));
378 }
379
380 void Engineer::sensor_event(bool, Sensor *sensor)
381 {
382         const list<Block *> &blocks = trfc_mgr->get_blocks();
383         for(list<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
384                 if((*i)->get_sensor_id()==sensor->get_address())
385                         reset_block_color(**i);
386 }
387
388 void Engineer::block_reserved(const Block &block, const Train *)
389 {
390         reset_block_color(block);
391 }
392
393 Track3D *Engineer::pick_track(int x, int y)
394 {
395         float view_height = tan(camera.get_field_of_view()/2)*2;
396         float xx = ((float(x)-window->get_width()/2)/window->get_height())*view_height;
397         float yy = (float(y)/window->get_height()-0.5)*view_height;
398         float size = 4.0/window->get_height()*view_height;
399
400         camera.apply();
401
402         return layout_3d.pick_track(xx, yy, size);
403 }
404
405 void Engineer::train_added(Train &train)
406 {
407         TrainPanel *tpanel = new TrainPanel(*this, ui_res, train);
408         root->add(*tpanel);
409         int y = main_panel->get_geometry().y;
410         for(list<TrainPanel *>::iterator i=train_panels.begin(); i!=train_panels.end(); ++i)
411                 y -= (*i)->get_geometry().h;
412         tpanel->set_position(0, y-tpanel->get_geometry().h);
413         train_panels.push_back(tpanel);
414         tpanel->set_visible(true);
415
416         new_trains.push_back(&train);
417 }
418
419 void Engineer::sighandler(int sig)
420 {
421         if(sig==SIGSEGV || sig==SIGILL || sig==SIGFPE || sig==SIGABRT)
422         {
423                 signal(sig, SIG_DFL);
424                 IO::print(IO::cerr, "Fatal signal received, terminating\n");
425                 const map<unsigned, Locomotive *> &locos = control.get_locomotives();
426                 for(map<unsigned, Locomotive *>::const_iterator i=locos.begin(); i!=locos.end(); ++i)
427                         i->second->set_speed(0);
428                 control.flush();
429                 raise(sig);
430         }
431         else if(sig==SIGTERM || sig==SIGINT)
432                 exit(0);
433 }
434
435 Application::RegApp<Engineer> Engineer::reg;