]> git.tdb.fi Git - r2c2.git/blobdiff - source/engineer/engineer.cpp
Rename the project to R²C²
[r2c2.git] / source / engineer / engineer.cpp
index 87a4d6d3afa6c4a75f424ce804e4c3b49491e3e4..1f3b7dc4accc617e56eb8c587f4064c0d9e091d2 100644 (file)
@@ -1,21 +1,21 @@
 /* $Id$
 
-This file is part of the MSP Märklin suite
+This file is part of R²C²
 Copyright © 2006-2010 Mikkosoft Productions, Mikko Rasa
 Distributed under the GPL
 */
 
+#include <algorithm>
 #include <cmath>
+#include <cstdlib>
 #include <limits>
 #include <signal.h>
 #include <msp/core/except.h>
-#include <msp/core/getopt.h>
 #include <msp/fs/stat.h>
 #include <msp/gbase/display.h>
 #include <msp/gbase/window.h>
 #include <msp/gl/blend.h>
 #include <msp/gl/framebuffer.h>
-#include <msp/gl/immediate.h>
 #include <msp/gl/matrix.h>
 #include <msp/gl/misc.h>
 #include <msp/gl/projection.h>
@@ -23,120 +23,94 @@ Distributed under the GPL
 #include <msp/gl/transform.h>
 #include <msp/io/print.h>
 #include <msp/strings/formatter.h>
-#include <msp/strings/lexicalcast.h>
-#include <msp/strings/regex.h>
 #include <msp/time/units.h>
-#include "libmarklin/except.h"
-#include "libmarklin/tracktype.h"
+#include <msp/time/utils.h>
+#include "libr2c2/driver.h"
+#include "libr2c2/tracktype.h"
+#include "3d/path.h"
+#include "3d/track.h"
+#include "3d/vehicle.h"
 #include "engineer.h"
 #include "mainpanel.h"
 #include "trainpanel.h"
 #include "trainproperties.h"
+#include "trainview.h"
 
 using namespace std;
-using namespace Marklin;
+using namespace R2C2;
 using namespace Msp;
 
+Application::RegApp<Engineer> Engineer::reg;
+
 Engineer::Engineer(int argc, char **argv):
-       layout(catalogue),
+       options(argc, argv),
+       window(options.screen_w, options.screen_h, options.fullscreen),
+       layout(catalogue, (options.driver.empty() ? 0 : Driver::create(options.driver))),
        layout_3d(layout),
        server(0),
