LCOV - code coverage report
Current view: top level - src/microsim - MSVehicle.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 96.3 % 3382 3256
Test Date: 2026-08-23 15:49:09 Functions: 95.2 % 227 216

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
       4              : // This program and the accompanying materials are made available under the
       5              : // terms of the Eclipse Public License 2.0 which is available at
       6              : // https://www.eclipse.org/legal/epl-2.0/
       7              : // This Source Code may also be made available under the following Secondary
       8              : // Licenses when the conditions for such availability set forth in the Eclipse
       9              : // Public License 2.0 are satisfied: GNU General Public License, version 2
      10              : // or later which is available at
      11              : // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
      12              : // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
      13              : /****************************************************************************/
      14              : /// @file    MSVehicle.cpp
      15              : /// @author  Christian Roessel
      16              : /// @author  Jakob Erdmann
      17              : /// @author  Bjoern Hendriks
      18              : /// @author  Daniel Krajzewicz
      19              : /// @author  Thimor Bohn
      20              : /// @author  Friedemann Wesner
      21              : /// @author  Laura Bieker
      22              : /// @author  Clemens Honomichl
      23              : /// @author  Michael Behrisch
      24              : /// @author  Axel Wegener
      25              : /// @author  Christoph Sommer
      26              : /// @author  Leonhard Luecken
      27              : /// @author  Lara Codeca
      28              : /// @author  Mirko Barthauer
      29              : /// @date    Mon, 05 Mar 2001
      30              : ///
      31              : // Representation of a vehicle in the micro simulation
      32              : /****************************************************************************/
      33              : #include <config.h>
      34              : 
      35              : #include <iostream>
      36              : #include <cassert>
      37              : #include <cmath>
      38              : #include <cstdlib>
      39              : #include <algorithm>
      40              : #include <map>
      41              : #include <memory>
      42              : #include <utils/common/ToString.h>
      43              : #include <utils/common/FileHelpers.h>
      44              : #include <utils/router/DijkstraRouter.h>
      45              : #include <utils/common/MsgHandler.h>
      46              : #include <utils/common/RandHelper.h>
      47              : #include <utils/common/StringUtils.h>
      48              : #include <utils/common/StdDefs.h>
      49              : #include <utils/geom/GeomHelper.h>
      50              : #include <utils/iodevices/OutputDevice.h>
      51              : #include <utils/xml/SUMOSAXAttributes.h>
      52              : #include <utils/vehicle/SUMOVehicleParserHelper.h>
      53              : #include <microsim/lcmodels/MSAbstractLaneChangeModel.h>
      54              : #include <microsim/transportables/MSPerson.h>
      55              : #include <microsim/transportables/MSPModel.h>
      56              : #include <microsim/devices/MSDevice_Transportable.h>
      57              : #include <microsim/devices/MSDevice_DriverState.h>
      58              : #include <microsim/devices/MSDevice_Friction.h>
      59              : #include <microsim/devices/MSDevice_Taxi.h>
      60              : #include <microsim/devices/MSDevice_Vehroutes.h>
      61              : #include <microsim/devices/MSDevice_ElecHybrid.h>
      62              : #include <microsim/devices/MSDevice_GLOSA.h>
      63              : #include <microsim/output/MSStopOut.h>
      64              : #include <microsim/trigger/MSChargingStation.h>
      65              : #include <microsim/trigger/MSOverheadWire.h>
      66              : #include <microsim/traffic_lights/MSTrafficLightLogic.h>
      67              : #include <microsim/traffic_lights/MSRailSignalControl.h>
      68              : #include <microsim/lcmodels/MSAbstractLaneChangeModel.h>
      69              : #include <microsim/transportables/MSTransportableControl.h>
      70              : #include <microsim/devices/MSDevice_Transportable.h>
      71              : #include "MSEdgeControl.h"
      72              : #include "MSVehicleControl.h"
      73              : #include "MSInsertionControl.h"
      74              : #include "MSVehicleTransfer.h"
      75              : #include "MSGlobals.h"
      76              : #include "MSJunctionLogic.h"
      77              : #include "MSStop.h"
      78              : #include "MSStoppingPlace.h"
      79              : #include "MSParkingArea.h"
      80              : #include "MSMoveReminder.h"
      81              : #include "MSLane.h"
      82              : #include "MSJunction.h"
      83              : #include "MSEdge.h"
      84              : #include "MSVehicleType.h"
      85              : #include "MSNet.h"
      86              : #include "MSRoute.h"
      87              : #include "MSLeaderInfo.h"
      88              : #include "MSDriverState.h"
      89              : #include "MSVehicle.h"
      90              : 
      91              : 
      92              : //#define DEBUG_PLAN_MOVE
      93              : //#define DEBUG_PLAN_MOVE_LEADERINFO
      94              : //#define DEBUG_CHECKREWINDLINKLANES
      95              : //#define DEBUG_EXEC_MOVE
      96              : //#define DEBUG_FURTHER
      97              : //#define DEBUG_SETFURTHER
      98              : //#define DEBUG_TARGET_LANE
      99              : //#define DEBUG_STOPS
     100              : //#define DEBUG_BESTLANES
     101              : //#define DEBUG_IGNORE_RED
     102              : //#define DEBUG_ACTIONSTEPS
     103              : //#define DEBUG_NEXT_TURN
     104              : //#define DEBUG_TRACI
     105              : //#define DEBUG_REVERSE_BIDI
     106              : //#define DEBUG_EXTRAPOLATE_DEPARTPOS
     107              : //#define DEBUG_REMOTECONTROL
     108              : //#define DEBUG_MOVEREMINDERS
     109              : //#define DEBUG_COND (getID() == "ego")
     110              : //#define DEBUG_COND (true)
     111              : #define DEBUG_COND (isSelected())
     112              : //#define DEBUG_COND2(obj) (obj->getID() == "ego")
     113              : #define DEBUG_COND2(obj) (obj->isSelected())
     114              : 
     115              : //#define PARALLEL_STOPWATCH
     116              : 
     117              : 
     118              : #define STOPPING_PLACE_OFFSET 0.5
     119              : 
     120              : #define CRLL_LOOK_AHEAD 5
     121              : 
     122              : #define JUNCTION_BLOCKAGE_TIME 5 // s
     123              : 
     124              : // @todo Calibrate with real-world values / make configurable
     125              : #define DIST_TO_STOPLINE_EXPECT_PRIORITY 1.0
     126              : 
     127              : #define NUMERICAL_EPS_SPEED (0.1 * NUMERICAL_EPS * TS)
     128              : 
     129              : // ===========================================================================
     130              : // static value definitions
     131              : // ===========================================================================
     132              : std::vector<MSLane*> MSVehicle::myEmptyLaneVector;
     133              : 
     134              : 
     135              : // ===========================================================================
     136              : // method definitions
     137              : // ===========================================================================
     138              : /* -------------------------------------------------------------------------
     139              :  * methods of MSVehicle::State
     140              :  * ----------------------------------------------------------------------- */
     141            0 : MSVehicle::State::State(const State& state) {
     142            0 :     myPos = state.myPos;
     143            0 :     mySpeed = state.mySpeed;
     144            0 :     myPosLat = state.myPosLat;
     145            0 :     myBackPos = state.myBackPos;
     146            0 :     myPreviousSpeed = state.myPreviousSpeed;
     147            0 :     myLastCoveredDist = state.myLastCoveredDist;
     148            0 : }
     149              : 
     150              : 
     151              : MSVehicle::State&
     152      3554479 : MSVehicle::State::operator=(const State& state) {
     153      3554479 :     myPos   = state.myPos;
     154      3554479 :     mySpeed = state.mySpeed;
     155      3554479 :     myPosLat   = state.myPosLat;
     156      3554479 :     myBackPos = state.myBackPos;
     157      3554479 :     myPreviousSpeed = state.myPreviousSpeed;
     158      3554479 :     myLastCoveredDist = state.myLastCoveredDist;
     159      3554479 :     return *this;
     160              : }
     161              : 
     162              : 
     163              : bool
     164            0 : MSVehicle::State::operator!=(const State& state) {
     165            0 :     return (myPos    != state.myPos ||
     166            0 :             mySpeed  != state.mySpeed ||
     167            0 :             myPosLat != state.myPosLat ||
     168            0 :             myLastCoveredDist != state.myLastCoveredDist ||
     169            0 :             myPreviousSpeed != state.myPreviousSpeed ||
     170            0 :             myBackPos != state.myBackPos);
     171              : }
     172              : 
     173              : 
     174      8088562 : MSVehicle::State::State(double pos, double speed, double posLat, double backPos, double previousSpeed) :
     175      8088562 :     myPos(pos), mySpeed(speed), myPosLat(posLat), myBackPos(backPos), myPreviousSpeed(previousSpeed), myLastCoveredDist(SPEED2DIST(speed)) {}
     176              : 
     177              : 
     178              : 
     179              : /* -------------------------------------------------------------------------
     180              :  * methods of MSVehicle::WaitingTimeCollector
     181              :  * ----------------------------------------------------------------------- */
     182      4534083 : MSVehicle::WaitingTimeCollector::WaitingTimeCollector(SUMOTime memory) : myMemorySize(memory) {}
     183              : 
     184              : 
     185              : SUMOTime
     186      1428911 : MSVehicle::WaitingTimeCollector::cumulatedWaitingTime(SUMOTime memorySpan) const {
     187              :     assert(memorySpan <= myMemorySize);
     188      1428911 :     if (memorySpan == -1) {
     189            0 :         memorySpan = myMemorySize;
     190              :     }
     191              :     SUMOTime totalWaitingTime = 0;
     192      5944953 :     for (const auto& interval : myWaitingIntervals) {
     193      4516042 :         if (interval.second >= memorySpan) {
     194       655960 :             if (interval.first >= memorySpan) {
     195              :                 break;
     196              :             } else {
     197       655960 :                 totalWaitingTime += memorySpan - interval.first;
     198              :             }
     199              :         } else {
     200      3860082 :             totalWaitingTime += interval.second - interval.first;
     201              :         }
     202              :     }
     203      1428911 :     return totalWaitingTime;
     204              : }
     205              : 
     206              : 
     207              : void
     208    705038181 : MSVehicle::WaitingTimeCollector::passTime(SUMOTime dt, bool waiting) {
     209              :     auto i = myWaitingIntervals.begin();
     210              :     const auto end = myWaitingIntervals.end();
     211    705038181 :     const bool startNewInterval = i == end || (i->first != 0);
     212   1164923511 :     while (i != end) {
     213    462286267 :         i->first += dt;
     214    462286267 :         if (i->first >= myMemorySize) {
     215              :             break;
     216              :         }
     217    459885330 :         i->second += dt;
     218              :         i++;
     219              :     }
     220              : 
     221              :     // remove intervals beyond memorySize
     222              :     auto d = std::distance(i, end);
     223    707439118 :     while (d > 0) {
     224      2400937 :         myWaitingIntervals.pop_back();
     225      2400937 :         d--;
     226              :     }
     227              : 
     228    705038181 :     if (!waiting) {
     229              :         return;
     230     95442158 :     } else if (!startNewInterval) {
     231     91654101 :         myWaitingIntervals.begin()->first = 0;
     232              :     } else {
     233      7576114 :         myWaitingIntervals.push_front(std::make_pair(0, dt));
     234              :     }
     235              :     return;
     236              : }
     237              : 
     238              : 
     239              : const std::string
     240         2625 : MSVehicle::WaitingTimeCollector::getState() const {
     241         2625 :     std::ostringstream state;
     242         2625 :     state << myMemorySize << " " << myWaitingIntervals.size();
     243         3545 :     for (const auto& interval : myWaitingIntervals) {
     244         1840 :         state << " " << interval.first << " " << interval.second;
     245              :     }
     246         2625 :     return state.str();
     247         2625 : }
     248              : 
     249              : 
     250              : void
     251         3483 : MSVehicle::WaitingTimeCollector::setState(const std::string& state) {
     252         3483 :     std::istringstream is(state);
     253              :     int numIntervals;
     254              :     SUMOTime begin, end;
     255         3483 :     is >> myMemorySize >> numIntervals;
     256         5185 :     while (numIntervals-- > 0) {
     257              :         is >> begin >> end;
     258         1702 :         myWaitingIntervals.emplace_back(begin, end);
     259              :     }
     260         3483 : }
     261              : 
     262              : 
     263              : /* -------------------------------------------------------------------------
     264              :  * methods of MSVehicle::Influencer::GapControlState
     265              :  * ----------------------------------------------------------------------- */
     266              : void
     267           30 : MSVehicle::Influencer::GapControlVehStateListener::vehicleStateChanged(const SUMOVehicle* const vehicle, MSNet::VehicleState to, const std::string& /*info*/) {
     268              : //    std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << ", to=" << to << std::endl;
     269           30 :     switch (to) {
     270            4 :         case MSNet::VehicleState::STARTING_TELEPORT:
     271              :         case MSNet::VehicleState::ARRIVED:
     272              :         case MSNet::VehicleState::STARTING_PARKING: {
     273              :             // Vehicle left road
     274              : //         Look up reference vehicle in refVehMap and in case deactivate corresponding gap control
     275            4 :             const MSVehicle* msVeh = static_cast<const MSVehicle*>(vehicle);
     276              : //        std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << " left the road." << std::endl;
     277            4 :             if (GapControlState::refVehMap.find(msVeh) != end(GapControlState::refVehMap)) {
     278              : //            std::cout << "GapControlVehStateListener::deactivating ref vehicle=" << vehicle->getID() << std::endl;
     279            4 :                 GapControlState::refVehMap[msVeh]->deactivate();
     280              :             }
     281              :         }
     282            4 :         break;
     283           30 :         default:
     284              :         {};
     285              :             // do nothing, vehicle still on road
     286              :     }
     287           30 : }
     288              : 
     289              : std::map<const MSVehicle*, MSVehicle::Influencer::GapControlState*>
     290              : MSVehicle::Influencer::GapControlState::refVehMap;
     291              : 
     292              : MSVehicle::Influencer::GapControlVehStateListener* MSVehicle::Influencer::GapControlState::myVehStateListener(nullptr);
     293              : 
     294           58 : MSVehicle::Influencer::GapControlState::GapControlState() :
     295           58 :     tauOriginal(-1), tauCurrent(-1), tauTarget(-1), addGapCurrent(-1), addGapTarget(-1),
     296           58 :     remainingDuration(-1), changeRate(-1), maxDecel(-1), referenceVeh(nullptr), active(false), gapAttained(false), prevLeader(nullptr),
     297           58 :     lastUpdate(-1), timeHeadwayIncrement(0.0), spaceHeadwayIncrement(0.0) {}
     298              : 
     299              : 
     300           58 : MSVehicle::Influencer::GapControlState::~GapControlState() {
     301           58 :     deactivate();
     302           58 : }
     303              : 
     304              : void
     305           58 : MSVehicle::Influencer::GapControlState::init() {
     306           58 :     if (MSNet::hasInstance()) {
     307           58 :         if (myVehStateListener == nullptr) {
     308              :             //std::cout << "GapControlState::init()" << std::endl;
     309           58 :             myVehStateListener = new GapControlVehStateListener();
     310           58 :             MSNet::getInstance()->addVehicleStateListener(myVehStateListener);
     311              :         }
     312              :     } else {
     313            0 :         WRITE_ERROR("MSVehicle::Influencer::GapControlState::init(): No MSNet instance found!")
     314              :     }
     315           58 : }
     316              : 
     317              : void
     318        35339 : MSVehicle::Influencer::GapControlState::cleanup() {
     319        35339 :     if (myVehStateListener != nullptr) {
     320           58 :         MSNet::getInstance()->removeVehicleStateListener(myVehStateListener);
     321           58 :         delete myVehStateListener;
     322           58 :         myVehStateListener = nullptr;
     323              :     }
     324        35339 : }
     325              : 
     326              : void
     327           58 : MSVehicle::Influencer::GapControlState::activate(double tauOrig, double tauNew, double additionalGap, double dur, double rate, double decel, const MSVehicle* refVeh) {
     328           58 :     if (MSGlobals::gUseMesoSim) {
     329            0 :         WRITE_ERROR(TL("No gap control available for meso."))
     330              :     } else {
     331              :         // always deactivate control before activating (triggers clean-up of refVehMap)
     332              : //        std::cout << "activate gap control with refVeh=" << (refVeh==nullptr? "NULL" : refVeh->getID()) << std::endl;
     333           58 :         tauOriginal = tauOrig;
     334           58 :         tauCurrent = tauOrig;
     335           58 :         tauTarget = tauNew;
     336           58 :         addGapCurrent = 0.0;
     337           58 :         addGapTarget = additionalGap;
     338           58 :         remainingDuration = dur;
     339           58 :         changeRate = rate;
     340           58 :         maxDecel = decel;
     341           58 :         referenceVeh = refVeh;
     342           58 :         active = true;
     343           58 :         gapAttained = false;
     344           58 :         prevLeader = nullptr;
     345           58 :         lastUpdate = SIMSTEP - DELTA_T;
     346           58 :         timeHeadwayIncrement = changeRate * TS * (tauTarget - tauOriginal);
     347           58 :         spaceHeadwayIncrement = changeRate * TS * addGapTarget;
     348              : 
     349           58 :         if (referenceVeh != nullptr) {
     350              :             // Add refVeh to refVehMap
     351           12 :             GapControlState::refVehMap[referenceVeh] = this;
     352              :         }
     353              :     }
     354           58 : }
     355              : 
     356              : void
     357          116 : MSVehicle::Influencer::GapControlState::deactivate() {
     358          116 :     active = false;
     359          116 :     if (referenceVeh != nullptr) {
     360              :         // Remove corresponding refVehMapEntry if appropriate
     361           12 :         GapControlState::refVehMap.erase(referenceVeh);
     362           12 :         referenceVeh = nullptr;
     363              :     }
     364          116 : }
     365              : 
     366              : 
     367              : /* -------------------------------------------------------------------------
     368              :  * methods of MSVehicle::Influencer
     369              :  * ----------------------------------------------------------------------- */
     370         3487 : MSVehicle::Influencer::Influencer() :
     371              :     myGapControlState(nullptr),
     372         3487 :     myOriginalSpeed(-1),
     373         3487 :     myLatDist(0),
     374         3487 :     mySpeedAdaptationStarted(true),
     375         3487 :     myConsiderSafeVelocity(true),
     376         3487 :     myConsiderSpeedLimit(true),
     377         3487 :     myConsiderMaxAcceleration(true),
     378         3487 :     myConsiderMaxDeceleration(true),
     379         3487 :     myRespectJunctionPriority(true),
     380         3487 :     myEmergencyBrakeRedLight(true),
     381         3487 :     myRespectJunctionLeaderPriority(true),
     382         3487 :     myLastRemoteAccess(-TIME2STEPS(20)),
     383         3487 :     myStrategicLC(LC_NOCONFLICT),
     384         3487 :     myCooperativeLC(LC_NOCONFLICT),
     385         3487 :     mySpeedGainLC(LC_NOCONFLICT),
     386         3487 :     myRightDriveLC(LC_NOCONFLICT),
     387         3487 :     mySublaneLC(LC_NOCONFLICT),
     388         3487 :     myTraciLaneChangePriority(LCP_URGENT),
     389         3487 :     myTraCISignals(-1)
     390         3487 : {}
     391              : 
     392              : 
     393        10461 : MSVehicle::Influencer::~Influencer() {}
     394              : 
     395              : void
     396           58 : MSVehicle::Influencer::init() {
     397           58 :     GapControlState::init();
     398           58 : }
     399              : 
     400              : void
     401        35339 : MSVehicle::Influencer::cleanup() {
     402        35339 :     GapControlState::cleanup();
     403        35339 : }
     404              : 
     405              : void
     406        43462 : MSVehicle::Influencer::setSpeedTimeLine(const std::vector<std::pair<SUMOTime, double> >& speedTimeLine) {
     407        43462 :     mySpeedAdaptationStarted = true;
     408        43462 :     mySpeedTimeLine = speedTimeLine;
     409        43462 : }
     410              : 
     411              : void
     412           58 : MSVehicle::Influencer::activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle* refVeh) {
     413           58 :     if (myGapControlState == nullptr) {
     414           58 :         myGapControlState = std::make_shared<GapControlState>();
     415           58 :         init(); // only does things on first call
     416              :     }
     417           58 :     myGapControlState->activate(originalTau, newTimeHeadway, newSpaceHeadway, duration, changeRate, maxDecel, refVeh);
     418           58 : }
     419              : 
     420              : void
     421           10 : MSVehicle::Influencer::deactivateGapController() {
     422           10 :     if (myGapControlState != nullptr && myGapControlState->active) {
     423           10 :         myGapControlState->deactivate();
     424              :     }
     425           10 : }
     426              : 
     427              : void
     428         7341 : MSVehicle::Influencer::setLaneTimeLine(const std::vector<std::pair<SUMOTime, int> >& laneTimeLine) {
     429         7341 :     myLaneTimeLine = laneTimeLine;
     430         7341 : }
     431              : 
     432              : 
     433              : void
     434         9042 : MSVehicle::Influencer::adaptLaneTimeLine(int indexShift) {
     435        19192 :     for (auto& item : myLaneTimeLine) {
     436        10150 :         item.second += indexShift;
     437              :     }
     438         9042 : }
     439              : 
     440              : 
     441              : void
     442         1268 : MSVehicle::Influencer::setSublaneChange(double latDist) {
     443         1268 :     myLatDist = latDist;
     444         1268 : }
     445              : 
     446              : int
     447           68 : MSVehicle::Influencer::getSpeedMode() const {
     448           68 :     return (1 * myConsiderSafeVelocity +
     449           68 :             2 * myConsiderMaxAcceleration +
     450           68 :             4 * myConsiderMaxDeceleration +
     451           68 :             8 * myRespectJunctionPriority +
     452           68 :             16 * myEmergencyBrakeRedLight +
     453           68 :             32 * !myRespectJunctionLeaderPriority + // inverted!
     454           68 :             64 * !myConsiderSpeedLimit // inverted!
     455           68 :            );
     456              : }
     457              : 
     458              : 
     459              : int
     460         1469 : MSVehicle::Influencer::getLaneChangeMode() const {
     461         1469 :     return (1 * myStrategicLC +
     462         1469 :             4 * myCooperativeLC +
     463         1469 :             16 * mySpeedGainLC +
     464         1469 :             64 * myRightDriveLC +
     465         1469 :             256 * myTraciLaneChangePriority +
     466         1469 :             1024 * mySublaneLC);
     467              : }
     468              : 
     469              : SUMOTime
     470           60 : MSVehicle::Influencer::getLaneTimeLineDuration() {
     471              :     SUMOTime duration = -1;
     472          180 :     for (std::vector<std::pair<SUMOTime, int>>::iterator i = myLaneTimeLine.begin(); i != myLaneTimeLine.end(); ++i) {
     473          120 :         if (duration < 0) {
     474           60 :             duration = i->first;
     475              :         } else {
     476           60 :             duration -=  i->first;
     477              :         }
     478              :     }
     479           60 :     return -duration;
     480              : }
     481              : 
     482              : SUMOTime
     483            0 : MSVehicle::Influencer::getLaneTimeLineEnd() {
     484            0 :     if (!myLaneTimeLine.empty()) {
     485            0 :         return myLaneTimeLine.back().first;
     486              :     } else {
     487              :         return -1;
     488              :     }
     489              : }
     490              : 
     491              : 
     492              : double
     493       989018 : MSVehicle::Influencer::influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax) {
     494              :     // remove leading commands which are no longer valid
     495       990376 :     while (mySpeedTimeLine.size() == 1 || (mySpeedTimeLine.size() > 1 && currentTime > mySpeedTimeLine[1].first)) {
     496              :         mySpeedTimeLine.erase(mySpeedTimeLine.begin());
     497              :     }
     498              : 
     499       989018 :     if (!(mySpeedTimeLine.size() < 2 || currentTime < mySpeedTimeLine[0].first)) {
     500              :         // Speed advice is active -> compute new speed according to speedTimeLine
     501        53670 :         if (!mySpeedAdaptationStarted) {
     502            0 :             mySpeedTimeLine[0].second = speed;
     503            0 :             mySpeedAdaptationStarted = true;
     504              :         }
     505        53670 :         currentTime += DELTA_T; // start slowing down in the step in which this command was issued (the input value of currentTime still reflects the previous step)
     506       107002 :         const double td = MIN2(1.0, STEPS2TIME(currentTime - mySpeedTimeLine[0].first) / MAX2(TS, STEPS2TIME(mySpeedTimeLine[1].first - mySpeedTimeLine[0].first)));
     507              : 
     508        53670 :         speed = mySpeedTimeLine[0].second - (mySpeedTimeLine[0].second - mySpeedTimeLine[1].second) * td;
     509        53670 :         if (myConsiderSafeVelocity) {
     510              :             speed = MIN2(speed, vSafe);
     511              :         }
     512        53670 :         if (myConsiderMaxAcceleration) {
     513              :             speed = MIN2(speed, vMax);
     514              :         }
     515        53670 :         if (myConsiderMaxDeceleration) {
     516              :             speed = MAX2(speed, vMin);
     517              :         }
     518              :     }
     519       989018 :     return speed;
     520              : }
     521              : 
     522              : double
     523       491830 : MSVehicle::Influencer::gapControlSpeed(SUMOTime currentTime, const SUMOVehicle* veh, double speed, double vSafe, double vMin, double vMax) {
     524              : #ifdef DEBUG_TRACI
     525              :     if DEBUG_COND2(veh) {
     526              :         std::cout << currentTime << " Influencer::gapControlSpeed(): speed=" << speed
     527              :                   << ", vSafe=" << vSafe
     528              :                   << ", vMin=" << vMin
     529              :                   << ", vMax=" << vMax
     530              :                   << std::endl;
     531              :     }
     532              : #endif
     533              :     double gapControlSpeed = speed;
     534       491830 :     if (myGapControlState != nullptr && myGapControlState->active) {
     535              :         // Determine leader and the speed that would be chosen by the gap controller
     536         7772 :         const double currentSpeed = veh->getSpeed();
     537         7772 :         const MSVehicle* msVeh = dynamic_cast<const MSVehicle*>(veh);
     538              :         assert(msVeh != nullptr);
     539         7772 :         const double desiredTargetTimeSpacing = myGapControlState->tauTarget * currentSpeed;
     540              :         std::pair<const MSVehicle*, double> leaderInfo;
     541         7772 :         if (myGapControlState->referenceVeh == nullptr) {
     542              :             // No reference vehicle specified -> use current leader as reference
     543         7340 :             const double brakeGap = msVeh->getBrakeGap(true);
     544        14680 :             leaderInfo = msVeh->getLeader(MAX2(desiredTargetTimeSpacing, myGapControlState->addGapCurrent)  + MAX2(brakeGap, 20.0));
     545              : #ifdef DEBUG_TRACI
     546              :             if DEBUG_COND2(veh) {
     547              :                 std::cout <<  "  ---   no refVeh; myGapControlState->addGapCurrent: " << myGapControlState->addGapCurrent << ", brakeGap: " << brakeGap << " in simstep: " << SIMSTEP << std::endl;
     548              :             }
     549              : #endif
     550              :         } else {
     551              :             // Control gap wrt reference vehicle
     552              :             const MSVehicle* leader = myGapControlState->referenceVeh;
     553          432 :             double dist = msVeh->getDistanceToPosition(leader->getPositionOnLane(), leader->getLane()) - leader->getLength();
     554          432 :             if (dist > 100000) {
     555              :                 // Reference vehicle was not found downstream the ego's route
     556              :                 // Maybe, it is behind the ego vehicle
     557           40 :                 dist = - leader->getDistanceToPosition(msVeh->getPositionOnLane(), msVeh->getLane()) - leader->getLength();
     558              : #ifdef DEBUG_TRACI
     559              :                 if DEBUG_COND2(veh) {
     560              :                     if (dist < -100000) {
     561              :                         // also the ego vehicle is not ahead of the reference vehicle -> no CF-relation
     562              :                         std::cout <<  " Ego and reference vehicle are not in CF relation..." << std::endl;
     563              :                     } else {
     564              :                         std::cout <<  " Reference vehicle is behind ego..." << std::endl;
     565              :                     }
     566              :                 }
     567              : #endif
     568              :             }
     569          432 :             leaderInfo = std::make_pair(leader, dist - msVeh->getVehicleType().getMinGap());
     570              :         }
     571         7772 :         const double fakeDist = MAX2(0.0, leaderInfo.second - myGapControlState->addGapCurrent);
     572              : #ifdef DEBUG_TRACI
     573              :         if DEBUG_COND2(veh) {
     574              :             const double desiredCurrentSpacing = myGapControlState->tauCurrent * currentSpeed;
     575              :             std::cout <<  " Gap control active:"
     576              :                       << " currentSpeed=" << currentSpeed
     577              :                       << ", desiredTargetTimeSpacing=" << desiredTargetTimeSpacing
     578              :                       << ", desiredCurrentSpacing=" << desiredCurrentSpacing
     579              :                       << ", leader=" << (leaderInfo.first == nullptr ? "NULL" : leaderInfo.first->getID())
     580              :                       << ", dist=" << leaderInfo.second
     581              :                       << ", fakeDist=" << fakeDist
     582              :                       << ",\n tauOriginal=" << myGapControlState->tauOriginal
     583              :                       << ", tauTarget=" << myGapControlState->tauTarget
     584              :                       << ", tauCurrent=" << myGapControlState->tauCurrent
     585              :                       << std::endl;
     586              :         }
     587              : #endif
     588         7772 :         if (leaderInfo.first != nullptr) {
     589              :             if (myGapControlState->prevLeader != nullptr && myGapControlState->prevLeader != leaderInfo.first) {
     590              :                 // TODO: The leader changed. What to do?
     591              :             }
     592              :             // Remember leader
     593         7772 :             myGapControlState->prevLeader = leaderInfo.first;
     594              : 
     595              :             // Calculate desired following speed assuming the alternative headway time
     596         7772 :             MSCFModel* cfm = (MSCFModel*) & (msVeh->getVehicleType().getCarFollowModel());
     597         7772 :             const double origTau = cfm->getHeadwayTime();
     598         7772 :             cfm->setHeadwayTime(myGapControlState->tauCurrent);
     599         7772 :             gapControlSpeed = MIN2(gapControlSpeed,
     600         7772 :                                    cfm->followSpeed(msVeh, currentSpeed, fakeDist, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first));
     601         7772 :             cfm->setHeadwayTime(origTau);
     602              : #ifdef DEBUG_TRACI
     603              :             if DEBUG_COND2(veh) {
     604              :                 std::cout << " -> gapControlSpeed=" << gapControlSpeed;
     605              :                 if (myGapControlState->maxDecel > 0) {
     606              :                     std::cout << ", with maxDecel bound: " << MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
     607              :                 }
     608              :                 std::cout << std::endl;
     609              :             }
     610              : #endif
     611         7772 :             if (myGapControlState->maxDecel > 0) {
     612         2568 :                 gapControlSpeed = MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
     613              :             }
     614              :         }
     615              : 
     616              :         // Update gap controller
     617              :         // Check (1) if the gap control has established the desired gap,
     618              :         // and (2) if it has maintained active for the given duration afterwards
     619         7772 :         if (myGapControlState->lastUpdate < currentTime) {
     620              : #ifdef DEBUG_TRACI
     621              :             if DEBUG_COND2(veh) {
     622              :                 std::cout << " Updating GapControlState." << std::endl;
     623              :             }
     624              : #endif
     625         7772 :             if (myGapControlState->tauCurrent == myGapControlState->tauTarget && myGapControlState->addGapCurrent == myGapControlState->addGapTarget) {
     626         2990 :                 if (!myGapControlState->gapAttained) {
     627              :                     // Check if the desired gap was established (add the POSITION_EPS to avoid infinite asymptotic behavior without having established the gap)
     628         4176 :                     myGapControlState->gapAttained = leaderInfo.first == nullptr ||  leaderInfo.second > MAX2(desiredTargetTimeSpacing, myGapControlState->addGapTarget) - POSITION_EPS;
     629              : #ifdef DEBUG_TRACI
     630              :                     if DEBUG_COND2(veh) {
     631              :                         if (myGapControlState->gapAttained) {
     632              :                             std::cout << "   Target gap was established." << std::endl;
     633              :                         }
     634              :                     }
     635              : #endif
     636              :                 } else {
     637              :                     // Count down remaining time if desired gap was established
     638          924 :                     myGapControlState->remainingDuration -= TS;
     639              : #ifdef DEBUG_TRACI
     640              :                     if DEBUG_COND2(veh) {
     641              :                         std::cout << "   Gap control remaining duration: " << myGapControlState->remainingDuration << std::endl;
     642              :                     }
     643              : #endif
     644          924 :                     if (myGapControlState->remainingDuration <= 0) {
     645              : #ifdef DEBUG_TRACI
     646              :                         if DEBUG_COND2(veh) {
     647              :                             std::cout << "   Gap control duration expired, deactivating control." << std::endl;
     648              :                         }
     649              : #endif
     650              :                         // switch off gap control
     651           44 :                         myGapControlState->deactivate();
     652              :                     }
     653              :                 }
     654              :             } else {
     655              :                 // Adjust current headway values
     656         4782 :                 myGapControlState->tauCurrent = MIN2(myGapControlState->tauCurrent + myGapControlState->timeHeadwayIncrement, myGapControlState->tauTarget);
     657         5160 :                 myGapControlState->addGapCurrent = MIN2(myGapControlState->addGapCurrent + myGapControlState->spaceHeadwayIncrement, myGapControlState->addGapTarget);
     658              :             }
     659              :         }
     660         7772 :         if (myConsiderSafeVelocity) {
     661              :             gapControlSpeed = MIN2(gapControlSpeed, vSafe);
     662              :         }
     663         7772 :         if (myConsiderMaxAcceleration) {
     664              :             gapControlSpeed = MIN2(gapControlSpeed, vMax);
     665              :         }
     666         7772 :         if (myConsiderMaxDeceleration) {
     667              :             gapControlSpeed = MAX2(gapControlSpeed, vMin);
     668              :         }
     669              :         return MIN2(speed, gapControlSpeed);
     670              :     } else {
     671              :         return speed;
     672              :     }
     673              : }
     674              : 
     675              : double
     676         7135 : MSVehicle::Influencer::getOriginalSpeed() const {
     677         7135 :     return myOriginalSpeed;
     678              : }
     679              : 
     680              : void
     681       497188 : MSVehicle::Influencer::setOriginalSpeed(double speed) {
     682       497188 :     myOriginalSpeed = speed;
     683       497188 : }
     684              : 
     685              : 
     686              : int
     687      2829460 : MSVehicle::Influencer::influenceChangeDecision(const SUMOTime currentTime, const MSEdge& currentEdge, const int currentLaneIndex, int state) {
     688              :     // remove leading commands which are no longer valid
     689      2829712 :     while (myLaneTimeLine.size() == 1 || (myLaneTimeLine.size() > 1 && currentTime > myLaneTimeLine[1].first)) {
     690              :         myLaneTimeLine.erase(myLaneTimeLine.begin());
     691              :     }
     692              :     ChangeRequest changeRequest = REQUEST_NONE;
     693              :     // do nothing if the time line does not apply for the current time
     694      2829460 :     if (myLaneTimeLine.size() >= 2 && currentTime >= myLaneTimeLine[0].first) {
     695       173425 :         const int destinationLaneIndex = myLaneTimeLine[1].second;
     696       173425 :         if (destinationLaneIndex < (int)currentEdge.getLanes().size()) {
     697       173133 :             if (currentLaneIndex > destinationLaneIndex) {
     698              :                 changeRequest = REQUEST_RIGHT;
     699       172258 :             } else if (currentLaneIndex < destinationLaneIndex) {
     700              :                 changeRequest = REQUEST_LEFT;
     701              :             } else {
     702              :                 changeRequest = REQUEST_HOLD;
     703              :             }
     704          292 :         } else if (currentEdge.getLanes().back()->getOpposite() != nullptr) { // change to opposite direction driving
     705              :             changeRequest = REQUEST_LEFT;
     706          292 :             state = state | LCA_TRACI;
     707              :         }
     708              :     }
     709              :     // check whether the current reason shall be canceled / overridden
     710      2829460 :     if ((state & LCA_WANTS_LANECHANGE_OR_STAY) != 0) {
     711              :         // flags for the current reason
     712              :         LaneChangeMode mode = LC_NEVER;
     713      1603041 :         if ((state & LCA_TRACI) != 0 && myLatDist != 0) {
     714              :             // security checks
     715         2380 :             if ((myTraciLaneChangePriority == LCP_ALWAYS)
     716          552 :                     || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     717         2252 :                 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     718              :             }
     719              :             // continue sublane change manoeuvre
     720         2380 :             return state;
     721      1600661 :         } else if ((state & LCA_STRATEGIC) != 0) {
     722       486038 :             mode = myStrategicLC;
     723      1114623 :         } else if ((state & LCA_COOPERATIVE) != 0) {
     724           78 :             mode = myCooperativeLC;
     725      1114545 :         } else if ((state & LCA_SPEEDGAIN) != 0) {
     726        42175 :             mode = mySpeedGainLC;
     727      1072370 :         } else if ((state & LCA_KEEPRIGHT) != 0) {
     728         5994 :             mode = myRightDriveLC;
     729      1066376 :         } else if ((state & LCA_SUBLANE) != 0) {
     730      1066374 :             mode = mySublaneLC;
     731            2 :         } else if ((state & LCA_TRACI) != 0) {
     732              :             mode = LC_NEVER;
     733              :         } else {
     734            0 :             WRITE_WARNINGF(TL("Lane change model did not provide a reason for changing (state=%, time=%\n"), toString(state), time2string(currentTime));
     735              :         }
     736      1600659 :         if (mode == LC_NEVER) {
     737              :             // cancel all lcModel requests
     738              :             state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     739        42510 :             state &= ~LCA_URGENT;
     740        42510 :             if (changeRequest == REQUEST_NONE) {
     741              :                 // also remove all reasons except TRACI
     742        42043 :                 state &= ~LCA_CHANGE_REASONS | LCA_TRACI;
     743              :             }
     744      1558151 :         } else if (mode == LC_NOCONFLICT && changeRequest != REQUEST_NONE) {
     745         5623 :             if (
     746         5623 :                 ((state & LCA_LEFT) != 0 && changeRequest != REQUEST_LEFT) ||
     747         5391 :                 ((state & LCA_RIGHT) != 0 && changeRequest != REQUEST_RIGHT) ||
     748         4943 :                 ((state & LCA_STAY) != 0 && changeRequest != REQUEST_HOLD)) {
     749              :                 // cancel conflicting lcModel request
     750              :                 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     751          827 :                 state &= ~LCA_URGENT;
     752              :             }
     753      1552528 :         } else if (mode == LC_ALWAYS) {
     754              :             // ignore any TraCI requests
     755              :             return state;
     756              :         }
     757              :     }
     758              :     // apply traci requests
     759      2821879 :     if (changeRequest == REQUEST_NONE) {
     760      2654035 :         return state;
     761              :     } else {
     762       173035 :         state |= LCA_TRACI;
     763              :         // security checks
     764       173035 :         if ((myTraciLaneChangePriority == LCP_ALWAYS)
     765       171179 :                 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     766         2250 :             state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     767              :         }
     768       173035 :         if (changeRequest != REQUEST_HOLD && myTraciLaneChangePriority != LCP_OPPORTUNISTIC) {
     769         2094 :             state |= LCA_URGENT;
     770              :         }
     771         2123 :         switch (changeRequest) {
     772              :             case REQUEST_HOLD:
     773       170912 :                 return state | LCA_STAY;
     774         1328 :             case REQUEST_LEFT:
     775         1328 :                 return state | LCA_LEFT;
     776          795 :             case REQUEST_RIGHT:
     777          795 :                 return state | LCA_RIGHT;
     778              :             default:
     779              :                 throw ProcessError(TL("should not happen"));
     780              :         }
     781              :     }
     782              : }
     783              : 
     784              : 
     785              : double
     786          364 : MSVehicle::Influencer::changeRequestRemainingSeconds(const SUMOTime currentTime) const {
     787              :     assert(myLaneTimeLine.size() >= 2);
     788              :     assert(currentTime >= myLaneTimeLine[0].first);
     789          364 :     return STEPS2TIME(myLaneTimeLine[1].first - currentTime);
     790              : }
     791              : 
     792              : 
     793              : void
     794         5622 : MSVehicle::Influencer::setSpeedMode(int speedMode) {
     795         5622 :     myConsiderSafeVelocity = ((speedMode & 1) != 0);
     796         5622 :     myConsiderMaxAcceleration = ((speedMode & 2) != 0);
     797         5622 :     myConsiderMaxDeceleration = ((speedMode & 4) != 0);
     798         5622 :     myRespectJunctionPriority = ((speedMode & 8) != 0);
     799         5622 :     myEmergencyBrakeRedLight = ((speedMode & 16) != 0);
     800         5622 :     myRespectJunctionLeaderPriority = ((speedMode & 32) == 0); // inverted!
     801         5622 :     myConsiderSpeedLimit = ((speedMode & 64) == 0); // inverted!
     802         5622 : }
     803              : 
     804              : 
     805              : void
     806        18534 : MSVehicle::Influencer::setLaneChangeMode(int value) {
     807        18534 :     myStrategicLC = (LaneChangeMode)(value & (1 + 2));
     808        18534 :     myCooperativeLC = (LaneChangeMode)((value & (4 + 8)) >> 2);
     809        18534 :     mySpeedGainLC = (LaneChangeMode)((value & (16 + 32)) >> 4);
     810        18534 :     myRightDriveLC = (LaneChangeMode)((value & (64 + 128)) >> 6);
     811        18534 :     myTraciLaneChangePriority = (TraciLaneChangePriority)((value & (256 + 512)) >> 8);
     812        18534 :     mySublaneLC = (LaneChangeMode)((value & (1024 + 2048)) >> 10);
     813        18534 : }
     814              : 
     815              : 
     816              : void
     817         7359 : MSVehicle::Influencer::setRemoteControlled(Position xyPos, MSLane* l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector& route, SUMOTime t) {
     818         7359 :     myRemoteXYPos = xyPos;
     819         7359 :     myRemoteLane = l;
     820         7359 :     myRemotePos = pos;
     821         7359 :     myRemotePosLat = posLat;
     822         7359 :     myRemoteAngle = angle;
     823         7359 :     myRemoteEdgeOffset = edgeOffset;
     824         7359 :     myRemoteRoute = route;
     825         7359 :     myLastRemoteAccess = t;
     826         7359 : }
     827              : 
     828              : 
     829              : bool
     830      1017800 : MSVehicle::Influencer::isRemoteControlled() const {
     831      1017800 :     return myLastRemoteAccess == MSNet::getInstance()->getCurrentTimeStep();
     832              : }
     833              : 
     834              : 
     835              : bool
     836       482926 : MSVehicle::Influencer::isRemoteAffected(SUMOTime t) const {
     837       482926 :     return myLastRemoteAccess >= t - TIME2STEPS(10);
     838              : }
     839              : 
     840              : 
     841              : void
     842       491830 : MSVehicle::Influencer::updateRemoteControlRoute(MSVehicle* v) {
     843       491830 :     if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
     844              :         // only replace route at this time if the vehicle is moving with the flow
     845           79 :         const bool isForward = v->getLane() != 0 && &v->getLane()->getEdge() == myRemoteRoute[0];
     846              : #ifdef DEBUG_REMOTECONTROL
     847              :         std::cout << SIMSTEP << " updateRemoteControlRoute veh=" << v->getID() << " old=" << toString(v->getRoute().getEdges()) << " new=" << toString(myRemoteRoute) << " fwd=" << isForward << "\n";
     848              : #endif
     849              :         if (isForward) {
     850           12 :             v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     851           12 :             v->updateBestLanes();
     852              :         }
     853              :     }
     854       491830 : }
     855              : 
     856              : 
     857              : void
     858         7339 : MSVehicle::Influencer::postProcessRemoteControl(MSVehicle* v) {
     859         7339 :     const bool wasOnRoad = v->isOnRoad();
     860         7339 :     const bool withinLane = myRemoteLane != nullptr && fabs(myRemotePosLat) < 0.5 * (myRemoteLane->getWidth() + v->getVehicleType().getWidth());
     861         7339 :     const bool keepLane = wasOnRoad && v->getLane() == myRemoteLane;
     862         7339 :     if (v->isOnRoad() && !(keepLane && withinLane)) {
     863          154 :         if (myRemoteLane != nullptr && &v->getLane()->getEdge() == &myRemoteLane->getEdge()) {
     864              :             // correct odometer which gets incremented via onRemovalFromNet->leaveLane
     865           64 :             v->myOdometer -= v->getLane()->getLength();
     866              :         }
     867          154 :         v->onRemovalFromNet(MSMoveReminder::NOTIFICATION_TELEPORT);
     868          154 :         v->getMutableLane()->removeVehicle(v, MSMoveReminder::NOTIFICATION_TELEPORT, false);
     869              :     }
     870         7339 :     if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
     871              :         // needed for the insertion step
     872              : #ifdef DEBUG_REMOTECONTROL
     873              :         std::cout << SIMSTEP << " postProcessRemoteControl veh=" << v->getID()
     874              :                   << "\n  oldLane=" << Named::getIDSecure(v->getLane())
     875              :                   << " oldRoute=" << toString(v->getRoute().getEdges())
     876              :                   << "\n  newLane=" << Named::getIDSecure(myRemoteLane)
     877              :                   << " newRoute=" << toString(myRemoteRoute)
     878              :                   << " newRouteEdge=" << myRemoteRoute[myRemoteEdgeOffset]->getID()
     879              :                   << "\n";
     880              : #endif
     881              :         // clear any prior stops because they cannot apply to the new route
     882           79 :         const_cast<SUMOVehicleParameter&>(v->getParameter()).stops.clear();
     883          158 :         v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     884              :         myRemoteRoute.clear();
     885              :     }
     886         7339 :     v->myCurrEdge = v->getRoute().begin() + myRemoteEdgeOffset;
     887         7339 :     if (myRemoteLane != nullptr && myRemotePos > myRemoteLane->getLength()) {
     888            0 :         myRemotePos = myRemoteLane->getLength();
     889              :     }
     890         7339 :     if (myRemoteLane != nullptr && withinLane) {
     891         7193 :         if (keepLane) {
     892              :             // TODO this handles only the case when the new vehicle is completely on the edge
     893         7016 :             const bool needFurtherUpdate = v->myState.myPos < v->getVehicleType().getLength() && myRemotePos >= v->getVehicleType().getLength();
     894         7016 :             v->myState.myPos = myRemotePos;
     895         7016 :             v->myState.myPosLat = myRemotePosLat;
     896         7016 :             if (needFurtherUpdate) {
     897            4 :                 v->myState.myBackPos = v->updateFurtherLanes(v->myFurtherLanes, v->myFurtherLanesPosLat, std::vector<MSLane*>());
     898              :             }
     899              :         } else {
     900          177 :             MSMoveReminder::Notification notify = v->getDeparture() == NOT_YET_DEPARTED
     901          177 :                                                   ? MSMoveReminder::NOTIFICATION_DEPARTED
     902              :                                                   : MSMoveReminder::NOTIFICATION_TELEPORT_ARRIVED;
     903          177 :             if (!v->isOnRoad()) {
     904          177 :                 MSVehicleTransfer::getInstance()->remove(v);  // TODO may need optimization, this is linear in the number of vehicles in transfer
     905              :             }
     906          177 :             myRemoteLane->forceVehicleInsertion(v, myRemotePos, notify, myRemotePosLat);
     907          177 :             v->updateBestLanes();
     908              :         }
     909         7193 :         if (!wasOnRoad) {
     910           53 :             v->drawOutsideNetwork(false);
     911              :         }
     912              :         //std::cout << "on road network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << " pos=" << myRemotePos << " posLat=" << myRemotePosLat << "\n";
     913         7193 :         myRemoteLane->requireCollisionCheck();
     914              :     } else {
     915          146 :         if (v->getDeparture() == NOT_YET_DEPARTED) {
     916            4 :             v->onDepart();
     917              :         }
     918          146 :         v->drawOutsideNetwork(true);
     919              :         // see updateState
     920          146 :         double vNext = v->processTraCISpeedControl(
     921          146 :                            v->getMaxSpeed(), v->getSpeed());
     922          146 :         v->setBrakingSignals(vNext);
     923          146 :         v->myState.myPreviousSpeed = v->getSpeed();
     924          146 :         v->myAcceleration = SPEED2ACCEL(vNext - v->getSpeed());
     925          146 :         v->myState.mySpeed = vNext;
     926          146 :         v->updateWaitingTime(vNext);
     927              :         //std::cout << "outside network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << "\n";
     928              :     }
     929              :     // ensure that the position is correct (i.e. when the lanePosition is ambiguous at corners)
     930         7339 :     v->setRemoteState(myRemoteXYPos);
     931         7339 :     v->setAngle(GeomHelper::fromNaviDegree(myRemoteAngle));
     932         7339 : }
     933              : 
     934              : 
     935              : double
     936         7320 : MSVehicle::Influencer::implicitSpeedRemote(const MSVehicle* veh, double oldSpeed) {
     937         7320 :     if (veh->getPosition() == Position::INVALID) {
     938            8 :         return oldSpeed;
     939              :     }
     940         7312 :     double dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
     941         7312 :     if (myRemoteLane != nullptr) {
     942              :         // if the vehicles is frequently placed on a new edge, the route may
     943              :         // consist only of a single edge. In this case the new edge may not be
     944              :         // on the route so distAlongRoute will be double::max.
     945              :         // In this case we still want a sensible speed value
     946         7198 :         const double distAlongRoute = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     947         7198 :         if (distAlongRoute != std::numeric_limits<double>::max()) {
     948              :             dist = distAlongRoute;
     949              :         }
     950              :     }
     951              :     //std::cout << SIMTIME << " veh=" << veh->getID() << " oldPos=" << veh->getPosition() << " traciPos=" << myRemoteXYPos << " dist=" << dist << "\n";
     952         7312 :     const double minSpeed = myConsiderMaxDeceleration ?
     953         4044 :                             veh->getCarFollowModel().minNextSpeedEmergency(oldSpeed, veh) : 0;
     954         7312 :     const double maxSpeed = (myRemoteLane != nullptr
     955         7312 :                              ? myRemoteLane->getVehicleMaxSpeed(veh)
     956          114 :                              : (veh->getLane() != nullptr
     957          114 :                                 ? veh->getLane()->getVehicleMaxSpeed(veh)
     958            4 :                                 : veh->getMaxSpeed()));
     959         7312 :     return MIN2(maxSpeed, MAX2(minSpeed, DIST2SPEED(dist)));
     960              : }
     961              : 
     962              : 
     963              : double
     964         7182 : MSVehicle::Influencer::implicitDeltaPosRemote(const MSVehicle* veh) {
     965              :     double dist = 0;
     966         7182 :     if (myRemoteLane == nullptr) {
     967            5 :         dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
     968              :     } else {
     969              :         // if the vehicles is frequently placed on a new edge, the route may
     970              :         // consist only of a single edge. In this case the new edge may not be
     971              :         // on the route so getDistanceToPosition will return double::max.
     972              :         // In this case we would rather not move the vehicle in executeMove
     973              :         // (updateState) as it would result in emergency braking
     974         7177 :         dist = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     975              :     }
     976         7182 :     if (dist == std::numeric_limits<double>::max()) {
     977              :         return 0;
     978              :     } else {
     979         6961 :         if (DIST2SPEED(dist) > veh->getMaxSpeed() * 1.1) {
     980           42 :             WRITE_WARNINGF(TL("Vehicle '%' moved by TraCI from % to % (dist %) with implied speed of % (exceeding maximum speed %). time=%."),
     981              :                            veh->getID(), veh->getPosition(), myRemoteXYPos, dist, DIST2SPEED(dist), veh->getMaxSpeed(), time2string(SIMSTEP));
     982              :             // some sanity check here
     983           14 :             dist = MIN2(dist, SPEED2DIST(veh->getMaxSpeed() * 2));
     984              :         }
     985         6961 :         return dist;
     986              :     }
     987              : }
     988              : 
     989              : 
     990              : /* -------------------------------------------------------------------------
     991              :  * MSVehicle-methods
     992              :  * ----------------------------------------------------------------------- */
     993      4534083 : MSVehicle::MSVehicle(SUMOVehicleParameter* pars, ConstMSRoutePtr route,
     994      4534083 :                      MSVehicleType* type, const double speedFactor) :
     995              :     MSBaseVehicle(pars, route, type, speedFactor),
     996      4534083 :     myWaitingTime(0),
     997      4534083 :     myWaitingTimeCollector(),
     998      4534083 :     myTimeLoss(0),
     999      4534083 :     myState(0, 0, 0, 0, 0),
    1000      4534083 :     myDriverState(nullptr),
    1001      4534083 :     myActionStep(true),
    1002      4534083 :     myLastActionTime(0),
    1003      4534083 :     myLane(nullptr),
    1004      4534083 :     myLaneChangeModel(nullptr),
    1005      4534083 :     myLastBestLanesEdge(nullptr),
    1006      4534083 :     myLastBestLanesInternalLane(nullptr),
    1007      4534083 :     myAcceleration(0),
    1008              :     myNextTurn(0., nullptr),
    1009      4534083 :     mySignals(0),
    1010      4534083 :     myAmOnNet(false),
    1011      4534083 :     myAmIdling(false),
    1012      4534083 :     myHaveToWaitOnNextLink(false),
    1013      4534083 :     myAngle(0),
    1014      4534083 :     myRawAngle(0),
    1015      4534083 :     myLastAngle(INVALID_DOUBLE),
    1016      4534083 :     myStopDist(std::numeric_limits<double>::max()),
    1017      4534083 :     myStopSpeed(std::numeric_limits<double>::max()),
    1018      4534083 :     myCollisionImmunity(-1),
    1019      4534083 :     myCachedPosition(Position::INVALID),
    1020      4534083 :     myJunctionEntryTime(SUMOTime_MAX),
    1021      4534083 :     myJunctionEntryTimeNeverYield(SUMOTime_MAX),
    1022      4534083 :     myJunctionConflictEntryTime(SUMOTime_MAX),
    1023      4534083 :     myTimeSinceStartup(TIME2STEPS(3600 * 24)),
    1024      4534083 :     myHaveStoppedFor(nullptr),
    1025     13602249 :     myInfluencer(nullptr) {
    1026      4534083 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    1027      4534083 :     myNextDriveItem = myLFLinkLanes.begin();
    1028      4534083 : }
    1029              : 
    1030              : 
    1031      8418472 : MSVehicle::~MSVehicle() {
    1032      4534006 :     cleanupParkingReservation();
    1033      4534006 :     cleanupFurtherLanes();
    1034      4534006 :     delete myLaneChangeModel;
    1035      4534006 :     if (myType->isVehicleSpecific()) {
    1036          314 :         MSNet::getInstance()->getVehicleControl().removeVType(myType);
    1037              :     }
    1038      4534006 :     delete myInfluencer;
    1039      4534006 :     delete myCFVariables;
    1040     12952478 : }
    1041              : 
    1042              : 
    1043              : void
    1044      4534568 : MSVehicle::cleanupFurtherLanes() {
    1045      4537083 :     for (MSLane* further : myFurtherLanes) {
    1046         2515 :         further->resetPartialOccupation(this);
    1047         2515 :         if (further->getBidiLane() != nullptr
    1048         2515 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    1049            0 :             further->getBidiLane()->resetPartialOccupation(this);
    1050              :         }
    1051              :     }
    1052      4534568 :     if (myLaneChangeModel != nullptr) {
    1053      4534534 :         removeApproachingInformation(myLFLinkLanes);
    1054      4534534 :         myLaneChangeModel->cleanupShadowLane();
    1055      4534534 :         myLaneChangeModel->cleanupTargetLane();
    1056              :         // still needed when calling resetPartialOccupation (getShadowLane) and when removing
    1057              :         // approach information from parallel links
    1058              :     }
    1059              :     myFurtherLanes.clear();
    1060              :     myFurtherLanesPosLat.clear();
    1061      4534568 : }
    1062              : 
    1063              : 
    1064              : void
    1065      3379247 : MSVehicle::onRemovalFromNet(const MSMoveReminder::Notification reason) {
    1066              : #ifdef DEBUG_ACTIONSTEPS
    1067              :     if (DEBUG_COND) {
    1068              :         std::cout << SIMTIME << " Removing vehicle '" << getID() << "' (reason: " << toString(reason) << ")" << std::endl;
    1069              :     }
    1070              : #endif
    1071      3379247 :     MSVehicleTransfer::getInstance()->remove(this);
    1072      3379247 :     removeApproachingInformation(myLFLinkLanes);
    1073      3379247 :     leaveLane(reason);
    1074      3379247 :     if (reason == MSMoveReminder::NOTIFICATION_VAPORIZED_COLLISION) {
    1075          562 :         cleanupFurtherLanes();
    1076              :     }
    1077      3379247 : }
    1078              : 
    1079              : 
    1080              : void
    1081      4534083 : MSVehicle::initDevices() {
    1082      4534083 :     MSBaseVehicle::initDevices();
    1083      4534071 :     myLaneChangeModel = MSAbstractLaneChangeModel::build(myType->getLaneChangeModel(), *this);
    1084      4534049 :     myDriverState = static_cast<MSDevice_DriverState*>(getDevice(typeid(MSDevice_DriverState)));
    1085      4534049 :     myFrictionDevice = static_cast<MSDevice_Friction*>(getDevice(typeid(MSDevice_Friction)));
    1086      4534049 : }
    1087              : 
    1088              : 
    1089              : // ------------ interaction with the route
    1090              : bool
    1091   2238252825 : MSVehicle::hasValidRouteStart(std::string& msg) {
    1092              :     // note: not a const method because getDepartLane may call updateBestLanes
    1093   2238252825 :     if (!(*myCurrEdge)->isTazConnector()) {
    1094   2237924467 :         if (myParameter->departLaneProcedure == DepartLaneDefinition::GIVEN
    1095   2237924467 :                 || (myParameter->departLaneProcedure == DepartLaneDefinition::DEFAULT && MSEdge::getDefaultDepartLaneDefinition() == DepartLaneDefinition::GIVEN)) {
    1096     60880006 :             if ((*myCurrEdge)->getDepartLane(*this) == nullptr) {
    1097          132 :                 msg = "Invalid departLane definition for vehicle '" + getID() + "'.";
    1098           66 :                 if (myParameter->departLane >= (int)(*myCurrEdge)->getLanes().size()) {
    1099           11 :                     myRouteValidity |= ROUTE_START_INVALID_LANE;
    1100              :                 } else {
    1101           55 :                     myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
    1102              :                 }
    1103           66 :                 return false;
    1104              :             }
    1105              :         } else {
    1106   2177044461 :             if ((*myCurrEdge)->allowedLanes(getVClass(), ignoreTransientPermissions()) == nullptr) {
    1107          144 :                 msg = "Vehicle '" + getID() + "' is not allowed to depart on any lane of edge '" + (*myCurrEdge)->getID() + "'.";
    1108           72 :                 myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
    1109           72 :                 return false;
    1110              :             }
    1111              :         }
    1112   2237924329 :         if (myParameter->departSpeedProcedure == DepartSpeedDefinition::GIVEN && myParameter->departSpeed > myType->getMaxSpeed() + SPEED_EPS) {
    1113           38 :             msg = "Departure speed for vehicle '" + getID() + "' is too high for the vehicle type '" + myType->getID() + "'.";
    1114           19 :             myRouteValidity |= ROUTE_START_INVALID_LANE;
    1115           19 :             return false;
    1116              :         }
    1117              :     }
    1118   2238252668 :     myRouteValidity &= ~(ROUTE_START_INVALID_LANE | ROUTE_START_INVALID_PERMISSIONS);
    1119   2238252668 :     return true;
    1120              : }
    1121              : 
    1122              : 
    1123              : bool
    1124    718308357 : MSVehicle::hasArrived() const {
    1125    718308357 :     return hasArrivedInternal(false);
    1126              : }
    1127              : 
    1128              : 
    1129              : bool
    1130   1446011707 : MSVehicle::hasArrivedInternal(bool oppositeTransformed) const {
    1131   2355140537 :     return ((myCurrEdge == myRoute->end() - 1 || (myParameter->arrivalEdge >= 0 && getRoutePosition() >= myParameter->arrivalEdge))
    1132    536932150 :             && (myStops.empty() || myStops.front().edge != myCurrEdge || myStops.front().getSpeed() > 0)
    1133   1004504918 :             && ((myLaneChangeModel->isOpposite() && !oppositeTransformed) ? myLane->getLength() - myState.myPos : myState.myPos) > MIN2(myLane->getLength(), myArrivalPos) - POSITION_EPS
    1134   1457444455 :             && !isRemoteControlled());
    1135              : }
    1136              : 
    1137              : 
    1138              : bool
    1139      1573818 : MSVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
    1140      3147636 :     if (MSBaseVehicle::replaceRoute(newRoute, info, onInit, offset, addRouteStops, removeStops, msgReturn)) {
    1141              :         // update best lanes (after stops were added)
    1142      1573800 :         myLastBestLanesEdge = nullptr;
    1143      1573800 :         myLastBestLanesInternalLane = nullptr;
    1144      1573800 :         updateBestLanes(true, onInit ? (*myCurrEdge)->getLanes().front() : 0);
    1145              :         assert(!removeStops || haveValidStopEdges());
    1146      1573800 :         if (myStops.size() == 0) {
    1147      1529535 :             myStopDist = std::numeric_limits<double>::max();
    1148              :         }
    1149      1573800 :         return true;
    1150              :     }
    1151              :     return false;
    1152              : }
    1153              : 
    1154              : 
    1155              : // ------------ Interaction with move reminders
    1156              : void
    1157    705189714 : MSVehicle::workOnMoveReminders(double oldPos, double newPos, double newSpeed) {
    1158              :     // This erasure-idiom works for all stl-sequence-containers
    1159              :     // See Meyers: Effective STL, Item 9
    1160   1871612204 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    1161              :         // XXX: calling notifyMove with newSpeed seems not the best choice. For the ballistic update, the average speed is calculated and used
    1162              :         //      although a higher order quadrature-formula might be more adequate.
    1163              :         //      For the euler case (where the speed is considered constant for each time step) it is conceivable that
    1164              :         //      the current calculations may lead to systematic errors for large time steps (compared to reality). Refs. #2579
    1165   2332844982 :         if (!rem->first->notifyMove(*this, oldPos + rem->second, newPos + rem->second, MAX2(0., newSpeed))) {
    1166              : #ifdef _DEBUG
    1167              :             if (myTraceMoveReminders) {
    1168              :                 traceMoveReminder("notifyMove", rem->first, rem->second, false);
    1169              :             }
    1170              : #endif
    1171              :             rem = myMoveReminders.erase(rem);
    1172              :         } else {
    1173              : #ifdef _DEBUG
    1174              :             if (myTraceMoveReminders) {
    1175              :                 traceMoveReminder("notifyMove", rem->first, rem->second, true);
    1176              :             }
    1177              : #endif
    1178              :             ++rem;
    1179              :         }
    1180              :     }
    1181    705189713 :     if (myEnergyParams != nullptr) {
    1182              :         // TODO make the vehicle energy params a derived class which is a move reminder
    1183    141458279 :         myEnergyParams->setDynamicValues(isStopped() ? getNextStop().duration : -1, isParking(), getWaitingTime(), getAngleDiff());
    1184              :     }
    1185    705189713 : }
    1186              : 
    1187              : 
    1188              : void
    1189        66796 : MSVehicle::workOnIdleReminders() {
    1190        66796 :     updateWaitingTime(0.);   // cf issue 2233
    1191              : 
    1192              :     // vehicle move reminders
    1193        80324 :     for (const auto& rem : myMoveReminders) {
    1194        13528 :         rem.first->notifyIdle(*this);
    1195              :     }
    1196              : 
    1197              :     // lane move reminders - for aggregated values
    1198       166721 :     for (MSMoveReminder* rem : getLane()->getMoveReminders()) {
    1199        99925 :         rem->notifyIdle(*this);
    1200              :     }
    1201        66796 : }
    1202              : 
    1203              : // XXX: consider renaming...
    1204              : void
    1205     19616430 : MSVehicle::adaptLaneEntering2MoveReminder(const MSLane& enteredLane) {
    1206              :     // save the old work reminders, patching the position information
    1207              :     //  add the information about the new offset to the old lane reminders
    1208     19616430 :     const double oldLaneLength = myLane->getLength();
    1209     55521625 :     for (auto& rem : myMoveReminders) {
    1210     35905195 :         rem.second += oldLaneLength;
    1211              : #ifdef _DEBUG
    1212              : //        if (rem->first==0) std::cout << "Null reminder (?!)" << std::endl;
    1213              : //        std::cout << "Adapted MoveReminder on lane " << ((rem->first->getLane()==0) ? "NULL" : rem->first->getLane()->getID()) <<" position to " << rem->second << std::endl;
    1214              :         if (myTraceMoveReminders) {
    1215              :             traceMoveReminder("adaptedPos", rem.first, rem.second, true);
    1216              :         }
    1217              : #endif
    1218              :     }
    1219     32897495 :     for (MSMoveReminder* const rem : enteredLane.getMoveReminders()) {
    1220     13281065 :         addReminder(rem);
    1221              :     }
    1222     19616430 : }
    1223              : 
    1224              : 
    1225              : // ------------ Other getter methods
    1226              : double
    1227    164824264 : MSVehicle::getSlope() const {
    1228    164824264 :     if (isParking() && getStops().begin()->parkingarea != nullptr) {
    1229         3881 :         return getStops().begin()->parkingarea->getVehicleSlope(*this);
    1230              :     }
    1231    164820383 :     if (myLane == nullptr) {
    1232              :         return 0;
    1233              :     }
    1234    164820383 :     if (MSGlobals::gSlopeCentered) {
    1235              :         MSLane* centerLane = myLane;
    1236          248 :         double centerPos = getPositionOnLane() - getLength() / 2;
    1237              :         int furtherIndex = 0;
    1238          280 :         while (centerPos < 0 && furtherIndex < (int)myFurtherLanes.size()) {
    1239           32 :             centerLane = myFurtherLanes[furtherIndex];
    1240           32 :             centerPos += centerLane->getLength();
    1241           32 :             furtherIndex++;
    1242              :         }
    1243          248 :         return centerLane->getShape().slopeDegreeAtOffset(centerLane->interpolateLanePosToGeometryPos(centerPos));
    1244              :     }
    1245    164820135 :     const double posLat = myState.myPosLat; // @todo get rid of the '-'
    1246    164820135 :     Position p1 = getPosition();
    1247    164820135 :     Position p2 = getBackPosition();
    1248              :     if (p2 == Position::INVALID) {
    1249              :         // Handle special case of vehicle's back reaching out of the network
    1250            6 :         if (myFurtherLanes.size() > 0) {
    1251            6 :             p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
    1252              :             if (p2 == Position::INVALID) {
    1253              :                 // unsuitable lane geometry
    1254            0 :                 p2 = myLane->geometryPositionAtOffset(0, posLat);
    1255              :             }
    1256              :         } else {
    1257            0 :             p2 = myLane->geometryPositionAtOffset(0, posLat);
    1258              :         }
    1259              :     }
    1260    164820135 :     return (p1 != p2 ? RAD2DEG(p2.slopeTo2D(p1)) : myLane->getShape().slopeDegreeAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1261              : }
    1262              : 
    1263              : 
    1264              : Position
    1265    942381228 : MSVehicle::getPosition(const double offset) const {
    1266    942381228 :     if (myLane == nullptr) {
    1267              :         // when called in the context of GUI-Drawing, the simulation step is already incremented
    1268          146 :         if (myInfluencer != nullptr && myInfluencer->isRemoteAffected(MSNet::getInstance()->getCurrentTimeStep())) {
    1269           40 :             return myCachedPosition;
    1270              :         } else {
    1271          106 :             return Position::INVALID;
    1272              :         }
    1273              :     }
    1274    942381082 :     if (isParking()) {
    1275      3729012 :         if (myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() > getNextStopParameter()->started) {
    1276          123 :             return myCachedPosition;
    1277              :         }
    1278      3728889 :         if (myStops.begin()->parkingarea != nullptr) {
    1279        23582 :             return myStops.begin()->parkingarea->getVehiclePosition(*this);
    1280              :         } else {
    1281              :             // position beside the road
    1282      3705307 :             PositionVector shp = myLane->getEdge().getLanes()[0]->getShape();
    1283      7410493 :             shp.move2side(SUMO_const_laneWidth * (MSGlobals::gLefthand ? -1 : 1));
    1284      3705307 :             return shp.positionAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane() + offset));
    1285      3705307 :         }
    1286              :     }
    1287    938652070 :     const bool changingLanes = myLaneChangeModel->isChangingLanes();
    1288   1867157392 :     const double posLat = (MSGlobals::gLefthand ? 1 : -1) * getLateralPositionOnLane();
    1289    938652070 :     if (offset == 0. && !changingLanes) {
    1290              :         if (myCachedPosition == Position::INVALID) {
    1291    709769576 :             myCachedPosition = validatePosition(myLane->geometryPositionAtOffset(myState.myPos, posLat));
    1292    709769576 :             if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1293        61155 :                 interpolateLateralZ(myCachedPosition, myState.myPos, posLat);
    1294              :             }
    1295              :         }
    1296    931883156 :         return myCachedPosition;
    1297              :     }
    1298      6768914 :     Position result = validatePosition(myLane->geometryPositionAtOffset(getPositionOnLane() + offset, posLat), offset);
    1299      6768914 :     interpolateLateralZ(result, getPositionOnLane() + offset, posLat);
    1300      6768914 :     return result;
    1301              : }
    1302              : 
    1303              : 
    1304              : void
    1305      7115353 : MSVehicle::interpolateLateralZ(Position& pos, double offset, double posLat) const {
    1306      7115353 :     const MSLane* shadow = myLaneChangeModel->getShadowLane();
    1307      7115353 :     if (shadow != nullptr && pos != Position::INVALID) {
    1308              :         // ignore negative offset
    1309              :         const Position shadowPos = shadow->geometryPositionAtOffset(MAX2(0.0, offset));
    1310        60205 :         if (shadowPos != Position::INVALID && pos.z() != shadowPos.z()) {
    1311          325 :             const double centerDist = (myLane->getWidth() + shadow->getWidth()) * 0.5;
    1312          325 :             double relOffset = fabs(posLat) / centerDist;
    1313          325 :             double newZ = (1 - relOffset) * pos.z() + relOffset * shadowPos.z();
    1314              :             pos.setz(newZ);
    1315              :         }
    1316              :     }
    1317      7115353 : }
    1318              : 
    1319              : 
    1320              : double
    1321      1110508 : MSVehicle::getDistanceToLeaveJunction() const {
    1322      1110508 :     double result = getLength() - getPositionOnLane();
    1323      1110508 :     if (myLane->isNormal()) {
    1324              :         return MAX2(0.0, result);
    1325              :     }
    1326         5088 :     const MSLane* lane = myLane;
    1327        10176 :     while (lane->isInternal()) {
    1328         5088 :         result += lane->getLength();
    1329         5088 :         lane = lane->getCanonicalSuccessorLane();
    1330              :     }
    1331              :     return result;
    1332              : }
    1333              : 
    1334              : 
    1335              : Position
    1336       103033 : MSVehicle::getPositionAlongBestLanes(double offset) const {
    1337              :     assert(MSGlobals::gUsingInternalLanes);
    1338       103033 :     if (!isOnRoad()) {
    1339            0 :         return Position::INVALID;
    1340              :     }
    1341       103033 :     const std::vector<MSLane*>& bestLanes = getBestLanesContinuation();
    1342              :     auto nextBestLane = bestLanes.begin();
    1343       103033 :     const bool opposite = myLaneChangeModel->isOpposite();
    1344       103033 :     double pos = opposite ? myLane->getLength() - myState.myPos : myState.myPos;
    1345       103033 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : getLane();
    1346              :     assert(lane != 0);
    1347              :     bool success = true;
    1348              : 
    1349       304195 :     while (offset > 0) {
    1350              :         // take into account lengths along internal lanes
    1351       307565 :         while (lane->isInternal() && offset > 0) {
    1352       106403 :             if (offset > lane->getLength() - pos) {
    1353         3561 :                 offset -= lane->getLength() - pos;
    1354         3561 :                 lane = lane->getLinkCont()[0]->getViaLaneOrLane();
    1355              :                 pos = 0.;
    1356         3561 :                 if (lane == nullptr) {
    1357              :                     success = false;
    1358              :                     offset = 0.;
    1359              :                 }
    1360              :             } else {
    1361       102842 :                 pos += offset;
    1362              :                 offset = 0;
    1363              :             }
    1364              :         }
    1365              :         // set nextBestLane to next non-internal lane
    1366       206290 :         while (nextBestLane != bestLanes.end() && *nextBestLane == nullptr) {
    1367              :             ++nextBestLane;
    1368              :         }
    1369       201162 :         if (offset > 0) {
    1370              :             assert(!lane->isInternal());
    1371              :             assert(lane == *nextBestLane);
    1372        98320 :             if (offset > lane->getLength() - pos) {
    1373        98137 :                 offset -= lane->getLength() - pos;
    1374              :                 ++nextBestLane;
    1375              :                 assert(nextBestLane == bestLanes.end() || *nextBestLane != 0);
    1376        98137 :                 if (nextBestLane == bestLanes.end()) {
    1377              :                     success = false;
    1378              :                     offset = 0.;
    1379              :                 } else {
    1380        98137 :                     const MSLink* link = lane->getLinkTo(*nextBestLane);
    1381              :                     assert(link != nullptr);
    1382              :                     lane = link->getViaLaneOrLane();
    1383              :                     pos = 0.;
    1384              :                 }
    1385              :             } else {
    1386          183 :                 pos += offset;
    1387              :                 offset = 0;
    1388              :             }
    1389              :         }
    1390              : 
    1391              :     }
    1392              : 
    1393       103033 :     if (success) {
    1394       103033 :         return lane->geometryPositionAtOffset(pos, -getLateralPositionOnLane());
    1395              :     } else {
    1396            0 :         return Position::INVALID;
    1397              :     }
    1398              : }
    1399              : 
    1400              : 
    1401              : double
    1402       709059 : MSVehicle::getMaxSpeedOnLane() const {
    1403       709059 :     if (myLane != nullptr) {
    1404       709059 :         return myLane->getVehicleMaxSpeed(this);
    1405              :     }
    1406            0 :     return myType->getMaxSpeed();
    1407              : }
    1408              : 
    1409              : 
    1410              : Position
    1411    716538490 : MSVehicle::validatePosition(Position result, double offset) const {
    1412              :     int furtherIndex = 0;
    1413    716538490 :     double lastLength = getPositionOnLane();
    1414    716538490 :     while (result == Position::INVALID) {
    1415       210686 :         if (furtherIndex >= (int)myFurtherLanes.size()) {
    1416              :             //WRITE_WARNINGF(TL("Could not compute position for vehicle '%', time=%."), getID(), time2string(MSNet::getInstance()->getCurrentTimeStep()));
    1417              :             break;
    1418              :         }
    1419              :         //std::cout << SIMTIME << " veh=" << getID() << " lane=" << myLane->getID() << " pos=" << getPositionOnLane() << " posLat=" << getLateralPositionOnLane() << " offset=" << offset << " result=" << result << " i=" << furtherIndex << " further=" << myFurtherLanes.size() << "\n";
    1420       192663 :         MSLane* further = myFurtherLanes[furtherIndex];
    1421       192663 :         offset += lastLength;
    1422       192663 :         result = further->geometryPositionAtOffset(further->getLength() + offset, -getLateralPositionOnLane());
    1423              :         lastLength = further->getLength();
    1424       192663 :         furtherIndex++;
    1425              :         //std::cout << SIMTIME << "   newResult=" << result << "\n";
    1426              :     }
    1427    716538490 :     return result;
    1428              : }
    1429              : 
    1430              : 
    1431              : ConstMSEdgeVector::const_iterator
    1432       283043 : MSVehicle::getRerouteOrigin() const {
    1433              :     // too close to the next junction, so avoid an emergency brake here
    1434       283043 :     if (myLane != nullptr && (myCurrEdge + 1) != myRoute->end() && !isRailway(getVClass())) {
    1435       220647 :         if (myLane->isInternal()) {
    1436              :             return myCurrEdge + 1;
    1437              :         }
    1438       213573 :         if (myState.myPos > myLane->getLength() - getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)) {
    1439              :             return myCurrEdge + 1;
    1440              :         }
    1441       211169 :         if (myLane->getEdge().hasChangeProhibitions(getVClass(), myLane->getIndex())) {
    1442              :             return myCurrEdge + 1;
    1443              :         }
    1444              :     }
    1445       273453 :     return myCurrEdge;
    1446              : }
    1447              : 
    1448              : 
    1449              : double
    1450    141458921 : MSVehicle::getAngleDiff() const {
    1451    141458921 :     return myLastAngle == INVALID_DOUBLE ? 0. : GeomHelper::angleDiff(myLastAngle, myAngle);
    1452              : }
    1453              : 
    1454              : double
    1455          642 : MSVehicle::getCurveRadius() const {
    1456          642 :     const double angleDiff = getAngleDiff();
    1457              :     return angleDiff == 0
    1458          642 :         ? std::numeric_limits<double>::max()
    1459            0 :         : SPEED2DIST(getSpeed()) / fabs(angleDiff);
    1460              : }
    1461              : 
    1462              : 
    1463              : void
    1464      5340092 : MSVehicle::setAngle(double angle, bool straightenFurther) {
    1465              : #ifdef DEBUG_FURTHER
    1466              :     if (DEBUG_COND) {
    1467              :         std::cout << SIMTIME << " veh '" << getID() << " setAngle(" << angle <<  ") straightenFurther=" << straightenFurther << std::endl;
    1468              :     }
    1469              : #endif
    1470      5340092 :     myAngle = angle;
    1471      5340092 :     MSLane* next = myLane;
    1472      5340092 :     if (straightenFurther && myFurtherLanesPosLat.size() > 0) {
    1473       202132 :         for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    1474       103861 :             MSLane* further = myFurtherLanes[i];
    1475       103861 :             const MSLink* link = further->getLinkTo(next);
    1476       103861 :             if (link  != nullptr) {
    1477       103432 :                 myFurtherLanesPosLat[i] = getLateralPositionOnLane() - link->getLateralShift();
    1478              :                 next = further;
    1479              :             } else {
    1480              :                 break;
    1481              :             }
    1482              :         }
    1483              :     }
    1484      5340092 : }
    1485              : 
    1486              : 
    1487              : void
    1488       451368 : MSVehicle::setActionStepLength(double actionStepLength, bool resetOffset) {
    1489       451368 :     SUMOTime actionStepLengthMillisecs = SUMOVehicleParserHelper::processActionStepLength(actionStepLength);
    1490              :     SUMOTime previousActionStepLength = getActionStepLength();
    1491              :     const bool newActionStepLength = actionStepLengthMillisecs != previousActionStepLength;
    1492       451368 :     if (newActionStepLength) {
    1493            7 :         getSingularType().setActionStepLength(actionStepLengthMillisecs, resetOffset);
    1494            7 :         if (!resetOffset) {
    1495            1 :             updateActionOffset(previousActionStepLength, actionStepLengthMillisecs);
    1496              :         }
    1497              :     }
    1498       451362 :     if (resetOffset) {
    1499            6 :         resetActionOffset();
    1500              :     }
    1501       451368 : }
    1502              : 
    1503              : 
    1504              : bool
    1505    299760458 : MSVehicle::congested() const {
    1506    299760458 :     return myState.mySpeed < (60.0 / 3.6) || myLane->getSpeedLimit() < (60.1 / 3.6);
    1507              : }
    1508              : 
    1509              : 
    1510              : double
    1511    712502103 : MSVehicle::computeAngle() const {
    1512              :     Position p1;
    1513    712502103 :     const double posLat = -myState.myPosLat; // @todo get rid of the '-'
    1514    712502103 :     const double lefthandSign = (MSGlobals::gLefthand ? -1 : 1);
    1515              : 
    1516              :     // if parking manoeuvre is happening then rotate vehicle on each step
    1517    712502103 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    1518          450 :         return getAngle() + myManoeuvre.getGUIIncrement();
    1519              :     }
    1520              : 
    1521    712501653 :     if (isParking()) {
    1522        29059 :         if (myStops.begin()->parkingarea != nullptr) {
    1523        15761 :             return myStops.begin()->parkingarea->getVehicleAngle(*this);
    1524              :         } else {
    1525        13298 :             return myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane()));
    1526              :         }
    1527              :     }
    1528    712472594 :     if (myLaneChangeModel->isChangingLanes()) {
    1529              :         // cannot use getPosition() because it already includes the offset to the side and thus messes up the angle
    1530      1147030 :         p1 = myLane->geometryPositionAtOffset(myState.myPos, lefthandSign * posLat);
    1531            9 :         if (p1 == Position::INVALID && myLane->getShape().length2D() == 0. && myLane->isInternal()) {
    1532              :             // workaround: extrapolate the preceding lane shape
    1533            9 :             MSLane* predecessorLane = myLane->getCanonicalPredecessorLane();
    1534            9 :             p1 = predecessorLane->geometryPositionAtOffset(predecessorLane->getLength() + myState.myPos, lefthandSign * posLat);
    1535              :         }
    1536              :     } else {
    1537    711325564 :         p1 = getPosition();
    1538              :     }
    1539              : 
    1540              :     Position p2;
    1541    712472594 :     if (getVehicleType().getParameter().locomotiveLength > 0) {
    1542              :         // articulated vehicle should use the heading of the first part
    1543      1878490 :         const double locoLength = MIN2(getVehicleType().getParameter().locomotiveLength, getLength());
    1544      1878490 :         p2 = getPosition(-locoLength);
    1545              :     } else {
    1546    710594104 :         p2 = getBackPosition();
    1547              :     }
    1548              :     if (p2 == Position::INVALID) {
    1549              :         // Handle special case of vehicle's back reaching out of the network
    1550         2134 :         if (myFurtherLanes.size() > 0) {
    1551          120 :             p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
    1552              :             if (p2 == Position::INVALID) {
    1553              :                 // unsuitable lane geometry
    1554           75 :                 p2 = myLane->geometryPositionAtOffset(0, posLat);
    1555              :             }
    1556              :         } else {
    1557         2014 :             p2 = myLane->geometryPositionAtOffset(0, posLat);
    1558              :         }
    1559              :     }
    1560              :     double result = (p1 != p2 ? p2.angleTo2D(p1) :
    1561       104665 :                      myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1562              : 
    1563    712472594 :     result += lefthandSign * myLaneChangeModel->calcAngleOffset();
    1564              : 
    1565              : #ifdef DEBUG_FURTHER
    1566              :     if (DEBUG_COND) {
    1567              :         std::cout << SIMTIME << " computeAngle veh=" << getID() << " p1=" << p1 << " p2=" << p2 << " angle=" << RAD2DEG(result) << " naviDegree=" << GeomHelper::naviDegree(result) << "\n";
    1568              :     }
    1569              : #endif
    1570    712472594 :     return result;
    1571              : }
    1572              : 
    1573              : 
    1574              : const Position
    1575    882561686 : MSVehicle::getBackPosition() const {
    1576    882561686 :     const double posLat = MSGlobals::gLefthand ? myState.myPosLat : -myState.myPosLat;
    1577              :     Position result;
    1578    882561686 :     if (myState.myPos >= myType->getLength()) {
    1579              :         // vehicle is fully on the new lane
    1580    864905273 :         result = myLane->geometryPositionAtOffset(myState.myPos - myType->getLength(), posLat);
    1581              :     } else {
    1582     17656413 :         if (myLaneChangeModel->isChangingLanes() && myFurtherLanes.size() > 0 && myLaneChangeModel->getShadowLane(myFurtherLanes.back()) == nullptr) {
    1583              :             // special case where the target lane has no predecessor
    1584              : #ifdef DEBUG_FURTHER
    1585              :             if (DEBUG_COND) {
    1586              :                 std::cout << "    getBackPosition veh=" << getID() << " specialCase using myLane=" << myLane->getID() << " pos=0 posLat=" << myState.myPosLat << " result=" << myLane->geometryPositionAtOffset(0, posLat) << "\n";
    1587              :             }
    1588              : #endif
    1589         1906 :             result = myLane->geometryPositionAtOffset(0, posLat);
    1590              :         } else {
    1591              : #ifdef DEBUG_FURTHER
    1592              :             if (DEBUG_COND) {
    1593              :                 std::cout << "    getBackPosition veh=" << getID() << " myLane=" << myLane->getID() << " further=" << toString(myFurtherLanes) << " myFurtherLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
    1594              :             }
    1595              : #endif
    1596     17654507 :             if (myFurtherLanes.size() > 0 && !myLaneChangeModel->isChangingLanes()) {
    1597              :                 // truncate to 0 if vehicle starts on an edge that is shorter than its length
    1598     17278473 :                 const double backPos = MAX2(0.0, getBackPositionOnLane(myFurtherLanes.back()));
    1599     34257861 :                 result = myFurtherLanes.back()->geometryPositionAtOffset(backPos, -myFurtherLanesPosLat.back() * (MSGlobals::gLefthand ? -1 : 1));
    1600              :             } else {
    1601       376034 :                 result = myLane->geometryPositionAtOffset(0, posLat);
    1602              :             }
    1603              :         }
    1604              :     }
    1605    882561686 :     if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1606       285284 :         interpolateLateralZ(result, myState.myPos - myType->getLength(), posLat);
    1607              :     }
    1608    882561686 :     return result;
    1609              : }
    1610              : 
    1611              : 
    1612              : bool
    1613       454440 : MSVehicle::willStop() const {
    1614       454440 :     return !isStopped() && !myStops.empty() && myLane != nullptr && &myStops.front().lane->getEdge() == &myLane->getEdge();
    1615              : }
    1616              : 
    1617              : bool
    1618    371569077 : MSVehicle::isStoppedOnLane() const {
    1619    371569077 :     return isStopped() && myStops.front().lane == myLane;
    1620              : }
    1621              : 
    1622              : bool
    1623     31129204 : MSVehicle::keepStopping(bool afterProcessing) const {
    1624     31129204 :     if (isStopped()) {
    1625              :         // when coming out of vehicleTransfer we must shift the time forward
    1626     37183790 :         return (myStops.front().duration - (afterProcessing ? DELTA_T : 0) > 0 || isStoppedTriggered() || myStops.front().pars.collision
    1627     30857803 :                 || myStops.front().pars.breakDown || (myStops.front().getSpeed() > 0
    1628        35771 :                         && (myState.myPos < MIN2(myStops.front().pars.endPos, myStops.front().lane->getLength() - POSITION_EPS))
    1629        29918 :                         && (myStops.front().pars.parking == ParkingType::ONROAD || getSpeed() >= SUMO_const_haltingSpeed)));
    1630              :     } else {
    1631              :         return false;
    1632              :     }
    1633              : }
    1634              : 
    1635              : 
    1636              : SUMOTime
    1637        16149 : MSVehicle::remainingStopDuration() const {
    1638        16149 :     if (isStopped()) {
    1639        16149 :         return myStops.front().duration;
    1640              :     }
    1641              :     return 0;
    1642              : }
    1643              : 
    1644              : 
    1645              : SUMOTime
    1646    684886730 : MSVehicle::collisionStopTime() const {
    1647    684886730 :     return (myStops.empty() || !myStops.front().pars.collision) ? myCollisionImmunity : MAX2((SUMOTime)0, myStops.front().duration);
    1648              : }
    1649              : 
    1650              : 
    1651              : bool
    1652    684749491 : MSVehicle::brokeDown() const {
    1653    684749491 :     return isStopped() && !myStops.empty() && myStops.front().pars.breakDown;
    1654              : }
    1655              : 
    1656              : 
    1657              : bool
    1658       169772 : MSVehicle::ignoreCollision() const {
    1659       169772 :     return myCollisionImmunity > 0;
    1660              : }
    1661              : 
    1662              : 
    1663              : double
    1664    648511732 : MSVehicle::processNextStop(double currentVelocity) {
    1665    648511732 :     if (myStops.empty()) {
    1666              :         // no stops; pass
    1667              :         return currentVelocity;
    1668              :     }
    1669              : 
    1670              : #ifdef DEBUG_STOPS
    1671              :     if (DEBUG_COND) {
    1672              :         std::cout << "\nPROCESS_NEXT_STOP\n" << SIMTIME << " vehicle '" << getID() << "'" << std::endl;
    1673              :     }
    1674              : #endif
    1675              : 
    1676              :     MSStop& stop = myStops.front();
    1677     41386333 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1678     41386333 :     if (stop.reached) {
    1679     25967051 :         stop.duration -= getActionStepLength();
    1680     25967051 :         if (getSpeed() > 0) {
    1681              :             // re-enter stopping places to correct waiting position (except for parkingArea since it's place-based)
    1682      3734095 :             if (stop.busstop != nullptr) {
    1683              :                 // let the bus stop know the vehicle
    1684        12979 :                 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1685              :             }
    1686      3734095 :             if (stop.containerstop != nullptr) {
    1687              :                 // let the container stop know the vehicle
    1688      3688548 :                 stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1689              :             }
    1690      3734095 :             if (stop.chargingStation != nullptr) {
    1691              :                 // let the container stop know the vehicle
    1692         3057 :                 stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1693              :             }
    1694      3734095 :             if (stop.getSpeed() <= 0) {
    1695      3716925 :                 stop.entryPos = getPositionOnLane();
    1696              :             }
    1697              :         }
    1698              : 
    1699              : #ifdef DEBUG_STOPS
    1700              :         if (DEBUG_COND) {
    1701              :             std::cout << SIMTIME << " vehicle '" << getID() << "' reached stop.\n"
    1702              :                       << "Remaining duration: " << STEPS2TIME(stop.duration) << std::endl;
    1703              :             if (stop.getSpeed() > 0) {
    1704              :                 std::cout << " waypointSpeed=" << stop.getSpeed() << " vehPos=" << myState.myPos << " endPos=" << stop.pars.endPos << "\n";
    1705              :             }
    1706              :         }
    1707              : #endif
    1708     25967051 :         if (stop.duration <= 0 && stop.pars.join != "") {
    1709              :             // join this train (part) to another one
    1710        37478 :             MSVehicle* joinVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.join));
    1711          969 :             if (joinVeh && joinVeh->hasDeparted() && (joinVeh->joinTrainPart(this) || joinVeh->joinTrainPartFront(this))) {
    1712           36 :                 stop.joinTriggered = false;
    1713           36 :                 if (myAmRegisteredAsWaiting) {
    1714           21 :                     MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1715           21 :                     myAmRegisteredAsWaiting = false;
    1716              :                 }
    1717              :                 // avoid collision warning before this vehicle is removed (joinVeh was already made longer)
    1718           36 :                 myCollisionImmunity = TIME2STEPS(100);
    1719              :                 // mark this vehicle as arrived
    1720           36 :                 myArrivalPos = getPositionOnLane();
    1721           36 :                 const_cast<SUMOVehicleParameter*>(myParameter)->arrivalEdge = getRoutePosition();
    1722              :                 // handle transportables that want to continue in the other vehicle
    1723           36 :                 if (myPersonDevice != nullptr) {
    1724            3 :                     myPersonDevice->transferAtSplitOrJoin(joinVeh);
    1725              :                 }
    1726           36 :                 if (myContainerDevice != nullptr) {
    1727            3 :                     myContainerDevice->transferAtSplitOrJoin(joinVeh);
    1728              :                 }
    1729              :             }
    1730              :         }
    1731     25967051 :         boardTransportables(stop);
    1732     22278909 :         if (time > stop.endBoarding) {
    1733              :             // for taxi: cancel customers
    1734       198308 :             MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1735              :             if (taxiDevice != nullptr) {
    1736              :                 // may invalidate stops including the current reference
    1737           64 :                 taxiDevice->cancelCurrentCustomers();
    1738           64 :                 resumeFromStopping();
    1739           64 :                 return currentVelocity;
    1740              :             }
    1741              :         }
    1742     22278845 :         if (!keepStopping() && isOnRoad()) {
    1743              : #ifdef DEBUG_STOPS
    1744              :             if (DEBUG_COND) {
    1745              :                 std::cout << SIMTIME << " vehicle '" << getID() << "' resumes from stopping." << std::endl;
    1746              :             }
    1747              : #endif
    1748        44723 :             resumeFromStopping();
    1749        44723 :             if (isRail() && hasStops()) {
    1750              :                 // stay on the current lane in case of a double stop
    1751         3132 :                 const MSStop& nextStop = getNextStop();
    1752         3132 :                 if (nextStop.edge == myCurrEdge) {
    1753         1079 :                     const double stopSpeed = getCarFollowModel().stopSpeed(this, getSpeed(), nextStop.pars.endPos - myState.myPos);
    1754              :                     //std::cout << SIMTIME << " veh=" << getID() << " resumedFromStopping currentVelocity=" << currentVelocity << " stopSpeed=" << stopSpeed << "\n";
    1755         1079 :                     return stopSpeed;
    1756              :                 }
    1757              :             }
    1758              :         } else {
    1759     22234122 :             if (stop.triggered) {
    1760      3239471 :                 if (getVehicleType().getPersonCapacity() == getPersonNumber()) {
    1761           30 :                     WRITE_WARNINGF(TL("Vehicle '%' ignores triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
    1762           10 :                     stop.triggered = false;
    1763      3239461 :                 } else if (!myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
    1764              :                     // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
    1765         4344 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1766         4344 :                     myAmRegisteredAsWaiting = true;
    1767              : #ifdef DEBUG_STOPS
    1768              :                     if (DEBUG_COND) {
    1769              :                         std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for person." << std::endl;
    1770              :                     }
    1771              : #endif
    1772              :                 }
    1773              :             }
    1774     22234122 :             if (stop.containerTriggered) {
    1775        39500 :                 if (getVehicleType().getContainerCapacity() == getContainerNumber()) {
    1776         1332 :                     WRITE_WARNINGF(TL("Vehicle '%' ignores container triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
    1777          444 :                     stop.containerTriggered = false;
    1778        39056 :                 } else if (stop.containerTriggered && !myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
    1779              :                     // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
    1780           92 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1781           92 :                     myAmRegisteredAsWaiting = true;
    1782              : #ifdef DEBUG_STOPS
    1783              :                     if (DEBUG_COND) {
    1784              :                         std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for container." << std::endl;
    1785              :                     }
    1786              : #endif
    1787              :                 }
    1788              :             }
    1789              :             // joining only takes place after stop duration is over
    1790     22234122 :             if (stop.joinTriggered && !myAmRegisteredAsWaiting
    1791         7199 :                     && stop.duration <= (stop.pars.extension >= 0 ? -stop.pars.extension : 0)) {
    1792          101 :                 if (stop.pars.extension >= 0) {
    1793          108 :                     WRITE_WARNINGF(TL("Vehicle '%' aborts joining after extension of %s at time %."), getID(), STEPS2TIME(stop.pars.extension), time2string(SIMSTEP));
    1794           36 :                     stop.joinTriggered = false;
    1795              :                 } else {
    1796              :                     // keep stopping indefinitely but ensure that simulation terminates
    1797           65 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1798           65 :                     myAmRegisteredAsWaiting = true;
    1799              :                 }
    1800              :             }
    1801     22234122 :             if (stop.getSpeed() > 0) {
    1802              :                 //waypoint mode
    1803       219665 :                 if (stop.duration == 0) {
    1804          243 :                     return stop.getSpeed();
    1805              :                 } else {
    1806              :                     // stop for 'until' (computed in planMove)
    1807              :                     return currentVelocity;
    1808              :                 }
    1809              :             } else {
    1810              :                 // brake
    1811     22014457 :                 if (MSGlobals::gSemiImplicitEulerUpdate || stop.getSpeed() > 0) {
    1812     21745360 :                     return 0;
    1813              :                 } else {
    1814              :                     // ballistic:
    1815       269097 :                     return getSpeed() - getCarFollowModel().getMaxDecel();
    1816              :                 }
    1817              :             }
    1818              :         }
    1819              :     } else {
    1820              : 
    1821              : #ifdef DEBUG_STOPS
    1822              :         if (DEBUG_COND) {
    1823              :             std::cout << SIMTIME << " vehicle '" << getID() << "' hasn't reached next stop." << std::endl;
    1824              :         }
    1825              : #endif
    1826              :         //std::cout << SIMTIME <<  " myStopDist=" << myStopDist << " bGap=" << getBrakeGap(myLane->getVehicleMaxSpeed(this)) << "\n";
    1827     15481810 :         if (stop.pars.onDemand && !stop.skipOnDemand && myStopDist <= getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this))) {
    1828          577 :             MSNet* const net = MSNet::getInstance();
    1829           44 :             const bool noExits = ((myPersonDevice == nullptr || !myPersonDevice->anyLeavingAtStop(stop))
    1830          587 :                                   && (myContainerDevice == nullptr || !myContainerDevice->anyLeavingAtStop(stop)));
    1831           83 :             const bool noEntries = ((!net->hasPersons() || !net->getPersonControl().hasAnyWaiting(stop.getEdge(), this))
    1832          626 :                                     && (!net->hasContainers() || !net->getContainerControl().hasAnyWaiting(stop.getEdge(), this)));
    1833          577 :             if (noExits && noEntries) {
    1834              :                 //std::cout << " skipOnDemand\n";
    1835          509 :                 stop.skipOnDemand = true;
    1836              :                 // bestLanes must be extended past this stop
    1837          509 :                 updateBestLanes(true);
    1838              :             }
    1839              :         }
    1840              :         // is the next stop on the current lane?
    1841     15419282 :         if (stop.edge == myCurrEdge) {
    1842              :             // get the stopping position
    1843      5582830 :             bool useStoppingPlace = stop.busstop != nullptr || stop.containerstop != nullptr || stop.parkingarea != nullptr;
    1844              :             bool fitsOnStoppingPlace = true;
    1845      5582830 :             if (!stop.skipOnDemand) {  // no need to check available space if we skip it anyway
    1846      5577038 :                 if (stop.busstop != nullptr) {
    1847      1711648 :                     fitsOnStoppingPlace &= stop.busstop->fits(myState.myPos, *this);
    1848              :                 }
    1849      5577038 :                 if (stop.containerstop != nullptr) {
    1850        21791 :                     fitsOnStoppingPlace &= stop.containerstop->fits(myState.myPos, *this);
    1851              :                 }
    1852              :                 // if the stop is a parking area we check if there is a free position on the area
    1853      5577038 :                 if (stop.parkingarea != nullptr) {
    1854       683604 :                     fitsOnStoppingPlace &= myState.myPos > stop.parkingarea->getBeginLanePosition();
    1855       683604 :                     if (stop.parkingarea->getOccupancy() >= stop.parkingarea->getCapacity()) {
    1856              :                         fitsOnStoppingPlace = false;
    1857              :                         // trigger potential parkingZoneReroute
    1858       434958 :                         MSParkingArea* oldParkingArea = stop.parkingarea;
    1859       476126 :                         for (MSMoveReminder* rem : myLane->getMoveReminders()) {
    1860        41168 :                             if (rem->isParkingRerouter()) {
    1861        19940 :                                 rem->notifyEnter(*this, MSMoveReminder::NOTIFICATION_PARKING_REROUTE, myLane);
    1862              :                             }
    1863              :                         }
    1864       434958 :                         if (myStops.empty() || myStops.front().parkingarea != oldParkingArea) {
    1865              :                             // rerouted, keep driving
    1866              :                             return currentVelocity;
    1867              :                         }
    1868       248646 :                     } else if (stop.parkingarea->getOccupancyIncludingReservations(this) >= stop.parkingarea->getCapacity()) {
    1869              :                         fitsOnStoppingPlace = false;
    1870       117238 :                     } else if (stop.parkingarea->parkOnRoad() && stop.parkingarea->getLotIndex(this) < 0) {
    1871              :                         fitsOnStoppingPlace = false;
    1872              :                     }
    1873              :                 }
    1874              :             }
    1875      5581050 :             const double targetPos = myState.myPos + myStopDist + (stop.getSpeed() > 0 ? (stop.pars.startPos - stop.pars.endPos) : 0);
    1876      5581050 :             double reachedThreshold = (useStoppingPlace ? targetPos - STOPPING_PLACE_OFFSET : stop.getReachedThreshold()) - NUMERICAL_EPS;
    1877      5581050 :             if (stop.busstop != nullptr && stop.getSpeed() <= 0 && getWaitingTime() > DELTA_T && myLane == stop.lane) {
    1878              :                 // count (long) busStop as reached when fully within and jammed before the designated spot
    1879       818773 :                 reachedThreshold = MIN2(reachedThreshold, stop.pars.startPos + getLength());
    1880              :             }
    1881      5581050 :             const bool posReached = myState.pos() >= reachedThreshold && currentVelocity <= stop.getSpeed() + SUMO_const_haltingSpeed && myLane == stop.lane;
    1882              : #ifdef DEBUG_STOPS
    1883              :             if (DEBUG_COND) {
    1884              :                 std::cout <<  "   pos=" << myState.pos() << " speed=" << currentVelocity << " targetPos=" << targetPos << " fits=" << fitsOnStoppingPlace
    1885              :                           << " reachedThresh=" << reachedThreshold
    1886              :                           << " posReached=" << posReached
    1887              :                           << " myLane=" << Named::getIDSecure(myLane)
    1888              :                           << " stopLane=" << Named::getIDSecure(stop.lane)
    1889              :                           << "\n";
    1890              :             }
    1891              : #endif
    1892      5581050 :             if (posReached && !fitsOnStoppingPlace && MSStopOut::active()) {
    1893         5890 :                 MSStopOut::getInstance()->stopBlocked(this, time);
    1894              :             }
    1895      5581050 :             if (fitsOnStoppingPlace && posReached && (!MSGlobals::gModelParkingManoeuver || myManoeuvre.entryManoeuvreIsComplete(this))) {
    1896              :                 // ok, we may stop (have reached the stop)  and either we are not modelling maneuvering or have completed entry
    1897        56854 :                 stop.reached = true;
    1898        56854 :                 if (!stop.startedFromState) {
    1899        56620 :                     stop.pars.started = time;
    1900              :                 }
    1901              : #ifdef DEBUG_STOPS
    1902              :                 if (DEBUG_COND) {
    1903              :                     std::cout << SIMTIME << " vehicle '" << getID() << "' reached next stop." << std::endl;
    1904              :                 }
    1905              : #endif
    1906        56854 :                 if (MSStopOut::active()) {
    1907         5635 :                     MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), time);
    1908              :                 }
    1909        56854 :                 myLane->getEdge().addWaiting(this);
    1910        56854 :                 MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::STARTING_STOP);
    1911        56854 :                 MSNet::getInstance()->getVehicleControl().registerStopStarted();
    1912              :                 // compute stopping time
    1913        56854 :                 stop.duration = stop.getMinDuration(time);
    1914        56854 :                 stop.endBoarding = stop.pars.extension >= 0 ? time + stop.duration + stop.pars.extension : SUMOTime_MAX;
    1915        56854 :                 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1916         4153 :                 if (taxiDevice != nullptr && stop.pars.extension >= 0) {
    1917              :                     // earliestPickupTime is set with waitUntil
    1918           84 :                     stop.endBoarding = MAX2(time, stop.pars.waitUntil) + stop.pars.extension;
    1919              :                 }
    1920        56854 :                 if (stop.getSpeed() > 0) {
    1921              :                     // ignore duration parameter in waypoint mode unless 'until' or 'ended' are set
    1922         3429 :                     if (stop.getUntil() > time) {
    1923          348 :                         stop.duration = stop.getUntil() - time;
    1924              :                     } else {
    1925         3081 :                         stop.duration = 0;
    1926              :                     }
    1927              :                 } else {
    1928        53425 :                     stop.entryPos = getPositionOnLane();
    1929              :                 }
    1930        56854 :                 if (stop.busstop != nullptr) {
    1931              :                     // let the bus stop know the vehicle
    1932        18782 :                     stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1933              :                 }
    1934        56854 :                 if (stop.containerstop != nullptr) {
    1935              :                     // let the container stop know the vehicle
    1936          571 :                     stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1937              :                 }
    1938        56854 :                 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    1939              :                     // let the parking area know the vehicle
    1940         9867 :                     stop.parkingarea->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1941              :                 }
    1942        56854 :                 if (stop.chargingStation != nullptr) {
    1943              :                     // let the container stop know the vehicle
    1944         3567 :                     stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1945              :                 }
    1946              : 
    1947        56854 :                 if (stop.pars.tripId != "") {
    1948         2922 :                     ((SUMOVehicleParameter&)getParameter()).setParameter("tripId", stop.pars.tripId);
    1949              :                 }
    1950        56854 :                 if (stop.pars.line != "") {
    1951         1464 :                     ((SUMOVehicleParameter&)getParameter()).line = stop.pars.line;
    1952              :                 }
    1953        56854 :                 if (stop.pars.split != "") {
    1954              :                     // split the train
    1955         1240 :                     MSVehicle* splitVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.split));
    1956           24 :                     if (splitVeh == nullptr) {
    1957         3648 :                         WRITE_WARNINGF(TL("Vehicle '%' to split from vehicle '%' is not known. time=%."), stop.pars.split, getID(), SIMTIME)
    1958              :                     } else {
    1959           24 :                         MSNet::getInstance()->getInsertionControl().add(splitVeh);
    1960           24 :                         splitVeh->getRoute().getEdges()[0]->removeWaiting(splitVeh);
    1961           24 :                         MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1962           24 :                         const double newLength = MAX2(myType->getLength() - splitVeh->getVehicleType().getLength(),
    1963           24 :                                                       myType->getParameter().locomotiveLength);
    1964           24 :                         getSingularType().setLength(newLength);
    1965              :                         // handle transportables that want to continue in the split part
    1966           24 :                         if (myPersonDevice != nullptr) {
    1967            0 :                             myPersonDevice->transferAtSplitOrJoin(splitVeh);
    1968              :                         }
    1969           24 :                         if (myContainerDevice != nullptr) {
    1970            6 :                             myContainerDevice->transferAtSplitOrJoin(splitVeh);
    1971              :                         }
    1972           24 :                         if (splitVeh->getParameter().departPosProcedure == DepartPosDefinition::SPLIT_FRONT) {
    1973            3 :                             const double backShift = splitVeh->getLength() + getVehicleType().getMinGap();
    1974            3 :                             myState.myPos -= backShift;
    1975            3 :                             myState.myBackPos -= backShift;
    1976              :                         }
    1977              :                     }
    1978              :                 }
    1979              : 
    1980        56854 :                 boardTransportables(stop);
    1981        56850 :                 if (stop.pars.posLat != INVALID_DOUBLE) {
    1982          231 :                     myState.myPosLat = stop.pars.posLat;
    1983              :                 }
    1984              :             }
    1985              :         }
    1986              :     }
    1987              :     return currentVelocity;
    1988              : }
    1989              : 
    1990              : 
    1991              : void
    1992     26023905 : MSVehicle::boardTransportables(MSStop& stop) {
    1993     26023905 :     if (stop.skipOnDemand) {
    1994              :         return;
    1995              :     }
    1996              :     // we have reached the stop
    1997              :     // any waiting persons may board now
    1998     25820697 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1999     25820697 :     MSNet* const net = MSNet::getInstance();
    2000     25820697 :     const bool boarded = (time <= stop.endBoarding
    2001     25819112 :                           && net->hasPersons()
    2002      1539952 :                           && net->getPersonControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToBoardNextPerson, stop.duration)
    2003     25828373 :                           && stop.numExpectedPerson == 0);
    2004              :     // load containers
    2005     25820697 :     const bool loaded = (time <= stop.endBoarding
    2006     25819112 :                          && net->hasContainers()
    2007      3790580 :                          && net->getContainerControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToLoadNextContainer, stop.duration)
    2008     25821272 :                          && stop.numExpectedContainer == 0);
    2009              : 
    2010              :     bool unregister = false;
    2011     22132551 :     if (time > stop.endBoarding) {
    2012         1585 :         stop.triggered = false;
    2013         1585 :         stop.containerTriggered = false;
    2014         1585 :         if (myAmRegisteredAsWaiting) {
    2015              :             unregister = true;
    2016          328 :             myAmRegisteredAsWaiting = false;
    2017              :         }
    2018              :     }
    2019     22132551 :     if (boarded) {
    2020              :         // the triggering condition has been fulfilled. Maybe we want to wait a bit longer for additional riders (car pooling)
    2021         7537 :         if (myAmRegisteredAsWaiting) {
    2022              :             unregister = true;
    2023              :         }
    2024         7537 :         stop.triggered = false;
    2025         7537 :         myAmRegisteredAsWaiting = false;
    2026              :     }
    2027     22132551 :     if (loaded) {
    2028              :         // the triggering condition has been fulfilled
    2029          555 :         if (myAmRegisteredAsWaiting) {
    2030              :             unregister = true;
    2031              :         }
    2032          555 :         stop.containerTriggered = false;
    2033          555 :         myAmRegisteredAsWaiting = false;
    2034              :     }
    2035              : 
    2036     22132551 :     if (unregister) {
    2037          412 :         MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2038              : #ifdef DEBUG_STOPS
    2039              :         if (DEBUG_COND) {
    2040              :             std::cout << SIMTIME << " vehicle '" << getID() << "' unregisters as waiting for transportable." << std::endl;
    2041              :         }
    2042              : #endif
    2043              :     }
    2044              : }
    2045              : 
    2046              : bool
    2047          921 : MSVehicle::joinTrainPart(MSVehicle* veh) {
    2048              :     // check if veh is close enough to be joined to the rear of this vehicle
    2049          921 :     MSLane* backLane = myFurtherLanes.size() == 0 ? myLane : myFurtherLanes.back();
    2050          921 :     double gap = getBackPositionOnLane() - veh->getPositionOnLane();
    2051         1144 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == veh->getLane()
    2052          951 :             && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
    2053           15 :         const double newLength = myType->getLength() + veh->getVehicleType().getLength();
    2054           15 :         getSingularType().setLength(newLength);
    2055           15 :         myStops.begin()->joinTriggered = false;
    2056           15 :         if (myAmRegisteredAsWaiting) {
    2057            0 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2058            0 :             myAmRegisteredAsWaiting = false;
    2059              :         }
    2060              :         return true;
    2061              :     } else {
    2062          906 :         return false;
    2063              :     }
    2064              : }
    2065              : 
    2066              : 
    2067              : bool
    2068          906 : MSVehicle::joinTrainPartFront(MSVehicle* veh) {
    2069              :     // check if veh is close enough to be joined to the front of this vehicle
    2070          906 :     MSLane* backLane = veh->myFurtherLanes.size() == 0 ? veh->myLane : veh->myFurtherLanes.back();
    2071          906 :     double gap = veh->getBackPositionOnLane(backLane) - getPositionOnLane();
    2072         1114 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == getLane()
    2073          930 :             && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
    2074              :         double skippedLaneLengths = 0;
    2075           24 :         if (veh->myFurtherLanes.size() > 0) {
    2076            9 :             skippedLaneLengths += getLane()->getLength();
    2077              :             // this vehicle must be moved to the lane of veh
    2078              :             // ensure that lane and furtherLanes of veh match our route
    2079            9 :             int routeIndex = getRoutePosition();
    2080            9 :             if (myLane->isInternal()) {
    2081            0 :                 routeIndex++;
    2082              :             }
    2083           27 :             for (int i = (int)veh->myFurtherLanes.size() - 1; i >= 0; i--) {
    2084           18 :                 MSEdge* edge = &veh->myFurtherLanes[i]->getEdge();
    2085           18 :                 if (edge->isInternal()) {
    2086            9 :                     continue;
    2087              :                 }
    2088            9 :                 if (!edge->isInternal() && edge != myRoute->getEdges()[routeIndex]) {
    2089            0 :                     std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
    2090            0 :                     WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
    2091              :                     return false;
    2092              :                 }
    2093            9 :                 routeIndex++;
    2094              :             }
    2095            9 :             if (veh->getCurrentEdge()->getNormalSuccessor() != myRoute->getEdges()[routeIndex]) {
    2096            3 :                 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
    2097            9 :                 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
    2098              :                 return false;
    2099              :             }
    2100           12 :             for (int i = (int)veh->myFurtherLanes.size() - 2; i >= 0; i--) {
    2101            6 :                 skippedLaneLengths += veh->myFurtherLanes[i]->getLength();
    2102              :             }
    2103              :         }
    2104              : 
    2105           21 :         const double newLength = myType->getLength() + veh->getVehicleType().getLength();
    2106           21 :         getSingularType().setLength(newLength);
    2107              :         // lane will be advanced just as for regular movement
    2108           21 :         myState.myPos = skippedLaneLengths + veh->getPositionOnLane();
    2109           21 :         myStops.begin()->joinTriggered = false;
    2110           21 :         if (myAmRegisteredAsWaiting) {
    2111            8 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2112            8 :             myAmRegisteredAsWaiting = false;
    2113              :         }
    2114           21 :         return true;
    2115              :     } else {
    2116          882 :         return false;
    2117              :     }
    2118              : }
    2119              : 
    2120              : double
    2121      9006605 : MSVehicle::getBrakeGap(bool delayed) const {
    2122      9006605 :     return getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), delayed ? getCarFollowModel().getHeadwayTime() : 0);
    2123              : }
    2124              : 
    2125              : 
    2126              : bool
    2127    708659388 : MSVehicle::checkActionStep(const SUMOTime t) {
    2128    708659388 :     myActionStep = isActionStep(t);
    2129    708659388 :     if (myActionStep) {
    2130    637097452 :         myLastActionTime = t;
    2131              :     }
    2132    708659388 :     return myActionStep;
    2133              : }
    2134              : 
    2135              : 
    2136              : void
    2137         1470 : MSVehicle::resetActionOffset(const SUMOTime timeUntilNextAction) {
    2138         1470 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + timeUntilNextAction;
    2139         1470 : }
    2140              : 
    2141              : 
    2142              : void
    2143            1 : MSVehicle::updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength) {
    2144            1 :     SUMOTime now = MSNet::getInstance()->getCurrentTimeStep();
    2145            1 :     SUMOTime timeSinceLastAction = now - myLastActionTime;
    2146            1 :     if (timeSinceLastAction == 0) {
    2147              :         // Action was scheduled now, may be delayed be new action step length
    2148              :         timeSinceLastAction = oldActionStepLength;
    2149              :     }
    2150            1 :     if (timeSinceLastAction >= newActionStepLength) {
    2151              :         // Action point required in this step
    2152            0 :         myLastActionTime = now;
    2153              :     } else {
    2154            1 :         SUMOTime timeUntilNextAction = newActionStepLength - timeSinceLastAction;
    2155            1 :         resetActionOffset(timeUntilNextAction);
    2156              :     }
    2157            1 : }
    2158              : 
    2159              : 
    2160              : 
    2161              : void
    2162    708659388 : MSVehicle::planMove(const SUMOTime t, const MSLeaderInfo& ahead, const double lengthsInFront) {
    2163              : #ifdef DEBUG_PLAN_MOVE
    2164              :     if (DEBUG_COND) {
    2165              :         std::cout
    2166              :                 << "\nPLAN_MOVE\n"
    2167              :                 << SIMTIME
    2168              :                 << std::setprecision(gPrecision)
    2169              :                 << " veh=" << getID()
    2170              :                 << " lane=" << myLane->getID()
    2171              :                 << " pos=" << getPositionOnLane()
    2172              :                 << " posLat=" << getLateralPositionOnLane()
    2173              :                 << " speed=" << getSpeed()
    2174              :                 << "\n";
    2175              :     }
    2176              : #endif
    2177              :     // Update the driver state
    2178    708659388 :     if (hasDriverState()) {
    2179       451354 :         myDriverState->update();
    2180       902708 :         setActionStepLength(myDriverState->getDriverState()->getActionStepLength(), false);
    2181              :     }
    2182              : 
    2183    708659388 :     myStopSpeed = getCarFollowModel().maxNextSpeed(myStopSpeed, this);
    2184    708659388 :     if (!checkActionStep(t)) {
    2185              : #ifdef DEBUG_ACTIONSTEPS
    2186              :         if (DEBUG_COND) {
    2187              :             std::cout << STEPS2TIME(t) << " vehicle '" << getID() << "' skips action." << std::endl;
    2188              :         }
    2189              : #endif
    2190              :         // During non-action passed drive items still need to be removed
    2191              :         // @todo rather work with updating myCurrentDriveItem (refs #3714)
    2192     71561936 :         removePassedDriveItems();
    2193     71561936 :         return;
    2194              :     } else {
    2195              : #ifdef DEBUG_ACTIONSTEPS
    2196              :         if (DEBUG_COND) {
    2197              :             std::cout << STEPS2TIME(t) << " vehicle = '" << getID() << "' takes action." << std::endl;
    2198              :         }
    2199              : #endif
    2200              :         myLFLinkLanesPrev.swap(myLFLinkLanes);
    2201    637097452 :         if (myInfluencer != nullptr) {
    2202       491830 :             myInfluencer->updateRemoteControlRoute(this);
    2203              :         }
    2204    637097452 :         planMoveInternal(t, ahead, myLFLinkLanes, myStopDist, myStopSpeed, myNextTurn);
    2205              : #ifdef DEBUG_PLAN_MOVE
    2206              :         if (DEBUG_COND) {
    2207              :             DriveItemVector::iterator i;
    2208              :             for (i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
    2209              :                 std::cout
    2210              :                         << " vPass=" << (*i).myVLinkPass
    2211              :                         << " vWait=" << (*i).myVLinkWait
    2212              :                         << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
    2213              :                         << " request=" << (*i).mySetRequest
    2214              :                         << "\n";
    2215              :             }
    2216              :         }
    2217              : #endif
    2218    637097452 :         checkRewindLinkLanes(lengthsInFront, myLFLinkLanes);
    2219    637097452 :         myNextDriveItem = myLFLinkLanes.begin();
    2220              :         // ideally would only do this with the call inside planMoveInternal - but that needs a const method
    2221              :         //   so this is a kludge here - nuisance as it adds an extra check in a busy loop
    2222    637097452 :         if (MSGlobals::gModelParkingManoeuver) {
    2223         2971 :             if (getManoeuvreType() == MSVehicle::MANOEUVRE_EXIT && manoeuvreIsComplete()) {
    2224           30 :                 setManoeuvreType(MSVehicle::MANOEUVRE_NONE);
    2225              :             }
    2226              :         }
    2227              :     }
    2228    637097452 :     myLaneChangeModel->resetChanged();
    2229              : }
    2230              : 
    2231              : 
    2232              : bool
    2233    178191208 : MSVehicle::brakeForOverlap(const MSLink* link, const MSLane* lane) const {
    2234              :     // @review needed
    2235              :     //const double futurePosLat = getLateralPositionOnLane() + link->getLateralShift();
    2236              :     //const double overlap = getLateralOverlap(futurePosLat, link->getViaLaneOrLane());
    2237              :     //const double edgeWidth = link->getViaLaneOrLane()->getEdge().getWidth();
    2238    178191208 :     const double futurePosLat = getLateralPositionOnLane() + (
    2239    178191208 :                                     lane != myLane && lane->isInternal() ? lane->getIncomingLanes()[0].viaLink->getLateralShift() : 0);
    2240    178191208 :     const double overlap = getLateralOverlap(futurePosLat, lane);
    2241              :     const double edgeWidth = lane->getEdge().getWidth();
    2242              :     const bool result = (overlap > POSITION_EPS
    2243              :                          // do not get stuck on narrow edges
    2244      3095680 :                          && getVehicleType().getWidth() <= edgeWidth
    2245      3090075 :                          && link->getViaLane() == nullptr
    2246              :                          // this is the exit link of a junction. The normal edge should support the shadow
    2247      1505168 :                          && ((myLaneChangeModel->getShadowLane(link->getLane()) == nullptr)
    2248              :                              // the shadow lane must be permitted
    2249      1118832 :                              || !myLaneChangeModel->getShadowLane(link->getLane())->allowsVehicleClass(getVClass())
    2250              :                              // the internal lane after an internal junction has no parallel lane. make sure there is no shadow before continuing
    2251      1058487 :                              || (lane->getEdge().isInternal() && lane->getIncomingLanes()[0].lane->getEdge().isInternal()))
    2252              :                          // ignore situations where the shadow lane is part of a double-connection with the current lane
    2253       466341 :                          && (myLaneChangeModel->getShadowLane() == nullptr
    2254       255142 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().size() == 0
    2255       237603 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().front()->getLane() != link->getLane())
    2256              :                          // emergency vehicles may do some crazy stuff
    2257    178595732 :                          && !myLaneChangeModel->hasBlueLight());
    2258              : 
    2259              : #ifdef DEBUG_PLAN_MOVE
    2260              :     if (DEBUG_COND) {
    2261              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getDescription() << " lane=" << lane->getID()
    2262              :                   << " linkLane=" << link->getLane()->getID()
    2263              :                   << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    2264              :                   << " shift=" << link->getLateralShift()
    2265              :                   << " fpLat=" << futurePosLat << " overlap=" << overlap << " w=" << getVehicleType().getWidth()
    2266              :                   << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane(link->getLane()))
    2267              :                   << " result=" << result << "\n";
    2268              :     }
    2269              : #endif
    2270    178191208 :     return result;
    2271              : }
    2272              : 
    2273              : 
    2274              : 
    2275              : void
    2276    637097452 : MSVehicle::planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector& lfLinks, double& newStopDist, double& newStopSpeed, std::pair<double, const MSLink*>& nextTurn) const {
    2277              :     lfLinks.clear();
    2278    637097452 :     newStopDist = std::numeric_limits<double>::max();
    2279              :     //
    2280              :     const MSCFModel& cfModel = getCarFollowModel();
    2281    637097452 :     const double vehicleLength = getVehicleType().getLength();
    2282    637097452 :     const double maxV = cfModel.maxNextSpeed(myState.mySpeed, this);
    2283    637097452 :     const double maxVD = MAX2(getMaxSpeed(), MIN2(maxV, getDesiredMaxSpeed()));
    2284    637097452 :     const bool opposite = myLaneChangeModel->isOpposite();
    2285              :     // maxVD is possibly higher than vType-maxSpeed and in this case laneMaxV may be higher as well
    2286    637097452 :     double laneMaxV = myLane->getVehicleMaxSpeed(this, maxVD);
    2287    637097452 :     const double vMinComfortable = cfModel.minNextSpeed(getSpeed(), this);
    2288              :     double lateralShift = 0;
    2289    637097452 :     if (isRail()) {
    2290              :         // speed limits must hold for the whole length of the train
    2291      1791584 :         for (MSLane* l : myFurtherLanes) {
    2292       404529 :             laneMaxV = MIN2(laneMaxV, l->getVehicleMaxSpeed(this, maxVD));
    2293              : #ifdef DEBUG_PLAN_MOVE
    2294              :             if (DEBUG_COND) {
    2295              :                 std::cout << "   laneMaxV=" << laneMaxV << " lane=" << l->getID() << "\n";
    2296              :             }
    2297              : #endif
    2298              :         }
    2299              :     }
    2300              :     //  speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
    2301              :     laneMaxV = MAX2(laneMaxV, vMinComfortable);
    2302    637589250 :     if (myInfluencer && !myInfluencer->considerSpeedLimit()) {
    2303              :         laneMaxV = std::numeric_limits<double>::max();
    2304              :     }
    2305              :     // v is the initial maximum velocity of this vehicle in this step
    2306    637097452 :     double v = cfModel.maximumLaneSpeedCF(this, maxV, laneMaxV);
    2307              :     // if we are modelling parking then we dawdle until the manoeuvre is complete - by setting a very low max speed
    2308              :     //   in practice this only applies to exit manoeuvre because entry manoeuvre just delays setting stop.reached - when the vehicle is virtually stopped
    2309    637097452 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    2310          420 :         v = NUMERICAL_EPS_SPEED;
    2311              :     }
    2312              : 
    2313    637097452 :     if (myInfluencer != nullptr) {
    2314       491830 :         const double vMin = MAX2(0., cfModel.minNextSpeed(myState.mySpeed, this));
    2315              : #ifdef DEBUG_TRACI
    2316              :         if (DEBUG_COND) {
    2317              :             std::cout << SIMTIME << " veh=" << getID() << " speedBeforeTraci=" << v;
    2318              :         }
    2319              : #endif
    2320       491830 :         v = myInfluencer->influenceSpeed(t, v, v, vMin, maxV);
    2321              : #ifdef DEBUG_TRACI
    2322              :         if (DEBUG_COND) {
    2323              :             std::cout << " influencedSpeed=" << v;
    2324              :         }
    2325              : #endif
    2326       491830 :         v = myInfluencer->gapControlSpeed(t, this, v, v, vMin, maxV);
    2327              : #ifdef DEBUG_TRACI
    2328              :         if (DEBUG_COND) {
    2329              :             std::cout << " gapControlSpeed=" << v << "\n";
    2330              :         }
    2331              : #endif
    2332              :     }
    2333              :     // all links within dist are taken into account (potentially)
    2334    637097452 :     const double dist = SPEED2DIST(maxV) + cfModel.brakeGap(maxV);
    2335              : 
    2336    637097452 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation();
    2337              : #ifdef DEBUG_PLAN_MOVE
    2338              :     if (DEBUG_COND) {
    2339              :         std::cout << "   dist=" << dist << " bestLaneConts=" << toString(bestLaneConts)
    2340              :                   << "\n   maxV=" << maxV << " laneMaxV=" << laneMaxV << " v=" << v << "\n";
    2341              :     }
    2342              : #endif
    2343              :     assert(bestLaneConts.size() > 0);
    2344              :     bool hadNonInternal = false;
    2345              :     // the distance already "seen"; in the following always up to the end of the current "lane"
    2346    637097452 :     double seen = opposite ? myState.myPos : myLane->getLength() - myState.myPos;
    2347    637097452 :     nextTurn.first = seen;
    2348    637097452 :     nextTurn.second = nullptr;
    2349    637097452 :     bool encounteredTurn = (MSGlobals::gLateralResolution <= 0); // next turn is only needed for sublane
    2350              :     double seenNonInternal = 0;
    2351    637097452 :     double seenInternal = myLane->isInternal() ? seen : 0;
    2352    637097452 :     double vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(seen, v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    2353              :     int view = 0;
    2354              :     DriveProcessItem* lastLink = nullptr;
    2355              :     bool slowedDownForMinor = false; // whether the vehicle already had to slow down on approach to a minor link
    2356              :     double mustSeeBeforeReversal = 0;
    2357              :     // iterator over subsequent lanes and fill lfLinks until stopping distance or stopped
    2358    637097452 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : myLane;
    2359              :     assert(lane != 0);
    2360    637097452 :     const MSLane* leaderLane = myLane;
    2361    637097452 :     bool foundRailSignal = !isRail();
    2362              :     bool planningToStop = false;
    2363              : #ifdef PARALLEL_STOPWATCH
    2364              :     myLane->getStopWatch()[0].start();
    2365              : #endif
    2366              : 
    2367              :     // optionally slow down to match arrival time
    2368    637097452 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    2369    637087160 :     if (v > vMinComfortable && hasStops() && myStops.front().pars.arrival >= 0 && sfp > 0
    2370         4279 :             && v > myLane->getSpeedLimit() * sfp
    2371    637100488 :             && !myStops.front().reached) {
    2372         2786 :         const double vSlowDown = slowDownForSchedule(vMinComfortable);
    2373         5403 :         v = MIN2(v, vSlowDown);
    2374              :     }
    2375              :     auto stopIt = myStops.begin();
    2376              :     while (true) {
    2377              :         // check leader on lane
    2378              :         //  leader is given for the first edge only
    2379   1232801126 :         if (opposite &&
    2380              :                 (leaderLane->getVehicleNumberWithPartials() > 1
    2381       104110 :                  || (leaderLane != myLane && leaderLane->getVehicleNumber() > 0))) {
    2382       397523 :             ahead.clear();
    2383              :             // find opposite-driving leader that must be respected on the currently looked at lane
    2384              :             // (only looking at one lane at a time)
    2385       397523 :             const double backOffset = leaderLane == myLane ? getPositionOnLane() : leaderLane->getLength();
    2386       397523 :             const double gapOffset = leaderLane == myLane ? 0 : seen - leaderLane->getLength();
    2387       397523 :             const MSLeaderDistanceInfo cands = leaderLane->getFollowersOnConsecutive(this, backOffset, true, backOffset, MSLane::MinorLinkMode::FOLLOW_NEVER);
    2388       397523 :             MSLeaderDistanceInfo oppositeLeaders(leaderLane->getWidth(), this, 0.);
    2389       397523 :             const double minTimeToLeaveLane = MSGlobals::gSublane ? MAX2(TS, (0.5 *  myLane->getWidth() - getLateralPositionOnLane()) / getVehicleType().getMaxSpeedLat()) : TS;
    2390      1056009 :             for (int i = 0; i < cands.numSublanes(); i++) {
    2391       658486 :                 CLeaderDist cand = cands[i];
    2392       658486 :                 if (cand.first != 0) {
    2393       541331 :                     if ((cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() != leaderLane)
    2394       541802 :                             || (!cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() == leaderLane)) {
    2395              :                         // respect leaders that also drive in the opposite direction (fully or with some overlap)
    2396       351466 :                         oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - getVehicleType().getMinGap() + cand.first->getVehicleType().getMinGap() - cand.first->getVehicleType().getLength());
    2397              :                     } else {
    2398              :                         // avoid frontal collision
    2399       346896 :                         const bool assumeStopped = cand.first->isStopped() || cand.first->getWaitingSeconds() > 1;
    2400       189865 :                         const double predMaxDist = cand.first->getSpeed() + (assumeStopped ? 0 : cand.first->getCarFollowModel().getMaxAccel()) * minTimeToLeaveLane;
    2401       189865 :                         if (cand.second >= 0 && (cand.second - v * minTimeToLeaveLane - predMaxDist < 0 || assumeStopped)) {
    2402        44653 :                             oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - predMaxDist - getVehicleType().getMinGap());
    2403              :                         }
    2404              :                     }
    2405              :                 }
    2406              :             }
    2407              : #ifdef DEBUG_PLAN_MOVE
    2408              :             if (DEBUG_COND) {
    2409              :                 std::cout <<  " leaderLane=" << leaderLane->getID() << " gapOffset=" << gapOffset << " minTimeToLeaveLane=" << minTimeToLeaveLane
    2410              :                           << " cands=" << cands.toString() << " oppositeLeaders=" <<  oppositeLeaders.toString() << "\n";
    2411              :             }
    2412              : #endif
    2413       397523 :             adaptToLeaderDistance(oppositeLeaders, 0, seen, lastLink, v, vLinkPass);
    2414       397523 :         } else {
    2415   1232403603 :             if (MSGlobals::gLateralResolution > 0 && myLaneChangeModel->getShadowLane() == nullptr) {
    2416    200912109 :                 const double rightOL = getRightSideOnLane(lane) + lateralShift;
    2417    200912109 :                 const double leftOL = getLeftSideOnLane(lane) + lateralShift;
    2418              :                 const bool outsideLeft = leftOL > lane->getWidth();
    2419              : #ifdef DEBUG_PLAN_MOVE
    2420              :                 if (DEBUG_COND) {
    2421              :                     std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " rightOL=" << rightOL << " leftOL=" << leftOL << "\n";
    2422              :                 }
    2423              : #endif
    2424    200912109 :                 if (rightOL < 0 || outsideLeft) {
    2425      1311403 :                     MSLeaderInfo outsideLeaders(lane->getWidth());
    2426              :                     // if ego is driving outside lane bounds we must consider
    2427              :                     // potential leaders that are also outside bounds
    2428              :                     int sublaneOffset = 0;
    2429      1311403 :                     if (outsideLeft) {
    2430       541870 :                         sublaneOffset = MIN2(-1, -(int)ceil((leftOL - lane->getWidth()) / MSGlobals::gLateralResolution));
    2431              :                     } else {
    2432       769533 :                         sublaneOffset = MAX2(1, (int)ceil(-rightOL / MSGlobals::gLateralResolution));
    2433              :                     }
    2434      1311403 :                     outsideLeaders.setSublaneOffset(sublaneOffset);
    2435              : #ifdef DEBUG_PLAN_MOVE
    2436              :                     if (DEBUG_COND) {
    2437              :                         std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " sublaneOffset=" << sublaneOffset << " outsideLeft=" << outsideLeft << "\n";
    2438              :                     }
    2439              : #endif
    2440      5431543 :                     for (const MSVehicle* cand : lane->getVehiclesSecure()) {
    2441      1485364 :                         if ((lane != myLane || cand->getPositionOnLane() > getPositionOnLane())
    2442      4751224 :                                 && ((!outsideLeft && cand->getLeftSideOnEdge() < 0)
    2443      3265772 :                                     || (outsideLeft && cand->getLeftSideOnEdge() > lane->getEdge().getWidth()))) {
    2444        97442 :                             outsideLeaders.addLeader(cand, true);
    2445              : #ifdef DEBUG_PLAN_MOVE
    2446              :                             if (DEBUG_COND) {
    2447              :                                 std::cout << " outsideLeader=" << cand->getID() << " ahead=" << outsideLeaders.toString() << "\n";
    2448              :                             }
    2449              : #endif
    2450              :                         }
    2451              :                     }
    2452      1311403 :                     lane->releaseVehicles();
    2453      1311403 :                     if (outsideLeaders.hasVehicles()) {
    2454        26262 :                         adaptToLeaders(outsideLeaders, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2455              :                     }
    2456      1311403 :                 }
    2457              :             }
    2458   1232403603 :             adaptToLeaders(ahead, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2459              :         }
    2460   1232801126 :         if (lastLink != nullptr) {
    2461   1121627418 :             lastLink->myVLinkWait = MIN2(lastLink->myVLinkWait, v);
    2462              :         }
    2463              : #ifdef DEBUG_PLAN_MOVE
    2464              :         if (DEBUG_COND) {
    2465              :             std::cout << "\nv = " << v << "\n";
    2466              : 
    2467              :         }
    2468              : #endif
    2469              :         // XXX efficiently adapt to shadow leaders using neighAhead by iteration over the whole edge in parallel (lanechanger-style)
    2470   1232801126 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    2471              :             // also slow down for leaders on the shadowLane relative to the current lane
    2472      5026357 :             const MSLane* shadowLane = myLaneChangeModel->getShadowLane(leaderLane);
    2473              :             if (shadowLane != nullptr
    2474      5026357 :                     && (MSGlobals::gLateralResolution > 0 || getLateralOverlap() > POSITION_EPS
    2475              :                         // continous lane change cannot be stopped so we must adapt to the leader on the target lane
    2476       191108 :                         || myLaneChangeModel->getLaneChangeCompletion() < 0.5)) {
    2477      4473514 :                 if ((&shadowLane->getEdge() == &leaderLane->getEdge() || myLaneChangeModel->isOpposite())) {
    2478      4430916 :                     double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    2479      4430916 :                     if (myLaneChangeModel->isOpposite()) {
    2480              :                         // ego posLat is added when retrieving sublanes but it
    2481              :                         // should be negated (subtract twice to compensate)
    2482       138584 :                         latOffset = ((myLane->getWidth() + shadowLane->getWidth()) * 0.5
    2483       138584 :                                      - 2 * getLateralPositionOnLane());
    2484              : 
    2485              :                     }
    2486      4430916 :                     MSLeaderInfo shadowLeaders = shadowLane->getLastVehicleInformation(this, latOffset, lane->getLength() - seen);
    2487              : #ifdef DEBUG_PLAN_MOVE
    2488              :                     if (DEBUG_COND && myLaneChangeModel->isOpposite()) {
    2489              :                         std::cout << SIMTIME << " opposite veh=" << getID() << " shadowLane=" << shadowLane->getID() << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
    2490              :                     }
    2491              : #endif
    2492      4430916 :                     if (myLaneChangeModel->isOpposite()) {
    2493              :                         // ignore oncoming vehicles on the shadow lane
    2494       138584 :                         shadowLeaders.removeOpposite(shadowLane);
    2495              :                     }
    2496      4430916 :                     const double turningDifference = MAX2(0.0, leaderLane->getLength() - shadowLane->getLength());
    2497      4430916 :                     adaptToLeaders(shadowLeaders, latOffset, seen - turningDifference, lastLink, shadowLane, v, vLinkPass);
    2498      4473514 :                 } else if (shadowLane == myLaneChangeModel->getShadowLane() && leaderLane == myLane) {
    2499              :                     // check for leader vehicles driving in the opposite direction on the opposite-direction shadow lane
    2500              :                     // (and thus in the same direction as ego)
    2501        30563 :                     MSLeaderDistanceInfo shadowLeaders = shadowLane->getFollowersOnConsecutive(this, myLane->getOppositePos(getPositionOnLane()), true);
    2502              :                     const double latOffset = 0;
    2503              : #ifdef DEBUG_PLAN_MOVE
    2504              :                     if (DEBUG_COND) {
    2505              :                         std::cout << SIMTIME << " opposite shadows veh=" << getID() << " shadowLane=" << shadowLane->getID()
    2506              :                                   << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
    2507              :                     }
    2508              : #endif
    2509        30563 :                     shadowLeaders.fixOppositeGaps(true);
    2510              : #ifdef DEBUG_PLAN_MOVE
    2511              :                     if (DEBUG_COND) {
    2512              :                         std::cout << "   shadowLeadersFixed=" << shadowLeaders.toString() << "\n";
    2513              :                     }
    2514              : #endif
    2515        30563 :                     adaptToLeaderDistance(shadowLeaders, latOffset, seen, lastLink, v, vLinkPass);
    2516        30563 :                 }
    2517              :             }
    2518              :         }
    2519              :         // adapt to pedestrians on the same lane
    2520   1232801126 :         if (lane->getEdge().getPersons().size() > 0 && lane->hasPedestrians()) {
    2521       193893 :             const double relativePos = lane->getLength() - seen;
    2522              : #ifdef DEBUG_PLAN_MOVE
    2523              :             if (DEBUG_COND) {
    2524              :                 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
    2525              :             }
    2526              : #endif
    2527       193893 :             const double stopTime = MAX2(1.0, ceil(getSpeed() / cfModel.getMaxDecel()));
    2528       193893 :             PersonDist leader = lane->nextBlocking(relativePos,
    2529       193893 :                                                    getRightSideOnLane(lane), getRightSideOnLane(lane) + getVehicleType().getWidth(), stopTime);
    2530       193893 :             if (leader.first != 0) {
    2531        20843 :                 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
    2532        29576 :                 v = MIN2(v, stopSpeed);
    2533              : #ifdef DEBUG_PLAN_MOVE
    2534              :                 if (DEBUG_COND) {
    2535              :                     std::cout << SIMTIME << "    pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
    2536              :                 }
    2537              : #endif
    2538              :             }
    2539              :         }
    2540   1232801126 :         if (lane->getBidiLane() != nullptr) {
    2541              :             // adapt to pedestrians on the bidi lane
    2542      5515772 :             const MSLane* bidiLane = lane->getBidiLane();
    2543      5515772 :             if (bidiLane->getEdge().getPersons().size() > 0 && bidiLane->hasPedestrians()) {
    2544         1028 :                 const double relativePos = seen;
    2545              : #ifdef DEBUG_PLAN_MOVE
    2546              :                 if (DEBUG_COND) {
    2547              :                     std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
    2548              :                 }
    2549              : #endif
    2550         1028 :                 const double stopTime = ceil(getSpeed() / cfModel.getMaxDecel());
    2551         1028 :                 const double leftSideOnLane = bidiLane->getWidth() - getRightSideOnLane(lane);
    2552         1028 :                 PersonDist leader = bidiLane->nextBlocking(relativePos,
    2553         1028 :                                     leftSideOnLane - getVehicleType().getWidth(), leftSideOnLane, stopTime, true);
    2554         1028 :                 if (leader.first != 0) {
    2555          267 :                     const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
    2556          524 :                     v = MIN2(v, stopSpeed);
    2557              : #ifdef DEBUG_PLAN_MOVE
    2558              :                     if (DEBUG_COND) {
    2559              :                         std::cout << SIMTIME << "    pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
    2560              :                     }
    2561              : #endif
    2562              :                 }
    2563              :             }
    2564              :         }
    2565              :         // adapt to vehicles blocked from (urgent) lane-changing
    2566   1232801126 :         if (!opposite && lane->getEdge().hasLaneChanger()) {
    2567    596399248 :             const double vHelp = myLaneChangeModel->getCooperativeHelpSpeed(lane, seen);
    2568              : #ifdef DEBUG_PLAN_MOVE
    2569              :             if (DEBUG_COND && vHelp < v) {
    2570              :                 std::cout << SIMTIME << "   applying cooperativeHelpSpeed v=" << vHelp << "\n";
    2571              :             }
    2572              : #endif
    2573    596479535 :             v = MIN2(v, vHelp);
    2574              :         }
    2575              : 
    2576              :         // process all stops and waypoints on the current edge
    2577              :         bool foundRealStop = false;
    2578              :         while (stopIt != myStops.end()
    2579     65844031 :                 && ((&stopIt->lane->getEdge() == &lane->getEdge())
    2580     33195758 :                     || (stopIt->isOpposite && stopIt->lane->getEdge().getOppositeEdge() == &lane->getEdge()))
    2581              :                 // ignore stops that occur later in a looped route
    2582   1288178877 :                 && stopIt->edge == myCurrEdge + view) {
    2583     32593072 :             double stopDist = std::numeric_limits<double>::max();
    2584              :             const MSStop& stop = *stopIt;
    2585              :             const bool isFirstStop = stopIt == myStops.begin();
    2586              :             stopIt++;
    2587     32593072 :             if (!stop.reached || (stop.getSpeed() > 0 && keepStopping())) {
    2588              :                 // we are approaching a stop on the edge; must not drive further
    2589     14960247 :                 bool isWaypoint = stop.getSpeed() > 0;
    2590     14960247 :                 double endPos = stop.getEndPos(*this) + NUMERICAL_EPS;
    2591     14960247 :                 if (stop.parkingarea != nullptr) {
    2592              :                     // leave enough space so parking vehicles can exit
    2593      1649346 :                     const double brakePos = getBrakeGap() + lane->getLength() - seen;
    2594      1649346 :                     endPos = stop.parkingarea->getLastFreePosWithReservation(t, *this, brakePos);
    2595     13310901 :                 } else if (isWaypoint && !stop.reached) {
    2596       107831 :                     endPos = stop.pars.startPos;
    2597              :                 }
    2598     14960247 :                 stopDist = seen + endPos - lane->getLength();
    2599              : #ifdef DEBUG_STOPS
    2600              :                 if (DEBUG_COND) {
    2601              :                     std::cout << SIMTIME << " veh=" << getID() <<  " stopDist=" << stopDist << " stopLane=" << stop.lane->getID() << " stopEndPos=" << endPos << "\n";
    2602              :                 }
    2603              : #endif
    2604              :                 double stopSpeed = laneMaxV;
    2605     14960247 :                 if (isWaypoint) {
    2606              :                     bool waypointWithStop = false;
    2607       123377 :                     if (stop.getUntil() > t) {
    2608              :                         // check if we have to slow down or even stop
    2609              :                         SUMOTime time2end = 0;
    2610         3691 :                         if (stop.reached) {
    2611          702 :                             time2end = TIME2STEPS((stop.pars.endPos - myState.myPos) / stop.getSpeed());
    2612              :                         } else {
    2613         3267 :                             time2end = TIME2STEPS(
    2614              :                                            // time to reach waypoint start
    2615              :                                            stopDist / ((getSpeed() + stop.getSpeed()) / 2)
    2616              :                                            // time to reach waypoint end
    2617              :                                            + (stop.pars.endPos - stop.pars.startPos) / stop.getSpeed());
    2618              :                         }
    2619         3691 :                         if (stop.getUntil() > t + time2end) {
    2620              :                             // we need to stop
    2621              :                             double distToEnd = stopDist;
    2622         3398 :                             if (!stop.reached) {
    2623         2783 :                                 distToEnd += stop.pars.endPos - stop.pars.startPos;
    2624              :                             }
    2625         3398 :                             stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), distToEnd), vMinComfortable);
    2626              :                             waypointWithStop = true;
    2627         3398 :                             if (stopSpeed <= SUMO_const_haltingSpeed) {
    2628          531 :                                 const_cast<MSStop&>(stop).waypointWithStop = true;
    2629              :                             }
    2630              :                         }
    2631              :                     }
    2632       123377 :                     if (stop.reached) {
    2633        14802 :                         stopSpeed = MIN2(stop.getSpeed(), stopSpeed);
    2634        14802 :                         if (myState.myPos >= stop.pars.endPos && !waypointWithStop) {
    2635          278 :                             stopDist = std::numeric_limits<double>::max();
    2636              :                         }
    2637              :                     } else {
    2638       108575 :                         stopSpeed = MIN2(MAX2(cfModel.freeSpeed(this, getSpeed(), stopDist, stop.getSpeed()), vMinComfortable), stopSpeed);
    2639       108575 :                         if (!stop.reached) {
    2640       108575 :                             stopDist += stop.pars.endPos - stop.pars.startPos;
    2641              :                         }
    2642       108575 :                         if (lastLink != nullptr) {
    2643        66550 :                             lastLink->adaptLeaveSpeed(cfModel.freeSpeed(this, vLinkPass, endPos, stop.getSpeed(), false, MSCFModel::CalcReason::FUTURE));
    2644              :                         }
    2645              :                     }
    2646              :                 } else {
    2647     14836870 :                     stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist);
    2648     14836870 :                     if (!instantStopping()) {
    2649              :                         // regular stops are not emergencies
    2650              :                         stopSpeed = MAX2(stopSpeed, vMinComfortable);
    2651           20 :                     } else if (myInfluencer && !myInfluencer->hasSpeedTimeLine(SIMSTEP)) {
    2652              :                         std::vector<std::pair<SUMOTime, double> > speedTimeLine;
    2653           20 :                         speedTimeLine.push_back(std::make_pair(SIMSTEP, getSpeed()));
    2654           20 :                         speedTimeLine.push_back(std::make_pair(SIMSTEP + DELTA_T, stopSpeed));
    2655           20 :                         myInfluencer->setSpeedTimeLine(speedTimeLine);
    2656           20 :                     }
    2657     14836870 :                     if (lastLink != nullptr) {
    2658      9125662 :                         lastLink->adaptLeaveSpeed(cfModel.stopSpeed(this, vLinkPass, endPos, MSCFModel::CalcReason::FUTURE));
    2659              :                     }
    2660              :                 }
    2661     14960247 :                 if (stopSpeed < getSpeed() && getSpeed() > SUMO_const_haltingSpeed) {
    2662              :                     // only discount braking-for-stop timeLoss if we are actually braking
    2663       615347 :                     newStopSpeed = MIN2(newStopSpeed, stopSpeed);
    2664     14652487 :                 } else if (getSpeed() < SUMO_const_haltingSpeed) {
    2665              :                     // blocked from entering a stop
    2666      7824563 :                     newStopSpeed = std::numeric_limits<double>::max();
    2667              :                 }
    2668     14960247 :                 v = MIN2(v, stopSpeed);
    2669     14960247 :                 if (lane->isInternal()) {
    2670         7011 :                     std::vector<MSLink*>::const_iterator exitLink = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2671              :                     assert(!lane->isLinkEnd(exitLink));
    2672              :                     bool dummySetRequest;
    2673              :                     double dummyVLinkWait;
    2674         7011 :                     checkLinkLeaderCurrentAndParallel(*exitLink, lane, seen, lastLink, v, vLinkPass, dummyVLinkWait, dummySetRequest);
    2675              :                 }
    2676              : 
    2677              : #ifdef DEBUG_PLAN_MOVE
    2678              :                 if (DEBUG_COND) {
    2679              :                     std::cout << "\n" << SIMTIME << " next stop: distance = " << stopDist << " requires stopSpeed = " << stopSpeed << "\n";
    2680              : 
    2681              :                 }
    2682              : #endif
    2683     14960247 :                 if (isFirstStop) {
    2684     10278709 :                     newStopDist = stopDist;
    2685              :                     // if the vehicle is going to stop we don't need to look further
    2686              :                     // (except for trains that make use of further link-approach registration for safety purposes)
    2687     10278709 :                     if (!isWaypoint) {
    2688              :                         planningToStop = true;
    2689     10190707 :                         if (!isRail()) {
    2690      9866755 :                             lfLinks.emplace_back(v, stopDist);
    2691              :                             foundRealStop = true;
    2692              :                             break;
    2693              :                         }
    2694              :                     }
    2695              :                 }
    2696              :             }
    2697              :         }
    2698              :         if (foundRealStop) {
    2699              :             break;
    2700              :         }
    2701              : 
    2702              :         // move to next lane
    2703              :         //  get the next link used
    2704   1222934371 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2705   1222934371 :         if (lane->isLinkEnd(link) && myLaneChangeModel->hasBlueLight() && myCurrEdge != myRoute->end() - 1) {
    2706              :             // emergency vehicle is on the wrong lane. Obtain the link that it would use from the correct turning lane
    2707              :             const int currentIndex = lane->getIndex();
    2708              :             const MSLane* bestJump = nullptr;
    2709       194469 :             for (const LaneQ& preb : getBestLanes()) {
    2710       127902 :                 if (preb.allowsContinuation &&
    2711              :                         (bestJump == nullptr
    2712         3216 :                          || abs(currentIndex - preb.lane->getIndex()) < abs(currentIndex - bestJump->getIndex()))) {
    2713        67572 :                     bestJump = preb.lane;
    2714              :                 }
    2715              :             }
    2716        66567 :             if (bestJump != nullptr) {
    2717        66567 :                 const MSEdge* nextEdge = *(myCurrEdge + 1);
    2718       122908 :                 for (auto cand_it = bestJump->getLinkCont().begin(); cand_it != bestJump->getLinkCont().end(); cand_it++) {
    2719       117529 :                     if (&(*cand_it)->getLane()->getEdge() == nextEdge) {
    2720              :                         link = cand_it;
    2721              :                         break;
    2722              :                     }
    2723              :                 }
    2724              :             }
    2725              :         }
    2726              : 
    2727              :         // Check whether this is a turn (to save info about the next upcoming turn)
    2728   1222934371 :         if (!encounteredTurn) {
    2729    194521391 :             if (!lane->isLinkEnd(link) && lane->getLinkCont().size() > 1) {
    2730     19878654 :                 LinkDirection linkDir = (*link)->getDirection();
    2731     19878654 :                 switch (linkDir) {
    2732              :                     case LinkDirection::STRAIGHT:
    2733              :                     case LinkDirection::NODIR:
    2734              :                         break;
    2735      7808248 :                     default:
    2736      7808248 :                         nextTurn.first = seen;
    2737      7808248 :                         nextTurn.second = *link;
    2738              :                         encounteredTurn = true;
    2739              : #ifdef DEBUG_NEXT_TURN
    2740              :                         if (DEBUG_COND) {
    2741              :                             std::cout << SIMTIME << " veh '" << getID() << "' nextTurn: " << toString(linkDir)
    2742              :                                       << " at " << nextTurn.first << "m." << std::endl;
    2743              :                         }
    2744              : #endif
    2745              :                 }
    2746              :             }
    2747              :         }
    2748              : 
    2749              :         //  check whether the vehicle is on its final edge
    2750   2112880049 :         if (myCurrEdge + view + 1 == myRoute->end()
    2751   1222934371 :                 || (myParameter->arrivalEdge >= 0 && getRoutePosition() + view == myParameter->arrivalEdge)) {
    2752    332988693 :             const double arrivalSpeed = (myParameter->arrivalSpeedProcedure == ArrivalSpeedDefinition::GIVEN ?
    2753              :                                          myParameter->arrivalSpeed : laneMaxV);
    2754              :             // subtract the arrival speed from the remaining distance so we get one additional driving step with arrival speed
    2755              :             // XXX: This does not work for ballistic update refs #2579
    2756    332988693 :             const double distToArrival = seen + myArrivalPos - lane->getLength() - SPEED2DIST(arrivalSpeed);
    2757    332988693 :             const double va = MAX2(NUMERICAL_EPS, cfModel.freeSpeed(this, getSpeed(), distToArrival, arrivalSpeed));
    2758    332988693 :             v = MIN2(v, va);
    2759    332988693 :             if (lastLink != nullptr) {
    2760              :                 lastLink->adaptLeaveSpeed(va);
    2761              :             }
    2762    332988693 :             lfLinks.push_back(DriveProcessItem(v, seen, lane->getEdge().isFringe() ? 1000 : 0));
    2763    332988693 :             break;
    2764              :         }
    2765              :         // check whether the lane or the shadowLane is a dead end (allow some leeway on intersections)
    2766              :         if (lane->isLinkEnd(link)
    2767    880868646 :                 || (MSGlobals::gSublane && brakeForOverlap(*link, lane))
    2768   1770462963 :                 || (opposite && (*link)->getViaLaneOrLane()->getParallelOpposite() == nullptr
    2769       212832 :                     && !myLaneChangeModel->hasBlueLight())) {
    2770      9681107 :             double va = cfModel.stopSpeed(this, getSpeed(), seen);
    2771      9681107 :             if (lastLink != nullptr) {
    2772              :                 lastLink->adaptLeaveSpeed(va);
    2773              :             }
    2774      9681107 :             if (myLaneChangeModel->getCommittedSpeed() > 0) {
    2775       373617 :                 v = MIN2(myLaneChangeModel->getCommittedSpeed(), v);
    2776              :             } else {
    2777     18073943 :                 v = MIN2(va, v);
    2778              :             }
    2779              : #ifdef DEBUG_PLAN_MOVE
    2780              :             if (DEBUG_COND) {
    2781              :                 std::cout << "   braking for link end lane=" << lane->getID() << " seen=" << seen
    2782              :                           << " overlap=" << getLateralOverlap() << " va=" << va << " committed=" << myLaneChangeModel->getCommittedSpeed() << " v=" << v << "\n";
    2783              : 
    2784              :             }
    2785              : #endif
    2786      9681107 :             if (lane->isLinkEnd(link)) {
    2787      9077032 :                 lfLinks.emplace_back(v, seen);
    2788              :                 break;
    2789              :             }
    2790              :         }
    2791    880868646 :         lateralShift += (*link)->getLateralShift();
    2792    880868646 :         const bool yellowOrRed = (*link)->haveRed() || (*link)->haveYellow();
    2793              :         // We distinguish 3 cases when determining the point at which a vehicle stops:
    2794              :         // - allway_stop: the vehicle should stop close to the stop line but may stop at larger distance
    2795              :         // - red/yellow light: here the vehicle 'knows' that it will have priority eventually and does not need to stop on a precise spot
    2796              :         // - other types of minor links: the vehicle needs to stop as close to the junction as necessary
    2797              :         //   to minimize the time window for passing the junction. If the
    2798              :         //   vehicle 'decides' to accelerate and cannot enter the junction in
    2799              :         //   the next step, new foes may appear and cause a collision (see #1096)
    2800              :         // - major links: stopping point is irrelevant
    2801              :         double laneStopOffset;
    2802    880868646 :         const double majorStopOffset = MAX2(getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, DIST_TO_STOPLINE_EXPECT_PRIORITY), lane->getVehicleStopOffset(this));
    2803              :         // override low desired decel at yellow and red
    2804    880868646 :         const double stopDecel = yellowOrRed && !isRail() ? MAX2(MIN2(MSGlobals::gTLSYellowMinDecel, cfModel.getEmergencyDecel()), cfModel.getMaxDecel()) : cfModel.getMaxDecel();
    2805    880868646 :         const double brakeDist = cfModel.brakeGap(myState.mySpeed, stopDecel, 0);
    2806    880868646 :         const bool canBrakeBeforeLaneEnd = seen >= brakeDist;
    2807    880868646 :         const bool canBrakeBeforeStopLine = seen - lane->getVehicleStopOffset(this) >= brakeDist;
    2808    880868646 :         if (yellowOrRed) {
    2809              :             // Wait at red traffic light with full distance if possible
    2810              :             laneStopOffset = majorStopOffset;
    2811    819331334 :         } else if ((*link)->havePriority()) {
    2812              :             // On priority link, we should never stop below visibility distance
    2813    774518510 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, majorStopOffset);
    2814              :         } else {
    2815     44812824 :             double minorStopOffset = MAX2(lane->getVehicleStopOffset(this),
    2816     44812824 :                                           getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_CROSSING_GAP, MSPModel::SAFETY_GAP) - (*link)->getDistToFoePedCrossing());
    2817              : #ifdef DEBUG_PLAN_MOVE
    2818              :             if (DEBUG_COND) {
    2819              :                 std::cout << "  minorStopOffset=" << minorStopOffset << " distToFoePedCrossing=" << (*link)->getDistToFoePedCrossing() << "\n";
    2820              :             }
    2821              : #endif
    2822     44812824 :             if ((*link)->getState() == LINKSTATE_ALLWAY_STOP) {
    2823      1425260 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, 0));
    2824              :             } else {
    2825     43387564 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP_MINOR, 0));
    2826              :             }
    2827              :             // On minor link, we should likewise never stop below visibility distance
    2828     44812824 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, minorStopOffset);
    2829              :         }
    2830              : #ifdef DEBUG_PLAN_MOVE
    2831              :         if (DEBUG_COND) {
    2832              :             std::cout << SIMTIME << " veh=" << getID() << " desired stopOffset on lane '" << lane->getID() << "' is " << laneStopOffset << "\n";
    2833              :         }
    2834              : #endif
    2835    880868646 :         if (canBrakeBeforeLaneEnd) {
    2836              :             // avoid emergency braking if possible
    2837    853391141 :             laneStopOffset = MIN2(laneStopOffset, seen - brakeDist);
    2838              :         }
    2839              :         laneStopOffset = MAX2(POSITION_EPS, laneStopOffset);
    2840    880868646 :         double stopDist = MAX2(0., seen - laneStopOffset);
    2841     61537312 :         if (yellowOrRed && getDevice(typeid(MSDevice_GLOSA)) != nullptr
    2842          508 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->getOverrideSafety()
    2843    880868646 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->isSpeedAdviceActive()) {
    2844              :             stopDist = std::numeric_limits<double>::max();
    2845              :         }
    2846    880868646 :         if (newStopDist != std::numeric_limits<double>::max()) {
    2847              :             stopDist = MAX2(stopDist, newStopDist);
    2848              :         }
    2849              : #ifdef DEBUG_PLAN_MOVE
    2850              :         if (DEBUG_COND) {
    2851              :             std::cout << SIMTIME << " veh=" << getID() << " effective stopOffset on lane '" << lane->getID()
    2852              :                       << "' is " << laneStopOffset << " (-> stopDist=" << stopDist << ")" << std::endl;
    2853              :         }
    2854              : #endif
    2855    880868646 :         if (isRail()
    2856    880868646 :                 && !lane->isInternal()) {
    2857              :             // check for train direction reversal
    2858      3232656 :             if (lane->getBidiLane() != nullptr
    2859      3232656 :                     && (*link)->getLane()->getBidiLane() == lane) {
    2860       631456 :                 double vMustReverse = getCarFollowModel().stopSpeed(this, getSpeed(), seen - POSITION_EPS);
    2861       631456 :                 if (seen < 1) {
    2862         2277 :                     mustSeeBeforeReversal = 2 * seen + getLength();
    2863              :                 }
    2864      1221824 :                 v = MIN2(v, vMustReverse);
    2865              :             }
    2866              :             // signal that is passed in the current step does not count
    2867      6465312 :             foundRailSignal |= ((*link)->getTLLogic() != nullptr
    2868       745709 :                                 && (*link)->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL
    2869      3926324 :                                 && seen > SPEED2DIST(v));
    2870              :         }
    2871              : 
    2872    880868646 :         bool canReverseEventually = false;
    2873    880868646 :         const double vReverse = checkReversal(canReverseEventually, laneMaxV, seen);
    2874    880868646 :         v = MIN2(v, vReverse);
    2875              : #ifdef DEBUG_PLAN_MOVE
    2876              :         if (DEBUG_COND) {
    2877              :             std::cout << SIMTIME << " veh=" << getID() << " canReverseEventually=" << canReverseEventually << " v=" << v << "\n";
    2878              :         }
    2879              : #endif
    2880              : 
    2881              :         // check whether we need to slow down in order to finish a continuous lane change
    2882    880868646 :         if (myLaneChangeModel->isChangingLanes()) {
    2883              :             if (    // slow down to finish lane change before a turn lane
    2884       179825 :                 ((*link)->getDirection() == LinkDirection::LEFT || (*link)->getDirection() == LinkDirection::RIGHT) ||
    2885              :                 // slow down to finish lane change before the shadow lane ends
    2886       146767 :                 (myLaneChangeModel->getShadowLane() != nullptr &&
    2887       146767 :                  (*link)->getViaLaneOrLane()->getParallelLane(myLaneChangeModel->getShadowDirection()) == nullptr)) {
    2888              :                 // XXX maybe this is too harsh. Vehicles could cut some corners here
    2889        54636 :                 const double timeRemaining = STEPS2TIME(myLaneChangeModel->remainingTime());
    2890              :                 assert(timeRemaining != 0);
    2891              :                 // XXX: Euler-logic (#860), but I couldn't identify problems from this yet (Leo). Refs. #2575
    2892        54636 :                 const double va = MAX2(cfModel.stopSpeed(this, getSpeed(), seen - POSITION_EPS),
    2893        54636 :                                        (seen - POSITION_EPS) / timeRemaining);
    2894              : #ifdef DEBUG_PLAN_MOVE
    2895              :                 if (DEBUG_COND) {
    2896              :                     std::cout << SIMTIME << " veh=" << getID() << " slowing down to finish continuous change before"
    2897              :                               << " link=" << (*link)->getViaLaneOrLane()->getID()
    2898              :                               << " timeRemaining=" << timeRemaining
    2899              :                               << " v=" << v
    2900              :                               << " va=" << va
    2901              :                               << std::endl;
    2902              :                 }
    2903              : #endif
    2904       108776 :                 v = MIN2(va, v);
    2905              :             }
    2906              :         }
    2907              : 
    2908              :         // - always issue a request to leave the intersection we are currently on
    2909    880868646 :         const bool leavingCurrentIntersection = myLane->getEdge().isInternal() && lastLink == nullptr;
    2910              :         // - do not issue a request to enter an intersection after we already slowed down for an earlier one
    2911    880868646 :         const bool abortRequestAfterMinor = slowedDownForMinor && (*link)->getInternalLaneBefore() == nullptr;
    2912              :         // - even if red, if we cannot break we should issue a request
    2913    880868646 :         bool setRequest = (v > NUMERICAL_EPS_SPEED && !abortRequestAfterMinor) || (leavingCurrentIntersection);
    2914              : 
    2915    880868646 :         double stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist, stopDecel, MSCFModel::CalcReason::CURRENT_WAIT);
    2916    880868646 :         double vLinkWait = MIN2(v, stopSpeed);
    2917              : #ifdef DEBUG_PLAN_MOVE
    2918              :         if (DEBUG_COND) {
    2919              :             std::cout
    2920              :                     << " stopDist=" << stopDist
    2921              :                     << " stopDecel=" << stopDecel
    2922              :                     << " vLinkWait=" << vLinkWait
    2923              :                     << " brakeDist=" << brakeDist
    2924              :                     << " seen=" << seen
    2925              :                     << " leaveIntersection=" << leavingCurrentIntersection
    2926              :                     << " setRequest=" << setRequest
    2927              :                     //<< std::setprecision(16)
    2928              :                     //<< " v=" << v
    2929              :                     //<< " speedEps=" << NUMERICAL_EPS_SPEED
    2930              :                     //<< std::setprecision(gPrecision)
    2931              :                     << "\n";
    2932              :         }
    2933              : #endif
    2934              : 
    2935    880868646 :         if (yellowOrRed && canBrakeBeforeStopLine && !ignoreRed(*link, canBrakeBeforeStopLine) && seen >= mustSeeBeforeReversal) {
    2936     61475203 :             if (lane->isInternal()) {
    2937        42351 :                 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2938              :             }
    2939              :             // arrivalSpeed / arrivalTime when braking for red light is only relevent for rail signal switching
    2940     61475203 :             const SUMOTime arrivalTime = getArrivalTime(t, seen, v, vLinkPass);
    2941              :             // the vehicle is able to brake in front of a yellow/red traffic light
    2942     61475203 :             lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, false, arrivalTime, vLinkWait, 0, seen, -1));
    2943              :             //lfLinks.push_back(DriveProcessItem(0, vLinkWait, vLinkWait, false, 0, 0, stopDist));
    2944     61475203 :             break;
    2945              :         }
    2946              : 
    2947    819393443 :         const MSLink* entryLink = (*link)->getCorrespondingEntryLink();
    2948    819393443 :         if (entryLink->haveRed() && ignoreRed(*link, canBrakeBeforeStopLine) && STEPS2TIME(t - entryLink->getLastStateChange()) > 2) {
    2949              :             // restrict speed when ignoring a red light
    2950       118484 :             const double redSpeed = MIN2(v, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_RED_SPEED, v));
    2951       118484 :             const double va = MAX2(redSpeed, cfModel.freeSpeed(this, getSpeed(), seen, redSpeed));
    2952       236520 :             v = MIN2(va, v);
    2953              : #ifdef DEBUG_PLAN_MOVE
    2954              :             if (DEBUG_COND) std::cout
    2955              :                         << "   ignoreRed spent=" << STEPS2TIME(t - (*link)->getLastStateChange())
    2956              :                         << " redSpeed=" << redSpeed
    2957              :                         << " va=" << va
    2958              :                         << " v=" << v
    2959              :                         << "\n";
    2960              : #endif
    2961              :         }
    2962              : 
    2963    819393443 :         checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2964              : 
    2965    819393443 :         if (lastLink != nullptr) {
    2966              :             lastLink->adaptLeaveSpeed(laneMaxV);
    2967              :         }
    2968    819393443 :         double arrivalSpeed = vLinkPass;
    2969              :         // vehicles should decelerate when approaching a minor link
    2970              :         // - unless they are close enough to have clear visibility of all relevant foe lanes and may start to accelerate again
    2971              :         // - and unless they are so close that stopping is impossible (i.e. when a green light turns to yellow when close to the junction)
    2972              : 
    2973              :         // whether the vehicle/driver is close enough to the link to see all possible foes #2123
    2974    819393443 :         const double visibilityDistance = (*link)->getFoeVisibilityDistance();
    2975    819393443 :         const double determinedFoePresence = seen <= visibilityDistance;
    2976              : //        // VARIANT: account for time needed to recognize whether relevant vehicles are on the foe lanes. (Leo)
    2977              : //        double foeRecognitionTime = 0.0;
    2978              : //        double determinedFoePresence = seen < visibilityDistance - myState.mySpeed*foeRecognitionTime;
    2979              : 
    2980              : #ifdef DEBUG_PLAN_MOVE
    2981              :         if (DEBUG_COND) {
    2982              :             std::cout << " approaching link=" << (*link)->getViaLaneOrLane()->getID() << " prio=" << (*link)->havePriority() << " seen=" << seen << " visibilityDistance=" << visibilityDistance << " brakeDist=" << brakeDist << "\n";
    2983              :         }
    2984              : #endif
    2985              : 
    2986    819393443 :         const bool couldBrakeForMinor = !(*link)->havePriority() && brakeDist < seen && !(*link)->lastWasContMajor();
    2987     44286380 :         if (couldBrakeForMinor && !determinedFoePresence) {
    2988              :             // vehicle decelerates just enough to be able to stop if necessary and then accelerates
    2989     41506587 :             double maxSpeedAtVisibilityDist = cfModel.maximumSafeStopSpeed(visibilityDistance, cfModel.getMaxDecel(), myState.mySpeed, false, 0., false);
    2990              :             // XXX: estimateSpeedAfterDistance does not use euler-logic (thus returns a lower value than possible here...)
    2991     41506587 :             double maxArrivalSpeed = cfModel.estimateSpeedAfterDistance(visibilityDistance, maxSpeedAtVisibilityDist, cfModel.getMaxAccel());
    2992     41506587 :             arrivalSpeed = MIN2(vLinkPass, maxArrivalSpeed);
    2993              :             slowedDownForMinor = true;
    2994              : #ifdef DEBUG_PLAN_MOVE
    2995              :             if (DEBUG_COND) {
    2996              :                 std::cout << "   slowedDownForMinor maxSpeedAtVisDist=" << maxSpeedAtVisibilityDist << " maxArrivalSpeed=" << maxArrivalSpeed << " arrivalSpeed=" << arrivalSpeed << "\n";
    2997              :             }
    2998              : #endif
    2999    777886856 :         } else if ((*link)->getState() == LINKSTATE_EQUAL && myWaitingTime > 0) {
    3000              :             // check for deadlock (circular yielding)
    3001              :             //std::cout << SIMTIME << " veh=" << getID() << " check rbl-deadlock\n";
    3002         2810 :             std::pair<const SUMOVehicle*, const MSLink*> blocker = (*link)->getFirstApproachingFoe(*link);
    3003              :             //std::cout << "   blocker=" << Named::getIDSecure(blocker.first) << "\n";
    3004              :             int n = 100;
    3005         5622 :             while (blocker.second != nullptr && blocker.second != *link && n > 0) {
    3006         2812 :                 blocker = blocker.second->getFirstApproachingFoe(*link);
    3007         2812 :                 n--;
    3008              :                 //std::cout << "   blocker=" << Named::getIDSecure(blocker.first) << "\n";
    3009              :             }
    3010         2810 :             if (n == 0) {
    3011            0 :                 WRITE_WARNINGF(TL("Suspicious right_before_left junction '%'."), lane->getEdge().getToJunction()->getID());
    3012              :             }
    3013              :             //std::cout << "   blockerLink=" << blocker.second << " link=" << *link << "\n";
    3014         2810 :             if (blocker.second == *link) {
    3015          489 :                 const double threshold = (*link)->getDirection() == LinkDirection::STRAIGHT ? 0.25 : 0.75;
    3016          489 :                 if (RandHelper::rand(getRNG()) < threshold) {
    3017              :                     //std::cout << "   abort request, threshold=" << threshold << "\n";
    3018          308 :                     setRequest = false;
    3019              :                 }
    3020              :             }
    3021              :         }
    3022              : 
    3023    819393443 :         const SUMOTime arrivalTime = getArrivalTime(t, seen, v, arrivalSpeed);
    3024    819393443 :         if (couldBrakeForMinor && determinedFoePresence && (*link)->getLane()->getEdge().isRoundabout()) {
    3025       872052 :             const bool wasOpened = (*link)->opened(arrivalTime, arrivalSpeed, arrivalSpeed,
    3026       872052 :                                                    getLength(), getImpatience(),
    3027              :                                                    getCarFollowModel().getMaxDecel(),
    3028       872052 :                                                    getWaitingTime(), getLateralPositionOnLane(),
    3029              :                                                    nullptr, false, this);
    3030       872052 :             if (!wasOpened) {
    3031              :                 slowedDownForMinor = true;
    3032              :             }
    3033              : #ifdef DEBUG_PLAN_MOVE
    3034              :             if (DEBUG_COND) {
    3035              :                 std::cout << "   slowedDownForMinor at roundabout=" << (!wasOpened) << "\n";
    3036              :             }
    3037              : #endif
    3038              :         }
    3039              : 
    3040              :         // compute arrival speed and arrival time if vehicle starts braking now
    3041              :         // if stopping is possible, arrivalTime can be arbitrarily large. A small value keeps fractional times (impatience) meaningful
    3042              :         double arrivalSpeedBraking = 0;
    3043    819393443 :         const double bGap = cfModel.brakeGap(v);
    3044    819393443 :         if (seen < bGap && !isStopped() && !planningToStop) { // XXX: should this use the current speed (at least for the ballistic case)? (Leo) Refs. #2575
    3045              :             // vehicle cannot come to a complete stop in time
    3046     56998815 :             if (MSGlobals::gSemiImplicitEulerUpdate) {
    3047     54281508 :                 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeedEuler(seen, v);
    3048              :                 // due to discrete/continuous mismatch (when using Euler update) we have to ensure that braking actually helps
    3049              :                 arrivalSpeedBraking = MIN2(arrivalSpeedBraking, arrivalSpeed);
    3050              :             } else {
    3051      2717307 :                 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeed(seen, myState.mySpeed);
    3052              :             }
    3053              :         }
    3054              : 
    3055              :         // estimate leave speed for passing time computation
    3056              :         // l=linkLength, a=accel, t=continuousTime, v=vLeave
    3057              :         // l=v*t + 0.5*a*t^2, solve for t and multiply with a, then add v
    3058   1211766184 :         const double estimatedLeaveSpeed = MIN2((*link)->getViaLaneOrLane()->getVehicleMaxSpeed(this, maxVD),
    3059    819393443 :                                                 getCarFollowModel().estimateSpeedAfterDistance((*link)->getLength(), arrivalSpeed, getVehicleType().getCarFollowModel().getMaxAccel()));
    3060    819393443 :         lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, setRequest,
    3061              :                                            arrivalTime, arrivalSpeed,
    3062              :                                            arrivalSpeedBraking,
    3063              :                                            seen, estimatedLeaveSpeed));
    3064    819393443 :         if ((*link)->getViaLane() == nullptr) {
    3065              :             hadNonInternal = true;
    3066              :             ++view;
    3067              :         }
    3068              : #ifdef DEBUG_PLAN_MOVE
    3069              :         if (DEBUG_COND) {
    3070              :             std::cout << "   checkAbort setRequest=" << setRequest << " v=" << v << " seen=" << seen << " dist=" << dist
    3071              :                       << " seenNonInternal=" << seenNonInternal
    3072              :                       << " seenInternal=" << seenInternal << " length=" << vehicleLength << "\n";
    3073              :         }
    3074              : #endif
    3075              :         // we need to look ahead far enough to see available space for checkRewindLinkLanes
    3076    845722523 :         if ((!setRequest || v <= 0 || seen > dist) && hadNonInternal && seenNonInternal > MAX2(vehicleLength * CRLL_LOOK_AHEAD, vehicleLength + seenInternal) && foundRailSignal) {
    3077              :             break;
    3078              :         }
    3079              :         // get the following lane
    3080              :         lane = (*link)->getViaLaneOrLane();
    3081    595914647 :         laneMaxV = lane->getVehicleMaxSpeed(this, maxVD);
    3082    596314521 :         if (myInfluencer && !myInfluencer->considerSpeedLimit()) {
    3083              :             laneMaxV = std::numeric_limits<double>::max();
    3084              :         }
    3085              :         // the link was passed
    3086              :         // compute the velocity to use when the link is not blocked by other vehicles
    3087              :         //  the vehicle shall be not faster when reaching the next lane than allowed
    3088              :         //  speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
    3089    595914647 :         const double va = MAX2(cfModel.freeSpeed(this, getSpeed(), seen, laneMaxV), vMinComfortable - NUMERICAL_EPS);
    3090   1182042063 :         v = MIN2(va, v);
    3091              : #ifdef DEBUG_PLAN_MOVE
    3092              :         if (DEBUG_COND) {
    3093              :             std::cout << "   laneMaxV=" << laneMaxV << " freeSpeed=" << va << " v=" << v << "\n";
    3094              :         }
    3095              : #endif
    3096    595914647 :         if (lane->getEdge().isInternal()) {
    3097    260752966 :             seenInternal += lane->getLength();
    3098              :         } else {
    3099    335161681 :             seenNonInternal += lane->getLength();
    3100              :         }
    3101              :         // do not restrict results to the current vehicle to allow caching for the current time step
    3102    595914647 :         leaderLane = opposite ? lane->getParallelOpposite() : lane;
    3103    595914647 :         if (leaderLane == nullptr) {
    3104              : 
    3105              :             break;
    3106              :         }
    3107   1191407348 :         ahead = opposite ? MSLeaderInfo(leaderLane->getWidth()) : leaderLane->getLastVehicleInformation(nullptr, 0);
    3108    595703674 :         seen += lane->getLength();
    3109   1191407348 :         vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(lane->getLength(), v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    3110              :         lastLink = &lfLinks.back();
    3111    595703674 :     }
    3112              : 
    3113              : //#ifdef DEBUG_PLAN_MOVE
    3114              : //    if(DEBUG_COND){
    3115              : //        std::cout << "planMoveInternal found safe speed v = " << v << std::endl;
    3116              : //    }
    3117              : //#endif
    3118              : 
    3119              : #ifdef PARALLEL_STOPWATCH
    3120              :     myLane->getStopWatch()[0].stop();
    3121              : #endif
    3122    637097452 : }
    3123              : 
    3124              : 
    3125              : double
    3126         2786 : MSVehicle::slowDownForSchedule(double vMinComfortable) const {
    3127         2786 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    3128              :     const MSStop& stop = myStops.front();
    3129         2786 :     std::pair<double, double> timeDist = estimateTimeToNextStop();
    3130         2786 :     double arrivalDelay = SIMTIME + timeDist.first - STEPS2TIME(stop.pars.arrival);
    3131         2786 :     double t = STEPS2TIME(stop.pars.arrival - SIMSTEP);
    3132         5572 :     if (stop.pars.hasParameter(toString(SUMO_ATTR_FLEX_ARRIVAL))) {
    3133          150 :         SUMOTime flexStart = string2time(stop.pars.getParameter(toString(SUMO_ATTR_FLEX_ARRIVAL)));
    3134           75 :         arrivalDelay += STEPS2TIME(stop.pars.arrival - flexStart);
    3135           75 :         t = STEPS2TIME(flexStart - SIMSTEP);
    3136         2711 :     } else if (stop.pars.started >= 0 && MSGlobals::gUseStopStarted) {
    3137          200 :         arrivalDelay += STEPS2TIME(stop.pars.arrival - stop.pars.started);
    3138          200 :         t = STEPS2TIME(stop.pars.started - SIMSTEP);
    3139              :     }
    3140         2786 :     if (arrivalDelay < 0 && sfp < getChosenSpeedFactor()) {
    3141              :         // we can slow down to better match the schedule (and increase energy efficiency)
    3142         2721 :         const double vSlowDownMin = MAX2(myLane->getSpeedLimit() * sfp, vMinComfortable);
    3143         2721 :         const double s = timeDist.second;
    3144              :         const double b = getCarFollowModel().getMaxDecel();
    3145              :         // x = speed for arriving in t seconds
    3146              :         // u = time at full speed
    3147              :         // u * x + (t - u) * 0.5 * x = s
    3148              :         // t - u = x / b
    3149              :         // eliminate u, solve x
    3150         2721 :         const double radicand = 4 * t * t * b * b - 8 * s * b;
    3151         2721 :         const double x = radicand >= 0 ? t * b - sqrt(radicand) * 0.5 : vSlowDownMin;
    3152         2721 :         double vSlowDown = x < vSlowDownMin ? vSlowDownMin : x;
    3153              : #ifdef DEBUG_PLAN_MOVE
    3154              :         if (DEBUG_COND) {
    3155              :             std::cout << SIMTIME << " veh=" << getID() << " ad=" << arrivalDelay << " t=" << t << " vsm=" << vSlowDownMin
    3156              :                       << " r=" << radicand << " vs=" << vSlowDown << "\n";
    3157              :         }
    3158              : #endif
    3159         2721 :         return vSlowDown;
    3160           65 :     } else if (arrivalDelay > 0 && sfp > getChosenSpeedFactor()) {
    3161              :         // in principle we could up to catch up with the schedule
    3162              :         // but at this point we can only lower the speed, the
    3163              :         // information would have to be used when computing getVehicleMaxSpeed
    3164              :     }
    3165           65 :     return getMaxSpeed();
    3166              : }
    3167              : 
    3168              : SUMOTime
    3169    880868646 : MSVehicle::getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const {
    3170              :     const MSCFModel& cfModel = getCarFollowModel();
    3171              :     SUMOTime arrivalTime;
    3172    880868646 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3173              :         // @note intuitively it would make sense to compare arrivalSpeed with getSpeed() instead of v
    3174              :         // however, due to the current position update rule (ticket #860) the vehicle moves with v in this step
    3175              :         // subtract DELTA_T because t is the time at the end of this step and the movement is not carried out yet
    3176    824037656 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, v, arrivalSpeed);
    3177              :     } else {
    3178     56830990 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, myState.mySpeed, arrivalSpeed);
    3179              :     }
    3180    880868646 :     if (isStopped()) {
    3181     11911108 :         arrivalTime += MAX2((SUMOTime)0, myStops.front().duration);
    3182              :     }
    3183    880868646 :     return arrivalTime;
    3184              : }
    3185              : 
    3186              : 
    3187              : void
    3188   1237820617 : MSVehicle::adaptToLeaders(const MSLeaderInfo& ahead, double latOffset,
    3189              :                           const double seen, DriveProcessItem* const lastLink,
    3190              :                           const MSLane* const lane, double& v, double& vLinkPass) const {
    3191              :     int rightmost;
    3192              :     int leftmost;
    3193   1237820617 :     ahead.getSubLanes(this, latOffset, rightmost, leftmost);
    3194              : #ifdef DEBUG_PLAN_MOVE
    3195              :     if (DEBUG_COND) std::cout << SIMTIME
    3196              :                                   << "\nADAPT_TO_LEADERS\nveh=" << getID()
    3197              :                                   << " lane=" << lane->getID()
    3198              :                                   << " latOffset=" << latOffset
    3199              :                                   << " rm=" << rightmost
    3200              :                                   << " lm=" << leftmost
    3201              :                                   << " shift=" << ahead.getSublaneOffset()
    3202              :                                   << " ahead=" << ahead.toString()
    3203              :                                   << "\n";
    3204              : #endif
    3205              :     /*
    3206              :     if (myLaneChangeModel->getCommittedSpeed() > 0) {
    3207              :         v = MIN2(v, myLaneChangeModel->getCommittedSpeed());
    3208              :         vLinkPass = MIN2(vLinkPass, myLaneChangeModel->getCommittedSpeed());
    3209              :     #ifdef DEBUG_PLAN_MOVE
    3210              :         if (DEBUG_COND) std::cout << "   hasCommitted=" << myLaneChangeModel->getCommittedSpeed() << "\n";
    3211              :     #endif
    3212              :         return;
    3213              :     }
    3214              :     */
    3215   3039955059 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3216   1802134442 :         const MSVehicle* pred = ahead[sublane];
    3217   1802134442 :         if (pred != nullptr && pred != this) {
    3218              :             // @todo avoid multiple adaptations to the same leader
    3219   1318883727 :             const double predBack = pred->getBackPositionOnLane(lane);
    3220              :             double gap = (lastLink == nullptr
    3221   1895151032 :                           ? predBack - myState.myPos - getVehicleType().getMinGap()
    3222    576267305 :                           : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3223              :             bool oncoming = false;
    3224   1318883727 :             if (myLaneChangeModel->isOpposite()) {
    3225        26995 :                 if (pred->getLaneChangeModel().isOpposite() || lane == pred->getLaneChangeModel().getShadowLane()) {
    3226              :                     // ego might and leader are driving against lane
    3227              :                     gap = (lastLink == nullptr
    3228            0 :                            ? myState.myPos - predBack - getVehicleType().getMinGap()
    3229            0 :                            : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3230              :                 } else {
    3231              :                     // ego and leader are driving in the same direction as lane (shadowlane for ego)
    3232              :                     gap = (lastLink == nullptr
    3233        27727 :                            ? predBack - (myLane->getLength() - myState.myPos) - getVehicleType().getMinGap()
    3234          732 :                            : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3235              :                 }
    3236   1318856732 :             } else if (pred->getLaneChangeModel().isOpposite() && pred->getLaneChangeModel().getShadowLane() != lane) {
    3237              :                 // must react to stopped / dangerous oncoming vehicles
    3238       188556 :                 gap += -pred->getVehicleType().getLength() + getVehicleType().getMinGap() - MAX2(getVehicleType().getMinGap(), pred->getVehicleType().getMinGap());
    3239              :                 // try to avoid collision in the next second
    3240       188556 :                 const double predMaxDist = pred->getSpeed() + pred->getCarFollowModel().getMaxAccel();
    3241              : #ifdef DEBUG_PLAN_MOVE
    3242              :                 if (DEBUG_COND) {
    3243              :                     std::cout << "    fixedGap=" << gap << " predMaxDist=" << predMaxDist << "\n";
    3244              :                 }
    3245              : #endif
    3246       188556 :                 if (gap < predMaxDist + getSpeed() || pred->getLane() == lane->getBidiLane()) {
    3247        20611 :                     gap -= predMaxDist;
    3248              :                 }
    3249   1318668176 :             } else if (pred->getLane() == lane->getBidiLane()) {
    3250       618776 :                 gap -= pred->getVehicleType().getLengthWithGap();
    3251              :                 oncoming = true;
    3252              :             }
    3253              : #ifdef DEBUG_PLAN_MOVE
    3254              :             if (DEBUG_COND) {
    3255              :                 std::cout << "     pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << gap << " predBack=" << predBack << " seen=" << seen << " lane=" << lane->getID() << " myLane=" << myLane->getID() << " lastLink=" << (lastLink == nullptr ? "NULL" : lastLink->myLink->getDescription()) << " oncoming=" << oncoming << "\n";
    3256              :             }
    3257              : #endif
    3258       618776 :             if (oncoming && gap >= 0) {
    3259       555302 :                 adaptToOncomingLeader(std::make_pair(pred, gap), lastLink, v, vLinkPass);
    3260              :             } else {
    3261   1318328425 :                 adaptToLeader(std::make_pair(pred, gap), seen, lastLink, v, vLinkPass);
    3262              :             }
    3263              :         }
    3264              :     }
    3265   1237820617 : }
    3266              : 
    3267              : void
    3268       428086 : MSVehicle::adaptToLeaderDistance(const MSLeaderDistanceInfo& ahead, double latOffset,
    3269              :                                  double seen,
    3270              :                                  DriveProcessItem* const lastLink,
    3271              :                                  double& v, double& vLinkPass) const {
    3272              :     int rightmost;
    3273              :     int leftmost;
    3274       428086 :     ahead.getSubLanes(this, latOffset, rightmost, leftmost);
    3275              : #ifdef DEBUG_PLAN_MOVE
    3276              :     if (DEBUG_COND) std::cout << SIMTIME
    3277              :                                   << "\nADAPT_TO_LEADERS_DISTANCE\nveh=" << getID()
    3278              :                                   << " latOffset=" << latOffset
    3279              :                                   << " rm=" << rightmost
    3280              :                                   << " lm=" << leftmost
    3281              :                                   << " ahead=" << ahead.toString()
    3282              :                                   << "\n";
    3283              : #endif
    3284      1049089 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3285       621003 :         CLeaderDist predDist = ahead[sublane];
    3286       621003 :         const MSVehicle* pred = predDist.first;
    3287       621003 :         if (pred != nullptr && pred != this) {
    3288              : #ifdef DEBUG_PLAN_MOVE
    3289              :             if (DEBUG_COND) {
    3290              :                 std::cout << "     pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << predDist.second << "\n";
    3291              :             }
    3292              : #endif
    3293       391199 :             adaptToLeader(predDist, seen, lastLink, v, vLinkPass);
    3294              :         }
    3295              :     }
    3296       428086 : }
    3297              : 
    3298              : 
    3299              : void
    3300   1318719624 : MSVehicle::adaptToLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3301              :                          double seen,
    3302              :                          DriveProcessItem* const lastLink,
    3303              :                          double& v, double& vLinkPass) const {
    3304   1318719624 :     if (leaderInfo.first != 0) {
    3305   1318719624 :         if (ignoreFoe(leaderInfo.first)) {
    3306              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3307              :             if (DEBUG_COND) {
    3308              :                 std::cout << "  foe ignored\n";
    3309              :             }
    3310              : #endif
    3311              :             return;
    3312              :         }
    3313              :         const MSCFModel& cfModel = getCarFollowModel();
    3314              :         double vsafeLeader = 0;
    3315   1318718818 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3316              :             vsafeLeader = -std::numeric_limits<double>::max();
    3317              :         }
    3318              :         bool backOnRoute = true;
    3319   1318718818 :         if (leaderInfo.second < 0 && lastLink != nullptr && lastLink->myLink != nullptr) {
    3320              :             backOnRoute = false;
    3321              :             // this can either be
    3322              :             // a) a merging situation (leader back is is not our route) or
    3323              :             // b) a minGap violation / collision
    3324              :             MSLane* current = lastLink->myLink->getViaLaneOrLane();
    3325       291991 :             if (leaderInfo.first->getBackLane() == current) {
    3326              :                 backOnRoute = true;
    3327              :             } else {
    3328       660872 :                 for (MSLane* lane : getBestLanesContinuation()) {
    3329       581805 :                     if (lane == current) {
    3330              :                         break;
    3331              :                     }
    3332       434806 :                     if (leaderInfo.first->getBackLane() == lane) {
    3333              :                         backOnRoute = true;
    3334              :                     }
    3335              :                 }
    3336              :             }
    3337              : #ifdef DEBUG_PLAN_MOVE
    3338              :             if (DEBUG_COND) {
    3339              :                 std::cout << SIMTIME << " current=" << current->getID() << " leaderBackLane=" << leaderInfo.first->getBackLane()->getID() << " backOnRoute=" << backOnRoute << "\n";
    3340              :             }
    3341              : #endif
    3342       226066 :             if (!backOnRoute) {
    3343       124191 :                 double stopDist = seen - current->getLength() - POSITION_EPS;
    3344       124191 :                 if (lastLink->myLink->getInternalLaneBefore() != nullptr) {
    3345              :                     // do not drive onto the junction conflict area
    3346       107559 :                     stopDist -= lastLink->myLink->getInternalLaneBefore()->getLength();
    3347              :                 }
    3348       124191 :                 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), stopDist);
    3349              :             }
    3350              :         }
    3351       190116 :         if (backOnRoute) {
    3352   1318594627 :             vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3353              :         }
    3354   1318718818 :         if (lastLink != nullptr) {
    3355    576220013 :             const double futureVSafe = cfModel.followSpeed(this, lastLink->accelV, leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first, MSCFModel::CalcReason::FUTURE);
    3356              :             lastLink->adaptLeaveSpeed(futureVSafe);
    3357              : #ifdef DEBUG_PLAN_MOVE
    3358              :             if (DEBUG_COND) {
    3359              :                 std::cout << "   vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
    3360              :             }
    3361              : #endif
    3362              :         }
    3363   1318718818 :         v = MIN2(v, vsafeLeader);
    3364   2273053162 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3365              : #ifdef DEBUG_PLAN_MOVE
    3366              :         if (DEBUG_COND) std::cout
    3367              :                     << SIMTIME
    3368              :                     //std::cout << std::setprecision(10);
    3369              :                     << " veh=" << getID()
    3370              :                     << " lead=" << leaderInfo.first->getID()
    3371              :                     << " leadSpeed=" << leaderInfo.first->getSpeed()
    3372              :                     << " gap=" << leaderInfo.second
    3373              :                     << " leadLane=" << leaderInfo.first->getLane()->getID()
    3374              :                     << " predPos=" << leaderInfo.first->getPositionOnLane()
    3375              :                     << " myLane=" << myLane->getID()
    3376              :                     << " v=" << v
    3377              :                     << " vSafeLeader=" << vsafeLeader
    3378              :                     << " vLinkPass=" << vLinkPass
    3379              :                     << "\n";
    3380              : #endif
    3381              :     }
    3382              : }
    3383              : 
    3384              : 
    3385              : void
    3386     18840055 : MSVehicle::adaptToJunctionLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3387              :                                  const double seen, DriveProcessItem* const lastLink,
    3388              :                                  const MSLane* const lane, double& v, double& vLinkPass,
    3389              :                                  double distToCrossing) const {
    3390     18840055 :     if (leaderInfo.first != 0) {
    3391     18840055 :         if (ignoreFoe(leaderInfo.first)) {
    3392              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3393              :             if (DEBUG_COND) {
    3394              :                 std::cout << "  junction foe ignored\n";
    3395              :             }
    3396              : #endif
    3397              :             return;
    3398              :         }
    3399              :         const MSCFModel& cfModel = getCarFollowModel();
    3400              :         double vsafeLeader = 0;
    3401     18840044 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3402              :             vsafeLeader = -std::numeric_limits<double>::max();
    3403              :         }
    3404     18840044 :         if (leaderInfo.second >= 0) {
    3405     15853921 :             if (hasDeparted()) {
    3406     15848568 :                 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3407              :             } else {
    3408              :                 // called in the context of MSLane::isInsertionSuccess
    3409         5353 :                 vsafeLeader = cfModel.insertionFollowSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3410              :             }
    3411      2986123 :         } else if (leaderInfo.first != this) {
    3412              :             // the leading, in-lapping vehicle is occupying the complete next lane
    3413              :             // stop before entering this lane
    3414      2564013 :             vsafeLeader = cfModel.stopSpeed(this, getSpeed(), seen - lane->getLength() - POSITION_EPS);
    3415              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3416              :             if (DEBUG_COND) {
    3417              :                 std::cout << SIMTIME << " veh=" << getID() << "  stopping before junction: lane=" << lane->getID() << " seen=" << seen
    3418              :                           << " laneLength=" << lane->getLength()
    3419              :                           << " stopDist=" << seen - lane->getLength()  - POSITION_EPS
    3420              :                           << " vsafeLeader=" << vsafeLeader
    3421              :                           << " distToCrossing=" << distToCrossing
    3422              :                           << "\n";
    3423              :             }
    3424              : #endif
    3425              :         }
    3426     18840044 :         if (distToCrossing >= 0) {
    3427              :             // can the leader still stop in the way?
    3428      6097113 :             const double vStop = cfModel.stopSpeed(this, getSpeed(), distToCrossing - getVehicleType().getMinGap());
    3429      6097113 :             if (leaderInfo.first == this) {
    3430              :                 // braking for pedestrian
    3431       410791 :                 const double vStopCrossing = cfModel.stopSpeed(this, getSpeed(), distToCrossing);
    3432              :                 vsafeLeader = vStopCrossing;
    3433              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3434              :                 if (DEBUG_COND) {
    3435              :                     std::cout << "  breaking for pedestrian distToCrossing=" << distToCrossing << " vStopCrossing=" << vStopCrossing << "\n";
    3436              :                 }
    3437              : #endif
    3438       410791 :                 if (lastLink != nullptr) {
    3439              :                     lastLink->adaptStopSpeed(vsafeLeader);
    3440              :                 }
    3441      5686322 :             } else if (leaderInfo.second == -std::numeric_limits<double>::max()) {
    3442              :                 // drive up to the crossing point and stop
    3443              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3444              :                 if (DEBUG_COND) {
    3445              :                     std::cout << "  stop at crossing point for critical leader vStop=" << vStop << "\n";
    3446              :                 };
    3447              : #endif
    3448              :                 vsafeLeader = MAX2(vsafeLeader, vStop);
    3449              :             } else {
    3450      5629877 :                 const double leaderDistToCrossing = distToCrossing - leaderInfo.second;
    3451              :                 // estimate the time at which the leader has gone past the crossing point
    3452      5629877 :                 const double leaderPastCPTime = leaderDistToCrossing / MAX2(leaderInfo.first->getSpeed(), SUMO_const_haltingSpeed);
    3453              :                 // reach distToCrossing after that time
    3454              :                 // avgSpeed * leaderPastCPTime = distToCrossing
    3455              :                 // ballistic: avgSpeed = (getSpeed + vFinal) / 2
    3456      5629877 :                 const double vFinal = MAX2(getSpeed(), 2 * (distToCrossing - getVehicleType().getMinGap()) / leaderPastCPTime - getSpeed());
    3457      5629877 :                 const double v2 = getSpeed() + ACCEL2SPEED((vFinal - getSpeed()) / leaderPastCPTime);
    3458              :                 vsafeLeader = MAX2(vsafeLeader, MIN2(v2, vStop));
    3459              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3460              :                 if (DEBUG_COND) {
    3461              :                     std::cout << "    driving up to the crossing point (distToCrossing=" << distToCrossing << ")"
    3462              :                               << " leaderPastCPTime=" << leaderPastCPTime
    3463              :                               << " vFinal=" << vFinal
    3464              :                               << " v2=" << v2
    3465              :                               << " vStop=" << vStop
    3466              :                               << " vsafeLeader=" << vsafeLeader << "\n";
    3467              :                 }
    3468              : #endif
    3469              :             }
    3470              :         }
    3471     18429253 :         if (lastLink != nullptr) {
    3472              :             lastLink->adaptLeaveSpeed(vsafeLeader);
    3473              :         }
    3474     18840044 :         v = MIN2(v, vsafeLeader);
    3475     35124065 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3476              : #ifdef DEBUG_PLAN_MOVE
    3477              :         if (DEBUG_COND) std::cout
    3478              :                     << SIMTIME
    3479              :                     //std::cout << std::setprecision(10);
    3480              :                     << " veh=" << getID()
    3481              :                     << " lead=" << leaderInfo.first->getID()
    3482              :                     << " leadSpeed=" << leaderInfo.first->getSpeed()
    3483              :                     << " gap=" << leaderInfo.second
    3484              :                     << " leadLane=" << leaderInfo.first->getLane()->getID()
    3485              :                     << " predPos=" << leaderInfo.first->getPositionOnLane()
    3486              :                     << " seen=" << seen
    3487              :                     << " lane=" << lane->getID()
    3488              :                     << " myLane=" << myLane->getID()
    3489              :                     << " dTC=" << distToCrossing
    3490              :                     << " v=" << v
    3491              :                     << " vSafeLeader=" << vsafeLeader
    3492              :                     << " vLinkPass=" << vLinkPass
    3493              :                     << "\n";
    3494              : #endif
    3495              :     }
    3496              : }
    3497              : 
    3498              : 
    3499              : void
    3500       555302 : MSVehicle::adaptToOncomingLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3501              :                                  DriveProcessItem* const lastLink,
    3502              :                                  double& v, double& vLinkPass) const {
    3503       555302 :     if (leaderInfo.first != 0) {
    3504       555302 :         if (ignoreFoe(leaderInfo.first)) {
    3505              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3506              :             if (DEBUG_COND) {
    3507              :                 std::cout << "  oncoming foe ignored\n";
    3508              :             }
    3509              : #endif
    3510              :             return;
    3511              :         }
    3512              :         const MSCFModel& cfModel = getCarFollowModel();
    3513              :         const MSVehicle* lead = leaderInfo.first;
    3514              :         const MSCFModel& cfModelL = lead->getCarFollowModel();
    3515              :         // assume the leader reacts symmetrically (neither stopping instantly nor ignoring ego)
    3516       555254 :         const double leaderBrakeGap = cfModelL.brakeGap(lead->getSpeed(), cfModelL.getMaxDecel(), 0);
    3517       555254 :         const double egoBrakeGap = cfModel.brakeGap(getSpeed(), cfModel.getMaxDecel(), 0);
    3518       555254 :         const double gapSum = leaderBrakeGap + egoBrakeGap;
    3519              :         // ensure that both vehicles can leave an intersection if they are currently on it
    3520       555254 :         double egoExit = getDistanceToLeaveJunction();
    3521       555254 :         const double leaderExit = lead->getDistanceToLeaveJunction();
    3522              :         double gap = leaderInfo.second;
    3523       555254 :         if (egoExit + leaderExit < gap) {
    3524       460878 :             gap -= egoExit + leaderExit;
    3525              :         } else {
    3526              :             egoExit = 0;
    3527              :         }
    3528              :         // split any distance in excess of brakeGaps evenly
    3529       555254 :         const double freeGap = MAX2(0.0, gap - gapSum);
    3530              :         const double splitGap = MIN2(gap, gapSum);
    3531              :         // assume remaining distance is allocated in proportion to braking distance
    3532       555254 :         const double gapRatio = gapSum > 0 ? egoBrakeGap / gapSum : 0.5;
    3533       555254 :         const double vsafeLeader = cfModel.stopSpeed(this, getSpeed(), splitGap * gapRatio + egoExit + 0.5 * freeGap);
    3534       555254 :         if (lastLink != nullptr) {
    3535        67371 :             const double futureVSafe = cfModel.stopSpeed(this, lastLink->accelV, leaderInfo.second, MSCFModel::CalcReason::FUTURE);
    3536              :             lastLink->adaptLeaveSpeed(futureVSafe);
    3537              : #ifdef DEBUG_PLAN_MOVE
    3538              :             if (DEBUG_COND) {
    3539              :                 std::cout << "   vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
    3540              :             }
    3541              : #endif
    3542              :         }
    3543       555254 :         v = MIN2(v, vsafeLeader);
    3544      1097045 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3545              : #ifdef DEBUG_PLAN_MOVE
    3546              :         if (DEBUG_COND) std::cout
    3547              :                     << SIMTIME
    3548              :                     //std::cout << std::setprecision(10);
    3549              :                     << " veh=" << getID()
    3550              :                     << " oncomingLead=" << lead->getID()
    3551              :                     << " leadSpeed=" << lead->getSpeed()
    3552              :                     << " gap=" << leaderInfo.second
    3553              :                     << " gap2=" << gap
    3554              :                     << " gapRatio=" << gapRatio
    3555              :                     << " leadLane=" << lead->getLane()->getID()
    3556              :                     << " predPos=" << lead->getPositionOnLane()
    3557              :                     << " myLane=" << myLane->getID()
    3558              :                     << " v=" << v
    3559              :                     << " vSafeLeader=" << vsafeLeader
    3560              :                     << " vLinkPass=" << vLinkPass
    3561              :                     << "\n";
    3562              : #endif
    3563              :     }
    3564              : }
    3565              : 
    3566              : 
    3567              : void
    3568    819442805 : MSVehicle::checkLinkLeaderCurrentAndParallel(const MSLink* link, const MSLane* lane, double seen,
    3569              :         DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest) const {
    3570    819442805 :     if (MSGlobals::gUsingInternalLanes && (myInfluencer == nullptr || myInfluencer->getRespectJunctionLeaderPriority())) {
    3571              :         // we want to pass the link but need to check for foes on internal lanes
    3572    819333651 :         checkLinkLeader(link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    3573    819333651 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    3574      3155920 :             const MSLink* const parallelLink = link->getParallelLink(myLaneChangeModel->getShadowDirection());
    3575      3155920 :             if (parallelLink != nullptr) {
    3576      2188391 :                 checkLinkLeader(parallelLink, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest, true);
    3577              :             }
    3578              :         }
    3579              :     }
    3580              : 
    3581    819442805 : }
    3582              : 
    3583              : void
    3584    821768367 : MSVehicle::checkLinkLeader(const MSLink* link, const MSLane* lane, double seen,
    3585              :                            DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest,
    3586              :                            bool isShadowLink) const {
    3587              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3588              :     if (DEBUG_COND) {
    3589              :         gDebugFlag1 = true;    // See MSLink::getLeaderInfo
    3590              :     }
    3591              : #endif
    3592    821768367 :     const MSLink::LinkLeaders linkLeaders = link->getLeaderInfo(this, seen, nullptr, isShadowLink);
    3593              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3594              :     if (DEBUG_COND) {
    3595              :         gDebugFlag1 = false;    // See MSLink::getLeaderInfo
    3596              :     }
    3597              : #endif
    3598    841606048 :     for (MSLink::LinkLeaders::const_iterator it = linkLeaders.begin(); it != linkLeaders.end(); ++it) {
    3599              :         // the vehicle to enter the junction first has priority
    3600     19837681 :         const MSVehicle* leader = (*it).vehAndGap.first;
    3601     19837681 :         if (leader == nullptr) {
    3602              :             // leader is a pedestrian. Passing 'this' as a dummy.
    3603              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3604              :             if (DEBUG_COND) {
    3605              :                 std::cout << SIMTIME << " veh=" << getID() << " is blocked on link to " << link->getViaLaneOrLane()->getID() << " by pedestrian. dist=" << it->distToCrossing << "\n";
    3606              :             }
    3607              : #endif
    3608       422806 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3609       422806 :                     && getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) >= RandHelper::rand(getRNG())) {
    3610              : #ifdef DEBUG_PLAN_MOVE
    3611              :                 if (DEBUG_COND) {
    3612              :                     std::cout << SIMTIME << " veh=" << getID() << " is ignoring pedestrian (jmIgnoreJunctionFoeProb)\n";
    3613              :                 }
    3614              : #endif
    3615          696 :                 continue;
    3616              :             }
    3617       422110 :             adaptToJunctionLeader(std::make_pair(this, -1), seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3618              :             // if blocked by a pedestrian for too long we must yield our request
    3619       422110 :             if (v < SUMO_const_haltingSpeed && getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME)) {
    3620        75600 :                 setRequest = false;
    3621              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3622              :                 if (DEBUG_COND) {
    3623              :                     std::cout << "   aborting request\n";
    3624              :                 }
    3625              : #endif
    3626              :             }
    3627     19414875 :         } else if (isLeader(link, leader, (*it).vehAndGap.second) || (*it).inTheWay()) {
    3628     19349018 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3629     19349018 :                     && getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) >= RandHelper::rand(getRNG())) {
    3630              : #ifdef DEBUG_PLAN_MOVE
    3631              :                 if (DEBUG_COND) {
    3632              :                     std::cout << SIMTIME << " veh=" << getID() << " is ignoring linkLeader=" << leader->getID() << " (jmIgnoreJunctionFoeProb)\n";
    3633              :                 }
    3634              : #endif
    3635         2194 :                 continue;
    3636              :             }
    3637     26368173 :             if (MSGlobals::gLateralResolution > 0 &&
    3638              :                     // sibling link (XXX: could also be partial occupator where this check fails)
    3639      7021349 :                     &leader->getLane()->getEdge() == &lane->getEdge()) {
    3640              :                 // check for sublane obstruction (trivial for sibling link leaders)
    3641              :                 const MSLane* conflictLane = link->getInternalLaneBefore();
    3642       959836 :                 MSLeaderInfo linkLeadersAhead = MSLeaderInfo(conflictLane->getWidth());
    3643       959836 :                 linkLeadersAhead.addLeader(leader, false, 0); // assume sibling lane has the same geometry as the leader lane
    3644       959836 :                 const double latOffset = isShadowLink ? (getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge()) : 0;
    3645              :                 // leader is neither on lane nor conflictLane (the conflict is only established geometrically)
    3646       959836 :                 adaptToLeaders(linkLeadersAhead, latOffset, seen, lastLink, leader->getLane(), v, vLinkPass);
    3647              : #ifdef DEBUG_PLAN_MOVE
    3648              :                 if (DEBUG_COND) {
    3649              :                     std::cout << SIMTIME << " veh=" << getID()
    3650              :                               << " siblingFoe link=" << link->getViaLaneOrLane()->getID()
    3651              :                               << " isShadowLink=" << isShadowLink
    3652              :                               << " lane=" << lane->getID()
    3653              :                               << " foe=" << leader->getID()
    3654              :                               << " foeLane=" << leader->getLane()->getID()
    3655              :                               << " latOffset=" << latOffset
    3656              :                               << " latOffsetFoe=" << leader->getLatOffset(lane)
    3657              :                               << " linkLeadersAhead=" << linkLeadersAhead.toString()
    3658              :                               << "\n";
    3659              :                 }
    3660              : #endif
    3661       959836 :             } else {
    3662              : #ifdef DEBUG_PLAN_MOVE
    3663              :                 if (DEBUG_COND) {
    3664              :                     std::cout << SIMTIME << " veh=" << getID() << " linkLeader=" << leader->getID() << " gap=" << it->vehAndGap.second
    3665              :                               << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
    3666              :                               << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
    3667              :                               << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
    3668              :                               << "\n";
    3669              :                 }
    3670              : #endif
    3671     18386988 :                 adaptToJunctionLeader(it->vehAndGap, seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3672              :             }
    3673     19346824 :             if (lastLink != nullptr) {
    3674              :                 // we are not yet on the junction with this linkLeader.
    3675              :                 // at least we can drive up to the previous link and stop there
    3676     37184134 :                 v = MAX2(v, lastLink->myVLinkWait);
    3677              :             }
    3678              :             // if blocked by a leader from the same or next lane we must yield our request
    3679              :             // also, if blocked by a stopped or blocked leader
    3680     19346824 :             if (v < SUMO_const_haltingSpeed
    3681              :                     //&& leader->getSpeed() < SUMO_const_haltingSpeed
    3682     19346824 :                     && (leader->getLane()->getLogicalPredecessorLane() == myLane->getLogicalPredecessorLane()
    3683     10634736 :                         || leader->getLane()->getLogicalPredecessorLane() == myLane
    3684      8507768 :                         || leader->isStopped()
    3685      8429258 :                         || leader->getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME))) {
    3686      4337784 :                 setRequest = false;
    3687              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3688              :                 if (DEBUG_COND) {
    3689              :                     std::cout << "   aborting request\n";
    3690              :                 }
    3691              : #endif
    3692      4337784 :                 if (lastLink != nullptr && leader->getLane()->getLogicalPredecessorLane() == myLane) {
    3693              :                     // we are not yet on the junction so must abort that request as well
    3694              :                     // (or maybe we are already on the junction and the leader is a partial occupator beyond)
    3695      2114878 :                     lastLink->mySetRequest = false;
    3696              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3697              :                     if (DEBUG_COND) {
    3698              :                         std::cout << "      aborting previous request\n";
    3699              :                     }
    3700              : #endif
    3701              :                 }
    3702              :             }
    3703              :         }
    3704              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3705              :         else {
    3706              :             if (DEBUG_COND) {
    3707              :                 std::cout << SIMTIME << " veh=" << getID() << " ignoring leader " << leader->getID() << " gap=" << (*it).vehAndGap.second << " dtC=" << (*it).distToCrossing
    3708              :                           << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
    3709              :                           << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
    3710              :                           << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
    3711              :                           << "\n";
    3712              :             }
    3713              :         }
    3714              : #endif
    3715              :     }
    3716              :     // if this is the link between two internal lanes we may have to slow down for pedestrians
    3717    821768367 :     vLinkWait = MIN2(vLinkWait, v);
    3718    821768367 : }
    3719              : 
    3720              : 
    3721              : double
    3722     99303976 : MSVehicle::getDeltaPos(const double accel) const {
    3723     99303976 :     double vNext = myState.mySpeed + ACCEL2SPEED(accel);
    3724     99303976 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3725              :         // apply implicit Euler positional update
    3726            0 :         return SPEED2DIST(MAX2(vNext, 0.));
    3727              :     } else {
    3728              :         // apply ballistic update
    3729     99303976 :         if (vNext >= 0) {
    3730              :             // assume constant acceleration during this time step
    3731     98668291 :             return SPEED2DIST(myState.mySpeed + 0.5 * ACCEL2SPEED(accel));
    3732              :         } else {
    3733              :             // negative vNext indicates a stop within the middle of time step
    3734              :             // The corresponding stop time is s = mySpeed/deceleration \in [0,dt], and the
    3735              :             // covered distance is therefore deltaPos = mySpeed*s - 0.5*deceleration*s^2.
    3736              :             // Here, deceleration = (myState.mySpeed - vNext)/dt is the constant deceleration
    3737              :             // until the vehicle stops.
    3738       635685 :             return -SPEED2DIST(0.5 * myState.mySpeed * myState.mySpeed / ACCEL2SPEED(accel));
    3739              :         }
    3740              :     }
    3741              : }
    3742              : 
    3743              : void
    3744    637097452 : MSVehicle::processLinkApproaches(double& vSafe, double& vSafeMin, double& vSafeMinDist) {
    3745              : 
    3746              :     const MSCFModel& cfModel = getCarFollowModel();
    3747              :     // Speed limit due to zipper merging
    3748              :     double vSafeZipper = std::numeric_limits<double>::max();
    3749              : 
    3750    637097452 :     myHaveToWaitOnNextLink = false;
    3751              :     bool canBrakeVSafeMin = false;
    3752              : 
    3753              :     // Get safe velocities from DriveProcessItems.
    3754              :     assert(myLFLinkLanes.size() != 0 || isRemoteControlled());
    3755   1279110868 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    3756   1103730755 :         MSLink* const link = dpi.myLink;
    3757              : 
    3758              : #ifdef DEBUG_EXEC_MOVE
    3759              :         if (DEBUG_COND) {
    3760              :             std::cout
    3761              :                     << SIMTIME
    3762              :                     << " veh=" << getID()
    3763              :                     << " link=" << (link == 0 ? "NULL" : link->getViaLaneOrLane()->getID())
    3764              :                     << " req=" << dpi.mySetRequest
    3765              :                     << " vP=" << dpi.myVLinkPass
    3766              :                     << " vW=" << dpi.myVLinkWait
    3767              :                     << " d=" << dpi.myDistance
    3768              :                     << "\n";
    3769              :             gDebugFlag1 = true; // See MSLink_DEBUG_OPENED
    3770              :         }
    3771              : #endif
    3772              : 
    3773              :         // the vehicle must change the lane on one of the next lanes (XXX: refs to code further below???, Leo)
    3774   1103730755 :         if (link != nullptr && dpi.mySetRequest) {
    3775              : 
    3776              :             const LinkState ls = link->getState();
    3777              :             // vehicles should brake when running onto a yellow light if the distance allows to halt in front
    3778              :             const bool yellow = link->haveYellow();
    3779    663249305 :             const bool canBrake = (dpi.myDistance > cfModel.brakeGap(myState.mySpeed, cfModel.getMaxDecel(), 0.)
    3780    663249305 :                                    || (MSGlobals::gSemiImplicitEulerUpdate && myState.mySpeed < ACCEL2SPEED(cfModel.getMaxDecel())));
    3781              :             assert(link->getLaneBefore() != nullptr);
    3782    663249305 :             const bool beyondStopLine = dpi.myDistance < link->getLaneBefore()->getVehicleStopOffset(this);
    3783    663249305 :             const bool ignoreRedLink = ignoreRed(link, canBrake) || beyondStopLine;
    3784    663249305 :             if (yellow && canBrake && !ignoreRedLink) {
    3785           10 :                 vSafe = dpi.myVLinkWait;
    3786           10 :                 myHaveToWaitOnNextLink = true;
    3787              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3788              :                 if (DEBUG_COND) {
    3789              :                     std::cout << SIMTIME << " veh=" << getID() << " haveToWait (yellow)\n";
    3790              :                 }
    3791              : #endif
    3792     21235889 :                 break;
    3793              :             }
    3794    663249295 :             const bool influencerPrio = (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority());
    3795              :             MSLink::BlockingFoes collectFoes;
    3796    663249295 :             bool opened = (yellow || influencerPrio
    3797   1989422243 :                            || link->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3798    663086474 :                                            getVehicleType().getLength(),
    3799    635632223 :                                            canBrake ? getImpatience() : 1,
    3800              :                                            cfModel.getMaxDecel(),
    3801    663086474 :                                            getWaitingTimeFor(link), getLateralPositionOnLane(),
    3802              :                                            ls == LINKSTATE_ZIPPER ? &collectFoes : nullptr,
    3803    663086474 :                                            ignoreRedLink, this, dpi.myDistance));
    3804    657564468 :             if (opened && myLaneChangeModel->getShadowLane() != nullptr) {
    3805      1962651 :                 const MSLink* const parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    3806      1962651 :                 if (parallelLink != nullptr) {
    3807      1220838 :                     const double shadowLatPos = getLateralPositionOnLane() - myLaneChangeModel->getShadowDirection() * 0.5 * (
    3808      1220838 :                                                     myLane->getWidth() + myLaneChangeModel->getShadowLane()->getWidth());
    3809      2440905 :                     opened = yellow || influencerPrio || (opened && parallelLink->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3810      1220067 :                                                           getVehicleType().getLength(), getImpatience(),
    3811              :                                                           cfModel.getMaxDecel(),
    3812              :                                                           getWaitingTimeFor(link), shadowLatPos, nullptr,
    3813      1220067 :                                                           ignoreRedLink, this, dpi.myDistance));
    3814              : #ifdef DEBUG_EXEC_MOVE
    3815              :                     if (DEBUG_COND) {
    3816              :                         std::cout << SIMTIME
    3817              :                                   << " veh=" << getID()
    3818              :                                   << " shadowLane=" << myLaneChangeModel->getShadowLane()->getID()
    3819              :                                   << " shadowDir=" << myLaneChangeModel->getShadowDirection()
    3820              :                                   << " parallelLink=" << (parallelLink == 0 ? "NULL" : parallelLink->getViaLaneOrLane()->getID())
    3821              :                                   << " opened=" << opened
    3822              :                                   << "\n";
    3823              :                     }
    3824              : #endif
    3825              :                 }
    3826              :             }
    3827              :             // vehicles should decelerate when approaching a minor link
    3828              : #ifdef DEBUG_EXEC_MOVE
    3829              :             if (DEBUG_COND) {
    3830              :                 std::cout << SIMTIME
    3831              :                           << "   opened=" << opened
    3832              :                           << " influencerPrio=" << influencerPrio
    3833              :                           << " linkPrio=" << link->havePriority()
    3834              :                           << " lastContMajor=" << link->lastWasContMajor()
    3835              :                           << " isCont=" << link->isCont()
    3836              :                           << " ignoreRed=" << ignoreRedLink
    3837              :                           << "\n";
    3838              :             }
    3839              : #endif
    3840              :             double visibilityDistance = link->getFoeVisibilityDistance();
    3841    663249295 :             bool determinedFoePresence = dpi.myDistance <= visibilityDistance;
    3842    663249295 :             if (opened && !influencerPrio && !link->havePriority() && !link->lastWasContMajor() && !link->isCont() && !ignoreRedLink) {
    3843     17843895 :                 if (!determinedFoePresence && (canBrake || !yellow)) {
    3844     16858083 :                     vSafe = dpi.myVLinkWait;
    3845     16858083 :                     myHaveToWaitOnNextLink = true;
    3846              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3847              :                     if (DEBUG_COND) {
    3848              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (minor)\n";
    3849              :                     }
    3850              : #endif
    3851     16858083 :                     break;
    3852              :                 } else {
    3853              :                     // past the point of no return. we need to drive fast enough
    3854              :                     // to make it across the link. However, minor slowdowns
    3855              :                     // should be permissible to follow leading traffic safely
    3856              :                     // basically, this code prevents dawdling
    3857              :                     // (it's harder to do this later using
    3858              :                     // SUMO_ATTR_JM_SIGMA_MINOR because we don't know whether the
    3859              :                     // vehicle is already too close to stop at that part of the code)
    3860              :                     //
    3861              :                     // XXX: There is a problem in subsecond simulation: If we cannot
    3862              :                     // make it across the minor link in one step, new traffic
    3863              :                     // could appear on a major foe link and cause a collision. Refs. #1845, #2123
    3864       985812 :                     vSafeMinDist = dpi.myDistance; // distance that must be covered
    3865       985812 :                     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3866      1798776 :                         vSafeMin = MIN3((double)DIST2SPEED(vSafeMinDist + POSITION_EPS), dpi.myVLinkPass, cfModel.maxNextSafeMin(getSpeed(), this));
    3867              :                     } else {
    3868       172848 :                         vSafeMin = MIN3((double)DIST2SPEED(2 * vSafeMinDist + NUMERICAL_EPS) - getSpeed(), dpi.myVLinkPass, cfModel.maxNextSafeMin(getSpeed(), this));
    3869              :                     }
    3870              :                     canBrakeVSafeMin = canBrake;
    3871              : #ifdef DEBUG_EXEC_MOVE
    3872              :                     if (DEBUG_COND) {
    3873              :                         std::cout << "     vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << " canBrake=" << canBrake << "\n";
    3874              :                     }
    3875              : #endif
    3876              :                 }
    3877              :             }
    3878              :             // have waited; may pass if opened...
    3879    646391212 :             if (opened) {
    3880    640685465 :                 vSafe = dpi.myVLinkPass;
    3881    640685465 :                 if (vSafe < cfModel.getMaxDecel() && vSafe <= dpi.myVLinkWait && vSafe < cfModel.maxNextSpeed(getSpeed(), this)) {
    3882              :                     // this vehicle is probably not gonna drive across the next junction (heuristic)
    3883     55487642 :                     myHaveToWaitOnNextLink = true;
    3884              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3885              :                     if (DEBUG_COND) {
    3886              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (very slow)\n";
    3887              :                     }
    3888              : #endif
    3889              :                 }
    3890    640685465 :                 if (link->mustStop() && determinedFoePresence && myHaveStoppedFor == nullptr) {
    3891        20820 :                     myHaveStoppedFor = link;
    3892              :                 }
    3893      5705747 :             } else if (link->getState() == LINKSTATE_ZIPPER) {
    3894      1327718 :                 vSafeZipper = MIN2(vSafeZipper,
    3895      1327718 :                                    link->getZipperSpeed(this, dpi.myDistance, dpi.myVLinkPass, dpi.myArrivalTime, &collectFoes));
    3896              :             } else if (!canBrake
    3897              :                        // always brake hard for traffic lights (since an emergency stop is necessary anyway)
    3898         1882 :                        && link->getTLLogic() == nullptr
    3899              :                        // cannot brake even with emergency deceleration
    3900      4378914 :                        && dpi.myDistance < cfModel.brakeGap(myState.mySpeed, cfModel.getEmergencyDecel(), 0.)) {
    3901              : #ifdef DEBUG_EXEC_MOVE
    3902              :                 if (DEBUG_COND) {
    3903              :                     std::cout << SIMTIME << " too fast to brake for closed link\n";
    3904              :                 }
    3905              : #endif
    3906          233 :                 vSafe = dpi.myVLinkPass;
    3907              :             } else {
    3908      4377796 :                 vSafe = dpi.myVLinkWait;
    3909      4377796 :                 myHaveToWaitOnNextLink = true;
    3910              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3911              :                 if (DEBUG_COND) {
    3912              :                     std::cout << SIMTIME << " veh=" << getID() << " haveToWait (closed)\n";
    3913              :                 }
    3914              : #endif
    3915              : #ifdef DEBUG_EXEC_MOVE
    3916              :                 if (DEBUG_COND) {
    3917              :                     std::cout << SIMTIME << " braking for closed link=" << link->getViaLaneOrLane()->getID() << "\n";
    3918              :                 }
    3919              : #endif
    3920      4377796 :                 break;
    3921              :             }
    3922    642013416 :             if (myLane->isInternal() && myJunctionEntryTime == SUMOTime_MAX) {
    3923              :                 // request was renewed, restoring entry time
    3924              :                 // @note: using myJunctionEntryTimeNeverYield could lead to inconsistencies with other vehicles already on the junction
    3925        79833 :                 myJunctionEntryTime = SIMSTEP;;
    3926              :             }
    3927    663249295 :         } else {
    3928    440481450 :             if (link != nullptr && link->getInternalLaneBefore() != nullptr && myLane->isInternal() && link->getJunction() == myLane->getEdge().getToJunction()) {
    3929              :                 // blocked on the junction. yield request so other vehicles may
    3930              :                 // become junction leader
    3931              : #ifdef DEBUG_EXEC_MOVE
    3932              :                 if (DEBUG_COND) {
    3933              :                     std::cout << SIMTIME << " resetting junctionEntryTime at junction '" << link->getJunction()->getID() << "' beause of non-request exitLink\n";
    3934              :                 }
    3935              : #endif
    3936       262328 :                 myJunctionEntryTime = SUMOTime_MAX;
    3937       262328 :                 myJunctionConflictEntryTime = SUMOTime_MAX;
    3938              :             }
    3939              :             // we have: i->link == 0 || !i->setRequest
    3940    440481450 :             vSafe = dpi.myVLinkWait;
    3941    440481450 :             if (link != nullptr || myStopDist < (myLane->getLength() - getPositionOnLane())) {
    3942    111286311 :                 if (vSafe < getSpeed()) {
    3943     16402544 :                     myHaveToWaitOnNextLink = true;
    3944              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3945              :                     if (DEBUG_COND) {
    3946              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, braking) vSafe=" << vSafe << "\n";
    3947              :                     }
    3948              : #endif
    3949     94883767 :                 } else if (vSafe < SUMO_const_haltingSpeed) {
    3950     67431414 :                     myHaveToWaitOnNextLink = true;
    3951              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3952              :                     if (DEBUG_COND) {
    3953              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, stopping)\n";
    3954              :                     }
    3955              : #endif
    3956              :                 }
    3957              :             }
    3958    333650165 :             if (link == nullptr && myLFLinkLanes.size() == 1
    3959    263868822 :                     && getBestLanesContinuation().size() > 1
    3960      1127215 :                     && getBestLanesContinuation()[1]->hadPermissionChanges()
    3961    440618786 :                     && myLane->getFirstAnyVehicle() == this) {
    3962              :                 // temporal lane closing without notification, visible to the
    3963              :                 // vehicle at the front of the queue
    3964        35619 :                 updateBestLanes(true);
    3965              :                 //std::cout << SIMTIME << " veh=" << getID() << " updated bestLanes=" << toString(getBestLanesContinuation()) << "\n";
    3966              :             }
    3967              :             break;
    3968              :         }
    3969              :     }
    3970              : 
    3971              : //#ifdef DEBUG_EXEC_MOVE
    3972              : //    if (DEBUG_COND) {
    3973              : //        std::cout << "\nvCurrent = " << toString(getSpeed(), 24) << "" << std::endl;
    3974              : //        std::cout << "vSafe = " << toString(vSafe, 24) << "" << std::endl;
    3975              : //        std::cout << "vSafeMin = " << toString(vSafeMin, 24) << "" << std::endl;
    3976              : //        std::cout << "vSafeMinDist = " << toString(vSafeMinDist, 24) << "" << std::endl;
    3977              : //
    3978              : //        double gap = getLeader().second;
    3979              : //        std::cout << "gap = " << toString(gap, 24) << std::endl;
    3980              : //        std::cout << "vSafeStoppedLeader = " << toString(getCarFollowModel().stopSpeed(this, getSpeed(), gap, MSCFModel::CalcReason::FUTURE), 24)
    3981              : //                << "\n" << std::endl;
    3982              : //    }
    3983              : //#endif
    3984              : 
    3985    637097452 :     if ((MSGlobals::gSemiImplicitEulerUpdate && vSafe + NUMERICAL_EPS < vSafeMin)
    3986    636875129 :             || (!MSGlobals::gSemiImplicitEulerUpdate && (vSafe + NUMERICAL_EPS < vSafeMin && vSafeMin != 0))) { // this might be good for the euler case as well
    3987              :         // XXX: (Leo) This often called stopSpeed with vSafeMinDist==0 (for the ballistic update), since vSafe can become negative
    3988              :         //      For the Euler update the term '+ NUMERICAL_EPS' prevented a call here... Recheck, consider of -INVALID_SPEED instead of 0 to indicate absence of vSafeMin restrictions. Refs. #2577
    3989              : #ifdef DEBUG_EXEC_MOVE
    3990              :         if (DEBUG_COND) {
    3991              :             std::cout << "vSafeMin Problem? vSafe=" << vSafe << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << std::endl;
    3992              :         }
    3993              : #endif
    3994       263502 :         if (canBrakeVSafeMin && vSafe < getSpeed()) {
    3995              :             // cannot drive across a link so we need to stop before it
    3996       127612 :             vSafe = MIN2(vSafe, MAX2(getCarFollowModel().minNextSpeed(getSpeed(), this),
    3997        63806 :                                      getCarFollowModel().stopSpeed(this, getSpeed(), vSafeMinDist)));
    3998        63806 :             vSafeMin = 0;
    3999        63806 :             myHaveToWaitOnNextLink = true;
    4000              : #ifdef DEBUG_CHECKREWINDLINKLANES
    4001              :             if (DEBUG_COND) {
    4002              :                 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (vSafe=" << vSafe << " < vSafeMin=" << vSafeMin << ")\n";
    4003              :             }
    4004              : #endif
    4005              :         } else {
    4006              :             // if the link is yellow or visibility distance is large
    4007              :             // then we might not make it across the link in one step anyway..
    4008              :             // Possibly, the lane after the intersection has a lower speed limit so
    4009              :             // we really need to drive slower already
    4010              :             // -> keep driving without dawdling
    4011       199696 :             vSafeMin = vSafe;
    4012              :         }
    4013              :     }
    4014              : 
    4015              :     // vehicles inside a roundabout should maintain their requests
    4016    637097452 :     if (myLane->getEdge().isRoundabout()) {
    4017      2682137 :         myHaveToWaitOnNextLink = false;
    4018              :     }
    4019              : 
    4020    637097452 :     vSafe = MIN2(vSafe, vSafeZipper);
    4021    637097452 : }
    4022              : 
    4023              : 
    4024              : double
    4025    704971385 : MSVehicle::processTraCISpeedControl(double vSafe, double vNext) {
    4026    704971385 :     if (myInfluencer != nullptr) {
    4027       497188 :         myInfluencer->setOriginalSpeed(vNext);
    4028              : #ifdef DEBUG_TRACI
    4029              :         if DEBUG_COND2(this) {
    4030              :             std::cout << SIMTIME << " MSVehicle::processTraCISpeedControl() for vehicle '" << getID() << "'"
    4031              :                       << " vSafe=" << vSafe << " (init)vNext=" << vNext << " keepStopping=" << keepStopping();
    4032              :         }
    4033              : #endif
    4034       497188 :         if (myInfluencer->isRemoteControlled()) {
    4035         7320 :             vNext = myInfluencer->implicitSpeedRemote(this, myState.mySpeed);
    4036              :         }
    4037       497188 :         const double vMax = getVehicleType().getCarFollowModel().maxNextSpeed(myState.mySpeed, this);
    4038       497188 :         double vMin = getVehicleType().getCarFollowModel().minNextSpeed(myState.mySpeed, this);
    4039       497188 :         if (MSGlobals::gSemiImplicitEulerUpdate) {
    4040              :             vMin = MAX2(0., vMin);
    4041              :         }
    4042       497188 :         vNext = myInfluencer->influenceSpeed(MSNet::getInstance()->getCurrentTimeStep(), vNext, vSafe, vMin, vMax);
    4043       497188 :         if (keepStopping() && myStops.front().getSpeed() == 0) {
    4044              :             // avoid driving while stopped (unless it's actually a waypoint
    4045         3818 :             vNext = myInfluencer->getOriginalSpeed();
    4046              :         }
    4047              : #ifdef DEBUG_TRACI
    4048              :         if DEBUG_COND2(this) {
    4049              :             std::cout << " (processed)vNext=" << vNext << std::endl;
    4050              :         }
    4051              : #endif
    4052              :     }
    4053    704971385 :     return vNext;
    4054              : }
    4055              : 
    4056              : 
    4057              : void
    4058     71561936 : MSVehicle::removePassedDriveItems() {
    4059              : #ifdef DEBUG_ACTIONSTEPS
    4060              :     if (DEBUG_COND) {
    4061              :         std::cout << SIMTIME << " veh=" << getID() << " removePassedDriveItems()\n"
    4062              :                   << "    Current items: ";
    4063              :         for (auto& j : myLFLinkLanes) {
    4064              :             if (j.myLink == 0) {
    4065              :                 std::cout << "\n    Stop at distance " << j.myDistance;
    4066              :             } else {
    4067              :                 const MSLane* to = j.myLink->getViaLaneOrLane();
    4068              :                 const MSLane* from = j.myLink->getLaneBefore();
    4069              :                 std::cout << "\n    Link at distance " << j.myDistance << ": '"
    4070              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    4071              :             }
    4072              :         }
    4073              :         std::cout << "\n    myNextDriveItem: ";
    4074              :         if (myLFLinkLanes.size() != 0) {
    4075              :             if (myNextDriveItem->myLink == 0) {
    4076              :                 std::cout << "\n    Stop at distance " << myNextDriveItem->myDistance;
    4077              :             } else {
    4078              :                 const MSLane* to = myNextDriveItem->myLink->getViaLaneOrLane();
    4079              :                 const MSLane* from = myNextDriveItem->myLink->getLaneBefore();
    4080              :                 std::cout << "\n    Link at distance " << myNextDriveItem->myDistance << ": '"
    4081              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    4082              :             }
    4083              :         }
    4084              :         std::cout << std::endl;
    4085              :     }
    4086              : #endif
    4087     71886683 :     for (auto j = myLFLinkLanes.begin(); j != myNextDriveItem; ++j) {
    4088              : #ifdef DEBUG_ACTIONSTEPS
    4089              :         if (DEBUG_COND) {
    4090              :             std::cout << "    Removing item: ";
    4091              :             if (j->myLink == 0) {
    4092              :                 std::cout << "Stop at distance " << j->myDistance;
    4093              :             } else {
    4094              :                 const MSLane* to = j->myLink->getViaLaneOrLane();
    4095              :                 const MSLane* from = j->myLink->getLaneBefore();
    4096              :                 std::cout << "Link at distance " << j->myDistance << ": '"
    4097              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    4098              :             }
    4099              :             std::cout << std::endl;
    4100              :         }
    4101              : #endif
    4102       324747 :         if (j->myLink != nullptr) {
    4103       324674 :             j->myLink->removeApproaching(this);
    4104              :         }
    4105              :     }
    4106     71561936 :     myLFLinkLanes.erase(myLFLinkLanes.begin(), myNextDriveItem);
    4107     71561936 :     myNextDriveItem = myLFLinkLanes.begin();
    4108     71561936 : }
    4109              : 
    4110              : 
    4111              : void
    4112      1138103 : MSVehicle::updateDriveItems() {
    4113              : #ifdef DEBUG_ACTIONSTEPS
    4114              :     if (DEBUG_COND) {
    4115              :         std::cout << SIMTIME << " updateDriveItems(), veh='" << getID() << "' (lane: '" << getLane()->getID() << "')\nCurrent drive items:" << std::endl;
    4116              :         for (const auto& dpi : myLFLinkLanes) {
    4117              :             std::cout
    4118              :                     << " vPass=" << dpi.myVLinkPass
    4119              :                     << " vWait=" << dpi.myVLinkWait
    4120              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    4121              :                     << " request=" << dpi.mySetRequest
    4122              :                     << "\n";
    4123              :         }
    4124              :         std::cout << " myNextDriveItem's linked lane: " << (myNextDriveItem->myLink == 0 ? "NULL" : myNextDriveItem->myLink->getViaLaneOrLane()->getID()) << std::endl;
    4125              :     }
    4126              : #endif
    4127      1138103 :     if (myLFLinkLanes.size() == 0) {
    4128              :         // nothing to update
    4129              :         return;
    4130              :     }
    4131              :     const MSLink* nextPlannedLink = nullptr;
    4132              : //    auto i = myLFLinkLanes.begin();
    4133      1138101 :     auto i = myNextDriveItem;
    4134      2276157 :     while (i != myLFLinkLanes.end() && nextPlannedLink == nullptr) {
    4135      1138056 :         nextPlannedLink = i->myLink;
    4136              :         ++i;
    4137              :     }
    4138              : 
    4139      1138101 :     if (nextPlannedLink == nullptr) {
    4140              :         // No link for upcoming item -> no need for an update
    4141              : #ifdef DEBUG_ACTIONSTEPS
    4142              :         if (DEBUG_COND) {
    4143              :             std::cout << "Found no link-related drive item." << std::endl;
    4144              :         }
    4145              : #endif
    4146              :         return;
    4147              :     }
    4148              : 
    4149       557363 :     if (getLane() == nextPlannedLink->getLaneBefore()) {
    4150              :         // Current lane approaches the stored next link, i.e. no LC happend and no update is required.
    4151              : #ifdef DEBUG_ACTIONSTEPS
    4152              :         if (DEBUG_COND) {
    4153              :             std::cout << "Continuing on planned lane sequence, no update required." << std::endl;
    4154              :         }
    4155              : #endif
    4156              :         return;
    4157              :     }
    4158              :     // Lane must have been changed, determine the change direction
    4159       547321 :     const MSLink* parallelLink = nextPlannedLink->getParallelLink(1);
    4160       547321 :     if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4161              :         // lcDir = 1;
    4162              :     } else {
    4163       265866 :         parallelLink = nextPlannedLink->getParallelLink(-1);
    4164       265866 :         if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4165              :             // lcDir = -1;
    4166              :         } else {
    4167              :             // If the vehicle's current lane is not the approaching lane for the next
    4168              :             // drive process item's link, it is expected to lead to a parallel link,
    4169              :             // XXX: What if the lc was an overtaking maneuver and there is no upcoming link?
    4170              :             //      Then a stop item should be scheduled! -> TODO!
    4171              :             //assert(false);
    4172        72832 :             return;
    4173              :         }
    4174              :     }
    4175              : #ifdef DEBUG_ACTIONSTEPS
    4176              :     if (DEBUG_COND) {
    4177              :         std::cout << "Changed lane. Drive items will be updated along the current lane continuation." << std::endl;
    4178              :     }
    4179              : #endif
    4180              :     // Trace link sequence along current best lanes and transfer drive items to the corresponding links
    4181              : //        DriveItemVector::iterator driveItemIt = myLFLinkLanes.begin();
    4182       474489 :     DriveItemVector::iterator driveItemIt = myNextDriveItem;
    4183              :     // In the loop below, lane holds the currently considered lane on the vehicles continuation (including internal lanes)
    4184       474489 :     const MSLane* lane = myLane;
    4185              :     assert(myLane == parallelLink->getLaneBefore());
    4186              :     // *lit is a pointer to the next lane in best continuations for the current lane (always non-internal)
    4187       474489 :     std::vector<MSLane*>::const_iterator bestLaneIt = getBestLanesContinuation().begin() + 1;
    4188              :     // Pointer to the new link for the current drive process item
    4189              :     MSLink* newLink = nullptr;
    4190      1772834 :     while (driveItemIt != myLFLinkLanes.end()) {
    4191      1327032 :         if (driveItemIt->myLink == nullptr) {
    4192              :             // Items not related to a specific link are not updated
    4193              :             // (XXX: when a stop item corresponded to a dead end, which is overcome by the LC that made
    4194              :             //       the update necessary, this may slow down the vehicle's continuation on the new lane...)
    4195              :             ++driveItemIt;
    4196       171856 :             continue;
    4197              :         }
    4198              :         // Continuation links for current best lanes are less than for the former drive items (myLFLinkLanes)
    4199              :         // We just remove the leftover link-items, as they cannot be mapped to new links.
    4200      1155176 :         if (bestLaneIt == getBestLanesContinuation().end()) {
    4201              : #ifdef DEBUG_ACTIONSTEPS
    4202              :             if (DEBUG_COND) {
    4203              :                 std::cout << "Reached end of the new continuation sequence. Erasing leftover link-items." << std::endl;
    4204              :             }
    4205              : #endif
    4206        91086 :             while (driveItemIt != myLFLinkLanes.end()) {
    4207        62399 :                 if (driveItemIt->myLink == nullptr) {
    4208              :                     ++driveItemIt;
    4209        14241 :                     continue;
    4210              :                 } else {
    4211        48158 :                     driveItemIt->myLink->removeApproaching(this);
    4212              :                     driveItemIt = myLFLinkLanes.erase(driveItemIt);
    4213              :                 }
    4214              :             }
    4215              :             break;
    4216              :         }
    4217              :         // Do the actual link-remapping for the item. And un/register approaching information on the corresponding links
    4218      1126489 :         const MSLane* const target = *bestLaneIt;
    4219              :         assert(!target->isInternal());
    4220              :         newLink = nullptr;
    4221      1241901 :         for (MSLink* const link : lane->getLinkCont()) {
    4222      1241901 :             if (link->getLane() == target) {
    4223              :                 newLink = link;
    4224              :                 break;
    4225              :             }
    4226              :         }
    4227              : 
    4228      1126489 :         if (newLink == driveItemIt->myLink) {
    4229              :             // new continuation merged into previous - stop update
    4230              : #ifdef DEBUG_ACTIONSTEPS
    4231              :             if (DEBUG_COND) {
    4232              :                 std::cout << "Old and new continuation sequences merge at link\n"
    4233              :                           << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'"
    4234              :                           << "\nNo update beyond merge required." << std::endl;
    4235              :             }
    4236              : #endif
    4237              :             break;
    4238              :         }
    4239              : 
    4240              : #ifdef DEBUG_ACTIONSTEPS
    4241              :         if (DEBUG_COND) {
    4242              :             std::cout << "lane=" << lane->getID() << "\nUpdating link\n    '" << driveItemIt->myLink->getLaneBefore()->getID() << "'->'" << driveItemIt->myLink->getViaLaneOrLane()->getID() << "'"
    4243              :                       << "==> " << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'" << std::endl;
    4244              :         }
    4245              : #endif
    4246      1126489 :         newLink->setApproaching(this, driveItemIt->myLink->getApproaching(this));
    4247      1126489 :         driveItemIt->myLink->removeApproaching(this);
    4248      1126489 :         driveItemIt->myLink = newLink;
    4249              :         lane = newLink->getViaLaneOrLane();
    4250              :         ++driveItemIt;
    4251      1126489 :         if (!lane->isInternal()) {
    4252              :             ++bestLaneIt;
    4253              :         }
    4254              :     }
    4255              : #ifdef DEBUG_ACTIONSTEPS
    4256              :     if (DEBUG_COND) {
    4257              :         std::cout << "Updated drive items:" << std::endl;
    4258              :         for (const auto& dpi : myLFLinkLanes) {
    4259              :             std::cout
    4260              :                     << " vPass=" << dpi.myVLinkPass
    4261              :                     << " vWait=" << dpi.myVLinkWait
    4262              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    4263              :                     << " request=" << dpi.mySetRequest
    4264              :                     << "\n";
    4265              :         }
    4266              :     }
    4267              : #endif
    4268              : }
    4269              : 
    4270              : 
    4271              : void
    4272    704971385 : MSVehicle::setBrakingSignals(double vNext) {
    4273              :     // To avoid casual blinking brake lights at high speeds due to dawdling of the
    4274              :     // leading vehicle, we don't show brake lights when the deceleration could be caused
    4275              :     // by frictional forces and air resistance (i.e. proportional to v^2, coefficient could be adapted further)
    4276    704971385 :     double pseudoFriction = (0.05 +  0.005 * getSpeed()) * getSpeed();
    4277    704971385 :     bool brakelightsOn = vNext < getSpeed() - ACCEL2SPEED(pseudoFriction);
    4278              : 
    4279    704971385 :     if (vNext <= SUMO_const_haltingSpeed) {
    4280              :         brakelightsOn = true;
    4281              :     }
    4282    704971385 :     if (brakelightsOn && !isStopped()) {
    4283              :         switchOnSignal(VEH_SIGNAL_BRAKELIGHT);
    4284              :     } else {
    4285              :         switchOffSignal(VEH_SIGNAL_BRAKELIGHT);
    4286              :     }
    4287    704971385 : }
    4288              : 
    4289              : 
    4290              : void
    4291    705038181 : MSVehicle::updateWaitingTime(double vNext) {
    4292    705038181 :     if (vNext <= SUMO_const_haltingSpeed && (!isStopped() || isIdling()) && myAcceleration <= accelThresholdForWaiting())  {
    4293     95442158 :         myWaitingTime += DELTA_T;
    4294     95442158 :         myWaitingTimeCollector.passTime(DELTA_T, true);
    4295              :     } else {
    4296    609596023 :         myWaitingTime = 0;
    4297    609596023 :         myWaitingTimeCollector.passTime(DELTA_T, false);
    4298    609596023 :         if (hasInfluencer()) {
    4299       271165 :             getInfluencer().setExtraImpatience(0);
    4300              :         }
    4301              :     }
    4302    705038181 : }
    4303              : 
    4304              : 
    4305              : void
    4306    704971239 : MSVehicle::updateTimeLoss(double vNext) {
    4307              :     // update time loss (depends on the updated edge)
    4308    704971239 :     if (!isStopped()) {
    4309              :         // some cfModels (i.e. EIDM may drive faster than predicted by maxNextSpeed)
    4310    694691487 :         const double vmax = MIN2(myLane->getVehicleMaxSpeed(this), MAX2(myStopSpeed, vNext));
    4311    690952406 :         if (vmax > 0) {
    4312    690943565 :             myTimeLoss += TS * (vmax - vNext) / vmax;
    4313              :         }
    4314              :     }
    4315    704971239 : }
    4316              : 
    4317              : 
    4318              : double
    4319   1586058360 : MSVehicle::checkReversal(bool& canReverse, double speedThreshold, double seen) const {
    4320     63742030 :     const bool stopOk = (myStops.empty() || myStops.front().edge != myCurrEdge
    4321   1618167274 :                          || (myStops.front().getSpeed() > 0 && myState.myPos > myStops.front().pars.endPos - 2 * POSITION_EPS));
    4322              : #ifdef DEBUG_REVERSE_BIDI
    4323              :     if (DEBUG_COND) std::cout << SIMTIME  << " checkReversal lane=" << myLane->getID()
    4324              :                                   << " pos=" << myState.myPos
    4325              :                                   << " speed=" << std::setprecision(6) << getPreviousSpeed() << std::setprecision(gPrecision)
    4326              :                                   << " speedThreshold=" << speedThreshold
    4327              :                                   << " seen=" << seen
    4328              :                                   << " isRail=" << isRail()
    4329              :                                   << " speedOk=" << (getPreviousSpeed() <= speedThreshold)
    4330              :                                   << " posOK=" << (myState.myPos <= myLane->getLength())
    4331              :                                   << " normal=" << !myLane->isInternal()
    4332              :                                   << " routeOK=" << ((myCurrEdge + 1) != myRoute->end())
    4333              :                                   << " bidi=" << (myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1))
    4334              :                                   << " stopOk=" << stopOk
    4335              :                                   << "\n";
    4336              : #endif
    4337   1586058360 :     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4338      7282893 :             && getPreviousSpeed() <= speedThreshold
    4339      6203866 :             && myState.myPos <= myLane->getLength()
    4340      6202761 :             && !myLane->isInternal()
    4341      6128806 :             && (myCurrEdge + 1) != myRoute->end()
    4342      6017730 :             && myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1)
    4343              :             // ensure there are no further stops on this edge
    4344   1586907634 :             && stopOk
    4345              :        ) {
    4346              :         //if (isSelected()) std::cout << "   check1 passed\n";
    4347              : 
    4348              :         // ensure that the vehicle is fully on bidi edges that allow reversal
    4349       180793 :         const int neededFutureRoute = 1 + (int)(MSGlobals::gUsingInternalLanes
    4350              :                                                 ? myFurtherLanes.size()
    4351          504 :                                                 : ceil((double)myFurtherLanes.size() / 2.0));
    4352       180793 :         const int remainingRoute = int(myRoute->end() - myCurrEdge) - 1;
    4353       180793 :         if (remainingRoute < neededFutureRoute) {
    4354              : #ifdef DEBUG_REVERSE_BIDI
    4355              :             if (DEBUG_COND) {
    4356              :                 std::cout << "    fail: remainingEdges=" << ((int)(myRoute->end() - myCurrEdge)) << " further=" << myFurtherLanes.size() << "\n";
    4357              :             }
    4358              : #endif
    4359         3567 :             return getMaxSpeed();
    4360              :         }
    4361              :         //if (isSelected()) std::cout << "   check2 passed\n";
    4362              : 
    4363              :         // ensure that the turn-around connection exists from the current edge to its bidi-edge
    4364       177226 :         const MSEdgeVector& succ = myLane->getEdge().getSuccessors();
    4365       177226 :         if (std::find(succ.begin(), succ.end(), myLane->getEdge().getBidiEdge()) == succ.end()) {
    4366              : #ifdef DEBUG_REVERSE_BIDI
    4367              :             if (DEBUG_COND) {
    4368              :                 std::cout << "    noTurn (bidi=" << myLane->getEdge().getBidiEdge()->getID() << " succ=" << toString(succ) << "\n";
    4369              :             }
    4370              : #endif
    4371          909 :             return getMaxSpeed();
    4372              :         }
    4373              :         //if (isSelected()) std::cout << "   check3 passed\n";
    4374              : 
    4375              :         // ensure that the vehicle front will not move past a stop on the bidi edge of the current edge
    4376       176317 :         if (!myStops.empty() && myStops.front().edge == (myCurrEdge + 1)) {
    4377       160006 :             const double stopPos = myStops.front().getEndPos(*this);
    4378       160006 :             const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
    4379       160006 :             const double newPos = myLane->getLength() - (getBackPositionOnLane() + brakeDist);
    4380       160006 :             if (newPos > stopPos) {
    4381              : #ifdef DEBUG_REVERSE_BIDI
    4382              :                 if (DEBUG_COND) {
    4383              :                     std::cout << "    reversal would go past stop on " << myLane->getBidiLane()->getID() << "\n";
    4384              :                 }
    4385              : #endif
    4386       158332 :                 if (seen > MAX2(brakeDist, 1.0)) {
    4387       157202 :                     return getMaxSpeed();
    4388              :                 } else {
    4389              : #ifdef DEBUG_REVERSE_BIDI
    4390              :                     if (DEBUG_COND) {
    4391              :                         std::cout << "    train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
    4392              :                     }
    4393              : #endif
    4394              :                 }
    4395              :             }
    4396              :         }
    4397              :         //if (isSelected()) std::cout << "   check4 passed\n";
    4398              : 
    4399              :         // ensure that bidi-edges exist for all further edges
    4400              :         // and that no stops will be skipped when reversing
    4401              :         // and that the train will not be on top of a red rail signal after reversal
    4402        19115 :         const MSLane* bidi = myLane->getBidiLane();
    4403              :         int view = 2;
    4404        38572 :         for (MSLane* further : myFurtherLanes) {
    4405        21893 :             if (!further->getEdge().isInternal()) {
    4406        11393 :                 if (further->getEdge().getBidiEdge() != *(myCurrEdge + view)) {
    4407              : #ifdef DEBUG_REVERSE_BIDI
    4408              :                     if (DEBUG_COND) {
    4409              :                         std::cout << "    noBidi view=" << view << " further=" << further->getID() << " furtherBidi=" << Named::getIDSecure(further->getEdge().getBidiEdge()) << " future=" << (*(myCurrEdge + view))->getID() << "\n";
    4410              :                     }
    4411              : #endif
    4412         2277 :                     return getMaxSpeed();
    4413              :                 }
    4414         9116 :                 const MSLane* nextBidi = further->getBidiLane();
    4415         9116 :                 const MSLink* toNext = bidi->getLinkTo(nextBidi);
    4416         9116 :                 if (toNext == nullptr) {
    4417              :                     // can only happen if the route is invalid
    4418            0 :                     return getMaxSpeed();
    4419              :                 }
    4420         9116 :                 if (toNext->haveRed()) {
    4421              : #ifdef DEBUG_REVERSE_BIDI
    4422              :                     if (DEBUG_COND) {
    4423              :                         std::cout << "    do not reverse on a red signal\n";
    4424              :                     }
    4425              : #endif
    4426            0 :                     return getMaxSpeed();
    4427              :                 }
    4428              :                 bidi = nextBidi;
    4429         9116 :                 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + view)) {
    4430          453 :                     const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
    4431          453 :                     const double stopPos = myStops.front().getEndPos(*this);
    4432          453 :                     const double newPos = further->getLength() - (getBackPositionOnLane(further) + brakeDist);
    4433          453 :                     if (newPos > stopPos) {
    4434              : #ifdef DEBUG_REVERSE_BIDI
    4435              :                         if (DEBUG_COND) {
    4436              :                             std::cout << "    reversal would go past stop on further-opposite lane " << further->getBidiLane()->getID() << "\n";
    4437              :                         }
    4438              : #endif
    4439          171 :                         if (seen > MAX2(brakeDist, 1.0)) {
    4440          159 :                             canReverse = false;
    4441          159 :                             return getMaxSpeed();
    4442              :                         } else {
    4443              : #ifdef DEBUG_REVERSE_BIDI
    4444              :                             if (DEBUG_COND) {
    4445              :                                 std::cout << "    train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
    4446              :                             }
    4447              : #endif
    4448              :                         }
    4449              :                     }
    4450              :                 }
    4451         8957 :                 view++;
    4452              :             }
    4453              :         }
    4454              :         // reverse as soon as comfortably possible
    4455        16679 :         const double vMinComfortable = getCarFollowModel().minNextSpeed(getSpeed(), this);
    4456              : #ifdef DEBUG_REVERSE_BIDI
    4457              :         if (DEBUG_COND) {
    4458              :             std::cout << SIMTIME << " seen=" << seen  << " vReverseOK=" << vMinComfortable << "\n";
    4459              :         }
    4460              : #endif
    4461        16679 :         canReverse = true;
    4462        16679 :         return vMinComfortable;
    4463              :     }
    4464   1585877567 :     return getMaxSpeed();
    4465              : }
    4466              : 
    4467              : 
    4468              : void
    4469    705189714 : MSVehicle::processLaneAdvances(std::vector<MSLane*>& passedLanes, std::string& emergencyReason) {
    4470    721136286 :     for (std::vector<MSLane*>::reverse_iterator i = myFurtherLanes.rbegin(); i != myFurtherLanes.rend(); ++i) {
    4471     15946572 :         passedLanes.push_back(*i);
    4472              :     }
    4473    705189714 :     if (passedLanes.size() == 0 || passedLanes.back() != myLane) {
    4474    705189714 :         passedLanes.push_back(myLane);
    4475              :     }
    4476              :     // let trains reverse direction
    4477    705189714 :     bool reverseTrain = false;
    4478    705189714 :     checkReversal(reverseTrain);
    4479    705189714 :     if (reverseTrain) {
    4480              :         // Train is 'reversing' so toggle the logical state
    4481          810 :         myAmReversed = !myAmReversed;
    4482              :         // add some slack to ensure that the back of train does appear looped
    4483          810 :         myState.myPos += 2 * (myLane->getLength() - myState.myPos) + myType->getLength() + NUMERICAL_EPS;
    4484          810 :         myState.mySpeed = 0;
    4485              : #ifdef DEBUG_REVERSE_BIDI
    4486              :         if (DEBUG_COND) {
    4487              :             std::cout << SIMTIME << " reversing train=" << getID() << " newPos=" << myState.myPos << "\n";
    4488              :         }
    4489              : #endif
    4490              :     }
    4491              :     // move on lane(s)
    4492    705189714 :     if (myState.myPos > myLane->getLength()) {
    4493              :         // The vehicle has moved at least to the next lane (maybe it passed even more than one)
    4494     20033395 :         if (myCurrEdge != myRoute->end() - 1) {
    4495     16899296 :             MSLane* approachedLane = myLane;
    4496              :             // move the vehicle forward
    4497     16899296 :             myNextDriveItem = myLFLinkLanes.begin();
    4498     36482863 :             while (myNextDriveItem != myLFLinkLanes.end() && approachedLane != nullptr && myState.myPos > approachedLane->getLength()) {
    4499     19602467 :                 const MSLink* link = myNextDriveItem->myLink;
    4500     19602467 :                 const double linkDist = myNextDriveItem->myDistance;
    4501              :                 ++myNextDriveItem;
    4502              :                 // check whether the vehicle was allowed to enter lane
    4503              :                 //  otherwise it is decelerated and we do not need to test for it's
    4504              :                 //  approach on the following lanes when a lane changing is performed
    4505              :                 // proceed to the next lane
    4506     19602467 :                 if (approachedLane->mustCheckJunctionCollisions()) {
    4507              :                     // vehicle moves past approachedLane within a single step, collision checking must still be done
    4508        66527 :                     MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(approachedLane);
    4509              :                 }
    4510     19602467 :                 if (link != nullptr) {
    4511     19598280 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4512        46034 :                             && !myLane->isInternal()
    4513        24232 :                             && myLane->getBidiLane() != nullptr
    4514        13042 :                             && link->getLane()->getBidiLane() == myLane
    4515     19599087 :                             && !reverseTrain) {
    4516              :                         emergencyReason = " because it must reverse direction";
    4517              :                         approachedLane = nullptr;
    4518              :                         break;
    4519              :                     }
    4520     19598277 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4521        46031 :                             && myState.myPos < myLane->getLength() + NUMERICAL_EPS
    4522     19598487 :                             && hasStops() && getNextStop().edge == myCurrEdge) {
    4523              :                         // avoid skipping stop due to numerical instability
    4524              :                         // this is a special case for rail vehicles because they
    4525              :                         // continue myLFLinkLanes past stops
    4526          196 :                         approachedLane = myLane;
    4527          196 :                         myState.myPos = myLane->getLength();
    4528          196 :                         break;
    4529              :                     }
    4530     19598081 :                     approachedLane = link->getViaLaneOrLane();
    4531     19598081 :                     if (myInfluencer == nullptr || myInfluencer->getEmergencyBrakeRedLight()) {
    4532     19596476 :                         bool beyondStopLine = linkDist < link->getLaneBefore()->getVehicleStopOffset(this);
    4533     19596476 :                         if (link->haveRed() && !ignoreRed(link, false) && !beyondStopLine && !reverseTrain) {
    4534              :                             emergencyReason = " because of a red traffic light";
    4535              :                             break;
    4536              :                         }
    4537              :                     }
    4538     19598012 :                     if (reverseTrain && approachedLane->isInternal()) {
    4539              :                         // avoid getting stuck on a slow turn-around internal lane
    4540          888 :                         myState.myPos += approachedLane->getLength();
    4541              :                     }
    4542         4187 :                 } else if (myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4543              :                     // avoid warning due to numerical instability
    4544          229 :                     approachedLane = myLane;
    4545          229 :                     myState.myPos = myLane->getLength();
    4546         3958 :                 } else if (reverseTrain) {
    4547            0 :                     approachedLane = (*(myCurrEdge + 1))->getLanes()[0];
    4548            0 :                     link = myLane->getLinkTo(approachedLane);
    4549              :                     assert(link != 0);
    4550            0 :                     while (link->getViaLane() != nullptr) {
    4551            0 :                         link = link->getViaLane()->getLinkCont()[0];
    4552              :                     }
    4553              :                     --myNextDriveItem;
    4554              :                 } else {
    4555              :                     emergencyReason = " because there is no connection to the next edge";
    4556              :                     approachedLane = nullptr;
    4557              :                     break;
    4558              :                 }
    4559     19598241 :                 if (approachedLane != myLane && approachedLane != nullptr) {
    4560     19598012 :                     leaveLane(MSMoveReminder::NOTIFICATION_JUNCTION, approachedLane);
    4561     19598012 :                     myState.myPos -= myLane->getLength();
    4562              :                     assert(myState.myPos > 0);
    4563     19598012 :                     enterLaneAtMove(approachedLane);
    4564     19598012 :                     if (link->isEntryLink()) {
    4565      7703382 :                         myJunctionEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4566      7703382 :                         myJunctionEntryTimeNeverYield = myJunctionEntryTime;
    4567      7703382 :                         myHaveStoppedFor = nullptr;
    4568              :                     }
    4569     19598012 :                     if (link->isConflictEntryLink()) {
    4570      7702785 :                         myJunctionConflictEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4571              :                         // renew yielded request
    4572      7702785 :                         myJunctionEntryTime = myJunctionEntryTimeNeverYield;
    4573              :                     }
    4574     19598012 :                     if (link->isExitLink()) {
    4575              :                         // passed junction, reset for approaching the next one
    4576      7641079 :                         myJunctionEntryTime = SUMOTime_MAX;
    4577      7641079 :                         myJunctionEntryTimeNeverYield = SUMOTime_MAX;
    4578      7641079 :                         myJunctionConflictEntryTime = SUMOTime_MAX;
    4579              :                     }
    4580              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    4581              :                     if (DEBUG_COND) {
    4582              :                         std::cout << "Update junctionTimes link=" << link->getViaLaneOrLane()->getID()
    4583              :                                   << " entry=" << link->isEntryLink() << " conflict=" << link->isConflictEntryLink() << " exit=" << link->isExitLink()
    4584              :                                   << " ET=" << myJunctionEntryTime
    4585              :                                   << " ETN=" << myJunctionEntryTimeNeverYield
    4586              :                                   << " CET=" << myJunctionConflictEntryTime
    4587              :                                   << "\n";
    4588              :                     }
    4589              : #endif
    4590     19598012 :                     if (hasArrivedInternal()) {
    4591              :                         break;
    4592              :                     }
    4593     19584094 :                     if (myLaneChangeModel->isChangingLanes()) {
    4594         7272 :                         if (link->getDirection() == LinkDirection::LEFT || link->getDirection() == LinkDirection::RIGHT) {
    4595              :                             // abort lane change
    4596           54 :                             WRITE_WARNINGF("Vehicle '%' could not finish continuous lane change (turn lane) time=%.", getID(), time2string(SIMSTEP));
    4597           18 :                             myLaneChangeModel->endLaneChangeManeuver();
    4598              :                         }
    4599              :                     }
    4600     19584094 :                     if (approachedLane->getEdge().isVaporizing()) {
    4601          756 :                         leaveLane(MSMoveReminder::NOTIFICATION_VAPORIZED_VAPORIZER);
    4602              :                         break;
    4603              :                     }
    4604     19583338 :                     passedLanes.push_back(approachedLane);
    4605              :                 }
    4606              :             }
    4607              :             // NOTE: Passed drive items will be erased in the next simstep's planMove()
    4608              : 
    4609              : #ifdef DEBUG_ACTIONSTEPS
    4610              :             if (DEBUG_COND && myNextDriveItem != myLFLinkLanes.begin()) {
    4611              :                 std::cout << "Updated drive items:" << std::endl;
    4612              :                 for (DriveItemVector::iterator i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
    4613              :                     std::cout
    4614              :                             << " vPass=" << (*i).myVLinkPass
    4615              :                             << " vWait=" << (*i).myVLinkWait
    4616              :                             << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
    4617              :                             << " request=" << (*i).mySetRequest
    4618              :                             << "\n";
    4619              :                 }
    4620              :             }
    4621              : #endif
    4622      3134099 :         } else if (!hasArrivedInternal() && myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4623              :             // avoid warning due to numerical instability when stopping at the end of the route
    4624           90 :             myState.myPos = myLane->getLength();
    4625              :         }
    4626              : 
    4627              :     }
    4628    705189714 : }
    4629              : 
    4630              : 
    4631              : 
    4632              : bool
    4633    708659388 : MSVehicle::executeMove() {
    4634              : #ifdef DEBUG_EXEC_MOVE
    4635              :     if (DEBUG_COND) {
    4636              :         std::cout << "\nEXECUTE_MOVE\n"
    4637              :                   << SIMTIME
    4638              :                   << " veh=" << getID()
    4639              :                   << " speed=" << getSpeed() // toString(getSpeed(), 24)
    4640              :                   << std::endl;
    4641              :     }
    4642              : #endif
    4643              : 
    4644              : 
    4645              :     // Maximum safe velocity
    4646    708659388 :     double vSafe = std::numeric_limits<double>::max();
    4647              :     // Minimum safe velocity (lower bound).
    4648    708659388 :     double vSafeMin = -std::numeric_limits<double>::max();
    4649              :     // The distance to a link, which should either be crossed this step
    4650              :     // or in front of which we need to stop.
    4651    708659388 :     double vSafeMinDist = 0;
    4652              : 
    4653    708659388 :     if (myActionStep) {
    4654              :         // Actuate control (i.e. choose bounds for safe speed in current simstep (euler), resp. after current sim step (ballistic))
    4655    637097452 :         processLinkApproaches(vSafe, vSafeMin, vSafeMinDist);
    4656              : #ifdef DEBUG_ACTIONSTEPS
    4657              :         if (DEBUG_COND) {
    4658              :             std::cout << SIMTIME << " vehicle '" << getID() << "'\n"
    4659              :                       "   vsafe from processLinkApproaches(): vsafe " << vSafe << std::endl;
    4660              :         }
    4661              : #endif
    4662              :     } else {
    4663              :         // Continue with current acceleration
    4664     71561936 :         vSafe = getSpeed() + ACCEL2SPEED(myAcceleration);
    4665              : #ifdef DEBUG_ACTIONSTEPS
    4666              :         if (DEBUG_COND) {
    4667              :             std::cout << SIMTIME << " vehicle '" << getID() << "' skips processLinkApproaches()\n"
    4668              :                       "   continues with constant accel " <<  myAcceleration << "...\n"
    4669              :                       << "speed: "  << getSpeed() << " -> " << vSafe << std::endl;
    4670              :         }
    4671              : #endif
    4672              :     }
    4673              : 
    4674              : 
    4675              : //#ifdef DEBUG_EXEC_MOVE
    4676              : //    if (DEBUG_COND) {
    4677              : //        std::cout << "vSafe = " << toString(vSafe,12) << "\n" << std::endl;
    4678              : //    }
    4679              : //#endif
    4680              : 
    4681              :     // Determine vNext = speed after current sim step (ballistic), resp. in current simstep (euler)
    4682              :     // Call to finalizeSpeed applies speed reduction due to dawdling / lane changing but ensures minimum safe speed
    4683    708659388 :     double vNext = vSafe;
    4684              :     const MSCFModel& cfModel = getCarFollowModel();
    4685    708659388 :     const double rawAccel = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4686    708659388 :     if (vNext <= SUMO_const_haltingSpeed * TS && myWaitingTime > MSGlobals::gStartupWaitThreshold && rawAccel <= accelThresholdForWaiting() && myActionStep) {
    4687     78640583 :         myTimeSinceStartup = 0;
    4688    630018805 :     } else if (isStopped()) {
    4689              :         // do not apply startupDelay for waypoints
    4690     17694960 :         if (cfModel.startupDelayStopped() && getNextStop().pars.speed <= 0) {
    4691        13772 :             myTimeSinceStartup = DELTA_T;
    4692              :         } else {
    4693              :             // do not apply startupDelay but signal that a stop has taken place
    4694     17681188 :             myTimeSinceStartup = cfModel.getStartupDelay() + DELTA_T;
    4695              :         }
    4696              :     } else {
    4697              :         // identify potential startup (before other effects reduce the speed again)
    4698    612323845 :         myTimeSinceStartup += DELTA_T;
    4699              :     }
    4700    708659388 :     if (myActionStep) {
    4701    637097452 :         vNext = cfModel.finalizeSpeed(this, vSafe);
    4702    633409303 :         if (vNext > 0) {
    4703    587337332 :             vNext = MAX2(vNext, vSafeMin);
    4704              :         }
    4705              :     }
    4706              :     // (Leo) to avoid tiny oscillations (< 1e-10) of vNext in a standing vehicle column (observed for ballistic update), we cap off vNext
    4707              :     //       (We assure to do this only for vNext<<NUMERICAL_EPS since otherwise this would nullify the workaround for #2995
    4708              :     // (Jakob) We also need to make sure to reach a stop at the start of the next edge
    4709    704971239 :     if (fabs(vNext) < NUMERICAL_EPS_SPEED && (myStopDist > POSITION_EPS || (hasStops() && myCurrEdge == getNextStop().edge))) {
    4710              :         vNext = 0.;
    4711              :     }
    4712              : #ifdef DEBUG_EXEC_MOVE
    4713              :     if (DEBUG_COND) {
    4714              :         std::cout << SIMTIME << " finalizeSpeed vSafe=" << vSafe << " vSafeMin=" << (vSafeMin == -std::numeric_limits<double>::max() ? "-Inf" : toString(vSafeMin))
    4715              :                   << " vNext=" << vNext << " (i.e. accel=" << SPEED2ACCEL(vNext - getSpeed()) << ")" << std::endl;
    4716              :     }
    4717              : #endif
    4718              : 
    4719              :     // vNext may be higher than vSafe without implying a bug:
    4720              :     //  - when approaching a green light that suddenly switches to yellow
    4721              :     //  - when using unregulated junctions
    4722              :     //  - when using tau < step-size
    4723              :     //  - when using unsafe car following models
    4724              :     //  - when using TraCI and some speedMode / laneChangeMode settings
    4725              :     //if (vNext > vSafe + NUMERICAL_EPS) {
    4726              :     //    WRITE_WARNING("vehicle '" + getID() + "' cannot brake hard enough to reach safe speed "
    4727              :     //            + toString(vSafe, 4) + ", moving at " + toString(vNext, 4) + " instead. time="
    4728              :     //            + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    4729              :     //}
    4730              : 
    4731    704971239 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4732              :         vNext = MAX2(vNext, 0.);
    4733              :     } else {
    4734              :         // (Leo) Ballistic: negative vNext can be used to indicate a stop within next step.
    4735              :     }
    4736              : 
    4737              :     // Check for speed advices from the traci client
    4738    704971239 :     vNext = processTraCISpeedControl(vSafe, vNext);
    4739              : 
    4740              :     // the acceleration of a vehicle equipped with the elecHybrid device is restricted by the maximal power of the electric drive as well
    4741    704971239 :     MSDevice_ElecHybrid* elecHybridOfVehicle = dynamic_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid)));
    4742          981 :     if (elecHybridOfVehicle != nullptr) {
    4743              :         // this is the consumption given by the car following model-computed acceleration
    4744          981 :         elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4745              :         // but the maximum power of the electric motor may be lower
    4746              :         // it needs to be converted from [W] to [Wh/s] (3600s / 1h) so that TS can be taken into account
    4747          981 :         double maxPower = getEmissionParameters()->getDoubleOptional(SUMO_ATTR_MAXIMUMPOWER, 100000.) / 3600;
    4748          981 :         if (elecHybridOfVehicle->getConsum() / TS > maxPower) {
    4749              :             // no, we cannot accelerate that fast, recompute the maximum possible acceleration
    4750           70 :             double accel = elecHybridOfVehicle->acceleration(*this, maxPower, this->getSpeed());
    4751              :             // and update the speed of the vehicle
    4752           70 :             vNext = MIN2(vNext, this->getSpeed() + accel * TS);
    4753              :             vNext = MAX2(vNext, 0.);
    4754              :             // and set the vehicle consumption to reflect this
    4755           70 :             elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4756              :         }
    4757              :     }
    4758              : 
    4759    704971239 :     setBrakingSignals(vNext);
    4760              : 
    4761              :     // update position and speed
    4762    704971239 :     int oldLaneOffset = myLane->getEdge().getNumLanes() - myLane->getIndex();
    4763              :     const MSLane* oldLaneMaybeOpposite = myLane;
    4764    704971239 :     if (myLaneChangeModel->isOpposite()) {
    4765              :         // transform to the forward-direction lane, move and then transform back
    4766       406939 :         myState.myPos = myLane->getOppositePos(myState.myPos);
    4767       406939 :         myLane = myLane->getParallelOpposite();
    4768              :     }
    4769    704971239 :     updateState(vNext);
    4770    704971239 :     updateWaitingTime(vNext);
    4771              : 
    4772              :     // Lanes, which the vehicle touched at some moment of the executed simstep
    4773              :     std::vector<MSLane*> passedLanes;
    4774              :     // remember previous lane (myLane is updated in processLaneAdvances)
    4775    704971239 :     const MSLane* oldLane = myLane;
    4776              :     // Reason for a possible emergency stop
    4777              :     std::string emergencyReason;
    4778    704971239 :     processLaneAdvances(passedLanes, emergencyReason);
    4779              : 
    4780    704971239 :     updateTimeLoss(vNext);
    4781    704971239 :     myCollisionImmunity = MAX2((SUMOTime) - 1, myCollisionImmunity - DELTA_T);
    4782              : 
    4783    704971239 :     if (!hasArrivedInternal() && !myLane->getEdge().isVaporizing()) {
    4784    701641505 :         if (myState.myPos > myLane->getLength()) {
    4785          359 :             if (emergencyReason == "") {
    4786           17 :                 emergencyReason = TL(" for unknown reasons");
    4787              :             }
    4788         1436 :             WRITE_WARNINGF(TL("Vehicle '%' performs emergency stop at the end of lane '%'% (decel=%, offset=%), time=%."),
    4789              :                            getID(), myLane->getID(), emergencyReason, myAcceleration - myState.mySpeed,
    4790              :                            myState.myPos - myLane->getLength(), time2string(SIMSTEP));
    4791          359 :             MSNet::getInstance()->getVehicleControl().registerEmergencyStop();
    4792          359 :             MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::EMERGENCYSTOP);
    4793          359 :             myState.myPos = myLane->getLength();
    4794          359 :             myState.mySpeed = 0;
    4795          359 :             myAcceleration = 0;
    4796              :         }
    4797    701641505 :         const MSLane* oldBackLane = getBackLane();
    4798    701641505 :         if (myLaneChangeModel->isOpposite()) {
    4799              :             passedLanes.clear(); // ignore back occupation
    4800              :         }
    4801              : #ifdef DEBUG_ACTIONSTEPS
    4802              :         if (DEBUG_COND) {
    4803              :             std::cout << SIMTIME << " veh '" << getID() << "' updates further lanes." << std::endl;
    4804              :         }
    4805              : #endif
    4806    701641505 :         myState.myBackPos = updateFurtherLanes(myFurtherLanes, myFurtherLanesPosLat, passedLanes);
    4807    701641505 :         if (passedLanes.size() > 1 && isRail()) {
    4808       883140 :             for (auto pi = passedLanes.rbegin(); pi != passedLanes.rend(); ++pi) {
    4809       666187 :                 MSLane* pLane = *pi;
    4810       666187 :                 if (pLane != myLane && std::find(myFurtherLanes.begin(), myFurtherLanes.end(), pLane) == myFurtherLanes.end()) {
    4811        45691 :                     leaveLaneBack(MSMoveReminder::NOTIFICATION_JUNCTION, *pi);
    4812              :                 }
    4813              :             }
    4814              :         }
    4815              :         // bestLanes need to be updated before lane changing starts. NOTE: This call is also a presumption for updateDriveItems()
    4816    701641505 :         updateBestLanes();
    4817    701641505 :         if (myLane != oldLane || oldBackLane != getBackLane()) {
    4818     24826428 :             if (myLaneChangeModel->getShadowLane() != nullptr || getLateralOverlap() > POSITION_EPS) {
    4819              :                 // shadow lane must be updated if the front or back lane changed
    4820              :                 // either if we already have a shadowLane or if there is lateral overlap
    4821       553780 :                 myLaneChangeModel->updateShadowLane();
    4822              :             }
    4823     24826428 :             if (MSGlobals::gLateralResolution > 0 && !myLaneChangeModel->isOpposite()) {
    4824              :                 // The vehicles target lane must be also be updated if the front or back lane changed
    4825      4434638 :                 myLaneChangeModel->updateTargetLane();
    4826              :             }
    4827              :         }
    4828    701641505 :         setBlinkerInformation(); // needs updated bestLanes
    4829              :         //change the blue light only for emergency vehicles SUMOVehicleClass
    4830    701641505 :         if (myType->getVehicleClass() == SVC_EMERGENCY) {
    4831        85867 :             setEmergencyBlueLight(MSNet::getInstance()->getCurrentTimeStep());
    4832              :         }
    4833              :         // must be done before angle computation
    4834              :         // State needs to be reset for all vehicles before the next call to MSEdgeControl::changeLanes
    4835    701641505 :         if (myActionStep) {
    4836              :             // check (#2681): Can this be skipped?
    4837    630100849 :             myLaneChangeModel->prepareStep();
    4838              :         } else {
    4839     71540656 :             myLaneChangeModel->resetSpeedLat();
    4840              : #ifdef DEBUG_ACTIONSTEPS
    4841              :             if (DEBUG_COND) {
    4842              :                 std::cout << SIMTIME << " veh '" << getID() << "' skips LCM->prepareStep()." << std::endl;
    4843              :             }
    4844              : #endif
    4845              :         }
    4846    701641505 :         myLaneChangeModel->setPreviousAngleOffset(myLaneChangeModel->getAngleOffset());
    4847    701641505 :         myAngle = computeAngle();
    4848              :     }
    4849              : 
    4850              : #ifdef DEBUG_EXEC_MOVE
    4851              :     if (DEBUG_COND) {
    4852              :         std::cout << SIMTIME << " executeMove finished veh=" << getID() << " lane=" << myLane->getID() << " myPos=" << getPositionOnLane() << " myPosLat=" << getLateralPositionOnLane() << "\n";
    4853              :         gDebugFlag1 = false; // See MSLink_DEBUG_OPENED
    4854              :     }
    4855              : #endif
    4856    704971239 :     if (myLaneChangeModel->isOpposite()) {
    4857              :         // transform back to the opposite-direction lane
    4858              :         MSLane* newOpposite = nullptr;
    4859       406939 :         const MSEdge* newOppositeEdge = myLane->getEdge().getOppositeEdge();
    4860       406939 :         if (newOppositeEdge != nullptr) {
    4861       406889 :             newOpposite = newOppositeEdge->getLanes()[newOppositeEdge->getNumLanes() - MAX2(1, oldLaneOffset)];
    4862              : #ifdef DEBUG_EXEC_MOVE
    4863              :             if (DEBUG_COND) {
    4864              :                 std::cout << SIMTIME << "   newOppositeEdge=" << newOppositeEdge->getID() << " oldLaneOffset=" << oldLaneOffset << " leftMost=" << newOppositeEdge->getNumLanes() - 1 << " newOpposite=" << Named::getIDSecure(newOpposite) << "\n";
    4865              :             }
    4866              : #endif
    4867              :         }
    4868       406889 :         if (newOpposite == nullptr) {
    4869           50 :             if (!myLaneChangeModel->hasBlueLight()) {
    4870              :                 // unusual overtaking at junctions is ok for emergency vehicles
    4871            0 :                 WRITE_WARNINGF(TL("Unexpected end of opposite lane for vehicle '%' at lane '%', time=%."),
    4872              :                                getID(), myLane->getID(), time2string(SIMSTEP));
    4873              :             }
    4874           50 :             myLaneChangeModel->changedToOpposite();
    4875           50 :             if (myState.myPos < getLength()) {
    4876              :                 // further lanes is always cleared during opposite driving
    4877           50 :                 MSLane* oldOpposite = oldLane->getOpposite();
    4878           50 :                 if (oldOpposite != nullptr) {
    4879           50 :                     myFurtherLanes.push_back(oldOpposite);
    4880           51 :                     myFurtherLanesPosLat.push_back(0);
    4881              :                     // small value since the lane is going in the other direction
    4882           50 :                     myState.myBackPos = getLength() - myState.myPos;
    4883           50 :                     myAngle = computeAngle();
    4884              :                 } else {
    4885              :                     SOFT_ASSERT(false);
    4886              :                 }
    4887              :             }
    4888              :         } else {
    4889       406889 :             myState.myPos = myLane->getOppositePos(myState.myPos);
    4890       406889 :             myLane = newOpposite;
    4891              :             oldLane = oldLaneMaybeOpposite;
    4892              :             //std::cout << SIMTIME << " updated myLane=" << Named::getIDSecure(myLane) << " oldLane=" << oldLane->getID() << "\n";
    4893       406889 :             myCachedPosition = Position::INVALID;
    4894       406889 :             myLaneChangeModel->updateShadowLane();
    4895              :         }
    4896              :     }
    4897              :     // myAngle was already updated. Update lastAngle so moveRemindes have consisent angleDiff (after finalizeSpeed because it uses the old angles)
    4898    704971239 :     myLastAngle = myRawAngle;
    4899              :     // store angle before lane changing
    4900    704971239 :     myRawAngle = myAngle;
    4901              : 
    4902    704971239 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4903              :     // Return whether the vehicle did move to another lane
    4904   1409942476 :     return myLane != oldLane;
    4905    704971239 : }
    4906              : 
    4907              : void
    4908       218475 : MSVehicle::executeFractionalMove(double dist) {
    4909       218475 :     myState.myPos += dist;
    4910       218475 :     myState.myLastCoveredDist = dist;
    4911       218475 :     myCachedPosition = Position::INVALID;
    4912              : 
    4913       218475 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(dist);
    4914       218475 :     const SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
    4915       452955 :     for (int i = 0; i < (int)lanes.size(); i++) {
    4916       234480 :         MSLink* link = nullptr;
    4917       234480 :         if (i + 1 < (int)lanes.size()) {
    4918        16005 :             const MSLane* const to = lanes[i + 1];
    4919        16005 :             const bool internal = to->isInternal();
    4920        16010 :             for (MSLink* const l : lanes[i]->getLinkCont()) {
    4921        16010 :                 if ((internal && l->getViaLane() == to) || (!internal && l->getLane() == to)) {
    4922        16005 :                     link = l;
    4923        16005 :                     break;
    4924              :                 }
    4925              :             }
    4926              :         }
    4927       234480 :         myLFLinkLanes.emplace_back(link, getSpeed(), getSpeed(), true, t, getSpeed(), 0, 0, dist);
    4928              :     }
    4929              :     // minimum execute move:
    4930              :     std::vector<MSLane*> passedLanes;
    4931              :     // Reason for a possible emergency stop
    4932       218475 :     if (lanes.size() > 1) {
    4933         4005 :         myLane->removeVehicle(this, MSMoveReminder::NOTIFICATION_JUNCTION, false);
    4934              :     }
    4935              :     std::string emergencyReason;
    4936       218475 :     processLaneAdvances(passedLanes, emergencyReason);
    4937              : #ifdef DEBUG_EXTRAPOLATE_DEPARTPOS
    4938              :     if (DEBUG_COND) {
    4939              :         std::cout << SIMTIME << " veh=" << getID() << " executeFractionalMove dist=" << dist
    4940              :                   << " passedLanes=" << toString(passedLanes) << " lanes=" << toString(lanes)
    4941              :                   << " finalPos=" << myState.myPos
    4942              :                   << " speed=" << getSpeed()
    4943              :                   << " myFurtherLanes=" << toString(myFurtherLanes)
    4944              :                   << "\n";
    4945              :     }
    4946              : #endif
    4947       218475 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4948       218475 :     if (lanes.size() > 1) {
    4949         4010 :         for (std::vector<MSLane*>::iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    4950              : #ifdef DEBUG_FURTHER
    4951              :             if (DEBUG_COND) {
    4952              :                 std::cout << SIMTIME << " leaveLane \n";
    4953              :             }
    4954              : #endif
    4955            5 :             (*i)->resetPartialOccupation(this);
    4956              :         }
    4957              :         myFurtherLanes.clear();
    4958              :         myFurtherLanesPosLat.clear();
    4959         4005 :         myLane->forceVehicleInsertion(this, getPositionOnLane(), MSMoveReminder::NOTIFICATION_JUNCTION, getLateralPositionOnLane());
    4960              :     }
    4961       218475 : }
    4962              : 
    4963              : 
    4964              : void
    4965    713290456 : MSVehicle::updateState(double vNext, bool parking) {
    4966              :     // update position and speed
    4967              :     double deltaPos; // positional change
    4968    713290456 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4969              :         // euler
    4970    613986480 :         deltaPos = SPEED2DIST(vNext);
    4971              :     } else {
    4972              :         // ballistic
    4973     99303976 :         deltaPos = getDeltaPos(SPEED2ACCEL(vNext - myState.mySpeed));
    4974              :     }
    4975              : 
    4976              :     // the *mean* acceleration during the next step (probably most appropriate for emission calculation)
    4977              :     // NOTE: for the ballistic update vNext may be negative, indicating a stop.
    4978    713290456 :     myAcceleration = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4979              : 
    4980              : #ifdef DEBUG_EXEC_MOVE
    4981              :     if (DEBUG_COND) {
    4982              :         std::cout << SIMTIME << " updateState() for veh '" << getID() << "': deltaPos=" << deltaPos
    4983              :                   << " pos=" << myState.myPos << " newPos=" << myState.myPos + deltaPos << std::endl;
    4984              :     }
    4985              : #endif
    4986    713290456 :     double decelPlus = -myAcceleration - getCarFollowModel().getMaxDecel() - NUMERICAL_EPS;
    4987    713290456 :     if (decelPlus > 0) {
    4988       460353 :         const double previousAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    4989       460353 :         if (myAcceleration + NUMERICAL_EPS < previousAcceleration) {
    4990              :             // vehicle brakes beyond wished maximum deceleration (only warn at the start of the braking manoeuvre)
    4991       320031 :             decelPlus += 2 * NUMERICAL_EPS;
    4992       320031 :             const double emergencyFraction = decelPlus / MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel());
    4993       320031 :             if (emergencyFraction >= MSGlobals::gEmergencyDecelWarningThreshold) {
    4994        95715 :                 WRITE_WARNINGF(TL("Vehicle '%' performs emergency braking on lane '%' with decel=%, wished=%, severity=%, time=%."),
    4995              :                                //+ " decelPlus=" + toString(decelPlus)
    4996              :                                //+ " prevAccel=" + toString(previousAcceleration)
    4997              :                                //+ " reserve=" + toString(MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel()))
    4998              :                                getID(), myLane->getID(), -myAcceleration, getCarFollowModel().getMaxDecel(), emergencyFraction, time2string(SIMSTEP));
    4999        31905 :                 MSNet::getInstance()->getVehicleControl().registerEmergencyBraking();
    5000              :             }
    5001              :         }
    5002              :     }
    5003              : 
    5004    713290456 :     myState.myPreviousSpeed = myState.mySpeed;
    5005    713290456 :     myState.mySpeed = MAX2(vNext, 0.);
    5006              : 
    5007    713290456 :     if (isRemoteControlled()) {
    5008         7182 :         deltaPos = myInfluencer->implicitDeltaPosRemote(this);
    5009              :     }
    5010              : 
    5011    713290456 :     myState.myPos += deltaPos;
    5012    713290456 :     myState.myLastCoveredDist = deltaPos;
    5013    713290456 :     myNextTurn.first -= deltaPos;
    5014              : 
    5015    713290456 :     if (!parking) {
    5016    704971239 :         myCachedPosition = Position::INVALID;
    5017              :     }
    5018    713290456 : }
    5019              : 
    5020              : void
    5021      8319217 : MSVehicle::updateParkingState() {
    5022      8319217 :     updateState(0, true);
    5023              :     // deboard while parked
    5024      8319217 :     if (myPersonDevice != nullptr) {
    5025       625450 :         myPersonDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    5026              :     }
    5027      8319217 :     if (myContainerDevice != nullptr) {
    5028        59887 :         myContainerDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    5029              :     }
    5030     16832562 :     for (MSVehicleDevice* const dev : myDevices) {
    5031      8513345 :         dev->notifyParking();
    5032              :     }
    5033      8319217 : }
    5034              : 
    5035              : 
    5036              : void
    5037        30644 : MSVehicle::replaceVehicleType(const MSVehicleType* type) {
    5038        30644 :     MSBaseVehicle::replaceVehicleType(type);
    5039        30644 :     delete myCFVariables;
    5040        30644 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    5041        30644 : }
    5042              : 
    5043              : 
    5044              : const MSLane*
    5045   1387353270 : MSVehicle::getBackLane() const {
    5046   1387353270 :     if (myFurtherLanes.size() > 0) {
    5047     19056105 :         return myFurtherLanes.back();
    5048              :     } else {
    5049   1368297165 :         return myLane;
    5050              :     }
    5051              : }
    5052              : 
    5053              : 
    5054              : double
    5055    707153492 : MSVehicle::updateFurtherLanes(std::vector<MSLane*>& furtherLanes, std::vector<double>& furtherLanesPosLat,
    5056              :                               const std::vector<MSLane*>& passedLanes) {
    5057              : #ifdef DEBUG_SETFURTHER
    5058              :     if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID()
    5059              :                                   << " updateFurtherLanes oldFurther=" << toString(furtherLanes)
    5060              :                                   << " oldFurtherPosLat=" << toString(furtherLanesPosLat)
    5061              :                                   << " passed=" << toString(passedLanes)
    5062              :                                   << "\n";
    5063              : #endif
    5064    723136226 :     for (MSLane* further : furtherLanes) {
    5065     15982734 :         further->resetPartialOccupation(this);
    5066     15982734 :         if (further->getBidiLane() != nullptr
    5067     15982734 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5068       101819 :             further->getBidiLane()->resetPartialOccupation(this);
    5069              :         }
    5070              :     }
    5071              : 
    5072              :     std::vector<MSLane*> newFurther;
    5073              :     std::vector<double> newFurtherPosLat;
    5074    707153492 :     double backPosOnPreviousLane = myState.myPos - getLength();
    5075              :     bool widthShift = myFurtherLanesPosLat.size() > myFurtherLanes.size();
    5076    707153492 :     if (passedLanes.size() > 1) {
    5077              :         // There are candidates for further lanes. (passedLanes[-1] is the current lane, or current shadow lane in context of updateShadowLanes())
    5078              :         std::vector<MSLane*>::const_iterator fi = furtherLanes.begin();
    5079              :         std::vector<double>::const_iterator fpi = furtherLanesPosLat.begin();
    5080     44841505 :         for (auto pi = passedLanes.rbegin() + 1; pi != passedLanes.rend() && backPosOnPreviousLane < 0; ++pi) {
    5081              :             // As long as vehicle back reaches into passed lane, add it to the further lanes
    5082     15915164 :             MSLane* further = *pi;
    5083     15915164 :             newFurther.push_back(further);
    5084     15915164 :             backPosOnPreviousLane += further->setPartialOccupation(this);
    5085     15915164 :             if (further->getBidiLane() != nullptr
    5086     15915164 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5087       100022 :                 further->getBidiLane()->setPartialOccupation(this);
    5088              :             }
    5089     15915164 :             if (fi != furtherLanes.end() && further == *fi) {
    5090              :                 // Lateral position on this lane is already known. Assume constant and use old value.
    5091      5704287 :                 newFurtherPosLat.push_back(*fpi);
    5092              :                 ++fi;
    5093              :                 ++fpi;
    5094              :             } else {
    5095              :                 // The lane *pi was not in furtherLanes before.
    5096              :                 // If it is downstream, we assume as lateral position the current position
    5097              :                 // If it is a new lane upstream (can appear as shadow further in case of LC-maneuvering, e.g.)
    5098              :                 // we assign the last known lateral position.
    5099     10210877 :                 if (newFurtherPosLat.size() == 0) {
    5100      9587554 :                     if (widthShift) {
    5101      1507762 :                         newFurtherPosLat.push_back(myFurtherLanesPosLat.back());
    5102              :                     } else {
    5103      8079792 :                         newFurtherPosLat.push_back(myState.myPosLat);
    5104              :                     }
    5105              :                 } else {
    5106       623323 :                     newFurtherPosLat.push_back(newFurtherPosLat.back());
    5107              :                 }
    5108              :             }
    5109              : #ifdef DEBUG_SETFURTHER
    5110              :             if (DEBUG_COND) {
    5111              :                 std::cout << SIMTIME << " updateFurtherLanes \n"
    5112              :                           << "    further lane '" << further->getID() << "' backPosOnPreviousLane=" << backPosOnPreviousLane
    5113              :                           << std::endl;
    5114              :             }
    5115              : #endif
    5116              :         }
    5117     28926341 :         furtherLanes = newFurther;
    5118     28926341 :         furtherLanesPosLat = newFurtherPosLat;
    5119              :     } else {
    5120              :         furtherLanes.clear();
    5121              :         furtherLanesPosLat.clear();
    5122              :     }
    5123              : #ifdef DEBUG_SETFURTHER
    5124              :     if (DEBUG_COND) std::cout
    5125              :                 << " newFurther=" << toString(furtherLanes)
    5126              :                 << " newFurtherPosLat=" << toString(furtherLanesPosLat)
    5127              :                 << " newBackPos=" << backPosOnPreviousLane
    5128              :                 << "\n";
    5129              : #endif
    5130    707153492 :     return backPosOnPreviousLane;
    5131    707153492 : }
    5132              : 
    5133              : 
    5134              : double
    5135  35110687424 : MSVehicle::getBackPositionOnLane(const MSLane* lane, bool calledByGetPosition) const {
    5136              : #ifdef DEBUG_FURTHER
    5137              :     if (DEBUG_COND) {
    5138              :         std::cout << SIMTIME
    5139              :                   << " getBackPositionOnLane veh=" << getID()
    5140              :                   << " lane=" << Named::getIDSecure(lane)
    5141              :                   << " cbgP=" << calledByGetPosition
    5142              :                   << " pos=" << myState.myPos
    5143              :                   << " backPos=" << myState.myBackPos
    5144              :                   << " myLane=" << myLane->getID()
    5145              :                   << " myLaneBidi=" << Named::getIDSecure(myLane->getBidiLane())
    5146              :                   << " further=" << toString(myFurtherLanes)
    5147              :                   << " furtherPosLat=" << toString(myFurtherLanesPosLat)
    5148              :                   << "\n     shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    5149              :                   << " shadowFurther=" << toString(myLaneChangeModel->getShadowFurtherLanes())
    5150              :                   << " shadowFurtherPosLat=" << toString(myLaneChangeModel->getShadowFurtherLanesPosLat())
    5151              :                   << "\n     targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    5152              :                   << " furtherTargets=" << toString(myLaneChangeModel->getFurtherTargetLanes())
    5153              :                   << std::endl;
    5154              :     }
    5155              : #endif
    5156  35110687424 :     if (lane == myLane
    5157   8524817687 :             || lane == myLaneChangeModel->getShadowLane()
    5158  40168348922 :             || lane == myLaneChangeModel->getTargetLane()) {
    5159  30054608027 :         if (myLaneChangeModel->isOpposite()) {
    5160    231248247 :             if (lane == myLaneChangeModel->getShadowLane()) {
    5161    199161504 :                 return lane->getLength() - myState.myPos - myType->getLength();
    5162              :             } else {
    5163     36882293 :                 return myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5164              :             }
    5165  29823359780 :         } else if (&lane->getEdge() != &myLane->getEdge()) {
    5166     20782115 :             return lane->getLength() - myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5167              :         } else {
    5168              :             // account for parallel lanes of different lengths in the most conservative manner (i.e. while turning)
    5169  59605861829 :             return myState.myPos - myType->getLength() + MIN2(0.0, lane->getLength() - myLane->getLength());
    5170              :         }
    5171   5056079397 :     } else if (lane == myLane->getBidiLane()) {
    5172     41916559 :         return lane->getLength() - myState.myPos + myType->getLength() * (calledByGetPosition ? -1 : 1);
    5173   5021920534 :     } else if (myFurtherLanes.size() > 0 && lane == myFurtherLanes.back()) {
    5174   4971621801 :         return myState.myBackPos;
    5175     50298733 :     } else if ((myLaneChangeModel->getShadowFurtherLanes().size() > 0 && lane == myLaneChangeModel->getShadowFurtherLanes().back())
    5176     50757789 :                || (myLaneChangeModel->getFurtherTargetLanes().size() > 0 && lane == myLaneChangeModel->getFurtherTargetLanes().back())) {
    5177              :         assert(myFurtherLanes.size() > 0);
    5178     19547101 :         if (lane->getLength() == myFurtherLanes.back()->getLength()) {
    5179     18881224 :             return myState.myBackPos;
    5180              :         } else {
    5181              :             // interpolate
    5182              :             //if (DEBUG_COND) {
    5183              :             //if (myFurtherLanes.back()->getLength() != lane->getLength()) {
    5184              :             //    std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " further=" << myFurtherLanes.back()->getID()
    5185              :             //        << " len=" << lane->getLength() << " fLen=" << myFurtherLanes.back()->getLength()
    5186              :             //        << " backPos=" << myState.myBackPos << " result=" << myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength() << "\n";
    5187              :             //}
    5188       665877 :             return myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength();
    5189              :         }
    5190              :     } else {
    5191              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherLanes=" << toString(myFurtherLanes) << "\n";
    5192     30751632 :         double leftLength = myType->getLength() - myState.myPos;
    5193              : 
    5194              :         std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin();
    5195     32809923 :         while (leftLength > 0 && i != myFurtherLanes.end()) {
    5196     32756299 :             leftLength -= (*i)->getLength();
    5197              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5198     32756299 :             if (*i == lane) {
    5199     29676857 :                 return -leftLength;
    5200      3079442 :             } else if (*i == lane->getBidiLane()) {
    5201      1021151 :                 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
    5202              :             }
    5203              :             ++i;
    5204              :         }
    5205              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    5206        53624 :         leftLength = myType->getLength() - myState.myPos;
    5207        53624 :         i = myLaneChangeModel->getShadowFurtherLanes().begin();
    5208        53624 :         while (leftLength > 0 && i != myLaneChangeModel->getShadowFurtherLanes().end()) {
    5209        53618 :             leftLength -= (*i)->getLength();
    5210              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5211        53618 :             if (*i == lane) {
    5212        25198 :                 return -leftLength;
    5213        28420 :             } else if (*i == lane->getBidiLane()) {
    5214        28420 :                 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
    5215              :             }
    5216              :             ++i;
    5217              :         }
    5218              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherTargetLanes=" << toString(myLaneChangeModel->getFurtherTargetLanes()) << "\n";
    5219            6 :         leftLength = myType->getLength() - myState.myPos;
    5220              :         i = getFurtherLanes().begin();
    5221            6 :         const std::vector<MSLane*> furtherTargetLanes = myLaneChangeModel->getFurtherTargetLanes();
    5222              :         auto j = furtherTargetLanes.begin();
    5223            6 :         while (leftLength > 0 && j != furtherTargetLanes.end()) {
    5224            0 :             leftLength -= (*i)->getLength();
    5225              :             // if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5226            0 :             if (*j == lane) {
    5227            0 :                 return -leftLength;
    5228            0 :             } else if (*j == lane->getBidiLane()) {
    5229            0 :                 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
    5230              :             }
    5231              :             ++i;
    5232              :             ++j;
    5233              :         }
    5234           24 :         WRITE_WARNINGF("Request backPos of vehicle '%' for invalid lane '%' time=%.",
    5235              :                 getID(), Named::getIDSecure(lane), time2string(SIMSTEP))
    5236              :         SOFT_ASSERT(false);
    5237            6 :         return  myState.myBackPos;
    5238            6 :     }
    5239              : }
    5240              : 
    5241              : 
    5242              : double
    5243  28568673497 : MSVehicle::getPositionOnLane(const MSLane* lane) const {
    5244  28568673497 :     return getBackPositionOnLane(lane, true) + myType->getLength();
    5245              : }
    5246              : 
    5247              : 
    5248              : bool
    5249    424712340 : MSVehicle::isFrontOnLane(const MSLane* lane) const {
    5250    424712340 :     return lane == myLane || lane == myLaneChangeModel->getShadowLane() || lane == myLane->getBidiLane();
    5251              : }
    5252              : 
    5253              : 
    5254              : void
    5255    637097452 : MSVehicle::checkRewindLinkLanes(const double lengthsInFront, DriveItemVector& lfLinks) const {
    5256    637097452 :     if (MSGlobals::gUsingInternalLanes && !myLane->getEdge().isRoundabout() && !myLaneChangeModel->isOpposite()) {
    5257    633886972 :         double seenSpace = -lengthsInFront;
    5258              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5259              :         if (DEBUG_COND) {
    5260              :             std::cout << "\nCHECK_REWIND_LINKLANES\n" << " veh=" << getID() << " lengthsInFront=" << lengthsInFront << "\n";
    5261              :         };
    5262              : #endif
    5263    633886972 :         bool foundStopped = false;
    5264              :         // compute available space until a stopped vehicle is found
    5265              :         // this is the sum of non-interal lane length minus in-between vehicle lengths
    5266   1858816131 :         for (int i = 0; i < (int)lfLinks.size(); ++i) {
    5267              :             // skip unset links
    5268   1224929159 :             DriveProcessItem& item = lfLinks[i];
    5269              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5270              :             if (DEBUG_COND) std::cout << SIMTIME
    5271              :                                           << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5272              :                                           << " foundStopped=" << foundStopped;
    5273              : #endif
    5274   1224929159 :             if (item.myLink == nullptr || foundStopped) {
    5275    401026216 :                 if (!foundStopped) {
    5276    343367761 :                     item.availableSpace += seenSpace;
    5277              :                 } else {
    5278     57658455 :                     item.availableSpace = seenSpace;
    5279              :                 }
    5280              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5281              :                 if (DEBUG_COND) {
    5282              :                     std::cout << " avail=" << item.availableSpace << "\n";
    5283              :                 }
    5284              : #endif
    5285    401026216 :                 continue;
    5286              :             }
    5287              :             // get the next lane, determine whether it is an internal lane
    5288              :             const MSLane* approachedLane = item.myLink->getViaLane();
    5289    823902943 :             if (approachedLane != nullptr) {
    5290    450000044 :                 if (keepClear(item.myLink)) {
    5291    141872402 :                     seenSpace = seenSpace - approachedLane->getBruttoVehLenSum();
    5292    141872402 :                     if (approachedLane == myLane) {
    5293        48432 :                         seenSpace += getVehicleType().getLengthWithGap();
    5294              :                     }
    5295              :                 } else {
    5296    308127642 :                     seenSpace = seenSpace + approachedLane->getSpaceTillLastStanding(this, foundStopped);// - approachedLane->getBruttoVehLenSum() + approachedLane->getLength();
    5297              :                 }
    5298    450000044 :                 item.availableSpace = seenSpace;
    5299              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5300              :                 if (DEBUG_COND) std::cout
    5301              :                             << " approached=" << approachedLane->getID()
    5302              :                             << " approachedBrutto=" << approachedLane->getBruttoVehLenSum()
    5303              :                             << " avail=" << item.availableSpace
    5304              :                             << " seenSpace=" << seenSpace
    5305              :                             << " hadStoppedVehicle=" << item.hadStoppedVehicle
    5306              :                             << " lengthsInFront=" << lengthsInFront
    5307              :                             << "\n";
    5308              : #endif
    5309    450000044 :                 continue;
    5310              :             }
    5311              :             approachedLane = item.myLink->getLane();
    5312    373902899 :             const MSVehicle* last = approachedLane->getLastAnyVehicle();
    5313    373902899 :             if (last == nullptr || last == this) {
    5314     61289764 :                 if (approachedLane->getLength() > getVehicleType().getLength()
    5315     61289764 :                         || keepClear(item.myLink)) {
    5316     58904412 :                     seenSpace += approachedLane->getLength();
    5317              :                 }
    5318     61289764 :                 item.availableSpace = seenSpace;
    5319              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5320              :                 if (DEBUG_COND) {
    5321              :                     std::cout << " last=" << Named::getIDSecure(last) << " laneLength=" << approachedLane->getLength() << " avail=" << item.availableSpace << "\n";
    5322              :                 }
    5323              : #endif
    5324              :             } else {
    5325    312613135 :                 bool foundStopped2 = false;
    5326    312613135 :                 double spaceTillLastStanding = approachedLane->getSpaceTillLastStanding(this, foundStopped2);
    5327    312613135 :                 if (approachedLane->getBidiLane() != nullptr) {
    5328       490745 :                     const MSVehicle* oncomingVeh = approachedLane->getBidiLane()->getFirstFullVehicle();
    5329       490745 :                     if (oncomingVeh) {
    5330       334689 :                         const double oncomingGap = approachedLane->getLength() - oncomingVeh->getPositionOnLane();
    5331       334689 :                         const double oncomingBGap = oncomingVeh->getBrakeGap(true);
    5332              :                         // oncoming movement until ego enters the junction
    5333       334689 :                         const double oncomingMove = STEPS2TIME(item.myArrivalTime - SIMSTEP) * oncomingVeh->getSpeed();
    5334       334689 :                         const double spaceTillOncoming = oncomingGap - oncomingBGap - oncomingMove;
    5335              :                         spaceTillLastStanding = MIN2(spaceTillLastStanding, spaceTillOncoming);
    5336       334689 :                         if (spaceTillOncoming <= getVehicleType().getLengthWithGap()) {
    5337        27306 :                             foundStopped = true;
    5338              :                         }
    5339              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5340              :                         if (DEBUG_COND) {
    5341              :                             std::cout << " oVeh=" << oncomingVeh->getID()
    5342              :                                       << " oGap=" << oncomingGap
    5343              :                                       << " bGap=" << oncomingBGap
    5344              :                                       << " mGap=" << oncomingMove
    5345              :                                       << " sto=" << spaceTillOncoming;
    5346              :                         }
    5347              : #endif
    5348              :                     }
    5349              :                 }
    5350    312613135 :                 seenSpace += spaceTillLastStanding;
    5351    312613135 :                 if (foundStopped2) {
    5352     24617342 :                     foundStopped = true;
    5353     24617342 :                     item.hadStoppedVehicle = true;
    5354              :                 }
    5355    312613135 :                 item.availableSpace = seenSpace;
    5356    312613135 :                 if (last->myHaveToWaitOnNextLink || last->isStopped()) {
    5357     32809288 :                     foundStopped = true;
    5358     32809288 :                     item.hadStoppedVehicle = true;
    5359              :                 }
    5360              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5361              :                 if (DEBUG_COND) std::cout
    5362              :                             << " approached=" << approachedLane->getID()
    5363              :                             << " last=" << last->getID()
    5364              :                             << " lastHasToWait=" << last->myHaveToWaitOnNextLink
    5365              :                             << " lastBrakeLight=" << last->signalSet(VEH_SIGNAL_BRAKELIGHT)
    5366              :                             << " lastBrakeGap=" << last->getCarFollowModel().brakeGap(last->getSpeed())
    5367              :                             << " lastGap=" << (last->getBackPositionOnLane(approachedLane) + last->getCarFollowModel().brakeGap(last->getSpeed()) - last->getSpeed() * last->getCarFollowModel().getHeadwayTime()
    5368              :                                                // gap of last up to the next intersection
    5369              :                                                - last->getVehicleType().getMinGap())
    5370              :                             << " stls=" << spaceTillLastStanding
    5371              :                             << " avail=" << item.availableSpace
    5372              :                             << " seenSpace=" << seenSpace
    5373              :                             << " foundStopped=" << foundStopped
    5374              :                             << " foundStopped2=" << foundStopped2
    5375              :                             << "\n";
    5376              : #endif
    5377              :             }
    5378              :         }
    5379              : 
    5380              :         // check which links allow continuation and add pass available to the previous item
    5381   1224929159 :         for (int i = ((int)lfLinks.size() - 1); i > 0; --i) {
    5382    591042187 :             DriveProcessItem& item = lfLinks[i - 1];
    5383    591042187 :             DriveProcessItem& nextItem = lfLinks[i];
    5384    591042187 :             const bool canLeaveJunction = item.myLink->getViaLane() == nullptr || nextItem.myLink == nullptr || nextItem.mySetRequest;
    5385              :             const bool opened = (item.myLink != nullptr
    5386    591042187 :                                  && (canLeaveJunction || (
    5387              :                                          // indirect bicycle turn
    5388     32162797 :                                          nextItem.myLink != nullptr && nextItem.myLink->isInternalJunctionLink() && nextItem.myLink->haveRed()))
    5389    558893452 :                                  && (
    5390    558893452 :                                      item.myLink->havePriority()
    5391     27925167 :                                      || i == 1 // the upcoming link (item 0) is checked in executeMove anyway. No need to use outdata approachData here
    5392      5436622 :                                      || (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority())
    5393      5407109 :                                      || item.myLink->opened(item.myArrivalTime, item.myArrivalSpeed,
    5394      5407109 :                                              item.getLeaveSpeed(), getVehicleType().getLength(),
    5395      5407109 :                                              getImpatience(), getCarFollowModel().getMaxDecel(), getWaitingTime(), getLateralPositionOnLane(), nullptr, false, this)));
    5396    591042187 :             bool allowsContinuation = (item.myLink == nullptr || item.myLink->isCont() || opened) && !item.hadStoppedVehicle;
    5397              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5398              :             if (DEBUG_COND) std::cout
    5399              :                         << "   link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5400              :                         << " canLeave=" << canLeaveJunction
    5401              :                         << " opened=" << opened
    5402              :                         << " allowsContinuation=" << allowsContinuation
    5403              :                         << " foundStopped=" << foundStopped
    5404              :                         << "\n";
    5405              : #endif
    5406    591042187 :             if (!opened && item.myLink != nullptr) {
    5407     32891769 :                 foundStopped = true;
    5408     32891769 :                 if (i > 1) {
    5409      5001528 :                     DriveProcessItem& item2 = lfLinks[i - 2];
    5410      5001528 :                     if (item2.myLink != nullptr && item2.myLink->isCont()) {
    5411              :                         allowsContinuation = true;
    5412              :                     }
    5413              :                 }
    5414              :             }
    5415    587831030 :             if (allowsContinuation) {
    5416    524215573 :                 item.availableSpace = nextItem.availableSpace;
    5417              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5418              :                 if (DEBUG_COND) std::cout
    5419              :                             << "   link=" << (item.myLink == nullptr ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5420              :                             << " copy nextAvail=" << nextItem.availableSpace
    5421              :                             << "\n";
    5422              : #endif
    5423              :             }
    5424              :         }
    5425              : 
    5426              :         // find removalBegin
    5427              :         int removalBegin = -1;
    5428    777347106 :         for (int i = 0; foundStopped && i < (int)lfLinks.size() && removalBegin < 0; ++i) {
    5429              :             // skip unset links
    5430    143460134 :             const DriveProcessItem& item = lfLinks[i];
    5431    143460134 :             if (item.myLink == nullptr) {
    5432      7000057 :                 continue;
    5433              :             }
    5434              :             /*
    5435              :             double impatienceCorrection = MAX2(0., double(double(myWaitingTime)));
    5436              :             if (seenSpace<getVehicleType().getLengthWithGap()-impatienceCorrection/10.&&nextSeenNonInternal!=0) {
    5437              :                 removalBegin = lastLinkToInternal;
    5438              :             }
    5439              :             */
    5440              : 
    5441    136460077 :             const double leftSpace = item.availableSpace - getVehicleType().getLengthWithGap();
    5442              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5443              :             if (DEBUG_COND) std::cout
    5444              :                         << SIMTIME
    5445              :                         << " veh=" << getID()
    5446              :                         << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5447              :                         << " avail=" << item.availableSpace
    5448              :                         << " leftSpace=" << leftSpace
    5449              :                         << "\n";
    5450              : #endif
    5451    136460077 :             if (leftSpace < 0/* && item.myLink->willHaveBlockedFoe()*/) {
    5452              :                 double impatienceCorrection = 0;
    5453              :                 /*
    5454              :                 if(item.myLink->getState()==LINKSTATE_MINOR) {
    5455              :                     impatienceCorrection = MAX2(0., STEPS2TIME(myWaitingTime));
    5456              :                 }
    5457              :                 */
    5458              :                 // may ignore keepClear rules
    5459     89063720 :                 if (leftSpace < -impatienceCorrection / 10. && keepClear(item.myLink)) {
    5460              :                     removalBegin = i;
    5461              :                 }
    5462              :                 //removalBegin = i;
    5463              :             }
    5464              :         }
    5465              :         // abort requests
    5466    633886972 :         if (removalBegin != -1 && !(removalBegin == 0 && myLane->getEdge().isInternal())) {
    5467     31029192 :             const double brakeGap = getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.);
    5468    106388663 :             while (removalBegin < (int)(lfLinks.size())) {
    5469     80306434 :                 DriveProcessItem& dpi = lfLinks[removalBegin];
    5470     80306434 :                 if (dpi.myLink == nullptr) {
    5471              :                     break;
    5472              :                 }
    5473     75359471 :                 dpi.myVLinkPass = dpi.myVLinkWait;
    5474              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5475              :                 if (DEBUG_COND) {
    5476              :                     std::cout << " removalBegin=" << removalBegin << " brakeGap=" << brakeGap << " dist=" << dpi.myDistance << " speed=" << myState.mySpeed << " a2s=" << ACCEL2SPEED(getCarFollowModel().getMaxDecel()) << "\n";
    5477              :                 }
    5478              : #endif
    5479     75359471 :                 if (dpi.myDistance >= brakeGap + POSITION_EPS) {
    5480              :                     // always leave junctions after requesting to enter
    5481     75350811 :                     if (!dpi.myLink->isExitLink() || !lfLinks[removalBegin - 1].mySetRequest) {
    5482     75343213 :                         dpi.mySetRequest = false;
    5483              :                     }
    5484              :                 }
    5485     75359471 :                 ++removalBegin;
    5486              :             }
    5487              :         }
    5488              :     }
    5489    637097452 : }
    5490              : 
    5491              : 
    5492              : void
    5493    708659388 : MSVehicle::setApproachingForAllLinks() {
    5494    708659388 :     if (!myActionStep) {
    5495              :         return;
    5496              :     }
    5497    637097452 :     removeApproachingInformation(myLFLinkLanesPrev);
    5498   1869898578 :     for (DriveProcessItem& dpi : myLFLinkLanes) {
    5499   1232801126 :         if (dpi.myLink != nullptr) {
    5500    880868646 :             if (dpi.myLink->getState() == LINKSTATE_ALLWAY_STOP) {
    5501      2850520 :                 dpi.myArrivalTime += (SUMOTime)RandHelper::rand((int)2, getRNG()); // tie braker
    5502              :             }
    5503    880868646 :             dpi.myLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5504    880868646 :                                        dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance, getLateralPositionOnLane());
    5505              :         }
    5506              :     }
    5507    637097452 :     if (isRail()) {
    5508      8251259 :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5509      6864204 :             if (dpi.myLink != nullptr && dpi.myLink->getTLLogic() != nullptr && dpi.myLink->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
    5510       693668 :                 MSRailSignalControl::getInstance().notifyApproach(dpi.myLink);
    5511              :             }
    5512              :         }
    5513              :     }
    5514    637097452 :     if (myLaneChangeModel->getShadowLane() != nullptr) {
    5515              :         // register on all shadow links
    5516      7580738 :         for (const DriveProcessItem& dpi : myLFLinkLanes) {
    5517      5026357 :             if (dpi.myLink != nullptr) {
    5518      3435408 :                 MSLink* parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    5519      3435408 :                 if (parallelLink == nullptr && getLaneChangeModel().isOpposite() && dpi.myLink->isEntryLink()) {
    5520              :                     // register on opposite direction entry link to warn foes at minor side road
    5521       169746 :                     parallelLink = dpi.myLink->getOppositeDirectionLink();
    5522              :                 }
    5523      3435408 :                 if (parallelLink != nullptr) {
    5524      2447757 :                     const double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    5525      2447757 :                     parallelLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5526      2447757 :                                                  dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance,
    5527              :                                                  latOffset);
    5528      2447757 :                     myLaneChangeModel->setShadowApproachingInformation(parallelLink);
    5529              :                 }
    5530              :             }
    5531              :         }
    5532              :     }
    5533              : #ifdef DEBUG_PLAN_MOVE
    5534              :     if (DEBUG_COND) {
    5535              :         std::cout << SIMTIME
    5536              :                   << " veh=" << getID()
    5537              :                   << " after checkRewindLinkLanes\n";
    5538              :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5539              :             std::cout
    5540              :                     << " vPass=" << dpi.myVLinkPass
    5541              :                     << " vWait=" << dpi.myVLinkWait
    5542              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    5543              :                     << " request=" << dpi.mySetRequest
    5544              :                     << " atime=" << dpi.myArrivalTime
    5545              :                     << "\n";
    5546              :         }
    5547              :     }
    5548              : #endif
    5549              : }
    5550              : 
    5551              : 
    5552              : void
    5553         1860 : MSVehicle::registerInsertionApproach(MSLink* link, double dist) {
    5554              :     DriveProcessItem dpi(0, dist);
    5555         1860 :     dpi.myLink = link;
    5556         1860 :     const double arrivalSpeedBraking = getCarFollowModel().getMinimalArrivalSpeedEuler(dist, getSpeed());
    5557         1860 :     link->setApproaching(this, SUMOTime_MAX, 0, 0, false, arrivalSpeedBraking, 0, dpi.myDistance, 0);
    5558              :     // ensure cleanup in the next step
    5559         1860 :     myLFLinkLanes.push_back(dpi);
    5560         1860 :     MSRailSignalControl::getInstance().notifyApproach(link);
    5561         1860 : }
    5562              : 
    5563              : 
    5564              : void
    5565     19616430 : MSVehicle::enterLaneAtMove(MSLane* enteredLane, bool onTeleporting) {
    5566     19616430 :     myAmOnNet = !onTeleporting;
    5567              :     // vaporizing edge?
    5568              :     /*
    5569              :     if (enteredLane->getEdge().isVaporizing()) {
    5570              :         // yep, let's do the vaporization...
    5571              :         myLane = enteredLane;
    5572              :         return true;
    5573              :     }
    5574              :     */
    5575              :     // Adjust MoveReminder offset to the next lane
    5576     19616430 :     adaptLaneEntering2MoveReminder(*enteredLane);
    5577              :     // set the entered lane as the current lane
    5578     19616430 :     MSLane* oldLane = myLane;
    5579     19616430 :     myLane = enteredLane;
    5580     19616430 :     myLastBestLanesEdge = nullptr;
    5581              : 
    5582              :     // internal edges are not a part of the route...
    5583     19616430 :     if (!enteredLane->getEdge().isInternal()) {
    5584              :         ++myCurrEdge;
    5585              :         assert(myLaneChangeModel->isOpposite() || haveValidStopEdges());
    5586              :     }
    5587     19616430 :     if (myInfluencer != nullptr) {
    5588         9042 :         myInfluencer->adaptLaneTimeLine(myLane->getIndex() - oldLane->getIndex());
    5589              :     }
    5590     19616430 :     if (!onTeleporting) {
    5591     19598012 :         activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION, enteredLane);
    5592     19598012 :         if (MSGlobals::gLateralResolution > 0) {
    5593      3852078 :             myFurtherLanesPosLat.push_back(myState.myPosLat);
    5594              :             // transform lateral position when the lane width changes
    5595              :             assert(oldLane != nullptr);
    5596      3852078 :             const MSLink* const link = oldLane->getLinkTo(myLane);
    5597      3852078 :             if (link != nullptr) {
    5598      3852036 :                 myState.myPosLat += link->getLateralShift();
    5599              :             } else {
    5600           42 :                 myState.myPosLat += (oldLane->getCenterOnEdge() - myLane->getCanonicalPredecessorLane()->getRightSideOnEdge()) / 2;
    5601              :             }
    5602     15745934 :         } else if (fabs(myState.myPosLat) > NUMERICAL_EPS) {
    5603       243611 :             const double overlap = MAX2(0.0, getLateralOverlap(myState.myPosLat, oldLane));
    5604       243611 :             const double range = (oldLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
    5605       243611 :             const double range2 = (myLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
    5606       243611 :             myState.myPosLat *= range2 / range;
    5607              :         }
    5608     19598012 :         if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5609              :             // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
    5610              :             // (unless the lane is shared with cars)
    5611        27203 :             myLane->getBidiLane()->setPartialOccupation(this);
    5612              :         }
    5613              :     } else {
    5614              :         // normal move() isn't called so reset position here. must be done
    5615              :         // before calling reminders
    5616        18418 :         myState.myPos = 0;
    5617        18418 :         myCachedPosition = Position::INVALID;
    5618        18418 :         activateReminders(MSMoveReminder::NOTIFICATION_TELEPORT, enteredLane);
    5619              :     }
    5620              :     // update via
    5621     19616430 :     if (myParameter->via.size() > 0 &&  myLane->getEdge().getID() == myParameter->via.front()) {
    5622         7271 :         myParameter->via.erase(myParameter->via.begin());
    5623              :     }
    5624     19616430 : }
    5625              : 
    5626              : 
    5627              : void
    5628      1093654 : MSVehicle::enterLaneAtLaneChange(MSLane* enteredLane) {
    5629      1093654 :     myAmOnNet = true;
    5630      1093654 :     myLane = enteredLane;
    5631      1093654 :     myCachedPosition = Position::INVALID;
    5632              :     // need to update myCurrentLaneInBestLanes
    5633      1093654 :     updateBestLanes();
    5634              :     // switch to and activate the new lane's reminders
    5635              :     // keep OldLaneReminders
    5636      1294220 :     for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5637       200566 :         addReminder(*rem);
    5638              :     }
    5639      1093654 :     activateReminders(MSMoveReminder::NOTIFICATION_LANE_CHANGE, enteredLane);
    5640      1093654 :     MSLane* lane = myLane;
    5641      1093654 :     double leftLength = getVehicleType().getLength() - myState.myPos;
    5642              :     int deleteFurther = 0;
    5643              : #ifdef DEBUG_SETFURTHER
    5644              :     if (DEBUG_COND) {
    5645              :         std::cout << SIMTIME << " enterLaneAtLaneChange entered=" << Named::getIDSecure(enteredLane) << " oldFurther=" << toString(myFurtherLanes) << "\n";
    5646              :     }
    5647              : #endif
    5648      1093654 :     if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5649              :         // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
    5650              :         // (unless the lane is shared with cars)
    5651        19949 :         myLane->getBidiLane()->setPartialOccupation(this);
    5652              :     }
    5653      1180755 :     for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    5654        87101 :         if (lane != nullptr) {
    5655        83937 :             lane = lane->getLogicalPredecessorLane(myFurtherLanes[i]->getEdge());
    5656              :         }
    5657              : #ifdef DEBUG_SETFURTHER
    5658              :         if (DEBUG_COND) {
    5659              :             std::cout << "  enterLaneAtLaneChange i=" << i << " lane=" << Named::getIDSecure(lane) << " leftLength=" << leftLength << "\n";
    5660              :         }
    5661              : #endif
    5662        87101 :         if (leftLength > 0) {
    5663        86527 :             if (lane != nullptr) {
    5664        35444 :                 myFurtherLanes[i]->resetPartialOccupation(this);
    5665        35444 :                 if (myFurtherLanes[i]->getBidiLane() != nullptr
    5666        35444 :                         && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5667           66 :                     myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
    5668              :                 }
    5669              :                 // lane changing onto longer lanes may reduce the number of
    5670              :                 // remaining further lanes
    5671        35444 :                 myFurtherLanes[i] = lane;
    5672        35444 :                 myFurtherLanesPosLat[i] = myState.myPosLat;
    5673        35444 :                 leftLength -= lane->setPartialOccupation(this);
    5674        35444 :                 if (lane->getBidiLane() != nullptr
    5675        35444 :                         && (!isRailway(getVClass()) || (lane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5676         1892 :                     lane->getBidiLane()->setPartialOccupation(this);
    5677              :                 }
    5678        35444 :                 myState.myBackPos = -leftLength;
    5679              : #ifdef DEBUG_SETFURTHER
    5680              :                 if (DEBUG_COND) {
    5681              :                     std::cout << SIMTIME << "   newBackPos=" << myState.myBackPos << "\n";
    5682              :                 }
    5683              : #endif
    5684              :             } else {
    5685              :                 // keep the old values, but ensure there is no shadow
    5686        51083 :                 if (myLaneChangeModel->isChangingLanes()) {
    5687           15 :                     myLaneChangeModel->setNoShadowPartialOccupator(myFurtherLanes[i]);
    5688              :                 }
    5689        51083 :                 if (myState.myBackPos < 0) {
    5690          311 :                     myState.myBackPos += myFurtherLanes[i]->getLength();
    5691              :                 }
    5692              : #ifdef DEBUG_SETFURTHER
    5693              :                 if (DEBUG_COND) {
    5694              :                     std::cout << SIMTIME << "   i=" << i << " further=" << myFurtherLanes[i]->getID() << " newBackPos=" << myState.myBackPos << "\n";
    5695              :                 }
    5696              : #endif
    5697              :             }
    5698              :         } else {
    5699          574 :             myFurtherLanes[i]->resetPartialOccupation(this);
    5700          574 :             if (myFurtherLanes[i]->getBidiLane() != nullptr
    5701          574 :                     && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5702            0 :                 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
    5703              :             }
    5704          574 :             deleteFurther++;
    5705              :         }
    5706              :     }
    5707      1093654 :     if (deleteFurther > 0) {
    5708              : #ifdef DEBUG_SETFURTHER
    5709              :         if (DEBUG_COND) {
    5710              :             std::cout << SIMTIME << " veh=" << getID() << " shortening myFurtherLanes by " << deleteFurther << "\n";
    5711              :         }
    5712              : #endif
    5713          556 :         myFurtherLanes.erase(myFurtherLanes.end() - deleteFurther, myFurtherLanes.end());
    5714          556 :         myFurtherLanesPosLat.erase(myFurtherLanesPosLat.end() - deleteFurther, myFurtherLanesPosLat.end());
    5715              :     }
    5716              : #ifdef DEBUG_SETFURTHER
    5717              :     if (DEBUG_COND) {
    5718              :         std::cout << SIMTIME << " enterLaneAtLaneChange new furtherLanes=" << toString(myFurtherLanes)
    5719              :                   << " furterLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
    5720              :     }
    5721              : #endif
    5722      1093654 :     myAngle = computeAngle();
    5723      1093654 : }
    5724              : 
    5725              : 
    5726              : void
    5727      3554932 : MSVehicle::computeFurtherLanes(MSLane* enteredLane, double pos, bool collision) {
    5728              :     // build the list of lanes the vehicle is lapping into
    5729      3554932 :     if (!myLaneChangeModel->isOpposite()) {
    5730      3532602 :         double leftLength = myType->getLength() - pos;
    5731      3532602 :         MSLane* clane = enteredLane;
    5732      3532602 :         int routeIndex = getRoutePosition();
    5733      3638094 :         while (leftLength > 0) {
    5734       237162 :             if (routeIndex > 0 && clane->getEdge().isNormal()) {
    5735              :                 // get predecessor lane that corresponds to prior route
    5736         4578 :                 routeIndex--;
    5737         4578 :                 const MSEdge* fromRouteEdge = myRoute->getEdges()[routeIndex];
    5738              :                 MSLane* target = clane;
    5739         4578 :                 clane = nullptr;
    5740         6118 :                 for (auto ili : target->getIncomingLanes()) {
    5741         6111 :                     if (ili.lane->getEdge().getNormalBefore() == fromRouteEdge) {
    5742         4571 :                         clane = ili.lane;
    5743         4571 :                         break;
    5744              :                     }
    5745              :                 }
    5746              :             } else {
    5747       232584 :                 clane = clane->getLogicalPredecessorLane();
    5748              :             }
    5749       145833 :             if (clane == nullptr || clane == myLane || clane == myLane->getBidiLane()
    5750       382987 :                     || (clane->isInternal() && (
    5751       122219 :                             clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN
    5752        81886 :                             || clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN_LEFTHAND))) {
    5753              :                 break;
    5754              :             }
    5755       105492 :             if (!collision || std::find(myFurtherLanes.begin(), myFurtherLanes.end(), clane) == myFurtherLanes.end()) {
    5756       105044 :                 myFurtherLanes.push_back(clane);
    5757       105044 :                 myFurtherLanesPosLat.push_back(myState.myPosLat);
    5758       105044 :                 clane->setPartialOccupation(this);
    5759       105044 :                 if (clane->getBidiLane() != nullptr
    5760       105044 :                         && (!isRailway(getVClass()) || (clane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5761            5 :                     clane->getBidiLane()->setPartialOccupation(this);
    5762              :                 }
    5763              :             }
    5764       105492 :             leftLength -= clane->getLength();
    5765              :         }
    5766      3532602 :         myState.myBackPos = -leftLength;
    5767              : #ifdef DEBUG_SETFURTHER
    5768              :         if (DEBUG_COND) {
    5769              :             std::cout << SIMTIME << " computeFurtherLanes veh=" << getID() << " pos=" << pos << " myFurtherLanes=" << toString(myFurtherLanes) << " backPos=" << myState.myBackPos << "\n";
    5770              :         }
    5771              : #endif
    5772              :     } else {
    5773              :         // clear partial occupation
    5774        22702 :         for (MSLane* further : myFurtherLanes) {
    5775              : #ifdef DEBUG_SETFURTHER
    5776              :             if (DEBUG_COND) {
    5777              :                 std::cout << SIMTIME << " opposite: resetPartialOccupation " << further->getID() << " \n";
    5778              :             }
    5779              : #endif
    5780          372 :             further->resetPartialOccupation(this);
    5781          372 :             if (further->getBidiLane() != nullptr
    5782          372 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5783            0 :                 further->getBidiLane()->resetPartialOccupation(this);
    5784              :             }
    5785              :         }
    5786              :         myFurtherLanes.clear();
    5787              :         myFurtherLanesPosLat.clear();
    5788              :     }
    5789      3554932 : }
    5790              : 
    5791              : 
    5792              : void
    5793      3554479 : MSVehicle::enterLaneAtInsertion(MSLane* enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification) {
    5794      3554479 :     myState = State(pos, speed, posLat, pos - getVehicleType().getLength(), hasDeparted() ? myState.myPreviousSpeed : speed);
    5795      3554479 :     if (myDeparture == NOT_YET_DEPARTED) {
    5796      3480038 :         onDepart();
    5797              :     }
    5798      3554479 :     if (enteredLane->isInternal() && myJunctionEntryTime == SUMOTime_MAX) {
    5799          100 :         myJunctionEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    5800          100 :         myJunctionEntryTimeNeverYield = myJunctionEntryTime;
    5801              :         assert(enteredLane->getIncomingLanes().size() == 1);
    5802          100 :         if (enteredLane->getIncomingLanes().front().viaLink->isConflictEntryLink()) {
    5803           70 :             myJunctionConflictEntryTime = myJunctionEntryTime;
    5804              :         }
    5805              :     }
    5806      3554479 :     myCachedPosition = Position::INVALID;
    5807              :     assert(myState.myPos >= 0);
    5808              :     assert(myState.mySpeed >= 0);
    5809      3554479 :     myLane = enteredLane;
    5810      3554479 :     myAmOnNet = true;
    5811              :     // schedule action for the next timestep
    5812      3554479 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + DELTA_T;
    5813      3554479 :     if (notification != MSMoveReminder::NOTIFICATION_TELEPORT) {
    5814      3542685 :         if (notification == MSMoveReminder::NOTIFICATION_PARKING && myInfluencer != nullptr) {
    5815           12 :             drawOutsideNetwork(false);
    5816              :         }
    5817              :         // set and activate the new lane's reminders, teleports already did that at enterLaneAtMove
    5818      7517656 :         for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5819      3974971 :             addReminder(*rem);
    5820              :         }
    5821      3542685 :         activateReminders(notification, enteredLane);
    5822              :     } else {
    5823        11794 :         myLastBestLanesEdge = nullptr;
    5824        11794 :         myLastBestLanesInternalLane = nullptr;
    5825        11794 :         myLaneChangeModel->resetState();
    5826        12929 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()
    5827        12481 :                 && myStops.front().pars.endPos < pos) {
    5828            0 :             WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5829              :                            time2string(MSNet::getInstance()->getCurrentTimeStep()));
    5830            0 :             cleanupParkingReservation();
    5831            0 :             myStops.pop_front();
    5832              :         }
    5833              :         // avoid startup-effects after teleport
    5834        11794 :         myTimeSinceStartup = getCarFollowModel().getStartupDelay() + DELTA_T;
    5835        11794 :         myStopSpeed = std::numeric_limits<double>::max();
    5836              :     }
    5837      3554479 :     computeFurtherLanes(enteredLane, pos);
    5838      3554479 :     if (MSGlobals::gLateralResolution > 0) {
    5839       524984 :         myLaneChangeModel->updateShadowLane();
    5840       524984 :         myLaneChangeModel->updateTargetLane();
    5841      3029495 :     } else if (MSGlobals::gLaneChangeDuration > 0) {
    5842        40414 :         myLaneChangeModel->updateShadowLane();
    5843              :     }
    5844      3554479 :     if (notification != MSMoveReminder::NOTIFICATION_LOAD_STATE) {
    5845      3553029 :         myAngle = computeAngle();
    5846      3553029 :         myRawAngle = myAngle;
    5847      3553029 :         if (myLaneChangeModel->isOpposite()) {
    5848        22330 :             myAngle += M_PI;
    5849              :         }
    5850              :     }
    5851      3554479 :     if (MSNet::getInstance()->hasPersons()) {
    5852        58707 :         for (MSLane* further : myFurtherLanes) {
    5853          883 :             if (further->mustCheckJunctionCollisions()) {
    5854            4 :                 MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(further);
    5855              :             }
    5856              :         }
    5857              :     }
    5858      3554479 : }
    5859              : 
    5860              : 
    5861              : void
    5862     24140241 : MSVehicle::leaveLane(const MSMoveReminder::Notification reason, const MSLane* approachedLane) {
    5863     66726746 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5864     42586505 :         if (rem->first->notifyLeave(*this, myState.myPos + rem->second, reason, approachedLane)) {
    5865              : #ifdef _DEBUG
    5866              :             if (myTraceMoveReminders) {
    5867              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, true);
    5868              :             }
    5869              : #endif
    5870              :             ++rem;
    5871              :         } else {
    5872              : #ifdef _DEBUG
    5873              :             if (myTraceMoveReminders) {
    5874              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, false);
    5875              :             }
    5876              : #endif
    5877              :             rem = myMoveReminders.erase(rem);
    5878              :         }
    5879              :     }
    5880     24140241 :     if ((reason == MSMoveReminder::NOTIFICATION_JUNCTION
    5881     24140241 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT
    5882      4529743 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT_CONTINUATION)
    5883     19616690 :             && myLane != nullptr) {
    5884     19616661 :         myOdometer += getLane()->getLength();
    5885              :     }
    5886     24140212 :     if (myLane != nullptr && myLane->getBidiLane() != nullptr && myAmOnNet
    5887     24213368 :             && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5888        48610 :         myLane->getBidiLane()->resetPartialOccupation(this);
    5889              :     }
    5890     24140241 :     if (reason != MSMoveReminder::NOTIFICATION_JUNCTION && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5891              :         // @note. In case of lane change, myFurtherLanes and partial occupation
    5892              :         // are handled in enterLaneAtLaneChange()
    5893      3437118 :         for (MSLane* further : myFurtherLanes) {
    5894              : #ifdef DEBUG_FURTHER
    5895              :             if (DEBUG_COND) {
    5896              :                 std::cout << SIMTIME << " leaveLane \n";
    5897              :             }
    5898              : #endif
    5899        32992 :             further->resetPartialOccupation(this);
    5900        32992 :             if (further->getBidiLane() != nullptr
    5901        32992 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5902            4 :                 further->getBidiLane()->resetPartialOccupation(this);
    5903              :             }
    5904              :         }
    5905              :         myFurtherLanes.clear();
    5906              :         myFurtherLanesPosLat.clear();
    5907              :     }
    5908      3404126 :     if (reason >= MSMoveReminder::NOTIFICATION_TELEPORT) {
    5909      3404126 :         myAmOnNet = false;
    5910      3404126 :         myWaitingTime = 0;
    5911              :     }
    5912     24140241 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && resumeFromStopping()) {
    5913           18 :         myStopDist = std::numeric_limits<double>::max();
    5914           18 :         if (myPastStops.back().speed <= 0) {
    5915           54 :             WRITE_WARNINGF(TL("Vehicle '%' aborts stop."), getID());
    5916              :         }
    5917              :     }
    5918     24140241 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5919     22987137 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()) {
    5920         1441 :             if (myStops.front().getSpeed() <= 0) {
    5921         3321 :                 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5922              :                                time2string(MSNet::getInstance()->getCurrentTimeStep()));
    5923         1107 :                 cleanupParkingReservation();
    5924         1107 :                 if (MSStopOut::active()) {
    5925              :                     // clean up if stopBlocked was called
    5926           17 :                     MSStopOut::getInstance()->stopNotStarted(this);
    5927              :                 }
    5928         1107 :                 myStops.pop_front();
    5929              :             } else {
    5930              :                 MSStop& stop = myStops.front();
    5931              :                 // passed waypoint at the end of the lane
    5932          334 :                 if (!stop.reached) {
    5933          334 :                     if (MSStopOut::active()) {
    5934           21 :                         MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), MSNet::getInstance()->getCurrentTimeStep());
    5935              :                     }
    5936          334 :                     stop.reached = true;
    5937              :                     // enter stopping place so leaveFrom works as expected
    5938          334 :                     if (stop.busstop != nullptr) {
    5939              :                         // let the bus stop know the vehicle
    5940           25 :                         stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5941              :                     }
    5942          334 :                     if (stop.containerstop != nullptr) {
    5943              :                         // let the container stop know the vehicle
    5944           13 :                         stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5945              :                     }
    5946              :                     // do not enter parkingarea!
    5947          334 :                     if (stop.chargingStation != nullptr) {
    5948              :                         // let the container stop know the vehicle
    5949          122 :                         stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5950              :                     }
    5951              :                 }
    5952          334 :                 resumeFromStopping();
    5953              :             }
    5954         1441 :             myStopDist = std::numeric_limits<double>::max();
    5955              :         }
    5956              :     }
    5957     24140241 : }
    5958              : 
    5959              : 
    5960              : void
    5961        45691 : MSVehicle::leaveLaneBack(const MSMoveReminder::Notification reason, const MSLane* leftLane) {
    5962       186331 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5963       140640 :         if (rem->first->notifyLeaveBack(*this, reason, leftLane)) {
    5964              : #ifdef _DEBUG
    5965              :             if (myTraceMoveReminders) {
    5966              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, true);
    5967              :             }
    5968              : #endif
    5969              :             ++rem;
    5970              :         } else {
    5971              : #ifdef _DEBUG
    5972              :             if (myTraceMoveReminders) {
    5973              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, false);
    5974              :             }
    5975              : #endif
    5976              :             rem = myMoveReminders.erase(rem);
    5977              :         }
    5978              :     }
    5979              : #ifdef DEBUG_MOVEREMINDERS
    5980              :     if (DEBUG_COND) {
    5981              :         std::cout << SIMTIME << " veh=" << getID() << " myReminders:";
    5982              :         for (auto rem : myMoveReminders) {
    5983              :             std::cout << rem.first->getDescription() << " ";
    5984              :         }
    5985              :         std::cout << "\n";
    5986              :     }
    5987              : #endif
    5988        45691 : }
    5989              : 
    5990              : 
    5991              : MSAbstractLaneChangeModel&
    5992  10515360112 : MSVehicle::getLaneChangeModel() {
    5993  10515360112 :     return *myLaneChangeModel;
    5994              : }
    5995              : 
    5996              : 
    5997              : const MSAbstractLaneChangeModel&
    5998   4962612116 : MSVehicle::getLaneChangeModel() const {
    5999   4962612116 :     return *myLaneChangeModel;
    6000              : }
    6001              : 
    6002              : bool
    6003       518381 : MSVehicle::isOppositeLane(const MSLane* lane) const {
    6004       518381 :     return (lane->isInternal()
    6005       518381 :             ? & (lane->getLinkCont()[0]->getLane()->getEdge()) != *(myCurrEdge + 1)
    6006       516605 :             : &lane->getEdge() != *myCurrEdge);
    6007              : }
    6008              : 
    6009              : const std::vector<MSVehicle::LaneQ>&
    6010   1347271789 : MSVehicle::getBestLanes() const {
    6011   1347271789 :     return *myBestLanes.begin();
    6012              : }
    6013              : 
    6014              : 
    6015              : void
    6016   1880763648 : MSVehicle::updateBestLanes(bool forceRebuild, const MSLane* startLane) {
    6017              : #ifdef DEBUG_BESTLANES
    6018              :     if (DEBUG_COND) {
    6019              :         std::cout << SIMTIME << " updateBestLanes veh=" << getID() << " force=" << forceRebuild << " startLane1=" << Named::getIDSecure(startLane) << " myLane=" << Named::getIDSecure(myLane) << "\n";
    6020              :     }
    6021              : #endif
    6022   1880763648 :     if (startLane == nullptr) {
    6023    997601136 :         startLane = myLane;
    6024              :     }
    6025              :     assert(startLane != 0);
    6026   1880763648 :     if (myLaneChangeModel->isOpposite()) {
    6027              :         // depending on the calling context, startLane might be the forward lane
    6028              :         // or the reverse-direction lane. In the latter case we need to
    6029              :         // transform it to the forward lane.
    6030       518381 :         if (isOppositeLane(startLane)) {
    6031              :             // use leftmost lane of forward edge
    6032       111197 :             startLane = startLane->getEdge().getOppositeEdge()->getLanes().back();
    6033              :             assert(startLane != 0);
    6034              : #ifdef DEBUG_BESTLANES
    6035              :             if (DEBUG_COND) {
    6036              :                 std::cout << "   startLaneIsOpposite newStartLane=" << startLane->getID() << "\n";
    6037              :             }
    6038              : #endif
    6039              :         }
    6040              :     }
    6041   1880763648 :     if (forceRebuild) {
    6042      1757873 :         myLastBestLanesEdge = nullptr;
    6043      1757873 :         myLastBestLanesInternalLane = nullptr;
    6044              :     }
    6045   1880763648 :     if (myBestLanes.size() > 0 && !forceRebuild && myLastBestLanesEdge == &startLane->getEdge()) {
    6046   1849713288 :         updateOccupancyAndCurrentBestLane(startLane);
    6047              : #ifdef DEBUG_BESTLANES
    6048              :         if (DEBUG_COND) {
    6049              :             std::cout << "  only updateOccupancyAndCurrentBestLane\n";
    6050              :         }
    6051              : #endif
    6052   1849713288 :         return;
    6053              :     }
    6054     31050360 :     if (startLane->getEdge().isInternal()) {
    6055     14863497 :         if (myBestLanes.size() == 0 || forceRebuild) {
    6056              :             // rebuilt from previous non-internal lane (may backtrack twice if behind an internal junction)
    6057         2310 :             updateBestLanes(true, startLane->getLogicalPredecessorLane());
    6058              :         }
    6059     14863497 :         if (myLastBestLanesInternalLane == startLane && !forceRebuild) {
    6060              : #ifdef DEBUG_BESTLANES
    6061              :             if (DEBUG_COND) {
    6062              :                 std::cout << "  nothing to do on internal\n";
    6063              :             }
    6064              : #endif
    6065              :             return;
    6066              :         }
    6067              :         // adapt best lanes to fit the current internal edge:
    6068              :         // keep the entries that are reachable from this edge
    6069      5279516 :         const MSEdge* nextEdge = startLane->getNextNormal();
    6070              :         assert(!nextEdge->isInternal());
    6071     10408665 :         for (std::vector<std::vector<LaneQ> >::iterator it = myBestLanes.begin(); it != myBestLanes.end();) {
    6072              :             std::vector<LaneQ>& lanes = *it;
    6073              :             assert(lanes.size() > 0);
    6074     10408665 :             if (&(lanes[0].lane->getEdge()) == nextEdge) {
    6075              :                 // keep those lanes which are successors of internal lanes from the edge of startLane
    6076      5279516 :                 std::vector<LaneQ> oldLanes = lanes;
    6077              :                 lanes.clear();
    6078              :                 const std::vector<MSLane*>& sourceLanes = startLane->getEdge().getLanes();
    6079     11949487 :                 for (std::vector<MSLane*>::const_iterator it_source = sourceLanes.begin(); it_source != sourceLanes.end(); ++it_source) {
    6080     11251813 :                     for (std::vector<LaneQ>::iterator it_lane = oldLanes.begin(); it_lane != oldLanes.end(); ++it_lane) {
    6081     11251813 :                         if ((*it_source)->getLinkCont()[0]->getLane() == (*it_lane).lane) {
    6082      6669971 :                             lanes.push_back(*it_lane);
    6083              :                             break;
    6084              :                         }
    6085              :                     }
    6086              :                 }
    6087              :                 assert(lanes.size() == startLane->getEdge().getLanes().size());
    6088              :                 // patch invalid bestLaneOffset and updated myCurrentLaneInBestLanes
    6089     11949487 :                 for (int i = 0; i < (int)lanes.size(); ++i) {
    6090      6669971 :                     if (i + lanes[i].bestLaneOffset < 0) {
    6091       106754 :                         lanes[i].bestLaneOffset = -i;
    6092              :                     }
    6093      6669971 :                     if (i + lanes[i].bestLaneOffset >= (int)lanes.size()) {
    6094        26539 :                         lanes[i].bestLaneOffset = (int)lanes.size() - i - 1;
    6095              :                     }
    6096              :                     assert(i + lanes[i].bestLaneOffset >= 0);
    6097              :                     assert(i + lanes[i].bestLaneOffset < (int)lanes.size());
    6098      6669971 :                     if (lanes[i].bestContinuations[0] != 0) {
    6099              :                         // patch length of bestContinuation to match expectations (only once)
    6100      6473664 :                         lanes[i].bestContinuations.insert(lanes[i].bestContinuations.begin(), (MSLane*)nullptr);
    6101              :                     }
    6102      6669971 :                     if (startLane->getLinkCont()[0]->getLane() == lanes[i].lane) {
    6103      5323541 :                         myCurrentLaneInBestLanes = lanes.begin() + i;
    6104              :                     }
    6105              :                     assert(&(lanes[i].lane->getEdge()) == nextEdge);
    6106              :                 }
    6107      5279516 :                 myLastBestLanesInternalLane = startLane;
    6108      5279516 :                 updateOccupancyAndCurrentBestLane(startLane);
    6109              : #ifdef DEBUG_BESTLANES
    6110              :                 if (DEBUG_COND) {
    6111              :                     std::cout << "  updated for internal\n";
    6112              :                 }
    6113              : #endif
    6114              :                 return;
    6115      5279516 :             } else {
    6116              :                 // remove passed edges
    6117      5129149 :                 it = myBestLanes.erase(it);
    6118              :             }
    6119              :         }
    6120              :         assert(false); // should always find the next edge
    6121              :     }
    6122              :     // start rebuilding
    6123     16186863 :     myLastBestLanesInternalLane = nullptr;
    6124     16186863 :     myLastBestLanesEdge = &startLane->getEdge();
    6125              :     myBestLanes.clear();
    6126              : 
    6127              :     // get information about the next stop
    6128     16186863 :     MSRouteIterator nextStopEdge = myRoute->end();
    6129              :     const MSLane* nextStopLane = nullptr;
    6130              :     double nextStopPos = 0;
    6131     16186863 :     if (!myStops.empty()) {
    6132              :         const MSStop& nextStop = myStops.front();
    6133       263003 :         nextStopLane = nextStop.lane;
    6134       263003 :         if (nextStop.isOpposite) {
    6135              :             // target leftmost lane in forward direction
    6136          340 :             nextStopLane = nextStopLane->getEdge().getOppositeEdge()->getLanes().back();
    6137              :         }
    6138       263003 :         nextStopEdge = nextStop.edge;
    6139       263003 :         nextStopPos = nextStop.pars.startPos;
    6140              :     }
    6141              :     // myArrivalTime = -1 in the context of validating departSpeed with departLane=best
    6142     16186863 :     if (myParameter->arrivalLaneProcedure >= ArrivalLaneDefinition::GIVEN && nextStopEdge == myRoute->end() && myArrivalLane >= 0) {
    6143       337533 :         nextStopEdge = (myRoute->end() - 1);
    6144       337533 :         nextStopLane = (*nextStopEdge)->getLanes()[myArrivalLane];
    6145       337533 :         nextStopPos = myArrivalPos;
    6146              :     }
    6147     16186863 :     if (nextStopEdge != myRoute->end()) {
    6148              :         // make sure that the "wrong" lanes get a penalty. (penalty needs to be
    6149              :         // large enough to overcome a magic threshold in MSLaneChangeModel::DK2004.cpp:383)
    6150       600536 :         nextStopPos = MAX2(POSITION_EPS, MIN2((double)nextStopPos, (double)(nextStopLane->getLength() - 2 * POSITION_EPS)));
    6151       600536 :         if (nextStopLane->isInternal()) {
    6152              :             // switch to the correct lane before entering the intersection
    6153          171 :             nextStopPos = (*nextStopEdge)->getLength();
    6154              :         }
    6155              :     }
    6156              : 
    6157              :     // go forward along the next lanes; always look past stops to ensure that we
    6158              :     // know where to go once the stop ends
    6159              :     // trains do not have to deal with lane-changing for stops but their best
    6160              :     // lanes lookahead is needed for rail signal control
    6161              :     int seen = 0;
    6162              :     double seenLength = 0;
    6163              :     bool progress = true;
    6164              :     // bestLanes must cover the braking distance even when at the very end of the current lane to avoid unecessary slow down
    6165     32373726 :     const double maxBrakeDist = startLane->getLength() + getCarFollowModel().getHeadwayTime() * getMaxSpeed() + getCarFollowModel().brakeGap(getMaxSpeed()) + getVehicleType().getMinGap();
    6166     16186863 :     const double lookahead = getLaneChangeModel().getStrategicLookahead();
    6167     81761906 :     for (MSRouteIterator ce = myCurrEdge; progress;) {
    6168              :         std::vector<LaneQ> currentLanes;
    6169              :         const std::vector<MSLane*>* allowed = nullptr;
    6170              :         const MSEdge* nextEdge = nullptr;
    6171     65575043 :         if (ce != myRoute->end() && ce + 1 != myRoute->end()) {
    6172     53525662 :             nextEdge = *(ce + 1);
    6173     53525662 :             allowed = (*ce)->allowedLanes(*nextEdge, myType->getVehicleClass());
    6174              :         }
    6175     65575043 :         const std::vector<MSLane*>& lanes = (*ce)->getLanes();
    6176    165817909 :         for (std::vector<MSLane*>::const_iterator i = lanes.begin(); i != lanes.end(); ++i) {
    6177              :             LaneQ q;
    6178    100242866 :             MSLane* cl = *i;
    6179    100242866 :             q.lane = cl;
    6180    100242866 :             q.bestContinuations.push_back(cl);
    6181    100242866 :             q.bestLaneOffset = 0;
    6182    100242866 :             q.length = cl->allowsVehicleClass(myType->getVehicleClass()) ? (*ce)->getLength() : 0;
    6183    100242866 :             q.currentLength = q.length;
    6184              :             // if all lanes are forbidden (i.e. due to a dynamic closing) we want to express no preference
    6185    100242866 :             q.allowsContinuation = allowed == nullptr || std::find(allowed->begin(), allowed->end(), cl) != allowed->end();
    6186    100242866 :             q.occupation = 0;
    6187    100242866 :             q.nextOccupation = 0;
    6188    100242866 :             currentLanes.push_back(q);
    6189              :         }
    6190              :         //
    6191              :         if (nextStopEdge == ce
    6192              :                 // already past the stop edge
    6193     65575043 :                 && !(ce == myCurrEdge && myLane != nullptr && myLane->isInternal())) {
    6194       593236 :             const MSLane* normalStopLane = nextStopLane->getNormalPredecessorLane();
    6195      1879649 :             for (std::vector<LaneQ>::iterator q = currentLanes.begin(); q != currentLanes.end(); ++q) {
    6196      1286413 :                 if (nextStopLane != nullptr && normalStopLane != (*q).lane) {
    6197       693177 :                     (*q).allowsContinuation = false;
    6198       693177 :                     (*q).length = nextStopPos;
    6199       693177 :                     (*q).currentLength = (*q).length;
    6200              :                 }
    6201              :             }
    6202              :         }
    6203              : 
    6204     65575043 :         myBestLanes.push_back(currentLanes);
    6205     65575043 :         ++seen;
    6206     65575043 :         seenLength += currentLanes[0].lane->getLength();
    6207              :         ++ce;
    6208     65575043 :         if (lookahead >= 0) {
    6209           45 :             progress &= (seen <= 2 || seenLength < lookahead); // custom (but we need to look at least one edge ahead)
    6210              :         } else {
    6211     87097863 :             progress &= (seen <= 4 || seenLength < MAX2(maxBrakeDist, 3000.0)); // motorway
    6212     70441908 :             progress &= (seen <= 8 || seenLength < MAX2(maxBrakeDist, 200.0) || isRailway(getVClass()));  // urban
    6213              :         }
    6214     65575043 :         progress &= ce != myRoute->end();
    6215              :         /*
    6216              :         if(progress) {
    6217              :           progress &= (currentLanes.size()!=1||(*ce)->getLanes().size()!=1);
    6218              :         }
    6219              :         */
    6220     65575043 :     }
    6221              : 
    6222              :     // we are examining the last lane explicitly
    6223     16186863 :     if (myBestLanes.size() != 0) {
    6224              :         double bestLength = -1;
    6225              :         // minimum and maximum lane index with best length
    6226              :         int bestThisIndex = 0;
    6227              :         int bestThisMaxIndex = 0;
    6228              :         int index = 0;
    6229              :         std::vector<LaneQ>& last = myBestLanes.back();
    6230     42075996 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6231     25889133 :             if ((*j).length > bestLength) {
    6232              :                 bestLength = (*j).length;
    6233              :                 bestThisIndex = index;
    6234              :                 bestThisMaxIndex = index;
    6235      6142075 :             } else if ((*j).length == bestLength) {
    6236              :                 bestThisMaxIndex = index;
    6237              :             }
    6238              :         }
    6239              :         index = 0;
    6240              :         bool requiredChangeRightForbidden = false;
    6241              :         int requireChangeToLeftForbidden = -1;
    6242     42075996 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6243     25889133 :             if ((*j).length < bestLength) {
    6244      3960951 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6245       146959 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6246              :                 } else {
    6247      3813992 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6248              :                 }
    6249      3960951 :                 if (!(*j).allowsContinuation) {
    6250       563150 :                     if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6251       251188 :                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6252       248535 :                                 || requiredChangeRightForbidden)) {
    6253              :                         // this lane and all further lanes to the left cannot be used
    6254              :                         requiredChangeRightForbidden = true;
    6255         2653 :                         (*j).length = 0;
    6256       560497 :                     } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6257       311936 :                                 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6258              :                         // this lane and all previous lanes to the right cannot be used
    6259         6427 :                         requireChangeToLeftForbidden = (*j).lane->getIndex();
    6260              :                     }
    6261              :                 }
    6262              :             }
    6263              :         }
    6264     16193300 :         for (int i = requireChangeToLeftForbidden; i >= 0; i--) {
    6265         6437 :             if (last[i].bestLaneOffset > 0) {
    6266         6437 :                 last[i].length = 0;
    6267              :             }
    6268              :         }
    6269              : #ifdef DEBUG_BESTLANES
    6270              :         if (DEBUG_COND) {
    6271              :             std::cout << "   last edge=" << last.front().lane->getEdge().getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6272              :             std::vector<LaneQ>& laneQs = myBestLanes.back();
    6273              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6274              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << "\n";
    6275              :             }
    6276              :         }
    6277              : #endif
    6278              :     }
    6279              :     // go backward through the lanes
    6280              :     // track back best lane and compute the best prior lane(s)
    6281     65575043 :     for (std::vector<std::vector<LaneQ> >::reverse_iterator i = myBestLanes.rbegin() + 1; i != myBestLanes.rend(); ++i) {
    6282              :         std::vector<LaneQ>& nextLanes = (*(i - 1));
    6283              :         std::vector<LaneQ>& clanes = (*i);
    6284     49388180 :         MSEdge* const cE = &clanes[0].lane->getEdge();
    6285              :         int index = 0;
    6286              :         double bestConnectedLength = -1;
    6287              :         double bestLength = -1;
    6288    123031408 :         for (const LaneQ& j : nextLanes) {
    6289    147286456 :             if (j.lane->isApproachedFrom(cE) && bestConnectedLength < j.length) {
    6290              :                 bestConnectedLength = j.length;
    6291              :             }
    6292     73643228 :             if (bestLength < j.length) {
    6293              :                 bestLength = j.length;
    6294              :             }
    6295              :         }
    6296              :         // compute index of the best lane (highest length and least offset from the best next lane)
    6297              :         int bestThisIndex = 0;
    6298              :         int bestThisMaxIndex = 0;
    6299     49388180 :         if (bestConnectedLength > 0) {
    6300              :             index = 0;
    6301    123706306 :             for (LaneQ& j : clanes) {
    6302              :                 const LaneQ* bestConnectedNext = nullptr;
    6303     74330740 :                 if (j.allowsContinuation) {
    6304    176850616 :                     for (const LaneQ& m : nextLanes) {
    6305    122183883 :                         if ((m.lane->allowsVehicleClass(getVClass()) || m.lane->hadPermissionChanges())
    6306    112583515 :                                 && m.lane->isApproachedFrom(j.lane, getVClass())) {
    6307     66467055 :                             if (betterContinuation(bestConnectedNext, m)) {
    6308              :                                 bestConnectedNext = &m;
    6309              :                             }
    6310              :                         }
    6311              :                     }
    6312     64324685 :                     if (bestConnectedNext != nullptr) {
    6313     64324677 :                         if (bestConnectedNext->length == bestConnectedLength && abs(bestConnectedNext->bestLaneOffset) < 2) {
    6314     62567136 :                             j.length += bestLength;
    6315              :                         } else {
    6316      1757541 :                             j.length += bestConnectedNext->length;
    6317              :                         }
    6318     64324677 :                         j.bestLaneOffset = bestConnectedNext->bestLaneOffset;
    6319              :                     }
    6320              :                 }
    6321     64324677 :                 if (bestConnectedNext != nullptr && (bestConnectedNext->allowsContinuation || bestConnectedNext->length > 0)) {
    6322     64286678 :                     copy(bestConnectedNext->bestContinuations.begin(), bestConnectedNext->bestContinuations.end(), back_inserter(j.bestContinuations));
    6323              :                 } else {
    6324     10044062 :                     j.allowsContinuation = false;
    6325              :                 }
    6326     74330740 :                 if (clanes[bestThisIndex].length < j.length
    6327     67175892 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) > abs(j.bestLaneOffset))
    6328    204312774 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset) &&
    6329     62950484 :                             nextLinkPriority(clanes[bestThisIndex].bestContinuations) < nextLinkPriority(j.bestContinuations))
    6330              :                    ) {
    6331              :                     bestThisIndex = index;
    6332              :                     bestThisMaxIndex = index;
    6333     67019679 :                 } else if (clanes[bestThisIndex].length == j.length
    6334     62938745 :                            && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset)
    6335    129958292 :                            && nextLinkPriority(clanes[bestThisIndex].bestContinuations) == nextLinkPriority(j.bestContinuations)) {
    6336              :                     bestThisMaxIndex = index;
    6337              :                 }
    6338     74330740 :                 index++;
    6339              :             }
    6340              : 
    6341              :             //vehicle with elecHybrid device prefers running under an overhead wire
    6342     49375566 :             if (getDevice(typeid(MSDevice_ElecHybrid)) != nullptr) {
    6343              :                 index = 0;
    6344          491 :                 for (const LaneQ& j : clanes) {
    6345          339 :                     std::string overheadWireSegmentID = MSNet::getInstance()->getStoppingPlaceID(j.lane, j.currentLength / 2., SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6346          339 :                     if (overheadWireSegmentID != "") {
    6347              :                         bestThisIndex = index;
    6348              :                         bestThisMaxIndex = index;
    6349              :                     }
    6350          339 :                     index++;
    6351              :                 }
    6352              :             }
    6353              : 
    6354              :         } else {
    6355              :             // only needed in case of disconnected routes
    6356              :             int bestNextIndex = 0;
    6357        12614 :             int bestDistToNeeded = (int) clanes.size();
    6358              :             index = 0;
    6359        35607 :             for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6360        22993 :                 if ((*j).allowsContinuation) {
    6361              :                     int nextIndex = 0;
    6362        56876 :                     for (std::vector<LaneQ>::const_iterator m = nextLanes.begin(); m != nextLanes.end(); ++m, ++nextIndex) {
    6363        34633 :                         if ((*m).lane->isApproachedFrom((*j).lane, getVClass())) {
    6364         5023 :                             if (bestDistToNeeded > abs((*m).bestLaneOffset)) {
    6365              :                                 bestDistToNeeded = abs((*m).bestLaneOffset);
    6366              :                                 bestThisIndex = index;
    6367              :                                 bestThisMaxIndex = index;
    6368              :                                 bestNextIndex = nextIndex;
    6369              :                             }
    6370              :                         }
    6371              :                     }
    6372              :                 }
    6373              :             }
    6374        12614 :             clanes[bestThisIndex].length += nextLanes[bestNextIndex].length;
    6375        12614 :             copy(nextLanes[bestNextIndex].bestContinuations.begin(), nextLanes[bestNextIndex].bestContinuations.end(), back_inserter(clanes[bestThisIndex].bestContinuations));
    6376              : 
    6377              :         }
    6378              :         // set bestLaneOffset for all lanes
    6379              :         index = 0;
    6380              :         bool requiredChangeRightForbidden = false;
    6381              :         int requireChangeToLeftForbidden = -1;
    6382    123741913 :         for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6383     74353733 :             if ((*j).length < clanes[bestThisIndex].length
    6384     62608582 :                     || ((*j).length == clanes[bestThisIndex].length && abs((*j).bestLaneOffset) > abs(clanes[bestThisIndex].bestLaneOffset))
    6385    136962083 :                     || (nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)
    6386              :                ) {
    6387     11922088 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6388       772110 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6389              :                 } else {
    6390     11149978 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6391              :                 }
    6392     11922088 :                 if ((nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)) {
    6393              :                     // try to move away from the lower-priority lane before it ends
    6394     10209669 :                     (*j).length = (*j).currentLength;
    6395              :                 }
    6396     11922088 :                 if (!(*j).allowsContinuation) {
    6397     10029196 :                     if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6398      2569418 :                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6399      2555632 :                                 || requiredChangeRightForbidden)) {
    6400              :                         // this lane and all further lanes to the left cannot be used
    6401              :                         requiredChangeRightForbidden = true;
    6402        28100 :                         if ((*j).length == (*j).currentLength) {
    6403        28100 :                             (*j).length = 0;
    6404              :                         }
    6405     10001096 :                     } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6406      7402426 :                                 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6407              :                         // this lane and all previous lanes to the right cannot be used
    6408       114586 :                         requireChangeToLeftForbidden = (*j).lane->getIndex();
    6409              :                     }
    6410              :                 }
    6411              :             } else {
    6412     62431645 :                 (*j).bestLaneOffset = 0;
    6413              :             }
    6414              :         }
    6415     49521009 :         for (int idx = requireChangeToLeftForbidden; idx >= 0; idx--) {
    6416       132829 :             if (clanes[idx].length == clanes[idx].currentLength) {
    6417       132829 :                 clanes[idx].length = 0;
    6418              :             };
    6419              :         }
    6420              : 
    6421              :         //vehicle with elecHybrid device prefers running under an overhead wire
    6422     49388180 :         if (static_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid))) != 0) {
    6423              :             index = 0;
    6424          152 :             std::string overheadWireID = MSNet::getInstance()->getStoppingPlaceID(clanes[bestThisIndex].lane, (clanes[bestThisIndex].currentLength) / 2, SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6425          152 :             if (overheadWireID != "") {
    6426          373 :                 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6427          261 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6428              :                 }
    6429              :             }
    6430              :         }
    6431              : 
    6432              : #ifdef DEBUG_BESTLANES
    6433              :         if (DEBUG_COND) {
    6434              :             std::cout << "   edge=" << cE->getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6435              :             std::vector<LaneQ>& laneQs = clanes;
    6436              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6437              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << " allowCont=" << (*j).allowsContinuation << "\n";
    6438              :             }
    6439              :         }
    6440              : #endif
    6441              : 
    6442              :     }
    6443     16186863 :     if (myBestLanes.front().front().lane->isInternal()) {
    6444              :         // route starts on an internal lane
    6445           36 :         if (myLane != nullptr) {
    6446              :             startLane = myLane;
    6447              :         } else {
    6448              :             // vehicle not yet departed
    6449           12 :             startLane = myBestLanes.front().front().lane;
    6450              :         }
    6451              :     }
    6452     16186863 :     updateOccupancyAndCurrentBestLane(startLane);
    6453              : #ifdef DEBUG_BESTLANES
    6454              :     if (DEBUG_COND) {
    6455              :         std::cout << SIMTIME << " veh=" << getID() << " bestCont=" << toString(getBestLanesContinuation()) << "\n";
    6456              :     }
    6457              : #endif
    6458              : }
    6459              : 
    6460              : void
    6461          225 : MSVehicle::updateLaneBruttoSum() {
    6462          225 :     if (myLane != nullptr) {
    6463          225 :         myLane->markRecalculateBruttoSum();
    6464              :     }
    6465          225 : }
    6466              : 
    6467              : bool
    6468     66467055 : MSVehicle::betterContinuation(const LaneQ* bestConnectedNext, const LaneQ& m) const {
    6469     66467055 :     if (bestConnectedNext == nullptr) {
    6470              :         return true;
    6471      2142378 :     } else if (m.lane->getBidiLane() != nullptr && bestConnectedNext->lane->getBidiLane() == nullptr) {
    6472              :         return false;
    6473      2141586 :     } else if (bestConnectedNext->lane->getBidiLane() != nullptr && m.lane->getBidiLane() == nullptr) {
    6474              :         return true;
    6475      2141586 :     } else if (bestConnectedNext->length < m.length) {
    6476              :         return true;
    6477      1775412 :     } else if (bestConnectedNext->length == m.length) {
    6478      1247439 :         if (abs(bestConnectedNext->bestLaneOffset) > abs(m.bestLaneOffset)) {
    6479              :             return true;
    6480              :         }
    6481      1081232 :         const double contRight = getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_CONTRIGHT, 1);
    6482              :         if (contRight < 1
    6483              :                 // if we don't check for adjacency, the rightmost line will get
    6484              :                 // multiple chances to be better which leads to an uninituitve distribution
    6485         1006 :                 && (m.lane->getIndex() - bestConnectedNext->lane->getIndex()) == 1
    6486      1082011 :                 && RandHelper::rand(getRNG()) > contRight) {
    6487              :             return true;
    6488              :         }
    6489              :     }
    6490              :     return false;
    6491              : }
    6492              : 
    6493              : 
    6494              : int
    6495    400839070 : MSVehicle::nextLinkPriority(const std::vector<MSLane*>& conts) {
    6496    400839070 :     if (conts.size() < 2) {
    6497              :         return -1;
    6498              :     } else {
    6499    364900889 :         const MSLink* const link = conts[0]->getLinkTo(conts[1]);
    6500    364900889 :         if (link != nullptr) {
    6501    364879152 :             return link->havePriority() ? 1 : 0;
    6502              :         } else {
    6503              :             // disconnected route
    6504              :             return -1;
    6505              :         }
    6506              :     }
    6507              : }
    6508              : 
    6509              : 
    6510              : void
    6511   1871179667 : MSVehicle::updateOccupancyAndCurrentBestLane(const MSLane* startLane) {
    6512              :     std::vector<LaneQ>& currLanes = *myBestLanes.begin();
    6513              :     std::vector<LaneQ>::iterator i;
    6514              : #ifdef _DEBUG
    6515              :     bool found = false;
    6516              : #endif
    6517   5343631617 :     for (i = currLanes.begin(); i != currLanes.end(); ++i) {
    6518              :         double nextOccupation = 0;
    6519   7669466444 :         for (std::vector<MSLane*>::const_iterator j = (*i).bestContinuations.begin() + 1; j != (*i).bestContinuations.end(); ++j) {
    6520   4197014494 :             nextOccupation += (*j)->getBruttoVehLenSum();
    6521              :         }
    6522   3472451950 :         (*i).nextOccupation = nextOccupation;
    6523              : #ifdef DEBUG_BESTLANES
    6524              :         if (DEBUG_COND) {
    6525              :             std::cout << "     lane=" << (*i).lane->getID() << " nextOccupation=" << nextOccupation << "\n";
    6526              :         }
    6527              : #endif
    6528   3472451950 :         if ((*i).lane == startLane) {
    6529   1865900151 :             myCurrentLaneInBestLanes = i;
    6530              : #ifdef _DEBUG
    6531              :             found = true;
    6532              : #endif
    6533              :         }
    6534              :     }
    6535              : #ifdef _DEBUG
    6536              :     assert(found || startLane->isInternal());
    6537              : #endif
    6538   1871179667 : }
    6539              : 
    6540              : 
    6541              : const std::vector<MSLane*>&
    6542   2057221750 : MSVehicle::getBestLanesContinuation() const {
    6543   2057221750 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6544              :         return myEmptyLaneVector;
    6545              :     }
    6546   2057221750 :     return (*myCurrentLaneInBestLanes).bestContinuations;
    6547              : }
    6548              : 
    6549              : 
    6550              : const std::vector<MSLane*>&
    6551     69590123 : MSVehicle::getBestLanesContinuation(const MSLane* const l) const {
    6552              :     const MSLane* lane = l;
    6553              :     // XXX: shouldn't this be a "while" to cover more than one internal lane? (Leo) Refs. #2575
    6554     69590123 :     if (lane->getEdge().isInternal()) {
    6555              :         // internal edges are not kept inside the bestLanes structure
    6556      5110483 :         lane = lane->getLinkCont()[0]->getLane();
    6557              :     }
    6558     69590123 :     if (myBestLanes.size() == 0) {
    6559              :         return myEmptyLaneVector;
    6560              :     }
    6561    114906425 :     for (std::vector<LaneQ>::const_iterator i = myBestLanes[0].begin(); i != myBestLanes[0].end(); ++i) {
    6562    114893717 :         if ((*i).lane == lane) {
    6563     69577415 :             return (*i).bestContinuations;
    6564              :         }
    6565              :     }
    6566              :     return myEmptyLaneVector;
    6567              : }
    6568              : 
    6569              : const std::vector<const MSLane*>
    6570       290937 : MSVehicle::getUpcomingLanesUntil(double distance) const {
    6571              :     std::vector<const MSLane*> lanes;
    6572              : 
    6573       290937 :     if (distance <= 0. || hasArrived()) {
    6574              :         // WRITE_WARNINGF(TL("MSVehicle::getUpcomingLanesUntil(): distance ('%') should be greater than 0."), distance);
    6575              :         return lanes;
    6576              :     }
    6577              : 
    6578       290729 :     if (!myLaneChangeModel->isOpposite()) {
    6579       287403 :         distance += getPositionOnLane();
    6580              :     } else {
    6581         3326 :         distance += myLane->getOppositePos(getPositionOnLane());
    6582              :     }
    6583       290729 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6584       298762 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6585         8033 :         lanes.insert(lanes.end(), lane);
    6586         8033 :         distance -= lane->getLength();
    6587        13513 :         lane = lane->getLinkCont().front()->getViaLaneOrLane();
    6588              :     }
    6589              : 
    6590       290729 :     const std::vector<MSLane*>& contLanes = getBestLanesContinuation();
    6591       290729 :     if (contLanes.empty()) {
    6592              :         return lanes;
    6593              :     }
    6594              :     auto contLanesIt = contLanes.begin();
    6595       290729 :     MSRouteIterator routeIt = myCurrEdge;  // keep track of covered edges in myRoute
    6596       621921 :     while (distance > 0.) {
    6597       338998 :         MSLane* l = nullptr;
    6598       338998 :         if (contLanesIt != contLanes.end()) {
    6599       323118 :             l = *contLanesIt;
    6600              :             if (l != nullptr) {
    6601              :                 assert(l->getEdge().getID() == (*routeIt)->getLanes().front()->getEdge().getID());
    6602              :             }
    6603              :             ++contLanesIt;
    6604       323118 :             if (l != nullptr || myLane->isInternal()) {
    6605              :                 ++routeIt;
    6606              :             }
    6607       323118 :             if (l == nullptr) {
    6608         5476 :                 continue;
    6609              :             }
    6610        15880 :         } else if (routeIt != myRoute->end()) {  // bestLanes didn't get us far enough
    6611              :             // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6612         8963 :             l = (*routeIt)->getLanes().back();
    6613              :             ++routeIt;
    6614              :         } else {  // the search distance goes beyond our route
    6615              :             break;
    6616              :         }
    6617              : 
    6618              :         assert(l != nullptr);
    6619              : 
    6620              :         // insert internal lanes if applicable
    6621       326605 :         const MSLane* internalLane = lanes.size() > 0 ? lanes.back()->getInternalFollowingLane(l) : nullptr;
    6622       370758 :         while ((internalLane != nullptr) && internalLane->isInternal() && (distance > 0.)) {
    6623        44153 :             lanes.insert(lanes.end(), internalLane);
    6624        44153 :             distance -= internalLane->getLength();
    6625        70564 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6626              :         }
    6627       326605 :         if (distance <= 0.) {
    6628              :             break;
    6629              :         }
    6630              : 
    6631       325716 :         lanes.insert(lanes.end(), l);
    6632       325716 :         distance -= l->getLength();
    6633              :     }
    6634              : 
    6635              :     return lanes;
    6636            0 : }
    6637              : 
    6638              : const std::vector<const MSLane*>
    6639         6694 : MSVehicle::getPastLanesUntil(double distance) const {
    6640              :     std::vector<const MSLane*> lanes;
    6641              : 
    6642         6694 :     if (distance <= 0.) {
    6643              :         // WRITE_WARNINGF(TL("MSVehicle::getPastLanesUntil(): distance ('%') should be greater than 0."), distance);
    6644              :         return lanes;
    6645              :     }
    6646              : 
    6647         6586 :     MSRouteIterator routeIt = myCurrEdge;
    6648         6586 :     if (!myLaneChangeModel->isOpposite()) {
    6649         6562 :         distance += myLane->getLength() - getPositionOnLane();
    6650              :     } else {
    6651           24 :         distance += myLane->getParallelOpposite()->getLength() - myLane->getOppositePos(getPositionOnLane());
    6652              :     }
    6653         6586 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6654         6607 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6655           21 :         lanes.insert(lanes.end(), lane);
    6656           21 :         distance -= lane->getLength();
    6657           21 :         lane = lane->getLogicalPredecessorLane();
    6658              :     }
    6659              : 
    6660        10136 :     while (distance > 0.) {
    6661              :         // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6662         8799 :         MSLane* l = (*routeIt)->getLanes().back();
    6663              : 
    6664              :         // insert internal lanes if applicable
    6665         8799 :         const MSEdge* internalEdge = lanes.size() > 0 ? (*routeIt)->getInternalFollowingEdge(&(lanes.back()->getEdge()), getVClass()) : nullptr;
    6666         8820 :         const MSLane* internalLane = internalEdge != nullptr ? internalEdge->getLanes().front() : nullptr;
    6667              :         std::vector<const MSLane*> internalLanes;
    6668        11018 :         while ((internalLane != nullptr) && internalLane->isInternal()) {  // collect all internal successor lanes
    6669         2219 :             internalLanes.insert(internalLanes.begin(), internalLane);
    6670         4432 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6671              :         }
    6672        11018 :         for (auto it = internalLanes.begin(); (it != internalLanes.end()) && (distance > 0.); ++it) {  // check remaining distance in correct order
    6673         2219 :             lanes.insert(lanes.end(), *it);
    6674         2219 :             distance -= (*it)->getLength();
    6675              :         }
    6676         8799 :         if (distance <= 0.) {
    6677              :             break;
    6678              :         }
    6679              : 
    6680         8783 :         lanes.insert(lanes.end(), l);
    6681         8783 :         distance -= l->getLength();
    6682              : 
    6683              :         // NOTE: we're going backwards with the (bi-directional) Iterator
    6684              :         // TODO: consider make reverse_iterator() when moving on to C++14 or later
    6685         8783 :         if (routeIt != myRoute->begin()) {
    6686              :             --routeIt;
    6687              :         } else {  // we went backwards to begin() and already processed the first and final element
    6688              :             break;
    6689              :         }
    6690         8799 :     }
    6691              : 
    6692              :     return lanes;
    6693            0 : }
    6694              : 
    6695              : 
    6696              : const std::vector<MSLane*>
    6697         6358 : MSVehicle::getUpstreamOppositeLanes() const {
    6698         6358 :     const std::vector<const MSLane*> routeLanes = getPastLanesUntil(myLane->getMaximumBrakeDist());
    6699              :     std::vector<MSLane*> result;
    6700        15551 :     for (const MSLane* lane : routeLanes) {
    6701         9917 :         MSLane* opposite = lane->getOpposite();
    6702         9917 :         if (opposite != nullptr) {
    6703         9193 :             result.push_back(opposite);
    6704              :         } else {
    6705              :             break;
    6706              :         }
    6707              :     }
    6708         6358 :     return result;
    6709         6358 : }
    6710              : 
    6711              : 
    6712              : int
    6713    311173455 : MSVehicle::getBestLaneOffset() const {
    6714    311173455 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6715              :         return 0;
    6716              :     } else {
    6717    310882032 :         return (*myCurrentLaneInBestLanes).bestLaneOffset;
    6718              :     }
    6719              : }
    6720              : 
    6721              : double
    6722        23228 : MSVehicle::getBestLaneDist() const {
    6723        23228 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6724              :         return -1;
    6725              :     } else {
    6726        23228 :         return (*myCurrentLaneInBestLanes).length;
    6727              :     }
    6728              : }
    6729              : 
    6730              : 
    6731              : 
    6732              : void
    6733    644924572 : MSVehicle::adaptBestLanesOccupation(int laneIndex, double density) {
    6734              :     std::vector<MSVehicle::LaneQ>& preb = myBestLanes.front();
    6735              :     assert(laneIndex < (int)preb.size());
    6736    644924572 :     preb[laneIndex].occupation = density + preb[laneIndex].nextOccupation;
    6737    644924572 : }
    6738              : 
    6739              : 
    6740              : void
    6741        71298 : MSVehicle::fixPosition() {
    6742        71298 :     if (MSGlobals::gLaneChangeDuration > 0 && !myLaneChangeModel->isChangingLanes()) {
    6743        39640 :         myState.myPosLat = 0;
    6744              :     }
    6745        71298 : }
    6746              : 
    6747              : std::pair<const MSLane*, double>
    6748          303 : MSVehicle::getLanePosAfterDist(double distance) const {
    6749          303 :     if (distance == 0) {
    6750          255 :         return std::make_pair(myLane, getPositionOnLane());
    6751              :     }
    6752           48 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(distance);
    6753           48 :     distance += getPositionOnLane();
    6754           48 :     for (const MSLane* lane : lanes) {
    6755           48 :         if (lane->getLength() > distance) {
    6756              :             return std::make_pair(lane, distance);
    6757              :         }
    6758            0 :         distance -= lane->getLength();
    6759              :     }
    6760            0 :     return std::make_pair(nullptr, -1);
    6761           48 : }
    6762              : 
    6763              : 
    6764              : double
    6765        16113 : MSVehicle::getDistanceToPosition(double destPos, const MSLane* destLane) const {
    6766        16113 :     if (isOnRoad() && destLane != nullptr) {
    6767        16076 :         return myRoute->getDistanceBetween(getPositionOnLane(), destPos, myLane, destLane);
    6768              :     }
    6769              :     return std::numeric_limits<double>::max();
    6770              : }
    6771              : 
    6772              : 
    6773              : std::pair<const MSVehicle* const, double>
    6774     76421763 : MSVehicle::getLeader(double dist, bool considerCrossingFoes) const {
    6775     76421763 :     if (myLane == nullptr) {
    6776            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6777              :     }
    6778     76421763 :     if (dist == 0) {
    6779         2460 :         dist = getCarFollowModel().brakeGap(getSpeed()) + getVehicleType().getMinGap();
    6780              :     }
    6781              :     const MSVehicle* lead = nullptr;
    6782     76421763 :     const MSLane* lane = myLane; // ensure lane does not change between getVehiclesSecure and releaseVehicles;
    6783     76421763 :     const MSLane::VehCont& vehs = lane->getVehiclesSecure();
    6784              :     // vehicle might be outside the road network
    6785     76421763 :     MSLane::VehCont::const_iterator it = std::find(vehs.begin(), vehs.end(), this);
    6786     76421763 :     if (it != vehs.end() && it + 1 != vehs.end()) {
    6787     72700050 :         lead = *(it + 1);
    6788              :     }
    6789     72700050 :     if (lead != nullptr) {
    6790              :         std::pair<const MSVehicle* const, double> result(
    6791     72700050 :             lead, lead->getBackPositionOnLane(myLane) - getPositionOnLane() - getVehicleType().getMinGap());
    6792     72700050 :         lane->releaseVehicles();
    6793     72700050 :         return result;
    6794              :     }
    6795      3721713 :     const double seen = myLane->getLength() - getPositionOnLane();
    6796      3721713 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(myLane);
    6797      3721713 :     std::pair<const MSVehicle* const, double> result = myLane->getLeaderOnConsecutive(dist, seen, getSpeed(), *this, bestLaneConts, considerCrossingFoes);
    6798      3721710 :     lane->releaseVehicles();
    6799      3721710 :     return result;
    6800              : }
    6801              : 
    6802              : 
    6803              : std::pair<const MSVehicle* const, double>
    6804      2267653 : MSVehicle::getFollower(double dist) const {
    6805      2267653 :     if (myLane == nullptr) {
    6806            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6807              :     }
    6808      2267653 :     if (dist == 0) {
    6809       810978 :         dist = getCarFollowModel().brakeGap(myLane->getEdge().getSpeedLimit() * 2, 4.5, 0);
    6810              :     }
    6811      2267653 :     return myLane->getFollower(this, getPositionOnLane(), dist, MSLane::MinorLinkMode::FOLLOW_NEVER);
    6812              : }
    6813              : 
    6814              : 
    6815              : double
    6816            0 : MSVehicle::getTimeGapOnLane() const {
    6817              :     // calling getLeader with 0 would induce a dist calculation but we only want to look for the leaders on the current lane
    6818            0 :     std::pair<const MSVehicle* const, double> leaderInfo = getLeader(-1);
    6819            0 :     if (leaderInfo.first == nullptr || getSpeed() == 0) {
    6820            0 :         return -1;
    6821              :     }
    6822            0 :     return (leaderInfo.second + getVehicleType().getMinGap()) / getSpeed();
    6823              : }
    6824              : 
    6825              : 
    6826              : void
    6827      3729392 : MSVehicle::addTransportable(MSTransportable* transportable) {
    6828      3729392 :     MSBaseVehicle::addTransportable(transportable);
    6829        41246 :     if (myStops.size() > 0 && myStops.front().reached) {
    6830        37802 :         if (transportable->isPerson()) {
    6831        37223 :             if (myStops.front().triggered && myStops.front().numExpectedPerson > 0) {
    6832         1838 :                 myStops.front().numExpectedPerson -= (int)myStops.front().pars.awaitedPersons.count(transportable->getID());
    6833              :             }
    6834              :         } else {
    6835          579 :             if (myStops.front().pars.containerTriggered && myStops.front().numExpectedContainer > 0) {
    6836           20 :                 myStops.front().numExpectedContainer -= (int)myStops.front().pars.awaitedContainers.count(transportable->getID());
    6837              :             }
    6838              :         }
    6839              :     }
    6840        41246 : }
    6841              : 
    6842              : 
    6843              : void
    6844    701641505 : MSVehicle::setBlinkerInformation() {
    6845              :     switchOffSignal(VEH_SIGNAL_BLINKER_RIGHT | VEH_SIGNAL_BLINKER_LEFT);
    6846    701641505 :     int state = myLaneChangeModel->getOwnState();
    6847              :     // do not set blinker for sublane changes or when blocked from changing to the right
    6848    701641505 :     const bool blinkerManoeuvre = (((state & LCA_SUBLANE) == 0) && (
    6849    610023979 :                                        (state & LCA_KEEPRIGHT) == 0 || (state & LCA_BLOCKED) == 0));
    6850              :     Signalling left = VEH_SIGNAL_BLINKER_LEFT;
    6851              :     Signalling right = VEH_SIGNAL_BLINKER_RIGHT;
    6852    701641505 :     if (MSGlobals::gLefthand) {
    6853              :         // lane indices increase from left to right
    6854              :         std::swap(left, right);
    6855              :     }
    6856    701641505 :     if ((state & LCA_LEFT) != 0 && blinkerManoeuvre) {
    6857     20014485 :         switchOnSignal(left);
    6858    681627020 :     } else if ((state & LCA_RIGHT) != 0 && blinkerManoeuvre) {
    6859      5545635 :         switchOnSignal(right);
    6860    676081385 :     } else if (myLaneChangeModel->isChangingLanes()) {
    6861       254915 :         if (myLaneChangeModel->getLaneChangeDirection() == 1) {
    6862       165402 :             switchOnSignal(left);
    6863              :         } else {
    6864        89513 :             switchOnSignal(right);
    6865              :         }
    6866              :     } else {
    6867    675826470 :         const MSLane* lane = getLane();
    6868    675826470 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, 1, *lane, getBestLanesContinuation());
    6869    675826470 :         if (link != lane->getLinkCont().end() && lane->getLength() - getPositionOnLane() < lane->getVehicleMaxSpeed(this) * (double) 7.) {
    6870    170534373 :             switch ((*link)->getDirection()) {
    6871              :                 case LinkDirection::TURN:
    6872              :                 case LinkDirection::LEFT:
    6873              :                 case LinkDirection::PARTLEFT:
    6874              :                     switchOnSignal(VEH_SIGNAL_BLINKER_LEFT);
    6875              :                     break;
    6876              :                 case LinkDirection::RIGHT:
    6877              :                 case LinkDirection::PARTRIGHT:
    6878              :                     switchOnSignal(VEH_SIGNAL_BLINKER_RIGHT);
    6879              :                     break;
    6880              :                 default:
    6881              :                     break;
    6882              :             }
    6883              :         }
    6884              :     }
    6885              :     // stopping related signals
    6886    701641505 :     if (hasStops()
    6887    701641505 :             && (myStops.begin()->reached ||
    6888     15399275 :                 (myStopDist < (myLane->getLength() - getPositionOnLane())
    6889      4314913 :                  && myStopDist < getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this), getCarFollowModel().getMaxDecel(), 3)))) {
    6890     17311340 :         if (myStops.begin()->lane->getIndex() > 0 && myStops.begin()->lane->getParallelLane(-1)->allowsVehicleClass(getVClass())) {
    6891              :             // not stopping on the right. Activate emergency blinkers
    6892              :             switchOnSignal(VEH_SIGNAL_BLINKER_LEFT | VEH_SIGNAL_BLINKER_RIGHT);
    6893     17055377 :         } else if (!myStops.begin()->reached && (myStops.begin()->pars.parking == ParkingType::OFFROAD)) {
    6894              :             // signal upcoming parking stop on the current lane when within braking distance (~2 seconds before braking)
    6895      1636276 :             switchOnSignal(MSGlobals::gLefthand ? VEH_SIGNAL_BLINKER_LEFT : VEH_SIGNAL_BLINKER_RIGHT);
    6896              :         }
    6897              :     }
    6898    701641505 :     if (myInfluencer != nullptr && myInfluencer->getSignals() >= 0) {
    6899           14 :         mySignals = myInfluencer->getSignals();
    6900              :         myInfluencer->setSignals(-1); // overwrite computed signals only once
    6901              :     }
    6902    701641505 : }
    6903              : 
    6904              : void
    6905        85867 : MSVehicle::setEmergencyBlueLight(SUMOTime currentTime) {
    6906              : 
    6907              :     //TODO look if timestep ist SIMSTEP
    6908        85867 :     if (currentTime % 1000 == 0) {
    6909        26076 :         if (signalSet(VEH_SIGNAL_EMERGENCY_BLUE)) {
    6910              :             switchOffSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6911              :         } else {
    6912              :             switchOnSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6913              :         }
    6914              :     }
    6915        85867 : }
    6916              : 
    6917              : 
    6918              : int
    6919     22439224 : MSVehicle::getLaneIndex() const {
    6920     22439224 :     return myLane == nullptr ? -1 : myLane->getIndex();
    6921              : }
    6922              : 
    6923              : 
    6924              : void
    6925     14752066 : MSVehicle::setTentativeLaneAndPosition(MSLane* lane, double pos, double posLat) {
    6926     14752066 :     myLane = lane;
    6927     14752066 :     myState.myPos = pos;
    6928     14752066 :     myState.myPosLat = posLat;
    6929     14752066 :     myState.myBackPos = pos - getVehicleType().getLength();
    6930     14752066 : }
    6931              : 
    6932              : 
    6933              : double
    6934    395317436 : MSVehicle::getRightSideOnLane() const {
    6935    395317436 :     return myState.myPosLat + 0.5 * myLane->getWidth() - 0.5 * getVehicleType().getWidth();
    6936              : }
    6937              : 
    6938              : 
    6939              : double
    6940    390038962 : MSVehicle::getLeftSideOnLane() const {
    6941    390038962 :     return myState.myPosLat + 0.5 * myLane->getWidth() + 0.5 * getVehicleType().getWidth();
    6942              : }
    6943              : 
    6944              : 
    6945              : double
    6946    315970365 : MSVehicle::getRightSideOnLane(const MSLane* lane) const {
    6947    315970365 :     return myState.myPosLat + 0.5 * lane->getWidth() - 0.5 * getVehicleType().getWidth();
    6948              : }
    6949              : 
    6950              : 
    6951              : double
    6952    315481231 : MSVehicle::getLeftSideOnLane(const MSLane* lane) const {
    6953    315481231 :     return myState.myPosLat + 0.5 * lane->getWidth() + 0.5 * getVehicleType().getWidth();
    6954              : }
    6955              : 
    6956              : 
    6957              : double
    6958    249255473 : MSVehicle::getRightSideOnEdge(const MSLane* lane) const {
    6959    249255473 :     return getCenterOnEdge(lane) - 0.5 * getVehicleType().getWidth();
    6960              : }
    6961              : 
    6962              : 
    6963              : double
    6964     30974258 : MSVehicle::getLeftSideOnEdge(const MSLane* lane) const {
    6965     30974258 :     return getCenterOnEdge(lane) + 0.5 * getVehicleType().getWidth();
    6966              : }
    6967              : 
    6968              : 
    6969              : double
    6970    730162631 : MSVehicle::getCenterOnEdge(const MSLane* lane) const {
    6971    730162631 :     if (lane == nullptr || &lane->getEdge() == &myLane->getEdge()) {
    6972    729700673 :         return myLane->getRightSideOnEdge() + myState.myPosLat + 0.5 * myLane->getWidth();
    6973       461958 :     } else if (lane == myLaneChangeModel->getShadowLane()) {
    6974        13739 :         if (myLaneChangeModel->isOpposite() && &lane->getEdge() != &myLane->getEdge()) {
    6975        13730 :             return lane->getRightSideOnEdge() + lane->getWidth() - myState.myPosLat + 0.5 * myLane->getWidth();
    6976              :         }
    6977            9 :         if (myLaneChangeModel->getShadowDirection() == -1) {
    6978            0 :             return lane->getRightSideOnEdge() + lane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6979              :         } else {
    6980            9 :             return lane->getRightSideOnEdge() - myLane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6981              :         }
    6982       448219 :     } else if (lane == myLane->getBidiLane()) {
    6983        17033 :         return lane->getRightSideOnEdge() - myState.myPosLat + 0.5 * lane->getWidth();
    6984              :     } else {
    6985              :         assert(myFurtherLanes.size() == myFurtherLanesPosLat.size());
    6986       507611 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6987       481731 :             if (myFurtherLanes[i] == lane) {
    6988              : #ifdef DEBUG_FURTHER
    6989              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat=" << myFurtherLanesPosLat[i]
    6990              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6991              :                                               << "\n";
    6992              : #endif
    6993       405227 :                 return lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6994        76504 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    6995              : #ifdef DEBUG_FURTHER
    6996              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat(bidi)=" << myFurtherLanesPosLat[i]
    6997              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6998              :                                               << "\n";
    6999              : #endif
    7000           79 :                 return lane->getRightSideOnEdge() - myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    7001              :             }
    7002              :         }
    7003              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    7004        25880 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    7005        26153 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    7006              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    7007        26153 :             if (shadowFurther[i] == lane) {
    7008              :                 assert(myLaneChangeModel->getShadowLane() != 0);
    7009        25880 :                 return (lane->getRightSideOnEdge() + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
    7010        25880 :                         + (myLane->getCenterOnEdge() - myLaneChangeModel->getShadowLane()->getCenterOnEdge()));
    7011              :             }
    7012              :         }
    7013              :         assert(false);
    7014            0 :         throw ProcessError("Request lateral pos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    7015              :     }
    7016              : }
    7017              : 
    7018              : 
    7019              : double
    7020   3387441498 : MSVehicle::getLatOffset(const MSLane* lane) const {
    7021              :     assert(lane != 0);
    7022   3387441498 :     if (&lane->getEdge() == &myLane->getEdge()) {
    7023   3337121342 :         return myLane->getRightSideOnEdge() - lane->getRightSideOnEdge();
    7024     50320156 :     } else if (myLane->getParallelOpposite() == lane) {
    7025      2134265 :         return (myLane->getWidth() + lane->getWidth()) * 0.5 - 2 * getLateralPositionOnLane();
    7026     48185891 :     } else if (myLane->getBidiLane() == lane) {
    7027       808173 :         return -2 * getLateralPositionOnLane();
    7028              :     } else {
    7029              :         // Check whether the lane is a further lane for the vehicle
    7030     53504919 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    7031     52560124 :             if (myFurtherLanes[i] == lane) {
    7032              : #ifdef DEBUG_FURTHER
    7033              :                 if (DEBUG_COND) {
    7034              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherLat=" << myFurtherLanesPosLat[i] << "\n";
    7035              :                 }
    7036              : #endif
    7037     46399415 :                 return myFurtherLanesPosLat[i] - myState.myPosLat;
    7038      6160709 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    7039              : #ifdef DEBUG_FURTHER
    7040              :                 if (DEBUG_COND) {
    7041              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    7042              :                 }
    7043              : #endif
    7044        33508 :                 return -2 * (myFurtherLanesPosLat[i] - myState.myPosLat);
    7045              :             }
    7046              :         }
    7047              : #ifdef DEBUG_FURTHER
    7048              :         if (DEBUG_COND) {
    7049              :             std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    7050              :         }
    7051              : #endif
    7052              :         // Check whether the lane is a "shadow further lane" for the vehicle
    7053       944795 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    7054       956559 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    7055       952879 :             if (shadowFurther[i] == lane) {
    7056              : #ifdef DEBUG_FURTHER
    7057              :                 if (DEBUG_COND) std::cout << "    getLatOffset veh=" << getID()
    7058              :                                               << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    7059              :                                               << " lane=" << lane->getID()
    7060              :                                               << " i=" << i
    7061              :                                               << " posLat=" << myState.myPosLat
    7062              :                                               << " shadowPosLat=" << getLatOffset(myLaneChangeModel->getShadowLane())
    7063              :                                               << " shadowFurtherLat=" << myLaneChangeModel->getShadowFurtherLanesPosLat()[i]
    7064              :                                               <<  "\n";
    7065              : #endif
    7066       940441 :                 return getLatOffset(myLaneChangeModel->getShadowLane()) + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] - myState.myPosLat;
    7067        12438 :             } else if (shadowFurther[i]->getBidiLane() == lane) {
    7068              : #ifdef DEBUG_FURTHER
    7069              :                 if (DEBUG_COND) {
    7070              :                     std::cout << "    getLatOffset veh=" << getID() << " shadowbidilane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    7071              :                 }
    7072              : #endif
    7073          674 :                 return -2 * getLatOffset(myLaneChangeModel->getShadowLane()) + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] - myState.myPosLat;
    7074              :             }
    7075              :         }
    7076              :         // Check whether the vehicle issued a maneuverReservation on the lane.
    7077         3680 :         const std::vector<MSLane*>& furtherTargets = myLaneChangeModel->getFurtherTargetLanes();
    7078         5215 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    7079              :             // Further target lanes are just neighboring lanes of the vehicle's further lanes, @see MSAbstractLaneChangeModel::updateTargetLane()
    7080         5211 :             MSLane* targetLane = furtherTargets[i];
    7081         5211 :             if (targetLane == lane) {
    7082         3676 :                 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
    7083         3676 :                 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
    7084              : #ifdef DEBUG_TARGET_LANE
    7085              :                 if (DEBUG_COND) {
    7086              :                     std::cout << "    getLatOffset veh=" << getID()
    7087              :                               << " wrt targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    7088              :                               << "\n    i=" << i
    7089              :                               << " posLat=" << myState.myPosLat
    7090              :                               << " furtherPosLat=" << myFurtherLanesPosLat[i]
    7091              :                               << " maneuverDist=" << myLaneChangeModel->getManeuverDist()
    7092              :                               << " targetDir=" << targetDir
    7093              :                               << " latOffset=" << latOffset
    7094              :                               <<  std::endl;
    7095              :                 }
    7096              : #endif
    7097         3676 :                 return latOffset;
    7098         1535 :             } else if (targetLane != nullptr && targetLane->getBidiLane() == lane) {
    7099            0 :                 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
    7100            0 :                 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
    7101              : #ifdef DEBUG_FURTHER
    7102              :                 if (DEBUG_COND) {
    7103              :                     std::cout << "    getLatOffset veh=" << getID() << " furthertargetbidilane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    7104              :                 }
    7105              : #endif
    7106            0 :                 return -2 * latOffset;
    7107              :             }
    7108              :         }
    7109              :         assert(false);
    7110           24 :         throw ProcessError("Request lateral offset of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    7111              :     }
    7112              : }
    7113              : 
    7114              : 
    7115              : double
    7116     36269696 : MSVehicle::lateralDistanceToLane(const int offset) const {
    7117              :     // compute the distance when changing to the neighboring lane
    7118              :     // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
    7119              :     assert(offset == 0 || offset == 1 || offset == -1);
    7120              :     assert(myLane != nullptr);
    7121              :     assert(myLane->getParallelLane(offset) != nullptr || myLane->getParallelOpposite() != nullptr);
    7122     36269696 :     const double halfCurrentLaneWidth = 0.5 * myLane->getWidth();
    7123     36269696 :     const double halfVehWidth = 0.5 * (getWidth() + NUMERICAL_EPS);
    7124     36269696 :     const double latPos = getLateralPositionOnLane();
    7125     36269696 :     const double oppositeSign = getLaneChangeModel().isOpposite() ? -1 : 1;
    7126     36269696 :     double leftLimit = halfCurrentLaneWidth - halfVehWidth - oppositeSign * latPos;
    7127     36269696 :     double rightLimit = -halfCurrentLaneWidth + halfVehWidth - oppositeSign * latPos;
    7128              :     double latLaneDist = 0;  // minimum distance to move the vehicle fully onto the new lane
    7129     36269696 :     if (offset == 0) {
    7130            8 :         if (latPos + halfVehWidth > halfCurrentLaneWidth) {
    7131              :             // correct overlapping left
    7132            4 :             latLaneDist = halfCurrentLaneWidth - latPos - halfVehWidth;
    7133            4 :         } else if (latPos - halfVehWidth < -halfCurrentLaneWidth) {
    7134              :             // correct overlapping right
    7135            4 :             latLaneDist = -halfCurrentLaneWidth - latPos + halfVehWidth;
    7136              :         }
    7137            8 :         latLaneDist *= oppositeSign;
    7138     36269688 :     } else if (offset == -1) {
    7139     16759961 :         latLaneDist = rightLimit - (getWidth() + NUMERICAL_EPS);
    7140     19509727 :     } else if (offset == 1) {
    7141     19509727 :         latLaneDist = leftLimit + (getWidth() + NUMERICAL_EPS);
    7142              :     }
    7143              : #ifdef DEBUG_ACTIONSTEPS
    7144              :     if (DEBUG_COND) {
    7145              :         std::cout << SIMTIME
    7146              :                   << " veh=" << getID()
    7147              :                   << " halfCurrentLaneWidth=" << halfCurrentLaneWidth
    7148              :                   << " halfVehWidth=" << halfVehWidth
    7149              :                   << " latPos=" << latPos
    7150              :                   << " latLaneDist=" << latLaneDist
    7151              :                   << " leftLimit=" << leftLimit
    7152              :                   << " rightLimit=" << rightLimit
    7153              :                   << "\n";
    7154              :     }
    7155              : #endif
    7156     36269696 :     return latLaneDist;
    7157              : }
    7158              : 
    7159              : 
    7160              : double
    7161   5192077222 : MSVehicle::getLateralOverlap(double posLat, const MSLane* lane) const {
    7162   5192077222 :     return (fabs(posLat) + 0.5 * getVehicleType().getWidth()
    7163   5192077222 :             - 0.5 * lane->getWidth());
    7164              : }
    7165              : 
    7166              : double
    7167            0 : MSVehicle::getLateralOverlap(const MSLane* lane) const {
    7168            0 :     return getLateralOverlap(getLateralPositionOnLane(), lane);
    7169              : }
    7170              : 
    7171              : double
    7172   4995095677 : MSVehicle::getLateralOverlap() const {
    7173   4995095677 :     return getLateralOverlap(getLateralPositionOnLane(), myLane);
    7174              : }
    7175              : 
    7176              : 
    7177              : void
    7178    645011233 : MSVehicle::removeApproachingInformation(const DriveItemVector& lfLinks) const {
    7179   1881099756 :     for (const DriveProcessItem& dpi : lfLinks) {
    7180   1236088523 :         if (dpi.myLink != nullptr) {
    7181    880581444 :             dpi.myLink->removeApproaching(this);
    7182              :         }
    7183              :     }
    7184              :     // unregister on all shadow links
    7185    645011233 :     myLaneChangeModel->removeShadowApproachingInformation();
    7186    645011233 : }
    7187              : 
    7188              : 
    7189              : bool
    7190       847241 : MSVehicle::unsafeLinkAhead(const MSLane* lane, double zipperDist) const {
    7191              :     // the following links are unsafe:
    7192              :     // - zipper links if they are close enough and have approaching vehicles in the relevant time range
    7193              :     // - unprioritized links if the vehicle is currently approaching a prioritzed link and unable to stop in time
    7194       847241 :     double seen = myLane->getLength() - getPositionOnLane();
    7195       847241 :     const double dist = MAX2(zipperDist, getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0));
    7196       847241 :     if (seen < dist) {
    7197        71195 :         const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(lane);
    7198              :         int view = 1;
    7199        71195 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7200              :         DriveItemVector::const_iterator di = myLFLinkLanes.begin();
    7201       118475 :         while (!lane->isLinkEnd(link) && seen <= dist) {
    7202        71920 :             if ((!lane->isInternal()
    7203        49296 :                     && (((*link)->getState() == LINKSTATE_ZIPPER && seen < (*link)->getFoeVisibilityDistance())
    7204        26694 :                         || !(*link)->havePriority()))
    7205        98381 :                     || (lane->isInternal() && zipperDist > 0)) {
    7206              :                 // find the drive item corresponding to this link
    7207              :                 bool found = false;
    7208        52288 :                 while (di != myLFLinkLanes.end() && !found) {
    7209        27086 :                     if ((*di).myLink != nullptr) {
    7210              :                         const MSLane* diPredLane = (*di).myLink->getLaneBefore();
    7211        27081 :                         if (diPredLane != nullptr) {
    7212        27081 :                             if (&diPredLane->getEdge() == &lane->getEdge()) {
    7213              :                                 found = true;
    7214              :                             }
    7215              :                         }
    7216              :                     }
    7217        27086 :                     if (!found) {
    7218              :                         di++;
    7219              :                     }
    7220              :                 }
    7221        25202 :                 if (found) {
    7222        25197 :                     const SUMOTime leaveTime = (*link)->getLeaveTime((*di).myArrivalTime, (*di).myArrivalSpeed,
    7223        25197 :                                                (*di).getLeaveSpeed(), getVehicleType().getLength());
    7224        25197 :                     const MSLink* entry = (*link)->getCorrespondingEntryLink();
    7225              :                     //if (DEBUG_COND) {
    7226              :                     //    std::cout << SIMTIME << " veh=" << getID() << " changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << " zipperDist=" << zipperDist << " aT=" << STEPS2TIME((*di).myArrivalTime) << " lT=" << STEPS2TIME(leaveTime) << "\n";
    7227              :                     //}
    7228        25197 :                     if (entry->hasApproachingFoe((*di).myArrivalTime, leaveTime, (*di).myArrivalSpeed, getCarFollowModel().getMaxDecel())) {
    7229              :                         //std::cout << SIMTIME << " veh=" << getID() << " aborting changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << "\n";
    7230              :                         return true;
    7231              :                     }
    7232              :                 }
    7233              :                 // no drive item is found if the vehicle aborts its request within dist
    7234              :             }
    7235        47280 :             lane = (*link)->getViaLaneOrLane();
    7236        47280 :             if (!lane->getEdge().isInternal()) {
    7237        24628 :                 view++;
    7238              :             }
    7239        47280 :             seen += lane->getLength();
    7240        47280 :             link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7241              :         }
    7242              :     }
    7243              :     return false;
    7244              : }
    7245              : 
    7246              : 
    7247              : PositionVector
    7248      6886975 : MSVehicle::getBoundingBox(double offset) const {
    7249      6886975 :     PositionVector centerLine;
    7250      6886975 :     Position pos = getPosition();
    7251      6886975 :     centerLine.push_back(pos);
    7252      6886975 :     switch (myType->getGuiShape()) {
    7253        29069 :         case SUMOVehicleShape::BUS_FLEXIBLE:
    7254              :         case SUMOVehicleShape::RAIL:
    7255              :         case SUMOVehicleShape::RAIL_CAR:
    7256              :         case SUMOVehicleShape::RAIL_CARGO:
    7257              :         case SUMOVehicleShape::TRUCK_SEMITRAILER:
    7258              :         case SUMOVehicleShape::TRUCK_1TRAILER: {
    7259        60781 :             for (MSLane* lane : myFurtherLanes) {
    7260        31712 :                 centerLine.push_back(lane->getShape().back());
    7261              :             }
    7262              :             break;
    7263              :         }
    7264              :         default:
    7265              :             break;
    7266              :     }
    7267      6886975 :     double l = getLength();
    7268      6886975 :     Position backPos = getBackPosition();
    7269      6886975 :     if (pos.distanceTo2D(backPos) > l + NUMERICAL_EPS) {
    7270              :         // getBackPosition may not match the visual back in networks without internal lanes
    7271       348778 :         double a = getAngle() + M_PI; // angle pointing backwards
    7272       348778 :         backPos = pos + Position(l * cos(a), l * sin(a));
    7273              :     }
    7274      6886975 :     centerLine.push_back(backPos);
    7275      6886975 :     if (offset != 0) {
    7276         6543 :         centerLine.extrapolate2D(offset);
    7277              :     }
    7278              :     PositionVector result = centerLine;
    7279     13769660 :     result.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7280     13769660 :     centerLine.move2side(MIN2(0.0, -0.5 * myType->getWidth() - offset));
    7281      6886975 :     result.append(centerLine.reverse(), POSITION_EPS);
    7282      6886975 :     return result;
    7283      6886975 : }
    7284              : 
    7285              : 
    7286              : PositionVector
    7287        72897 : MSVehicle::getBoundingPoly(double offset) const {
    7288        72897 :     switch (myType->getGuiShape()) {
    7289        72371 :         case SUMOVehicleShape::PASSENGER:
    7290              :         case SUMOVehicleShape::PASSENGER_SEDAN:
    7291              :         case SUMOVehicleShape::PASSENGER_HATCHBACK:
    7292              :         case SUMOVehicleShape::PASSENGER_WAGON:
    7293              :         case SUMOVehicleShape::PASSENGER_VAN: {
    7294              :             // box with corners cut off
    7295        72371 :             PositionVector result;
    7296        72371 :             PositionVector centerLine;
    7297        72371 :             centerLine.push_back(getPosition());
    7298        72371 :             centerLine.push_back(getBackPosition());
    7299        72371 :             if (offset != 0) {
    7300         1600 :                 centerLine.extrapolate2D(offset);
    7301              :             }
    7302              :             PositionVector line1 = centerLine;
    7303              :             PositionVector line2 = centerLine;
    7304       144742 :             line1.move2side(MAX2(0.0, 0.3 * myType->getWidth() + offset));
    7305       144742 :             line2.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7306        72371 :             line2.scaleRelative(0.8);
    7307        72371 :             result.push_back(line1[0]);
    7308        72371 :             result.push_back(line2[0]);
    7309        72371 :             result.push_back(line2[1]);
    7310        72371 :             result.push_back(line1[1]);
    7311       144742 :             line1.move2side(MIN2(0.0, -0.6 * myType->getWidth() - offset));
    7312       144742 :             line2.move2side(MIN2(0.0, -1.0 * myType->getWidth() - offset));
    7313        72371 :             result.push_back(line1[1]);
    7314        72371 :             result.push_back(line2[1]);
    7315        72371 :             result.push_back(line2[0]);
    7316        72371 :             result.push_back(line1[0]);
    7317              :             return result;
    7318        72371 :         }
    7319          526 :         default:
    7320          526 :             return getBoundingBox();
    7321              :     }
    7322              : }
    7323              : 
    7324              : 
    7325              : bool
    7326     12727452 : MSVehicle::onFurtherEdge(const MSEdge* edge) const {
    7327     13741521 :     for (std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    7328      1597412 :         if (&(*i)->getEdge() == edge) {
    7329              :             return true;
    7330              :         }
    7331              :     }
    7332              :     return false;
    7333              : }
    7334              : 
    7335              : 
    7336              : bool
    7337   7790682885 : MSVehicle::isBidiOn(const MSLane* lane) const {
    7338   7806745283 :     return lane->getBidiLane() != nullptr && (
    7339     16062398 :                myLane == lane->getBidiLane()
    7340     12727452 :                || onFurtherEdge(&lane->getBidiLane()->getEdge()));
    7341              : }
    7342              : 
    7343              : 
    7344              : bool
    7345           16 : MSVehicle::rerouteParkingArea(const std::string& parkingAreaID, std::string& errorMsg) {
    7346              :     // this function is based on MSTriggeredRerouter::rerouteParkingArea in order to keep
    7347              :     // consistency in the behaviour.
    7348              : 
    7349              :     // get vehicle params
    7350           16 :     MSParkingArea* destParkArea = getNextParkingArea();
    7351           16 :     const MSRoute& route = getRoute();
    7352           16 :     const MSEdge* lastEdge = route.getLastEdge();
    7353              : 
    7354           16 :     if (destParkArea == nullptr) {
    7355              :         // not driving towards a parking area
    7356            0 :         errorMsg = "Vehicle " + getID() + " is not driving to a parking area so it cannot be rerouted.";
    7357            0 :         return false;
    7358              :     }
    7359              : 
    7360              :     // if the current route ends at the parking area, the new route will also and at the new area
    7361           16 :     bool newDestination = (&destParkArea->getLane().getEdge() == route.getLastEdge()
    7362            8 :                            && getArrivalPos() >= destParkArea->getBeginLanePosition()
    7363           24 :                            && getArrivalPos() <= destParkArea->getEndLanePosition());
    7364              : 
    7365              :     // retrieve info on the new parking area
    7366           16 :     MSParkingArea* newParkingArea = (MSParkingArea*) MSNet::getInstance()->getStoppingPlace(
    7367              :                                         parkingAreaID, SumoXMLTag::SUMO_TAG_PARKING_AREA);
    7368              : 
    7369           16 :     if (newParkingArea == nullptr) {
    7370            0 :         errorMsg = "Parking area ID " + toString(parkingAreaID) + " not found in the network.";
    7371            0 :         return false;
    7372              :     }
    7373              : 
    7374           16 :     const MSEdge* newEdge = &(newParkingArea->getLane().getEdge());
    7375           16 :     SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = getRouterTT();
    7376              : 
    7377              :     // Compute the route from the current edge to the parking area edge
    7378              :     ConstMSEdgeVector edgesToPark;
    7379           16 :     router.compute(getEdge(), getPositionOnLane(), newEdge, newParkingArea->getEndLanePosition(), this, MSNet::getInstance()->getCurrentTimeStep(), edgesToPark);
    7380              : 
    7381              :     // Compute the route from the parking area edge to the end of the route
    7382              :     ConstMSEdgeVector edgesFromPark;
    7383           16 :     if (!newDestination) {
    7384           12 :         router.compute(newEdge, lastEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesFromPark);
    7385              :     } else {
    7386              :         // adapt plans of any riders
    7387            8 :         for (MSTransportable* p : getPersons()) {
    7388            4 :             p->rerouteParkingArea(getNextParkingArea(), newParkingArea);
    7389              :         }
    7390              :     }
    7391              : 
    7392              :     // we have a new destination, let's replace the vehicle route
    7393           16 :     ConstMSEdgeVector edges = edgesToPark;
    7394           16 :     if (edgesFromPark.size() > 0) {
    7395           12 :         edges.insert(edges.end(), edgesFromPark.begin() + 1, edgesFromPark.end());
    7396              :     }
    7397              : 
    7398           16 :     if (newDestination && getParameter().arrivalPosProcedure != ArrivalPosDefinition::DEFAULT) {
    7399            4 :         SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
    7400            4 :         *newParameter = getParameter();
    7401            4 :         newParameter->arrivalPosProcedure = ArrivalPosDefinition::GIVEN;
    7402            4 :         newParameter->arrivalPos = newParkingArea->getEndLanePosition();
    7403            4 :         replaceParameter(newParameter);
    7404              :     }
    7405           16 :     const double routeCost = router.recomputeCosts(edges, this, MSNet::getInstance()->getCurrentTimeStep());
    7406           16 :     ConstMSEdgeVector prevEdges(myCurrEdge, myRoute->end());
    7407           16 :     const double savings = router.recomputeCosts(prevEdges, this, MSNet::getInstance()->getCurrentTimeStep());
    7408           16 :     if (replaceParkingArea(newParkingArea, errorMsg)) {
    7409           16 :         const bool onInit = myLane == nullptr;
    7410           32 :         replaceRouteEdges(edges, routeCost, savings, "TraCI:" + toString(SUMO_TAG_PARKING_AREA_REROUTE), onInit, false, false);
    7411              :     } else {
    7412            0 :         WRITE_WARNINGF("Vehicle '%' could not reroute to new parkingArea '%' reason=%, time=%.",
    7413              :                 getID(), newParkingArea->getID(), errorMsg, time2string(SIMSTEP));
    7414            0 :         return false;
    7415              :     }
    7416           16 :     return true;
    7417           16 : }
    7418              : 
    7419              : 
    7420              : bool
    7421        46192 : MSVehicle::addTraciStop(SUMOVehicleParameter::Stop stop, std::string& errorMsg) {
    7422        46192 :     const int numStops = (int)myStops.size();
    7423        46192 :     const bool result = MSBaseVehicle::addTraciStop(stop, errorMsg);
    7424        46192 :     if (myLane != nullptr && numStops != (int)myStops.size()) {
    7425        44577 :         updateBestLanes(true);
    7426              :     }
    7427        46192 :     return result;
    7428              : }
    7429              : 
    7430              : 
    7431              : bool
    7432         3238 : MSVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
    7433         3238 :     if (myCurrEdge == stop.edge && distToStop + POSITION_EPS < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0)) {
    7434         1495 :         if (distToStop < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)) {
    7435         1086 :             double vNew = getCarFollowModel().maximumSafeStopSpeed(distToStop, getCarFollowModel().getMaxDecel(), getSpeed(), false, 0);
    7436              :             //std::cout << SIMTIME << " veh=" << getID() << " v=" << myState.mySpeed << " distToStop=" << distToStop
    7437              :             //    << " vMinNex=" << getCarFollowModel().minNextSpeed(getSpeed(), this)
    7438              :             //    << " bg1=" << getCarFollowModel().brakeGap(myState.mySpeed)
    7439              :             //    << " bg2=" << getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)
    7440              :             //    << " vNew=" << vNew
    7441              :             //    << "\n";
    7442         1086 :             myState.mySpeed = MIN2(myState.mySpeed, vNew + ACCEL2SPEED(getCarFollowModel().getEmergencyDecel()));
    7443         1086 :             myState.myPos = MIN2(myState.myPos, stop.pars.endPos);
    7444         1086 :             myCachedPosition = Position::INVALID;
    7445         1086 :             if (myState.myPos < myType->getLength()) {
    7446          453 :                 computeFurtherLanes(myLane, myState.myPos, true);
    7447          453 :                 myAngle = computeAngle();
    7448          453 :                 if (myLaneChangeModel->isOpposite()) {
    7449            0 :                     myAngle += M_PI;
    7450              :                 }
    7451              :             }
    7452              :         }
    7453              :     }
    7454         3238 :     return true;
    7455              : }
    7456              : 
    7457              : 
    7458              : bool
    7459     24173029 : MSVehicle::resumeFromStopping() {
    7460     24173029 :     if (isStopped()) {
    7461        49368 :         if (myAmRegisteredAsWaiting) {
    7462          750 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    7463          750 :             myAmRegisteredAsWaiting = false;
    7464              :         }
    7465              :         MSStop& stop = myStops.front();
    7466              :         // we have waited long enough and fulfilled any passenger-requirements
    7467        49368 :         if (stop.busstop != nullptr) {
    7468              :             // inform bus stop about leaving it
    7469        18592 :             stop.busstop->leaveFrom(this);
    7470              :         }
    7471              :         // we have waited long enough and fulfilled any container-requirements
    7472        49368 :         if (stop.containerstop != nullptr) {
    7473              :             // inform container stop about leaving it
    7474          530 :             stop.containerstop->leaveFrom(this);
    7475              :         }
    7476        49368 :         if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    7477              :             // inform parking area about leaving it
    7478         8435 :             stop.parkingarea->leaveFrom(this);
    7479              :         }
    7480        49368 :         if (stop.chargingStation != nullptr) {
    7481              :             // inform charging station about leaving it
    7482         3583 :             stop.chargingStation->leaveFrom(this);
    7483              :         }
    7484              :         // the current stop is no longer valid
    7485        49368 :         myLane->getEdge().removeWaiting(this);
    7486              :         // MSStopOut needs to know whether the stop had a loaded 'ended' value so we call this before replacing the value
    7487        49368 :         if (stop.pars.started == -1) {
    7488              :             // waypoint edge was passed in a single step
    7489          334 :             stop.pars.started = MSNet::getInstance()->getCurrentTimeStep();
    7490              :         }
    7491        49368 :         if (MSStopOut::active()) {
    7492         4265 :             MSStopOut::getInstance()->stopEnded(this, stop);
    7493              :         }
    7494        49368 :         stop.pars.ended = MSNet::getInstance()->getCurrentTimeStep();
    7495       112403 :         for (const auto& rem : myMoveReminders) {
    7496        63035 :             rem.first->notifyStopEnded();
    7497              :         }
    7498        49368 :         if (stop.pars.collision && MSLane::getCollisionAction() == MSLane::COLLISION_ACTION_WARN) {
    7499          425 :             myCollisionImmunity = TIME2STEPS(5); // leave the conflict area
    7500              :         }
    7501        49368 :         if (stop.pars.posLat != INVALID_DOUBLE && MSGlobals::gLateralResolution <= 0) {
    7502              :             // reset lateral position to default
    7503          195 :             myState.myPosLat = 0;
    7504              :         }
    7505        49368 :         const bool wasWaypoint = stop.getSpeed() > 0;
    7506        49368 :         myPastStops.push_back(stop.pars);
    7507        49368 :         myPastStops.back().routeIndex = (int)(stop.edge - myRoute->begin());
    7508        49368 :         myStops.pop_front();
    7509        49368 :         myStopDist = std::numeric_limits<double>::max();
    7510              :         // do not count the stopping time towards gridlock time.
    7511              :         // Other outputs use an independent counter and are not affected.
    7512        49368 :         myWaitingTime = 0;
    7513        49368 :         myStopSpeed = getCarFollowModel().maxNextSpeed(getSpeed(), this);
    7514              :         // maybe the next stop is on the same edge; let's rebuild best lanes
    7515        49368 :         updateBestLanes(true);
    7516              :         // continue as wished...
    7517        49368 :         MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::ENDING_STOP);
    7518        49368 :         MSNet::getInstance()->getVehicleControl().registerStopEnded();
    7519        49368 :         return !wasWaypoint;
    7520              :     }
    7521              :     return false;
    7522              : }
    7523              : 
    7524              : 
    7525              : MSVehicle::Influencer&
    7526      4566636 : MSVehicle::getInfluencer() {
    7527      4566636 :     if (myInfluencer == nullptr) {
    7528         3487 :         myInfluencer = new Influencer();
    7529              :     }
    7530      4566636 :     return *myInfluencer;
    7531              : }
    7532              : 
    7533              : MSVehicle::BaseInfluencer&
    7534           24 : MSVehicle::getBaseInfluencer() {
    7535           24 :     return getInfluencer();
    7536              : }
    7537              : 
    7538              : 
    7539              : const MSVehicle::Influencer*
    7540            0 : MSVehicle::getInfluencer() const {
    7541            0 :     return myInfluencer;
    7542              : }
    7543              : 
    7544              : const MSVehicle::BaseInfluencer*
    7545       237154 : MSVehicle::getBaseInfluencer() const {
    7546       237154 :     return myInfluencer;
    7547              : }
    7548              : 
    7549              : 
    7550              : double
    7551         4078 : MSVehicle::getSpeedWithoutTraciInfluence() const {
    7552         4078 :     if (myInfluencer != nullptr && myInfluencer->getOriginalSpeed() >= 0) {
    7553              :         // influencer original speed is -1 on initialization
    7554         1655 :         return myInfluencer->getOriginalSpeed();
    7555              :     }
    7556         2423 :     return myState.mySpeed;
    7557              : }
    7558              : 
    7559              : 
    7560              : int
    7561    999585049 : MSVehicle::influenceChangeDecision(int state) {
    7562    999585049 :     if (hasInfluencer()) {
    7563      2829460 :         state = getInfluencer().influenceChangeDecision(
    7564              :                     MSNet::getInstance()->getCurrentTimeStep(),
    7565      2829460 :                     myLane->getEdge(),
    7566              :                     getLaneIndex(),
    7567              :                     state);
    7568              :     }
    7569    999585049 :     return state;
    7570              : }
    7571              : 
    7572              : 
    7573              : void
    7574         7339 : MSVehicle::setRemoteState(Position xyPos) {
    7575         7339 :     myCachedPosition = xyPos;
    7576         7339 : }
    7577              : 
    7578              : 
    7579              : bool
    7580    796881565 : MSVehicle::isRemoteControlled() const {
    7581    796881565 :     return myInfluencer != nullptr && myInfluencer->isRemoteControlled();
    7582              : }
    7583              : 
    7584              : 
    7585              : bool
    7586        20568 : MSVehicle::wasRemoteControlled(SUMOTime lookBack) const {
    7587        20568 :     return myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() + lookBack >= MSNet::getInstance()->getCurrentTimeStep();
    7588              : }
    7589              : 
    7590              : 
    7591              : bool
    7592    541451501 : MSVehicle::keepClear(const MSLink* link) const {
    7593    541451501 :     if (link->hasFoes() && link->keepClear() /* && item.myLink->willHaveBlockedFoe()*/) {
    7594    174550944 :         const double keepClearTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, -1);
    7595              :         //std::cout << SIMTIME << " veh=" << getID() << " keepClearTime=" << keepClearTime << " accWait=" << getAccumulatedWaitingSeconds() << " keepClear=" << (keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime) << "\n";
    7596    175973289 :         return keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime;
    7597              :     } else {
    7598              :         return false;
    7599              :     }
    7600              : }
    7601              : 
    7602              : 
    7603              : bool
    7604    731606905 : MSVehicle::ignoreRed(const MSLink* link, bool canBrake) const {
    7605    731606905 :     if ((myInfluencer != nullptr && !myInfluencer->getEmergencyBrakeRedLight())) {
    7606              :         return true;
    7607              :     }
    7608    731299094 :     const double ignoreRedTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, -1);
    7609              : #ifdef DEBUG_IGNORE_RED
    7610              :     if (DEBUG_COND) {
    7611              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID() << " state=" << toString(link->getState()) << "\n";
    7612              :     }
    7613              : #endif
    7614    731299094 :     if (ignoreRedTime < 0) {
    7615    731293695 :         const double ignoreYellowTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, 0);
    7616    731293695 :         if (ignoreYellowTime > 0 && link->haveYellow()) {
    7617              :             assert(link->getTLLogic() != 0);
    7618           52 :             const double yellowDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7619              :             // when activating ignoreYellow behavior, vehicles will drive if they cannot brake
    7620           92 :             return !canBrake || ignoreYellowTime > yellowDuration;
    7621              :         } else {
    7622              :             return false;
    7623              :         }
    7624         5399 :     } else if (link->haveYellow()) {
    7625              :         // always drive at yellow when ignoring red
    7626              :         return true;
    7627         5243 :     } else if (link->haveRed()) {
    7628              :         assert(link->getTLLogic() != 0);
    7629         3832 :         const double redDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7630              : #ifdef DEBUG_IGNORE_RED
    7631              :         if (DEBUG_COND) {
    7632              :             std::cout
    7633              :             // << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID()
    7634              :                     << "   ignoreRedTime=" << ignoreRedTime
    7635              :                     << " spentRed=" << redDuration
    7636              :                     << " canBrake=" << canBrake << "\n";
    7637              :         }
    7638              : #endif
    7639              :         // when activating ignoreRed behavior, vehicles will always drive if they cannot brake
    7640         6356 :         return !canBrake || ignoreRedTime > redDuration;
    7641              :     } else {
    7642              :         return false;
    7643              :     }
    7644              : }
    7645              : 
    7646              : bool
    7647   1338114981 : MSVehicle::ignoreFoe(const SUMOTrafficObject* foe) const {
    7648   1338114981 :     if (!getParameter().wasSet(VEHPARS_CFMODEL_PARAMS_SET)) {
    7649              :         return false;
    7650              :     }
    7651         2548 :     for (const std::string& typeID : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_TYPES), "")).getVector()) {
    7652          398 :         if (typeID == foe->getVehicleType().getID()) {
    7653              :             return true;
    7654              :         }
    7655         1274 :     }
    7656         2161 :     for (const std::string& id : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_IDS), "")).getVector()) {
    7657          876 :         if (id == foe->getID()) {
    7658              :             return true;
    7659              :         }
    7660          876 :     }
    7661          409 :     return false;
    7662              : }
    7663              : 
    7664              : bool
    7665    548958683 : MSVehicle::passingMinor() const {
    7666              :     // either on an internal lane that was entered via minor link
    7667              :     // or on approach to minor link below visibility distance
    7668    548958683 :     if (myLane == nullptr) {
    7669              :         return false;
    7670              :     }
    7671    548958683 :     if (myLane->getEdge().isInternal()) {
    7672     10362557 :         return !myLane->getIncomingLanes().front().viaLink->havePriority();
    7673    538596126 :     } else if (myLFLinkLanes.size() > 0 && myLFLinkLanes.front().myLink != nullptr) {
    7674              :         MSLink* link = myLFLinkLanes.front().myLink;
    7675    281376995 :         return !link->havePriority() && myLFLinkLanes.front().myDistance <= link->getFoeVisibilityDistance();
    7676              :     }
    7677              :     return false;
    7678              : }
    7679              : 
    7680              : bool
    7681     21592940 : MSVehicle::isLeader(const MSLink* link, const MSVehicle* veh, const double gap) const {
    7682              :     assert(link->fromInternalLane());
    7683     21592940 :     if (veh == nullptr) {
    7684              :         return false;
    7685              :     }
    7686     21592940 :     if (!myLane->isInternal() || myLane->getEdge().getToJunction() != link->getJunction()) {
    7687              :         // if this vehicle is not yet on the junction, every vehicle is a leader
    7688              :         return true;
    7689              :     }
    7690      1984089 :     if (veh->getLaneChangeModel().hasBlueLight()) {
    7691              :         // blue light device automatically gets right of way
    7692              :         return true;
    7693              :     }
    7694      1983775 :     const MSLane* foeLane = veh->getLane();
    7695      1983775 :     if (foeLane->isInternal()) {
    7696      1486337 :         if (foeLane->getEdge().getFromJunction() == link->getJunction()) {
    7697      1465841 :             SUMOTime egoET = myJunctionConflictEntryTime;
    7698      1465841 :             SUMOTime foeET = veh->myJunctionEntryTime;
    7699              :             // check relationship between link and foeLane
    7700      1465841 :             if (foeLane->getNormalPredecessorLane() == link->getInternalLaneBefore()->getNormalPredecessorLane()) {
    7701              :                 // we are entering the junction from the same lane
    7702       496795 :                 egoET = myJunctionEntryTimeNeverYield;
    7703       496795 :                 foeET = veh->myJunctionEntryTimeNeverYield;
    7704       496795 :                 if (link->isExitLinkAfterInternalJunction() && link->getInternalLaneBefore()->getLogicalPredecessorLane()->getEntryLink()->isIndirect()) {
    7705        73850 :                     egoET = myJunctionConflictEntryTime;
    7706              :                 }
    7707              :             } else {
    7708       969046 :                 const MSLink* foeLink = foeLane->getIncomingLanes()[0].viaLink;
    7709       969046 :                 const MSJunctionLogic* logic = link->getJunction()->getLogic();
    7710              :                 assert(logic != nullptr);
    7711              :                 // determine who has right of way
    7712              :                 bool response; // ego response to foe
    7713              :                 bool response2; // foe response to ego
    7714              :                 // attempt 1: tlLinkState
    7715       969046 :                 const MSLink* entry = link->getCorrespondingEntryLink();
    7716       969046 :                 const MSLink* foeEntry = foeLink->getCorrespondingEntryLink();
    7717       969046 :                 if (entry->haveRed() || foeEntry->haveRed()) {
    7718              :                     // ensure that vehicles which are stuck on the intersection may exit
    7719       116985 :                     if (!foeEntry->haveRed() && veh->getSpeed() > SUMO_const_haltingSpeed && gap < 0) {
    7720              :                         // foe might be oncoming, don't drive unless foe can still brake safely
    7721        11722 :                         const double foeNextSpeed = veh->getSpeed() + ACCEL2SPEED(veh->getCarFollowModel().getMaxAccel());
    7722        11722 :                         const double foeBrakeGap = veh->getCarFollowModel().brakeGap(
    7723        11722 :                                                        foeNextSpeed, veh->getCarFollowModel().getMaxDecel(), veh->getCarFollowModel().getHeadwayTime());
    7724              :                         // the minGap was subtracted from gap in MSLink::getLeaderInfo (enlarging the negative gap)
    7725              :                         // so the -2* makes it point in the right direction
    7726        11722 :                         const double foeGap = -gap - veh->getLength() - 2 * getVehicleType().getMinGap();
    7727              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7728              :                         if (DEBUG_COND) {
    7729              :                             std::cout << " foeGap=" << foeGap << " foeBGap=" << foeBrakeGap << "\n";
    7730              : 
    7731              :                         }
    7732              : #endif
    7733        11722 :                         if (foeGap < foeBrakeGap) {
    7734              :                             response = true;
    7735              :                             response2 = false;
    7736              :                         } else {
    7737              :                             response = false;
    7738              :                             response2 = true;
    7739              :                         }
    7740              :                     } else {
    7741              :                         // let conflict entry time decide
    7742              :                         response = true;
    7743              :                         response2 = true;
    7744              :                     }
    7745       852061 :                 } else if (entry->havePriority() != foeEntry->havePriority()) {
    7746       642868 :                     response = !entry->havePriority();
    7747       642868 :                     response2 = !foeEntry->havePriority();
    7748       209193 :                 } else if (entry->haveYellow() && foeEntry->haveYellow()) {
    7749              :                     // let the faster vehicle keep moving
    7750         5720 :                     response = veh->getSpeed() >= getSpeed();
    7751         5720 :                     response2 = getSpeed() >= veh->getSpeed();
    7752              :                 } else {
    7753              :                     // fallback if pedestrian crossings are involved
    7754       203473 :                     response = logic->getResponseFor(link->getIndex()).test(foeLink->getIndex());
    7755       203473 :                     response2 = logic->getResponseFor(foeLink->getIndex()).test(link->getIndex());
    7756              :                 }
    7757              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7758              :                 if (DEBUG_COND) {
    7759              :                     std::cout << SIMTIME
    7760              :                               << " foeLane=" << foeLane->getID()
    7761              :                               << " foeLink=" << foeLink->getViaLaneOrLane()->getID()
    7762              :                               << " linkIndex=" << link->getIndex()
    7763              :                               << " foeLinkIndex=" << foeLink->getIndex()
    7764              :                               << " entryState=" << toString(entry->getState())
    7765              :                               << " entryState2=" << toString(foeEntry->getState())
    7766              :                               << " response=" << response
    7767              :                               << " response2=" << response2
    7768              :                               << "\n";
    7769              :                 }
    7770              : #endif
    7771       969046 :                 if (!response) {
    7772              :                     // if we have right of way over the foe, entryTime does not matter
    7773        82290 :                     foeET = veh->myJunctionConflictEntryTime;
    7774        82290 :                     egoET = myJunctionEntryTime;
    7775       886756 :                 } else if (response && response2) {
    7776              :                     // in a mutual conflict scenario, use entry time to avoid deadlock
    7777       128740 :                     foeET = veh->myJunctionConflictEntryTime;
    7778       128740 :                     egoET = myJunctionConflictEntryTime;
    7779              :                 }
    7780              :             }
    7781      1465841 :             if (egoET == foeET) {
    7782              :                 // try to use speed as tie braker
    7783       105570 :                 if (getSpeed() == veh->getSpeed()) {
    7784              :                     // use ID as tie braker
    7785              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7786              :                     if (DEBUG_COND) {
    7787              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7788              :                                   << " foeIsLeaderByID=" << (getID() < veh->getID()) << "\n";
    7789              :                     }
    7790              : #endif
    7791        55370 :                     return getID() < veh->getID();
    7792              :                 } else {
    7793              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7794              :                     if (DEBUG_COND) {
    7795              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7796              :                                   << " foeIsLeaderBySpeed=" << (getSpeed() < veh->getSpeed())
    7797              :                                   << " v=" << getSpeed() << " foeV=" << veh->getSpeed()
    7798              :                                   << "\n";
    7799              :                     }
    7800              : #endif
    7801        50200 :                     return getSpeed() < veh->getSpeed();
    7802              :                 }
    7803              :             } else {
    7804              :                 // leader was on the junction first
    7805              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7806              :                 if (DEBUG_COND) {
    7807              :                     std::cout << SIMTIME << " veh=" << getID() << " egoET " << egoET << " with foe " << veh->getID()
    7808              :                               << " foeET=" << foeET  << " isLeader=" << (egoET > foeET) << "\n";
    7809              :                 }
    7810              : #endif
    7811      1360271 :                 return egoET > foeET;
    7812              :             }
    7813              :         } else {
    7814              :             // vehicle can only be partially on the junction. Must be a leader
    7815              :             return true;
    7816              :         }
    7817              :     } else {
    7818              :         // vehicle can only be partially on the junction. Must be a leader
    7819              :         return true;
    7820              :     }
    7821              : }
    7822              : 
    7823              : void
    7824         2625 : MSVehicle::saveState(OutputDevice& out) {
    7825         2625 :     MSBaseVehicle::saveState(out);
    7826              :     // here starts the vehicle internal part (see loading)
    7827              :     std::vector<std::string> internals;
    7828         2625 :     internals.push_back(toString(myParameter->parametersSet));
    7829         2625 :     internals.push_back(toString(myDeparture));
    7830         2625 :     internals.push_back(toString(distance(myRoute->begin(), myCurrEdge)));
    7831         2625 :     internals.push_back(toString(myDepartPos));
    7832         2625 :     internals.push_back(toString(myWaitingTime));
    7833         2625 :     internals.push_back(toString(myTimeLoss));
    7834         2625 :     internals.push_back(toString(myLastActionTime));
    7835         2625 :     internals.push_back(toString(isStopped()));
    7836         2625 :     internals.push_back(toString(isStopped() ? myStops.front().duration : 0));
    7837         2625 :     internals.push_back(toString(myPastStops.size()));
    7838         2625 :     out.writeAttr(SUMO_ATTR_STATE, internals);
    7839         2625 :     out.writeAttr(SUMO_ATTR_POSITION, std::vector<double> { myState.myPos, myState.myBackPos, myState.myLastCoveredDist });
    7840         2625 :     out.writeAttr(SUMO_ATTR_SPEED, std::vector<double> { myState.mySpeed, myState.myPreviousSpeed });
    7841         2625 :     out.writeAttr(SUMO_ATTR_ANGLE, GeomHelper::naviDegree(myAngle));
    7842         2625 :     out.writeAttr(SUMO_ATTR_POSITION_LAT, myState.myPosLat);
    7843         2625 :     out.writeAttr(SUMO_ATTR_WAITINGTIME, myWaitingTimeCollector.getState());
    7844         2625 :     if (isStopped() && myStops.front().entryPos != getPositionOnLane()) {
    7845            1 :         out.writeAttr(SUMO_ATTR_ENTRYPOS, myStops.front().entryPos);
    7846              :     }
    7847         2625 :     myLaneChangeModel->saveState(out);
    7848              :     // save past stops
    7849         5704 :     for (SUMOVehicleParameter::Stop stop : myPastStops) {
    7850         3079 :         stop.write(out, false);
    7851              :         // do not write started and ended twice
    7852         3079 :         if ((stop.parametersSet & STOP_STARTED_SET) == 0) {
    7853         3074 :             out.writeAttr(SUMO_ATTR_STARTED, time2string(stop.started));
    7854              :         }
    7855         3079 :         if ((stop.parametersSet & STOP_ENDED_SET) == 0) {
    7856         3074 :             out.writeAttr(SUMO_ATTR_ENDED, time2string(stop.ended));
    7857              :         }
    7858         3079 :         stop.writeParams(out);
    7859         3079 :         out.closeTag();
    7860         3079 :     }
    7861              :     // save upcoming stops
    7862         3114 :     for (MSStop& stop : myStops) {
    7863          489 :         stop.write(out);
    7864              :     }
    7865              :     // save parameters and device states
    7866         2625 :     myParameter->writeParams(out);
    7867         6619 :     for (MSVehicleDevice* const dev : myDevices) {
    7868         3994 :         dev->saveState(out);
    7869              :     }
    7870         2625 :     if (myCFVariables != nullptr) {
    7871          110 :         myCFVariables->saveState(out, getCarFollowModel());
    7872              :     }
    7873         2625 :     out.closeTag();
    7874         2625 : }
    7875              : 
    7876              : void
    7877         3483 : MSVehicle::loadState(const SUMOSAXAttributes& attrs, const SUMOTime offset) {
    7878         3483 :     if (!attrs.hasAttribute(SUMO_ATTR_POSITION)) {
    7879            0 :         throw ProcessError(TL("Error: Invalid vehicles in state (may be a meso state)!"));
    7880              :     }
    7881              :     bool ok;
    7882              :     int routeOffset;
    7883              :     bool stopped;
    7884              :     SUMOTime stopDuration;
    7885              :     int pastStops;
    7886              : 
    7887         3483 :     std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
    7888         3483 :     bis >> myParameter->parametersSet;
    7889         3483 :     bis >> myDeparture;
    7890         3483 :     bis >> routeOffset;
    7891         3483 :     bis >> myDepartPos;
    7892         3483 :     bis >> myWaitingTime;
    7893         3483 :     bis >> myTimeLoss;
    7894         3483 :     bis >> myLastActionTime;
    7895              :     bis >> stopped;
    7896              :     bis >> stopDuration;
    7897         3483 :     bis >> pastStops;
    7898              : 
    7899         3483 :     if (attrs.hasAttribute(SUMO_ATTR_ARRIVALPOS_RANDOMIZED)) {
    7900            4 :         myArrivalPos = attrs.get<double>(SUMO_ATTR_ARRIVALPOS_RANDOMIZED, getID().c_str(), ok);
    7901              :     }
    7902              :     // load stops
    7903              :     myStops.clear();
    7904         3483 :     addStops(!MSGlobals::gCheckRoutes, &myCurrEdge, false);
    7905              : 
    7906         3483 :     if (hasDeparted()) {
    7907         1671 :         myCurrEdge = myRoute->begin() + routeOffset;
    7908         1671 :         myDeparture -= offset;
    7909              :         // fix stops
    7910         4726 :         while (pastStops > 0) {
    7911              :             SUMOVehicleParameter::Stop& pars = const_cast<SUMOVehicleParameter::Stop&>(myStops.front().pars);
    7912              :             // assumed these attributes were only added to restore vehroute-output.exit-times
    7913         3055 :             if (!MSGlobals::gUseStopEnded) {
    7914         3055 :                 pars.parametersSet &= ~STOP_ENDED_SET;
    7915              :             }
    7916         3055 :             if (!MSGlobals::gUseStopStarted) {
    7917         3055 :                 pars.parametersSet &= ~STOP_STARTED_SET;
    7918              :             }
    7919         6135 :             for (const auto& rem : myMoveReminders) {
    7920         3080 :                 rem.first->notifyStopEnded();
    7921              :             }
    7922         3055 :             myPastStops.push_back(myStops.front().pars);
    7923         3055 :             myPastStops.back().routeIndex = (int)(myStops.front().edge - myRoute->begin());
    7924         3055 :             myStops.pop_front();
    7925         3055 :             pastStops--;
    7926              :         }
    7927              :         // see MSBaseVehicle constructor
    7928         1671 :         if (myParameter->wasSet(VEHPARS_FORCE_REROUTE)) {
    7929         1147 :             calculateArrivalParams(true);
    7930              :         }
    7931              :         // a (tentative lane is needed for calling hasArrivedInternal
    7932         1671 :         myLane = (*myCurrEdge)->getLanes()[0];
    7933              :     }
    7934         3483 :     if (getActionStepLength() == DELTA_T && !isActionStep(SIMSTEP)) {
    7935            1 :         myLastActionTime -= (myLastActionTime - SIMSTEP) % DELTA_T;
    7936            3 :         WRITE_WARNINGF(TL("Action steps are out of sync for loaded vehicle '%'."), getID());
    7937              :     }
    7938         3483 :     std::istringstream pis(attrs.getString(SUMO_ATTR_POSITION));
    7939         3483 :     pis >> myState.myPos >> myState.myBackPos >> myState.myLastCoveredDist;
    7940         3483 :     std::istringstream sis(attrs.getString(SUMO_ATTR_SPEED));
    7941         3483 :     sis >> myState.mySpeed >> myState.myPreviousSpeed;
    7942         3483 :     myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7943         3483 :     myAngle = GeomHelper::fromNaviDegree(attrs.getFloat(SUMO_ATTR_ANGLE));
    7944         3483 :     myRawAngle = myAngle;
    7945         3483 :     myState.myPosLat = attrs.getFloat(SUMO_ATTR_POSITION_LAT);
    7946         3483 :     std::istringstream dis(attrs.getString(SUMO_ATTR_DISTANCE));
    7947         3483 :     dis >> myOdometer >> myNumberReroutes;
    7948         3483 :     myWaitingTimeCollector.setState(attrs.getString(SUMO_ATTR_WAITINGTIME));
    7949         3483 :     if (stopped) {
    7950          234 :         double realPos = getPositionOnLane();
    7951          234 :         double entryPos = attrs.getOpt<double>(SUMO_ATTR_ENTRYPOS, getID().c_str(), ok, realPos);
    7952          234 :         myStops.front().startedFromState = true;
    7953          234 :         if (entryPos != realPos) {
    7954            1 :             myStops.front().entryPos = entryPos;
    7955              :         }
    7956          234 :         myLane = const_cast<MSLane*>(myStops.front().lane);
    7957          234 :         myStopDist = 0;
    7958          234 :         myState.myPos = entryPos; // fake position for replication stop entry which happened before the position was updated
    7959          234 :         processNextStop(getSpeed());
    7960          234 :         myState.myPos = realPos; // reset fake position
    7961          234 :         if (myStops.front().pars.parking != ParkingType::ONROAD) {
    7962              :             // processNextStop is called again during MSVehicleTransfer::loadState
    7963          216 :             stopDuration += getActionStepLength();
    7964              :         }
    7965          234 :         myStops.front().duration = stopDuration;
    7966          234 :         if (!MSGlobals::gUseStopStarted) {
    7967              :             SUMOVehicleParameter::Stop& pars = const_cast<SUMOVehicleParameter::Stop&>(myStops.front().pars);
    7968          234 :             pars.parametersSet &= ~STOP_STARTED_SET;
    7969              :         }
    7970              :     }
    7971         3483 :     myLaneChangeModel->loadState(attrs);
    7972              :     // no need to reset myCachedPosition here since state loading happens directly after creation
    7973         3483 : }
    7974              : 
    7975              : void
    7976           32 : MSVehicle::loadPreviousApproaching(MSLink* link, bool setRequest,
    7977              :                                    SUMOTime arrivalTime, double arrivalSpeed,
    7978              :                                    double arrivalSpeedBraking,
    7979              :                                    double dist, double leaveSpeed) {
    7980              :     // ensure that approach information is reset on the next call to setApproachingForAllLinks
    7981           32 :     myLFLinkLanes.push_back(DriveProcessItem(link, 0, 0, setRequest,
    7982              :                             arrivalTime, arrivalSpeed, arrivalSpeedBraking, dist, leaveSpeed));
    7983              : 
    7984           32 : }
    7985              : 
    7986              : 
    7987              : std::shared_ptr<MSSimpleDriverState>
    7988      2565182 : MSVehicle::getDriverState() const {
    7989      2565182 :     return myDriverState->getDriverState();
    7990              : }
    7991              : 
    7992              : 
    7993              : double
    7994    627638502 : MSVehicle::getFriction() const {
    7995    627638502 :     return myFrictionDevice == nullptr ? 1. : myFrictionDevice->getMeasuredFriction();
    7996              : }
    7997              : 
    7998              : 
    7999              : void
    8000          196 : MSVehicle::setPreviousSpeed(double prevSpeed, double prevAcceleration) {
    8001          196 :     myState.mySpeed = MAX2(0., prevSpeed);
    8002              :     // also retcon acceleration
    8003          196 :     if (prevAcceleration != std::numeric_limits<double>::min()) {
    8004            8 :         myAcceleration = prevAcceleration;
    8005              :     } else {
    8006          188 :         myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    8007              :     }
    8008          196 : }
    8009              : 
    8010              : 
    8011              : double
    8012   1910676333 : MSVehicle::getCurrentApparentDecel() const {
    8013              :     //return MAX2(-myAcceleration, getCarFollowModel().getApparentDecel());
    8014   1910676333 :     return getCarFollowModel().getApparentDecel();
    8015              : }
    8016              : 
    8017              : /****************************************************************************/
    8018              : bool
    8019           32 : MSVehicle::setExitManoeuvre() {
    8020           32 :     return (myManoeuvre.configureExitManoeuvre(this));
    8021              : }
    8022              : 
    8023              : /* -------------------------------------------------------------------------
    8024              :  * methods of MSVehicle::manoeuvre
    8025              :  * ----------------------------------------------------------------------- */
    8026              : 
    8027      4534083 : MSVehicle::Manoeuvre::Manoeuvre() : myManoeuvreStop(""), myManoeuvreStartTime(0), myManoeuvreCompleteTime(0), myManoeuvreType(MSVehicle::MANOEUVRE_NONE), myGUIIncrement(0) {}
    8028              : 
    8029              : 
    8030            0 : MSVehicle::Manoeuvre::Manoeuvre(const Manoeuvre& manoeuvre) {
    8031            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    8032            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    8033            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    8034            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    8035            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    8036            0 : }
    8037              : 
    8038              : 
    8039              : MSVehicle::Manoeuvre&
    8040            0 : MSVehicle::Manoeuvre::operator=(const Manoeuvre& manoeuvre) {
    8041            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    8042            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    8043            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    8044            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    8045            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    8046            0 :     return *this;
    8047              : }
    8048              : 
    8049              : 
    8050              : bool
    8051            0 : MSVehicle::Manoeuvre::operator!=(const Manoeuvre& manoeuvre) {
    8052            0 :     return (myManoeuvreStop != manoeuvre.myManoeuvreStop ||
    8053            0 :             myManoeuvreStartTime != manoeuvre.myManoeuvreStartTime ||
    8054            0 :             myManoeuvreCompleteTime != manoeuvre.myManoeuvreCompleteTime ||
    8055            0 :             myManoeuvreType != manoeuvre.myManoeuvreType ||
    8056            0 :             myGUIIncrement != manoeuvre.myGUIIncrement
    8057            0 :            );
    8058              : }
    8059              : 
    8060              : 
    8061              : double
    8062          450 : MSVehicle::Manoeuvre::getGUIIncrement() const {
    8063          450 :     return (myGUIIncrement);
    8064              : }
    8065              : 
    8066              : 
    8067              : MSVehicle::ManoeuvreType
    8068         2971 : MSVehicle::Manoeuvre::getManoeuvreType() const {
    8069         2971 :     return (myManoeuvreType);
    8070              : }
    8071              : 
    8072              : 
    8073              : MSVehicle::ManoeuvreType
    8074         2971 : MSVehicle::getManoeuvreType() const {
    8075         2971 :     return (myManoeuvre.getManoeuvreType());
    8076              : }
    8077              : 
    8078              : 
    8079              : void
    8080           30 : MSVehicle::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    8081           30 :     myManoeuvre.setManoeuvreType(mType);
    8082           30 : }
    8083              : 
    8084              : 
    8085              : void
    8086           30 : MSVehicle::Manoeuvre::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    8087           30 :     myManoeuvreType = mType;
    8088           30 : }
    8089              : 
    8090              : 
    8091              : bool
    8092           30 : MSVehicle::Manoeuvre::configureEntryManoeuvre(MSVehicle* veh) {
    8093           30 :     if (!veh->hasStops()) {
    8094              :         return false;    // should never happen - checked before call
    8095              :     }
    8096              : 
    8097           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    8098           30 :     const MSStop& stop = veh->getNextStop();
    8099              : 
    8100           30 :     int manoeuverAngle = stop.parkingarea->getLastFreeLotAngle();
    8101           30 :     double GUIAngle = stop.parkingarea->getLastFreeLotGUIAngle();
    8102           30 :     if (abs(GUIAngle) < 0.1) {
    8103              :         GUIAngle = -0.1;    // Wiggle vehicle on parallel entry
    8104              :     }
    8105           30 :     myManoeuvreVehicleID = veh->getID();
    8106           30 :     myManoeuvreStop = stop.parkingarea->getID();
    8107           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_ENTRY;
    8108           30 :     myManoeuvreStartTime = currentTime;
    8109           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getEntryManoeuvreTime(manoeuverAngle);
    8110           30 :     myGUIIncrement = GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    8111              : 
    8112              : #ifdef DEBUG_STOPS
    8113              :     if (veh->isSelected()) {
    8114              :         std::cout << "ENTRY manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle << " Rotation angle=" << RAD2DEG(GUIAngle) << " Road Angle" << RAD2DEG(veh->getAngle()) << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime <<
    8115              :                   " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    8116              :     }
    8117              : #endif
    8118              : 
    8119           30 :     return (true);
    8120              : }
    8121              : 
    8122              : 
    8123              : bool
    8124           32 : MSVehicle::Manoeuvre::configureExitManoeuvre(MSVehicle* veh) {
    8125              :     // At the moment we only want to set for parking areas
    8126           32 :     if (!veh->hasStops()) {
    8127              :         return true;
    8128              :     }
    8129           32 :     if (veh->getNextStop().parkingarea == nullptr) {
    8130              :         return true;
    8131              :     }
    8132              : 
    8133           30 :     if (myManoeuvreType != MSVehicle::MANOEUVRE_NONE) {
    8134              :         return (false);
    8135              :     }
    8136              : 
    8137           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    8138              : 
    8139           30 :     int manoeuverAngle = veh->getCurrentParkingArea()->getManoeuverAngle(*veh);
    8140           30 :     double GUIAngle = veh->getCurrentParkingArea()->getGUIAngle(*veh);
    8141           30 :     if (abs(GUIAngle) < 0.1) {
    8142              :         GUIAngle = 0.1;    // Wiggle vehicle on parallel exit
    8143              :     }
    8144              : 
    8145           30 :     myManoeuvreVehicleID = veh->getID();
    8146           30 :     myManoeuvreStop = veh->getCurrentParkingArea()->getID();
    8147           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_EXIT;
    8148           30 :     myManoeuvreStartTime = currentTime;
    8149           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getExitManoeuvreTime(manoeuverAngle);
    8150           30 :     myGUIIncrement = -GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    8151           30 :     if (veh->remainingStopDuration() > 0) {
    8152           20 :         myManoeuvreCompleteTime += veh->remainingStopDuration();
    8153              :     }
    8154              : 
    8155              : #ifdef DEBUG_STOPS
    8156              :     if (veh->isSelected()) {
    8157              :         std::cout << "EXIT manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle  << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime
    8158              :                   << " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    8159              :     }
    8160              : #endif
    8161              : 
    8162              :     return (true);
    8163              : }
    8164              : 
    8165              : 
    8166              : bool
    8167          222 : MSVehicle::Manoeuvre::entryManoeuvreIsComplete(MSVehicle* veh) {
    8168              :     // At the moment we only want to consider parking areas - need to check because we could be setting up a manoeuvre
    8169          222 :     if (!veh->hasStops()) {
    8170              :         return (true);
    8171              :     }
    8172              :     MSStop* currentStop = &veh->myStops.front();
    8173          222 :     if (currentStop->parkingarea == nullptr) {
    8174              :         return true;
    8175          220 :     } else if (currentStop->parkingarea->getID() != myManoeuvreStop || MSVehicle::MANOEUVRE_ENTRY != myManoeuvreType) {
    8176           30 :         if (configureEntryManoeuvre(veh)) {
    8177           30 :             MSNet::getInstance()->informVehicleStateListener(veh, MSNet::VehicleState::MANEUVERING);
    8178           30 :             return (false);
    8179              :         } else { // cannot configure entry so stop trying
    8180              :             return true;
    8181              :         }
    8182          190 :     } else if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8183              :         return false;
    8184              :     } else { // manoeuvre complete
    8185           30 :         myManoeuvreType = MSVehicle::MANOEUVRE_NONE;
    8186           30 :         return true;
    8187              :     }
    8188              : }
    8189              : 
    8190              : 
    8191              : bool
    8192            0 : MSVehicle::Manoeuvre::manoeuvreIsComplete(const ManoeuvreType checkType) const {
    8193            0 :     if (checkType != myManoeuvreType) {
    8194              :         return true;    // we're not maneuvering / wrong manoeuvre
    8195              :     }
    8196              : 
    8197            0 :     if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8198              :         return false;
    8199              :     } else {
    8200              :         return true;
    8201              :     }
    8202              : }
    8203              : 
    8204              : 
    8205              : bool
    8206         6266 : MSVehicle::Manoeuvre::manoeuvreIsComplete() const {
    8207         6266 :     return (MSNet::getInstance()->getCurrentTimeStep() >= myManoeuvreCompleteTime);
    8208              : }
    8209              : 
    8210              : 
    8211              : bool
    8212         6266 : MSVehicle::manoeuvreIsComplete() const {
    8213         6266 :     return (myManoeuvre.manoeuvreIsComplete());
    8214              : }
    8215              : 
    8216              : 
    8217              : std::pair<double, double>
    8218         7440 : MSVehicle::estimateTimeToNextStop() const {
    8219         7440 :     if (hasStops()) {
    8220         7440 :         MSLane* lane = myLane;
    8221         7440 :         if (lane == nullptr) {
    8222              :             // not in network
    8223           84 :             lane = getEdge()->getLanes()[0];
    8224              :         }
    8225              :         const MSStop& stop = myStops.front();
    8226              :         auto it = myCurrEdge + 1;
    8227              :         // drive to end of current edge
    8228         7440 :         double dist = (lane->getLength() - getPositionOnLane());
    8229         7440 :         double travelTime = lane->getEdge().getMinimumTravelTime(this) * dist / lane->getLength();
    8230              :         // drive until stop edge
    8231         8804 :         while (it != myRoute->end() && it < stop.edge) {
    8232         1364 :             travelTime += (*it)->getMinimumTravelTime(this);
    8233         1364 :             dist += (*it)->getLength();
    8234              :             it++;
    8235              :         }
    8236              :         // drive up to the stop position
    8237         7440 :         const double stopEdgeDist = stop.pars.endPos - (lane == stop.lane ? lane->getLength() : 0);
    8238         7440 :         dist += stopEdgeDist;
    8239         7440 :         travelTime += stop.lane->getEdge().getMinimumTravelTime(this) * (stopEdgeDist / stop.lane->getLength());
    8240              :         // estimate time loss due to acceleration and deceleration
    8241              :         // maximum speed is limited by available distance:
    8242              :         const double a = getCarFollowModel().getMaxAccel();
    8243              :         const double b = getCarFollowModel().getMaxDecel();
    8244         7440 :         const double c = getSpeed();
    8245              :         const double d = dist;
    8246         7440 :         const double len = getVehicleType().getLength();
    8247         7440 :         const double vs = MIN2(MAX2(stop.getSpeed(), 0.0), stop.lane->getVehicleMaxSpeed(this));
    8248              :         // distAccel = (v - c)^2 / (2a)
    8249              :         // distDecel = (v + vs)*(v - vs) / 2b = (v^2 - vs^2) / (2b)
    8250              :         // distAccel + distDecel < d
    8251         7440 :         const double maxVD = MAX2(c, ((sqrt(MAX2(0.0, pow(2 * c * b, 2) + (4 * ((b * ((a * (2 * d * (b + a) + (vs * vs) - (c * c))) - (b * (c * c))))
    8252        14592 :                                             + pow((a * vs), 2))))) * 0.5) + (c * b)) / (b + a));
    8253         7440 :         it = myCurrEdge;
    8254              :         double v0 = c;
    8255         7440 :         bool v0Stable = getAcceleration() == 0 && v0 > 0;
    8256              :         double timeLossAccel = 0;
    8257              :         double timeLossDecel = 0;
    8258              :         double timeLossLength = 0;
    8259        17742 :         while (it != myRoute->end() && it <= stop.edge) {
    8260        10302 :             double v = MIN2(maxVD, (*it)->getVehicleMaxSpeed(this));
    8261        10302 :             double edgeLength = (it == stop.edge ? stop.pars.endPos : (*it)->getLength()) - (it == myCurrEdge ? getPositionOnLane() : 0);
    8262        10302 :             if (edgeLength <= len && v0Stable && v0 < v) {
    8263              :                 const double lengthDist = MIN2(len, edgeLength);
    8264           20 :                 const double dTL = lengthDist / v0 - lengthDist / v;
    8265              :                 //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " el=" << edgeLength << " lDist=" << lengthDist << " newTLL=" << dTL<< "\n";
    8266           20 :                 timeLossLength += dTL;
    8267              :             }
    8268        10302 :             if (edgeLength > len) {
    8269         9166 :                 const double dv = v - v0;
    8270         9166 :                 if (dv > 0) {
    8271              :                     // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8272         6504 :                     const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8273              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8274         6504 :                     timeLossAccel += dTA;
    8275              :                     // time loss from vehicle length
    8276         2662 :                 } else if (dv < 0) {
    8277              :                     // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8278          540 :                     const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8279              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8280          540 :                     timeLossDecel += dTD;
    8281              :                 }
    8282              :                 v0 = v;
    8283              :                 v0Stable = true;
    8284              :             }
    8285              :             it++;
    8286              :         }
    8287              :         // final deceleration to stop (may also be acceleration or deceleration to waypoint speed)
    8288              :         double v = vs;
    8289         7440 :         const double dv = v - v0;
    8290         7440 :         if (dv > 0) {
    8291              :             // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8292          144 :             const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8293              :             //std::cout << "  final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8294          144 :             timeLossAccel += dTA;
    8295              :             // time loss from vehicle length
    8296         7296 :         } else if (dv < 0) {
    8297              :             // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8298         7268 :             const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8299              :             //std::cout << "  final  e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8300         7268 :             timeLossDecel += dTD;
    8301              :         }
    8302         7440 :         const double result = travelTime + timeLossAccel + timeLossDecel + timeLossLength;
    8303              :         //std::cout << SIMTIME << " v=" << c << " a=" << a << " b=" << b << " maxVD=" << maxVD << " tt=" << travelTime
    8304              :         //    << " ta=" << timeLossAccel << " td=" << timeLossDecel << " tl=" << timeLossLength << " res=" << result << "\n";
    8305         7440 :         return {MAX2(0.0, result), dist};
    8306              :     } else {
    8307            0 :         return {INVALID_DOUBLE, INVALID_DOUBLE};
    8308              :     }
    8309              : }
    8310              : 
    8311              : 
    8312              : double
    8313         2457 : MSVehicle::getStopDelay() const {
    8314         2457 :     if (hasStops() && myStops.front().pars.until >= 0) {
    8315              :         const MSStop& stop = myStops.front();
    8316         1612 :         SUMOTime estimatedDepart = MSNet::getInstance()->getCurrentTimeStep() - DELTA_T;
    8317         1612 :         if (stop.reached) {
    8318          802 :             return STEPS2TIME(estimatedDepart + stop.duration - stop.pars.until);
    8319              :         }
    8320          810 :         if (stop.pars.duration > 0) {
    8321          608 :             estimatedDepart += stop.pars.duration;
    8322              :         }
    8323          810 :         estimatedDepart += TIME2STEPS(estimateTimeToNextStop().first);
    8324          810 :         const double result = MAX2(0.0, STEPS2TIME(estimatedDepart - stop.pars.until));
    8325          810 :         return result;
    8326              :     } else {
    8327              :         // vehicles cannot drive before 'until' so stop delay can never be
    8328              :         // negative and we can use -1 to signal "undefined"
    8329              :         return -1;
    8330              :     }
    8331              : }
    8332              : 
    8333              : 
    8334              : double
    8335         5510 : MSVehicle::getStopArrivalDelay() const {
    8336         5510 :     if (hasStops() && myStops.front().pars.arrival >= 0) {
    8337              :         const MSStop& stop = myStops.front();
    8338         4334 :         if (stop.reached) {
    8339         1304 :             return STEPS2TIME(stop.pars.started - stop.pars.arrival);
    8340              :         } else {
    8341         3030 :             return STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) + estimateTimeToNextStop().first - STEPS2TIME(stop.pars.arrival);
    8342              :         }
    8343              :     } else {
    8344              :         // vehicles can arrive earlier than planned so arrival delay can be negative
    8345              :         return INVALID_DOUBLE;
    8346              :     }
    8347              : }
    8348              : 
    8349              : 
    8350              : const MSEdge*
    8351   3135807465 : MSVehicle::getCurrentEdge() const {
    8352   3135807465 :     return myLane != nullptr ? &myLane->getEdge() : getEdge();
    8353              : }
    8354              : 
    8355              : 
    8356              : const MSEdge*
    8357         3932 : MSVehicle::getNextEdgePtr() const {
    8358         3932 :     if (myLane == nullptr || (myCurrEdge + 1) == myRoute->end()) {
    8359            8 :         return nullptr;
    8360              :     }
    8361         3924 :     if (myLane->isInternal()) {
    8362          568 :         return &myLane->getCanonicalSuccessorLane()->getEdge();
    8363              :     } else {
    8364         3356 :         const MSEdge* nextNormal = succEdge(1);
    8365         3356 :         const MSEdge* nextInternal = myLane->getEdge().getInternalFollowingEdge(nextNormal, getVClass());
    8366         3356 :         return nextInternal ? nextInternal : nextNormal;
    8367              :     }
    8368              : }
    8369              : 
    8370              : 
    8371              : const MSLane*
    8372         1602 : MSVehicle::getPreviousLane(const MSLane* current, int& furtherIndex) const {
    8373         1602 :     if (furtherIndex < (int)myFurtherLanes.size()) {
    8374         1225 :         return myFurtherLanes[furtherIndex++];
    8375              :     } else {
    8376              :         // try to use route information
    8377          377 :         int routeIndex = getRoutePosition();
    8378              :         bool resultInternal;
    8379          377 :         if (MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()) {
    8380            0 :             if (myLane->isInternal()) {
    8381            0 :                 if (furtherIndex % 2 == 0) {
    8382            0 :                     routeIndex -= (furtherIndex + 0) / 2;
    8383              :                     resultInternal = false;
    8384              :                 } else {
    8385            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8386              :                     resultInternal = false;
    8387              :                 }
    8388              :             } else {
    8389            0 :                 if (furtherIndex % 2 != 0) {
    8390            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8391              :                     resultInternal = false;
    8392              :                 } else {
    8393            0 :                     routeIndex -= (furtherIndex + 2) / 2;
    8394              :                     resultInternal = true;
    8395              :                 }
    8396              :             }
    8397              :         } else {
    8398          377 :             routeIndex -= furtherIndex;
    8399              :             resultInternal = false;
    8400              :         }
    8401          377 :         furtherIndex++;
    8402          377 :         if (routeIndex >= 0) {
    8403          163 :             if (resultInternal) {
    8404            0 :                 const MSEdge* prevNormal = myRoute->getEdges()[routeIndex];
    8405            0 :                 for (MSLane* cand : prevNormal->getLanes()) {
    8406            0 :                     for (MSLink* link : cand->getLinkCont()) {
    8407            0 :                         if (link->getLane() == current) {
    8408            0 :                             if (link->getViaLane() != nullptr) {
    8409              :                                 return link->getViaLane();
    8410              :                             } else {
    8411            0 :                                 return const_cast<MSLane*>(link->getLaneBefore());
    8412              :                             }
    8413              :                         }
    8414              :                     }
    8415              :                 }
    8416              :             } else {
    8417          163 :                 return myRoute->getEdges()[routeIndex]->getLanes()[0];
    8418              :             }
    8419              :         }
    8420              :     }
    8421              :     return current;
    8422              : }
    8423              : 
    8424              : SUMOTime
    8425   1547622944 : MSVehicle::getWaitingTimeFor(const MSLink* link) const {
    8426              :     // this vehicle currently has the highest priority on the allway_stop
    8427   1547622944 :     return link == myHaveStoppedFor ? SUMOTime_MAX : getWaitingTime();
    8428              : }
    8429              : 
    8430              : 
    8431              : void
    8432          694 : MSVehicle::resetApproachOnReroute() {
    8433              :     bool diverged = false;
    8434              :     const ConstMSEdgeVector& route = myRoute->getEdges();
    8435          694 :     int ri = getRoutePosition();
    8436         2928 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    8437         2234 :         if (dpi.myLink != nullptr) {
    8438         2231 :             if (!diverged) {
    8439         2000 :                 const MSEdge* next = route[ri + 1];
    8440         2000 :                 if (&dpi.myLink->getLane()->getEdge() != next) {
    8441              :                     diverged = true;
    8442              :                 } else {
    8443         1935 :                     if (dpi.myLink->getViaLane() == nullptr) {
    8444              :                         ri++;
    8445              :                     }
    8446              :                 }
    8447              :             }
    8448              :             if (diverged) {
    8449          296 :                 dpi.myLink->removeApproaching(this);
    8450              :             }
    8451              :         }
    8452              :     }
    8453          694 : }
    8454              : 
    8455              : 
    8456              : bool
    8457     14860139 : MSVehicle::instantStopping() const {
    8458     14860139 :     return myInfluencer && !myInfluencer->considerMaxDeceleration();
    8459              : }
    8460              : 
    8461              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1