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