-       placing_train(0),
-       placing_block(0),
-       placing_entry(0),
-       simulate(false)
+       pipeline(window.get_width(), window.get_height(), false),
+       picking(false),
+       picking_track(0),
+       picking_entry(0),
+       picking_path(0),
+       pointer_x(0),
+       pointer_y(0),
+       pointer_moved(false)
 {
-       // Parse options
-       unsigned screen_w = 1280;
-       unsigned screen_h = 960;
-       bool fullscreen = false;
-       string res;
-       bool debug = false;
-       string device = "/dev/ttyS0";
-       bool network = false;
-
-       GetOpt getopt;
-       getopt.add_option('r', "resolution",  res,         GetOpt::REQUIRED_ARG);
-       getopt.add_option('f', "fullscreen",  fullscreen,  GetOpt::NO_ARG);
-       getopt.add_option('g', "debug",       debug,       GetOpt::NO_ARG);
-       getopt.add_option('d', "device",      device,      GetOpt::REQUIRED_ARG);
-       getopt.add_option('s', "simulate",    simulate,    GetOpt::NO_ARG);
-       getopt.add_option('n', "network",     network,     GetOpt::NO_ARG);
-       getopt(argc, argv);
-
-       const vector<string> &args = getopt.get_args();
-       if(args.empty())
-               throw UsageError("No layout given");
-
-       if(!res.empty())
-       {
-               if(RegMatch m=Regex("([1-9][0-9]*)x([1-9][0-9]*)").match(res))
-               {
-                       screen_w = lexical_cast<unsigned>(m[1].str);
-                       screen_h = lexical_cast<unsigned>(m[2].str);
-               }
-               else
-                       throw UsageError("Invalid resolution");
-       }
-
        // Setup GUI
-       window = new Graphics::SimpleGLWindow(screen_w, screen_h, fullscreen);
-       window->set_title("Railroad Engineer");
-       window->signal_close.connect(sigc::bind(sigc::mem_fun(this, &Engineer::exit), 0));
+       window.set_title("Railroad Engineer");
+       window.signal_close.connect(sigc::bind(sigc::mem_fun(this, &Engineer::exit), 0));
 
-       DataFile::load(ui_res, "marklin.res");
-       root = new GLtk::Root(ui_res, *window);
+       DataFile::load(ui_res, "r2c2.res");
+       root = new GLtk::Root(ui_res, window);
        root->signal_button_press.connect(sigc::mem_fun(this, &Engineer::button_press));
        root->signal_pointer_motion.connect(sigc::mem_fun(this, &Engineer::pointer_motion));
        root->set_visible(true);
 
-       main_panel = new MainPanel(*this, ui_res);
+       main_panel = new MainPanel(*this);
        root->add(*main_panel);
-       main_panel->set_position(0, window->get_height()-main_panel->get_geometry().h);
+       main_panel->set_position(0, window.get_height()-main_panel->get_geometry().h);
        main_panel->set_visible(true);
 
+       overlay = new Overlay3D(window, camera, ui_res.get_default_font());
+
        // Setup railroad control
        DataFile::load(catalogue, "tracks.dat");
        DataFile::load(catalogue, "locos.dat");
-       DataFile::load(layout, args.front());
-
-       if(device!="none")
-               control.open(device);
+       DataFile::load(catalogue, "wagons.dat");
+       DataFile::load(layout, options.layout_fn);
 
-       control.set_debug(debug);
+       layout.signal_train_added.connect(sigc::mem_fun(this, &Engineer::train_added));
+       layout.signal_block_reserved.connect(sigc::mem_fun(this, &Engineer::block_reserved));
+       layout.signal_emergency.connect(sigc::mem_fun(this, &Engineer::set_status));
+       layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Engineer::sensor_event));
+       if(FS::exists(options.state_fn))
+               DataFile::load(layout, options.state_fn);
 
-       trfc_mgr = new TrafficManager(control, layout);
-       layout_3d.set_traffic_manager(*trfc_mgr);
-       trfc_mgr->signal_train_added.connect(sigc::mem_fun(this, &Engineer::train_added));
-       trfc_mgr->signal_block_reserved.connect(sigc::mem_fun(this, &Engineer::block_reserved));
-       if(FS::exists("engineer.state"))
-               DataFile::load(*trfc_mgr, "engineer.state");
-
-       if(network)
+       if(options.network)
        {
-               server = new Server(*trfc_mgr);
+               server = new Server(layout);
                server->use_event_dispatcher(event_disp);
        }
 
-       const map<unsigned, Sensor *> &sensors = control.get_sensors();
-       for(map<unsigned, Sensor *>::const_iterator i=sensors.begin(); i!=sensors.end(); ++i)
-               i->second->signal_state_changed.connect(sigc::bind(sigc::mem_fun(this, &Engineer::sensor_event), i->second));
-
        // Setup 3D view
        DataFile::load(arrow_mesh, "arrow.mesh");
 
-       overlay = new Overlay3D(*window, camera, ui_res.get_default_font());
-
-       pipeline = new GL::Pipeline(window->get_width(), window->get_height(), false);
-       pipeline->set_camera(&camera);
-       pipeline->add_renderable(layout_3d.get_scene());
+       pipeline.set_camera(&camera);
+       pipeline.add_renderable_for_pass(layout_3d.get_scene(), 0);
+       pipeline.add_renderable_for_pass(layout_3d.get_path_scene(), "unlit");
 
-       light.set_position(0, -0.259, 0.966, 0);
+       light.set_position(GL::Vector4(0, -0.259, 0.966, 0));
+       light.set_diffuse(GL::Color(0.9));
+       lighting.set_ambient(GL::Color(0.4));
        lighting.attach(0, light);
 
