]> git.tdb.fi Git - r2c2.git/blob - source/engineer/engineer.cpp
Allow intercepting and denying turnout route and locomotive speed changes
[r2c2.git] / source / engineer / engineer.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2009 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <cmath>
9 #include <limits>
10 #include <GL/gl.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/immediate.h>
17 #include <msp/gl/matrix.h>
18 #include <msp/gl/projection.h>
19 #include <msp/gl/transform.h>
20 #include <msp/strings/formatter.h>
21 #include <msp/strings/lexicalcast.h>
22 #include <msp/strings/regex.h>
23 #include "libmarklin/except.h"
24 #include "libmarklin/tracktype.h"
25 #include "engineer.h"
26 #include "mainpanel.h"
27 #include "trainpanel.h"
28 #include "trainproperties.h"
29
30 using namespace std;
31 using namespace Marklin;
32 using namespace Msp;
33
34 Engineer::Engineer(int argc, char **argv):
35         screen_w(1280),
36         screen_h(960),
37         fullscreen(false),
38         layout(catalogue),
39         layout_3d(layout),
40         no_lighting(false),
41         placing_train(0),
42         placing_block(0),
43         placing_entry(0),
44         simulate(false),
45         train_prop(0),
46         train_prop_stale(false)
47 {
48         string res;
49         bool   debug=false;
50         string device="/dev/ttyS0";
51         unsigned quality=4;
52
53         GetOpt getopt;
54         getopt.add_option('r', "resolution",  res,         GetOpt::REQUIRED_ARG);
55         getopt.add_option('f', "fullscreen",  fullscreen,  GetOpt::NO_ARG);
56         getopt.add_option('g', "debug",       debug,       GetOpt::NO_ARG);
57         getopt.add_option('d', "device",      device,      GetOpt::REQUIRED_ARG);
58         getopt.add_option('q', "quality",     quality,     GetOpt::REQUIRED_ARG);
59         getopt.add_option('s', "simulate",    simulate,    GetOpt::NO_ARG);
60         getopt.add_option(     "no-lighting", no_lighting, GetOpt::NO_ARG);
61         getopt(argc, argv);
62
63         if(!res.empty())
64         {
65                 if(RegMatch m=Regex("([1-9][0-9]*)x([1-9][0-9]*)").match(res))
66                 {
67                         screen_w=lexical_cast<unsigned>(m[1].str);
68                         screen_h=lexical_cast<unsigned>(m[2].str);
69                 }
70                 else
71                         throw UsageError("Invalid resolution");
72         }
73
74         if(device!="none")
75                 control.open(device);
76
77         control.set_debug(debug);
78
79         layout_3d.set_quality(quality);
80
81         catalogue.load("tracks.dat");
82         catalogue.load("locos.dat");
83
84         const vector<string> &args=getopt.get_args();
85         if(args.empty())
86                 throw UsageError("No layout given");
87         DataFile::load(layout, args.front());
88
89         trfc_mgr=new TrafficManager(control, layout);
90         trfc_mgr->signal_block_reserved.connect(sigc::mem_fun(this, &Engineer::block_reserved));
91         if(FS::exists("engineer.state"))
92                 DataFile::load(*trfc_mgr, "engineer.state");
93
94         const map<unsigned, Sensor *> &sensors=control.get_sensors();
95         for(map<unsigned, Sensor *>::const_iterator i=sensors.begin(); i!=sensors.end(); ++i)
96                 i->second->signal_state_changed.connect(sigc::bind(sigc::mem_fun(this, &Engineer::sensor_event), i->second));
97
98         view_all();
99 }
100
101 Engineer::~Engineer()
102 {
103         if(!simulate)
104                 trfc_mgr->save("engineer.state");
105         delete trfc_mgr;
106 }
107
108 void Engineer::add_train()
109 {
110         train_prop=new TrainProperties(*this, ui_res, 0);
111         root->add(*train_prop);
112         train_prop->signal_ok.connect(sigc::mem_fun(this, &Engineer::dismiss_train_prop));
113         train_prop_stale=false;
114         train_prop->set_visible(true);
115 }
116
117 Train *Engineer::add_train(const LocoType &type, unsigned addr)
118 {
119         Locomotive *loco=new Locomotive(type, control, addr);
120         Train *train=new Train(*trfc_mgr, *loco);
121         train->set_name(format("Train %d", trfc_mgr->get_trains().size()));
122
123         TrainPanel *tpanel=new TrainPanel(*this, ui_res, *train);
124         root->add(*tpanel);
125         int y=main_panel->get_geometry().y;
126         for(list<TrainPanel *>::iterator i=train_panels.begin(); i!=train_panels.end(); ++i)
127                 y-=(*i)->get_geometry().h;
128         tpanel->set_position(0, y-tpanel->get_geometry().h);
129         train_panels.push_back(tpanel);
130         tpanel->set_visible(true);
131
132         place_train(*train);
133
134         return train;
135 }
136
137 void Engineer::place_train(Train &train)
138 {
139         placing_train=&train;
140         placing_block=0;
141         main_panel->set_status_text("Select location");
142 }
143
144 int Engineer::main()
145 {
146         dpy=new Graphics::Display;
147
148         Graphics::WindowOptions wopt;
149         wopt.width=screen_w;
150         wopt.height=screen_h;
151         wopt.fullscreen=fullscreen;
152         wnd=new Graphics::Window(*dpy, wopt);
153
154         Graphics::GLOptions glopt;
155         //glopt.multisample=4;
156         glc=new Graphics::GLContext(*wnd, glopt);
157
158         wnd->signal_close.connect(sigc::bind(sigc::mem_fun(this, &Engineer::exit), 0));
159         wnd->signal_button_press.connect(sigc::mem_fun(this, &Engineer::button_press));
160         wnd->signal_button_release.connect(sigc::mem_fun(this, &Engineer::button_release));
161         wnd->signal_pointer_motion.connect(sigc::mem_fun(this, &Engineer::pointer_motion));
162
163         glEnableClientState(GL_VERTEX_ARRAY);
164         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
165         glEnable(GL_COLOR_MATERIAL);
166         glDepthFunc(GL_LEQUAL);
167         glEnable(GL_BLEND);
168         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
169
170         DataFile::load(ui_res, "marklin.res");
171         root=new GLtk::Root(ui_res, *wnd);
172         root->set_visible(true);
173
174         list<GL::Texture *> texs=ui_res.get_list<GL::Texture>();
175         for(list<GL::Texture *>::iterator i=texs.begin(); i!=texs.end(); ++i)
176         {
177                 (*i)->set_min_filter(GL::NEAREST);
178                 (*i)->set_mag_filter(GL::NEAREST);
179         }
180
181         main_panel=new MainPanel(*this, ui_res);
182         root->add(*main_panel);
183         main_panel->set_position(0, screen_h-main_panel->get_geometry().h);
184         main_panel->set_visible(true);
185
186         const list<Train *> &trains=trfc_mgr->get_trains();
187         int y=main_panel->get_geometry().y;
188         for(list<Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
189         {
190                 TrainPanel *tpanel=new TrainPanel(*this, ui_res, **i);
191                 root->add(*tpanel);
192                 tpanel->set_position(0, y-tpanel->get_geometry().h);
193                 train_panels.push_back(tpanel);
194                 tpanel->set_visible(true);
195                 y-=tpanel->get_geometry().h;
196         }
197
198         wnd->show();
199
200         Application::main();
201
202         delete glc;
203         delete wnd;
204         delete dpy;
205
206         return exit_code;
207 }
208
209 void Engineer::tick()
210 {
211         dpy->tick();
212
213         control.tick();
214         trfc_mgr->tick();
215
216         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
217
218         project_3d();
219         glLoadIdentity();
220         glRotatef(-cam_rot*180/M_PI, 0, 0, 1);
221         glTranslatef(-cam_pos.x, -cam_pos.y, -cam_pos.z);
222
223         if(!no_lighting)
224         {
225                 glEnable(GL_LIGHTING);
226                 glEnable(GL_LIGHT0);
227                 float params[4];
228                 params[0]=0;
229                 params[1]=-0.2;
230                 params[2]=1;
231                 params[3]=0;
232                 glLightfv(GL_LIGHT0, GL_POSITION, params);
233         }
234
235         //glEnable(GL_DEPTH_TEST);
236         glEnable(GL_MULTISAMPLE);
237
238         layout_3d.render();
239
240         glDisable(GL_LIGHTING);
241         glColor4f(1, 1, 1, 1);
242         const list<Track3D *> &ltracks=layout_3d.get_tracks();
243         for(list<Track3D *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
244         {
245                 Track &track=(*i)->get_track();
246                 if(track.get_turnout_id())
247                 {
248                         Turnout &trnt=control.get_turnout(track.get_turnout_id());
249                         (*i)->render_route(trnt.get_route());
250                 }
251                 else
252                         (*i)->render_route(-1);
253         }
254
255         if(placing_train && placing_block)
256         {
257                 GL::push_matrix();
258
259                 const Marklin::Block::Endpoint &bep=placing_block->get_endpoints()[placing_entry];
260                 float rot=bep.track->get_endpoint_direction(bep.track_ep);
261                 Point pos=bep.track->get_endpoint_position(bep.track_ep);
262
263                 GL::translate(pos.x, pos.y, pos.z+0.03);
264                 GL::rotate(rot*180/M_PI+180, 0, 0, 1);
265                 GL::Texture::unbind();
266
267                 GL::Immediate imm((GL::COLOR4_UBYTE, GL::VERTEX2));
268                 imm.color(1.0f, 1.0f, 1.0f);
269                 imm.begin(GL::TRIANGLE_FAN);
270                 imm.vertex(0.08,   0);
271                 imm.vertex(0.05,   0.03);
272                 imm.vertex(0.05,   0.01);
273                 imm.vertex(0,      0.01);
274                 imm.vertex(0,     -0.01);
275                 imm.vertex(0.05,  -0.01);
276                 imm.vertex(0.05,  -0.03);
277                 imm.end();
278
279                 GL::pop_matrix();
280         }
281
282         const list<Train *> &trains=trfc_mgr->get_trains();
283         for(list<Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
284         {
285                 GL::PushMatrix _push;
286
287                 const Point &tp=(*i)->get_position();
288                 GL::translate(tp.x, tp.y, 0.02);
289                 GL::Immediate imm((GL::COLOR4_UBYTE, GL::VERTEX2));
290                 imm.color(0.8f, 0.8f, 1.0f);
291                 imm.begin(GL::TRIANGLE_FAN);
292                 imm.vertex(0, 0);
293                 for(unsigned j=0; j<=12; ++j)
294                         imm.vertex(0.02*cos(j*M_PI/6), 0.02*sin(j*M_PI/6));
295                 imm.end();
296
297                 GL::rotate(cam_rot*180/M_PI, 0, 0, 1);
298                 GL::translate(0.03, -0.02, 0);
299                 GL::scale_uniform(0.04);
300                 ui_res.get_default_font().draw_string((*i)->get_name());
301                 GL::Texture::unbind();
302         }
303
304         GL::matrix_mode(GL::PROJECTION);
305         GL::load_identity();
306         GL::ortho_bottomleft(screen_w, screen_h);
307         GL::matrix_mode(GL::MODELVIEW);
308         GL::load_identity();
309
310         glDisable(GL_DEPTH_TEST);
311         glDisable(GL_LIGHTING);
312         glDisable(GL_MULTISAMPLE);
313
314         root->render();
315
316         if(train_prop_stale)
317         {
318                 delete train_prop;
319                 train_prop=0;
320         }
321
322         glc->swap_buffers();
323 }
324
325 void Engineer::key_press(unsigned key, unsigned mod, wchar_t ch)
326 {
327         if(train_prop)
328                 train_prop->key_press(key, mod, ch);
329 }
330
331 void Engineer::button_press(int x, int y, unsigned btn, unsigned)
332 {
333         if(placing_train)
334         {
335                 if(btn==1 && placing_block && !placing_block->get_train())
336                 {
337                         set_block_color(*placing_block, GL::Color(1, 1, 1));
338
339                         placing_train->place(placing_block, placing_entry);
340                         placing_train=0;
341                         main_panel->set_status_text(string());
342                 }
343                 else if(btn==3)
344                 {
345                         const vector<Block::Endpoint> &endpoints=placing_block->get_endpoints();
346                         placing_entry=(placing_entry+1)%endpoints.size();
347                 }
348         }
349         else
350         {
351                 Track3D *track=pick_track(x, screen_h-y-1);
352                 if(track)
353                 {
354                         if(unsigned tid=track->get_track().get_turnout_id())
355                         {
356                                 Turnout &turnout=control.get_turnout(tid);
357                                 try
358                                 {
359                                         turnout.set_route((turnout.get_route()+1)%track->get_track().get_type().get_n_routes());
360                                         main_panel->set_status_text(format("Turnout %d switched", turnout.get_address()));
361                                 }
362                                 catch(const TurnoutBusy &e)
363                                 {
364                                         main_panel->set_status_text(e.what());
365                                 }
366                         }
367                         else if(simulate)
368                         {
369                                 if(unsigned sid=track->get_track().get_sensor_id())
370                                 {
371                                         Sensor &sensor=control.get_sensor(sid);
372                                         control.signal_sensor_event.emit(sid, !sensor.get_state());
373                                 }
374                         }
375                 }
376         }
377 }
378
379 void Engineer::button_release(int, int, unsigned, unsigned)
380 {
381 }
382
383 void Engineer::pointer_motion(int x, int y)
384 {
385         if(placing_train)
386         {
387                 Track3D *track=pick_track(x, screen_h-y-1);
388                 if(track && placing_train)
389                 {
390                         Block &block=trfc_mgr->get_block_by_track(track->get_track());
391                         if(&block!=placing_block)
392                         {
393                                 if(placing_block)
394                                         reset_block_color(*placing_block);
395                                 placing_block=&block;
396                                 placing_entry=0;
397                                 set_block_color(*placing_block, GL::Color(0.5, 1, 0.7));
398                         }
399                 }
400                 else if(track && track->get_track().get_turnout_id())
401                         main_panel->set_status_text(format("Turnout %d", track->get_track().get_turnout_id()));
402                 else if(!placing_train)
403                         main_panel->set_status_text(string());
404         }
405 }
406
407 void Engineer::view_all()
408 {
409         const list<Track3D *> &tracks=layout_3d.get_tracks();
410
411         cam_rot=0;
412         float best_height=-1;
413         float mid_x=0;
414         float mid_y=0;
415         for(float angle=0; angle<M_PI; angle+=0.01)
416         {
417                 float min_x=0;
418                 float max_x=0;
419                 float min_y=0;
420                 float max_y=0;
421                 for(list<Track3D *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
422                 {
423                         Point minp, maxp;
424                         (*i)->get_bounds(angle, minp, maxp);
425                         min_x=min(min_x, minp.x);
426                         max_x=max(max_x, maxp.x);
427                         min_y=min(min_y, minp.y);
428                         max_y=max(max_y, maxp.y);
429                 }
430
431                 float width=max_x-min_x;
432                 float height=max_y-min_y;
433                 height=max(height, width);
434
435                 if(height<best_height || best_height<0)
436                 {
437                         cam_rot=angle;
438                         best_height=height;
439                         mid_x=(min_x+max_x)/2;
440                         mid_y=(min_y+max_y)/2;
441                 }
442         }
443
444         float c=cos(cam_rot);
445         float s=sin(cam_rot);
446         cam_pos.x=c*mid_x-s*mid_y;
447         cam_pos.y=s*mid_x+c*mid_y;
448         cam_pos.z=max(best_height*1.05/0.82843, 0.15);
449 }
450
451 void Engineer::set_block_color(const Block &block, const GL::Color &color)
452 {
453         const set<Track *> &tracks=block.get_tracks();
454         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
455                 layout_3d.get_track(**i).set_color(color);
456 }
457
458 void Engineer::reset_block_color(const Block &block)
459 {
460         if(unsigned sid=block.get_sensor_id())
461         {
462                 Sensor &sensor=control.get_sensor(sid);
463                 if(sensor.get_state())
464                 {
465                         set_block_color(block, GL::Color(1, 0.5, 0.3));
466                         return;
467                 }
468         }
469
470         if(block.get_train())
471                 set_block_color(block, GL::Color(1, 1, 0.3));
472         else
473                 set_block_color(block, GL::Color(1, 1, 1));
474 }
475
476 void Engineer::sensor_event(bool, Sensor *sensor)
477 {
478         const list<Block *> &blocks=trfc_mgr->get_blocks();
479         for(list<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
480                 if((*i)->get_sensor_id()==sensor->get_address())
481                         reset_block_color(**i);
482 }
483
484 void Engineer::block_reserved(const Block &block, const Train *)
485 {
486         reset_block_color(block);
487 }
488
489 void Engineer::project_3d()
490 {
491         glMatrixMode(GL_PROJECTION);
492         glLoadIdentity();
493         float offset=200.0/screen_w*0.055228;
494         glFrustum(-0.055228-offset, 0.055228-offset, -0.041421, 0.041421, 0.1, 10);
495         glMatrixMode(GL_MODELVIEW);
496 }
497
498 Track3D *Engineer::pick_track(int x, int y)
499 {
500         float xx=(static_cast<float>(x-static_cast<int>(screen_w)/2-100)/screen_h)*0.82843;
501         float yy=(static_cast<float>(y)/screen_h-0.5)*0.82843;
502         float size=4.0/screen_h*0.82843;
503
504         project_3d();
505         glLoadIdentity();
506         glRotatef(-cam_rot*180/M_PI, 0, 0, 1);
507         glTranslatef(-cam_pos.x, -cam_pos.y, -cam_pos.z);
508
509         return layout_3d.pick_track(xx, yy, size);
510 }
511
512 void Engineer::dismiss_train_prop()
513 {
514         train_prop_stale=true;
515 }
516
517 Application::RegApp<Engineer> Engineer::reg;