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