-       GL::PipelinePass &pass = pipeline->add_pass(0);
-       pass.depth_test = &GL::DepthTest::lequal();
-       pass.lighting = &lighting;
+       GL::PipelinePass *pass = &pipeline.add_pass(0);
+       pass->depth_test = &GL::DepthTest::lequal();
+       pass->lighting = &lighting;
+
+       pass = &pipeline.add_pass("unlit");
+       pass->depth_test = &GL::DepthTest::lequal();
 
        view_all();
 
@@ -151,66 +125,115 @@ Engineer::Engineer(int argc, char **argv):
 
 Engineer::~Engineer()
 {
-       const list<Train *> &trains = trfc_mgr->get_trains();
-       for(list<Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
-               (*i)->set_speed(0);
-
-       while(control.get_queue_length())
-               control.tick();
+       const map<unsigned, Train *> &trains = layout.get_trains();
+       for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
+               layout.get_driver().set_loco_speed(i->first, 0);
+       layout.get_driver().flush();
 
-       if(!simulate)
-               trfc_mgr->save("engineer.state");
+       if(!options.simulate)
+               layout.save_trains(options.state_fn);
 
-       delete pipeline;
        delete overlay;
        delete root;
-       delete window;
 
-       delete trfc_mgr;
        delete server;
 }
 
-void Engineer::place_train(Train &train)
+void Engineer::set_status(const string &text)
 {
-       placing_train = &train;
-       placing_block = 0;
-       main_panel->set_status_text("Select location");
+       main_panel->set_status_text(text);
+       status_timeout = Time::now()+10*Time::sec;
+}
+
+void Engineer::rearrange_panels()
+{
+       int y = main_panel->get_geometry().y;
+       for(list<TrainPanel *>::iterator i=train_panels.begin(); i!=train_panels.end(); ++i)
+       {
+               y -= (*i)->get_geometry().h;
+               (*i)->set_position(0, y);
+       }
+}
+
+void Engineer::add_train_view(TrainView &tv)
+{
+       train_views.push_back(&tv);
+}
+
+void Engineer::remove_train_view(TrainView &tv)
+{
+       train_views.erase(remove(train_views.begin(), train_views.end(), &tv), train_views.end());
+}
+
+void Engineer::pick(bool with_ep)
+{
+       picking = true;
+       picking_track = 0;
+       picking_entry = (with_ep ? 0 : -1);
 }
 
 int Engineer::main()
 {
-       window->show();
+       window.show();
 
        return Application::main();
 }
 
 void Engineer::tick()
 {
-       window->get_display().tick();
+       window.get_display().tick();
 
-       control.tick();
-       trfc_mgr->tick();
+       layout.tick();
        event_disp.tick(Time::zero);
 
-       for(list<Train *>::iterator i=new_trains.begin(); i!=new_trains.end(); ++i)
-               overlay->set_label(layout_3d.get_train(**i), (*i)->get_name());
-       new_trains.clear();
+       for(list<TrainView *>::iterator i=train_views.begin(); i!=train_views.end(); ++i)
+               (*i)->prepare();
 
-       GL::clear(GL::COLOR_BUFFER_BIT|GL::DEPTH_BUFFER_BIT);
+       if(status_timeout && Time::now()>status_timeout)
+       {
+               main_panel->set_status_text(string());
+               status_timeout = Time::TimeStamp();
+       }
+
+       GL::Framebuffer::system().clear(GL::COLOR_BUFFER_BIT|GL::DEPTH_BUFFER_BIT);
 
-       pipeline->render_all();
+       pipeline.render_all();
        {
                GL::Bind blend(GL::Blend::alpha());
                overlay->render(0);
        }
 
-       if(placing_train && placing_block)
+       if(pointer_moved)
+       {
+               pointer_moved = false;
+
+               if(picking)
+               {
+                       Track3D *track = pick_track(pointer_x, window.get_height()-pointer_y-1);
+                       if(track && &track->get_track()!=picking_track)
+                       {
+                               picking_track = &track->get_track();
+                               if(picking_entry>=0)
+                                       picking_entry = 0;
+
+                               delete picking_path;
+                               picking_path = new Path3D(*track);
+                               if(picking_entry>=0)
+                                       picking_path->set_mask(picking_track->get_type().get_endpoint(picking_entry).paths);
+                               else
+                                       picking_path->set_mask(picking_track->get_type().get_paths());
+                               picking_path->set_color(GL::Color(0));
+                               picking_path->set_layer(1);
+                       }
+               }
+       }
+
+       if(picking && picking_track && picking_entry>=0)
        {
                GL::PushMatrix push_mat;
 
-               const Marklin::Block::Endpoint &bep = placing_block->get_endpoints()[placing_entry];
-               float rot = bep.track->get_endpoint_direction(bep.track_ep);
-               Point pos = bep.track->get_endpoint_position(bep.track_ep);
+               float rot = picking_track->get_endpoint_direction(picking_entry);
+               Point pos = picking_track->get_endpoint_position(picking_entry);
 
                GL::translate(pos.x, pos.y, pos.z+0.03);
                GL::rotate(rot*180/M_PI+180, 0, 0, 1);
@@ -231,52 +254,57 @@ void Engineer::tick()
                GL::Texture::unbind();
        }
 
-       window->swap_buffers();
+       window.swap_buffers();
 }
 
 void Engineer::button_press(int x, int y, unsigned btn, unsigned)
 {
-       if(placing_train)
+       if(picking)
        {
-               if(btn==1 && placing_block && !placing_block->get_train())
+               if(btn==1 && picking_track)
                {
-                       reset_block_color(*placing_block);
-
-                       placing_train->place(*placing_block, placing_entry);
-                       placing_train = 0;
-                       main_panel->set_status_text(string());
+                       picking = false;
+                       delete picking_path;
+                       picking_path = 0;
+                       signal_pick_done.emit(picking_track, picking_entry);
                }
-               else if(btn==3)
+               else if(btn==3 && picking_entry>=0)
                {
-                       const vector<Block::Endpoint> &endpoints = placing_block->get_endpoints();
-                       placing_entry = (placing_entry+1)%endpoints.size();
+                       picking_entry = (picking_entry+1)%picking_track->get_type().get_endpoints().size();
+                       picking_path->set_mask(picking_track->get_type().get_endpoint(picking_entry).paths);
                }
        }
        else
        {
-               Track3D *track = pick_track(x, window->get_height()-y-1);
-               if(track)
+               Track3D *t3d = pick_track(x, window.get_height()-y-1);
+               if(t3d)
                {
-                       if(unsigned tid=track->get_track().get_turnout_id())
+                       Track &track = t3d->get_track();
+                       if(track.get_turnout_id())
                        {
-                               Turnout &turnout = control.get_turnout(tid);
-                               try
+                               Block &block = track.get_block();
+                               if(block.get_train() && !block.get_train()->free_block(block))
+                                       set_status("Turnout is busy");
+                               else
                                {
-                                       turnout.set_path((turnout.get_path()+1)%track->get_track().get_type().get_n_paths());
-                                       main_panel->set_status_text(format("Turnout %d switched", turnout.get_address()));
-                               }
-                               catch(const TurnoutBusy &e)
-                               {
-                                       main_panel->set_status_text(e.what());
+                                       unsigned paths = track.get_type().get_paths();
+                                       unsigned i = track.get_active_path()+1;
+                                       while(!(paths&(1<<i)))
+                                       {
+                                               if(!(paths>>i))
+                                                       i = 0;
+                                               else
+                                                       ++i;
+                                       }
+                                       track.set_active_path(i);
+                                       set_status(format("Turnout %d", track.get_turnout_id()));
                                }
                        }
-                       else if(simulate)
+                       if(unsigned sid = track.get_sensor_id())
                        {
-                               if(unsigned sid=track->get_track().get_sensor_id())
-                               {
-                                       Sensor &sensor = control.get_sensor(sid);
-                                       control.signal_sensor_event.emit(sid, !sensor.get_state());
-                               }
+                               if(options.simulate)
+                                       layout.get_driver().set_sensor(sid, !layout.get_driver().get_sensor(sid));
+                               set_status(format("Sensor %d", sid));
                        }
                }
        }
@@ -284,29 +312,16 @@ void Engineer::button_press(int x, int y, unsigned btn, unsigned)
 
 void Engineer::pointer_motion(int x, int y)
 {
-       if(placing_train)
-       {
-               Track3D *track = pick_track(x, window->get_height()-y-1);
-               if(track)
-               {
-                       Block &block = trfc_mgr->get_block_by_track(track->get_track());
-                       if(&block!=placing_block)
-                       {
-                               if(placing_block)
-                                       reset_block_color(*placing_block);
-                               placing_block = &block;
-                               placing_entry = 0;
-                               set_block_color(*placing_block, GL::Color(0.5, 1, 0.7));
-                       }
-               }
-       }
+       pointer_x = x;
+       pointer_y = y;
+       pointer_moved = true;
 }
 
 void Engineer::view_all()
 {
-       const list<Track3D *> &tracks = layout_3d.get_tracks();
+       const Layout3D::TrackMap &tracks = layout_3d.get_tracks();
 
-       float view_aspect = float(window->get_width()-200)/window->get_height();
+       float view_aspect = float(window.get_width()-200)/window.get_height();
        float view_height = tan(camera.get_field_of_view()/2)*2;
        float best_score = 0;
        GL::Vector3 pos;
@@ -317,10 +332,10 @@ void Engineer::view_all()
                float max_x = 0;
                float min_y = 0;
                float max_y = 0;
-               for(list<Track3D *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+               for(Layout3D::TrackMap::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
                {
                        Point minp, maxp;
-                       (*i)->get_bounds(angle, minp, maxp);
+                       i->second->get_bounds(angle, minp, maxp);
                        min_x = min(min_x, minp.x);
                        max_x = max(max_x, maxp.x);
                        min_y = min(min_y, minp.y);
@@ -339,7 +354,7 @@ void Engineer::view_all()
                        float size = max(width/view_aspect, height);
                        float c = cos(angle);
                        float s = sin(angle);
-                       float x = (min_x+max_x)/2-size*105/window->get_height();
+                       float x = (min_x+max_x)/2-size*105/window.get_height();
                        float y = (min_y+max_y)/2;
                        float z = max(size*1.05/view_height, 0.15);
 
@@ -351,37 +366,46 @@ void Engineer::view_all()
        camera.set_position(pos);
        camera.set_up_direction(up);
        camera.set_look_direction(GL::Vector3(0, 0, -1));
+       camera.set_aspect(float(window.get_width())/window.get_height());
+       camera.set_depth_clip(pos.z*0.5, pos.z*1.5);
 }
 
 void Engineer::set_block_color(const Block &block, const GL::Color &color)
 {
-       (void)block;
-       (void)color;
+       const set<Track *> &tracks = block.get_tracks();
+       for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+               layout_3d.get_track(**i).get_path().set_color(color);
 }
 
 void Engineer::reset_block_color(const Block &block)
 {
+       bool active = false;
        if(unsigned sid=block.get_sensor_id())
-       {
-               Sensor &sensor = control.get_sensor(sid);
-               if(sensor.get_state())
-               {
-                       set_block_color(block, GL::Color(1, 0.5, 0.3));
-                       return;
-               }
-       }
+               active = layout.get_driver().get_sensor(sid);
 
        if(block.get_train())
-               set_block_color(block, GL::Color(1, 1, 0.3));
+       {
+               GL::Color color;
+               map<Train *, GL::Color>::iterator i = train_colors.find(block.get_train());
+               if(i!=train_colors.end())
+                       color = i->second;
+
+               if(active)
+                       set_block_color(block, color*0.6);
+               else
+                       set_block_color(block, color*0.5+0.5);
+       }
+       else if(active)
+               set_block_color(block, GL::Color(0.6));
        else
-               set_block_color(block, GL::Color(1, 1, 1));
+               set_block_color(block, GL::Color(1));
 }
 
-void Engineer::sensor_event(bool, Sensor *sensor)
+void Engineer::sensor_event(unsigned addr, bool)
 {
-       const list<Block *> &blocks = trfc_mgr->get_blocks();
-       for(list<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
-               if((*i)->get_sensor_id()==sensor->get_address())
+       const set<Block *> &blocks = layout.get_blocks();
+       for(set<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
+               if((*i)->get_sensor_id()==addr)
                        reset_block_color(**i);
 }
 
@@ -393,9 +417,9 @@ void Engineer::block_reserved(const Block &block, const Train *)
 Track3D *Engineer::pick_track(int x, int y)
 {
        float view_height = tan(camera.get_field_of_view()/2)*2;
-       float xx = ((float(x)-window->get_width()/2)/window->get_height())*view_height;
-       float yy = (float(y)/window->get_height()-0.5)*view_height;
-       float size = 4.0/window->get_height()*view_height;
+       float xx = ((float(x)-window.get_width()/2)/window.get_height())*view_height;
+       float yy = (float(y)/window.get_height()-0.5)*view_height;
+       float size = 4.0/window.get_height()*view_height;
 
        camera.apply();
 
@@ -404,16 +428,41 @@ Track3D *Engineer::pick_track(int x, int y)
 
 void Engineer::train_added(Train &train)
 {
-       TrainPanel *tpanel = new TrainPanel(*this, ui_res, train);
+       TrainPanel *tpanel = new TrainPanel(*this, train);
        root->add(*tpanel);
-       int y = main_panel->get_geometry().y;
-       for(list<TrainPanel *>::iterator i=train_panels.begin(); i!=train_panels.end(); ++i)
-               y -= (*i)->get_geometry().h;
-       tpanel->set_position(0, y-tpanel->get_geometry().h);
        train_panels.push_back(tpanel);
-       tpanel->set_visible(true);
+       rearrange_panels();
 
-       new_trains.push_back(&train);
+       Vehicle3D &loco3d = layout_3d.get_vehicle(train.get_vehicle(0));
+       overlay->set_label(loco3d, train.get_name());
+       train.signal_name_changed.connect(sigc::bind<0>(sigc::mem_fun(overlay, &Overlay3D::set_label), sigc::ref(loco3d)));
+
+       GL::Color best_color;
+       float best_d_sq = 0;
+       for(unsigned i=0; i<10; ++i)
+       {
+               GL::Color color;
+               color.r = rand()*1.0/RAND_MAX;
+               color.g = rand()*1.0/RAND_MAX;
+               color.b = rand()*1.0/RAND_MAX;
+               color = color*(1/max(max(color.r, color.g), color.b));
+               float min_d_sq = 3;
+               for(map<Train *, GL::Color>::const_iterator j=train_colors.begin(); j!=train_colors.end(); ++j)
+               {
+                       float dr = color.r-j->second.r;
+                       float dg = color.g-j->second.g;
+                       float db = color.b-j->second.b;
+                       float d_sq = dr*dr+dg*dg+db*db;
+                       if(d_sq<min_d_sq)
+                               min_d_sq = d_sq;
+               }
+               if(min_d_sq>best_d_sq)
+               {
+                       best_color = color;
+                       best_d_sq = min_d_sq;
+               }
+       }
+       train_colors[&train] = best_color;
 }
 
 void Engineer::sighandler(int sig)
@@ -422,14 +471,12 @@ void Engineer::sighandler(int sig)
        {
                signal(sig, SIG_DFL);
                IO::print(IO::cerr, "Fatal signal received, terminating\n");
-               const map<unsigned, Locomotive *> &locos = control.get_locomotives();
-               for(map<unsigned, Locomotive *>::const_iterator i=locos.begin(); i!=locos.end(); ++i)
-                       i->second->set_speed(0);
-               control.flush();
+               const map<unsigned, Train *> &trains = layout.get_trains();
+               for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
+                       layout.get_driver().set_loco_speed(i->first, 0);
+               layout.get_driver().flush();
                raise(sig);
        }
        else if(sig==SIGTERM || sig==SIGINT)
                exit(0);
 }
-
-Application::RegApp<Engineer> Engineer::reg;