]> git.tdb.fi Git - r2c2.git/blobdiff - source/libr2c2/train.cpp
TrainAI framework
[r2c2.git] / source / libr2c2 / train.cpp
index ffa436b1d6a0c07795bf876d304077bb08a80fcd..38765cee7fde73517df49f546c5205bdd95caefa 100644 (file)
@@ -1,10 +1,11 @@
 /* $Id$
 
 This file is part of R²C²
-Copyright © 2006-2010  Mikkosoft Productions, Mikko Rasa
+Copyright © 2006-2011  Mikkosoft Productions, Mikko Rasa
 Distributed under the GPL
 */
 
+#include <algorithm>
 #include <cmath>
 #include <msp/strings/formatter.h>
 #include <msp/time/units.h>
@@ -15,6 +16,7 @@ Distributed under the GPL
 #include "layout.h"
 #include "route.h"
 #include "simplecontroller.h"
+#include "speedquantizer.h"
 #include "timetable.h"
 #include "trackiter.h"
 #include "tracktype.h"
@@ -48,13 +50,13 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
        protocol(p),
        priority(0),
        yielding_to(0),
+       preceding_train(0),
        cur_blocks_end(blocks.end()),
        clear_blocks_end(blocks.end()),
        pending_block(0),
        reserving(false),
        advancing(false),
-       controller(new AIControl(*this, new SimpleController)),
-       timetable(0),
+       controller(new SimpleController),
        active(false),
        current_speed_step(0),
        speed_changing(false),
@@ -64,18 +66,22 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
        status("Unplaced"),
        travel_dist(0),
        pure_speed(false),
-       real_speed(layout.get_driver().get_protocol_speed_steps(protocol)+1),
+       speed_quantizer(0),
        accurate_position(false),
        overshoot_dist(false)
 {
        if(!loco_type.is_locomotive())
                throw InvalidParameterValue("Initial vehicle must be a locomotive");
 
+       unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
+       if(speed_steps)
+               speed_quantizer = new SpeedQuantizer(speed_steps);
+
        vehicles.push_back(new Vehicle(layout, loco_type));
 
        layout.add_train(*this);
 
-       layout.get_driver().add_loco(address, protocol);
+       layout.get_driver().add_loco(address, protocol, loco_type);
        layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
        layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
 
@@ -95,7 +101,6 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
 Train::~Train()
 {
        delete controller;
-       delete timetable;
        for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
                delete *i;
        layout.remove_train(*this);
@@ -185,10 +190,7 @@ void Train::set_function(unsigned func, bool state)
 {
        if(!loco_type.get_functions().count(func))
                throw InvalidParameterValue("Invalid function");
-       if(func<5)
-               layout.get_driver().set_loco_function(address, func, state);
-       else
-               layout.get_driver().set_loco_function(address+1, func-4, state);
+       layout.get_driver().set_loco_function(address, func, state);
 }
 
 float Train::get_control(const string &ctrl) const
@@ -206,10 +208,32 @@ bool Train::get_function(unsigned func) const
        return (functions>>func)&1;
 }
 
-void Train::set_timetable(Timetable *tt)
+void Train::add_ai(TrainAI &ai)
+{
+       ais.push_back(&ai);
+       ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
+}
+
+void Train::remove_ai(TrainAI &ai)
+{
+       list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
+       if(i!=ais.end())
+               ais.erase(i);
+}
+
+TrainAI *Train::get_tagged_ai(const string &tag)
+{
+       for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
+               if((*i)->get_tag()==tag)
+                       return *i;
+
+       return 0;
+}
+
+void Train::ai_message(const TrainAI::Message &msg)
 {
-       delete timetable;
-       timetable = tt;
+       for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
+               (*i)->message(msg);
 }
 
 bool Train::set_route(const Route *r)
@@ -445,8 +469,7 @@ void Train::unplace()
 
 bool Train::free_block(Block &block)
 {
-       float margin = 10*layout.get_catalogue().get_scale();
-       if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3+margin)
+       if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
                return false;
 
        unsigned nsens = 0;
@@ -536,7 +559,15 @@ int Train::get_entry_to_block(Block &block) const
 
 float Train::get_reserved_distance() const
 {
-       return get_reserved_distance_until(0, false);
+       if(blocks.empty())
+               return 0;
+
+       float margin = 0;
+       TrackIter next = blocks.back().next().track_iter();
+       if(next && next->get_type().is_turnout())
+               margin = 15*layout.get_catalogue().get_scale();
+
+       return max(get_reserved_distance_until(0, false)-margin, 0.0f);
 }
 
 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
@@ -549,11 +580,10 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
 
        Driver &driver = layout.get_driver();
 
-       if(timetable)
-               timetable->tick(t);
+       for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
+               (*i)->tick(t, dt);
        controller->tick(dt);
        float speed = controller->get_speed();
-       unsigned speed_step = find_speed_step(speed);
 
        if(controller->get_reverse()!=reverse)
        {
@@ -565,17 +595,24 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
 
                reserve_more();
        }
-       if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
+
+       if(speed_quantizer)
        {
-               speed_changing = true;
-               driver.set_loco_speed(address, speed_step);
+               unsigned speed_step = speed_quantizer->find_speed_step(speed);
+               if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
+               {
+                       speed_changing = true;
+                       driver.set_loco_speed(address, speed_step);
 
-               pure_speed = false;
+                       pure_speed = false;
 
-               if(speed_step)
-                       set_status(format("Traveling %d kmh", get_travel_speed()));
-               else
-                       set_status("Waiting");
+                       if(speed_step)
+                               set_status(format("Traveling %d kmh", get_travel_speed()));
+                       else
+                               set_status("Waiting");
+               }
+
+               speed = speed_quantizer->get_speed(current_speed_step);
        }
 
        if(speed)
@@ -590,11 +627,7 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
                for(BlockList::const_iterator i=blocks.begin(); (!ok && i!=cur_blocks_end); ++i)
                        ok = (*i)->has_track(*track);
 
-               float d;
-               if(real_speed.size()>1)
-                       d = get_real_speed(current_speed_step)*(dt/Time::sec);
-               else
-                       d = speed*(dt/Time::sec);
+               float d = speed*(dt/Time::sec);
                if(ok)
                {
                        SetFlag setf(advancing);
@@ -639,9 +672,12 @@ void Train::save(list<DataFile::Statement> &st) const
                if(i!=vehicles.begin())
                        st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
 
-       for(unsigned i=0; i<real_speed.size(); ++i)
-               if(real_speed[i].weight)
-                       st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
+       if(speed_quantizer)
+       {
+               DataFile::Statement ss("quantized_speed");
+               speed_quantizer->save(ss.sub);
+               st.push_back(ss);
+       }
 
        if(!blocks.empty() && cur_blocks_end!=blocks.begin())
        {
@@ -664,12 +700,14 @@ void Train::save(list<DataFile::Statement> &st) const
                        st.push_back((DataFile::Statement("route"), i->route->get_name()));
        }
 
-       if(timetable)
-       {
-               DataFile::Statement ss("timetable");
-               timetable->save(ss.sub);
-               st.push_back(ss);
-       }
+       // XXX Need more generic way of saving AI state
+       for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
+               if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
+               {
+                       DataFile::Statement ss("timetable");
+                       timetable->save(ss.sub);
+                       st.push_back(ss);
+               }
 }
 
 void Train::control_changed(const Controller::Control &ctrl)
@@ -677,11 +715,13 @@ void Train::control_changed(const Controller::Control &ctrl)
        signal_control_changed.emit(ctrl.name, ctrl.value);
 }
 
