LCOV - code coverage report
Current view: top level - src/microsim - MSVehicle.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 96.3 % 3377 3252
Test Date: 2026-07-05 15:55:58 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      3546004 : MSVehicle::State::operator=(const State& state) {
     153      3546004 :     myPos   = state.myPos;
     154      3546004 :     mySpeed = state.mySpeed;
     155      3546004 :     myPosLat   = state.myPosLat;
     156      3546004 :     myBackPos = state.myBackPos;
     157      3546004 :     myPreviousSpeed = state.myPreviousSpeed;
     158      3546004 :     myLastCoveredDist = state.myLastCoveredDist;
     159      3546004 :     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      8066494 : MSVehicle::State::State(double pos, double speed, double posLat, double backPos, double previousSpeed) :
     175      8066494 :     myPos(pos), mySpeed(speed), myPosLat(posLat), myBackPos(backPos), myPreviousSpeed(previousSpeed), myLastCoveredDist(SPEED2DIST(speed)) {}
     176              : 
     177              : 
     178              : 
     179              : /* -------------------------------------------------------------------------
     180              :  * methods of MSVehicle::WaitingTimeCollector
     181              :  * ----------------------------------------------------------------------- */
     182      4520490 : 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    700873226 : MSVehicle::WaitingTimeCollector::passTime(SUMOTime dt, bool waiting) {
     209              :     auto i = myWaitingIntervals.begin();
     210              :     const auto end = myWaitingIntervals.end();
     211    700873226 :     const bool startNewInterval = i == end || (i->first != 0);
     212   1144316993 :     while (i != end) {
     213    445722252 :         i->first += dt;
     214    445722252 :         if (i->first >= myMemorySize) {
     215              :             break;
     216              :         }
     217    443443767 :         i->second += dt;
     218              :         i++;
     219              :     }
     220              : 
     221              :     // remove intervals beyond memorySize
     222              :     auto d = std::distance(i, end);
     223    703151711 :     while (d > 0) {
     224      2278485 :         myWaitingIntervals.pop_back();
     225      2278485 :         d--;
     226              :     }
     227              : 
     228    700873226 :     if (!waiting) {
     229              :         return;
     230     91590790 :     } else if (!startNewInterval) {
     231     87940062 :         myWaitingIntervals.begin()->first = 0;
     232              :     } else {
     233      7301456 :         myWaitingIntervals.push_front(std::make_pair(0, dt));
     234              :     }
     235              :     return;
     236              : }
     237              : 
     238              : 
     239              : const std::string
     240         2623 : MSVehicle::WaitingTimeCollector::getState() const {
     241         2623 :     std::ostringstream state;
     242         2623 :     state << myMemorySize << " " << myWaitingIntervals.size();
     243         3543 :     for (const auto& interval : myWaitingIntervals) {
     244         1840 :         state << " " << interval.first << " " << interval.second;
     245              :     }
     246         2623 :     return state.str();
     247         2623 : }
     248              : 
     249              : 
     250              : void
     251         3480 : MSVehicle::WaitingTimeCollector::setState(const std::string& state) {
     252         3480 :     std::istringstream is(state);
     253              :     int numIntervals;
     254              :     SUMOTime begin, end;
     255         3480 :     is >> myMemorySize >> numIntervals;
     256         5180 :     while (numIntervals-- > 0) {
     257              :         is >> begin >> end;
     258         1700 :         myWaitingIntervals.emplace_back(begin, end);
     259              :     }
     260         3480 : }
     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           57 : MSVehicle::Influencer::GapControlState::GapControlState() :
     295           57 :     tauOriginal(-1), tauCurrent(-1), tauTarget(-1), addGapCurrent(-1), addGapTarget(-1),
     296           57 :     remainingDuration(-1), changeRate(-1), maxDecel(-1), referenceVeh(nullptr), active(false), gapAttained(false), prevLeader(nullptr),
     297           57 :     lastUpdate(-1), timeHeadwayIncrement(0.0), spaceHeadwayIncrement(0.0) {}
     298              : 
     299              : 
     300           57 : MSVehicle::Influencer::GapControlState::~GapControlState() {
     301           57 :     deactivate();
     302           57 : }
     303              : 
     304              : void
     305           57 : MSVehicle::Influencer::GapControlState::init() {
     306           57 :     if (MSNet::hasInstance()) {
     307           57 :         if (myVehStateListener == nullptr) {
     308              :             //std::cout << "GapControlState::init()" << std::endl;
     309           57 :             myVehStateListener = new GapControlVehStateListener();
     310           57 :             MSNet::getInstance()->addVehicleStateListener(myVehStateListener);
     311              :         }
     312              :     } else {
     313            0 :         WRITE_ERROR("MSVehicle::Influencer::GapControlState::init(): No MSNet instance found!")
     314              :     }
     315           57 : }
     316              : 
     317              : void
     318        35227 : MSVehicle::Influencer::GapControlState::cleanup() {
     319        35227 :     if (myVehStateListener != nullptr) {
     320           57 :         MSNet::getInstance()->removeVehicleStateListener(myVehStateListener);
     321           57 :         delete myVehStateListener;
     322           57 :         myVehStateListener = nullptr;
     323              :     }
     324        35227 : }
     325              : 
     326              : void
     327           57 : MSVehicle::Influencer::GapControlState::activate(double tauOrig, double tauNew, double additionalGap, double dur, double rate, double decel, const MSVehicle* refVeh) {
     328           57 :     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           57 :         tauOriginal = tauOrig;
     334           57 :         tauCurrent = tauOrig;
     335           57 :         tauTarget = tauNew;
     336           57 :         addGapCurrent = 0.0;
     337           57 :         addGapTarget = additionalGap;
     338           57 :         remainingDuration = dur;
     339           57 :         changeRate = rate;
     340           57 :         maxDecel = decel;
     341           57 :         referenceVeh = refVeh;
     342           57 :         active = true;
     343           57 :         gapAttained = false;
     344           57 :         prevLeader = nullptr;
     345           57 :         lastUpdate = SIMSTEP - DELTA_T;
     346           57 :         timeHeadwayIncrement = changeRate * TS * (tauTarget - tauOriginal);
     347           57 :         spaceHeadwayIncrement = changeRate * TS * addGapTarget;
     348              : 
     349           57 :         if (referenceVeh != nullptr) {
     350              :             // Add refVeh to refVehMap
     351           11 :             GapControlState::refVehMap[referenceVeh] = this;
     352              :         }
     353              :     }
     354           57 : }
     355              : 
     356              : void
     357          114 : MSVehicle::Influencer::GapControlState::deactivate() {
     358          114 :     active = false;
     359          114 :     if (referenceVeh != nullptr) {
     360              :         // Remove corresponding refVehMapEntry if appropriate
     361           11 :         GapControlState::refVehMap.erase(referenceVeh);
     362           11 :         referenceVeh = nullptr;
     363              :     }
     364          114 : }
     365              : 
     366              : 
     367              : /* -------------------------------------------------------------------------
     368              :  * methods of MSVehicle::Influencer
     369              :  * ----------------------------------------------------------------------- */
     370         3473 : MSVehicle::Influencer::Influencer() :
     371              :     myGapControlState(nullptr),
     372         3473 :     myOriginalSpeed(-1),
     373         3473 :     myLatDist(0),
     374         3473 :     mySpeedAdaptationStarted(true),
     375         3473 :     myConsiderSafeVelocity(true),
     376         3473 :     myConsiderSpeedLimit(true),
     377         3473 :     myConsiderMaxAcceleration(true),
     378         3473 :     myConsiderMaxDeceleration(true),
     379         3473 :     myRespectJunctionPriority(true),
     380         3473 :     myEmergencyBrakeRedLight(true),
     381         3473 :     myRespectJunctionLeaderPriority(true),
     382         3473 :     myLastRemoteAccess(-TIME2STEPS(20)),
     383         3473 :     myStrategicLC(LC_NOCONFLICT),
     384         3473 :     myCooperativeLC(LC_NOCONFLICT),
     385         3473 :     mySpeedGainLC(LC_NOCONFLICT),
     386         3473 :     myRightDriveLC(LC_NOCONFLICT),
     387         3473 :     mySublaneLC(LC_NOCONFLICT),
     388         3473 :     myTraciLaneChangePriority(LCP_URGENT),
     389         3473 :     myTraCISignals(-1)
     390         3473 : {}
     391              : 
     392              : 
     393        10419 : MSVehicle::Influencer::~Influencer() {}
     394              : 
     395              : void
     396           57 : MSVehicle::Influencer::init() {
     397           57 :     GapControlState::init();
     398           57 : }
     399              : 
     400              : void
     401        35227 : MSVehicle::Influencer::cleanup() {
     402        35227 :     GapControlState::cleanup();
     403        35227 : }
     404              : 
     405              : void
     406        43337 : MSVehicle::Influencer::setSpeedTimeLine(const std::vector<std::pair<SUMOTime, double> >& speedTimeLine) {
     407        43337 :     mySpeedAdaptationStarted = true;
     408        43337 :     mySpeedTimeLine = speedTimeLine;
     409        43337 : }
     410              : 
     411              : void
     412           57 : MSVehicle::Influencer::activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle* refVeh) {
     413           57 :     if (myGapControlState == nullptr) {
     414           57 :         myGapControlState = std::make_shared<GapControlState>();
     415           57 :         init(); // only does things on first call
     416              :     }
     417           57 :     myGapControlState->activate(originalTau, newTimeHeadway, newSpaceHeadway, duration, changeRate, maxDecel, refVeh);
     418           57 : }
     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         7798 : MSVehicle::Influencer::setLaneTimeLine(const std::vector<std::pair<SUMOTime, int> >& laneTimeLine) {
     429         7798 :     myLaneTimeLine = laneTimeLine;
     430         7798 : }
     431              : 
     432              : 
     433              : void
     434         9034 : MSVehicle::Influencer::adaptLaneTimeLine(int indexShift) {
     435        19192 :     for (auto& item : myLaneTimeLine) {
     436        10158 :         item.second += indexShift;
     437              :     }
     438         9034 : }
     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       987935 : MSVehicle::Influencer::influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax) {
     494              :     // remove leading commands which are no longer valid
     495       989285 :     while (mySpeedTimeLine.size() == 1 || (mySpeedTimeLine.size() > 1 && currentTime > mySpeedTimeLine[1].first)) {
     496              :         mySpeedTimeLine.erase(mySpeedTimeLine.begin());
     497              :     }
     498              : 
     499       987935 :     if (!(mySpeedTimeLine.size() < 2 || currentTime < mySpeedTimeLine[0].first)) {
     500              :         // Speed advice is active -> compute new speed according to speedTimeLine
     501        53374 :         if (!mySpeedAdaptationStarted) {
     502            0 :             mySpeedTimeLine[0].second = speed;
     503            0 :             mySpeedAdaptationStarted = true;
     504              :         }
     505        53374 :         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       106389 :         const double td = MIN2(1.0, STEPS2TIME(currentTime - mySpeedTimeLine[0].first) / MAX2(TS, STEPS2TIME(mySpeedTimeLine[1].first - mySpeedTimeLine[0].first)));
     507              : 
     508        53374 :         speed = mySpeedTimeLine[0].second - (mySpeedTimeLine[0].second - mySpeedTimeLine[1].second) * td;
     509        53374 :         if (myConsiderSafeVelocity) {
     510              :             speed = MIN2(speed, vSafe);
     511              :         }
     512        53374 :         if (myConsiderMaxAcceleration) {
     513              :             speed = MIN2(speed, vMax);
     514              :         }
     515        53374 :         if (myConsiderMaxDeceleration) {
     516              :             speed = MAX2(speed, vMin);
     517              :         }
     518              :     }
     519       987935 :     return speed;
     520              : }
     521              : 
     522              : double
     523       491573 : 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       491573 :     if (myGapControlState != nullptr && myGapControlState->active) {
     535              :         // Determine leader and the speed that would be chosen by the gap controller
     536         7723 :         const double currentSpeed = veh->getSpeed();
     537         7723 :         const MSVehicle* msVeh = dynamic_cast<const MSVehicle*>(veh);
     538              :         assert(msVeh != nullptr);
     539         7723 :         const double desiredTargetTimeSpacing = myGapControlState->tauTarget * currentSpeed;
     540              :         std::pair<const MSVehicle*, double> leaderInfo;
     541         7723 :         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          383 :             double dist = msVeh->getDistanceToPosition(leader->getPositionOnLane(), leader->getLane()) - leader->getLength();
     554          383 :             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          383 :             leaderInfo = std::make_pair(leader, dist - msVeh->getVehicleType().getMinGap());
     570              :         }
     571         7723 :         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         7723 :         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         7723 :             myGapControlState->prevLeader = leaderInfo.first;
     594              : 
     595              :             // Calculate desired following speed assuming the alternative headway time
     596         7723 :             MSCFModel* cfm = (MSCFModel*) & (msVeh->getVehicleType().getCarFollowModel());
     597         7723 :             const double origTau = cfm->getHeadwayTime();
     598         7723 :             cfm->setHeadwayTime(myGapControlState->tauCurrent);
     599         7723 :             gapControlSpeed = MIN2(gapControlSpeed,
     600         7723 :                                    cfm->followSpeed(msVeh, currentSpeed, fakeDist, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first));
     601         7723 :             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         7723 :             if (myGapControlState->maxDecel > 0) {
     612         2519 :                 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         7723 :         if (myGapControlState->lastUpdate < currentTime) {
     620              : #ifdef DEBUG_TRACI
     621              :             if DEBUG_COND2(veh) {
     622              :                 std::cout << " Updating GapControlState." << std::endl;
     623              :             }
     624              : #endif
     625         7723 :             if (myGapControlState->tauCurrent == myGapControlState->tauTarget && myGapControlState->addGapCurrent == myGapControlState->addGapTarget) {
     626         2945 :                 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         4135 :                     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          899 :                     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          899 :                     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           43 :                         myGapControlState->deactivate();
     652              :                     }
     653              :                 }
     654              :             } else {
     655              :                 // Adjust current headway values
     656         4778 :                 myGapControlState->tauCurrent = MIN2(myGapControlState->tauCurrent + myGapControlState->timeHeadwayIncrement, myGapControlState->tauTarget);
     657         5152 :                 myGapControlState->addGapCurrent = MIN2(myGapControlState->addGapCurrent + myGapControlState->spaceHeadwayIncrement, myGapControlState->addGapTarget);
     658              :             }
     659              :         }
     660         7723 :         if (myConsiderSafeVelocity) {
     661              :             gapControlSpeed = MIN2(gapControlSpeed, vSafe);
     662              :         }
     663         7723 :         if (myConsiderMaxAcceleration) {
     664              :             gapControlSpeed = MIN2(gapControlSpeed, vMax);
     665              :         }
     666         7723 :         if (myConsiderMaxDeceleration) {
     667              :             gapControlSpeed = MAX2(gapControlSpeed, vMin);
     668              :         }
     669              :         return MIN2(speed, gapControlSpeed);
     670              :     } else {
     671              :         return speed;
     672              :     }
     673              : }
     674              : 
     675              : double
     676         7136 : MSVehicle::Influencer::getOriginalSpeed() const {
     677         7136 :     return myOriginalSpeed;
     678              : }
     679              : 
     680              : void
     681       496362 : MSVehicle::Influencer::setOriginalSpeed(double speed) {
     682       496362 :     myOriginalSpeed = speed;
     683       496362 : }
     684              : 
     685              : 
     686              : int
     687      2811302 : MSVehicle::Influencer::influenceChangeDecision(const SUMOTime currentTime, const MSEdge& currentEdge, const int currentLaneIndex, int state) {
     688              :     // remove leading commands which are no longer valid
     689      2811550 :     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      2811302 :     if (myLaneTimeLine.size() >= 2 && currentTime >= myLaneTimeLine[0].first) {
     695       173134 :         const int destinationLaneIndex = myLaneTimeLine[1].second;
     696       173134 :         if (destinationLaneIndex < (int)currentEdge.getLanes().size()) {
     697       172842 :             if (currentLaneIndex > destinationLaneIndex) {
     698              :                 changeRequest = REQUEST_RIGHT;
     699       171968 :             } 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      2811302 :     if ((state & LCA_WANTS_LANECHANGE_OR_STAY) != 0) {
     711              :         // flags for the current reason
     712              :         LaneChangeMode mode = LC_NEVER;
     713      1593030 :         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      1590650 :         } else if ((state & LCA_STRATEGIC) != 0) {
     722       485260 :             mode = myStrategicLC;
     723      1105390 :         } else if ((state & LCA_COOPERATIVE) != 0) {
     724           78 :             mode = myCooperativeLC;
     725      1105312 :         } else if ((state & LCA_SPEEDGAIN) != 0) {
     726        41570 :             mode = mySpeedGainLC;
     727      1063742 :         } else if ((state & LCA_KEEPRIGHT) != 0) {
     728         6221 :             mode = myRightDriveLC;
     729      1057521 :         } else if ((state & LCA_SUBLANE) != 0) {
     730      1057519 :             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      1590648 :         if (mode == LC_NEVER) {
     737              :             // cancel all lcModel requests
     738              :             state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     739        42040 :             state &= ~LCA_URGENT;
     740        42040 :             if (changeRequest == REQUEST_NONE) {
     741              :                 // also remove all reasons except TRACI
     742        41573 :                 state &= ~LCA_CHANGE_REASONS | LCA_TRACI;
     743              :             }
     744      1548610 :         } 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      1542987 :         } else if (mode == LC_ALWAYS) {
     754              :             // ignore any TraCI requests
     755              :             return state;
     756              :         }
     757              :     }
     758              :     // apply traci requests
     759      2803721 :     if (changeRequest == REQUEST_NONE) {
     760      2636168 :         return state;
     761              :     } else {
     762       172744 :         state |= LCA_TRACI;
     763              :         // security checks
     764       172744 :         if ((myTraciLaneChangePriority == LCP_ALWAYS)
     765       170888 :                 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     766         2247 :             state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     767              :         }
     768       172744 :         if (changeRequest != REQUEST_HOLD && myTraciLaneChangePriority != LCP_OPPORTUNISTIC) {
     769         2091 :             state |= LCA_URGENT;
     770              :         }
     771         2120 :         switch (changeRequest) {
     772              :             case REQUEST_HOLD:
     773       170624 :                 return state | LCA_STAY;
     774         1326 :             case REQUEST_LEFT:
     775         1326 :                 return state | LCA_LEFT;
     776          794 :             case REQUEST_RIGHT:
     777          794 :                 return state | LCA_RIGHT;
     778              :             default:
     779              :                 throw ProcessError(TL("should not happen"));
     780              :         }
     781              :     }
     782              : }
     783              : 
     784              : 
     785              : double
     786          363 : MSVehicle::Influencer::changeRequestRemainingSeconds(const SUMOTime currentTime) const {
     787              :     assert(myLaneTimeLine.size() >= 2);
     788              :     assert(currentTime >= myLaneTimeLine[0].first);
     789          363 :     return STEPS2TIME(myLaneTimeLine[1].first - currentTime);
     790              : }
     791              : 
     792              : 
     793              : void
     794         5620 : MSVehicle::Influencer::setSpeedMode(int speedMode) {
     795         5620 :     myConsiderSafeVelocity = ((speedMode & 1) != 0);
     796         5620 :     myConsiderMaxAcceleration = ((speedMode & 2) != 0);
     797         5620 :     myConsiderMaxDeceleration = ((speedMode & 4) != 0);
     798         5620 :     myRespectJunctionPriority = ((speedMode & 8) != 0);
     799         5620 :     myEmergencyBrakeRedLight = ((speedMode & 16) != 0);
     800         5620 :     myRespectJunctionLeaderPriority = ((speedMode & 32) == 0); // inverted!
     801         5620 :     myConsiderSpeedLimit = ((speedMode & 64) == 0); // inverted!
     802         5620 : }
     803              : 
     804              : 
     805              : void
     806        18599 : MSVehicle::Influencer::setLaneChangeMode(int value) {
     807        18599 :     myStrategicLC = (LaneChangeMode)(value & (1 + 2));
     808        18599 :     myCooperativeLC = (LaneChangeMode)((value & (4 + 8)) >> 2);
     809        18599 :     mySpeedGainLC = (LaneChangeMode)((value & (16 + 32)) >> 4);
     810        18599 :     myRightDriveLC = (LaneChangeMode)((value & (64 + 128)) >> 6);
     811        18599 :     myTraciLaneChangePriority = (TraciLaneChangePriority)((value & (256 + 512)) >> 8);
     812        18599 :     mySublaneLC = (LaneChangeMode)((value & (1024 + 2048)) >> 10);
     813        18599 : }
     814              : 
     815              : 
     816              : void
     817         7358 : MSVehicle::Influencer::setRemoteControlled(Position xyPos, MSLane* l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector& route, SUMOTime t) {
     818         7358 :     myRemoteXYPos = xyPos;
     819         7358 :     myRemoteLane = l;
     820         7358 :     myRemotePos = pos;
     821         7358 :     myRemotePosLat = posLat;
     822         7358 :     myRemoteAngle = angle;
     823         7358 :     myRemoteEdgeOffset = edgeOffset;
     824         7358 :     myRemoteRoute = route;
     825         7358 :     myLastRemoteAccess = t;
     826         7358 : }
     827              : 
     828              : 
     829              : bool
     830      1015968 : MSVehicle::Influencer::isRemoteControlled() const {
     831      1015968 :     return myLastRemoteAccess == MSNet::getInstance()->getCurrentTimeStep();
     832              : }
     833              : 
     834              : 
     835              : bool
     836       465173 : MSVehicle::Influencer::isRemoteAffected(SUMOTime t) const {
     837       465173 :     return myLastRemoteAccess >= t - TIME2STEPS(10);
     838              : }
     839              : 
     840              : 
     841              : void
     842       491573 : MSVehicle::Influencer::updateRemoteControlRoute(MSVehicle* v) {
     843       491573 :     if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
     844              :         // only replace route at this time if the vehicle is moving with the flow
     845           78 :         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       491573 : }
     855              : 
     856              : 
     857              : void
     858         7338 : MSVehicle::Influencer::postProcessRemoteControl(MSVehicle* v) {
     859         7338 :     const bool wasOnRoad = v->isOnRoad();
     860         7338 :     const bool withinLane = myRemoteLane != nullptr && fabs(myRemotePosLat) < 0.5 * (myRemoteLane->getWidth() + v->getVehicleType().getWidth());
     861         7338 :     const bool keepLane = wasOnRoad && v->getLane() == myRemoteLane;
     862         7338 :     if (v->isOnRoad() && !(keepLane && withinLane)) {
     863          153 :         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          153 :         v->onRemovalFromNet(MSMoveReminder::NOTIFICATION_TELEPORT);
     868          153 :         v->getMutableLane()->removeVehicle(v, MSMoveReminder::NOTIFICATION_TELEPORT, false);
     869              :     }
     870         7338 :     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           78 :         const_cast<SUMOVehicleParameter&>(v->getParameter()).stops.clear();
     883          156 :         v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     884              :         myRemoteRoute.clear();
     885              :     }
     886         7338 :     v->myCurrEdge = v->getRoute().begin() + myRemoteEdgeOffset;
     887         7338 :     if (myRemoteLane != nullptr && myRemotePos > myRemoteLane->getLength()) {
     888            0 :         myRemotePos = myRemoteLane->getLength();
     889              :     }
     890         7338 :     if (myRemoteLane != nullptr && withinLane) {
     891         7192 :         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          176 :             MSMoveReminder::Notification notify = v->getDeparture() == NOT_YET_DEPARTED
     901          176 :                                                   ? MSMoveReminder::NOTIFICATION_DEPARTED
     902              :                                                   : MSMoveReminder::NOTIFICATION_TELEPORT_ARRIVED;
     903          176 :             if (!v->isOnRoad()) {
     904          176 :                 MSVehicleTransfer::getInstance()->remove(v);  // TODO may need optimization, this is linear in the number of vehicles in transfer
     905              :             }
     906          176 :             myRemoteLane->forceVehicleInsertion(v, myRemotePos, notify, myRemotePosLat);
     907          176 :             v->updateBestLanes();
     908              :         }
     909         7192 :         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         7192 :         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         7338 :     v->setRemoteState(myRemoteXYPos);
     931         7338 :     v->setAngle(GeomHelper::fromNaviDegree(myRemoteAngle));
     932         7338 : }
     933              : 
     934              : 
     935              : double
     936         7319 : MSVehicle::Influencer::implicitSpeedRemote(const MSVehicle* veh, double oldSpeed) {
     937         7319 :     if (veh->getPosition() == Position::INVALID) {
     938            8 :         return oldSpeed;
     939              :     }
     940         7311 :     double dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
     941         7311 :     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         7197 :         const double distAlongRoute = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     947         7197 :         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         7311 :     const double minSpeed = myConsiderMaxDeceleration ?
     953         4043 :                             veh->getCarFollowModel().minNextSpeedEmergency(oldSpeed, veh) : 0;
     954         7311 :     const double maxSpeed = (myRemoteLane != nullptr
     955         7311 :                              ? myRemoteLane->getVehicleMaxSpeed(veh)
     956          114 :                              : (veh->getLane() != nullptr
     957          114 :                                 ? veh->getLane()->getVehicleMaxSpeed(veh)
     958            4 :                                 : veh->getMaxSpeed()));
     959         7311 :     return MIN2(maxSpeed, MAX2(minSpeed, DIST2SPEED(dist)));
     960              : }
     961              : 
     962              : 
     963              : double
     964         7181 : MSVehicle::Influencer::implicitDeltaPosRemote(const MSVehicle* veh) {
     965              :     double dist = 0;
     966         7181 :     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         7176 :         dist = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     975              :     }
     976         7181 :     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      4520490 : MSVehicle::MSVehicle(SUMOVehicleParameter* pars, ConstMSRoutePtr route,
     994      4520490 :                      MSVehicleType* type, const double speedFactor) :
     995              :     MSBaseVehicle(pars, route, type, speedFactor),
     996      4520490 :     myWaitingTime(0),
     997      4520490 :     myWaitingTimeCollector(),
     998      4520490 :     myTimeLoss(0),
     999      4520490 :     myState(0, 0, 0, 0, 0),
    1000      4520490 :     myDriverState(nullptr),
    1001      4520490 :     myActionStep(true),
    1002      4520490 :     myLastActionTime(0),
    1003      4520490 :     myLane(nullptr),
    1004      4520490 :     myLaneChangeModel(nullptr),
    1005      4520490 :     myLastBestLanesEdge(nullptr),
    1006      4520490 :     myLastBestLanesInternalLane(nullptr),
    1007      4520490 :     myAcceleration(0),
    1008              :     myNextTurn(0., nullptr),
    1009      4520490 :     mySignals(0),
    1010      4520490 :     myAmOnNet(false),
    1011      4520490 :     myAmIdling(false),
    1012      4520490 :     myHaveToWaitOnNextLink(false),
    1013      4520490 :     myAngle(0),
    1014      4520490 :     myRawAngle(0),
    1015      4520490 :     myLastAngle(INVALID_DOUBLE),
    1016      4520490 :     myStopDist(std::numeric_limits<double>::max()),
    1017      4520490 :     myStopSpeed(std::numeric_limits<double>::max()),
    1018      4520490 :     myCollisionImmunity(-1),
    1019      4520490 :     myCachedPosition(Position::INVALID),
    1020      4520490 :     myJunctionEntryTime(SUMOTime_MAX),
    1021      4520490 :     myJunctionEntryTimeNeverYield(SUMOTime_MAX),
    1022      4520490 :     myJunctionConflictEntryTime(SUMOTime_MAX),
    1023      4520490 :     myTimeSinceStartup(TIME2STEPS(3600 * 24)),
    1024      4520490 :     myHaveStoppedFor(nullptr),
    1025     13561470 :     myInfluencer(nullptr) {
    1026      4520490 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    1027      4520490 :     myNextDriveItem = myLFLinkLanes.begin();
    1028      4520490 : }
    1029              : 
    1030              : 
    1031      8394214 : MSVehicle::~MSVehicle() {
    1032      4520409 :     cleanupParkingReservation();
    1033      4520409 :     cleanupFurtherLanes();
    1034      4520409 :     delete myLaneChangeModel;
    1035      4520409 :     if (myType->isVehicleSpecific()) {
    1036          316 :         MSNet::getInstance()->getVehicleControl().removeVType(myType);
    1037              :     }
    1038      4520409 :     delete myInfluencer;
    1039      4520409 :     delete myCFVariables;
    1040     12914623 : }
    1041              : 
    1042              : 
    1043              : void
    1044      4520971 : MSVehicle::cleanupFurtherLanes() {
    1045      4523450 :     for (MSLane* further : myFurtherLanes) {
    1046         2479 :         further->resetPartialOccupation(this);
    1047         2479 :         if (further->getBidiLane() != nullptr
    1048         2479 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    1049            0 :             further->getBidiLane()->resetPartialOccupation(this);
    1050              :         }
    1051              :     }
    1052      4520971 :     if (myLaneChangeModel != nullptr) {
    1053      4520937 :         removeApproachingInformation(myLFLinkLanes);
    1054      4520937 :         myLaneChangeModel->cleanupShadowLane();
    1055      4520937 :         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      4520971 : }
    1062              : 
    1063              : 
    1064              : void
    1065      3373455 : 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      3373455 :     MSVehicleTransfer::getInstance()->remove(this);
    1072      3373455 :     removeApproachingInformation(myLFLinkLanes);
    1073      3373455 :     leaveLane(reason);
    1074      3373455 :     if (reason == MSMoveReminder::NOTIFICATION_VAPORIZED_COLLISION) {
    1075          562 :         cleanupFurtherLanes();
    1076              :     }
    1077      3373455 : }
    1078              : 
    1079              : 
    1080              : void
    1081      4520490 : MSVehicle::initDevices() {
    1082      4520490 :     MSBaseVehicle::initDevices();
    1083      4520478 :     myLaneChangeModel = MSAbstractLaneChangeModel::build(myType->getLaneChangeModel(), *this);
    1084      4520456 :     myDriverState = static_cast<MSDevice_DriverState*>(getDevice(typeid(MSDevice_DriverState)));
    1085      4520456 :     myFrictionDevice = static_cast<MSDevice_Friction*>(getDevice(typeid(MSDevice_Friction)));
    1086      4520456 : }
    1087              : 
    1088              : 
    1089              : // ------------ interaction with the route
    1090              : bool
    1091   2238641842 : MSVehicle::hasValidRouteStart(std::string& msg) {
    1092              :     // note: not a const method because getDepartLane may call updateBestLanes
    1093   2238641842 :     if (!(*myCurrEdge)->isTazConnector()) {
    1094   2238313484 :         if (myParameter->departLaneProcedure == DepartLaneDefinition::GIVEN
    1095   2238313484 :                 || (myParameter->departLaneProcedure == DepartLaneDefinition::DEFAULT && MSEdge::getDefaultDepartLaneDefinition() == DepartLaneDefinition::GIVEN)) {
    1096     62536428 :             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   2175777056 :             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   2238313346 :         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   2238641685 :     myRouteValidity &= ~(ROUTE_START_INVALID_LANE | ROUTE_START_INVALID_PERMISSIONS);
    1119   2238641685 :     return true;
    1120              : }
    1121              : 
    1122              : 
    1123              : bool
    1124    714108000 : MSVehicle::hasArrived() const {
    1125    714108000 :     return hasArrivedInternal(false);
    1126              : }
    1127              : 
    1128              : 
    1129              : bool
    1130   1437559111 : MSVehicle::hasArrivedInternal(bool oppositeTransformed) const {
    1131   2335215570 :     return ((myCurrEdge == myRoute->end() - 1 || (myParameter->arrivalEdge >= 0 && getRoutePosition() >= myParameter->arrivalEdge))
    1132    539951925 :             && (myStops.empty() || myStops.front().edge != myCurrEdge || myStops.front().getSpeed() > 0)
    1133   1010529190 :             && ((myLaneChangeModel->isOpposite() && !oppositeTransformed) ? myLane->getLength() - myState.myPos : myState.myPos) > MIN2(myLane->getLength(), myArrivalPos) - POSITION_EPS
    1134   1448972566 :             && !isRemoteControlled());
    1135              : }
    1136              : 
    1137              : 
    1138              : bool
    1139      1566453 : MSVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
    1140      3132906 :     if (MSBaseVehicle::replaceRoute(newRoute, info, onInit, offset, addRouteStops, removeStops, msgReturn)) {
    1141              :         // update best lanes (after stops were added)
    1142      1566435 :         myLastBestLanesEdge = nullptr;
    1143      1566435 :         myLastBestLanesInternalLane = nullptr;
    1144      1566435 :         updateBestLanes(true, onInit ? (*myCurrEdge)->getLanes().front() : 0);
    1145              :         assert(!removeStops || haveValidStopEdges());
    1146      1566435 :         if (myStops.size() == 0) {
    1147      1522552 :             myStopDist = std::numeric_limits<double>::max();
    1148              :         }
    1149      1566435 :         return true;
    1150              :     }
    1151              :     return false;
    1152              : }
    1153              : 
    1154              : 
    1155              : // ------------ Interaction with move reminders
    1156              : void
    1157    701021574 : 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   1855028837 :     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   2308014528 :         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    701021573 :     if (myEnergyParams != nullptr) {
    1182              :         // TODO make the vehicle energy params a derived class which is a move reminder
    1183    140127122 :         myEnergyParams->setDynamicValues(isStopped() ? getNextStop().duration : -1, isParking(), getWaitingTime(), getAngleDiff());
    1184              :     }
    1185    701021573 : }
    1186              : 
    1187              : 
    1188              : void
    1189        66788 : MSVehicle::workOnIdleReminders() {
    1190        66788 :     updateWaitingTime(0.);   // cf issue 2233
    1191              : 
    1192              :     // vehicle move reminders
    1193        80314 :     for (const auto& rem : myMoveReminders) {
    1194        13526 :         rem.first->notifyIdle(*this);
    1195              :     }
    1196              : 
    1197              :     // lane move reminders - for aggregated values
    1198       166697 :     for (MSMoveReminder* rem : getLane()->getMoveReminders()) {
    1199        99909 :         rem->notifyIdle(*this);
    1200              :     }
    1201        66788 : }
    1202              : 
    1203              : // XXX: consider renaming...
    1204              : void
    1205     19534811 : 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     19534811 :     const double oldLaneLength = myLane->getLength();
    1209     55284097 :     for (auto& rem : myMoveReminders) {
    1210     35749286 :         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     32778859 :     for (MSMoveReminder* const rem : enteredLane.getMoveReminders()) {
    1220     13244048 :         addReminder(rem);
    1221              :     }
    1222     19534811 : }
    1223              : 
    1224              : 
    1225              : // ------------ Other getter methods
    1226              : double
    1227    164788147 : MSVehicle::getSlope() const {
    1228    164788147 :     if (isParking() && getStops().begin()->parkingarea != nullptr) {
    1229         3882 :         return getStops().begin()->parkingarea->getVehicleSlope(*this);
    1230              :     }
    1231    164784265 :     if (myLane == nullptr) {
    1232              :         return 0;
    1233              :     }
    1234    164784265 :     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    164784017 :     const double posLat = myState.myPosLat; // @todo get rid of the '-'
    1246    164784017 :     Position p1 = getPosition();
    1247    164784017 :     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    164784017 :     return (p1 != p2 ? RAD2DEG(p2.slopeTo2D(p1)) : myLane->getShape().slopeDegreeAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1261              : }
    1262              : 
    1263              : 
    1264              : Position
    1265    937871039 : MSVehicle::getPosition(const double offset) const {
    1266    937871039 :     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    937870893 :     if (isParking()) {
    1275      3806669 :         if (myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() > getNextStopParameter()->started) {
    1276          120 :             return myCachedPosition;
    1277              :         }
    1278      3806549 :         if (myStops.begin()->parkingarea != nullptr) {
    1279        22291 :             return myStops.begin()->parkingarea->getVehiclePosition(*this);
    1280              :         } else {
    1281              :             // position beside the road
    1282      3784258 :             PositionVector shp = myLane->getEdge().getLanes()[0]->getShape();
    1283      7568396 :             shp.move2side(SUMO_const_laneWidth * (MSGlobals::gLefthand ? -1 : 1));
    1284      3784258 :             return shp.positionAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane() + offset));
    1285      3784258 :         }
    1286              :     }
    1287    934064224 :     const bool changingLanes = myLaneChangeModel->isChangingLanes();
    1288   1857990589 :     const double posLat = (MSGlobals::gLefthand ? 1 : -1) * getLateralPositionOnLane();
    1289    934064224 :     if (offset == 0. && !changingLanes) {
    1290              :         if (myCachedPosition == Position::INVALID) {
    1291    705594524 :             myCachedPosition = validatePosition(myLane->geometryPositionAtOffset(myState.myPos, posLat));
    1292    705594524 :             if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1293        61155 :                 interpolateLateralZ(myCachedPosition, myState.myPos, posLat);
    1294              :             }
    1295              :         }
    1296    927299848 :         return myCachedPosition;
    1297              :     }
    1298      6764376 :     Position result = validatePosition(myLane->geometryPositionAtOffset(getPositionOnLane() + offset, posLat), offset);
    1299      6764376 :     interpolateLateralZ(result, getPositionOnLane() + offset, posLat);
    1300      6764376 :     return result;
    1301              : }
    1302              : 
    1303              : 
    1304              : void
    1305      7110815 : MSVehicle::interpolateLateralZ(Position& pos, double offset, double posLat) const {
    1306      7110815 :     const MSLane* shadow = myLaneChangeModel->getShadowLane();
    1307      7110815 :     if (shadow != nullptr && pos != Position::INVALID) {
    1308              :         // ignore negative offset
    1309              :         const Position shadowPos = shadow->geometryPositionAtOffset(MAX2(0.0, offset));
    1310        55143 :         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      7110815 : }
    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       104142 : MSVehicle::getPositionAlongBestLanes(double offset) const {
    1337              :     assert(MSGlobals::gUsingInternalLanes);
    1338       104142 :     if (!isOnRoad()) {
    1339            0 :         return Position::INVALID;
    1340              :     }
    1341       104142 :     const std::vector<MSLane*>& bestLanes = getBestLanesContinuation();
    1342              :     auto nextBestLane = bestLanes.begin();
    1343       104142 :     const bool opposite = myLaneChangeModel->isOpposite();
    1344       104142 :     double pos = opposite ? myLane->getLength() - myState.myPos : myState.myPos;
    1345       104142 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : getLane();
    1346              :     assert(lane != 0);
    1347              :     bool success = true;
    1348              : 
    1349       307523 :     while (offset > 0) {
    1350              :         // take into account lengths along internal lanes
    1351       310893 :         while (lane->isInternal() && offset > 0) {
    1352       107512 :             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       103951 :                 pos += offset;
    1362              :                 offset = 0;
    1363              :             }
    1364              :         }
    1365              :         // set nextBestLane to next non-internal lane
    1366       208508 :         while (nextBestLane != bestLanes.end() && *nextBestLane == nullptr) {
    1367              :             ++nextBestLane;
    1368              :         }
    1369       203381 :         if (offset > 0) {
    1370              :             assert(!lane->isInternal());
    1371              :             assert(lane == *nextBestLane);
    1372        99430 :             if (offset > lane->getLength() - pos) {
    1373        99247 :                 offset -= lane->getLength() - pos;
    1374              :                 ++nextBestLane;
    1375              :                 assert(nextBestLane == bestLanes.end() || *nextBestLane != 0);
    1376        99247 :                 if (nextBestLane == bestLanes.end()) {
    1377              :                     success = false;
    1378              :                     offset = 0.;
    1379              :                 } else {
    1380        99247 :                     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       104142 :     if (success) {
    1394       104142 :         return lane->geometryPositionAtOffset(pos, -getLateralPositionOnLane());
    1395              :     } else {
    1396            0 :         return Position::INVALID;
    1397              :     }
    1398              : }
    1399              : 
    1400              : 
    1401              : double
    1402       714427 : MSVehicle::getMaxSpeedOnLane() const {
    1403       714427 :     if (myLane != nullptr) {
    1404       714427 :         return myLane->getVehicleMaxSpeed(this);
    1405              :     }
    1406            0 :     return myType->getMaxSpeed();
    1407              : }
    1408              : 
    1409              : 
    1410              : Position
    1411    712358900 : MSVehicle::validatePosition(Position result, double offset) const {
    1412              :     int furtherIndex = 0;
    1413    712358900 :     double lastLength = getPositionOnLane();
    1414    712358900 :     while (result == Position::INVALID) {
    1415       210703 :         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       192680 :         MSLane* further = myFurtherLanes[furtherIndex];
    1421       192680 :         offset += lastLength;
    1422       192680 :         result = further->geometryPositionAtOffset(further->getLength() + offset, -getLateralPositionOnLane());
    1423              :         lastLength = further->getLength();
    1424       192680 :         furtherIndex++;
    1425              :         //std::cout << SIMTIME << "   newResult=" << result << "\n";
    1426              :     }
    1427    712358900 :     return result;
    1428              : }
    1429              : 
    1430              : 
    1431              : ConstMSEdgeVector::const_iterator
    1432       282376 : MSVehicle::getRerouteOrigin() const {
    1433              :     // too close to the next junction, so avoid an emergency brake here
    1434       282376 :     if (myLane != nullptr && (myCurrEdge + 1) != myRoute->end() && !isRailway(getVClass())) {
    1435       219968 :         if (myLane->isInternal()) {
    1436              :             return myCurrEdge + 1;
    1437              :         }
    1438       212894 :         if (myState.myPos > myLane->getLength() - getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)) {
    1439              :             return myCurrEdge + 1;
    1440              :         }
    1441       210517 :         if (myLane->getEdge().hasChangeProhibitions(getVClass(), myLane->getIndex())) {
    1442              :             return myCurrEdge + 1;
    1443              :         }
    1444              :     }
    1445       272813 :     return myCurrEdge;
    1446              : }
    1447              : 
    1448              : 
    1449              : double
    1450    140144574 : MSVehicle::getAngleDiff() const {
    1451    140144574 :     return myLastAngle == INVALID_DOUBLE ? 0. : GeomHelper::angleDiff(myLastAngle, myAngle);
    1452              : }
    1453              : 
    1454              : double
    1455        17452 : MSVehicle::getCurveRadius() const {
    1456        17452 :     const double angleDiff = getAngleDiff();
    1457              :     return angleDiff == 0
    1458        17452 :         ? std::numeric_limits<double>::max()
    1459        10144 :         : SPEED2DIST(getSpeed()) / fabs(angleDiff);
    1460              : }
    1461              : 
    1462              : 
    1463              : void
    1464      5328390 : 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      5328390 :     myAngle = angle;
    1471      5328390 :     MSLane* next = myLane;
    1472      5328390 :     if (straightenFurther && myFurtherLanesPosLat.size() > 0) {
    1473       202225 :         for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    1474       103939 :             MSLane* further = myFurtherLanes[i];
    1475       103939 :             const MSLink* link = further->getLinkTo(next);
    1476       103939 :             if (link  != nullptr) {
    1477       103509 :                 myFurtherLanesPosLat[i] = getLateralPositionOnLane() - link->getLateralShift();
    1478              :                 next = further;
    1479              :             } else {
    1480              :                 break;
    1481              :             }
    1482              :         }
    1483              :     }
    1484      5328390 : }
    1485              : 
    1486              : 
    1487              : void
    1488       451557 : MSVehicle::setActionStepLength(double actionStepLength, bool resetOffset) {
    1489       451557 :     SUMOTime actionStepLengthMillisecs = SUMOVehicleParserHelper::processActionStepLength(actionStepLength);
    1490              :     SUMOTime previousActionStepLength = getActionStepLength();
    1491              :     const bool newActionStepLength = actionStepLengthMillisecs != previousActionStepLength;
    1492       451557 :     if (newActionStepLength) {
    1493            7 :         getSingularType().setActionStepLength(actionStepLengthMillisecs, resetOffset);
    1494            7 :         if (!resetOffset) {
    1495            1 :             updateActionOffset(previousActionStepLength, actionStepLengthMillisecs);
    1496              :         }
    1497              :     }
    1498       451551 :     if (resetOffset) {
    1499            6 :         resetActionOffset();
    1500              :     }
    1501       451557 : }
    1502              : 
    1503              : 
    1504              : bool
    1505    301723641 : MSVehicle::congested() const {
    1506    301723641 :     return myState.mySpeed < (60.0 / 3.6) || myLane->getSpeedLimit() < (60.1 / 3.6);
    1507              : }
    1508              : 
    1509              : 
    1510              : double
    1511    708323026 : MSVehicle::computeAngle() const {
    1512              :     Position p1;
    1513    708323026 :     const double posLat = -myState.myPosLat; // @todo get rid of the '-'
    1514    708323026 :     const double lefthandSign = (MSGlobals::gLefthand ? -1 : 1);
    1515              : 
    1516              :     // if parking manoeuvre is happening then rotate vehicle on each step
    1517    708323026 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    1518          450 :         return getAngle() + myManoeuvre.getGUIIncrement();
    1519              :     }
    1520              : 
    1521    708322576 :     if (isParking()) {
    1522        29086 :         if (myStops.begin()->parkingarea != nullptr) {
    1523        15810 :             return myStops.begin()->parkingarea->getVehicleAngle(*this);
    1524              :         } else {
    1525        13276 :             return myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane()));
    1526              :         }
    1527              :     }
    1528    708293490 :     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    707146460 :         p1 = getPosition();
    1538              :     }
    1539              : 
    1540              :     Position p2;
    1541    708293490 :     if (getVehicleType().getParameter().locomotiveLength > 0) {
    1542              :         // articulated vehicle should use the heading of the first part
    1543      1877488 :         const double locoLength = MIN2(getVehicleType().getParameter().locomotiveLength, getLength());
    1544      1877488 :         p2 = getPosition(-locoLength);
    1545              :     } else {
    1546    706416002 :         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       104661 :                      myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1562              : 
    1563    708293490 :     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    708293490 :     return result;
    1571              : }
    1572              : 
    1573              : 
    1574              : const Position
    1575    878347357 : MSVehicle::getBackPosition() const {
    1576    878347357 :     const double posLat = MSGlobals::gLefthand ? myState.myPosLat : -myState.myPosLat;
    1577              :     Position result;
    1578    878347357 :     if (myState.myPos >= myType->getLength()) {
    1579              :         // vehicle is fully on the new lane
    1580    860726300 :         result = myLane->geometryPositionAtOffset(myState.myPos - myType->getLength(), posLat);
    1581              :     } else {
    1582     17621057 :         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     17619151 :             if (myFurtherLanes.size() > 0 && !myLaneChangeModel->isChangingLanes()) {
    1597              :                 // truncate to 0 if vehicle starts on an edge that is shorter than its length
    1598     17231918 :                 const double backPos = MAX2(0.0, getBackPositionOnLane(myFurtherLanes.back()));
    1599     34164751 :                 result = myFurtherLanes.back()->geometryPositionAtOffset(backPos, -myFurtherLanesPosLat.back() * (MSGlobals::gLefthand ? -1 : 1));
    1600              :             } else {
    1601       387233 :                 result = myLane->geometryPositionAtOffset(0, posLat);
    1602              :             }
    1603              :         }
    1604              :     }
    1605    878347357 :     if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1606       285284 :         interpolateLateralZ(result, myState.myPos - myType->getLength(), posLat);
    1607              :     }
    1608    878347357 :     return result;
    1609              : }
    1610              : 
    1611              : 
    1612              : bool
    1613       454437 : MSVehicle::willStop() const {
    1614       454437 :     return !isStopped() && !myStops.empty() && myLane != nullptr && &myStops.front().lane->getEdge() == &myLane->getEdge();
    1615              : }
    1616              : 
    1617              : bool
    1618    371621593 : MSVehicle::isStoppedOnLane() const {
    1619    371621593 :     return isStopped() && myStops.front().lane == myLane;
    1620              : }
    1621              : 
    1622              : bool
    1623     31210756 : MSVehicle::keepStopping(bool afterProcessing) const {
    1624     31210756 :     if (isStopped()) {
    1625              :         // when coming out of vehicleTransfer we must shift the time forward
    1626     37262379 :         return (myStops.front().duration - (afterProcessing ? DELTA_T : 0) > 0 || isStoppedTriggered() || myStops.front().pars.collision
    1627     30940108 :                 || myStops.front().pars.breakDown || (myStops.front().getSpeed() > 0
    1628        35769 :                         && (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        16200 : MSVehicle::remainingStopDuration() const {
    1638        16200 :     if (isStopped()) {
    1639        16200 :         return myStops.front().duration;
    1640              :     }
    1641              :     return 0;
    1642              : }
    1643              : 
    1644              : 
    1645              : SUMOTime
    1646    680779477 : MSVehicle::collisionStopTime() const {
    1647    680779477 :     return (myStops.empty() || !myStops.front().pars.collision) ? myCollisionImmunity : MAX2((SUMOTime)0, myStops.front().duration);
    1648              : }
    1649              : 
    1650              : 
    1651              : bool
    1652    680642238 : MSVehicle::brokeDown() const {
    1653    680642238 :     return isStopped() && !myStops.empty() && myStops.front().pars.breakDown;
    1654              : }
    1655              : 
    1656              : 
    1657              : bool
    1658       169744 : MSVehicle::ignoreCollision() const {
    1659       169744 :     return myCollisionImmunity > 0;
    1660              : }
    1661              : 
    1662              : 
    1663              : double
    1664    644447575 : MSVehicle::processNextStop(double currentVelocity) {
    1665    644447575 :     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     41485854 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1678     41485854 :     if (stop.reached) {
    1679     26105105 :         stop.duration -= getActionStepLength();
    1680     26105105 :         if (getSpeed() > 0) {
    1681              :             // re-enter stopping places to correct waiting position (except for parkingArea since it's place-based)
    1682      3812029 :             if (stop.busstop != nullptr) {
    1683              :                 // let the bus stop know the vehicle
    1684        12960 :                 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1685              :             }
    1686      3812029 :             if (stop.containerstop != nullptr) {
    1687              :                 // let the container stop know the vehicle
    1688      3766523 :                 stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1689              :             }
    1690      3812029 :             if (stop.chargingStation != nullptr) {
    1691              :                 // let the container stop know the vehicle
    1692         3045 :                 stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1693              :             }
    1694      3812029 :             if (stop.getSpeed() <= 0) {
    1695      3794860 :                 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     26105105 :         if (stop.duration <= 0 && stop.pars.join != "") {
    1709              :             // join this train (part) to another one
    1710        37465 :             MSVehicle* joinVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.join));
    1711          968 :             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     26105105 :         boardTransportables(stop);
    1732     22338988 :         if (time > stop.endBoarding) {
    1733              :             // for taxi: cancel customers
    1734       198307 :             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     22338924 :         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        44678 :             resumeFromStopping();
    1749        44678 :             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     22294246 :             if (stop.triggered) {
    1760      3237620 :                 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      3237610 :                 } 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         4343 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1766         4343 :                     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     22294246 :             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     22294246 :             if (stop.joinTriggered && !myAmRegisteredAsWaiting
    1791         7104 :                     && stop.duration <= (stop.pars.extension >= 0 ? -stop.pars.extension : 0)) {
    1792           99 :                 if (stop.pars.extension >= 0) {
    1793          105 :                     WRITE_WARNINGF(TL("Vehicle '%' aborts joining after extension of %s at time %."), getID(), STEPS2TIME(stop.pars.extension), time2string(SIMSTEP));
    1794           35 :                     stop.joinTriggered = false;
    1795              :                 } else {
    1796              :                     // keep stopping indefinitely but ensure that simulation terminates
    1797           64 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1798           64 :                     myAmRegisteredAsWaiting = true;
    1799              :                 }
    1800              :             }
    1801     22294246 :             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     22074581 :                 if (MSGlobals::gSemiImplicitEulerUpdate || stop.getSpeed() > 0) {
    1812     21805484 :                     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     15443268 :         if (stop.pars.onDemand && !stop.skipOnDemand && myStopDist <= getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this))) {
    1828          576 :             MSNet* const net = MSNet::getInstance();
    1829           44 :             const bool noExits = ((myPersonDevice == nullptr || !myPersonDevice->anyLeavingAtStop(stop))
    1830          586 :                                   && (myContainerDevice == nullptr || !myContainerDevice->anyLeavingAtStop(stop)));
    1831           83 :             const bool noEntries = ((!net->hasPersons() || !net->getPersonControl().hasAnyWaiting(stop.getEdge(), this))
    1832          625 :                                     && (!net->hasContainers() || !net->getContainerControl().hasAnyWaiting(stop.getEdge(), this)));
    1833          576 :             if (noExits && noEntries) {
    1834              :                 //std::cout << " skipOnDemand\n";
    1835          508 :                 stop.skipOnDemand = true;
    1836              :                 // bestLanes must be extended past this stop
    1837          508 :                 updateBestLanes(true);
    1838              :             }
    1839              :         }
    1840              :         // is the next stop on the current lane?
    1841     15380749 :         if (stop.edge == myCurrEdge) {
    1842              :             // get the stopping position
    1843      5550518 :             bool useStoppingPlace = stop.busstop != nullptr || stop.containerstop != nullptr || stop.parkingarea != nullptr;
    1844              :             bool fitsOnStoppingPlace = true;
    1845      5550518 :             if (!stop.skipOnDemand) {  // no need to check available space if we skip it anyway
    1846      5544729 :                 if (stop.busstop != nullptr) {
    1847      1711493 :                     fitsOnStoppingPlace &= stop.busstop->fits(myState.myPos, *this);
    1848              :                 }
    1849      5544729 :                 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      5544729 :                 if (stop.parkingarea != nullptr) {
    1854       687682 :                     fitsOnStoppingPlace &= myState.myPos > stop.parkingarea->getBeginLanePosition();
    1855       687682 :                     if (stop.parkingarea->getOccupancy() >= stop.parkingarea->getCapacity()) {
    1856              :                         fitsOnStoppingPlace = false;
    1857              :                         // trigger potential parkingZoneReroute
    1858       439026 :                         MSParkingArea* oldParkingArea = stop.parkingarea;
    1859       484217 :                         for (MSMoveReminder* rem : myLane->getMoveReminders()) {
    1860        45191 :                             if (rem->isParkingRerouter()) {
    1861        23963 :                                 rem->notifyEnter(*this, MSMoveReminder::NOTIFICATION_PARKING_REROUTE, myLane);
    1862              :                             }
    1863              :                         }
    1864       439026 :                         if (myStops.empty() || myStops.front().parkingarea != oldParkingArea) {
    1865              :                             // rerouted, keep driving
    1866              :                             return currentVelocity;
    1867              :                         }
    1868       248656 :                     } else if (stop.parkingarea->getOccupancyIncludingReservations(this) >= stop.parkingarea->getCapacity()) {
    1869              :                         fitsOnStoppingPlace = false;
    1870       117305 :                     } else if (stop.parkingarea->parkOnRoad() && stop.parkingarea->getLotIndex(this) < 0) {
    1871              :                         fitsOnStoppingPlace = false;
    1872              :                     }
    1873              :                 }
    1874              :             }
    1875      5548738 :             const double targetPos = myState.myPos + myStopDist + (stop.getSpeed() > 0 ? (stop.pars.startPos - stop.pars.endPos) : 0);
    1876      5548738 :             double reachedThreshold = (useStoppingPlace ? targetPos - STOPPING_PLACE_OFFSET : stop.getReachedThreshold()) - NUMERICAL_EPS;
    1877      5548738 :             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      5548738 :             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      5548738 :             if (posReached && !fitsOnStoppingPlace && MSStopOut::active()) {
    1893         6711 :                 MSStopOut::getInstance()->stopBlocked(this, time);
    1894              :             }
    1895      5548738 :             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        56858 :                 stop.reached = true;
    1898        56858 :                 if (!stop.startedFromState) {
    1899        56624 :                     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        56858 :                 if (MSStopOut::active()) {
    1907         5665 :                     MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), time);
    1908              :                 }
    1909        56858 :                 myLane->getEdge().addWaiting(this);
    1910        56858 :                 MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::STARTING_STOP);
    1911        56858 :                 MSNet::getInstance()->getVehicleControl().registerStopStarted();
    1912              :                 // compute stopping time
    1913        56858 :                 stop.duration = stop.getMinDuration(time);
    1914        56858 :                 stop.endBoarding = stop.pars.extension >= 0 ? time + stop.duration + stop.pars.extension : SUMOTime_MAX;
    1915        56858 :                 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1916         4142 :                 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        56858 :                 if (stop.getSpeed() > 0) {
    1921              :                     // ignore duration parameter in waypoint mode unless 'until' or 'ended' are set
    1922         3428 :                     if (stop.getUntil() > time) {
    1923          348 :                         stop.duration = stop.getUntil() - time;
    1924              :                     } else {
    1925         3080 :                         stop.duration = 0;
    1926              :                     }
    1927              :                 } else {
    1928        53430 :                     stop.entryPos = getPositionOnLane();
    1929              :                 }
    1930        56858 :                 if (stop.busstop != nullptr) {
    1931              :                     // let the bus stop know the vehicle
    1932        18763 :                     stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1933              :                 }
    1934        56858 :                 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        56858 :                 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    1939              :                     // let the parking area know the vehicle
    1940         9916 :                     stop.parkingarea->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1941              :                 }
    1942        56858 :                 if (stop.chargingStation != nullptr) {
    1943              :                     // let the container stop know the vehicle
    1944         3555 :                     stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1945              :                 }
    1946              : 
    1947        56858 :                 if (stop.pars.tripId != "") {
    1948         2920 :                     ((SUMOVehicleParameter&)getParameter()).setParameter("tripId", stop.pars.tripId);
    1949              :                 }
    1950        56858 :                 if (stop.pars.line != "") {
    1951         1463 :                     ((SUMOVehicleParameter&)getParameter()).line = stop.pars.line;
    1952              :                 }
    1953        56858 :                 if (stop.pars.split != "") {
    1954              :                     // split the train
    1955         1239 :                     MSVehicle* splitVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.split));
    1956           24 :                     if (splitVeh == nullptr) {
    1957         3645 :                         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        56858 :                 boardTransportables(stop);
    1981        56854 :                 if (stop.pars.posLat != INVALID_DOUBLE) {
    1982          230 :                     myState.myPosLat = stop.pars.posLat;
    1983              :                 }
    1984              :             }
    1985              :         }
    1986              :     }
    1987              :     return currentVelocity;
    1988              : }
    1989              : 
    1990              : 
    1991              : void
    1992     26161963 : MSVehicle::boardTransportables(MSStop& stop) {
    1993     26161963 :     if (stop.skipOnDemand) {
    1994              :         return;
    1995              :     }
    1996              :     // we have reached the stop
    1997              :     // any waiting persons may board now
    1998     25958757 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1999     25958757 :     MSNet* const net = MSNet::getInstance();
    2000     25958757 :     const bool boarded = (time <= stop.endBoarding
    2001     25957173 :                           && net->hasPersons()
    2002      1537778 :                           && net->getPersonControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToBoardNextPerson, stop.duration)
    2003     25966428 :                           && stop.numExpectedPerson == 0);
    2004              :     // load containers
    2005     25958757 :     const bool loaded = (time <= stop.endBoarding
    2006     25957173 :                          && net->hasContainers()
    2007      3868555 :                          && net->getContainerControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToLoadNextContainer, stop.duration)
    2008     25959332 :                          && stop.numExpectedContainer == 0);
    2009              : 
    2010              :     bool unregister = false;
    2011     22192636 :     if (time > stop.endBoarding) {
    2012         1584 :         stop.triggered = false;
    2013         1584 :         stop.containerTriggered = false;
    2014         1584 :         if (myAmRegisteredAsWaiting) {
    2015              :             unregister = true;
    2016          328 :             myAmRegisteredAsWaiting = false;
    2017              :         }
    2018              :     }
    2019     22192636 :     if (boarded) {
    2020              :         // the triggering condition has been fulfilled. Maybe we want to wait a bit longer for additional riders (car pooling)
    2021         7532 :         if (myAmRegisteredAsWaiting) {
    2022              :             unregister = true;
    2023              :         }
    2024         7532 :         stop.triggered = false;
    2025         7532 :         myAmRegisteredAsWaiting = false;
    2026              :     }
    2027     22192636 :     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     22192636 :     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          920 : MSVehicle::joinTrainPart(MSVehicle* veh) {
    2048              :     // check if veh is close enough to be joined to the rear of this vehicle
    2049          920 :     MSLane* backLane = myFurtherLanes.size() == 0 ? myLane : myFurtherLanes.back();
    2050          920 :     double gap = getBackPositionOnLane() - veh->getPositionOnLane();
    2051         1141 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == veh->getLane()
    2052          950 :             && 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          905 :         return false;
    2063              :     }
    2064              : }
    2065              : 
    2066              : 
    2067              : bool
    2068          905 : MSVehicle::joinTrainPartFront(MSVehicle* veh) {
    2069              :     // check if veh is close enough to be joined to the front of this vehicle
    2070          905 :     MSLane* backLane = veh->myFurtherLanes.size() == 0 ? veh->myLane : veh->myFurtherLanes.back();
    2071          905 :     double gap = veh->getBackPositionOnLane(backLane) - getPositionOnLane();
    2072         1111 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == getLane()
    2073          929 :             && 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            7 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2112            7 :             myAmRegisteredAsWaiting = false;
    2113              :         }
    2114           21 :         return true;
    2115              :     } else {
    2116          881 :         return false;
    2117              :     }
    2118              : }
    2119              : 
    2120              : double
    2121      8970820 : MSVehicle::getBrakeGap(bool delayed) const {
    2122      8970820 :     return getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), delayed ? getCarFollowModel().getHeadwayTime() : 0);
    2123              : }
    2124              : 
    2125              : 
    2126              : bool
    2127    704572427 : MSVehicle::checkActionStep(const SUMOTime t) {
    2128    704572427 :     myActionStep = isActionStep(t);
    2129    704572427 :     if (myActionStep) {
    2130    633011044 :         myLastActionTime = t;
    2131              :     }
    2132    704572427 :     return myActionStep;
    2133              : }
    2134              : 
    2135              : 
    2136              : void
    2137         1467 : MSVehicle::resetActionOffset(const SUMOTime timeUntilNextAction) {
    2138         1467 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + timeUntilNextAction;
    2139         1467 : }
    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    704572427 : 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    704572427 :     if (hasDriverState()) {
    2179       451543 :         myDriverState->update();
    2180       903086 :         setActionStepLength(myDriverState->getDriverState()->getActionStepLength(), false);
    2181              :     }
    2182              : 
    2183    704572427 :     myStopSpeed = getCarFollowModel().maxNextSpeed(myStopSpeed, this);
    2184    704572427 :     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     71561383 :         removePassedDriveItems();
    2193     71561383 :         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    633011044 :         if (myInfluencer != nullptr) {
    2202       491573 :             myInfluencer->updateRemoteControlRoute(this);
    2203              :         }
    2204    633011044 :         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    633011044 :         checkRewindLinkLanes(lengthsInFront, myLFLinkLanes);
    2219    633011044 :         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    633011044 :         if (MSGlobals::gModelParkingManoeuver) {
    2223         2971 :             if (getManoeuvreType() == MSVehicle::MANOEUVRE_EXIT && manoeuvreIsComplete()) {
    2224           30 :                 setManoeuvreType(MSVehicle::MANOEUVRE_NONE);
    2225              :             }
    2226              :         }
    2227              :     }
    2228    633011044 :     myLaneChangeModel->resetChanged();
    2229              : }
    2230              : 
    2231              : 
    2232              : bool
    2233    174096260 : 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    174096260 :     const double futurePosLat = getLateralPositionOnLane() + (
    2239    174096260 :                                     lane != myLane && lane->isInternal() ? lane->getIncomingLanes()[0].viaLink->getLateralShift() : 0);
    2240    174096260 :     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      3099470 :                          && getVehicleType().getWidth() <= edgeWidth
    2245      3093865 :                          && link->getViaLane() == nullptr
    2246              :                          // this is the exit link of a junction. The normal edge should support the shadow
    2247      1506420 :                          && ((myLaneChangeModel->getShadowLane(link->getLane()) == nullptr)
    2248              :                              // the shadow lane must be permitted
    2249      1120350 :                              || !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      1059877 :                              || (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       467140 :                          && (myLaneChangeModel->getShadowLane() == nullptr
    2254       256451 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().size() == 0
    2255       239173 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().front()->getLane() != link->getLane())
    2256              :                          // emergency vehicles may do some crazy stuff
    2257    174501583 :                          && !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    174096260 :     return result;
    2271              : }
    2272              : 
    2273              : 
    2274              : 
    2275              : void
    2276    633011044 : MSVehicle::planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector& lfLinks, double& newStopDist, double& newStopSpeed, std::pair<double, const MSLink*>& nextTurn) const {
    2277              :     lfLinks.clear();
    2278    633011044 :     newStopDist = std::numeric_limits<double>::max();
    2279              :     //
    2280              :     const MSCFModel& cfModel = getCarFollowModel();
    2281    633011044 :     const double vehicleLength = getVehicleType().getLength();
    2282    633011044 :     const double maxV = cfModel.maxNextSpeed(myState.mySpeed, this);
    2283    633011044 :     const double maxVD = MAX2(getMaxSpeed(), MIN2(maxV, getDesiredMaxSpeed()));
    2284    633011044 :     const bool opposite = myLaneChangeModel->isOpposite();
    2285              :     // maxVD is possibly higher than vType-maxSpeed and in this case laneMaxV may be higher as well
    2286    633011044 :     double laneMaxV = myLane->getVehicleMaxSpeed(this, maxVD);
    2287    633011044 :     const double vMinComfortable = cfModel.minNextSpeed(getSpeed(), this);
    2288              :     double lateralShift = 0;
    2289    633011044 :     if (isRail()) {
    2290              :         // speed limits must hold for the whole length of the train
    2291      1790448 :         for (MSLane* l : myFurtherLanes) {
    2292       404395 :             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    633502585 :     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    633011044 :     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    633011044 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    2310          420 :         v = NUMERICAL_EPS_SPEED;
    2311              :     }
    2312              : 
    2313    633011044 :     if (myInfluencer != nullptr) {
    2314       491573 :         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       491573 :         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       491573 :         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    633011044 :     const double dist = SPEED2DIST(maxV) + cfModel.brakeGap(maxV);
    2335              : 
    2336    633011044 :     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    633011044 :     double seen = opposite ? myState.myPos : myLane->getLength() - myState.myPos;
    2347    633011044 :     nextTurn.first = seen;
    2348    633011044 :     nextTurn.second = nullptr;
    2349    633011044 :     bool encounteredTurn = (MSGlobals::gLateralResolution <= 0); // next turn is only needed for sublane
    2350              :     double seenNonInternal = 0;
    2351    633011044 :     double seenInternal = myLane->isInternal() ? seen : 0;
    2352    633011044 :     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    633011044 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : myLane;
    2359              :     assert(lane != 0);
    2360    633011044 :     const MSLane* leaderLane = myLane;
    2361    633011044 :     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    633011044 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    2369    633000654 :     if (v > vMinComfortable && hasStops() && myStops.front().pars.arrival >= 0 && sfp > 0
    2370         4279 :             && v > myLane->getSpeedLimit() * sfp
    2371    633014080 :             && !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   1217729335 :         if (opposite &&
    2380              :                 (leaderLane->getVehicleNumberWithPartials() > 1
    2381       103453 :                  || (leaderLane != myLane && leaderLane->getVehicleNumber() > 0))) {
    2382       397289 :             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       397289 :             const double backOffset = leaderLane == myLane ? getPositionOnLane() : leaderLane->getLength();
    2386       397289 :             const double gapOffset = leaderLane == myLane ? 0 : seen - leaderLane->getLength();
    2387       397289 :             const MSLeaderDistanceInfo cands = leaderLane->getFollowersOnConsecutive(this, backOffset, true, backOffset, MSLane::MinorLinkMode::FOLLOW_NEVER);
    2388       397289 :             MSLeaderDistanceInfo oppositeLeaders(leaderLane->getWidth(), this, 0.);
    2389       397289 :             const double minTimeToLeaveLane = MSGlobals::gSublane ? MAX2(TS, (0.5 *  myLane->getWidth() - getLateralPositionOnLane()) / getVehicleType().getMaxSpeedLat()) : TS;
    2390      1055541 :             for (int i = 0; i < cands.numSublanes(); i++) {
    2391       658252 :                 CLeaderDist cand = cands[i];
    2392       658252 :                 if (cand.first != 0) {
    2393       541151 :                     if ((cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() != leaderLane)
    2394       541622 :                             || (!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       351376 :                         oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - getVehicleType().getMinGap() + cand.first->getVehicleType().getMinGap() - cand.first->getVehicleType().getLength());
    2397              :                     } else {
    2398              :                         // avoid frontal collision
    2399       346716 :                         const bool assumeStopped = cand.first->isStopped() || cand.first->getWaitingSeconds() > 1;
    2400       189775 :                         const double predMaxDist = cand.first->getSpeed() + (assumeStopped ? 0 : cand.first->getCarFollowModel().getMaxAccel()) * minTimeToLeaveLane;
    2401       189775 :                         if (cand.second >= 0 && (cand.second - v * minTimeToLeaveLane - predMaxDist < 0 || assumeStopped)) {
    2402        44648 :                             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       397289 :             adaptToLeaderDistance(oppositeLeaders, 0, seen, lastLink, v, vLinkPass);
    2414       397289 :         } else {
    2415   1217332046 :             if (MSGlobals::gLateralResolution > 0 && myLaneChangeModel->getShadowLane() == nullptr) {
    2416    196705760 :                 const double rightOL = getRightSideOnLane(lane) + lateralShift;
    2417    196705760 :                 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    196705760 :                 if (rightOL < 0 || outsideLeft) {
    2425      1310262 :                     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      1310262 :                     if (outsideLeft) {
    2430       540450 :                         sublaneOffset = MIN2(-1, -(int)ceil((leftOL - lane->getWidth()) / MSGlobals::gLateralResolution));
    2431              :                     } else {
    2432       769812 :                         sublaneOffset = MAX2(1, (int)ceil(-rightOL / MSGlobals::gLateralResolution));
    2433              :                     }
    2434      1310262 :                     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      5429360 :                     for (const MSVehicle* cand : lane->getVehiclesSecure()) {
    2441      1484838 :                         if ((lane != myLane || cand->getPositionOnLane() > getPositionOnLane())
    2442      4750054 :                                 && ((!outsideLeft && cand->getLeftSideOnEdge() < 0)
    2443      3265128 :                                     || (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      1310262 :                     lane->releaseVehicles();
    2453      1310262 :                     if (outsideLeaders.hasVehicles()) {
    2454        26262 :                         adaptToLeaders(outsideLeaders, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2455              :                     }
    2456      1310262 :                 }
    2457              :             }
    2458   1217332046 :             adaptToLeaders(ahead, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2459              :         }
    2460   1217729335 :         if (lastLink != nullptr) {
    2461   1099796818 :             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   1217729335 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    2471              :             // also slow down for leaders on the shadowLane relative to the current lane
    2472      5035214 :             const MSLane* shadowLane = myLaneChangeModel->getShadowLane(leaderLane);
    2473              :             if (shadowLane != nullptr
    2474      5035214 :                     && (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      4479674 :                 if ((&shadowLane->getEdge() == &leaderLane->getEdge() || myLaneChangeModel->isOpposite())) {
    2478      4437077 :                     double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    2479      4437077 :                     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      4437077 :                     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      4437077 :                     if (myLaneChangeModel->isOpposite()) {
    2493              :                         // ignore oncoming vehicles on the shadow lane
    2494       138584 :                         shadowLeaders.removeOpposite(shadowLane);
    2495              :                     }
    2496      4437077 :                     const double turningDifference = MAX2(0.0, leaderLane->getLength() - shadowLane->getLength());
    2497      4437077 :                     adaptToLeaders(shadowLeaders, latOffset, seen - turningDifference, lastLink, shadowLane, v, vLinkPass);
    2498      4479674 :                 } 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   1217729335 :         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   1217729335 :         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   1217729335 :         if (!opposite && lane->getEdge().hasLaneChanger()) {
    2567    593611589 :             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    593691817 :             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     66141004 :                 && ((&stopIt->lane->getEdge() == &lane->getEdge())
    2580     33330313 :                     || (stopIt->isOpposite && stopIt->lane->getEdge().getOppositeEdge() == &lane->getEdge()))
    2581              :                 // ignore stops that occur later in a looped route
    2582   1273462233 :                 && stopIt->edge == myCurrEdge + view) {
    2583     32755565 :             double stopDist = std::numeric_limits<double>::max();
    2584              :             const MSStop& stop = *stopIt;
    2585              :             const bool isFirstStop = stopIt == myStops.begin();
    2586              :             stopIt++;
    2587     32755565 :             if (!stop.reached || (stop.getSpeed() > 0 && keepStopping())) {
    2588              :                 // we are approaching a stop on the edge; must not drive further
    2589     15006948 :                 bool isWaypoint = stop.getSpeed() > 0;
    2590     15006948 :                 double endPos = stop.getEndPos(*this) + NUMERICAL_EPS;
    2591     15006948 :                 if (stop.parkingarea != nullptr) {
    2592              :                     // leave enough space so parking vehicles can exit
    2593      1655343 :                     const double brakePos = getBrakeGap() + lane->getLength() - seen;
    2594      1655343 :                     endPos = stop.parkingarea->getLastFreePosWithReservation(t, *this, brakePos);
    2595     13351605 :                 } else if (isWaypoint && !stop.reached) {
    2596       107829 :                     endPos = stop.pars.startPos;
    2597              :                 }
    2598     15006948 :                 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     15006948 :                 if (isWaypoint) {
    2606              :                     bool waypointWithStop = false;
    2607       123375 :                     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       123375 :                     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       108573 :                         stopSpeed = MIN2(MAX2(cfModel.freeSpeed(this, getSpeed(), stopDist, stop.getSpeed()), vMinComfortable), stopSpeed);
    2639       108573 :                         if (!stop.reached) {
    2640       108573 :                             stopDist += stop.pars.endPos - stop.pars.startPos;
    2641              :                         }
    2642       108573 :                         if (lastLink != nullptr) {
    2643        66550 :                             lastLink->adaptLeaveSpeed(cfModel.freeSpeed(this, vLinkPass, endPos, stop.getSpeed(), false, MSCFModel::CalcReason::FUTURE));
    2644              :                         }
    2645              :                     }
    2646              :                 } else {
    2647     14883573 :                     stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist);
    2648     14883573 :                     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     14883573 :                     if (lastLink != nullptr) {
    2658      9204675 :                         lastLink->adaptLeaveSpeed(cfModel.stopSpeed(this, vLinkPass, endPos, MSCFModel::CalcReason::FUTURE));
    2659              :                     }
    2660              :                 }
    2661     15006948 :                 if (stopSpeed < getSpeed() && getSpeed() > SUMO_const_haltingSpeed) {
    2662              :                     // only discount braking-for-stop timeLoss if we are actually braking
    2663       615595 :                     newStopSpeed = MIN2(newStopSpeed, stopSpeed);
    2664     14699064 :                 } else if (getSpeed() < SUMO_const_haltingSpeed) {
    2665              :                     // blocked from entering a stop
    2666      7796438 :                     newStopSpeed = std::numeric_limits<double>::max();
    2667              :                 }
    2668     15006948 :                 v = MIN2(v, stopSpeed);
    2669     15006948 :                 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     15006948 :                 if (isFirstStop) {
    2684     10248471 :                     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     10248471 :                     if (!isWaypoint) {
    2688              :                         planningToStop = true;
    2689     10160471 :                         if (!isRail()) {
    2690      9836519 :                             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   1207892816 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2705   1207892816 :         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       193946 :             for (const LaneQ& preb : getBestLanes()) {
    2710       127553 :                 if (preb.allowsContinuation &&
    2711              :                         (bestJump == nullptr
    2712         3042 :                          || abs(currentIndex - preb.lane->getIndex()) < abs(currentIndex - bestJump->getIndex()))) {
    2713        67393 :                     bestJump = preb.lane;
    2714              :                 }
    2715              :             }
    2716        66393 :             if (bestJump != nullptr) {
    2717        66393 :                 const MSEdge* nextEdge = *(myCurrEdge + 1);
    2718       122734 :                 for (auto cand_it = bestJump->getLinkCont().begin(); cand_it != bestJump->getLinkCont().end(); cand_it++) {
    2719       117354 :                     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   1207892816 :         if (!encounteredTurn) {
    2729    190260840 :             if (!lane->isLinkEnd(link) && lane->getLinkCont().size() > 1) {
    2730     19900051 :                 LinkDirection linkDir = (*link)->getDirection();
    2731     19900051 :                 switch (linkDir) {
    2732              :                     case LinkDirection::STRAIGHT:
    2733              :                     case LinkDirection::NODIR:
    2734              :                         break;
    2735      7838111 :                     default:
    2736      7838111 :                         nextTurn.first = seen;
    2737      7838111 :                         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   2081511064 :         if (myCurrEdge + view + 1 == myRoute->end()
    2751   1207892816 :                 || (myParameter->arrivalEdge >= 0 && getRoutePosition() + view == myParameter->arrivalEdge)) {
    2752    334274568 :             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    334274568 :             const double distToArrival = seen + myArrivalPos - lane->getLength() - SPEED2DIST(arrivalSpeed);
    2757    334274568 :             const double va = MAX2(NUMERICAL_EPS, cfModel.freeSpeed(this, getSpeed(), distToArrival, arrivalSpeed));
    2758    334274568 :             v = MIN2(v, va);
    2759    334274568 :             if (lastLink != nullptr) {
    2760              :                 lastLink->adaptLeaveSpeed(va);
    2761              :             }
    2762    334274568 :             lfLinks.push_back(DriveProcessItem(v, seen, lane->getEdge().isFringe() ? 1000 : 0));
    2763    334274568 :             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    864599536 :                 || (MSGlobals::gSublane && brakeForOverlap(*link, lane))
    2768   1737865392 :                 || (opposite && (*link)->getViaLaneOrLane()->getParallelOpposite() == nullptr
    2769       212488 :                     && !myLaneChangeModel->hasBlueLight())) {
    2770      9623243 :             double va = cfModel.stopSpeed(this, getSpeed(), seen);
    2771      9623243 :             if (lastLink != nullptr) {
    2772              :                 lastLink->adaptLeaveSpeed(va);
    2773              :             }
    2774      9623243 :             if (myLaneChangeModel->getCommittedSpeed() > 0) {
    2775       373512 :                 v = MIN2(myLaneChangeModel->getCommittedSpeed(), v);
    2776              :             } else {
    2777     17966834 :                 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      9623243 :             if (lane->isLinkEnd(link)) {
    2787      9018712 :                 lfLinks.emplace_back(v, seen);
    2788              :                 break;
    2789              :             }
    2790              :         }
    2791    864599536 :         lateralShift += (*link)->getLateralShift();
    2792    864599536 :         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    864599536 :         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    864599536 :         const double stopDecel = yellowOrRed && !isRail() ? MAX2(MIN2(MSGlobals::gTLSYellowMinDecel, cfModel.getEmergencyDecel()), cfModel.getMaxDecel()) : cfModel.getMaxDecel();
    2805    864599536 :         const double brakeDist = cfModel.brakeGap(myState.mySpeed, stopDecel, 0);
    2806    864599536 :         const bool canBrakeBeforeLaneEnd = seen >= brakeDist;
    2807    864599536 :         const bool canBrakeBeforeStopLine = seen - lane->getVehicleStopOffset(this) >= brakeDist;
    2808    864599536 :         if (yellowOrRed) {
    2809              :             // Wait at red traffic light with full distance if possible
    2810              :             laneStopOffset = majorStopOffset;
    2811    803079260 :         } else if ((*link)->havePriority()) {
    2812              :             // On priority link, we should never stop below visibility distance
    2813    758245636 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, majorStopOffset);
    2814              :         } else {
    2815     44833624 :             double minorStopOffset = MAX2(lane->getVehicleStopOffset(this),
    2816     44833624 :                                           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     44833624 :             if ((*link)->getState() == LINKSTATE_ALLWAY_STOP) {
    2823      1425260 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, 0));
    2824              :             } else {
    2825     43408364 :                 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     44833624 :             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    864599536 :         if (canBrakeBeforeLaneEnd) {
    2836              :             // avoid emergency braking if possible
    2837    837203908 :             laneStopOffset = MIN2(laneStopOffset, seen - brakeDist);
    2838              :         }
    2839              :         laneStopOffset = MAX2(POSITION_EPS, laneStopOffset);
    2840    864599536 :         double stopDist = MAX2(0., seen - laneStopOffset);
    2841     61520276 :         if (yellowOrRed && getDevice(typeid(MSDevice_GLOSA)) != nullptr
    2842          508 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->getOverrideSafety()
    2843    864599536 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->isSpeedAdviceActive()) {
    2844              :             stopDist = std::numeric_limits<double>::max();
    2845              :         }
    2846    864599536 :         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    864599536 :         if (isRail()
    2856    864599536 :                 && !lane->isInternal()) {
    2857              :             // check for train direction reversal
    2858      3231517 :             if (lane->getBidiLane() != nullptr
    2859      3231517 :                     && (*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      6463034 :             foundRailSignal |= ((*link)->getTLLogic() != nullptr
    2868       744958 :                                 && (*link)->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL
    2869      3924434 :                                 && seen > SPEED2DIST(v));
    2870              :         }
    2871              : 
    2872    864599536 :         bool canReverseEventually = false;
    2873    864599536 :         const double vReverse = checkReversal(canReverseEventually, laneMaxV, seen);
    2874    864599536 :         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    864599536 :         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    864599536 :         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    864599536 :         const bool abortRequestAfterMinor = slowedDownForMinor && (*link)->getInternalLaneBefore() == nullptr;
    2912              :         // - even if red, if we cannot break we should issue a request
    2913    864599536 :         bool setRequest = (v > NUMERICAL_EPS_SPEED && !abortRequestAfterMinor) || (leavingCurrentIntersection);
    2914              : 
    2915    864599536 :         double stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist, stopDecel, MSCFModel::CalcReason::CURRENT_WAIT);
    2916    864599536 :         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    864599536 :         if (yellowOrRed && canBrakeBeforeStopLine && !ignoreRed(*link, canBrakeBeforeStopLine) && seen >= mustSeeBeforeReversal) {
    2936     61458367 :             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     61458367 :             const SUMOTime arrivalTime = getArrivalTime(t, seen, v, vLinkPass);
    2941              :             // the vehicle is able to brake in front of a yellow/red traffic light
    2942     61458367 :             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     61458367 :             break;
    2945              :         }
    2946              : 
    2947    803141169 :         const MSLink* entryLink = (*link)->getCorrespondingEntryLink();
    2948    803141169 :         if (entryLink->haveRed() && ignoreRed(*link, canBrakeBeforeStopLine) && STEPS2TIME(t - entryLink->getLastStateChange()) > 2) {
    2949              :             // restrict speed when ignoring a red light
    2950       118310 :             const double redSpeed = MIN2(v, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_RED_SPEED, v));
    2951       118310 :             const double va = MAX2(redSpeed, cfModel.freeSpeed(this, getSpeed(), seen, redSpeed));
    2952       236172 :             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    803141169 :         checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2964              : 
    2965    803141169 :         if (lastLink != nullptr) {
    2966              :             lastLink->adaptLeaveSpeed(laneMaxV);
    2967              :         }
    2968    803141169 :         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    803141169 :         const double visibilityDistance = (*link)->getFoeVisibilityDistance();
    2975    803141169 :         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    803141169 :         const bool couldBrakeForMinor = !(*link)->havePriority() && brakeDist < seen && !(*link)->lastWasContMajor();
    2987     44306634 :         if (couldBrakeForMinor && !determinedFoePresence) {
    2988              :             // vehicle decelerates just enough to be able to stop if necessary and then accelerates
    2989     41525626 :             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     41525626 :             double maxArrivalSpeed = cfModel.estimateSpeedAfterDistance(visibilityDistance, maxSpeedAtVisibilityDist, cfModel.getMaxAccel());
    2992     41525626 :             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    761615543 :         } 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    803141169 :         const SUMOTime arrivalTime = getArrivalTime(t, seen, v, arrivalSpeed);
    3024    803141169 :         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    803141169 :         const double bGap = cfModel.brakeGap(v);
    3044    803141169 :         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     56775909 :             if (MSGlobals::gSemiImplicitEulerUpdate) {
    3047     54061482 :                 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      2714427 :                 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   1189886690 :         const double estimatedLeaveSpeed = MIN2((*link)->getViaLaneOrLane()->getVehicleMaxSpeed(this, maxVD),
    3059    803141169 :                                                 getCarFollowModel().estimateSpeedAfterDistance((*link)->getLength(), arrivalSpeed, getVehicleType().getCarFollowModel().getMaxAccel()));
    3060    803141169 :         lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, setRequest,
    3061              :                                            arrivalTime, arrivalSpeed,
    3062              :                                            arrivalSpeedBraking,
    3063              :                                            seen, estimatedLeaveSpeed));
    3064    803141169 :         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    829468356 :         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    584929129 :         laneMaxV = lane->getVehicleMaxSpeed(this, maxVD);
    3082    585330201 :         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    584929129 :         const double va = MAX2(cfModel.freeSpeed(this, getSpeed(), seen, laneMaxV), vMinComfortable - NUMERICAL_EPS);
    3090   1160075762 :         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    584929129 :         if (lane->getEdge().isInternal()) {
    3097    255340978 :             seenInternal += lane->getLength();
    3098              :         } else {
    3099    329588151 :             seenNonInternal += lane->getLength();
    3100              :         }
    3101              :         // do not restrict results to the current vehicle to allow caching for the current time step
    3102    584929129 :         leaderLane = opposite ? lane->getParallelOpposite() : lane;
    3103    584929129 :         if (leaderLane == nullptr) {
    3104              : 
    3105              :             break;
    3106              :         }
    3107   1169436582 :         ahead = opposite ? MSLeaderInfo(leaderLane->getWidth()) : leaderLane->getLastVehicleInformation(nullptr, 0);
    3108    584718291 :         seen += lane->getLength();
    3109   1169436582 :         vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(lane->getLength(), v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    3110              :         lastLink = &lfLinks.back();
    3111    584718291 :     }
    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    633011044 : }
    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    864599536 : MSVehicle::getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const {
    3170              :     const MSCFModel& cfModel = getCarFollowModel();
    3171              :     SUMOTime arrivalTime;
    3172    864599536 :     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    807780419 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, v, arrivalSpeed);
    3177              :     } else {
    3178     56819117 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, myState.mySpeed, arrivalSpeed);
    3179              :     }
    3180    864599536 :     if (isStopped()) {
    3181     12061293 :         arrivalTime += MAX2((SUMOTime)0, myStops.front().duration);
    3182              :     }
    3183    864599536 :     return arrivalTime;
    3184              : }
    3185              : 
    3186              : 
    3187              : void
    3188   1222755121 : 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   1222755121 :     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   2997141475 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3216   1774386354 :         const MSVehicle* pred = ahead[sublane];
    3217   1774386354 :         if (pred != nullptr && pred != this) {
    3218              :             // @todo avoid multiple adaptations to the same leader
    3219   1294808220 :             const double predBack = pred->getBackPositionOnLane(lane);
    3220              :             double gap = (lastLink == nullptr
    3221   1855278962 :                           ? predBack - myState.myPos - getVehicleType().getMinGap()
    3222    560470742 :                           : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3223              :             bool oncoming = false;
    3224   1294808220 :             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   1294781225 :             } else if (pred->getLaneChangeModel().isOpposite() && pred->getLaneChangeModel().getShadowLane() != lane) {
    3237              :                 // must react to stopped / dangerous oncoming vehicles
    3238       188250 :                 gap += -pred->getVehicleType().getLength() + getVehicleType().getMinGap() - MAX2(getVehicleType().getMinGap(), pred->getVehicleType().getMinGap());
    3239              :                 // try to avoid collision in the next second
    3240       188250 :                 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       188250 :                 if (gap < predMaxDist + getSpeed() || pred->getLane() == lane->getBidiLane()) {
    3247        20607 :                     gap -= predMaxDist;
    3248              :                 }
    3249   1294592975 :             } 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   1294252918 :                 adaptToLeader(std::make_pair(pred, gap), seen, lastLink, v, vLinkPass);
    3262              :             }
    3263              :         }
    3264              :     }
    3265   1222755121 : }
    3266              : 
    3267              : void
    3268       427852 : 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       427852 :     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      1048621 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3285       620769 :         CLeaderDist predDist = ahead[sublane];
    3286       620769 :         const MSVehicle* pred = predDist.first;
    3287       620769 :         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       391104 :             adaptToLeader(predDist, seen, lastLink, v, vLinkPass);
    3294              :         }
    3295              :     }
    3296       427852 : }
    3297              : 
    3298              : 
    3299              : void
    3300   1294644022 : MSVehicle::adaptToLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3301              :                          double seen,
    3302              :                          DriveProcessItem* const lastLink,
    3303              :                          double& v, double& vLinkPass) const {
    3304   1294644022 :     if (leaderInfo.first != 0) {
    3305   1294644022 :         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   1294643216 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3316              :             vsafeLeader = -std::numeric_limits<double>::max();
    3317              :         }
    3318              :         bool backOnRoute = true;
    3319   1294643216 :         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       292115 :             if (leaderInfo.first->getBackLane() == current) {
    3326              :                 backOnRoute = true;
    3327              :             } else {
    3328       661421 :                 for (MSLane* lane : getBestLanesContinuation()) {
    3329       582366 :                     if (lane == current) {
    3330              :                         break;
    3331              :                     }
    3332       435065 :                     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       226356 :             if (!backOnRoute) {
    3343       124496 :                 double stopDist = seen - current->getLength() - POSITION_EPS;
    3344       124496 :                 if (lastLink->myLink->getInternalLaneBefore() != nullptr) {
    3345              :                     // do not drive onto the junction conflict area
    3346       107861 :                     stopDist -= lastLink->myLink->getInternalLaneBefore()->getLength();
    3347              :                 }
    3348       124496 :                 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), stopDist);
    3349              :             }
    3350              :         }
    3351       190255 :         if (backOnRoute) {
    3352   1294518720 :             vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3353              :         }
    3354   1294643216 :         if (lastLink != nullptr) {
    3355    560423407 :             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   1294643216 :         v = MIN2(v, vsafeLeader);
    3364   2230238929 :         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     18839933 : 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     18839933 :     if (leaderInfo.first != 0) {
    3391     18839933 :         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     18839922 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3402              :             vsafeLeader = -std::numeric_limits<double>::max();
    3403              :         }
    3404     18839922 :         if (leaderInfo.second >= 0) {
    3405     15853720 :             if (hasDeparted()) {
    3406     15848367 :                 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      2986202 :         } else if (leaderInfo.first != this) {
    3412              :             // the leading, in-lapping vehicle is occupying the complete next lane
    3413              :             // stop before entering this lane
    3414      2564092 :             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     18839922 :         if (distToCrossing >= 0) {
    3427              :             // can the leader still stop in the way?
    3428      6096400 :             const double vStop = cfModel.stopSpeed(this, getSpeed(), distToCrossing - getVehicleType().getMinGap());
    3429      6096400 :             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      5685609 :             } 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      5629217 :                 const double leaderDistToCrossing = distToCrossing - leaderInfo.second;
    3451              :                 // estimate the time at which the leader has gone past the crossing point
    3452      5629217 :                 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      5629217 :                 const double vFinal = MAX2(getSpeed(), 2 * (distToCrossing - getVehicleType().getMinGap()) / leaderPastCPTime - getSpeed());
    3457      5629217 :                 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     18429131 :         if (lastLink != nullptr) {
    3472              :             lastLink->adaptLeaveSpeed(vsafeLeader);
    3473              :         }
    3474     18839922 :         v = MIN2(v, vsafeLeader);
    3475     35124089 :         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    803190531 : MSVehicle::checkLinkLeaderCurrentAndParallel(const MSLink* link, const MSLane* lane, double seen,
    3569              :         DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest) const {
    3570    803190531 :     if (MSGlobals::gUsingInternalLanes && (myInfluencer == nullptr || myInfluencer->getRespectJunctionLeaderPriority())) {
    3571              :         // we want to pass the link but need to check for foes on internal lanes
    3572    803081377 :         checkLinkLeader(link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    3573    803081377 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    3574      3162336 :             const MSLink* const parallelLink = link->getParallelLink(myLaneChangeModel->getShadowDirection());
    3575      3162336 :             if (parallelLink != nullptr) {
    3576      2190229 :                 checkLinkLeader(parallelLink, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest, true);
    3577              :             }
    3578              :         }
    3579              :     }
    3580              : 
    3581    803190531 : }
    3582              : 
    3583              : void
    3584    805518057 : 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    805518057 :     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    825355499 :     for (MSLink::LinkLeaders::const_iterator it = linkLeaders.begin(); it != linkLeaders.end(); ++it) {
    3599              :         // the vehicle to enter the junction first has priority
    3600     19837442 :         const MSVehicle* leader = (*it).vehAndGap.first;
    3601     19837442 :         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     19414636 :         } else if (isLeader(link, leader, (*it).vehAndGap.second) || (*it).inTheWay()) {
    3628     19348786 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3629     19348786 :                     && 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         2181 :                 continue;
    3636              :             }
    3637     26367203 :             if (MSGlobals::gLateralResolution > 0 &&
    3638              :                     // sibling link (XXX: could also be partial occupator where this check fails)
    3639      7020598 :                     &leader->getLane()->getEdge() == &lane->getEdge()) {
    3640              :                 // check for sublane obstruction (trivial for sibling link leaders)
    3641              :                 const MSLane* conflictLane = link->getInternalLaneBefore();
    3642       959736 :                 MSLeaderInfo linkLeadersAhead = MSLeaderInfo(conflictLane->getWidth());
    3643       959736 :                 linkLeadersAhead.addLeader(leader, false, 0); // assume sibling lane has the same geometry as the leader lane
    3644       959736 :                 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       959736 :                 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       959736 :             } 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     18386869 :                 adaptToJunctionLeader(it->vehAndGap, seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3672              :             }
    3673     19346605 :             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     37182890 :                 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     19346605 :             if (v < SUMO_const_haltingSpeed
    3681              :                     //&& leader->getSpeed() < SUMO_const_haltingSpeed
    3682     19346605 :                     && (leader->getLane()->getLogicalPredecessorLane() == myLane->getLogicalPredecessorLane()
    3683     10636012 :                         || leader->getLane()->getLogicalPredecessorLane() == myLane
    3684      8508969 :                         || leader->isStopped()
    3685      8430459 :                         || leader->getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME))) {
    3686      4338314 :                 setRequest = false;
    3687              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3688              :                 if (DEBUG_COND) {
    3689              :                     std::cout << "   aborting request\n";
    3690              :                 }
    3691              : #endif
    3692      4338314 :                 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      2114953 :                     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    805518057 :     vLinkWait = MIN2(vLinkWait, v);
    3718    805518057 : }
    3719              : 
    3720              : 
    3721              : double
    3722     99295300 : MSVehicle::getDeltaPos(const double accel) const {
    3723     99295300 :     double vNext = myState.mySpeed + ACCEL2SPEED(accel);
    3724     99295300 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3725              :         // apply implicit Euler positional update
    3726            0 :         return SPEED2DIST(MAX2(vNext, 0.));
    3727              :     } else {
    3728              :         // apply ballistic update
    3729     99295300 :         if (vNext >= 0) {
    3730              :             // assume constant acceleration during this time step
    3731     98659628 :             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       635672 :             return -SPEED2DIST(0.5 * myState.mySpeed * myState.mySpeed / ACCEL2SPEED(accel));
    3739              :         }
    3740              :     }
    3741              : }
    3742              : 
    3743              : void
    3744    633011031 : 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    633011031 :     myHaveToWaitOnNextLink = false;
    3751              :     bool canBrakeVSafeMin = false;
    3752              : 
    3753              :     // Get safe velocities from DriveProcessItems.
    3754              :     assert(myLFLinkLanes.size() != 0 || isRemoteControlled());
    3755   1269595181 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    3756   1095909340 :         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   1095909340 :         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    657823584 :             const bool canBrake = (dpi.myDistance > cfModel.brakeGap(myState.mySpeed, cfModel.getMaxDecel(), 0.)
    3780    657823584 :                                    || (MSGlobals::gSemiImplicitEulerUpdate && myState.mySpeed < ACCEL2SPEED(cfModel.getMaxDecel())));
    3781              :             assert(link->getLaneBefore() != nullptr);
    3782    657823584 :             const bool beyondStopLine = dpi.myDistance < link->getLaneBefore()->getVehicleStopOffset(this);
    3783    657823584 :             const bool ignoreRedLink = ignoreRed(link, canBrake) || beyondStopLine;
    3784    657823584 :             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     21239434 :                 break;
    3793              :             }
    3794    657823574 :             const bool influencerPrio = (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority());
    3795              :             MSLink::BlockingFoes collectFoes;
    3796    657823574 :             bool opened = (yellow || influencerPrio
    3797   1973145482 :                            || link->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3798    657660954 :                                            getVehicleType().getLength(),
    3799    630287973 :                                            canBrake ? getImpatience() : 1,
    3800              :                                            cfModel.getMaxDecel(),
    3801    657660954 :                                            getWaitingTimeFor(link), getLateralPositionOnLane(),
    3802              :                                            ls == LINKSTATE_ZIPPER ? &collectFoes : nullptr,
    3803    657660954 :                                            ignoreRedLink, this, dpi.myDistance));
    3804    652140352 :             if (opened && myLaneChangeModel->getShadowLane() != nullptr) {
    3805      1966845 :                 const MSLink* const parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    3806      1966845 :                 if (parallelLink != nullptr) {
    3807      1222709 :                     const double shadowLatPos = getLateralPositionOnLane() - myLaneChangeModel->getShadowDirection() * 0.5 * (
    3808      1222709 :                                                     myLane->getWidth() + myLaneChangeModel->getShadowLane()->getWidth());
    3809      2444672 :                     opened = yellow || influencerPrio || (opened && parallelLink->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3810      1221963 :                                                           getVehicleType().getLength(), getImpatience(),
    3811              :                                                           cfModel.getMaxDecel(),
    3812              :                                                           getWaitingTimeFor(link), shadowLatPos, nullptr,
    3813      1221963 :                                                           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    657823574 :             bool determinedFoePresence = dpi.myDistance <= visibilityDistance;
    3842    657823574 :             if (opened && !influencerPrio && !link->havePriority() && !link->lastWasContMajor() && !link->isCont() && !ignoreRedLink) {
    3843     17848256 :                 if (!determinedFoePresence && (canBrake || !yellow)) {
    3844     16862919 :                     vSafe = dpi.myVLinkWait;
    3845     16862919 :                     myHaveToWaitOnNextLink = true;
    3846              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3847              :                     if (DEBUG_COND) {
    3848              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (minor)\n";
    3849              :                     }
    3850              : #endif
    3851     16862919 :                     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       985337 :                     vSafeMinDist = dpi.myDistance; // distance that must be covered
    3865       985337 :                     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3866      1797826 :                         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    640960655 :             if (opened) {
    3880    635256512 :                 vSafe = dpi.myVLinkPass;
    3881    635256512 :                 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     55421496 :                     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    635256512 :                 if (link->mustStop() && determinedFoePresence && myHaveStoppedFor == nullptr) {
    3891        20820 :                     myHaveStoppedFor = link;
    3892              :                 }
    3893      5704143 :             } else if (link->getState() == LINKSTATE_ZIPPER) {
    3894      1327404 :                 vSafeZipper = MIN2(vSafeZipper,
    3895      1327404 :                                    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      4377625 :                        && 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          234 :                 vSafe = dpi.myVLinkPass;
    3907              :             } else {
    3908      4376505 :                 vSafe = dpi.myVLinkWait;
    3909      4376505 :                 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      4376505 :                 break;
    3921              :             }
    3922    636584150 :             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        79641 :                 myJunctionEntryTime = SIMSTEP;;
    3926              :             }
    3927    657823574 :         } else {
    3928    438085756 :             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       262321 :                 myJunctionEntryTime = SUMOTime_MAX;
    3937       262321 :                 myJunctionConflictEntryTime = SUMOTime_MAX;
    3938              :             }
    3939              :             // we have: i->link == 0 || !i->setRequest
    3940    438085756 :             vSafe = dpi.myVLinkWait;
    3941    438085756 :             if (link != nullptr || myStopDist < (myLane->getLength() - getPositionOnLane())) {
    3942    107582748 :                 if (vSafe < getSpeed()) {
    3943     16291228 :                     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     91291520 :                 } else if (vSafe < SUMO_const_haltingSpeed) {
    3950     63843609 :                     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    334925871 :             if (link == nullptr && myLFLinkLanes.size() == 1
    3959    265367834 :                     && getBestLanesContinuation().size() > 1
    3960      1130485 :                     && getBestLanesContinuation()[1]->hadPermissionChanges()
    3961    438222803 :                     && myLane->getFirstAnyVehicle() == this) {
    3962              :                 // temporal lane closing without notification, visible to the
    3963              :                 // vehicle at the front of the queue
    3964        35330 :                 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    633011031 :     if ((MSGlobals::gSemiImplicitEulerUpdate && vSafe + NUMERICAL_EPS < vSafeMin)
    3986    632789023 :             || (!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       263187 :         if (canBrakeVSafeMin && vSafe < getSpeed()) {
    3995              :             // cannot drive across a link so we need to stop before it
    3996       127596 :             vSafe = MIN2(vSafe, MAX2(getCarFollowModel().minNextSpeed(getSpeed(), this),
    3997        63798 :                                      getCarFollowModel().stopSpeed(this, getSpeed(), vSafeMinDist)));
    3998        63798 :             vSafeMin = 0;
    3999        63798 :             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       199389 :             vSafeMin = vSafe;
    4012              :         }
    4013              :     }
    4014              : 
    4015              :     // vehicles inside a roundabout should maintain their requests
    4016    633011031 :     if (myLane->getEdge().isRoundabout()) {
    4017      2682137 :         myHaveToWaitOnNextLink = false;
    4018              :     }
    4019              : 
    4020    633011031 :     vSafe = MIN2(vSafe, vSafeZipper);
    4021    633011031 : }
    4022              : 
    4023              : 
    4024              : double
    4025    700806438 : MSVehicle::processTraCISpeedControl(double vSafe, double vNext) {
    4026    700806438 :     if (myInfluencer != nullptr) {
    4027       496362 :         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       496362 :         if (myInfluencer->isRemoteControlled()) {
    4035         7319 :             vNext = myInfluencer->implicitSpeedRemote(this, myState.mySpeed);
    4036              :         }
    4037       496362 :         const double vMax = getVehicleType().getCarFollowModel().maxNextSpeed(myState.mySpeed, this);
    4038       496362 :         double vMin = getVehicleType().getCarFollowModel().minNextSpeed(myState.mySpeed, this);
    4039       496362 :         if (MSGlobals::gSemiImplicitEulerUpdate) {
    4040              :             vMin = MAX2(0., vMin);
    4041              :         }
    4042       496362 :         vNext = myInfluencer->influenceSpeed(MSNet::getInstance()->getCurrentTimeStep(), vNext, vSafe, vMin, vMax);
    4043       496362 :         if (keepStopping() && myStops.front().getSpeed() == 0) {
    4044              :             // avoid driving while stopped (unless it's actually a waypoint
    4045         3819 :             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    700806438 :     return vNext;
    4054              : }
    4055              : 
    4056              : 
    4057              : void
    4058     71561383 : 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     71886130 :     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     71561383 :     myLFLinkLanes.erase(myLFLinkLanes.begin(), myNextDriveItem);
    4107     71561383 :     myNextDriveItem = myLFLinkLanes.begin();
    4108     71561383 : }
    4109              : 
    4110              : 
    4111              : void
    4112      1138173 : 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      1138173 :     if (myLFLinkLanes.size() == 0) {
    4128              :         // nothing to update
    4129              :         return;
    4130              :     }
    4131              :     const MSLink* nextPlannedLink = nullptr;
    4132              : //    auto i = myLFLinkLanes.begin();
    4133      1138171 :     auto i = myNextDriveItem;
    4134      2276297 :     while (i != myLFLinkLanes.end() && nextPlannedLink == nullptr) {
    4135      1138126 :         nextPlannedLink = i->myLink;
    4136              :         ++i;
    4137              :     }
    4138              : 
    4139      1138171 :     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       557886 :     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       547908 :     const MSLink* parallelLink = nextPlannedLink->getParallelLink(1);
    4160       547908 :     if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4161              :         // lcDir = 1;
    4162              :     } else {
    4163       265890 :         parallelLink = nextPlannedLink->getParallelLink(-1);
    4164       265890 :         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        72755 :             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       475153 :     DriveItemVector::iterator driveItemIt = myNextDriveItem;
    4183              :     // In the loop below, lane holds the currently considered lane on the vehicles continuation (including internal lanes)
    4184       475153 :     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       475153 :     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      1775493 :     while (driveItemIt != myLFLinkLanes.end()) {
    4191      1329027 :         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       172458 :             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      1156569 :         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      1127882 :         const MSLane* const target = *bestLaneIt;
    4219              :         assert(!target->isInternal());
    4220              :         newLink = nullptr;
    4221      1243288 :         for (MSLink* const link : lane->getLinkCont()) {
    4222      1243288 :             if (link->getLane() == target) {
    4223              :                 newLink = link;
    4224              :                 break;
    4225              :             }
    4226              :         }
    4227              : 
    4228      1127882 :         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      1127882 :         newLink->setApproaching(this, driveItemIt->myLink->getApproaching(this));
    4247      1127882 :         driveItemIt->myLink->removeApproaching(this);
    4248      1127882 :         driveItemIt->myLink = newLink;
    4249              :         lane = newLink->getViaLaneOrLane();
    4250              :         ++driveItemIt;
    4251      1127882 :         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    700806438 : 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    700806438 :     double pseudoFriction = (0.05 +  0.005 * getSpeed()) * getSpeed();
    4277    700806438 :     bool brakelightsOn = vNext < getSpeed() - ACCEL2SPEED(pseudoFriction);
    4278              : 
    4279    700806438 :     if (vNext <= SUMO_const_haltingSpeed) {
    4280              :         brakelightsOn = true;
    4281              :     }
    4282    700806438 :     if (brakelightsOn && !isStopped()) {
    4283              :         switchOnSignal(VEH_SIGNAL_BRAKELIGHT);
    4284              :     } else {
    4285              :         switchOffSignal(VEH_SIGNAL_BRAKELIGHT);
    4286              :     }
    4287    700806438 : }
    4288              : 
    4289              : 
    4290              : void
    4291    700873226 : MSVehicle::updateWaitingTime(double vNext) {
    4292    700873226 :     if (vNext <= SUMO_const_haltingSpeed && (!isStopped() || isIdling()) && myAcceleration <= accelThresholdForWaiting())  {
    4293     91590790 :         myWaitingTime += DELTA_T;
    4294     91590790 :         myWaitingTimeCollector.passTime(DELTA_T, true);
    4295              :     } else {
    4296    609282436 :         myWaitingTime = 0;
    4297    609282436 :         myWaitingTimeCollector.passTime(DELTA_T, false);
    4298    609282436 :         if (hasInfluencer()) {
    4299       271548 :             getInfluencer().setExtraImpatience(0);
    4300              :         }
    4301              :     }
    4302    700873226 : }
    4303              : 
    4304              : 
    4305              : void
    4306    700806292 : MSVehicle::updateTimeLoss(double vNext) {
    4307              :     // update time loss (depends on the updated edge)
    4308    700806292 :     if (!isStopped()) {
    4309              :         // some cfModels (i.e. EIDM may drive faster than predicted by maxNextSpeed)
    4310    689896420 :         const double vmax = MIN2(myLane->getVehicleMaxSpeed(this), MAX2(myStopSpeed, vNext));
    4311    686749593 :         if (vmax > 0) {
    4312    686740650 :             myTimeLoss += TS * (vmax - vNext) / vmax;
    4313              :         }
    4314              :     }
    4315    700806292 : }
    4316              : 
    4317              : 
    4318              : double
    4319   1565621110 : MSVehicle::checkReversal(bool& canReverse, double speedThreshold, double seen) const {
    4320     63873616 :     const bool stopOk = (myStops.empty() || myStops.front().edge != myCurrEdge
    4321   1597885753 :                          || (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   1565621110 :     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4338      7280719 :             && getPreviousSpeed() <= speedThreshold
    4339      6202390 :             && myState.myPos <= myLane->getLength()
    4340      6201288 :             && !myLane->isInternal()
    4341      6127325 :             && (myCurrEdge + 1) != myRoute->end()
    4342      6016250 :             && myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1)
    4343              :             // ensure there are no further stops on this edge
    4344   1566470384 :             && 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   1565440317 :     return getMaxSpeed();
    4465              : }
    4466              : 
    4467              : 
    4468              : void
    4469    701021574 : MSVehicle::processLaneAdvances(std::vector<MSLane*>& passedLanes, std::string& emergencyReason) {
    4470    716913015 :     for (std::vector<MSLane*>::reverse_iterator i = myFurtherLanes.rbegin(); i != myFurtherLanes.rend(); ++i) {
    4471     15891441 :         passedLanes.push_back(*i);
    4472              :     }
    4473    701021574 :     if (passedLanes.size() == 0 || passedLanes.back() != myLane) {
    4474    701021574 :         passedLanes.push_back(myLane);
    4475              :     }
    4476              :     // let trains reverse direction
    4477    701021574 :     bool reverseTrain = false;
    4478    701021574 :     checkReversal(reverseTrain);
    4479    701021574 :     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    701021574 :     if (myState.myPos > myLane->getLength()) {
    4493              :         // The vehicle has moved at least to the next lane (maybe it passed even more than one)
    4494     19975794 :         if (myCurrEdge != myRoute->end() - 1) {
    4495     16847384 :             MSLane* approachedLane = myLane;
    4496              :             // move the vehicle forward
    4497     16847384 :             myNextDriveItem = myLFLinkLanes.begin();
    4498     36349349 :             while (myNextDriveItem != myLFLinkLanes.end() && approachedLane != nullptr && myState.myPos > approachedLane->getLength()) {
    4499     19520866 :                 const MSLink* link = myNextDriveItem->myLink;
    4500     19520866 :                 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     19520866 :                 if (approachedLane->mustCheckJunctionCollisions()) {
    4507              :                     // vehicle moves past approachedLane within a single step, collision checking must still be done
    4508        66525 :                     MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(approachedLane);
    4509              :                 }
    4510     19520866 :                 if (link != nullptr) {
    4511     19516678 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4512        46016 :                             && !myLane->isInternal()
    4513        24214 :                             && myLane->getBidiLane() != nullptr
    4514        13042 :                             && link->getLane()->getBidiLane() == myLane
    4515     19517485 :                             && !reverseTrain) {
    4516              :                         emergencyReason = " because it must reverse direction";
    4517              :                         approachedLane = nullptr;
    4518              :                         break;
    4519              :                     }
    4520     19516675 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4521        46013 :                             && myState.myPos < myLane->getLength() + NUMERICAL_EPS
    4522     19516885 :                             && 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     19516479 :                     approachedLane = link->getViaLaneOrLane();
    4531     19516479 :                     if (myInfluencer == nullptr || myInfluencer->getEmergencyBrakeRedLight()) {
    4532     19514876 :                         bool beyondStopLine = linkDist < link->getLaneBefore()->getVehicleStopOffset(this);
    4533     19514876 :                         if (link->haveRed() && !ignoreRed(link, false) && !beyondStopLine && !reverseTrain) {
    4534              :                             emergencyReason = " because of a red traffic light";
    4535              :                             break;
    4536              :                         }
    4537              :                     }
    4538     19516409 :                     if (reverseTrain && approachedLane->isInternal()) {
    4539              :                         // avoid getting stuck on a slow turn-around internal lane
    4540          888 :                         myState.myPos += approachedLane->getLength();
    4541              :                     }
    4542         4188 :                 } else if (myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4543              :                     // avoid warning due to numerical instability
    4544          230 :                     approachedLane = myLane;
    4545          230 :                     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     19516639 :                 if (approachedLane != myLane && approachedLane != nullptr) {
    4560     19516409 :                     leaveLane(MSMoveReminder::NOTIFICATION_JUNCTION, approachedLane);
    4561     19516409 :                     myState.myPos -= myLane->getLength();
    4562              :                     assert(myState.myPos > 0);
    4563     19516409 :                     enterLaneAtMove(approachedLane);
    4564     19516409 :                     if (link->isEntryLink()) {
    4565      7668486 :                         myJunctionEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4566      7668486 :                         myJunctionEntryTimeNeverYield = myJunctionEntryTime;
    4567      7668486 :                         myHaveStoppedFor = nullptr;
    4568              :                     }
    4569     19516409 :                     if (link->isConflictEntryLink()) {
    4570      7667882 :                         myJunctionConflictEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4571              :                         // renew yielded request
    4572      7667882 :                         myJunctionEntryTime = myJunctionEntryTimeNeverYield;
    4573              :                     }
    4574     19516409 :                     if (link->isExitLink()) {
    4575              :                         // passed junction, reset for approaching the next one
    4576      7608206 :                         myJunctionEntryTime = SUMOTime_MAX;
    4577      7608206 :                         myJunctionEntryTimeNeverYield = SUMOTime_MAX;
    4578      7608206 :                         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     19516409 :                     if (hasArrivedInternal()) {
    4591              :                         break;
    4592              :                     }
    4593     19502491 :                     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     19502491 :                     if (approachedLane->getEdge().isVaporizing()) {
    4601          756 :                         leaveLane(MSMoveReminder::NOTIFICATION_VAPORIZED_VAPORIZER);
    4602              :                         break;
    4603              :                     }
    4604     19501735 :                     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      3128410 :         } 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    701021574 : }
    4629              : 
    4630              : 
    4631              : 
    4632              : bool
    4633    704572414 : 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    704572414 :     double vSafe = std::numeric_limits<double>::max();
    4647              :     // Minimum safe velocity (lower bound).
    4648    704572414 :     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    704572414 :     double vSafeMinDist = 0;
    4652              : 
    4653              :     // myAngle will be subsequently be updated by movement and entering new lanes or sublane-changing
    4654    704572414 :     myLastAngle = myRawAngle;
    4655              : 
    4656    704572414 :     if (myActionStep) {
    4657              :         // Actuate control (i.e. choose bounds for safe speed in current simstep (euler), resp. after current sim step (ballistic))
    4658    633011031 :         processLinkApproaches(vSafe, vSafeMin, vSafeMinDist);
    4659              : #ifdef DEBUG_ACTIONSTEPS
    4660              :         if (DEBUG_COND) {
    4661              :             std::cout << SIMTIME << " vehicle '" << getID() << "'\n"
    4662              :                       "   vsafe from processLinkApproaches(): vsafe " << vSafe << std::endl;
    4663              :         }
    4664              : #endif
    4665              :     } else {
    4666              :         // Continue with current acceleration
    4667     71561383 :         vSafe = getSpeed() + ACCEL2SPEED(myAcceleration);
    4668              : #ifdef DEBUG_ACTIONSTEPS
    4669              :         if (DEBUG_COND) {
    4670              :             std::cout << SIMTIME << " vehicle '" << getID() << "' skips processLinkApproaches()\n"
    4671              :                       "   continues with constant accel " <<  myAcceleration << "...\n"
    4672              :                       << "speed: "  << getSpeed() << " -> " << vSafe << std::endl;
    4673              :         }
    4674              : #endif
    4675              :     }
    4676              : 
    4677              : 
    4678              : //#ifdef DEBUG_EXEC_MOVE
    4679              : //    if (DEBUG_COND) {
    4680              : //        std::cout << "vSafe = " << toString(vSafe,12) << "\n" << std::endl;
    4681              : //    }
    4682              : //#endif
    4683              : 
    4684              :     // Determine vNext = speed after current sim step (ballistic), resp. in current simstep (euler)
    4685              :     // Call to finalizeSpeed applies speed reduction due to dawdling / lane changing but ensures minimum safe speed
    4686    704572414 :     double vNext = vSafe;
    4687              :     const MSCFModel& cfModel = getCarFollowModel();
    4688    704572414 :     const double rawAccel = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4689    704572414 :     if (vNext <= SUMO_const_haltingSpeed * TS && myWaitingTime > MSGlobals::gStartupWaitThreshold && rawAccel <= accelThresholdForWaiting() && myActionStep) {
    4690     75243761 :         myTimeSinceStartup = 0;
    4691    629328653 :     } else if (isStopped()) {
    4692              :         // do not apply startupDelay for waypoints
    4693     17810752 :         if (cfModel.startupDelayStopped() && getNextStop().pars.speed <= 0) {
    4694        13772 :             myTimeSinceStartup = DELTA_T;
    4695              :         } else {
    4696              :             // do not apply startupDelay but signal that a stop has taken place
    4697     17796980 :             myTimeSinceStartup = cfModel.getStartupDelay() + DELTA_T;
    4698              :         }
    4699              :     } else {
    4700              :         // identify potential startup (before other effects reduce the speed again)
    4701    611517901 :         myTimeSinceStartup += DELTA_T;
    4702              :     }
    4703    704572414 :     if (myActionStep) {
    4704    633011031 :         vNext = cfModel.finalizeSpeed(this, vSafe);
    4705    629244909 :         if (vNext > 0) {
    4706    586949355 :             vNext = MAX2(vNext, vSafeMin);
    4707              :         }
    4708              :     }
    4709              :     // (Leo) to avoid tiny oscillations (< 1e-10) of vNext in a standing vehicle column (observed for ballistic update), we cap off vNext
    4710              :     //       (We assure to do this only for vNext<<NUMERICAL_EPS since otherwise this would nullify the workaround for #2995
    4711              :     // (Jakob) We also need to make sure to reach a stop at the start of the next edge
    4712    700806292 :     if (fabs(vNext) < NUMERICAL_EPS_SPEED && (myStopDist > POSITION_EPS || (hasStops() && myCurrEdge == getNextStop().edge))) {
    4713              :         vNext = 0.;
    4714              :     }
    4715              : #ifdef DEBUG_EXEC_MOVE
    4716              :     if (DEBUG_COND) {
    4717              :         std::cout << SIMTIME << " finalizeSpeed vSafe=" << vSafe << " vSafeMin=" << (vSafeMin == -std::numeric_limits<double>::max() ? "-Inf" : toString(vSafeMin))
    4718              :                   << " vNext=" << vNext << " (i.e. accel=" << SPEED2ACCEL(vNext - getSpeed()) << ")" << std::endl;
    4719              :     }
    4720              : #endif
    4721              : 
    4722              :     // vNext may be higher than vSafe without implying a bug:
    4723              :     //  - when approaching a green light that suddenly switches to yellow
    4724              :     //  - when using unregulated junctions
    4725              :     //  - when using tau < step-size
    4726              :     //  - when using unsafe car following models
    4727              :     //  - when using TraCI and some speedMode / laneChangeMode settings
    4728              :     //if (vNext > vSafe + NUMERICAL_EPS) {
    4729              :     //    WRITE_WARNING("vehicle '" + getID() + "' cannot brake hard enough to reach safe speed "
    4730              :     //            + toString(vSafe, 4) + ", moving at " + toString(vNext, 4) + " instead. time="
    4731              :     //            + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    4732              :     //}
    4733              : 
    4734    700806292 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4735              :         vNext = MAX2(vNext, 0.);
    4736              :     } else {
    4737              :         // (Leo) Ballistic: negative vNext can be used to indicate a stop within next step.
    4738              :     }
    4739              : 
    4740              :     // Check for speed advices from the traci client
    4741    700806292 :     vNext = processTraCISpeedControl(vSafe, vNext);
    4742              : 
    4743              :     // the acceleration of a vehicle equipped with the elecHybrid device is restricted by the maximal power of the electric drive as well
    4744    700806292 :     MSDevice_ElecHybrid* elecHybridOfVehicle = dynamic_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid)));
    4745          981 :     if (elecHybridOfVehicle != nullptr) {
    4746              :         // this is the consumption given by the car following model-computed acceleration
    4747          981 :         elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4748              :         // but the maximum power of the electric motor may be lower
    4749              :         // it needs to be converted from [W] to [Wh/s] (3600s / 1h) so that TS can be taken into account
    4750          981 :         double maxPower = getEmissionParameters()->getDoubleOptional(SUMO_ATTR_MAXIMUMPOWER, 100000.) / 3600;
    4751          981 :         if (elecHybridOfVehicle->getConsum() / TS > maxPower) {
    4752              :             // no, we cannot accelerate that fast, recompute the maximum possible acceleration
    4753           70 :             double accel = elecHybridOfVehicle->acceleration(*this, maxPower, this->getSpeed());
    4754              :             // and update the speed of the vehicle
    4755           70 :             vNext = MIN2(vNext, this->getSpeed() + accel * TS);
    4756              :             vNext = MAX2(vNext, 0.);
    4757              :             // and set the vehicle consumption to reflect this
    4758           70 :             elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4759              :         }
    4760              :     }
    4761              : 
    4762    700806292 :     setBrakingSignals(vNext);
    4763              : 
    4764              :     // update position and speed
    4765    700806292 :     int oldLaneOffset = myLane->getEdge().getNumLanes() - myLane->getIndex();
    4766              :     const MSLane* oldLaneMaybeOpposite = myLane;
    4767    700806292 :     if (myLaneChangeModel->isOpposite()) {
    4768              :         // transform to the forward-direction lane, move and then transform back
    4769       406574 :         myState.myPos = myLane->getOppositePos(myState.myPos);
    4770       406574 :         myLane = myLane->getParallelOpposite();
    4771              :     }
    4772    700806292 :     updateState(vNext);
    4773    700806292 :     updateWaitingTime(vNext);
    4774              : 
    4775              :     // Lanes, which the vehicle touched at some moment of the executed simstep
    4776              :     std::vector<MSLane*> passedLanes;
    4777              :     // remember previous lane (myLane is updated in processLaneAdvances)
    4778    700806292 :     const MSLane* oldLane = myLane;
    4779              :     // Reason for a possible emergency stop
    4780              :     std::string emergencyReason;
    4781    700806292 :     processLaneAdvances(passedLanes, emergencyReason);
    4782              : 
    4783    700806292 :     updateTimeLoss(vNext);
    4784    700806292 :     myCollisionImmunity = MAX2((SUMOTime) - 1, myCollisionImmunity - DELTA_T);
    4785              : 
    4786    700806292 :     if (!hasArrivedInternal() && !myLane->getEdge().isVaporizing()) {
    4787    697482376 :         if (myState.myPos > myLane->getLength()) {
    4788          360 :             if (emergencyReason == "") {
    4789           17 :                 emergencyReason = TL(" for unknown reasons");
    4790              :             }
    4791         1440 :             WRITE_WARNINGF(TL("Vehicle '%' performs emergency stop at the end of lane '%'% (decel=%, offset=%), time=%."),
    4792              :                            getID(), myLane->getID(), emergencyReason, myAcceleration - myState.mySpeed,
    4793              :                            myState.myPos - myLane->getLength(), time2string(SIMSTEP));
    4794          360 :             MSNet::getInstance()->getVehicleControl().registerEmergencyStop();
    4795          360 :             MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::EMERGENCYSTOP);
    4796          360 :             myState.myPos = myLane->getLength();
    4797          360 :             myState.mySpeed = 0;
    4798          360 :             myAcceleration = 0;
    4799              :         }
    4800    697482376 :         const MSLane* oldBackLane = getBackLane();
    4801    697482376 :         if (myLaneChangeModel->isOpposite()) {
    4802              :             passedLanes.clear(); // ignore back occupation
    4803              :         }
    4804              : #ifdef DEBUG_ACTIONSTEPS
    4805              :         if (DEBUG_COND) {
    4806              :             std::cout << SIMTIME << " veh '" << getID() << "' updates further lanes." << std::endl;
    4807              :         }
    4808              : #endif
    4809    697482376 :         myState.myBackPos = updateFurtherLanes(myFurtherLanes, myFurtherLanesPosLat, passedLanes);
    4810    697482376 :         if (passedLanes.size() > 1 && isRail()) {
    4811       882694 :             for (auto pi = passedLanes.rbegin(); pi != passedLanes.rend(); ++pi) {
    4812       665888 :                 MSLane* pLane = *pi;
    4813       665888 :                 if (pLane != myLane && std::find(myFurtherLanes.begin(), myFurtherLanes.end(), pLane) == myFurtherLanes.end()) {
    4814        45673 :                     leaveLaneBack(MSMoveReminder::NOTIFICATION_JUNCTION, *pi);
    4815              :                 }
    4816              :             }
    4817              :         }
    4818              :         // bestLanes need to be updated before lane changing starts. NOTE: This call is also a presumption for updateDriveItems()
    4819    697482376 :         updateBestLanes();
    4820    697482376 :         if (myLane != oldLane || oldBackLane != getBackLane()) {
    4821     24760587 :             if (myLaneChangeModel->getShadowLane() != nullptr || getLateralOverlap() > POSITION_EPS) {
    4822              :                 // shadow lane must be updated if the front or back lane changed
    4823              :                 // either if we already have a shadowLane or if there is lateral overlap
    4824       554269 :                 myLaneChangeModel->updateShadowLane();
    4825              :             }
    4826     24760587 :             if (MSGlobals::gLateralResolution > 0 && !myLaneChangeModel->isOpposite()) {
    4827              :                 // The vehicles target lane must be also be updated if the front or back lane changed
    4828      4420557 :                 myLaneChangeModel->updateTargetLane();
    4829              :             }
    4830              :         }
    4831    697482376 :         setBlinkerInformation(); // needs updated bestLanes
    4832              :         //change the blue light only for emergency vehicles SUMOVehicleClass
    4833    697482376 :         if (myType->getVehicleClass() == SVC_EMERGENCY) {
    4834        85658 :             setEmergencyBlueLight(MSNet::getInstance()->getCurrentTimeStep());
    4835              :         }
    4836              :         // must be done before angle computation
    4837              :         // State needs to be reset for all vehicles before the next call to MSEdgeControl::changeLanes
    4838    697482376 :         if (myActionStep) {
    4839              :             // check (#2681): Can this be skipped?
    4840    625942273 :             myLaneChangeModel->prepareStep();
    4841              :         } else {
    4842     71540103 :             myLaneChangeModel->resetSpeedLat();
    4843              : #ifdef DEBUG_ACTIONSTEPS
    4844              :             if (DEBUG_COND) {
    4845              :                 std::cout << SIMTIME << " veh '" << getID() << "' skips LCM->prepareStep()." << std::endl;
    4846              :             }
    4847              : #endif
    4848              :         }
    4849    697482376 :         myLaneChangeModel->setPreviousAngleOffset(myLaneChangeModel->getAngleOffset());
    4850    697482376 :         myAngle = computeAngle();
    4851              :     }
    4852              : 
    4853              : #ifdef DEBUG_EXEC_MOVE
    4854              :     if (DEBUG_COND) {
    4855              :         std::cout << SIMTIME << " executeMove finished veh=" << getID() << " lane=" << myLane->getID() << " myPos=" << getPositionOnLane() << " myPosLat=" << getLateralPositionOnLane() << "\n";
    4856              :         gDebugFlag1 = false; // See MSLink_DEBUG_OPENED
    4857              :     }
    4858              : #endif
    4859    700806292 :     if (myLaneChangeModel->isOpposite()) {
    4860              :         // transform back to the opposite-direction lane
    4861              :         MSLane* newOpposite = nullptr;
    4862       406574 :         const MSEdge* newOppositeEdge = myLane->getEdge().getOppositeEdge();
    4863       406574 :         if (newOppositeEdge != nullptr) {
    4864       406524 :             newOpposite = newOppositeEdge->getLanes()[newOppositeEdge->getNumLanes() - MAX2(1, oldLaneOffset)];
    4865              : #ifdef DEBUG_EXEC_MOVE
    4866              :             if (DEBUG_COND) {
    4867              :                 std::cout << SIMTIME << "   newOppositeEdge=" << newOppositeEdge->getID() << " oldLaneOffset=" << oldLaneOffset << " leftMost=" << newOppositeEdge->getNumLanes() - 1 << " newOpposite=" << Named::getIDSecure(newOpposite) << "\n";
    4868              :             }
    4869              : #endif
    4870              :         }
    4871       406524 :         if (newOpposite == nullptr) {
    4872           50 :             if (!myLaneChangeModel->hasBlueLight()) {
    4873              :                 // unusual overtaking at junctions is ok for emergency vehicles
    4874            0 :                 WRITE_WARNINGF(TL("Unexpected end of opposite lane for vehicle '%' at lane '%', time=%."),
    4875              :                                getID(), myLane->getID(), time2string(SIMSTEP));
    4876              :             }
    4877           50 :             myLaneChangeModel->changedToOpposite();
    4878           50 :             if (myState.myPos < getLength()) {
    4879              :                 // further lanes is always cleared during opposite driving
    4880           50 :                 MSLane* oldOpposite = oldLane->getOpposite();
    4881           50 :                 if (oldOpposite != nullptr) {
    4882           50 :                     myFurtherLanes.push_back(oldOpposite);
    4883           51 :                     myFurtherLanesPosLat.push_back(0);
    4884              :                     // small value since the lane is going in the other direction
    4885           50 :                     myState.myBackPos = getLength() - myState.myPos;
    4886           50 :                     myAngle = computeAngle();
    4887              :                 } else {
    4888              :                     SOFT_ASSERT(false);
    4889              :                 }
    4890              :             }
    4891              :         } else {
    4892       406524 :             myState.myPos = myLane->getOppositePos(myState.myPos);
    4893       406524 :             myLane = newOpposite;
    4894              :             oldLane = oldLaneMaybeOpposite;
    4895              :             //std::cout << SIMTIME << " updated myLane=" << Named::getIDSecure(myLane) << " oldLane=" << oldLane->getID() << "\n";
    4896       406524 :             myCachedPosition = Position::INVALID;
    4897       406524 :             myLaneChangeModel->updateShadowLane();
    4898              :         }
    4899              :     }
    4900    700806292 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4901              :     // store angle before lane changing
    4902    700806291 :     myRawAngle = myAngle;
    4903              :     // Return whether the vehicle did move to another lane
    4904   1401612582 :     return myLane != oldLane;
    4905    700806292 : }
    4906              : 
    4907              : void
    4908       215282 : MSVehicle::executeFractionalMove(double dist) {
    4909       215282 :     myState.myPos += dist;
    4910       215282 :     myState.myLastCoveredDist = dist;
    4911       215282 :     myCachedPosition = Position::INVALID;
    4912              : 
    4913       215282 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(dist);
    4914       215282 :     const SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
    4915       446569 :     for (int i = 0; i < (int)lanes.size(); i++) {
    4916       231287 :         MSLink* link = nullptr;
    4917       231287 :         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       231287 :         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       215282 :     if (lanes.size() > 1) {
    4933         4005 :         myLane->removeVehicle(this, MSMoveReminder::NOTIFICATION_JUNCTION, false);
    4934              :     }
    4935              :     std::string emergencyReason;
    4936       215282 :     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       215282 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4948       215282 :     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       215282 : }
    4962              : 
    4963              : 
    4964              : void
    4965    709147771 : MSVehicle::updateState(double vNext, bool parking) {
    4966              :     // update position and speed
    4967              :     double deltaPos; // positional change
    4968    709147771 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4969              :         // euler
    4970    609852471 :         deltaPos = SPEED2DIST(vNext);
    4971              :     } else {
    4972              :         // ballistic
    4973     99295300 :         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    709147771 :     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    709147771 :     double decelPlus = -myAcceleration - getCarFollowModel().getMaxDecel() - NUMERICAL_EPS;
    4987    709147771 :     if (decelPlus > 0) {
    4988       429703 :         const double previousAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    4989       429703 :         if (myAcceleration + NUMERICAL_EPS < previousAcceleration) {
    4990              :             // vehicle brakes beyond wished maximum deceleration (only warn at the start of the braking manoeuvre)
    4991       290191 :             decelPlus += 2 * NUMERICAL_EPS;
    4992       290191 :             const double emergencyFraction = decelPlus / MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel());
    4993       290191 :             if (emergencyFraction >= MSGlobals::gEmergencyDecelWarningThreshold) {
    4994        95661 :                 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        31887 :                 MSNet::getInstance()->getVehicleControl().registerEmergencyBraking();
    5000              :             }
    5001              :         }
    5002              :     }
    5003              : 
    5004    709147771 :     myState.myPreviousSpeed = myState.mySpeed;
    5005    709147771 :     myState.mySpeed = MAX2(vNext, 0.);
    5006              : 
    5007    709147771 :     if (isRemoteControlled()) {
    5008         7181 :         deltaPos = myInfluencer->implicitDeltaPosRemote(this);
    5009              :     }
    5010              : 
    5011    709147771 :     myState.myPos += deltaPos;
    5012    709147771 :     myState.myLastCoveredDist = deltaPos;
    5013    709147771 :     myNextTurn.first -= deltaPos;
    5014              : 
    5015    709147771 :     if (!parking) {
    5016    700806292 :         myCachedPosition = Position::INVALID;
    5017              :     }
    5018    709147771 : }
    5019              : 
    5020              : void
    5021      8341479 : MSVehicle::updateParkingState() {
    5022      8341479 :     updateState(0, true);
    5023              :     // deboard while parked
    5024      8341479 :     if (myPersonDevice != nullptr) {
    5025       623370 :         myPersonDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    5026              :     }
    5027      8341479 :     if (myContainerDevice != nullptr) {
    5028        59887 :         myContainerDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    5029              :     }
    5030     16849761 :     for (MSVehicleDevice* const dev : myDevices) {
    5031      8508282 :         dev->notifyParking();
    5032              :     }
    5033      8341479 : }
    5034              : 
    5035              : 
    5036              : void
    5037        30616 : MSVehicle::replaceVehicleType(const MSVehicleType* type) {
    5038        30616 :     MSBaseVehicle::replaceVehicleType(type);
    5039        30616 :     delete myCFVariables;
    5040        30616 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    5041        30616 : }
    5042              : 
    5043              : 
    5044              : const MSLane*
    5045   1379087299 : MSVehicle::getBackLane() const {
    5046   1379087299 :     if (myFurtherLanes.size() > 0) {
    5047     18980649 :         return myFurtherLanes.back();
    5048              :     } else {
    5049   1360106650 :         return myLane;
    5050              :     }
    5051              : }
    5052              : 
    5053              : 
    5054              : double
    5055    702984743 : 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    718912566 :     for (MSLane* further : furtherLanes) {
    5065     15927823 :         further->resetPartialOccupation(this);
    5066     15927823 :         if (further->getBidiLane() != nullptr
    5067     15927823 :                 && (!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    702984743 :     double backPosOnPreviousLane = myState.myPos - getLength();
    5075              :     bool widthShift = myFurtherLanesPosLat.size() > myFurtherLanes.size();
    5076    702984743 :     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     44692631 :         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     15861402 :             MSLane* further = *pi;
    5083     15861402 :             newFurther.push_back(further);
    5084     15861402 :             backPosOnPreviousLane += further->setPartialOccupation(this);
    5085     15861402 :             if (further->getBidiLane() != nullptr
    5086     15861402 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5087       100022 :                 further->getBidiLane()->setPartialOccupation(this);
    5088              :             }
    5089     15861402 :             if (fi != furtherLanes.end() && further == *fi) {
    5090              :                 // Lateral position on this lane is already known. Assume constant and use old value.
    5091      5673188 :                 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     10188214 :                 if (newFurtherPosLat.size() == 0) {
    5100      9569385 :                     if (widthShift) {
    5101      1504610 :                         newFurtherPosLat.push_back(myFurtherLanesPosLat.back());
    5102              :                     } else {
    5103      8064775 :                         newFurtherPosLat.push_back(myState.myPosLat);
    5104              :                     }
    5105              :                 } else {
    5106       618829 :                     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     28831229 :         furtherLanes = newFurther;
    5118     28831229 :         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    702984743 :     return backPosOnPreviousLane;
    5131    702984743 : }
    5132              : 
    5133              : 
    5134              : double
    5135  33737494285 : 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  33737494285 :     if (lane == myLane
    5157   8099192964 :             || lane == myLaneChangeModel->getShadowLane()
    5158  38369927130 :             || lane == myLaneChangeModel->getTargetLane()) {
    5159  29106644792 :         if (myLaneChangeModel->isOpposite()) {
    5160    231235348 :             if (lane == myLaneChangeModel->getShadowLane()) {
    5161    199161482 :                 return lane->getLength() - myState.myPos - myType->getLength();
    5162              :             } else {
    5163     36868200 :                 return myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5164              :             }
    5165  28875409444 :         } else if (&lane->getEdge() != &myLane->getEdge()) {
    5166     20782119 :             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  57709961152 :             return myState.myPos - myType->getLength() + MIN2(0.0, lane->getLength() - myLane->getLength());
    5170              :         }
    5171   4630849493 :     } else if (lane == myLane->getBidiLane()) {
    5172     41916298 :         return lane->getLength() - myState.myPos + myType->getLength() * (calledByGetPosition ? -1 : 1);
    5173   4596690839 :     } else if (myFurtherLanes.size() > 0 && lane == myFurtherLanes.back()) {
    5174   4547872361 :         return myState.myBackPos;
    5175     48818478 :     } else if ((myLaneChangeModel->getShadowFurtherLanes().size() > 0 && lane == myLaneChangeModel->getShadowFurtherLanes().back())
    5176     49280249 :                || (myLaneChangeModel->getFurtherTargetLanes().size() > 0 && lane == myLaneChangeModel->getFurtherTargetLanes().back())) {
    5177              :         assert(myFurtherLanes.size() > 0);
    5178     19571920 :         if (lane->getLength() == myFurtherLanes.back()->getLength()) {
    5179     18906037 :             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       665883 :             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     29246558 :         double leftLength = myType->getLength() - myState.myPos;
    5193              : 
    5194              :         std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin();
    5195     31319317 :         while (leftLength > 0 && i != myFurtherLanes.end()) {
    5196     31265698 :             leftLength -= (*i)->getLength();
    5197              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5198     31265698 :             if (*i == lane) {
    5199     28171940 :                 return -leftLength;
    5200      3093758 :             } else if (*i == lane->getBidiLane()) {
    5201      1020999 :                 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        53619 :         leftLength = myType->getLength() - myState.myPos;
    5207        53619 :         i = myLaneChangeModel->getShadowFurtherLanes().begin();
    5208        53619 :         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            1 :         leftLength = myType->getLength() - myState.myPos;
    5220              :         i = getFurtherLanes().begin();
    5221            1 :         const std::vector<MSLane*> furtherTargetLanes = myLaneChangeModel->getFurtherTargetLanes();
    5222              :         auto j = furtherTargetLanes.begin();
    5223            1 :         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            4 :         WRITE_WARNINGF("Request backPos of vehicle '%' for invalid lane '%' time=%.",
    5235              :                 getID(), Named::getIDSecure(lane), time2string(SIMSTEP))
    5236              :         SOFT_ASSERT(false);
    5237            1 :         return  myState.myBackPos;
    5238            1 :     }
    5239              : }
    5240              : 
    5241              : 
    5242              : double
    5243  27331272362 : MSVehicle::getPositionOnLane(const MSLane* lane) const {
    5244  27331272362 :     return getBackPositionOnLane(lane, true) + myType->getLength();
    5245              : }
    5246              : 
    5247              : 
    5248              : bool
    5249    419609197 : MSVehicle::isFrontOnLane(const MSLane* lane) const {
    5250    419609197 :     return lane == myLane || lane == myLaneChangeModel->getShadowLane() || lane == myLane->getBidiLane();
    5251              : }
    5252              : 
    5253              : 
    5254              : void
    5255    633011044 : MSVehicle::checkRewindLinkLanes(const double lengthsInFront, DriveItemVector& lfLinks) const {
    5256    633011044 :     if (MSGlobals::gUsingInternalLanes && !myLane->getEdge().isRoundabout() && !myLaneChangeModel->isOpposite()) {
    5257    629800929 :         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    629800929 :         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   1839659097 :         for (int i = 0; i < (int)lfLinks.size(); ++i) {
    5267              :             // skip unset links
    5268   1209858168 :             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   1209858168 :             if (item.myLink == nullptr || foundStopped) {
    5275    397103830 :                 if (!foundStopped) {
    5276    344808084 :                     item.availableSpace += seenSpace;
    5277              :                 } else {
    5278     52295746 :                     item.availableSpace = seenSpace;
    5279              :                 }
    5280              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5281              :                 if (DEBUG_COND) {
    5282              :                     std::cout << " avail=" << item.availableSpace << "\n";
    5283              :                 }
    5284              : #endif
    5285    397103830 :                 continue;
    5286              :             }
    5287              :             // get the next lane, determine whether it is an internal lane
    5288              :             const MSLane* approachedLane = item.myLink->getViaLane();
    5289    812754338 :             if (approachedLane != nullptr) {
    5290    443574544 :                 if (keepClear(item.myLink)) {
    5291    141975854 :                     seenSpace = seenSpace - approachedLane->getBruttoVehLenSum();
    5292    141975854 :                     if (approachedLane == myLane) {
    5293        48432 :                         seenSpace += getVehicleType().getLengthWithGap();
    5294              :                     }
    5295              :                 } else {
    5296    301598690 :                     seenSpace = seenSpace + approachedLane->getSpaceTillLastStanding(this, foundStopped);// - approachedLane->getBruttoVehLenSum() + approachedLane->getLength();
    5297              :                 }
    5298    443574544 :                 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    443574544 :                 continue;
    5310              :             }
    5311              :             approachedLane = item.myLink->getLane();
    5312    369179794 :             const MSVehicle* last = approachedLane->getLastAnyVehicle();
    5313    369179794 :             if (last == nullptr || last == this) {
    5314     61323471 :                 if (approachedLane->getLength() > getVehicleType().getLength()
    5315     61323471 :                         || keepClear(item.myLink)) {
    5316     58938135 :                     seenSpace += approachedLane->getLength();
    5317              :                 }
    5318     61323471 :                 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    307856323 :                 bool foundStopped2 = false;
    5326    307856323 :                 double spaceTillLastStanding = approachedLane->getSpaceTillLastStanding(this, foundStopped2);
    5327    307856323 :                 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    307856323 :                 seenSpace += spaceTillLastStanding;
    5351    307856323 :                 if (foundStopped2) {
    5352     21059662 :                     foundStopped = true;
    5353     21059662 :                     item.hadStoppedVehicle = true;
    5354              :                 }
    5355    307856323 :                 item.availableSpace = seenSpace;
    5356    307856323 :                 if (last->myHaveToWaitOnNextLink || last->isStopped()) {
    5357     30637128 :                     foundStopped = true;
    5358     30637128 :                     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   1209858168 :         for (int i = ((int)lfLinks.size() - 1); i > 0; --i) {
    5382    580057239 :             DriveProcessItem& item = lfLinks[i - 1];
    5383    580057239 :             DriveProcessItem& nextItem = lfLinks[i];
    5384    580057239 :             const bool canLeaveJunction = item.myLink->getViaLane() == nullptr || nextItem.myLink == nullptr || nextItem.mySetRequest;
    5385              :             const bool opened = (item.myLink != nullptr
    5386    580057239 :                                  && (canLeaveJunction || (
    5387              :                                          // indirect bicycle turn
    5388     28531816 :                                          nextItem.myLink != nullptr && nextItem.myLink->isInternalJunctionLink() && nextItem.myLink->haveRed()))
    5389    551539485 :                                  && (
    5390    551539485 :                                      item.myLink->havePriority()
    5391     27939555 :                                      || i == 1 // the upcoming link (item 0) is checked in executeMove anyway. No need to use outdata approachData here
    5392      5445522 :                                      || (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority())
    5393      5416009 :                                      || item.myLink->opened(item.myArrivalTime, item.myArrivalSpeed,
    5394      5416009 :                                              item.getLeaveSpeed(), getVehicleType().getLength(),
    5395      5416009 :                                              getImpatience(), getCarFollowModel().getMaxDecel(), getWaitingTime(), getLateralPositionOnLane(), nullptr, false, this)));
    5396    580057239 :             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    580057239 :             if (!opened && item.myLink != nullptr) {
    5407     29260581 :                 foundStopped = true;
    5408     29260581 :                 if (i > 1) {
    5409      5006783 :                     DriveProcessItem& item2 = lfLinks[i - 2];
    5410      5006783 :                     if (item2.myLink != nullptr && item2.myLink->isCont()) {
    5411              :                         allowsContinuation = true;
    5412              :                     }
    5413              :                 }
    5414              :             }
    5415    576840827 :             if (allowsContinuation) {
    5416    520440860 :                 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    759155016 :         for (int i = 0; foundStopped && i < (int)lfLinks.size() && removalBegin < 0; ++i) {
    5429              :             // skip unset links
    5430    129354087 :             const DriveProcessItem& item = lfLinks[i];
    5431    129354087 :             if (item.myLink == nullptr) {
    5432      6750226 :                 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    122603861 :             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    122603861 :             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     77464057 :                 if (leftSpace < -impatienceCorrection / 10. && keepClear(item.myLink)) {
    5460              :                     removalBegin = i;
    5461              :                 }
    5462              :                 //removalBegin = i;
    5463              :             }
    5464              :         }
    5465              :         // abort requests
    5466    629800929 :         if (removalBegin != -1 && !(removalBegin == 0 && myLane->getEdge().isInternal())) {
    5467     31037479 :             const double brakeGap = getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.);
    5468    106419027 :             while (removalBegin < (int)(lfLinks.size())) {
    5469     80334316 :                 DriveProcessItem& dpi = lfLinks[removalBegin];
    5470     80334316 :                 if (dpi.myLink == nullptr) {
    5471              :                     break;
    5472              :                 }
    5473     75381548 :                 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     75381548 :                 if (dpi.myDistance >= brakeGap + POSITION_EPS) {
    5480              :                     // always leave junctions after requesting to enter
    5481     75372888 :                     if (!dpi.myLink->isExitLink() || !lfLinks[removalBegin - 1].mySetRequest) {
    5482     75365290 :                         dpi.mySetRequest = false;
    5483              :                     }
    5484              :                 }
    5485     75381548 :                 ++removalBegin;
    5486              :             }
    5487              :         }
    5488              :     }
    5489    633011044 : }
    5490              : 
    5491              : 
    5492              : void
    5493    704572427 : MSVehicle::setApproachingForAllLinks() {
    5494    704572427 :     if (!myActionStep) {
    5495              :         return;
    5496              :     }
    5497    633011044 :     removeApproachingInformation(myLFLinkLanesPrev);
    5498   1850740379 :     for (DriveProcessItem& dpi : myLFLinkLanes) {
    5499   1217729335 :         if (dpi.myLink != nullptr) {
    5500    864599536 :             if (dpi.myLink->getState() == LINKSTATE_ALLWAY_STOP) {
    5501      2850520 :                 dpi.myArrivalTime += (SUMOTime)RandHelper::rand((int)2, getRNG()); // tie braker
    5502              :             }
    5503    864599536 :             dpi.myLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5504    864599536 :                                        dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance, getLateralPositionOnLane());
    5505              :         }
    5506              :     }
    5507    633011044 :     if (isRail()) {
    5508      8248638 :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5509      6862585 :             if (dpi.myLink != nullptr && dpi.myLink->getTLLogic() != nullptr && dpi.myLink->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
    5510       692917 :                 MSRailSignalControl::getInstance().notifyApproach(dpi.myLink);
    5511              :             }
    5512              :         }
    5513              :     }
    5514    633011044 :     if (myLaneChangeModel->getShadowLane() != nullptr) {
    5515              :         // register on all shadow links
    5516      7592739 :         for (const DriveProcessItem& dpi : myLFLinkLanes) {
    5517      5035214 :             if (dpi.myLink != nullptr) {
    5518      3441603 :                 MSLink* parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    5519      3441603 :                 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      3441603 :                 if (parallelLink != nullptr) {
    5524      2449597 :                     const double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    5525      2449597 :                     parallelLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5526      2449597 :                                                  dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance,
    5527              :                                                  latOffset);
    5528      2449597 :                     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         1854 : MSVehicle::registerInsertionApproach(MSLink* link, double dist) {
    5554              :     DriveProcessItem dpi(0, dist);
    5555         1854 :     dpi.myLink = link;
    5556         1854 :     const double arrivalSpeedBraking = getCarFollowModel().getMinimalArrivalSpeedEuler(dist, getSpeed());
    5557         1854 :     link->setApproaching(this, SUMOTime_MAX, 0, 0, false, arrivalSpeedBraking, 0, dpi.myDistance, 0);
    5558              :     // ensure cleanup in the next step
    5559         1854 :     myLFLinkLanes.push_back(dpi);
    5560         1854 :     MSRailSignalControl::getInstance().notifyApproach(link);
    5561         1854 : }
    5562              : 
    5563              : 
    5564              : void
    5565     19534811 : MSVehicle::enterLaneAtMove(MSLane* enteredLane, bool onTeleporting) {
    5566     19534811 :     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     19534811 :     adaptLaneEntering2MoveReminder(*enteredLane);
    5577              :     // set the entered lane as the current lane
    5578     19534811 :     MSLane* oldLane = myLane;
    5579     19534811 :     myLane = enteredLane;
    5580     19534811 :     myLastBestLanesEdge = nullptr;
    5581              : 
    5582              :     // internal edges are not a part of the route...
    5583     19534811 :     if (!enteredLane->getEdge().isInternal()) {
    5584              :         ++myCurrEdge;
    5585              :         assert(myLaneChangeModel->isOpposite() || haveValidStopEdges());
    5586              :     }
    5587     19534811 :     if (myInfluencer != nullptr) {
    5588         9034 :         myInfluencer->adaptLaneTimeLine(myLane->getIndex() - oldLane->getIndex());
    5589              :     }
    5590     19534811 :     if (!onTeleporting) {
    5591     19516409 :         activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION, enteredLane);
    5592     19516409 :         if (MSGlobals::gLateralResolution > 0) {
    5593      3831721 :             myFurtherLanesPosLat.push_back(myState.myPosLat);
    5594              :             // transform lateral position when the lane width changes
    5595              :             assert(oldLane != nullptr);
    5596      3831721 :             const MSLink* const link = oldLane->getLinkTo(myLane);
    5597      3831721 :             if (link != nullptr) {
    5598      3831679 :                 myState.myPosLat += link->getLateralShift();
    5599              :             } else {
    5600           42 :                 myState.myPosLat += (oldLane->getCenterOnEdge() - myLane->getCanonicalPredecessorLane()->getRightSideOnEdge()) / 2;
    5601              :             }
    5602     15684688 :         } 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     19516409 :         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        18402 :         myState.myPos = 0;
    5617        18402 :         myCachedPosition = Position::INVALID;
    5618        18402 :         activateReminders(MSMoveReminder::NOTIFICATION_TELEPORT, enteredLane);
    5619              :     }
    5620              :     // update via
    5621     19534811 :     if (myParameter->via.size() > 0 &&  myLane->getEdge().getID() == myParameter->via.front()) {
    5622         7271 :         myParameter->via.erase(myParameter->via.begin());
    5623              :     }
    5624     19534811 : }
    5625              : 
    5626              : 
    5627              : void
    5628      1093860 : MSVehicle::enterLaneAtLaneChange(MSLane* enteredLane) {
    5629      1093860 :     myAmOnNet = true;
    5630      1093860 :     myLane = enteredLane;
    5631      1093860 :     myCachedPosition = Position::INVALID;
    5632              :     // need to update myCurrentLaneInBestLanes
    5633      1093860 :     updateBestLanes();
    5634              :     // switch to and activate the new lane's reminders
    5635              :     // keep OldLaneReminders
    5636      1293487 :     for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5637       199627 :         addReminder(*rem);
    5638              :     }
    5639      1093860 :     activateReminders(MSMoveReminder::NOTIFICATION_LANE_CHANGE, enteredLane);
    5640      1093860 :     MSLane* lane = myLane;
    5641      1093860 :     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      1093860 :     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      1181098 :     for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    5654        87238 :         if (lane != nullptr) {
    5655        84052 :             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        87238 :         if (leftLength > 0) {
    5663        86664 :             if (lane != nullptr) {
    5664        35441 :                 myFurtherLanes[i]->resetPartialOccupation(this);
    5665        35441 :                 if (myFurtherLanes[i]->getBidiLane() != nullptr
    5666        35441 :                         && (!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        35441 :                 myFurtherLanes[i] = lane;
    5672        35441 :                 myFurtherLanesPosLat[i] = myState.myPosLat;
    5673        35441 :                 leftLength -= lane->setPartialOccupation(this);
    5674        35441 :                 if (lane->getBidiLane() != nullptr
    5675        35441 :                         && (!isRailway(getVClass()) || (lane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5676         1892 :                     lane->getBidiLane()->setPartialOccupation(this);
    5677              :                 }
    5678        35441 :                 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        51223 :                 if (myLaneChangeModel->isChangingLanes()) {
    5687           15 :                     myLaneChangeModel->setNoShadowPartialOccupator(myFurtherLanes[i]);
    5688              :                 }
    5689        51223 :                 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      1093860 :     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      1093860 :     myAngle = computeAngle();
    5723      1093860 : }
    5724              : 
    5725              : 
    5726              : void
    5727      3546457 : MSVehicle::computeFurtherLanes(MSLane* enteredLane, double pos, bool collision) {
    5728              :     // build the list of lanes the vehicle is lapping into
    5729      3546457 :     if (!myLaneChangeModel->isOpposite()) {
    5730      3524196 :         double leftLength = myType->getLength() - pos;
    5731      3524196 :         MSLane* clane = enteredLane;
    5732      3524196 :         int routeIndex = getRoutePosition();
    5733      3628484 :         while (leftLength > 0) {
    5734       236385 :             if (routeIndex > 0 && clane->getEdge().isNormal()) {
    5735              :                 // get predecessor lane that corresponds to prior route
    5736         4571 :                 routeIndex--;
    5737         4571 :                 const MSEdge* fromRouteEdge = myRoute->getEdges()[routeIndex];
    5738              :                 MSLane* target = clane;
    5739         4571 :                 clane = nullptr;
    5740         6105 :                 for (auto ili : target->getIncomingLanes()) {
    5741         6098 :                     if (ili.lane->getEdge().getNormalBefore() == fromRouteEdge) {
    5742         4564 :                         clane = ili.lane;
    5743         4564 :                         break;
    5744              :                     }
    5745              :                 }
    5746              :             } else {
    5747       231814 :                 clane = clane->getLogicalPredecessorLane();
    5748              :             }
    5749       144627 :             if (clane == nullptr || clane == myLane || clane == myLane->getBidiLane()
    5750       381004 :                     || (clane->isInternal() && (
    5751       121400 :                             clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN
    5752        81069 :                             || clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN_LEFTHAND))) {
    5753              :                 break;
    5754              :             }
    5755       104288 :             if (!collision || std::find(myFurtherLanes.begin(), myFurtherLanes.end(), clane) == myFurtherLanes.end()) {
    5756       103840 :                 myFurtherLanes.push_back(clane);
    5757       103840 :                 myFurtherLanesPosLat.push_back(myState.myPosLat);
    5758       103840 :                 clane->setPartialOccupation(this);
    5759       103840 :                 if (clane->getBidiLane() != nullptr
    5760       103840 :                         && (!isRailway(getVClass()) || (clane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5761            5 :                     clane->getBidiLane()->setPartialOccupation(this);
    5762              :                 }
    5763              :             }
    5764       104288 :             leftLength -= clane->getLength();
    5765              :         }
    5766      3524196 :         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        22616 :         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          355 :             further->resetPartialOccupation(this);
    5781          355 :             if (further->getBidiLane() != nullptr
    5782          355 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5783            0 :                 further->getBidiLane()->resetPartialOccupation(this);
    5784              :             }
    5785              :         }
    5786              :         myFurtherLanes.clear();
    5787              :         myFurtherLanesPosLat.clear();
    5788              :     }
    5789      3546457 : }
    5790              : 
    5791              : 
    5792              : void
    5793      3546004 : MSVehicle::enterLaneAtInsertion(MSLane* enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification) {
    5794      3546004 :     myState = State(pos, speed, posLat, pos - getVehicleType().getLength(), hasDeparted() ? myState.myPreviousSpeed : speed);
    5795      3546004 :     if (myDeparture == NOT_YET_DEPARTED) {
    5796      3471717 :         onDepart();
    5797              :     }
    5798      3546004 :     myCachedPosition = Position::INVALID;
    5799              :     assert(myState.myPos >= 0);
    5800              :     assert(myState.mySpeed >= 0);
    5801      3546004 :     myLane = enteredLane;
    5802      3546004 :     myAmOnNet = true;
    5803              :     // schedule action for the next timestep
    5804      3546004 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + DELTA_T;
    5805      3546004 :     if (notification != MSMoveReminder::NOTIFICATION_TELEPORT) {
    5806      3534215 :         if (notification == MSMoveReminder::NOTIFICATION_PARKING && myInfluencer != nullptr) {
    5807           12 :             drawOutsideNetwork(false);
    5808              :         }
    5809              :         // set and activate the new lane's reminders, teleports already did that at enterLaneAtMove
    5810      7504117 :         for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5811      3969902 :             addReminder(*rem);
    5812              :         }
    5813      3534215 :         activateReminders(notification, enteredLane);
    5814              :     } else {
    5815        11789 :         myLastBestLanesEdge = nullptr;
    5816        11789 :         myLastBestLanesInternalLane = nullptr;
    5817        11789 :         myLaneChangeModel->resetState();
    5818        12926 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()
    5819        12477 :                 && myStops.front().pars.endPos < pos) {
    5820            0 :             WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5821              :                            time2string(MSNet::getInstance()->getCurrentTimeStep()));
    5822            0 :             cleanupParkingReservation();
    5823            0 :             myStops.pop_front();
    5824              :         }
    5825              :         // avoid startup-effects after teleport
    5826        11789 :         myTimeSinceStartup = getCarFollowModel().getStartupDelay() + DELTA_T;
    5827        11789 :         myStopSpeed = std::numeric_limits<double>::max();
    5828              :     }
    5829      3546004 :     computeFurtherLanes(enteredLane, pos);
    5830      3546004 :     if (MSGlobals::gLateralResolution > 0) {
    5831       521860 :         myLaneChangeModel->updateShadowLane();
    5832       521860 :         myLaneChangeModel->updateTargetLane();
    5833      3024144 :     } else if (MSGlobals::gLaneChangeDuration > 0) {
    5834        40414 :         myLaneChangeModel->updateShadowLane();
    5835              :     }
    5836      3546004 :     if (notification != MSMoveReminder::NOTIFICATION_LOAD_STATE) {
    5837      3544557 :         myAngle = computeAngle();
    5838      3544557 :         myRawAngle = myAngle;
    5839      3544557 :         if (myLaneChangeModel->isOpposite()) {
    5840        22261 :             myAngle += M_PI;
    5841              :         }
    5842              :     }
    5843      3546004 :     if (MSNet::getInstance()->hasPersons()) {
    5844        58453 :         for (MSLane* further : myFurtherLanes) {
    5845          880 :             if (further->mustCheckJunctionCollisions()) {
    5846            4 :                 MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(further);
    5847              :             }
    5848              :         }
    5849              :     }
    5850      3546004 : }
    5851              : 
    5852              : 
    5853              : void
    5854     24052909 : MSVehicle::leaveLane(const MSMoveReminder::Notification reason, const MSLane* approachedLane) {
    5855     66470181 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5856     42417272 :         if (rem->first->notifyLeave(*this, myState.myPos + rem->second, reason, approachedLane)) {
    5857              : #ifdef _DEBUG
    5858              :             if (myTraceMoveReminders) {
    5859              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, true);
    5860              :             }
    5861              : #endif
    5862              :             ++rem;
    5863              :         } else {
    5864              : #ifdef _DEBUG
    5865              :             if (myTraceMoveReminders) {
    5866              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, false);
    5867              :             }
    5868              : #endif
    5869              :             rem = myMoveReminders.erase(rem);
    5870              :         }
    5871              :     }
    5872     24052909 :     if ((reason == MSMoveReminder::NOTIFICATION_JUNCTION
    5873     24052909 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT
    5874      4524026 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT_CONTINUATION)
    5875     19535076 :             && myLane != nullptr) {
    5876     19535047 :         myOdometer += getLane()->getLength();
    5877              :     }
    5878     24052880 :     if (myLane != nullptr && myLane->getBidiLane() != nullptr && myAmOnNet
    5879     24126036 :             && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5880        48610 :         myLane->getBidiLane()->resetPartialOccupation(this);
    5881              :     }
    5882     24052909 :     if (reason != MSMoveReminder::NOTIFICATION_JUNCTION && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5883              :         // @note. In case of lane change, myFurtherLanes and partial occupation
    5884              :         // are handled in enterLaneAtLaneChange()
    5885      3431315 :         for (MSLane* further : myFurtherLanes) {
    5886              : #ifdef DEBUG_FURTHER
    5887              :             if (DEBUG_COND) {
    5888              :                 std::cout << SIMTIME << " leaveLane \n";
    5889              :             }
    5890              : #endif
    5891        32988 :             further->resetPartialOccupation(this);
    5892        32988 :             if (further->getBidiLane() != nullptr
    5893        32988 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5894            4 :                 further->getBidiLane()->resetPartialOccupation(this);
    5895              :             }
    5896              :         }
    5897              :         myFurtherLanes.clear();
    5898              :         myFurtherLanesPosLat.clear();
    5899              :     }
    5900      3398327 :     if (reason >= MSMoveReminder::NOTIFICATION_TELEPORT) {
    5901      3398327 :         myAmOnNet = false;
    5902      3398327 :         myWaitingTime = 0;
    5903              :     }
    5904     24052909 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && resumeFromStopping()) {
    5905           18 :         myStopDist = std::numeric_limits<double>::max();
    5906           18 :         if (myPastStops.back().speed <= 0) {
    5907           54 :             WRITE_WARNINGF(TL("Vehicle '%' aborts stop."), getID());
    5908              :         }
    5909              :     }
    5910     24052909 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5911     22899702 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()) {
    5912         1446 :             if (myStops.front().getSpeed() <= 0) {
    5913         3336 :                 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5914              :                                time2string(MSNet::getInstance()->getCurrentTimeStep()));
    5915         1112 :                 cleanupParkingReservation();
    5916         1112 :                 if (MSStopOut::active()) {
    5917              :                     // clean up if stopBlocked was called
    5918           22 :                     MSStopOut::getInstance()->stopNotStarted(this);
    5919              :                 }
    5920         1112 :                 myStops.pop_front();
    5921              :             } else {
    5922              :                 MSStop& stop = myStops.front();
    5923              :                 // passed waypoint at the end of the lane
    5924          334 :                 if (!stop.reached) {
    5925          334 :                     if (MSStopOut::active()) {
    5926           21 :                         MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), MSNet::getInstance()->getCurrentTimeStep());
    5927              :                     }
    5928          334 :                     stop.reached = true;
    5929              :                     // enter stopping place so leaveFrom works as expected
    5930          334 :                     if (stop.busstop != nullptr) {
    5931              :                         // let the bus stop know the vehicle
    5932           25 :                         stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5933              :                     }
    5934          334 :                     if (stop.containerstop != nullptr) {
    5935              :                         // let the container stop know the vehicle
    5936           13 :                         stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5937              :                     }
    5938              :                     // do not enter parkingarea!
    5939          334 :                     if (stop.chargingStation != nullptr) {
    5940              :                         // let the container stop know the vehicle
    5941          122 :                         stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5942              :                     }
    5943              :                 }
    5944          334 :                 resumeFromStopping();
    5945              :             }
    5946         1446 :             myStopDist = std::numeric_limits<double>::max();
    5947              :         }
    5948              :     }
    5949     24052909 : }
    5950              : 
    5951              : 
    5952              : void
    5953        45673 : MSVehicle::leaveLaneBack(const MSMoveReminder::Notification reason, const MSLane* leftLane) {
    5954       186220 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5955       140547 :         if (rem->first->notifyLeaveBack(*this, reason, leftLane)) {
    5956              : #ifdef _DEBUG
    5957              :             if (myTraceMoveReminders) {
    5958              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, true);
    5959              :             }
    5960              : #endif
    5961              :             ++rem;
    5962              :         } else {
    5963              : #ifdef _DEBUG
    5964              :             if (myTraceMoveReminders) {
    5965              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, false);
    5966              :             }
    5967              : #endif
    5968              :             rem = myMoveReminders.erase(rem);
    5969              :         }
    5970              :     }
    5971              : #ifdef DEBUG_MOVEREMINDERS
    5972              :     if (DEBUG_COND) {
    5973              :         std::cout << SIMTIME << " veh=" << getID() << " myReminders:";
    5974              :         for (auto rem : myMoveReminders) {
    5975              :             std::cout << rem.first->getDescription() << " ";
    5976              :         }
    5977              :         std::cout << "\n";
    5978              :     }
    5979              : #endif
    5980        45673 : }
    5981              : 
    5982              : 
    5983              : MSAbstractLaneChangeModel&
    5984  10320163873 : MSVehicle::getLaneChangeModel() {
    5985  10320163873 :     return *myLaneChangeModel;
    5986              : }
    5987              : 
    5988              : 
    5989              : const MSAbstractLaneChangeModel&
    5990   4919978412 : MSVehicle::getLaneChangeModel() const {
    5991   4919978412 :     return *myLaneChangeModel;
    5992              : }
    5993              : 
    5994              : bool
    5995       517940 : MSVehicle::isOppositeLane(const MSLane* lane) const {
    5996       517940 :     return (lane->isInternal()
    5997       517940 :             ? & (lane->getLinkCont()[0]->getLane()->getEdge()) != *(myCurrEdge + 1)
    5998       516188 :             : &lane->getEdge() != *myCurrEdge);
    5999              : }
    6000              : 
    6001              : const std::vector<MSVehicle::LaneQ>&
    6002   1345891349 : MSVehicle::getBestLanes() const {
    6003   1345891349 :     return *myBestLanes.begin();
    6004              : }
    6005              : 
    6006              : 
    6007              : void
    6008   1876640834 : MSVehicle::updateBestLanes(bool forceRebuild, const MSLane* startLane) {
    6009              : #ifdef DEBUG_BESTLANES
    6010              :     if (DEBUG_COND) {
    6011              :         std::cout << SIMTIME << " updateBestLanes veh=" << getID() << " force=" << forceRebuild << " startLane1=" << Named::getIDSecure(startLane) << " myLane=" << Named::getIDSecure(myLane) << "\n";
    6012              :     }
    6013              : #endif
    6014   1876640834 :     if (startLane == nullptr) {
    6015    993482301 :         startLane = myLane;
    6016              :     }
    6017              :     assert(startLane != 0);
    6018   1876640834 :     if (myLaneChangeModel->isOpposite()) {
    6019              :         // depending on the calling context, startLane might be the forward lane
    6020              :         // or the reverse-direction lane. In the latter case we need to
    6021              :         // transform it to the forward lane.
    6022       517940 :         if (isOppositeLane(startLane)) {
    6023              :             // use leftmost lane of forward edge
    6024       111128 :             startLane = startLane->getEdge().getOppositeEdge()->getLanes().back();
    6025              :             assert(startLane != 0);
    6026              : #ifdef DEBUG_BESTLANES
    6027              :             if (DEBUG_COND) {
    6028              :                 std::cout << "   startLaneIsOpposite newStartLane=" << startLane->getID() << "\n";
    6029              :             }
    6030              : #endif
    6031              :         }
    6032              :     }
    6033   1876640834 :     if (forceRebuild) {
    6034      1750333 :         myLastBestLanesEdge = nullptr;
    6035      1750333 :         myLastBestLanesInternalLane = nullptr;
    6036              :     }
    6037   1876640834 :     if (myBestLanes.size() > 0 && !forceRebuild && myLastBestLanesEdge == &startLane->getEdge()) {
    6038   1845661853 :         updateOccupancyAndCurrentBestLane(startLane);
    6039              : #ifdef DEBUG_BESTLANES
    6040              :         if (DEBUG_COND) {
    6041              :             std::cout << "  only updateOccupancyAndCurrentBestLane\n";
    6042              :         }
    6043              : #endif
    6044   1845661853 :         return;
    6045              :     }
    6046     30978981 :     if (startLane->getEdge().isInternal()) {
    6047     14848478 :         if (myBestLanes.size() == 0 || forceRebuild) {
    6048              :             // rebuilt from previous non-internal lane (may backtrack twice if behind an internal junction)
    6049         2302 :             updateBestLanes(true, startLane->getLogicalPredecessorLane());
    6050              :         }
    6051     14848478 :         if (myLastBestLanesInternalLane == startLane && !forceRebuild) {
    6052              : #ifdef DEBUG_BESTLANES
    6053              :             if (DEBUG_COND) {
    6054              :                 std::cout << "  nothing to do on internal\n";
    6055              :             }
    6056              : #endif
    6057              :             return;
    6058              :         }
    6059              :         // adapt best lanes to fit the current internal edge:
    6060              :         // keep the entries that are reachable from this edge
    6061      5274489 :         const MSEdge* nextEdge = startLane->getNextNormal();
    6062              :         assert(!nextEdge->isInternal());
    6063     10398180 :         for (std::vector<std::vector<LaneQ> >::iterator it = myBestLanes.begin(); it != myBestLanes.end();) {
    6064              :             std::vector<LaneQ>& lanes = *it;
    6065              :             assert(lanes.size() > 0);
    6066     10398180 :             if (&(lanes[0].lane->getEdge()) == nextEdge) {
    6067              :                 // keep those lanes which are successors of internal lanes from the edge of startLane
    6068      5274489 :                 std::vector<LaneQ> oldLanes = lanes;
    6069              :                 lanes.clear();
    6070              :                 const std::vector<MSLane*>& sourceLanes = startLane->getEdge().getLanes();
    6071     11939113 :                 for (std::vector<MSLane*>::const_iterator it_source = sourceLanes.begin(); it_source != sourceLanes.end(); ++it_source) {
    6072     11245053 :                     for (std::vector<LaneQ>::iterator it_lane = oldLanes.begin(); it_lane != oldLanes.end(); ++it_lane) {
    6073     11245053 :                         if ((*it_source)->getLinkCont()[0]->getLane() == (*it_lane).lane) {
    6074      6664624 :                             lanes.push_back(*it_lane);
    6075              :                             break;
    6076              :                         }
    6077              :                     }
    6078              :                 }
    6079              :                 assert(lanes.size() == startLane->getEdge().getLanes().size());
    6080              :                 // patch invalid bestLaneOffset and updated myCurrentLaneInBestLanes
    6081     11939113 :                 for (int i = 0; i < (int)lanes.size(); ++i) {
    6082      6664624 :                     if (i + lanes[i].bestLaneOffset < 0) {
    6083       106754 :                         lanes[i].bestLaneOffset = -i;
    6084              :                     }
    6085      6664624 :                     if (i + lanes[i].bestLaneOffset >= (int)lanes.size()) {
    6086        26893 :                         lanes[i].bestLaneOffset = (int)lanes.size() - i - 1;
    6087              :                     }
    6088              :                     assert(i + lanes[i].bestLaneOffset >= 0);
    6089              :                     assert(i + lanes[i].bestLaneOffset < (int)lanes.size());
    6090      6664624 :                     if (lanes[i].bestContinuations[0] != 0) {
    6091              :                         // patch length of bestContinuation to match expectations (only once)
    6092      6467917 :                         lanes[i].bestContinuations.insert(lanes[i].bestContinuations.begin(), (MSLane*)nullptr);
    6093              :                     }
    6094      6664624 :                     if (startLane->getLinkCont()[0]->getLane() == lanes[i].lane) {
    6095      5318511 :                         myCurrentLaneInBestLanes = lanes.begin() + i;
    6096              :                     }
    6097              :                     assert(&(lanes[i].lane->getEdge()) == nextEdge);
    6098              :                 }
    6099      5274489 :                 myLastBestLanesInternalLane = startLane;
    6100      5274489 :                 updateOccupancyAndCurrentBestLane(startLane);
    6101              : #ifdef DEBUG_BESTLANES
    6102              :                 if (DEBUG_COND) {
    6103              :                     std::cout << "  updated for internal\n";
    6104              :                 }
    6105              : #endif
    6106              :                 return;
    6107      5274489 :             } else {
    6108              :                 // remove passed edges
    6109      5123691 :                 it = myBestLanes.erase(it);
    6110              :             }
    6111              :         }
    6112              :         assert(false); // should always find the next edge
    6113              :     }
    6114              :     // start rebuilding
    6115     16130503 :     myLastBestLanesInternalLane = nullptr;
    6116     16130503 :     myLastBestLanesEdge = &startLane->getEdge();
    6117              :     myBestLanes.clear();
    6118              : 
    6119              :     // get information about the next stop
    6120     16130503 :     MSRouteIterator nextStopEdge = myRoute->end();
    6121              :     const MSLane* nextStopLane = nullptr;
    6122              :     double nextStopPos = 0;
    6123     16130503 :     if (!myStops.empty()) {
    6124              :         const MSStop& nextStop = myStops.front();
    6125       259923 :         nextStopLane = nextStop.lane;
    6126       259923 :         if (nextStop.isOpposite) {
    6127              :             // target leftmost lane in forward direction
    6128          340 :             nextStopLane = nextStopLane->getEdge().getOppositeEdge()->getLanes().back();
    6129              :         }
    6130       259923 :         nextStopEdge = nextStop.edge;
    6131       259923 :         nextStopPos = nextStop.pars.startPos;
    6132              :     }
    6133              :     // myArrivalTime = -1 in the context of validating departSpeed with departLane=best
    6134     16130503 :     if (myParameter->arrivalLaneProcedure >= ArrivalLaneDefinition::GIVEN && nextStopEdge == myRoute->end() && myArrivalLane >= 0) {
    6135       339319 :         nextStopEdge = (myRoute->end() - 1);
    6136       339319 :         nextStopLane = (*nextStopEdge)->getLanes()[myArrivalLane];
    6137       339319 :         nextStopPos = myArrivalPos;
    6138              :     }
    6139     16130503 :     if (nextStopEdge != myRoute->end()) {
    6140              :         // make sure that the "wrong" lanes get a penalty. (penalty needs to be
    6141              :         // large enough to overcome a magic threshold in MSLaneChangeModel::DK2004.cpp:383)
    6142       599242 :         nextStopPos = MAX2(POSITION_EPS, MIN2((double)nextStopPos, (double)(nextStopLane->getLength() - 2 * POSITION_EPS)));
    6143       599242 :         if (nextStopLane->isInternal()) {
    6144              :             // switch to the correct lane before entering the intersection
    6145          171 :             nextStopPos = (*nextStopEdge)->getLength();
    6146              :         }
    6147              :     }
    6148              : 
    6149              :     // go forward along the next lanes; always look past stops to ensure that we
    6150              :     // know where to go once the stop ends
    6151              :     // trains do not have to deal with lane-changing for stops but their best
    6152              :     // lanes lookahead is needed for rail signal control
    6153              :     int seen = 0;
    6154              :     double seenLength = 0;
    6155              :     bool progress = true;
    6156              :     // bestLanes must cover the braking distance even when at the very end of the current lane to avoid unecessary slow down
    6157     32261006 :     const double maxBrakeDist = startLane->getLength() + getCarFollowModel().getHeadwayTime() * getMaxSpeed() + getCarFollowModel().brakeGap(getMaxSpeed()) + getVehicleType().getMinGap();
    6158     16130503 :     const double lookahead = getLaneChangeModel().getStrategicLookahead();
    6159     81505352 :     for (MSRouteIterator ce = myCurrEdge; progress;) {
    6160              :         std::vector<LaneQ> currentLanes;
    6161              :         const std::vector<MSLane*>* allowed = nullptr;
    6162              :         const MSEdge* nextEdge = nullptr;
    6163     65374849 :         if (ce != myRoute->end() && ce + 1 != myRoute->end()) {
    6164     53366797 :             nextEdge = *(ce + 1);
    6165     53366797 :             allowed = (*ce)->allowedLanes(*nextEdge, myType->getVehicleClass());
    6166              :         }
    6167     65374849 :         const std::vector<MSLane*>& lanes = (*ce)->getLanes();
    6168    165400123 :         for (std::vector<MSLane*>::const_iterator i = lanes.begin(); i != lanes.end(); ++i) {
    6169              :             LaneQ q;
    6170    100025274 :             MSLane* cl = *i;
    6171    100025274 :             q.lane = cl;
    6172    100025274 :             q.bestContinuations.push_back(cl);
    6173    100025274 :             q.bestLaneOffset = 0;
    6174    100025274 :             q.length = cl->allowsVehicleClass(myType->getVehicleClass()) ? (*ce)->getLength() : 0;
    6175    100025274 :             q.currentLength = q.length;
    6176              :             // if all lanes are forbidden (i.e. due to a dynamic closing) we want to express no preference
    6177    100025274 :             q.allowsContinuation = allowed == nullptr || std::find(allowed->begin(), allowed->end(), cl) != allowed->end();
    6178    100025274 :             q.occupation = 0;
    6179    100025274 :             q.nextOccupation = 0;
    6180    100025274 :             currentLanes.push_back(q);
    6181              :         }
    6182              :         //
    6183              :         if (nextStopEdge == ce
    6184              :                 // already past the stop edge
    6185     65374849 :                 && !(ce == myCurrEdge && myLane != nullptr && myLane->isInternal())) {
    6186       592163 :             const MSLane* normalStopLane = nextStopLane->getNormalPredecessorLane();
    6187      1878360 :             for (std::vector<LaneQ>::iterator q = currentLanes.begin(); q != currentLanes.end(); ++q) {
    6188      1286197 :                 if (nextStopLane != nullptr && normalStopLane != (*q).lane) {
    6189       694034 :                     (*q).allowsContinuation = false;
    6190       694034 :                     (*q).length = nextStopPos;
    6191       694034 :                     (*q).currentLength = (*q).length;
    6192              :                 }
    6193              :             }
    6194              :         }
    6195              : 
    6196     65374849 :         myBestLanes.push_back(currentLanes);
    6197     65374849 :         ++seen;
    6198     65374849 :         seenLength += currentLanes[0].lane->getLength();
    6199              :         ++ce;
    6200     65374849 :         if (lookahead >= 0) {
    6201           45 :             progress &= (seen <= 2 || seenLength < lookahead); // custom (but we need to look at least one edge ahead)
    6202              :         } else {
    6203     86866547 :             progress &= (seen <= 4 || seenLength < MAX2(maxBrakeDist, 3000.0)); // motorway
    6204     70238773 :             progress &= (seen <= 8 || seenLength < MAX2(maxBrakeDist, 200.0) || isRailway(getVClass()));  // urban
    6205              :         }
    6206     65374849 :         progress &= ce != myRoute->end();
    6207              :         /*
    6208              :         if(progress) {
    6209              :           progress &= (currentLanes.size()!=1||(*ce)->getLanes().size()!=1);
    6210              :         }
    6211              :         */
    6212     65374849 :     }
    6213              : 
    6214              :     // we are examining the last lane explicitly
    6215     16130503 :     if (myBestLanes.size() != 0) {
    6216              :         double bestLength = -1;
    6217              :         // minimum and maximum lane index with best length
    6218              :         int bestThisIndex = 0;
    6219              :         int bestThisMaxIndex = 0;
    6220              :         int index = 0;
    6221              :         std::vector<LaneQ>& last = myBestLanes.back();
    6222     41968908 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6223     25838405 :             if ((*j).length > bestLength) {
    6224              :                 bestLength = (*j).length;
    6225              :                 bestThisIndex = index;
    6226              :                 bestThisMaxIndex = index;
    6227      6146554 :             } else if ((*j).length == bestLength) {
    6228              :                 bestThisMaxIndex = index;
    6229              :             }
    6230              :         }
    6231              :         index = 0;
    6232              :         bool requiredChangeRightForbidden = false;
    6233              :         int requireChangeToLeftForbidden = -1;
    6234     41968908 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6235     25838405 :             if ((*j).length < bestLength) {
    6236      3962053 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6237       145528 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6238              :                 } else {
    6239      3816525 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6240              :                 }
    6241      3962053 :                 if (!(*j).allowsContinuation) {
    6242       565811 :                     if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6243       252094 :                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6244       249441 :                                 || requiredChangeRightForbidden)) {
    6245              :                         // this lane and all further lanes to the left cannot be used
    6246              :                         requiredChangeRightForbidden = true;
    6247         2653 :                         (*j).length = 0;
    6248       563158 :                     } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6249       313691 :                                 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6250              :                         // this lane and all previous lanes to the right cannot be used
    6251         6427 :                         requireChangeToLeftForbidden = (*j).lane->getIndex();
    6252              :                     }
    6253              :                 }
    6254              :             }
    6255              :         }
    6256     16136940 :         for (int i = requireChangeToLeftForbidden; i >= 0; i--) {
    6257         6437 :             if (last[i].bestLaneOffset > 0) {
    6258         6437 :                 last[i].length = 0;
    6259              :             }
    6260              :         }
    6261              : #ifdef DEBUG_BESTLANES
    6262              :         if (DEBUG_COND) {
    6263              :             std::cout << "   last edge=" << last.front().lane->getEdge().getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6264              :             std::vector<LaneQ>& laneQs = myBestLanes.back();
    6265              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6266              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << "\n";
    6267              :             }
    6268              :         }
    6269              : #endif
    6270              :     }
    6271              :     // go backward through the lanes
    6272              :     // track back best lane and compute the best prior lane(s)
    6273     65374849 :     for (std::vector<std::vector<LaneQ> >::reverse_iterator i = myBestLanes.rbegin() + 1; i != myBestLanes.rend(); ++i) {
    6274              :         std::vector<LaneQ>& nextLanes = (*(i - 1));
    6275              :         std::vector<LaneQ>& clanes = (*i);
    6276     49244346 :         MSEdge* const cE = &clanes[0].lane->getEdge();
    6277              :         int index = 0;
    6278              :         double bestConnectedLength = -1;
    6279              :         double bestLength = -1;
    6280    122729043 :         for (const LaneQ& j : nextLanes) {
    6281    146969394 :             if (j.lane->isApproachedFrom(cE) && bestConnectedLength < j.length) {
    6282              :                 bestConnectedLength = j.length;
    6283              :             }
    6284     73484697 :             if (bestLength < j.length) {
    6285              :                 bestLength = j.length;
    6286              :             }
    6287              :         }
    6288              :         // compute index of the best lane (highest length and least offset from the best next lane)
    6289              :         int bestThisIndex = 0;
    6290              :         int bestThisMaxIndex = 0;
    6291     49244346 :         if (bestConnectedLength > 0) {
    6292              :             index = 0;
    6293    123395662 :             for (LaneQ& j : clanes) {
    6294              :                 const LaneQ* bestConnectedNext = nullptr;
    6295     74163914 :                 if (j.allowsContinuation) {
    6296    176531143 :                     for (const LaneQ& m : nextLanes) {
    6297    122011768 :                         if ((m.lane->allowsVehicleClass(getVClass()) || m.lane->hadPermissionChanges())
    6298    112412853 :                                 && m.lane->isApproachedFrom(j.lane, getVClass())) {
    6299     66317976 :                             if (betterContinuation(bestConnectedNext, m)) {
    6300              :                                 bestConnectedNext = &m;
    6301              :                             }
    6302              :                         }
    6303              :                     }
    6304     64175582 :                     if (bestConnectedNext != nullptr) {
    6305     64175574 :                         if (bestConnectedNext->length == bestConnectedLength && abs(bestConnectedNext->bestLaneOffset) < 2) {
    6306     62415802 :                             j.length += bestLength;
    6307              :                         } else {
    6308      1759772 :                             j.length += bestConnectedNext->length;
    6309              :                         }
    6310     64175574 :                         j.bestLaneOffset = bestConnectedNext->bestLaneOffset;
    6311              :                     }
    6312              :                 }
    6313     64175574 :                 if (bestConnectedNext != nullptr && (bestConnectedNext->allowsContinuation || bestConnectedNext->length > 0)) {
    6314     64137575 :                     copy(bestConnectedNext->bestContinuations.begin(), bestConnectedNext->bestContinuations.end(), back_inserter(j.bestContinuations));
    6315              :                 } else {
    6316     10026339 :                     j.allowsContinuation = false;
    6317              :                 }
    6318     74163914 :                 if (clanes[bestThisIndex].length < j.length
    6319     67023766 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) > abs(j.bestLaneOffset))
    6320    203841340 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset) &&
    6321     62798002 :                             nextLinkPriority(clanes[bestThisIndex].bestContinuations) < nextLinkPriority(j.bestContinuations))
    6322              :                    ) {
    6323              :                     bestThisIndex = index;
    6324              :                     bestThisMaxIndex = index;
    6325     66867553 :                 } else if (clanes[bestThisIndex].length == j.length
    6326     62786263 :                            && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset)
    6327    129653684 :                            && nextLinkPriority(clanes[bestThisIndex].bestContinuations) == nextLinkPriority(j.bestContinuations)) {
    6328              :                     bestThisMaxIndex = index;
    6329              :                 }
    6330     74163914 :                 index++;
    6331              :             }
    6332              : 
    6333              :             //vehicle with elecHybrid device prefers running under an overhead wire
    6334     49231748 :             if (getDevice(typeid(MSDevice_ElecHybrid)) != nullptr) {
    6335              :                 index = 0;
    6336          491 :                 for (const LaneQ& j : clanes) {
    6337          339 :                     std::string overheadWireSegmentID = MSNet::getInstance()->getStoppingPlaceID(j.lane, j.currentLength / 2., SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6338          339 :                     if (overheadWireSegmentID != "") {
    6339              :                         bestThisIndex = index;
    6340              :                         bestThisMaxIndex = index;
    6341              :                     }
    6342          339 :                     index++;
    6343              :                 }
    6344              :             }
    6345              : 
    6346              :         } else {
    6347              :             // only needed in case of disconnected routes
    6348              :             int bestNextIndex = 0;
    6349        12598 :             int bestDistToNeeded = (int) clanes.size();
    6350              :             index = 0;
    6351        35553 :             for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6352        22955 :                 if ((*j).allowsContinuation) {
    6353              :                     int nextIndex = 0;
    6354        56759 :                     for (std::vector<LaneQ>::const_iterator m = nextLanes.begin(); m != nextLanes.end(); ++m, ++nextIndex) {
    6355        34553 :                         if ((*m).lane->isApproachedFrom((*j).lane, getVClass())) {
    6356         5023 :                             if (bestDistToNeeded > abs((*m).bestLaneOffset)) {
    6357              :                                 bestDistToNeeded = abs((*m).bestLaneOffset);
    6358              :                                 bestThisIndex = index;
    6359              :                                 bestThisMaxIndex = index;
    6360              :                                 bestNextIndex = nextIndex;
    6361              :                             }
    6362              :                         }
    6363              :                     }
    6364              :                 }
    6365              :             }
    6366        12598 :             clanes[bestThisIndex].length += nextLanes[bestNextIndex].length;
    6367        12598 :             copy(nextLanes[bestNextIndex].bestContinuations.begin(), nextLanes[bestNextIndex].bestContinuations.end(), back_inserter(clanes[bestThisIndex].bestContinuations));
    6368              : 
    6369              :         }
    6370              :         // set bestLaneOffset for all lanes
    6371              :         index = 0;
    6372              :         bool requiredChangeRightForbidden = false;
    6373              :         int requireChangeToLeftForbidden = -1;
    6374    123431215 :         for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6375     74186869 :             if ((*j).length < clanes[bestThisIndex].length
    6376     62456538 :                     || ((*j).length == clanes[bestThisIndex].length && abs((*j).bestLaneOffset) > abs(clanes[bestThisIndex].bestLaneOffset))
    6377    136643175 :                     || (nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)
    6378              :                ) {
    6379     11907268 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6380       771342 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6381              :                 } else {
    6382     11135926 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6383              :                 }
    6384     11907268 :                 if ((nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)) {
    6385              :                     // try to move away from the lower-priority lane before it ends
    6386     10193187 :                     (*j).length = (*j).currentLength;
    6387              :                 }
    6388     11907268 :                 if (!(*j).allowsContinuation) {
    6389     10012095 :                     if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6390      2569130 :                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6391      2554944 :                                 || requiredChangeRightForbidden)) {
    6392              :                         // this lane and all further lanes to the left cannot be used
    6393              :                         requiredChangeRightForbidden = true;
    6394        28500 :                         if ((*j).length == (*j).currentLength) {
    6395        28500 :                             (*j).length = 0;
    6396              :                         }
    6397      9983595 :                     } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6398      7385613 :                                 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6399              :                         // this lane and all previous lanes to the right cannot be used
    6400       114110 :                         requireChangeToLeftForbidden = (*j).lane->getIndex();
    6401              :                     }
    6402              :                 }
    6403              :             } else {
    6404     62279601 :                 (*j).bestLaneOffset = 0;
    6405              :             }
    6406              :         }
    6407     49376699 :         for (int idx = requireChangeToLeftForbidden; idx >= 0; idx--) {
    6408       132353 :             if (clanes[idx].length == clanes[idx].currentLength) {
    6409       132353 :                 clanes[idx].length = 0;
    6410              :             };
    6411              :         }
    6412              : 
    6413              :         //vehicle with elecHybrid device prefers running under an overhead wire
    6414     49244346 :         if (static_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid))) != 0) {
    6415              :             index = 0;
    6416          152 :             std::string overheadWireID = MSNet::getInstance()->getStoppingPlaceID(clanes[bestThisIndex].lane, (clanes[bestThisIndex].currentLength) / 2, SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6417          152 :             if (overheadWireID != "") {
    6418          373 :                 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6419          261 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6420              :                 }
    6421              :             }
    6422              :         }
    6423              : 
    6424              : #ifdef DEBUG_BESTLANES
    6425              :         if (DEBUG_COND) {
    6426              :             std::cout << "   edge=" << cE->getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6427              :             std::vector<LaneQ>& laneQs = clanes;
    6428              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6429              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << " allowCont=" << (*j).allowsContinuation << "\n";
    6430              :             }
    6431              :         }
    6432              : #endif
    6433              : 
    6434              :     }
    6435     16130503 :     if (myBestLanes.front().front().lane->isInternal()) {
    6436              :         // route starts on an internal lane
    6437           28 :         if (myLane != nullptr) {
    6438              :             startLane = myLane;
    6439              :         } else {
    6440              :             // vehicle not yet departed
    6441           12 :             startLane = myBestLanes.front().front().lane;
    6442              :         }
    6443              :     }
    6444     16130503 :     updateOccupancyAndCurrentBestLane(startLane);
    6445              : #ifdef DEBUG_BESTLANES
    6446              :     if (DEBUG_COND) {
    6447              :         std::cout << SIMTIME << " veh=" << getID() << " bestCont=" << toString(getBestLanesContinuation()) << "\n";
    6448              :     }
    6449              : #endif
    6450              : }
    6451              : 
    6452              : void
    6453          249 : MSVehicle::updateLaneBruttoSum() {
    6454          249 :     if (myLane != nullptr) {
    6455          249 :         myLane->markRecalculateBruttoSum();
    6456              :     }
    6457          249 : }
    6458              : 
    6459              : bool
    6460     66317976 : MSVehicle::betterContinuation(const LaneQ* bestConnectedNext, const LaneQ& m) const {
    6461     66317976 :     if (bestConnectedNext == nullptr) {
    6462              :         return true;
    6463      2142402 :     } else if (m.lane->getBidiLane() != nullptr && bestConnectedNext->lane->getBidiLane() == nullptr) {
    6464              :         return false;
    6465      2141610 :     } else if (bestConnectedNext->lane->getBidiLane() != nullptr && m.lane->getBidiLane() == nullptr) {
    6466              :         return true;
    6467      2141610 :     } else if (bestConnectedNext->length < m.length) {
    6468              :         return true;
    6469      1775501 :     } else if (bestConnectedNext->length == m.length) {
    6470      1247452 :         if (abs(bestConnectedNext->bestLaneOffset) > abs(m.bestLaneOffset)) {
    6471              :             return true;
    6472              :         }
    6473      1081245 :         const double contRight = getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_CONTRIGHT, 1);
    6474              :         if (contRight < 1
    6475              :                 // if we don't check for adjacency, the rightmost line will get
    6476              :                 // multiple chances to be better which leads to an uninituitve distribution
    6477         1008 :                 && (m.lane->getIndex() - bestConnectedNext->lane->getIndex()) == 1
    6478      1082026 :                 && RandHelper::rand(getRNG()) > contRight) {
    6479              :             return true;
    6480              :         }
    6481              :     }
    6482              :     return false;
    6483              : }
    6484              : 
    6485              : 
    6486              : int
    6487    399895414 : MSVehicle::nextLinkPriority(const std::vector<MSLane*>& conts) {
    6488    399895414 :     if (conts.size() < 2) {
    6489              :         return -1;
    6490              :     } else {
    6491    364045775 :         const MSLink* const link = conts[0]->getLinkTo(conts[1]);
    6492    364045775 :         if (link != nullptr) {
    6493    364024092 :             return link->havePriority() ? 1 : 0;
    6494              :         } else {
    6495              :             // disconnected route
    6496              :             return -1;
    6497              :         }
    6498              :     }
    6499              : }
    6500              : 
    6501              : 
    6502              : void
    6503   1867066845 : MSVehicle::updateOccupancyAndCurrentBestLane(const MSLane* startLane) {
    6504              :     std::vector<LaneQ>& currLanes = *myBestLanes.begin();
    6505              :     std::vector<LaneQ>::iterator i;
    6506              : #ifdef _DEBUG
    6507              :     bool found = false;
    6508              : #endif
    6509   5341396315 :     for (i = currLanes.begin(); i != currLanes.end(); ++i) {
    6510              :         double nextOccupation = 0;
    6511   7646295760 :         for (std::vector<MSLane*>::const_iterator j = (*i).bestContinuations.begin() + 1; j != (*i).bestContinuations.end(); ++j) {
    6512   4171966290 :             nextOccupation += (*j)->getBruttoVehLenSum();
    6513              :         }
    6514   3474329470 :         (*i).nextOccupation = nextOccupation;
    6515              : #ifdef DEBUG_BESTLANES
    6516              :         if (DEBUG_COND) {
    6517              :             std::cout << "     lane=" << (*i).lane->getID() << " nextOccupation=" << nextOccupation << "\n";
    6518              :         }
    6519              : #endif
    6520   3474329470 :         if ((*i).lane == startLane) {
    6521   1861792356 :             myCurrentLaneInBestLanes = i;
    6522              : #ifdef _DEBUG
    6523              :             found = true;
    6524              : #endif
    6525              :         }
    6526              :     }
    6527              : #ifdef _DEBUG
    6528              :     assert(found || startLane->isInternal());
    6529              : #endif
    6530   1867066845 : }
    6531              : 
    6532              : 
    6533              : const std::vector<MSLane*>&
    6534   2044596497 : MSVehicle::getBestLanesContinuation() const {
    6535   2044596497 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6536              :         return myEmptyLaneVector;
    6537              :     }
    6538   2044596497 :     return (*myCurrentLaneInBestLanes).bestContinuations;
    6539              : }
    6540              : 
    6541              : 
    6542              : const std::vector<MSLane*>&
    6543     69565787 : MSVehicle::getBestLanesContinuation(const MSLane* const l) const {
    6544              :     const MSLane* lane = l;
    6545              :     // XXX: shouldn't this be a "while" to cover more than one internal lane? (Leo) Refs. #2575
    6546     69565787 :     if (lane->getEdge().isInternal()) {
    6547              :         // internal edges are not kept inside the bestLanes structure
    6548      5106834 :         lane = lane->getLinkCont()[0]->getLane();
    6549              :     }
    6550     69565787 :     if (myBestLanes.size() == 0) {
    6551              :         return myEmptyLaneVector;
    6552              :     }
    6553    114895720 :     for (std::vector<LaneQ>::const_iterator i = myBestLanes[0].begin(); i != myBestLanes[0].end(); ++i) {
    6554    114883106 :         if ((*i).lane == lane) {
    6555     69553173 :             return (*i).bestContinuations;
    6556              :         }
    6557              :     }
    6558              :     return myEmptyLaneVector;
    6559              : }
    6560              : 
    6561              : const std::vector<const MSLane*>
    6562       287533 : MSVehicle::getUpcomingLanesUntil(double distance) const {
    6563              :     std::vector<const MSLane*> lanes;
    6564              : 
    6565       287533 :     if (distance <= 0. || hasArrived()) {
    6566              :         // WRITE_WARNINGF(TL("MSVehicle::getUpcomingLanesUntil(): distance ('%') should be greater than 0."), distance);
    6567              :         return lanes;
    6568              :     }
    6569              : 
    6570       287327 :     if (!myLaneChangeModel->isOpposite()) {
    6571       284001 :         distance += getPositionOnLane();
    6572              :     } else {
    6573         3326 :         distance += myLane->getOppositePos(getPositionOnLane());
    6574              :     }
    6575       287327 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6576       295361 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6577         8034 :         lanes.insert(lanes.end(), lane);
    6578         8034 :         distance -= lane->getLength();
    6579        13515 :         lane = lane->getLinkCont().front()->getViaLaneOrLane();
    6580              :     }
    6581              : 
    6582       287327 :     const std::vector<MSLane*>& contLanes = getBestLanesContinuation();
    6583       287327 :     if (contLanes.empty()) {
    6584              :         return lanes;
    6585              :     }
    6586              :     auto contLanesIt = contLanes.begin();
    6587       287327 :     MSRouteIterator routeIt = myCurrEdge;  // keep track of covered edges in myRoute
    6588       615111 :     while (distance > 0.) {
    6589       335584 :         MSLane* l = nullptr;
    6590       335584 :         if (contLanesIt != contLanes.end()) {
    6591       319711 :             l = *contLanesIt;
    6592              :             if (l != nullptr) {
    6593              :                 assert(l->getEdge().getID() == (*routeIt)->getLanes().front()->getEdge().getID());
    6594              :             }
    6595              :             ++contLanesIt;
    6596       319711 :             if (l != nullptr || myLane->isInternal()) {
    6597              :                 ++routeIt;
    6598              :             }
    6599       319711 :             if (l == nullptr) {
    6600         5477 :                 continue;
    6601              :             }
    6602        15873 :         } else if (routeIt != myRoute->end()) {  // bestLanes didn't get us far enough
    6603              :             // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6604         8962 :             l = (*routeIt)->getLanes().back();
    6605              :             ++routeIt;
    6606              :         } else {  // the search distance goes beyond our route
    6607              :             break;
    6608              :         }
    6609              : 
    6610              :         assert(l != nullptr);
    6611              : 
    6612              :         // insert internal lanes if applicable
    6613       323196 :         const MSLane* internalLane = lanes.size() > 0 ? lanes.back()->getInternalFollowingLane(l) : nullptr;
    6614       367351 :         while ((internalLane != nullptr) && internalLane->isInternal() && (distance > 0.)) {
    6615        44155 :             lanes.insert(lanes.end(), internalLane);
    6616        44155 :             distance -= internalLane->getLength();
    6617        70567 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6618              :         }
    6619       323196 :         if (distance <= 0.) {
    6620              :             break;
    6621              :         }
    6622              : 
    6623       322307 :         lanes.insert(lanes.end(), l);
    6624       322307 :         distance -= l->getLength();
    6625              :     }
    6626              : 
    6627              :     return lanes;
    6628            0 : }
    6629              : 
    6630              : const std::vector<const MSLane*>
    6631         6694 : MSVehicle::getPastLanesUntil(double distance) const {
    6632              :     std::vector<const MSLane*> lanes;
    6633              : 
    6634         6694 :     if (distance <= 0.) {
    6635              :         // WRITE_WARNINGF(TL("MSVehicle::getPastLanesUntil(): distance ('%') should be greater than 0."), distance);
    6636              :         return lanes;
    6637              :     }
    6638              : 
    6639         6586 :     MSRouteIterator routeIt = myCurrEdge;
    6640         6586 :     if (!myLaneChangeModel->isOpposite()) {
    6641         6562 :         distance += myLane->getLength() - getPositionOnLane();
    6642              :     } else {
    6643           24 :         distance += myLane->getParallelOpposite()->getLength() - myLane->getOppositePos(getPositionOnLane());
    6644              :     }
    6645         6586 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6646         6607 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6647           21 :         lanes.insert(lanes.end(), lane);
    6648           21 :         distance -= lane->getLength();
    6649           21 :         lane = lane->getLogicalPredecessorLane();
    6650              :     }
    6651              : 
    6652        10136 :     while (distance > 0.) {
    6653              :         // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6654         8799 :         MSLane* l = (*routeIt)->getLanes().back();
    6655              : 
    6656              :         // insert internal lanes if applicable
    6657         8799 :         const MSEdge* internalEdge = lanes.size() > 0 ? (*routeIt)->getInternalFollowingEdge(&(lanes.back()->getEdge()), getVClass()) : nullptr;
    6658         8820 :         const MSLane* internalLane = internalEdge != nullptr ? internalEdge->getLanes().front() : nullptr;
    6659              :         std::vector<const MSLane*> internalLanes;
    6660        11018 :         while ((internalLane != nullptr) && internalLane->isInternal()) {  // collect all internal successor lanes
    6661         2219 :             internalLanes.insert(internalLanes.begin(), internalLane);
    6662         4432 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6663              :         }
    6664        11018 :         for (auto it = internalLanes.begin(); (it != internalLanes.end()) && (distance > 0.); ++it) {  // check remaining distance in correct order
    6665         2219 :             lanes.insert(lanes.end(), *it);
    6666         2219 :             distance -= (*it)->getLength();
    6667              :         }
    6668         8799 :         if (distance <= 0.) {
    6669              :             break;
    6670              :         }
    6671              : 
    6672         8783 :         lanes.insert(lanes.end(), l);
    6673         8783 :         distance -= l->getLength();
    6674              : 
    6675              :         // NOTE: we're going backwards with the (bi-directional) Iterator
    6676              :         // TODO: consider make reverse_iterator() when moving on to C++14 or later
    6677         8783 :         if (routeIt != myRoute->begin()) {
    6678              :             --routeIt;
    6679              :         } else {  // we went backwards to begin() and already processed the first and final element
    6680              :             break;
    6681              :         }
    6682         8799 :     }
    6683              : 
    6684              :     return lanes;
    6685            0 : }
    6686              : 
    6687              : 
    6688              : const std::vector<MSLane*>
    6689         6358 : MSVehicle::getUpstreamOppositeLanes() const {
    6690         6358 :     const std::vector<const MSLane*> routeLanes = getPastLanesUntil(myLane->getMaximumBrakeDist());
    6691              :     std::vector<MSLane*> result;
    6692        15551 :     for (const MSLane* lane : routeLanes) {
    6693         9917 :         MSLane* opposite = lane->getOpposite();
    6694         9917 :         if (opposite != nullptr) {
    6695         9193 :             result.push_back(opposite);
    6696              :         } else {
    6697              :             break;
    6698              :         }
    6699              :     }
    6700         6358 :     return result;
    6701         6358 : }
    6702              : 
    6703              : 
    6704              : int
    6705    306935337 : MSVehicle::getBestLaneOffset() const {
    6706    306935337 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6707              :         return 0;
    6708              :     } else {
    6709    306648390 :         return (*myCurrentLaneInBestLanes).bestLaneOffset;
    6710              :     }
    6711              : }
    6712              : 
    6713              : double
    6714        23262 : MSVehicle::getBestLaneDist() const {
    6715        23262 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6716              :         return -1;
    6717              :     } else {
    6718        23262 :         return (*myCurrentLaneInBestLanes).length;
    6719              :     }
    6720              : }
    6721              : 
    6722              : 
    6723              : 
    6724              : void
    6725    647944848 : MSVehicle::adaptBestLanesOccupation(int laneIndex, double density) {
    6726              :     std::vector<MSVehicle::LaneQ>& preb = myBestLanes.front();
    6727              :     assert(laneIndex < (int)preb.size());
    6728    647944848 :     preb[laneIndex].occupation = density + preb[laneIndex].nextOccupation;
    6729    647944848 : }
    6730              : 
    6731              : 
    6732              : void
    6733        71319 : MSVehicle::fixPosition() {
    6734        71319 :     if (MSGlobals::gLaneChangeDuration > 0 && !myLaneChangeModel->isChangingLanes()) {
    6735        39640 :         myState.myPosLat = 0;
    6736              :     }
    6737        71319 : }
    6738              : 
    6739              : std::pair<const MSLane*, double>
    6740          303 : MSVehicle::getLanePosAfterDist(double distance) const {
    6741          303 :     if (distance == 0) {
    6742          255 :         return std::make_pair(myLane, getPositionOnLane());
    6743              :     }
    6744           48 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(distance);
    6745           48 :     distance += getPositionOnLane();
    6746           48 :     for (const MSLane* lane : lanes) {
    6747           48 :         if (lane->getLength() > distance) {
    6748              :             return std::make_pair(lane, distance);
    6749              :         }
    6750            0 :         distance -= lane->getLength();
    6751              :     }
    6752            0 :     return std::make_pair(nullptr, -1);
    6753           48 : }
    6754              : 
    6755              : 
    6756              : double
    6757        16062 : MSVehicle::getDistanceToPosition(double destPos, const MSLane* destLane) const {
    6758        16062 :     if (isOnRoad() && destLane != nullptr) {
    6759        16025 :         return myRoute->getDistanceBetween(getPositionOnLane(), destPos, myLane, destLane);
    6760              :     }
    6761              :     return std::numeric_limits<double>::max();
    6762              : }
    6763              : 
    6764              : 
    6765              : std::pair<const MSVehicle* const, double>
    6766     76425837 : MSVehicle::getLeader(double dist, bool considerCrossingFoes) const {
    6767     76425837 :     if (myLane == nullptr) {
    6768            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6769              :     }
    6770     76425837 :     if (dist == 0) {
    6771         2460 :         dist = getCarFollowModel().brakeGap(getSpeed()) + getVehicleType().getMinGap();
    6772              :     }
    6773              :     const MSVehicle* lead = nullptr;
    6774     76425837 :     const MSLane* lane = myLane; // ensure lane does not change between getVehiclesSecure and releaseVehicles;
    6775     76425837 :     const MSLane::VehCont& vehs = lane->getVehiclesSecure();
    6776              :     // vehicle might be outside the road network
    6777     76425837 :     MSLane::VehCont::const_iterator it = std::find(vehs.begin(), vehs.end(), this);
    6778     76425837 :     if (it != vehs.end() && it + 1 != vehs.end()) {
    6779     72703355 :         lead = *(it + 1);
    6780              :     }
    6781     72703355 :     if (lead != nullptr) {
    6782              :         std::pair<const MSVehicle* const, double> result(
    6783     72703355 :             lead, lead->getBackPositionOnLane(myLane) - getPositionOnLane() - getVehicleType().getMinGap());
    6784     72703355 :         lane->releaseVehicles();
    6785     72703355 :         return result;
    6786              :     }
    6787      3722482 :     const double seen = myLane->getLength() - getPositionOnLane();
    6788      3722482 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(myLane);
    6789      3722482 :     std::pair<const MSVehicle* const, double> result = myLane->getLeaderOnConsecutive(dist, seen, getSpeed(), *this, bestLaneConts, considerCrossingFoes);
    6790      3722481 :     lane->releaseVehicles();
    6791      3722481 :     return result;
    6792              : }
    6793              : 
    6794              : 
    6795              : std::pair<const MSVehicle* const, double>
    6796      2267817 : MSVehicle::getFollower(double dist) const {
    6797      2267817 :     if (myLane == nullptr) {
    6798            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6799              :     }
    6800      2267817 :     if (dist == 0) {
    6801       811006 :         dist = getCarFollowModel().brakeGap(myLane->getEdge().getSpeedLimit() * 2, 4.5, 0);
    6802              :     }
    6803      2267817 :     return myLane->getFollower(this, getPositionOnLane(), dist, MSLane::MinorLinkMode::FOLLOW_NEVER);
    6804              : }
    6805              : 
    6806              : 
    6807              : double
    6808            0 : MSVehicle::getTimeGapOnLane() const {
    6809              :     // calling getLeader with 0 would induce a dist calculation but we only want to look for the leaders on the current lane
    6810            0 :     std::pair<const MSVehicle* const, double> leaderInfo = getLeader(-1);
    6811            0 :     if (leaderInfo.first == nullptr || getSpeed() == 0) {
    6812            0 :         return -1;
    6813              :     }
    6814            0 :     return (leaderInfo.second + getVehicleType().getMinGap()) / getSpeed();
    6815              : }
    6816              : 
    6817              : 
    6818              : void
    6819      3807124 : MSVehicle::addTransportable(MSTransportable* transportable) {
    6820      3807124 :     MSBaseVehicle::addTransportable(transportable);
    6821        41003 :     if (myStops.size() > 0 && myStops.front().reached) {
    6822        37799 :         if (transportable->isPerson()) {
    6823        37220 :             if (myStops.front().triggered && myStops.front().numExpectedPerson > 0) {
    6824         1835 :                 myStops.front().numExpectedPerson -= (int)myStops.front().pars.awaitedPersons.count(transportable->getID());
    6825              :             }
    6826              :         } else {
    6827          579 :             if (myStops.front().pars.containerTriggered && myStops.front().numExpectedContainer > 0) {
    6828           20 :                 myStops.front().numExpectedContainer -= (int)myStops.front().pars.awaitedContainers.count(transportable->getID());
    6829              :             }
    6830              :         }
    6831              :     }
    6832        41003 : }
    6833              : 
    6834              : 
    6835              : void
    6836    697482376 : MSVehicle::setBlinkerInformation() {
    6837              :     switchOffSignal(VEH_SIGNAL_BLINKER_RIGHT | VEH_SIGNAL_BLINKER_LEFT);
    6838    697482376 :     int state = myLaneChangeModel->getOwnState();
    6839              :     // do not set blinker for sublane changes or when blocked from changing to the right
    6840    697482376 :     const bool blinkerManoeuvre = (((state & LCA_SUBLANE) == 0) && (
    6841    607289636 :                                        (state & LCA_KEEPRIGHT) == 0 || (state & LCA_BLOCKED) == 0));
    6842              :     Signalling left = VEH_SIGNAL_BLINKER_LEFT;
    6843              :     Signalling right = VEH_SIGNAL_BLINKER_RIGHT;
    6844    697482376 :     if (MSGlobals::gLefthand) {
    6845              :         // lane indices increase from left to right
    6846              :         std::swap(left, right);
    6847              :     }
    6848    697482376 :     if ((state & LCA_LEFT) != 0 && blinkerManoeuvre) {
    6849     20018988 :         switchOnSignal(left);
    6850    677463388 :     } else if ((state & LCA_RIGHT) != 0 && blinkerManoeuvre) {
    6851      5550005 :         switchOnSignal(right);
    6852    671913383 :     } else if (myLaneChangeModel->isChangingLanes()) {
    6853       254915 :         if (myLaneChangeModel->getLaneChangeDirection() == 1) {
    6854       165402 :             switchOnSignal(left);
    6855              :         } else {
    6856        89513 :             switchOnSignal(right);
    6857              :         }
    6858              :     } else {
    6859    671658468 :         const MSLane* lane = getLane();
    6860    671658468 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, 1, *lane, getBestLanesContinuation());
    6861    671658468 :         if (link != lane->getLinkCont().end() && lane->getLength() - getPositionOnLane() < lane->getVehicleMaxSpeed(this) * (double) 7.) {
    6862    169398682 :             switch ((*link)->getDirection()) {
    6863              :                 case LinkDirection::TURN:
    6864              :                 case LinkDirection::LEFT:
    6865              :                 case LinkDirection::PARTLEFT:
    6866              :                     switchOnSignal(VEH_SIGNAL_BLINKER_LEFT);
    6867              :                     break;
    6868              :                 case LinkDirection::RIGHT:
    6869              :                 case LinkDirection::PARTRIGHT:
    6870              :                     switchOnSignal(VEH_SIGNAL_BLINKER_RIGHT);
    6871              :                     break;
    6872              :                 default:
    6873              :                     break;
    6874              :             }
    6875              :         }
    6876              :     }
    6877              :     // stopping related signals
    6878    697482376 :     if (hasStops()
    6879    697482376 :             && (myStops.begin()->reached ||
    6880     15360712 :                 (myStopDist < (myLane->getLength() - getPositionOnLane())
    6881      4282664 :                  && myStopDist < getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this), getCarFollowModel().getMaxDecel(), 3)))) {
    6882     17316479 :         if (myStops.begin()->lane->getIndex() > 0 && myStops.begin()->lane->getParallelLane(-1)->allowsVehicleClass(getVClass())) {
    6883              :             // not stopping on the right. Activate emergency blinkers
    6884              :             switchOnSignal(VEH_SIGNAL_BLINKER_LEFT | VEH_SIGNAL_BLINKER_RIGHT);
    6885     17060516 :         } else if (!myStops.begin()->reached && (myStops.begin()->pars.parking == ParkingType::OFFROAD)) {
    6886              :             // signal upcoming parking stop on the current lane when within braking distance (~2 seconds before braking)
    6887      1640377 :             switchOnSignal(MSGlobals::gLefthand ? VEH_SIGNAL_BLINKER_LEFT : VEH_SIGNAL_BLINKER_RIGHT);
    6888              :         }
    6889              :     }
    6890    697482376 :     if (myInfluencer != nullptr && myInfluencer->getSignals() >= 0) {
    6891           14 :         mySignals = myInfluencer->getSignals();
    6892              :         myInfluencer->setSignals(-1); // overwrite computed signals only once
    6893              :     }
    6894    697482376 : }
    6895              : 
    6896              : void
    6897        85658 : MSVehicle::setEmergencyBlueLight(SUMOTime currentTime) {
    6898              : 
    6899              :     //TODO look if timestep ist SIMSTEP
    6900        85658 :     if (currentTime % 1000 == 0) {
    6901        25866 :         if (signalSet(VEH_SIGNAL_EMERGENCY_BLUE)) {
    6902              :             switchOffSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6903              :         } else {
    6904              :             switchOnSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6905              :         }
    6906              :     }
    6907        85658 : }
    6908              : 
    6909              : 
    6910              : int
    6911     22450364 : MSVehicle::getLaneIndex() const {
    6912     22450364 :     return myLane == nullptr ? -1 : myLane->getIndex();
    6913              : }
    6914              : 
    6915              : 
    6916              : void
    6917     14748682 : MSVehicle::setTentativeLaneAndPosition(MSLane* lane, double pos, double posLat) {
    6918     14748682 :     myLane = lane;
    6919     14748682 :     myState.myPos = pos;
    6920     14748682 :     myState.myPosLat = posLat;
    6921     14748682 :     myState.myBackPos = pos - getVehicleType().getLength();
    6922     14748682 : }
    6923              : 
    6924              : 
    6925              : double
    6926    389614115 : MSVehicle::getRightSideOnLane() const {
    6927    389614115 :     return myState.myPosLat + 0.5 * myLane->getWidth() - 0.5 * getVehicleType().getWidth();
    6928              : }
    6929              : 
    6930              : 
    6931              : double
    6932    384335637 : MSVehicle::getLeftSideOnLane() const {
    6933    384335637 :     return myState.myPosLat + 0.5 * myLane->getWidth() + 0.5 * getVehicleType().getWidth();
    6934              : }
    6935              : 
    6936              : 
    6937              : double
    6938    310325199 : MSVehicle::getRightSideOnLane(const MSLane* lane) const {
    6939    310325199 :     return myState.myPosLat + 0.5 * lane->getWidth() - 0.5 * getVehicleType().getWidth();
    6940              : }
    6941              : 
    6942              : 
    6943              : double
    6944    309836065 : MSVehicle::getLeftSideOnLane(const MSLane* lane) const {
    6945    309836065 :     return myState.myPosLat + 0.5 * lane->getWidth() + 0.5 * getVehicleType().getWidth();
    6946              : }
    6947              : 
    6948              : 
    6949              : double
    6950    247812561 : MSVehicle::getRightSideOnEdge(const MSLane* lane) const {
    6951    247812561 :     return getCenterOnEdge(lane) - 0.5 * getVehicleType().getWidth();
    6952              : }
    6953              : 
    6954              : 
    6955              : double
    6956     30951112 : MSVehicle::getLeftSideOnEdge(const MSLane* lane) const {
    6957     30951112 :     return getCenterOnEdge(lane) + 0.5 * getVehicleType().getWidth();
    6958              : }
    6959              : 
    6960              : 
    6961              : double
    6962    724395038 : MSVehicle::getCenterOnEdge(const MSLane* lane) const {
    6963    724395038 :     if (lane == nullptr || &lane->getEdge() == &myLane->getEdge()) {
    6964    723933169 :         return myLane->getRightSideOnEdge() + myState.myPosLat + 0.5 * myLane->getWidth();
    6965       461869 :     } else if (lane == myLaneChangeModel->getShadowLane()) {
    6966        13739 :         if (myLaneChangeModel->isOpposite() && &lane->getEdge() != &myLane->getEdge()) {
    6967        13730 :             return lane->getRightSideOnEdge() + lane->getWidth() - myState.myPosLat + 0.5 * myLane->getWidth();
    6968              :         }
    6969            9 :         if (myLaneChangeModel->getShadowDirection() == -1) {
    6970            0 :             return lane->getRightSideOnEdge() + lane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6971              :         } else {
    6972            9 :             return lane->getRightSideOnEdge() - myLane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6973              :         }
    6974       448130 :     } else if (lane == myLane->getBidiLane()) {
    6975        17033 :         return lane->getRightSideOnEdge() - myState.myPosLat + 0.5 * lane->getWidth();
    6976              :     } else {
    6977              :         assert(myFurtherLanes.size() == myFurtherLanesPosLat.size());
    6978       507625 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6979       481696 :             if (myFurtherLanes[i] == lane) {
    6980              : #ifdef DEBUG_FURTHER
    6981              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat=" << myFurtherLanesPosLat[i]
    6982              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6983              :                                               << "\n";
    6984              : #endif
    6985       405089 :                 return lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6986        76607 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    6987              : #ifdef DEBUG_FURTHER
    6988              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat(bidi)=" << myFurtherLanesPosLat[i]
    6989              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6990              :                                               << "\n";
    6991              : #endif
    6992           79 :                 return lane->getRightSideOnEdge() - myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6993              :             }
    6994              :         }
    6995              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    6996        25929 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    6997        26202 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    6998              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    6999        26202 :             if (shadowFurther[i] == lane) {
    7000              :                 assert(myLaneChangeModel->getShadowLane() != 0);
    7001        25929 :                 return (lane->getRightSideOnEdge() + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
    7002        25929 :                         + (myLane->getCenterOnEdge() - myLaneChangeModel->getShadowLane()->getCenterOnEdge()));
    7003              :             }
    7004              :         }
    7005              :         assert(false);
    7006            0 :         throw ProcessError("Request lateral pos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    7007              :     }
    7008              : }
    7009              : 
    7010              : 
    7011              : double
    7012   3271922860 : MSVehicle::getLatOffset(const MSLane* lane) const {
    7013              :     assert(lane != 0);
    7014   3271922860 :     if (&lane->getEdge() == &myLane->getEdge()) {
    7015   3221687934 :         return myLane->getRightSideOnEdge() - lane->getRightSideOnEdge();
    7016     50234926 :     } else if (myLane->getParallelOpposite() == lane) {
    7017      2134258 :         return (myLane->getWidth() + lane->getWidth()) * 0.5 - 2 * getLateralPositionOnLane();
    7018     48100668 :     } else if (myLane->getBidiLane() == lane) {
    7019       808147 :         return -2 * getLateralPositionOnLane();
    7020              :     } else {
    7021              :         // Check whether the lane is a further lane for the vehicle
    7022     53434475 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    7023     52489075 :             if (myFurtherLanes[i] == lane) {
    7024              : #ifdef DEBUG_FURTHER
    7025              :                 if (DEBUG_COND) {
    7026              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherLat=" << myFurtherLanesPosLat[i] << "\n";
    7027              :                 }
    7028              : #endif
    7029     46313619 :                 return myFurtherLanesPosLat[i] - myState.myPosLat;
    7030      6175456 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    7031              : #ifdef DEBUG_FURTHER
    7032              :                 if (DEBUG_COND) {
    7033              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    7034              :                 }
    7035              : #endif
    7036        33502 :                 return -2 * (myFurtherLanesPosLat[i] - myState.myPosLat);
    7037              :             }
    7038              :         }
    7039              : #ifdef DEBUG_FURTHER
    7040              :         if (DEBUG_COND) {
    7041              :             std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    7042              :         }
    7043              : #endif
    7044              :         // Check whether the lane is a "shadow further lane" for the vehicle
    7045       945400 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    7046       957164 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    7047       953196 :             if (shadowFurther[i] == lane) {
    7048              : #ifdef DEBUG_FURTHER
    7049              :                 if (DEBUG_COND) std::cout << "    getLatOffset veh=" << getID()
    7050              :                                               << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    7051              :                                               << " lane=" << lane->getID()
    7052              :                                               << " i=" << i
    7053              :                                               << " posLat=" << myState.myPosLat
    7054              :                                               << " shadowPosLat=" << getLatOffset(myLaneChangeModel->getShadowLane())
    7055              :                                               << " shadowFurtherLat=" << myLaneChangeModel->getShadowFurtherLanesPosLat()[i]
    7056              :                                               <<  "\n";
    7057              : #endif
    7058       940758 :                 return getLatOffset(myLaneChangeModel->getShadowLane()) + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] - myState.myPosLat;
    7059        12438 :             } else if (shadowFurther[i]->getBidiLane() == lane) {
    7060              : #ifdef DEBUG_FURTHER
    7061              :                 if (DEBUG_COND) {
    7062              :                     std::cout << "    getLatOffset veh=" << getID() << " shadowbidilane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    7063              :                 }
    7064              : #endif
    7065          674 :                 return -2 * getLatOffset(myLaneChangeModel->getShadowLane()) + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] - myState.myPosLat;
    7066              :             }
    7067              :         }
    7068              :         // Check whether the vehicle issued a maneuverReservation on the lane.
    7069         3968 :         const std::vector<MSLane*>& furtherTargets = myLaneChangeModel->getFurtherTargetLanes();
    7070         5796 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    7071              :             // Further target lanes are just neighboring lanes of the vehicle's further lanes, @see MSAbstractLaneChangeModel::updateTargetLane()
    7072         5795 :             MSLane* targetLane = furtherTargets[i];
    7073         5795 :             if (targetLane == lane) {
    7074         3967 :                 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
    7075         3967 :                 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
    7076              : #ifdef DEBUG_TARGET_LANE
    7077              :                 if (DEBUG_COND) {
    7078              :                     std::cout << "    getLatOffset veh=" << getID()
    7079              :                               << " wrt targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    7080              :                               << "\n    i=" << i
    7081              :                               << " posLat=" << myState.myPosLat
    7082              :                               << " furtherPosLat=" << myFurtherLanesPosLat[i]
    7083              :                               << " maneuverDist=" << myLaneChangeModel->getManeuverDist()
    7084              :                               << " targetDir=" << targetDir
    7085              :                               << " latOffset=" << latOffset
    7086              :                               <<  std::endl;
    7087              :                 }
    7088              : #endif
    7089         3967 :                 return latOffset;
    7090         1828 :             } else if (targetLane != nullptr && targetLane->getBidiLane() == lane) {
    7091            0 :                 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
    7092            0 :                 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
    7093              : #ifdef DEBUG_FURTHER
    7094              :                 if (DEBUG_COND) {
    7095              :                     std::cout << "    getLatOffset veh=" << getID() << " furthertargetbidilane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    7096              :                 }
    7097              : #endif
    7098            0 :                 return -2 * latOffset;
    7099              :             }
    7100              :         }
    7101              :         assert(false);
    7102            6 :         throw ProcessError("Request lateral offset of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    7103              :     }
    7104              : }
    7105              : 
    7106              : 
    7107              : double
    7108     36259626 : MSVehicle::lateralDistanceToLane(const int offset) const {
    7109              :     // compute the distance when changing to the neighboring lane
    7110              :     // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
    7111              :     assert(offset == 0 || offset == 1 || offset == -1);
    7112              :     assert(myLane != nullptr);
    7113              :     assert(myLane->getParallelLane(offset) != nullptr || myLane->getParallelOpposite() != nullptr);
    7114     36259626 :     const double halfCurrentLaneWidth = 0.5 * myLane->getWidth();
    7115     36259626 :     const double halfVehWidth = 0.5 * (getWidth() + NUMERICAL_EPS);
    7116     36259626 :     const double latPos = getLateralPositionOnLane();
    7117     36259626 :     const double oppositeSign = getLaneChangeModel().isOpposite() ? -1 : 1;
    7118     36259626 :     double leftLimit = halfCurrentLaneWidth - halfVehWidth - oppositeSign * latPos;
    7119     36259626 :     double rightLimit = -halfCurrentLaneWidth + halfVehWidth - oppositeSign * latPos;
    7120              :     double latLaneDist = 0;  // minimum distance to move the vehicle fully onto the new lane
    7121     36259626 :     if (offset == 0) {
    7122            8 :         if (latPos + halfVehWidth > halfCurrentLaneWidth) {
    7123              :             // correct overlapping left
    7124            4 :             latLaneDist = halfCurrentLaneWidth - latPos - halfVehWidth;
    7125            4 :         } else if (latPos - halfVehWidth < -halfCurrentLaneWidth) {
    7126              :             // correct overlapping right
    7127            4 :             latLaneDist = -halfCurrentLaneWidth - latPos + halfVehWidth;
    7128              :         }
    7129            8 :         latLaneDist *= oppositeSign;
    7130     36259618 :     } else if (offset == -1) {
    7131     16749492 :         latLaneDist = rightLimit - (getWidth() + NUMERICAL_EPS);
    7132     19510126 :     } else if (offset == 1) {
    7133     19510126 :         latLaneDist = leftLimit + (getWidth() + NUMERICAL_EPS);
    7134              :     }
    7135              : #ifdef DEBUG_ACTIONSTEPS
    7136              :     if (DEBUG_COND) {
    7137              :         std::cout << SIMTIME
    7138              :                   << " veh=" << getID()
    7139              :                   << " halfCurrentLaneWidth=" << halfCurrentLaneWidth
    7140              :                   << " halfVehWidth=" << halfVehWidth
    7141              :                   << " latPos=" << latPos
    7142              :                   << " latLaneDist=" << latLaneDist
    7143              :                   << " leftLimit=" << leftLimit
    7144              :                   << " rightLimit=" << rightLimit
    7145              :                   << "\n";
    7146              :     }
    7147              : #endif
    7148     36259626 :     return latLaneDist;
    7149              : }
    7150              : 
    7151              : 
    7152              : double
    7153   5013830466 : MSVehicle::getLateralOverlap(double posLat, const MSLane* lane) const {
    7154   5013830466 :     return (fabs(posLat) + 0.5 * getVehicleType().getWidth()
    7155   5013830466 :             - 0.5 * lane->getWidth());
    7156              : }
    7157              : 
    7158              : double
    7159            0 : MSVehicle::getLateralOverlap(const MSLane* lane) const {
    7160            0 :     return getLateralOverlap(getLateralPositionOnLane(), lane);
    7161              : }
    7162              : 
    7163              : double
    7164   4820946691 : MSVehicle::getLateralOverlap() const {
    7165   4820946691 :     return getLateralOverlap(getLateralPositionOnLane(), myLane);
    7166              : }
    7167              : 
    7168              : 
    7169              : void
    7170    640905436 : MSVehicle::removeApproachingInformation(const DriveItemVector& lfLinks) const {
    7171   1861913148 :     for (const DriveProcessItem& dpi : lfLinks) {
    7172   1221007712 :         if (dpi.myLink != nullptr) {
    7173    864312283 :             dpi.myLink->removeApproaching(this);
    7174              :         }
    7175              :     }
    7176              :     // unregister on all shadow links
    7177    640905436 :     myLaneChangeModel->removeShadowApproachingInformation();
    7178    640905436 : }
    7179              : 
    7180              : 
    7181              : bool
    7182       846720 : MSVehicle::unsafeLinkAhead(const MSLane* lane, double zipperDist) const {
    7183              :     // the following links are unsafe:
    7184              :     // - zipper links if they are close enough and have approaching vehicles in the relevant time range
    7185              :     // - unprioritized links if the vehicle is currently approaching a prioritzed link and unable to stop in time
    7186       846720 :     double seen = myLane->getLength() - getPositionOnLane();
    7187       846720 :     const double dist = MAX2(zipperDist, getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0));
    7188       846720 :     if (seen < dist) {
    7189        71199 :         const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(lane);
    7190              :         int view = 1;
    7191        71199 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7192              :         DriveItemVector::const_iterator di = myLFLinkLanes.begin();
    7193       118526 :         while (!lane->isLinkEnd(link) && seen <= dist) {
    7194        71926 :             if ((!lane->isInternal()
    7195        49279 :                     && (((*link)->getState() == LINKSTATE_ZIPPER && seen < (*link)->getFoeVisibilityDistance())
    7196        26719 :                         || !(*link)->havePriority()))
    7197        98408 :                     || (lane->isInternal() && zipperDist > 0)) {
    7198              :                 // find the drive item corresponding to this link
    7199              :                 bool found = false;
    7200        52218 :                 while (di != myLFLinkLanes.end() && !found) {
    7201        27054 :                     if ((*di).myLink != nullptr) {
    7202              :                         const MSLane* diPredLane = (*di).myLink->getLaneBefore();
    7203        27050 :                         if (diPredLane != nullptr) {
    7204        27050 :                             if (&diPredLane->getEdge() == &lane->getEdge()) {
    7205              :                                 found = true;
    7206              :                             }
    7207              :                         }
    7208              :                     }
    7209        27054 :                     if (!found) {
    7210              :                         di++;
    7211              :                     }
    7212              :                 }
    7213        25164 :                 if (found) {
    7214        25160 :                     const SUMOTime leaveTime = (*link)->getLeaveTime((*di).myArrivalTime, (*di).myArrivalSpeed,
    7215        25160 :                                                (*di).getLeaveSpeed(), getVehicleType().getLength());
    7216        25160 :                     const MSLink* entry = (*link)->getCorrespondingEntryLink();
    7217              :                     //if (DEBUG_COND) {
    7218              :                     //    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";
    7219              :                     //}
    7220        25160 :                     if (entry->hasApproachingFoe((*di).myArrivalTime, leaveTime, (*di).myArrivalSpeed, getCarFollowModel().getMaxDecel())) {
    7221              :                         //std::cout << SIMTIME << " veh=" << getID() << " aborting changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << "\n";
    7222              :                         return true;
    7223              :                     }
    7224              :                 }
    7225              :                 // no drive item is found if the vehicle aborts its request within dist
    7226              :             }
    7227        47327 :             lane = (*link)->getViaLaneOrLane();
    7228        47327 :             if (!lane->getEdge().isInternal()) {
    7229        24654 :                 view++;
    7230              :             }
    7231        47327 :             seen += lane->getLength();
    7232        47327 :             link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7233              :         }
    7234              :     }
    7235              :     return false;
    7236              : }
    7237              : 
    7238              : 
    7239              : PositionVector
    7240      6886866 : MSVehicle::getBoundingBox(double offset) const {
    7241      6886866 :     PositionVector centerLine;
    7242      6886866 :     Position pos = getPosition();
    7243      6886866 :     centerLine.push_back(pos);
    7244      6886866 :     switch (myType->getGuiShape()) {
    7245        29069 :         case SUMOVehicleShape::BUS_FLEXIBLE:
    7246              :         case SUMOVehicleShape::RAIL:
    7247              :         case SUMOVehicleShape::RAIL_CAR:
    7248              :         case SUMOVehicleShape::RAIL_CARGO:
    7249              :         case SUMOVehicleShape::TRUCK_SEMITRAILER:
    7250              :         case SUMOVehicleShape::TRUCK_1TRAILER: {
    7251        60781 :             for (MSLane* lane : myFurtherLanes) {
    7252        31712 :                 centerLine.push_back(lane->getShape().back());
    7253              :             }
    7254              :             break;
    7255              :         }
    7256              :         default:
    7257              :             break;
    7258              :     }
    7259      6886866 :     double l = getLength();
    7260      6886866 :     Position backPos = getBackPosition();
    7261      6886866 :     if (pos.distanceTo2D(backPos) > l + NUMERICAL_EPS) {
    7262              :         // getBackPosition may not match the visual back in networks without internal lanes
    7263       348807 :         double a = getAngle() + M_PI; // angle pointing backwards
    7264       348807 :         backPos = pos + Position(l * cos(a), l * sin(a));
    7265              :     }
    7266      6886866 :     centerLine.push_back(backPos);
    7267      6886866 :     if (offset != 0) {
    7268         6543 :         centerLine.extrapolate2D(offset);
    7269              :     }
    7270              :     PositionVector result = centerLine;
    7271     13769442 :     result.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7272     13769442 :     centerLine.move2side(MIN2(0.0, -0.5 * myType->getWidth() - offset));
    7273      6886866 :     result.append(centerLine.reverse(), POSITION_EPS);
    7274      6886866 :     return result;
    7275      6886866 : }
    7276              : 
    7277              : 
    7278              : PositionVector
    7279        72897 : MSVehicle::getBoundingPoly(double offset) const {
    7280        72897 :     switch (myType->getGuiShape()) {
    7281        72371 :         case SUMOVehicleShape::PASSENGER:
    7282              :         case SUMOVehicleShape::PASSENGER_SEDAN:
    7283              :         case SUMOVehicleShape::PASSENGER_HATCHBACK:
    7284              :         case SUMOVehicleShape::PASSENGER_WAGON:
    7285              :         case SUMOVehicleShape::PASSENGER_VAN: {
    7286              :             // box with corners cut off
    7287        72371 :             PositionVector result;
    7288        72371 :             PositionVector centerLine;
    7289        72371 :             centerLine.push_back(getPosition());
    7290        72371 :             centerLine.push_back(getBackPosition());
    7291        72371 :             if (offset != 0) {
    7292         1600 :                 centerLine.extrapolate2D(offset);
    7293              :             }
    7294              :             PositionVector line1 = centerLine;
    7295              :             PositionVector line2 = centerLine;
    7296       144742 :             line1.move2side(MAX2(0.0, 0.3 * myType->getWidth() + offset));
    7297       144742 :             line2.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7298        72371 :             line2.scaleRelative(0.8);
    7299        72371 :             result.push_back(line1[0]);
    7300        72371 :             result.push_back(line2[0]);
    7301        72371 :             result.push_back(line2[1]);
    7302        72371 :             result.push_back(line1[1]);
    7303       144742 :             line1.move2side(MIN2(0.0, -0.6 * myType->getWidth() - offset));
    7304       144742 :             line2.move2side(MIN2(0.0, -1.0 * myType->getWidth() - offset));
    7305        72371 :             result.push_back(line1[1]);
    7306        72371 :             result.push_back(line2[1]);
    7307        72371 :             result.push_back(line2[0]);
    7308        72371 :             result.push_back(line1[0]);
    7309              :             return result;
    7310        72371 :         }
    7311          526 :         default:
    7312          526 :             return getBoundingBox();
    7313              :     }
    7314              : }
    7315              : 
    7316              : 
    7317              : bool
    7318     12727451 : MSVehicle::onFurtherEdge(const MSEdge* edge) const {
    7319     13741511 :     for (std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    7320      1597412 :         if (&(*i)->getEdge() == edge) {
    7321              :             return true;
    7322              :         }
    7323              :     }
    7324              :     return false;
    7325              : }
    7326              : 
    7327              : 
    7328              : bool
    7329   7504670155 : MSVehicle::isBidiOn(const MSLane* lane) const {
    7330   7520732553 :     return lane->getBidiLane() != nullptr && (
    7331     16062398 :                myLane == lane->getBidiLane()
    7332     12727451 :                || onFurtherEdge(&lane->getBidiLane()->getEdge()));
    7333              : }
    7334              : 
    7335              : 
    7336              : bool
    7337           16 : MSVehicle::rerouteParkingArea(const std::string& parkingAreaID, std::string& errorMsg) {
    7338              :     // this function is based on MSTriggeredRerouter::rerouteParkingArea in order to keep
    7339              :     // consistency in the behaviour.
    7340              : 
    7341              :     // get vehicle params
    7342           16 :     MSParkingArea* destParkArea = getNextParkingArea();
    7343           16 :     const MSRoute& route = getRoute();
    7344           16 :     const MSEdge* lastEdge = route.getLastEdge();
    7345              : 
    7346           16 :     if (destParkArea == nullptr) {
    7347              :         // not driving towards a parking area
    7348            0 :         errorMsg = "Vehicle " + getID() + " is not driving to a parking area so it cannot be rerouted.";
    7349            0 :         return false;
    7350              :     }
    7351              : 
    7352              :     // if the current route ends at the parking area, the new route will also and at the new area
    7353           16 :     bool newDestination = (&destParkArea->getLane().getEdge() == route.getLastEdge()
    7354            8 :                            && getArrivalPos() >= destParkArea->getBeginLanePosition()
    7355           24 :                            && getArrivalPos() <= destParkArea->getEndLanePosition());
    7356              : 
    7357              :     // retrieve info on the new parking area
    7358           16 :     MSParkingArea* newParkingArea = (MSParkingArea*) MSNet::getInstance()->getStoppingPlace(
    7359              :                                         parkingAreaID, SumoXMLTag::SUMO_TAG_PARKING_AREA);
    7360              : 
    7361           16 :     if (newParkingArea == nullptr) {
    7362            0 :         errorMsg = "Parking area ID " + toString(parkingAreaID) + " not found in the network.";
    7363            0 :         return false;
    7364              :     }
    7365              : 
    7366           16 :     const MSEdge* newEdge = &(newParkingArea->getLane().getEdge());
    7367           16 :     SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = getRouterTT();
    7368              : 
    7369              :     // Compute the route from the current edge to the parking area edge
    7370              :     ConstMSEdgeVector edgesToPark;
    7371           16 :     router.compute(getEdge(), getPositionOnLane(), newEdge, newParkingArea->getEndLanePosition(), this, MSNet::getInstance()->getCurrentTimeStep(), edgesToPark);
    7372              : 
    7373              :     // Compute the route from the parking area edge to the end of the route
    7374              :     ConstMSEdgeVector edgesFromPark;
    7375           16 :     if (!newDestination) {
    7376           12 :         router.compute(newEdge, lastEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesFromPark);
    7377              :     } else {
    7378              :         // adapt plans of any riders
    7379            8 :         for (MSTransportable* p : getPersons()) {
    7380            4 :             p->rerouteParkingArea(getNextParkingArea(), newParkingArea);
    7381              :         }
    7382              :     }
    7383              : 
    7384              :     // we have a new destination, let's replace the vehicle route
    7385           16 :     ConstMSEdgeVector edges = edgesToPark;
    7386           16 :     if (edgesFromPark.size() > 0) {
    7387           12 :         edges.insert(edges.end(), edgesFromPark.begin() + 1, edgesFromPark.end());
    7388              :     }
    7389              : 
    7390           16 :     if (newDestination && getParameter().arrivalPosProcedure != ArrivalPosDefinition::DEFAULT) {
    7391            4 :         SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
    7392            4 :         *newParameter = getParameter();
    7393            4 :         newParameter->arrivalPosProcedure = ArrivalPosDefinition::GIVEN;
    7394            4 :         newParameter->arrivalPos = newParkingArea->getEndLanePosition();
    7395            4 :         replaceParameter(newParameter);
    7396              :     }
    7397           16 :     const double routeCost = router.recomputeCosts(edges, this, MSNet::getInstance()->getCurrentTimeStep());
    7398           16 :     ConstMSEdgeVector prevEdges(myCurrEdge, myRoute->end());
    7399           16 :     const double savings = router.recomputeCosts(prevEdges, this, MSNet::getInstance()->getCurrentTimeStep());
    7400           16 :     if (replaceParkingArea(newParkingArea, errorMsg)) {
    7401           16 :         const bool onInit = myLane == nullptr;
    7402           32 :         replaceRouteEdges(edges, routeCost, savings, "TraCI:" + toString(SUMO_TAG_PARKING_AREA_REROUTE), onInit, false, false);
    7403              :     } else {
    7404            0 :         WRITE_WARNINGF("Vehicle '%' could not reroute to new parkingArea '%' reason=%, time=%.",
    7405              :                 getID(), newParkingArea->getID(), errorMsg, time2string(SIMSTEP));
    7406            0 :         return false;
    7407              :     }
    7408           16 :     return true;
    7409           16 : }
    7410              : 
    7411              : 
    7412              : bool
    7413        46329 : MSVehicle::addTraciStop(SUMOVehicleParameter::Stop stop, std::string& errorMsg) {
    7414        46329 :     const int numStops = (int)myStops.size();
    7415        46329 :     const bool result = MSBaseVehicle::addTraciStop(stop, errorMsg);
    7416        46329 :     if (myLane != nullptr && numStops != (int)myStops.size()) {
    7417        44731 :         updateBestLanes(true);
    7418              :     }
    7419        46329 :     return result;
    7420              : }
    7421              : 
    7422              : 
    7423              : bool
    7424         3238 : MSVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
    7425         3238 :     if (myCurrEdge == stop.edge && distToStop + POSITION_EPS < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0)) {
    7426         1495 :         if (distToStop < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)) {
    7427         1086 :             double vNew = getCarFollowModel().maximumSafeStopSpeed(distToStop, getCarFollowModel().getMaxDecel(), getSpeed(), false, 0);
    7428              :             //std::cout << SIMTIME << " veh=" << getID() << " v=" << myState.mySpeed << " distToStop=" << distToStop
    7429              :             //    << " vMinNex=" << getCarFollowModel().minNextSpeed(getSpeed(), this)
    7430              :             //    << " bg1=" << getCarFollowModel().brakeGap(myState.mySpeed)
    7431              :             //    << " bg2=" << getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)
    7432              :             //    << " vNew=" << vNew
    7433              :             //    << "\n";
    7434         1086 :             myState.mySpeed = MIN2(myState.mySpeed, vNew + ACCEL2SPEED(getCarFollowModel().getEmergencyDecel()));
    7435         1086 :             myState.myPos = MIN2(myState.myPos, stop.pars.endPos);
    7436         1086 :             myCachedPosition = Position::INVALID;
    7437         1086 :             if (myState.myPos < myType->getLength()) {
    7438          453 :                 computeFurtherLanes(myLane, myState.myPos, true);
    7439          453 :                 myAngle = computeAngle();
    7440          453 :                 if (myLaneChangeModel->isOpposite()) {
    7441            0 :                     myAngle += M_PI;
    7442              :                 }
    7443              :             }
    7444              :         }
    7445              :     }
    7446         3238 :     return true;
    7447              : }
    7448              : 
    7449              : 
    7450              : bool
    7451     24085614 : MSVehicle::resumeFromStopping() {
    7452     24085614 :     if (isStopped()) {
    7453        49323 :         if (myAmRegisteredAsWaiting) {
    7454          750 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    7455          750 :             myAmRegisteredAsWaiting = false;
    7456              :         }
    7457              :         MSStop& stop = myStops.front();
    7458              :         // we have waited long enough and fulfilled any passenger-requirements
    7459        49323 :         if (stop.busstop != nullptr) {
    7460              :             // inform bus stop about leaving it
    7461        18573 :             stop.busstop->leaveFrom(this);
    7462              :         }
    7463              :         // we have waited long enough and fulfilled any container-requirements
    7464        49323 :         if (stop.containerstop != nullptr) {
    7465              :             // inform container stop about leaving it
    7466          530 :             stop.containerstop->leaveFrom(this);
    7467              :         }
    7468        49323 :         if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    7469              :             // inform parking area about leaving it
    7470         8435 :             stop.parkingarea->leaveFrom(this);
    7471              :         }
    7472        49323 :         if (stop.chargingStation != nullptr) {
    7473              :             // inform charging station about leaving it
    7474         3571 :             stop.chargingStation->leaveFrom(this);
    7475              :         }
    7476              :         // the current stop is no longer valid
    7477        49323 :         myLane->getEdge().removeWaiting(this);
    7478              :         // MSStopOut needs to know whether the stop had a loaded 'ended' value so we call this before replacing the value
    7479        49323 :         if (stop.pars.started == -1) {
    7480              :             // waypoint edge was passed in a single step
    7481          334 :             stop.pars.started = MSNet::getInstance()->getCurrentTimeStep();
    7482              :         }
    7483        49323 :         if (MSStopOut::active()) {
    7484         4246 :             MSStopOut::getInstance()->stopEnded(this, stop);
    7485              :         }
    7486        49323 :         stop.pars.ended = MSNet::getInstance()->getCurrentTimeStep();
    7487       112288 :         for (const auto& rem : myMoveReminders) {
    7488        62965 :             rem.first->notifyStopEnded();
    7489              :         }
    7490        49323 :         if (stop.pars.collision && MSLane::getCollisionAction() == MSLane::COLLISION_ACTION_WARN) {
    7491          425 :             myCollisionImmunity = TIME2STEPS(5); // leave the conflict area
    7492              :         }
    7493        49323 :         if (stop.pars.posLat != INVALID_DOUBLE && MSGlobals::gLateralResolution <= 0) {
    7494              :             // reset lateral position to default
    7495          194 :             myState.myPosLat = 0;
    7496              :         }
    7497        49323 :         const bool wasWaypoint = stop.getSpeed() > 0;
    7498        49323 :         myPastStops.push_back(stop.pars);
    7499        49323 :         myPastStops.back().routeIndex = (int)(stop.edge - myRoute->begin());
    7500        49323 :         myStops.pop_front();
    7501        49323 :         myStopDist = std::numeric_limits<double>::max();
    7502              :         // do not count the stopping time towards gridlock time.
    7503              :         // Other outputs use an independent counter and are not affected.
    7504        49323 :         myWaitingTime = 0;
    7505        49323 :         myStopSpeed = getCarFollowModel().maxNextSpeed(getSpeed(), this);
    7506              :         // maybe the next stop is on the same edge; let's rebuild best lanes
    7507        49323 :         updateBestLanes(true);
    7508              :         // continue as wished...
    7509        49323 :         MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::ENDING_STOP);
    7510        49323 :         MSNet::getInstance()->getVehicleControl().registerStopEnded();
    7511        49323 :         return !wasWaypoint;
    7512              :     }
    7513              :     return false;
    7514              : }
    7515              : 
    7516              : 
    7517              : MSVehicle::Influencer&
    7518      4522485 : MSVehicle::getInfluencer() {
    7519      4522485 :     if (myInfluencer == nullptr) {
    7520         3473 :         myInfluencer = new Influencer();
    7521              :     }
    7522      4522485 :     return *myInfluencer;
    7523              : }
    7524              : 
    7525              : MSVehicle::BaseInfluencer&
    7526           24 : MSVehicle::getBaseInfluencer() {
    7527           24 :     return getInfluencer();
    7528              : }
    7529              : 
    7530              : 
    7531              : const MSVehicle::Influencer*
    7532            0 : MSVehicle::getInfluencer() const {
    7533            0 :     return myInfluencer;
    7534              : }
    7535              : 
    7536              : const MSVehicle::BaseInfluencer*
    7537       238297 : MSVehicle::getBaseInfluencer() const {
    7538       238297 :     return myInfluencer;
    7539              : }
    7540              : 
    7541              : 
    7542              : double
    7543         4078 : MSVehicle::getSpeedWithoutTraciInfluence() const {
    7544         4078 :     if (myInfluencer != nullptr && myInfluencer->getOriginalSpeed() >= 0) {
    7545              :         // influencer original speed is -1 on initialization
    7546         1655 :         return myInfluencer->getOriginalSpeed();
    7547              :     }
    7548         2423 :     return myState.mySpeed;
    7549              : }
    7550              : 
    7551              : 
    7552              : int
    7553    997870470 : MSVehicle::influenceChangeDecision(int state) {
    7554    997870470 :     if (hasInfluencer()) {
    7555      2811302 :         state = getInfluencer().influenceChangeDecision(
    7556              :                     MSNet::getInstance()->getCurrentTimeStep(),
    7557      2811302 :                     myLane->getEdge(),
    7558              :                     getLaneIndex(),
    7559              :                     state);
    7560              :     }
    7561    997870470 :     return state;
    7562              : }
    7563              : 
    7564              : 
    7565              : void
    7566         7338 : MSVehicle::setRemoteState(Position xyPos) {
    7567         7338 :     myCachedPosition = xyPos;
    7568         7338 : }
    7569              : 
    7570              : 
    7571              : bool
    7572    792711406 : MSVehicle::isRemoteControlled() const {
    7573    792711406 :     return myInfluencer != nullptr && myInfluencer->isRemoteControlled();
    7574              : }
    7575              : 
    7576              : 
    7577              : bool
    7578        20581 : MSVehicle::wasRemoteControlled(SUMOTime lookBack) const {
    7579        20581 :     return myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() + lookBack >= MSNet::getInstance()->getCurrentTimeStep();
    7580              : }
    7581              : 
    7582              : 
    7583              : bool
    7584    523426322 : MSVehicle::keepClear(const MSLink* link) const {
    7585    523426322 :     if (link->hasFoes() && link->keepClear() /* && item.myLink->willHaveBlockedFoe()*/) {
    7586    174662396 :         const double keepClearTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, -1);
    7587              :         //std::cout << SIMTIME << " veh=" << getID() << " keepClearTime=" << keepClearTime << " accWait=" << getAccumulatedWaitingSeconds() << " keepClear=" << (keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime) << "\n";
    7588    176084741 :         return keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime;
    7589              :     } else {
    7590              :         return false;
    7591              :     }
    7592              : }
    7593              : 
    7594              : 
    7595              : bool
    7596    726158111 : MSVehicle::ignoreRed(const MSLink* link, bool canBrake) const {
    7597    726158111 :     if ((myInfluencer != nullptr && !myInfluencer->getEmergencyBrakeRedLight())) {
    7598              :         return true;
    7599              :     }
    7600    725850823 :     const double ignoreRedTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, -1);
    7601              : #ifdef DEBUG_IGNORE_RED
    7602              :     if (DEBUG_COND) {
    7603              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID() << " state=" << toString(link->getState()) << "\n";
    7604              :     }
    7605              : #endif
    7606    725850823 :     if (ignoreRedTime < 0) {
    7607    725845424 :         const double ignoreYellowTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, 0);
    7608    725845424 :         if (ignoreYellowTime > 0 && link->haveYellow()) {
    7609              :             assert(link->getTLLogic() != 0);
    7610           52 :             const double yellowDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7611              :             // when activating ignoreYellow behavior, vehicles will drive if they cannot brake
    7612           92 :             return !canBrake || ignoreYellowTime > yellowDuration;
    7613              :         } else {
    7614              :             return false;
    7615              :         }
    7616         5399 :     } else if (link->haveYellow()) {
    7617              :         // always drive at yellow when ignoring red
    7618              :         return true;
    7619         5243 :     } else if (link->haveRed()) {
    7620              :         assert(link->getTLLogic() != 0);
    7621         3832 :         const double redDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7622              : #ifdef DEBUG_IGNORE_RED
    7623              :         if (DEBUG_COND) {
    7624              :             std::cout
    7625              :             // << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID()
    7626              :                     << "   ignoreRedTime=" << ignoreRedTime
    7627              :                     << " spentRed=" << redDuration
    7628              :                     << " canBrake=" << canBrake << "\n";
    7629              :         }
    7630              : #endif
    7631              :         // when activating ignoreRed behavior, vehicles will always drive if they cannot brake
    7632         6356 :         return !canBrake || ignoreRedTime > redDuration;
    7633              :     } else {
    7634              :         return false;
    7635              :     }
    7636              : }
    7637              : 
    7638              : bool
    7639   1314039257 : MSVehicle::ignoreFoe(const SUMOTrafficObject* foe) const {
    7640   1314039257 :     if (!getParameter().wasSet(VEHPARS_CFMODEL_PARAMS_SET)) {
    7641              :         return false;
    7642              :     }
    7643         2548 :     for (const std::string& typeID : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_TYPES), "")).getVector()) {
    7644          398 :         if (typeID == foe->getVehicleType().getID()) {
    7645              :             return true;
    7646              :         }
    7647         1274 :     }
    7648         2161 :     for (const std::string& id : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_IDS), "")).getVector()) {
    7649          876 :         if (id == foe->getID()) {
    7650              :             return true;
    7651              :         }
    7652          876 :     }
    7653          409 :     return false;
    7654              : }
    7655              : 
    7656              : bool
    7657    550364108 : MSVehicle::passingMinor() const {
    7658              :     // either on an internal lane that was entered via minor link
    7659              :     // or on approach to minor link below visibility distance
    7660    550364108 :     if (myLane == nullptr) {
    7661              :         return false;
    7662              :     }
    7663    550364108 :     if (myLane->getEdge().isInternal()) {
    7664     10363179 :         return !myLane->getIncomingLanes().front().viaLink->havePriority();
    7665    540000929 :     } else if (myLFLinkLanes.size() > 0 && myLFLinkLanes.front().myLink != nullptr) {
    7666              :         MSLink* link = myLFLinkLanes.front().myLink;
    7667    281254161 :         return !link->havePriority() && myLFLinkLanes.front().myDistance <= link->getFoeVisibilityDistance();
    7668              :     }
    7669              :     return false;
    7670              : }
    7671              : 
    7672              : bool
    7673     21591697 : MSVehicle::isLeader(const MSLink* link, const MSVehicle* veh, const double gap) const {
    7674              :     assert(link->fromInternalLane());
    7675     21591697 :     if (veh == nullptr) {
    7676              :         return false;
    7677              :     }
    7678     21591697 :     if (!myLane->isInternal() || myLane->getEdge().getToJunction() != link->getJunction()) {
    7679              :         // if this vehicle is not yet on the junction, every vehicle is a leader
    7680              :         return true;
    7681              :     }
    7682      1983928 :     if (veh->getLaneChangeModel().hasBlueLight()) {
    7683              :         // blue light device automatically gets right of way
    7684              :         return true;
    7685              :     }
    7686      1983628 :     const MSLane* foeLane = veh->getLane();
    7687      1983628 :     if (foeLane->isInternal()) {
    7688      1486370 :         if (foeLane->getEdge().getFromJunction() == link->getJunction()) {
    7689      1465874 :             SUMOTime egoET = myJunctionConflictEntryTime;
    7690      1465874 :             SUMOTime foeET = veh->myJunctionEntryTime;
    7691              :             // check relationship between link and foeLane
    7692      1465874 :             if (foeLane->getNormalPredecessorLane() == link->getInternalLaneBefore()->getNormalPredecessorLane()) {
    7693              :                 // we are entering the junction from the same lane
    7694       496601 :                 egoET = myJunctionEntryTimeNeverYield;
    7695       496601 :                 foeET = veh->myJunctionEntryTimeNeverYield;
    7696       496601 :                 if (link->isExitLinkAfterInternalJunction() && link->getInternalLaneBefore()->getLogicalPredecessorLane()->getEntryLink()->isIndirect()) {
    7697        73850 :                     egoET = myJunctionConflictEntryTime;
    7698              :                 }
    7699              :             } else {
    7700       969273 :                 const MSLink* foeLink = foeLane->getIncomingLanes()[0].viaLink;
    7701       969273 :                 const MSJunctionLogic* logic = link->getJunction()->getLogic();
    7702              :                 assert(logic != nullptr);
    7703              :                 // determine who has right of way
    7704              :                 bool response; // ego response to foe
    7705              :                 bool response2; // foe response to ego
    7706              :                 // attempt 1: tlLinkState
    7707       969273 :                 const MSLink* entry = link->getCorrespondingEntryLink();
    7708       969273 :                 const MSLink* foeEntry = foeLink->getCorrespondingEntryLink();
    7709       969273 :                 if (entry->haveRed() || foeEntry->haveRed()) {
    7710              :                     // ensure that vehicles which are stuck on the intersection may exit
    7711       116980 :                     if (!foeEntry->haveRed() && veh->getSpeed() > SUMO_const_haltingSpeed && gap < 0) {
    7712              :                         // foe might be oncoming, don't drive unless foe can still brake safely
    7713        11722 :                         const double foeNextSpeed = veh->getSpeed() + ACCEL2SPEED(veh->getCarFollowModel().getMaxAccel());
    7714        11722 :                         const double foeBrakeGap = veh->getCarFollowModel().brakeGap(
    7715        11722 :                                                        foeNextSpeed, veh->getCarFollowModel().getMaxDecel(), veh->getCarFollowModel().getHeadwayTime());
    7716              :                         // the minGap was subtracted from gap in MSLink::getLeaderInfo (enlarging the negative gap)
    7717              :                         // so the -2* makes it point in the right direction
    7718        11722 :                         const double foeGap = -gap - veh->getLength() - 2 * getVehicleType().getMinGap();
    7719              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7720              :                         if (DEBUG_COND) {
    7721              :                             std::cout << " foeGap=" << foeGap << " foeBGap=" << foeBrakeGap << "\n";
    7722              : 
    7723              :                         }
    7724              : #endif
    7725        11722 :                         if (foeGap < foeBrakeGap) {
    7726              :                             response = true;
    7727              :                             response2 = false;
    7728              :                         } else {
    7729              :                             response = false;
    7730              :                             response2 = true;
    7731              :                         }
    7732              :                     } else {
    7733              :                         // let conflict entry time decide
    7734              :                         response = true;
    7735              :                         response2 = true;
    7736              :                     }
    7737       852293 :                 } else if (entry->havePriority() != foeEntry->havePriority()) {
    7738       643172 :                     response = !entry->havePriority();
    7739       643172 :                     response2 = !foeEntry->havePriority();
    7740       209121 :                 } else if (entry->haveYellow() && foeEntry->haveYellow()) {
    7741              :                     // let the faster vehicle keep moving
    7742         5718 :                     response = veh->getSpeed() >= getSpeed();
    7743         5718 :                     response2 = getSpeed() >= veh->getSpeed();
    7744              :                 } else {
    7745              :                     // fallback if pedestrian crossings are involved
    7746       203403 :                     response = logic->getResponseFor(link->getIndex()).test(foeLink->getIndex());
    7747       203403 :                     response2 = logic->getResponseFor(foeLink->getIndex()).test(link->getIndex());
    7748              :                 }
    7749              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7750              :                 if (DEBUG_COND) {
    7751              :                     std::cout << SIMTIME
    7752              :                               << " foeLane=" << foeLane->getID()
    7753              :                               << " foeLink=" << foeLink->getViaLaneOrLane()->getID()
    7754              :                               << " linkIndex=" << link->getIndex()
    7755              :                               << " foeLinkIndex=" << foeLink->getIndex()
    7756              :                               << " entryState=" << toString(entry->getState())
    7757              :                               << " entryState2=" << toString(foeEntry->getState())
    7758              :                               << " response=" << response
    7759              :                               << " response2=" << response2
    7760              :                               << "\n";
    7761              :                 }
    7762              : #endif
    7763       969273 :                 if (!response) {
    7764              :                     // if we have right of way over the foe, entryTime does not matter
    7765        82584 :                     foeET = veh->myJunctionConflictEntryTime;
    7766        82584 :                     egoET = myJunctionEntryTime;
    7767       886689 :                 } else if (response && response2) {
    7768              :                     // in a mutual conflict scenario, use entry time to avoid deadlock
    7769       128680 :                     foeET = veh->myJunctionConflictEntryTime;
    7770       128680 :                     egoET = myJunctionConflictEntryTime;
    7771              :                 }
    7772              :             }
    7773      1465874 :             if (egoET == foeET) {
    7774              :                 // try to use speed as tie braker
    7775       106170 :                 if (getSpeed() == veh->getSpeed()) {
    7776              :                     // use ID as tie braker
    7777              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7778              :                     if (DEBUG_COND) {
    7779              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7780              :                                   << " foeIsLeaderByID=" << (getID() < veh->getID()) << "\n";
    7781              :                     }
    7782              : #endif
    7783        55975 :                     return getID() < veh->getID();
    7784              :                 } else {
    7785              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7786              :                     if (DEBUG_COND) {
    7787              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7788              :                                   << " foeIsLeaderBySpeed=" << (getSpeed() < veh->getSpeed())
    7789              :                                   << " v=" << getSpeed() << " foeV=" << veh->getSpeed()
    7790              :                                   << "\n";
    7791              :                     }
    7792              : #endif
    7793        50195 :                     return getSpeed() < veh->getSpeed();
    7794              :                 }
    7795              :             } else {
    7796              :                 // leader was on the junction first
    7797              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7798              :                 if (DEBUG_COND) {
    7799              :                     std::cout << SIMTIME << " veh=" << getID() << " egoET " << egoET << " with foe " << veh->getID()
    7800              :                               << " foeET=" << foeET  << " isLeader=" << (egoET > foeET) << "\n";
    7801              :                 }
    7802              : #endif
    7803      1359704 :                 return egoET > foeET;
    7804              :             }
    7805              :         } else {
    7806              :             // vehicle can only be partially on the junction. Must be a leader
    7807              :             return true;
    7808              :         }
    7809              :     } else {
    7810              :         // vehicle can only be partially on the junction. Must be a leader
    7811              :         return true;
    7812              :     }
    7813              : }
    7814              : 
    7815              : void
    7816         2623 : MSVehicle::saveState(OutputDevice& out) {
    7817         2623 :     MSBaseVehicle::saveState(out);
    7818              :     // here starts the vehicle internal part (see loading)
    7819              :     std::vector<std::string> internals;
    7820         2623 :     internals.push_back(toString(myParameter->parametersSet));
    7821         2623 :     internals.push_back(toString(myDeparture));
    7822         2623 :     internals.push_back(toString(distance(myRoute->begin(), myCurrEdge)));
    7823         2623 :     internals.push_back(toString(myDepartPos));
    7824         2623 :     internals.push_back(toString(myWaitingTime));
    7825         2623 :     internals.push_back(toString(myTimeLoss));
    7826         2623 :     internals.push_back(toString(myLastActionTime));
    7827         2623 :     internals.push_back(toString(isStopped()));
    7828         2623 :     internals.push_back(toString(isStopped() ? myStops.front().duration : 0));
    7829         2623 :     internals.push_back(toString(myPastStops.size()));
    7830         2623 :     out.writeAttr(SUMO_ATTR_STATE, internals);
    7831         2623 :     out.writeAttr(SUMO_ATTR_POSITION, std::vector<double> { myState.myPos, myState.myBackPos, myState.myLastCoveredDist });
    7832         2623 :     out.writeAttr(SUMO_ATTR_SPEED, std::vector<double> { myState.mySpeed, myState.myPreviousSpeed });
    7833         2623 :     out.writeAttr(SUMO_ATTR_ANGLE, GeomHelper::naviDegree(myAngle));
    7834         2623 :     out.writeAttr(SUMO_ATTR_POSITION_LAT, myState.myPosLat);
    7835         2623 :     out.writeAttr(SUMO_ATTR_WAITINGTIME, myWaitingTimeCollector.getState());
    7836         2623 :     if (isStopped() && myStops.front().entryPos != getPositionOnLane()) {
    7837            1 :         out.writeAttr(SUMO_ATTR_ENTRYPOS, myStops.front().entryPos);
    7838              :     }
    7839         2623 :     myLaneChangeModel->saveState(out);
    7840              :     // save past stops
    7841         5703 :     for (SUMOVehicleParameter::Stop stop : myPastStops) {
    7842         3080 :         stop.write(out, false);
    7843              :         // do not write started and ended twice
    7844         3080 :         if ((stop.parametersSet & STOP_STARTED_SET) == 0) {
    7845         3075 :             out.writeAttr(SUMO_ATTR_STARTED, time2string(stop.started));
    7846              :         }
    7847         3080 :         if ((stop.parametersSet & STOP_ENDED_SET) == 0) {
    7848         3075 :             out.writeAttr(SUMO_ATTR_ENDED, time2string(stop.ended));
    7849              :         }
    7850         3080 :         stop.writeParams(out);
    7851         3080 :         out.closeTag();
    7852         3080 :     }
    7853              :     // save upcoming stops
    7854         3112 :     for (MSStop& stop : myStops) {
    7855          489 :         stop.write(out);
    7856              :     }
    7857              :     // save parameters and device states
    7858         2623 :     myParameter->writeParams(out);
    7859         6614 :     for (MSVehicleDevice* const dev : myDevices) {
    7860         3991 :         dev->saveState(out);
    7861              :     }
    7862         2623 :     if (myCFVariables != nullptr) {
    7863          110 :         myCFVariables->saveState(out, getCarFollowModel());
    7864              :     }
    7865         2623 :     out.closeTag();
    7866         2623 : }
    7867              : 
    7868              : void
    7869         3480 : MSVehicle::loadState(const SUMOSAXAttributes& attrs, const SUMOTime offset) {
    7870         3480 :     if (!attrs.hasAttribute(SUMO_ATTR_POSITION)) {
    7871            0 :         throw ProcessError(TL("Error: Invalid vehicles in state (may be a meso state)!"));
    7872              :     }
    7873              :     bool ok;
    7874              :     int routeOffset;
    7875              :     bool stopped;
    7876              :     SUMOTime stopDuration;
    7877              :     int pastStops;
    7878              : 
    7879         3480 :     std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
    7880         3480 :     bis >> myParameter->parametersSet;
    7881         3480 :     bis >> myDeparture;
    7882         3480 :     bis >> routeOffset;
    7883         3480 :     bis >> myDepartPos;
    7884         3480 :     bis >> myWaitingTime;
    7885         3480 :     bis >> myTimeLoss;
    7886         3480 :     bis >> myLastActionTime;
    7887              :     bis >> stopped;
    7888              :     bis >> stopDuration;
    7889         3480 :     bis >> pastStops;
    7890              : 
    7891         3480 :     if (attrs.hasAttribute(SUMO_ATTR_ARRIVALPOS_RANDOMIZED)) {
    7892            4 :         myArrivalPos = attrs.get<double>(SUMO_ATTR_ARRIVALPOS_RANDOMIZED, getID().c_str(), ok);
    7893              :     }
    7894              :     // load stops
    7895              :     myStops.clear();
    7896         3480 :     addStops(!MSGlobals::gCheckRoutes, &myCurrEdge, false);
    7897              : 
    7898         3480 :     if (hasDeparted()) {
    7899         1669 :         myCurrEdge = myRoute->begin() + routeOffset;
    7900         1669 :         myDeparture -= offset;
    7901              :         // fix stops
    7902         4725 :         while (pastStops > 0) {
    7903              :             SUMOVehicleParameter::Stop& pars = const_cast<SUMOVehicleParameter::Stop&>(myStops.front().pars);
    7904              :             // assumed these attributes were only added to restore vehroute-output.exit-times
    7905         3056 :             if (!MSGlobals::gUseStopEnded) {
    7906         3056 :                 pars.parametersSet &= ~STOP_ENDED_SET;
    7907              :             }
    7908         3056 :             if (!MSGlobals::gUseStopStarted) {
    7909         3056 :                 pars.parametersSet &= ~STOP_STARTED_SET;
    7910              :             }
    7911         6140 :             for (const auto& rem : myMoveReminders) {
    7912         3084 :                 rem.first->notifyStopEnded();
    7913              :             }
    7914         3056 :             myPastStops.push_back(myStops.front().pars);
    7915         3056 :             myPastStops.back().routeIndex = (int)(myStops.front().edge - myRoute->begin());
    7916         3056 :             myStops.pop_front();
    7917         3056 :             pastStops--;
    7918              :         }
    7919              :         // see MSBaseVehicle constructor
    7920         1669 :         if (myParameter->wasSet(VEHPARS_FORCE_REROUTE)) {
    7921         1148 :             calculateArrivalParams(true);
    7922              :         }
    7923              :         // a (tentative lane is needed for calling hasArrivedInternal
    7924         1669 :         myLane = (*myCurrEdge)->getLanes()[0];
    7925              :     }
    7926         3480 :     if (getActionStepLength() == DELTA_T && !isActionStep(SIMSTEP)) {
    7927            1 :         myLastActionTime -= (myLastActionTime - SIMSTEP) % DELTA_T;
    7928            3 :         WRITE_WARNINGF(TL("Action steps are out of sync for loaded vehicle '%'."), getID());
    7929              :     }
    7930         3480 :     std::istringstream pis(attrs.getString(SUMO_ATTR_POSITION));
    7931         3480 :     pis >> myState.myPos >> myState.myBackPos >> myState.myLastCoveredDist;
    7932         3480 :     std::istringstream sis(attrs.getString(SUMO_ATTR_SPEED));
    7933         3480 :     sis >> myState.mySpeed >> myState.myPreviousSpeed;
    7934         3480 :     myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7935         3480 :     myAngle = GeomHelper::fromNaviDegree(attrs.getFloat(SUMO_ATTR_ANGLE));
    7936         3480 :     myRawAngle = myAngle;
    7937         3480 :     myState.myPosLat = attrs.getFloat(SUMO_ATTR_POSITION_LAT);
    7938         3480 :     std::istringstream dis(attrs.getString(SUMO_ATTR_DISTANCE));
    7939         3480 :     dis >> myOdometer >> myNumberReroutes;
    7940         3480 :     myWaitingTimeCollector.setState(attrs.getString(SUMO_ATTR_WAITINGTIME));
    7941         3480 :     if (stopped) {
    7942          234 :         double realPos = getPositionOnLane();
    7943          234 :         double entryPos = attrs.getOpt<double>(SUMO_ATTR_ENTRYPOS, getID().c_str(), ok, realPos);
    7944          234 :         myStops.front().startedFromState = true;
    7945          234 :         if (entryPos != realPos) {
    7946            1 :             myStops.front().entryPos = entryPos;
    7947              :         }
    7948          234 :         myLane = const_cast<MSLane*>(myStops.front().lane);
    7949          234 :         myStopDist = 0;
    7950          234 :         myState.myPos = entryPos; // fake position for replication stop entry which happened before the position was updated
    7951          234 :         processNextStop(getSpeed());
    7952          234 :         myState.myPos = realPos; // reset fake position
    7953          234 :         if (myStops.front().pars.parking != ParkingType::ONROAD) {
    7954              :             // processNextStop is called again during MSVehicleTransfer::loadState
    7955          216 :             stopDuration += getActionStepLength();
    7956              :         }
    7957          234 :         myStops.front().duration = stopDuration;
    7958          234 :         if (!MSGlobals::gUseStopStarted) {
    7959              :             SUMOVehicleParameter::Stop& pars = const_cast<SUMOVehicleParameter::Stop&>(myStops.front().pars);
    7960          234 :             pars.parametersSet &= ~STOP_STARTED_SET;
    7961              :         }
    7962              :     }
    7963         3480 :     myLaneChangeModel->loadState(attrs);
    7964              :     // no need to reset myCachedPosition here since state loading happens directly after creation
    7965         3480 : }
    7966              : 
    7967              : void
    7968           32 : MSVehicle::loadPreviousApproaching(MSLink* link, bool setRequest,
    7969              :                                    SUMOTime arrivalTime, double arrivalSpeed,
    7970              :                                    double arrivalSpeedBraking,
    7971              :                                    double dist, double leaveSpeed) {
    7972              :     // ensure that approach information is reset on the next call to setApproachingForAllLinks
    7973           32 :     myLFLinkLanes.push_back(DriveProcessItem(link, 0, 0, setRequest,
    7974              :                             arrivalTime, arrivalSpeed, arrivalSpeedBraking, dist, leaveSpeed));
    7975              : 
    7976           32 : }
    7977              : 
    7978              : 
    7979              : std::shared_ptr<MSSimpleDriverState>
    7980      2565915 : MSVehicle::getDriverState() const {
    7981      2565915 :     return myDriverState->getDriverState();
    7982              : }
    7983              : 
    7984              : 
    7985              : double
    7986    623474108 : MSVehicle::getFriction() const {
    7987    623474108 :     return myFrictionDevice == nullptr ? 1. : myFrictionDevice->getMeasuredFriction();
    7988              : }
    7989              : 
    7990              : 
    7991              : void
    7992          196 : MSVehicle::setPreviousSpeed(double prevSpeed, double prevAcceleration) {
    7993          196 :     myState.mySpeed = MAX2(0., prevSpeed);
    7994              :     // also retcon acceleration
    7995          196 :     if (prevAcceleration != std::numeric_limits<double>::min()) {
    7996            8 :         myAcceleration = prevAcceleration;
    7997              :     } else {
    7998          188 :         myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7999              :     }
    8000          196 : }
    8001              : 
    8002              : 
    8003              : double
    8004   1870803570 : MSVehicle::getCurrentApparentDecel() const {
    8005              :     //return MAX2(-myAcceleration, getCarFollowModel().getApparentDecel());
    8006   1870803570 :     return getCarFollowModel().getApparentDecel();
    8007              : }
    8008              : 
    8009              : /****************************************************************************/
    8010              : bool
    8011           32 : MSVehicle::setExitManoeuvre() {
    8012           32 :     return (myManoeuvre.configureExitManoeuvre(this));
    8013              : }
    8014              : 
    8015              : /* -------------------------------------------------------------------------
    8016              :  * methods of MSVehicle::manoeuvre
    8017              :  * ----------------------------------------------------------------------- */
    8018              : 
    8019      4520490 : MSVehicle::Manoeuvre::Manoeuvre() : myManoeuvreStop(""), myManoeuvreStartTime(0), myManoeuvreCompleteTime(0), myManoeuvreType(MSVehicle::MANOEUVRE_NONE), myGUIIncrement(0) {}
    8020              : 
    8021              : 
    8022            0 : MSVehicle::Manoeuvre::Manoeuvre(const Manoeuvre& manoeuvre) {
    8023            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    8024            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    8025            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    8026            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    8027            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    8028            0 : }
    8029              : 
    8030              : 
    8031              : MSVehicle::Manoeuvre&
    8032            0 : MSVehicle::Manoeuvre::operator=(const Manoeuvre& manoeuvre) {
    8033            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    8034            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    8035            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    8036            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    8037            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    8038            0 :     return *this;
    8039              : }
    8040              : 
    8041              : 
    8042              : bool
    8043            0 : MSVehicle::Manoeuvre::operator!=(const Manoeuvre& manoeuvre) {
    8044            0 :     return (myManoeuvreStop != manoeuvre.myManoeuvreStop ||
    8045            0 :             myManoeuvreStartTime != manoeuvre.myManoeuvreStartTime ||
    8046            0 :             myManoeuvreCompleteTime != manoeuvre.myManoeuvreCompleteTime ||
    8047            0 :             myManoeuvreType != manoeuvre.myManoeuvreType ||
    8048            0 :             myGUIIncrement != manoeuvre.myGUIIncrement
    8049            0 :            );
    8050              : }
    8051              : 
    8052              : 
    8053              : double
    8054          450 : MSVehicle::Manoeuvre::getGUIIncrement() const {
    8055          450 :     return (myGUIIncrement);
    8056              : }
    8057              : 
    8058              : 
    8059              : MSVehicle::ManoeuvreType
    8060         2971 : MSVehicle::Manoeuvre::getManoeuvreType() const {
    8061         2971 :     return (myManoeuvreType);
    8062              : }
    8063              : 
    8064              : 
    8065              : MSVehicle::ManoeuvreType
    8066         2971 : MSVehicle::getManoeuvreType() const {
    8067         2971 :     return (myManoeuvre.getManoeuvreType());
    8068              : }
    8069              : 
    8070              : 
    8071              : void
    8072           30 : MSVehicle::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    8073           30 :     myManoeuvre.setManoeuvreType(mType);
    8074           30 : }
    8075              : 
    8076              : 
    8077              : void
    8078           30 : MSVehicle::Manoeuvre::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    8079           30 :     myManoeuvreType = mType;
    8080           30 : }
    8081              : 
    8082              : 
    8083              : bool
    8084           30 : MSVehicle::Manoeuvre::configureEntryManoeuvre(MSVehicle* veh) {
    8085           30 :     if (!veh->hasStops()) {
    8086              :         return false;    // should never happen - checked before call
    8087              :     }
    8088              : 
    8089           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    8090           30 :     const MSStop& stop = veh->getNextStop();
    8091              : 
    8092           30 :     int manoeuverAngle = stop.parkingarea->getLastFreeLotAngle();
    8093           30 :     double GUIAngle = stop.parkingarea->getLastFreeLotGUIAngle();
    8094           30 :     if (abs(GUIAngle) < 0.1) {
    8095              :         GUIAngle = -0.1;    // Wiggle vehicle on parallel entry
    8096              :     }
    8097           30 :     myManoeuvreVehicleID = veh->getID();
    8098           30 :     myManoeuvreStop = stop.parkingarea->getID();
    8099           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_ENTRY;
    8100           30 :     myManoeuvreStartTime = currentTime;
    8101           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getEntryManoeuvreTime(manoeuverAngle);
    8102           30 :     myGUIIncrement = GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    8103              : 
    8104              : #ifdef DEBUG_STOPS
    8105              :     if (veh->isSelected()) {
    8106              :         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 <<
    8107              :                   " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    8108              :     }
    8109              : #endif
    8110              : 
    8111           30 :     return (true);
    8112              : }
    8113              : 
    8114              : 
    8115              : bool
    8116           32 : MSVehicle::Manoeuvre::configureExitManoeuvre(MSVehicle* veh) {
    8117              :     // At the moment we only want to set for parking areas
    8118           32 :     if (!veh->hasStops()) {
    8119              :         return true;
    8120              :     }
    8121           32 :     if (veh->getNextStop().parkingarea == nullptr) {
    8122              :         return true;
    8123              :     }
    8124              : 
    8125           30 :     if (myManoeuvreType != MSVehicle::MANOEUVRE_NONE) {
    8126              :         return (false);
    8127              :     }
    8128              : 
    8129           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    8130              : 
    8131           30 :     int manoeuverAngle = veh->getCurrentParkingArea()->getManoeuverAngle(*veh);
    8132           30 :     double GUIAngle = veh->getCurrentParkingArea()->getGUIAngle(*veh);
    8133           30 :     if (abs(GUIAngle) < 0.1) {
    8134              :         GUIAngle = 0.1;    // Wiggle vehicle on parallel exit
    8135              :     }
    8136              : 
    8137           30 :     myManoeuvreVehicleID = veh->getID();
    8138           30 :     myManoeuvreStop = veh->getCurrentParkingArea()->getID();
    8139           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_EXIT;
    8140           30 :     myManoeuvreStartTime = currentTime;
    8141           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getExitManoeuvreTime(manoeuverAngle);
    8142           30 :     myGUIIncrement = -GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    8143           30 :     if (veh->remainingStopDuration() > 0) {
    8144           20 :         myManoeuvreCompleteTime += veh->remainingStopDuration();
    8145              :     }
    8146              : 
    8147              : #ifdef DEBUG_STOPS
    8148              :     if (veh->isSelected()) {
    8149              :         std::cout << "EXIT manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle  << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime
    8150              :                   << " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    8151              :     }
    8152              : #endif
    8153              : 
    8154              :     return (true);
    8155              : }
    8156              : 
    8157              : 
    8158              : bool
    8159          222 : MSVehicle::Manoeuvre::entryManoeuvreIsComplete(MSVehicle* veh) {
    8160              :     // At the moment we only want to consider parking areas - need to check because we could be setting up a manoeuvre
    8161          222 :     if (!veh->hasStops()) {
    8162              :         return (true);
    8163              :     }
    8164              :     MSStop* currentStop = &veh->myStops.front();
    8165          222 :     if (currentStop->parkingarea == nullptr) {
    8166              :         return true;
    8167          220 :     } else if (currentStop->parkingarea->getID() != myManoeuvreStop || MSVehicle::MANOEUVRE_ENTRY != myManoeuvreType) {
    8168           30 :         if (configureEntryManoeuvre(veh)) {
    8169           30 :             MSNet::getInstance()->informVehicleStateListener(veh, MSNet::VehicleState::MANEUVERING);
    8170           30 :             return (false);
    8171              :         } else { // cannot configure entry so stop trying
    8172              :             return true;
    8173              :         }
    8174          190 :     } else if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8175              :         return false;
    8176              :     } else { // manoeuvre complete
    8177           30 :         myManoeuvreType = MSVehicle::MANOEUVRE_NONE;
    8178           30 :         return true;
    8179              :     }
    8180              : }
    8181              : 
    8182              : 
    8183              : bool
    8184            0 : MSVehicle::Manoeuvre::manoeuvreIsComplete(const ManoeuvreType checkType) const {
    8185            0 :     if (checkType != myManoeuvreType) {
    8186              :         return true;    // we're not maneuvering / wrong manoeuvre
    8187              :     }
    8188              : 
    8189            0 :     if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8190              :         return false;
    8191              :     } else {
    8192              :         return true;
    8193              :     }
    8194              : }
    8195              : 
    8196              : 
    8197              : bool
    8198         6266 : MSVehicle::Manoeuvre::manoeuvreIsComplete() const {
    8199         6266 :     return (MSNet::getInstance()->getCurrentTimeStep() >= myManoeuvreCompleteTime);
    8200              : }
    8201              : 
    8202              : 
    8203              : bool
    8204         6266 : MSVehicle::manoeuvreIsComplete() const {
    8205         6266 :     return (myManoeuvre.manoeuvreIsComplete());
    8206              : }
    8207              : 
    8208              : 
    8209              : std::pair<double, double>
    8210         7440 : MSVehicle::estimateTimeToNextStop() const {
    8211         7440 :     if (hasStops()) {
    8212         7440 :         MSLane* lane = myLane;
    8213         7440 :         if (lane == nullptr) {
    8214              :             // not in network
    8215           84 :             lane = getEdge()->getLanes()[0];
    8216              :         }
    8217              :         const MSStop& stop = myStops.front();
    8218              :         auto it = myCurrEdge + 1;
    8219              :         // drive to end of current edge
    8220         7440 :         double dist = (lane->getLength() - getPositionOnLane());
    8221         7440 :         double travelTime = lane->getEdge().getMinimumTravelTime(this) * dist / lane->getLength();
    8222              :         // drive until stop edge
    8223         8804 :         while (it != myRoute->end() && it < stop.edge) {
    8224         1364 :             travelTime += (*it)->getMinimumTravelTime(this);
    8225         1364 :             dist += (*it)->getLength();
    8226              :             it++;
    8227              :         }
    8228              :         // drive up to the stop position
    8229         7440 :         const double stopEdgeDist = stop.pars.endPos - (lane == stop.lane ? lane->getLength() : 0);
    8230         7440 :         dist += stopEdgeDist;
    8231         7440 :         travelTime += stop.lane->getEdge().getMinimumTravelTime(this) * (stopEdgeDist / stop.lane->getLength());
    8232              :         // estimate time loss due to acceleration and deceleration
    8233              :         // maximum speed is limited by available distance:
    8234              :         const double a = getCarFollowModel().getMaxAccel();
    8235              :         const double b = getCarFollowModel().getMaxDecel();
    8236         7440 :         const double c = getSpeed();
    8237              :         const double d = dist;
    8238         7440 :         const double len = getVehicleType().getLength();
    8239         7440 :         const double vs = MIN2(MAX2(stop.getSpeed(), 0.0), stop.lane->getVehicleMaxSpeed(this));
    8240              :         // distAccel = (v - c)^2 / (2a)
    8241              :         // distDecel = (v + vs)*(v - vs) / 2b = (v^2 - vs^2) / (2b)
    8242              :         // distAccel + distDecel < d
    8243         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))))
    8244        14592 :                                             + pow((a * vs), 2))))) * 0.5) + (c * b)) / (b + a));
    8245         7440 :         it = myCurrEdge;
    8246              :         double v0 = c;
    8247         7440 :         bool v0Stable = getAcceleration() == 0 && v0 > 0;
    8248              :         double timeLossAccel = 0;
    8249              :         double timeLossDecel = 0;
    8250              :         double timeLossLength = 0;
    8251        17742 :         while (it != myRoute->end() && it <= stop.edge) {
    8252        10302 :             double v = MIN2(maxVD, (*it)->getVehicleMaxSpeed(this));
    8253        10302 :             double edgeLength = (it == stop.edge ? stop.pars.endPos : (*it)->getLength()) - (it == myCurrEdge ? getPositionOnLane() : 0);
    8254        10302 :             if (edgeLength <= len && v0Stable && v0 < v) {
    8255              :                 const double lengthDist = MIN2(len, edgeLength);
    8256           20 :                 const double dTL = lengthDist / v0 - lengthDist / v;
    8257              :                 //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " el=" << edgeLength << " lDist=" << lengthDist << " newTLL=" << dTL<< "\n";
    8258           20 :                 timeLossLength += dTL;
    8259              :             }
    8260        10302 :             if (edgeLength > len) {
    8261         9166 :                 const double dv = v - v0;
    8262         9166 :                 if (dv > 0) {
    8263              :                     // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8264         6504 :                     const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8265              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8266         6504 :                     timeLossAccel += dTA;
    8267              :                     // time loss from vehicle length
    8268         2662 :                 } else if (dv < 0) {
    8269              :                     // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8270          540 :                     const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8271              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8272          540 :                     timeLossDecel += dTD;
    8273              :                 }
    8274              :                 v0 = v;
    8275              :                 v0Stable = true;
    8276              :             }
    8277              :             it++;
    8278              :         }
    8279              :         // final deceleration to stop (may also be acceleration or deceleration to waypoint speed)
    8280              :         double v = vs;
    8281         7440 :         const double dv = v - v0;
    8282         7440 :         if (dv > 0) {
    8283              :             // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8284          144 :             const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8285              :             //std::cout << "  final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8286          144 :             timeLossAccel += dTA;
    8287              :             // time loss from vehicle length
    8288         7296 :         } else if (dv < 0) {
    8289              :             // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8290         7268 :             const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8291              :             //std::cout << "  final  e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8292         7268 :             timeLossDecel += dTD;
    8293              :         }
    8294         7440 :         const double result = travelTime + timeLossAccel + timeLossDecel + timeLossLength;
    8295              :         //std::cout << SIMTIME << " v=" << c << " a=" << a << " b=" << b << " maxVD=" << maxVD << " tt=" << travelTime
    8296              :         //    << " ta=" << timeLossAccel << " td=" << timeLossDecel << " tl=" << timeLossLength << " res=" << result << "\n";
    8297         7440 :         return {MAX2(0.0, result), dist};
    8298              :     } else {
    8299            0 :         return {INVALID_DOUBLE, INVALID_DOUBLE};
    8300              :     }
    8301              : }
    8302              : 
    8303              : 
    8304              : double
    8305         2457 : MSVehicle::getStopDelay() const {
    8306         2457 :     if (hasStops() && myStops.front().pars.until >= 0) {
    8307              :         const MSStop& stop = myStops.front();
    8308         1612 :         SUMOTime estimatedDepart = MSNet::getInstance()->getCurrentTimeStep() - DELTA_T;
    8309         1612 :         if (stop.reached) {
    8310          802 :             return STEPS2TIME(estimatedDepart + stop.duration - stop.pars.until);
    8311              :         }
    8312          810 :         if (stop.pars.duration > 0) {
    8313          608 :             estimatedDepart += stop.pars.duration;
    8314              :         }
    8315          810 :         estimatedDepart += TIME2STEPS(estimateTimeToNextStop().first);
    8316          810 :         const double result = MAX2(0.0, STEPS2TIME(estimatedDepart - stop.pars.until));
    8317          810 :         return result;
    8318              :     } else {
    8319              :         // vehicles cannot drive before 'until' so stop delay can never be
    8320              :         // negative and we can use -1 to signal "undefined"
    8321              :         return -1;
    8322              :     }
    8323              : }
    8324              : 
    8325              : 
    8326              : double
    8327         5510 : MSVehicle::getStopArrivalDelay() const {
    8328         5510 :     if (hasStops() && myStops.front().pars.arrival >= 0) {
    8329              :         const MSStop& stop = myStops.front();
    8330         4334 :         if (stop.reached) {
    8331         1304 :             return STEPS2TIME(stop.pars.started - stop.pars.arrival);
    8332              :         } else {
    8333         3030 :             return STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) + estimateTimeToNextStop().first - STEPS2TIME(stop.pars.arrival);
    8334              :         }
    8335              :     } else {
    8336              :         // vehicles can arrive earlier than planned so arrival delay can be negative
    8337              :         return INVALID_DOUBLE;
    8338              :     }
    8339              : }
    8340              : 
    8341              : 
    8342              : const MSEdge*
    8343   3104266642 : MSVehicle::getCurrentEdge() const {
    8344   3104266642 :     return myLane != nullptr ? &myLane->getEdge() : getEdge();
    8345              : }
    8346              : 
    8347              : 
    8348              : const MSEdge*
    8349         3932 : MSVehicle::getNextEdgePtr() const {
    8350         3932 :     if (myLane == nullptr || (myCurrEdge + 1) == myRoute->end()) {
    8351            8 :         return nullptr;
    8352              :     }
    8353         3924 :     if (myLane->isInternal()) {
    8354          568 :         return &myLane->getCanonicalSuccessorLane()->getEdge();
    8355              :     } else {
    8356         3356 :         const MSEdge* nextNormal = succEdge(1);
    8357         3356 :         const MSEdge* nextInternal = myLane->getEdge().getInternalFollowingEdge(nextNormal, getVClass());
    8358         3356 :         return nextInternal ? nextInternal : nextNormal;
    8359              :     }
    8360              : }
    8361              : 
    8362              : 
    8363              : const MSLane*
    8364         1602 : MSVehicle::getPreviousLane(const MSLane* current, int& furtherIndex) const {
    8365         1602 :     if (furtherIndex < (int)myFurtherLanes.size()) {
    8366         1225 :         return myFurtherLanes[furtherIndex++];
    8367              :     } else {
    8368              :         // try to use route information
    8369          377 :         int routeIndex = getRoutePosition();
    8370              :         bool resultInternal;
    8371          377 :         if (MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()) {
    8372            0 :             if (myLane->isInternal()) {
    8373            0 :                 if (furtherIndex % 2 == 0) {
    8374            0 :                     routeIndex -= (furtherIndex + 0) / 2;
    8375              :                     resultInternal = false;
    8376              :                 } else {
    8377            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8378              :                     resultInternal = false;
    8379              :                 }
    8380              :             } else {
    8381            0 :                 if (furtherIndex % 2 != 0) {
    8382            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8383              :                     resultInternal = false;
    8384              :                 } else {
    8385            0 :                     routeIndex -= (furtherIndex + 2) / 2;
    8386              :                     resultInternal = true;
    8387              :                 }
    8388              :             }
    8389              :         } else {
    8390          377 :             routeIndex -= furtherIndex;
    8391              :             resultInternal = false;
    8392              :         }
    8393          377 :         furtherIndex++;
    8394          377 :         if (routeIndex >= 0) {
    8395          163 :             if (resultInternal) {
    8396            0 :                 const MSEdge* prevNormal = myRoute->getEdges()[routeIndex];
    8397            0 :                 for (MSLane* cand : prevNormal->getLanes()) {
    8398            0 :                     for (MSLink* link : cand->getLinkCont()) {
    8399            0 :                         if (link->getLane() == current) {
    8400            0 :                             if (link->getViaLane() != nullptr) {
    8401              :                                 return link->getViaLane();
    8402              :                             } else {
    8403            0 :                                 return const_cast<MSLane*>(link->getLaneBefore());
    8404              :                             }
    8405              :                         }
    8406              :                     }
    8407              :                 }
    8408              :             } else {
    8409          163 :                 return myRoute->getEdges()[routeIndex]->getLanes()[0];
    8410              :             }
    8411              :         }
    8412              :     }
    8413              :     return current;
    8414              : }
    8415              : 
    8416              : SUMOTime
    8417   1525932050 : MSVehicle::getWaitingTimeFor(const MSLink* link) const {
    8418              :     // this vehicle currently has the highest priority on the allway_stop
    8419   1525932050 :     return link == myHaveStoppedFor ? SUMOTime_MAX : getWaitingTime();
    8420              : }
    8421              : 
    8422              : 
    8423              : void
    8424          694 : MSVehicle::resetApproachOnReroute() {
    8425              :     bool diverged = false;
    8426              :     const ConstMSEdgeVector& route = myRoute->getEdges();
    8427          694 :     int ri = getRoutePosition();
    8428         2928 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    8429         2234 :         if (dpi.myLink != nullptr) {
    8430         2231 :             if (!diverged) {
    8431         1998 :                 const MSEdge* next = route[ri + 1];
    8432         1998 :                 if (&dpi.myLink->getLane()->getEdge() != next) {
    8433              :                     diverged = true;
    8434              :                 } else {
    8435         1932 :                     if (dpi.myLink->getViaLane() == nullptr) {
    8436              :                         ri++;
    8437              :                     }
    8438              :                 }
    8439              :             }
    8440              :             if (diverged) {
    8441          299 :                 dpi.myLink->removeApproaching(this);
    8442              :             }
    8443              :         }
    8444              :     }
    8445          694 : }
    8446              : 
    8447              : 
    8448              : bool
    8449     14906875 : MSVehicle::instantStopping() const {
    8450     14906875 :     return myInfluencer && !myInfluencer->considerMaxDeceleration();
    8451              : }
    8452              : 
    8453              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1