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