-void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
+void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
 {
        if(addr==address)
        {
                current_speed_step = speed;
+               if(rev!=reverse)
+                       layout.get_driver().set_loco_reverse(address, reverse);
                speed_changing = false;
                pure_speed = false;
        }
@@ -689,10 +729,8 @@ void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
 
 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
 {
-       if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
+       if(addr==address)
        {
-               if(addr==address+1)
-                       func += 4;
                if(state)
                        functions |= 1<<func;
                else
@@ -732,11 +770,8 @@ void Train::sensor_event(unsigned addr, bool state)
 
                        if(pure_speed)
                        {
-                               if(current_speed_step>0)
-                               {
-                                       RealSpeed &rs = real_speed[current_speed_step];
-                                       rs.add(travel_dist/travel_time_secs, travel_time_secs);
-                               }
+                               if(speed_quantizer && current_speed_step>0)
+                                       speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
                                set_status(format("Traveling %d kmh", get_travel_speed()));
                        }
 
@@ -777,6 +812,8 @@ void Train::sensor_event(unsigned addr, bool state)
                        }
 
                        // Move blocks up to the next sensor to our current blocks
+                       for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
+                               signal_advanced.emit(**j);
                        cur_blocks_end = end;
 
                        // Try to get more blocks if we're moving
@@ -841,6 +878,7 @@ void Train::reserve_more()
        BlockIter start = blocks.back();
 
        pending_block = 0;
+       preceding_train = 0;
 
        // See how many sensor blocks and how much track we already have
        unsigned nsens = 0;
@@ -875,7 +913,10 @@ void Train::reserve_more()
                if(!block || block->get_endpoints().size()<2)
                {
                        if(!blocking_train)
+                       {
                                good_end = blocks.end();
+                               end_of_route = true;
+                       }
                        break;
                }
 
@@ -952,10 +993,15 @@ void Train::reserve_more()
                        bool entry_conflict = (block.entry()==other_exit);
                        bool exit_conflict = (exit==static_cast<unsigned>(other_entry));
                        if(!entry_conflict && !last->get_turnout_id())
+                       {
                                /* The other train is not coming to the blocks we're holding, so we
                                can keep them. */
                                good_end = blocks.end();
 
+                               if(static_cast<unsigned>(other_entry)==block.entry())
+                                       preceding_train = other_train;
+                       }
+
                        int other_prio = other_train->get_priority();
 
                        if(!entry_conflict && !exit_conflict && other_prio<priority)
@@ -974,7 +1020,7 @@ void Train::reserve_more()
                                contested_blocks.push_back(block);
                                continue;
                        }
-                       else if(divert_track && (entry_conflict || exit_conflict))
+                       else if(divert_track && (entry_conflict || exit_conflict || !other_train->is_active()))
                                // We are blocked, but there's a diversion possibility
                                try_divert = true;
 
@@ -1127,77 +1173,13 @@ float Train::get_reserved_distance_until(const Block *until_block, bool back) co
        return result;
 }
 
-float Train::get_real_speed(unsigned i) const
-{
-       if(i==0)
-               return 0;
-       if(real_speed[i].weight)
-               return real_speed[i].speed;
-
-       unsigned low;
-       unsigned high;
-       for(low=i; low>0; --low)
-               if(real_speed[low].weight)
-                       break;
-       for(high=i; high+1<real_speed.size(); ++high)
-               if(real_speed[high].weight)
-                       break;
-
-       if(real_speed[high].weight)
-       {
-               if(real_speed[low].weight)
-               {
-                       float f = float(i-low)/(high-low);
-                       return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
-               }
-               else
-                       return real_speed[high].speed*float(i)/high;
-       }
-       else if(real_speed[low].weight)
-               return real_speed[low].speed*float(i)/low;
-       else
-               return 0;
-}
-
-unsigned Train::find_speed_step(float real) const
-{
-       if(real_speed.size()<=1)
-               return 0;
-       if(real<=real_speed[1].speed*0.5)
-               return 0;
-
-       unsigned low = 0;
-       unsigned high = 0;
-       unsigned last = 0;
-       for(unsigned i=0; (!high && i<real_speed.size()); ++i)
-               if(real_speed[i].weight)
-               {
-                       last = i;
-                       if(real_speed[i].speed<real)
-                               low = i;
-                       else
-                               high = i;
-               }
-       if(!high)
-       {
-               unsigned limit = real_speed.size()/5;
-               if(!low)
-               {
-                       if(real)
-                               return limit;
-                       else
-                               return 0;
-               }
-               return min(min(static_cast<unsigned>(low*real/real_speed[low].speed), real_speed.size()-1), last+limit);
-       }
-
-       float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
-       return static_cast<unsigned>(low*(1-f)+high*f+0.5);
-}
-
 float Train::get_travel_speed() const
 {
-       float speed = get_real_speed(current_speed_step);
+       float speed = 0;
+       if(speed_quantizer)
+               speed = speed_quantizer->get_speed(current_speed_step);
+       else
+               speed = controller->get_speed();
        float scale = layout.get_catalogue().get_scale();
        return static_cast<int>(round(speed/scale*3.6/5))*5;
 }
@@ -1287,7 +1269,7 @@ bool Train::is_valid_diversion(const Route &diversion, const TrackIter &from)
 
                track1 = track1.next(path);
 
-               if(track1.looped())
+               if(!track1 || track1.looped())
                        return false;
        }
 
@@ -1305,6 +1287,8 @@ bool Train::is_valid_diversion(const Route &diversion, const TrackIter &from)
                bool ok = (track2!=from && diversion.has_track(*track2));
 
                track2 = track2.next(path);
+               if(!track2)
+                       return false;
 
                if(ok)
                        break;
@@ -1330,18 +1314,6 @@ Train::RouteRef::RouteRef(const Route *r, unsigned d):
 { }
 
 
-Train::RealSpeed::RealSpeed():
-       speed(0),
-       weight(0)
-{ }
-
-void Train::RealSpeed::add(float s, float w)
-{
-       speed = (speed*weight+s*w)/(weight+w);
-       weight = min(weight+w, 300.0f);
-}
-
-
 Train::Loader::Loader(Train &t):
        DataFile::BasicLoader<Train>(t),
        prev_block(0),
@@ -1351,7 +1323,7 @@ Train::Loader::Loader(Train &t):
        add("block_hint",  &Loader::block_hint);
        add("name",        &Loader::name);
        add("priority",    &Train::priority);
-       add("real_speed",  &Loader::real_speed);
+       add("quantized_speed",  &Loader::quantized_speed);
        add("route",       &Loader::route);
        add("timetable",   &Loader::timetable);
        add("vehicle",     &Loader::vehicle);
@@ -1417,12 +1389,10 @@ void Train::Loader::name(const string &n)
        obj.set_name(n);
 }
 
-void Train::Loader::real_speed(unsigned i, float speed, float weight)
+void Train::Loader::quantized_speed()
 {
-       if(i>=obj.real_speed.size())
-               return;
-       obj.real_speed[i].speed = speed;
-       obj.real_speed[i].weight = weight;
+       if(obj.speed_quantizer)
+               load_sub(*obj.speed_quantizer);
 }
 
 void Train::Loader::route(const string &n)
@@ -1432,11 +1402,8 @@ void Train::Loader::route(const string &n)
 
 void Train::Loader::timetable()
 {
-       if(obj.timetable)
-               throw InvalidState("A timetable has already been loaded");
-
-       obj.timetable = new Timetable(obj);
-       load_sub(*obj.timetable);
+       Timetable *ttbl = new Timetable(obj);
+       load_sub(*ttbl);
 }
 
 void Train::Loader::vehicle(ArticleNumber art_nr)