LCOV - code coverage report
Current view: top level - src/microsim - MSVehicle.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 96.3 % 3286 3163
Test Date: 2026-01-01 15:49:29 Functions: 95.1 % 224 213

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2001-2025 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      3618849 : MSVehicle::State::operator=(const State& state) {
     153      3618849 :     myPos   = state.myPos;
     154      3618849 :     mySpeed = state.mySpeed;
     155      3618849 :     myPosLat   = state.myPosLat;
     156      3618849 :     myBackPos = state.myBackPos;
     157      3618849 :     myPreviousSpeed = state.myPreviousSpeed;
     158      3618849 :     myLastCoveredDist = state.myLastCoveredDist;
     159      3618849 :     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      8205237 : MSVehicle::State::State(double pos, double speed, double posLat, double backPos, double previousSpeed) :
     175      8205237 :     myPos(pos), mySpeed(speed), myPosLat(posLat), myBackPos(backPos), myPreviousSpeed(previousSpeed), myLastCoveredDist(SPEED2DIST(speed)) {}
     176              : 
     177              : 
     178              : 
     179              : /* -------------------------------------------------------------------------
     180              :  * methods of MSVehicle::WaitingTimeCollector
     181              :  * ----------------------------------------------------------------------- */
     182      4586388 : MSVehicle::WaitingTimeCollector::WaitingTimeCollector(SUMOTime memory) : myMemorySize(memory) {}
     183              : 
     184              : 
     185              : SUMOTime
     186      1428993 : MSVehicle::WaitingTimeCollector::cumulatedWaitingTime(SUMOTime memorySpan) const {
     187              :     assert(memorySpan <= myMemorySize);
     188      1428993 :     if (memorySpan == -1) {
     189            0 :         memorySpan = myMemorySize;
     190              :     }
     191              :     SUMOTime totalWaitingTime = 0;
     192      5945081 :     for (const auto& interval : myWaitingIntervals) {
     193      4516088 :         if (interval.second >= memorySpan) {
     194       655960 :             if (interval.first >= memorySpan) {
     195              :                 break;
     196              :             } else {
     197       655960 :                 totalWaitingTime += memorySpan - interval.first;
     198              :             }
     199              :         } else {
     200      3860128 :             totalWaitingTime += interval.second - interval.first;
     201              :         }
     202              :     }
     203      1428993 :     return totalWaitingTime;
     204              : }
     205              : 
     206              : 
     207              : void
     208    687092476 : MSVehicle::WaitingTimeCollector::passTime(SUMOTime dt, bool waiting) {
     209              :     auto i = myWaitingIntervals.begin();
     210              :     const auto end = myWaitingIntervals.end();
     211    687092476 :     const bool startNewInterval = i == end || (i->first != 0);
     212   1106584707 :     while (i != end) {
     213    421679023 :         i->first += dt;
     214    421679023 :         if (i->first >= myMemorySize) {
     215              :             break;
     216              :         }
     217    419492231 :         i->second += dt;
     218              :         i++;
     219              :     }
     220              : 
     221              :     // remove intervals beyond memorySize
     222              :     auto d = std::distance(i, end);
     223    689279268 :     while (d > 0) {
     224      2186792 :         myWaitingIntervals.pop_back();
     225      2186792 :         d--;
     226              :     }
     227              : 
     228    687092476 :     if (!waiting) {
     229              :         return;
     230     84997431 :     } else if (!startNewInterval) {
     231     81570282 :         myWaitingIntervals.begin()->first = 0;
     232              :     } else {
     233      6854298 :         myWaitingIntervals.push_front(std::make_pair(0, dt));
     234              :     }
     235              :     return;
     236              : }
     237              : 
     238              : 
     239              : const std::string
     240         2477 : MSVehicle::WaitingTimeCollector::getState() const {
     241         2477 :     std::ostringstream state;
     242         2477 :     state << myMemorySize << " " << myWaitingIntervals.size();
     243         3396 :     for (const auto& interval : myWaitingIntervals) {
     244         1838 :         state << " " << interval.first << " " << interval.second;
     245              :     }
     246         2477 :     return state.str();
     247         2477 : }
     248              : 
     249              : 
     250              : void
     251         4160 : MSVehicle::WaitingTimeCollector::setState(const std::string& state) {
     252         4160 :     std::istringstream is(state);
     253              :     int numIntervals;
     254              :     SUMOTime begin, end;
     255         4160 :     is >> myMemorySize >> numIntervals;
     256         6915 :     while (numIntervals-- > 0) {
     257              :         is >> begin >> end;
     258         2755 :         myWaitingIntervals.emplace_back(begin, end);
     259              :     }
     260         4160 : }
     261              : 
     262              : 
     263              : /* -------------------------------------------------------------------------
     264              :  * methods of MSVehicle::Influencer::GapControlState
     265              :  * ----------------------------------------------------------------------- */
     266              : void
     267           32 : 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           32 :     switch (to) {
     270            5 :         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            5 :             const MSVehicle* msVeh = static_cast<const MSVehicle*>(vehicle);
     276              : //        std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << " left the road." << std::endl;
     277            5 :             if (GapControlState::refVehMap.find(msVeh) != end(GapControlState::refVehMap)) {
     278              : //            std::cout << "GapControlVehStateListener::deactivating ref vehicle=" << vehicle->getID() << std::endl;
     279            5 :                 GapControlState::refVehMap[msVeh]->deactivate();
     280              :             }
     281              :         }
     282            5 :         break;
     283           32 :         default:
     284              :         {};
     285              :             // do nothing, vehicle still on road
     286              :     }
     287           32 : }
     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           59 : MSVehicle::Influencer::GapControlState::GapControlState() :
     295           59 :     tauOriginal(-1), tauCurrent(-1), tauTarget(-1), addGapCurrent(-1), addGapTarget(-1),
     296           59 :     remainingDuration(-1), changeRate(-1), maxDecel(-1), referenceVeh(nullptr), active(false), gapAttained(false), prevLeader(nullptr),
     297           59 :     lastUpdate(-1), timeHeadwayIncrement(0.0), spaceHeadwayIncrement(0.0) {}
     298              : 
     299              : 
     300           59 : MSVehicle::Influencer::GapControlState::~GapControlState() {
     301           59 :     deactivate();
     302           59 : }
     303              : 
     304              : void
     305           59 : MSVehicle::Influencer::GapControlState::init() {
     306           59 :     if (MSNet::hasInstance()) {
     307           59 :         if (myVehStateListener == nullptr) {
     308              :             //std::cout << "GapControlState::init()" << std::endl;
     309           59 :             myVehStateListener = new GapControlVehStateListener();
     310           59 :             MSNet::getInstance()->addVehicleStateListener(myVehStateListener);
     311              :         }
     312              :     } else {
     313            0 :         WRITE_ERROR("MSVehicle::Influencer::GapControlState::init(): No MSNet instance found!")
     314              :     }
     315           59 : }
     316              : 
     317              : void
     318        34009 : MSVehicle::Influencer::GapControlState::cleanup() {
     319        34009 :     if (myVehStateListener != nullptr) {
     320           59 :         MSNet::getInstance()->removeVehicleStateListener(myVehStateListener);
     321           59 :         delete myVehStateListener;
     322           59 :         myVehStateListener = nullptr;
     323              :     }
     324        34009 : }
     325              : 
     326              : void
     327           59 : MSVehicle::Influencer::GapControlState::activate(double tauOrig, double tauNew, double additionalGap, double dur, double rate, double decel, const MSVehicle* refVeh) {
     328           59 :     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           59 :         tauOriginal = tauOrig;
     334           59 :         tauCurrent = tauOrig;
     335           59 :         tauTarget = tauNew;
     336           59 :         addGapCurrent = 0.0;
     337           59 :         addGapTarget = additionalGap;
     338           59 :         remainingDuration = dur;
     339           59 :         changeRate = rate;
     340           59 :         maxDecel = decel;
     341           59 :         referenceVeh = refVeh;
     342           59 :         active = true;
     343           59 :         gapAttained = false;
     344           59 :         prevLeader = nullptr;
     345           59 :         lastUpdate = SIMSTEP - DELTA_T;
     346           59 :         timeHeadwayIncrement = changeRate * TS * (tauTarget - tauOriginal);
     347           59 :         spaceHeadwayIncrement = changeRate * TS * addGapTarget;
     348              : 
     349           59 :         if (referenceVeh != nullptr) {
     350              :             // Add refVeh to refVehMap
     351           13 :             GapControlState::refVehMap[referenceVeh] = this;
     352              :         }
     353              :     }
     354           59 : }
     355              : 
     356              : void
     357          118 : MSVehicle::Influencer::GapControlState::deactivate() {
     358          118 :     active = false;
     359          118 :     if (referenceVeh != nullptr) {
     360              :         // Remove corresponding refVehMapEntry if appropriate
     361           13 :         GapControlState::refVehMap.erase(referenceVeh);
     362           13 :         referenceVeh = nullptr;
     363              :     }
     364          118 : }
     365              : 
     366              : 
     367              : /* -------------------------------------------------------------------------
     368              :  * methods of MSVehicle::Influencer
     369              :  * ----------------------------------------------------------------------- */
     370         3530 : MSVehicle::Influencer::Influencer() :
     371              :     myGapControlState(nullptr),
     372         3530 :     myOriginalSpeed(-1),
     373         3530 :     myLatDist(0),
     374         3530 :     mySpeedAdaptationStarted(true),
     375         3530 :     myConsiderSafeVelocity(true),
     376         3530 :     myConsiderSpeedLimit(true),
     377         3530 :     myConsiderMaxAcceleration(true),
     378         3530 :     myConsiderMaxDeceleration(true),
     379         3530 :     myRespectJunctionPriority(true),
     380         3530 :     myEmergencyBrakeRedLight(true),
     381         3530 :     myRespectJunctionLeaderPriority(true),
     382         3530 :     myLastRemoteAccess(-TIME2STEPS(20)),
     383         3530 :     myStrategicLC(LC_NOCONFLICT),
     384         3530 :     myCooperativeLC(LC_NOCONFLICT),
     385         3530 :     mySpeedGainLC(LC_NOCONFLICT),
     386         3530 :     myRightDriveLC(LC_NOCONFLICT),
     387         3530 :     mySublaneLC(LC_NOCONFLICT),
     388         3530 :     myTraciLaneChangePriority(LCP_URGENT),
     389         3530 :     myTraCISignals(-1)
     390         3530 : {}
     391              : 
     392              : 
     393        10590 : MSVehicle::Influencer::~Influencer() {}
     394              : 
     395              : void
     396           59 : MSVehicle::Influencer::init() {
     397           59 :     GapControlState::init();
     398           59 : }
     399              : 
     400              : void
     401        34009 : MSVehicle::Influencer::cleanup() {
     402        34009 :     GapControlState::cleanup();
     403        34009 : }
     404              : 
     405              : void
     406        42871 : MSVehicle::Influencer::setSpeedTimeLine(const std::vector<std::pair<SUMOTime, double> >& speedTimeLine) {
     407        42871 :     mySpeedAdaptationStarted = true;
     408        42871 :     mySpeedTimeLine = speedTimeLine;
     409        42871 : }
     410              : 
     411              : void
     412           59 : MSVehicle::Influencer::activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle* refVeh) {
     413           59 :     if (myGapControlState == nullptr) {
     414           59 :         myGapControlState = std::make_shared<GapControlState>();
     415           59 :         init(); // only does things on first call
     416              :     }
     417           59 :     myGapControlState->activate(originalTau, newTimeHeadway, newSpaceHeadway, duration, changeRate, maxDecel, refVeh);
     418           59 : }
     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         8195 : MSVehicle::Influencer::setLaneTimeLine(const std::vector<std::pair<SUMOTime, int> >& laneTimeLine) {
     429         8195 :     myLaneTimeLine = laneTimeLine;
     430         8195 : }
     431              : 
     432              : 
     433              : void
     434         9036 : MSVehicle::Influencer::adaptLaneTimeLine(int indexShift) {
     435        19270 :     for (auto& item : myLaneTimeLine) {
     436        10234 :         item.second += indexShift;
     437              :     }
     438         9036 : }
     439              : 
     440              : 
     441              : void
     442         1487 : MSVehicle::Influencer::setSublaneChange(double latDist) {
     443         1487 :     myLatDist = latDist;
     444         1487 : }
     445              : 
     446              : int
     447           74 : MSVehicle::Influencer::getSpeedMode() const {
     448           74 :     return (1 * myConsiderSafeVelocity +
     449           74 :             2 * myConsiderMaxAcceleration +
     450           74 :             4 * myConsiderMaxDeceleration +
     451           74 :             8 * myRespectJunctionPriority +
     452           74 :             16 * myEmergencyBrakeRedLight +
     453           74 :             32 * !myRespectJunctionLeaderPriority + // inverted!
     454           74 :             64 * !myConsiderSpeedLimit // inverted!
     455           74 :            );
     456              : }
     457              : 
     458              : 
     459              : int
     460         1476 : MSVehicle::Influencer::getLaneChangeMode() const {
     461         1476 :     return (1 * myStrategicLC +
     462         1476 :             4 * myCooperativeLC +
     463         1476 :             16 * mySpeedGainLC +
     464         1476 :             64 * myRightDriveLC +
     465         1476 :             256 * myTraciLaneChangePriority +
     466         1476 :             1024 * mySublaneLC);
     467              : }
     468              : 
     469              : SUMOTime
     470           71 : MSVehicle::Influencer::getLaneTimeLineDuration() {
     471              :     SUMOTime duration = -1;
     472          213 :     for (std::vector<std::pair<SUMOTime, int>>::iterator i = myLaneTimeLine.begin(); i != myLaneTimeLine.end(); ++i) {
     473          142 :         if (duration < 0) {
     474           71 :             duration = i->first;
     475              :         } else {
     476           71 :             duration -=  i->first;
     477              :         }
     478              :     }
     479           71 :     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       993643 : MSVehicle::Influencer::influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax) {
     494              :     // remove leading commands which are no longer valid
     495       994975 :     while (mySpeedTimeLine.size() == 1 || (mySpeedTimeLine.size() > 1 && currentTime > mySpeedTimeLine[1].first)) {
     496              :         mySpeedTimeLine.erase(mySpeedTimeLine.begin());
     497              :     }
     498              : 
     499       993643 :     if (!(mySpeedTimeLine.size() < 2 || currentTime < mySpeedTimeLine[0].first)) {
     500              :         // Speed advice is active -> compute new speed according to speedTimeLine
     501        54372 :         if (!mySpeedAdaptationStarted) {
     502            0 :             mySpeedTimeLine[0].second = speed;
     503            0 :             mySpeedAdaptationStarted = true;
     504              :         }
     505        54372 :         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       108405 :         const double td = MIN2(1.0, STEPS2TIME(currentTime - mySpeedTimeLine[0].first) / MAX2(TS, STEPS2TIME(mySpeedTimeLine[1].first - mySpeedTimeLine[0].first)));
     507              : 
     508        54372 :         speed = mySpeedTimeLine[0].second - (mySpeedTimeLine[0].second - mySpeedTimeLine[1].second) * td;
     509        54372 :         if (myConsiderSafeVelocity) {
     510              :             speed = MIN2(speed, vSafe);
     511              :         }
     512        54372 :         if (myConsiderMaxAcceleration) {
     513              :             speed = MIN2(speed, vMax);
     514              :         }
     515        54372 :         if (myConsiderMaxDeceleration) {
     516              :             speed = MAX2(speed, vMin);
     517              :         }
     518              :     }
     519       993643 :     return speed;
     520              : }
     521              : 
     522              : double
     523       493531 : 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       493531 :     if (myGapControlState != nullptr && myGapControlState->active) {
     535              :         // Determine leader and the speed that would be chosen by the gap controller
     536         7778 :         const double currentSpeed = veh->getSpeed();
     537         7778 :         const MSVehicle* msVeh = dynamic_cast<const MSVehicle*>(veh);
     538              :         assert(msVeh != nullptr);
     539         7778 :         const double desiredTargetTimeSpacing = myGapControlState->tauTarget * currentSpeed;
     540              :         std::pair<const MSVehicle*, double> leaderInfo;
     541         7778 :         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          438 :             double dist = msVeh->getDistanceToPosition(leader->getPositionOnLane(), leader->getLane()) - leader->getLength();
     554          438 :             if (dist > 100000) {
     555              :                 // Reference vehicle was not found downstream the ego's route
     556              :                 // Maybe, it is behind the ego vehicle
     557           42 :                 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          438 :             leaderInfo = std::make_pair(leader, dist - msVeh->getVehicleType().getMinGap());
     570              :         }
     571         7778 :         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         7778 :         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         7778 :             myGapControlState->prevLeader = leaderInfo.first;
     594              : 
     595              :             // Calculate desired following speed assuming the alternative headway time
     596         7778 :             MSCFModel* cfm = (MSCFModel*) & (msVeh->getVehicleType().getCarFollowModel());
     597         7778 :             const double origTau = cfm->getHeadwayTime();
     598         7778 :             cfm->setHeadwayTime(myGapControlState->tauCurrent);
     599         7778 :             gapControlSpeed = MIN2(gapControlSpeed,
     600         7778 :                                    cfm->followSpeed(msVeh, currentSpeed, fakeDist, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first));
     601         7778 :             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         7778 :             if (myGapControlState->maxDecel > 0) {
     612         2568 :                 gapControlSpeed = MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
     613              :             }
     614              :         }
     615              : 
     616              :         // Update gap controller
     617              :         // Check (1) if the gap control has established the desired gap,
     618              :         // and (2) if it has maintained active for the given duration afterwards
     619         7778 :         if (myGapControlState->lastUpdate < currentTime) {
     620              : #ifdef DEBUG_TRACI
     621              :             if DEBUG_COND2(veh) {
     622              :                 std::cout << " Updating GapControlState." << std::endl;
     623              :             }
     624              : #endif
     625         7778 :             if (myGapControlState->tauCurrent == myGapControlState->tauTarget && myGapControlState->addGapCurrent == myGapControlState->addGapTarget) {
     626         2992 :                 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         4180 :                     myGapControlState->gapAttained = leaderInfo.first == nullptr ||  leaderInfo.second > MAX2(desiredTargetTimeSpacing, myGapControlState->addGapTarget) - POSITION_EPS;
     629              : #ifdef DEBUG_TRACI
     630              :                     if DEBUG_COND2(veh) {
     631              :                         if (myGapControlState->gapAttained) {
     632              :                             std::cout << "   Target gap was established." << std::endl;
     633              :                         }
     634              :                     }
     635              : #endif
     636              :                 } else {
     637              :                     // Count down remaining time if desired gap was established
     638          924 :                     myGapControlState->remainingDuration -= TS;
     639              : #ifdef DEBUG_TRACI
     640              :                     if DEBUG_COND2(veh) {
     641              :                         std::cout << "   Gap control remaining duration: " << myGapControlState->remainingDuration << std::endl;
     642              :                     }
     643              : #endif
     644          924 :                     if (myGapControlState->remainingDuration <= 0) {
     645              : #ifdef DEBUG_TRACI
     646              :                         if DEBUG_COND2(veh) {
     647              :                             std::cout << "   Gap control duration expired, deactivating control." << std::endl;
     648              :                         }
     649              : #endif
     650              :                         // switch off gap control
     651           44 :                         myGapControlState->deactivate();
     652              :                     }
     653              :                 }
     654              :             } else {
     655              :                 // Adjust current headway values
     656         4786 :                 myGapControlState->tauCurrent = MIN2(myGapControlState->tauCurrent + myGapControlState->timeHeadwayIncrement, myGapControlState->tauTarget);
     657         5168 :                 myGapControlState->addGapCurrent = MIN2(myGapControlState->addGapCurrent + myGapControlState->spaceHeadwayIncrement, myGapControlState->addGapTarget);
     658              :             }
     659              :         }
     660         7778 :         if (myConsiderSafeVelocity) {
     661              :             gapControlSpeed = MIN2(gapControlSpeed, vSafe);
     662              :         }
     663         7778 :         if (myConsiderMaxAcceleration) {
     664              :             gapControlSpeed = MIN2(gapControlSpeed, vMax);
     665              :         }
     666         7778 :         if (myConsiderMaxDeceleration) {
     667              :             gapControlSpeed = MAX2(gapControlSpeed, vMin);
     668              :         }
     669              :         return MIN2(speed, gapControlSpeed);
     670              :     } else {
     671              :         return speed;
     672              :     }
     673              : }
     674              : 
     675              : double
     676         7086 : MSVehicle::Influencer::getOriginalSpeed() const {
     677         7086 :     return myOriginalSpeed;
     678              : }
     679              : 
     680              : void
     681       500112 : MSVehicle::Influencer::setOriginalSpeed(double speed) {
     682       500112 :     myOriginalSpeed = speed;
     683       500112 : }
     684              : 
     685              : 
     686              : int
     687      2815542 : MSVehicle::Influencer::influenceChangeDecision(const SUMOTime currentTime, const MSEdge& currentEdge, const int currentLaneIndex, int state) {
     688              :     // remove leading commands which are no longer valid
     689      2815844 :     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      2815542 :     if (myLaneTimeLine.size() >= 2 && currentTime >= myLaneTimeLine[0].first) {
     695       177680 :         const int destinationLaneIndex = myLaneTimeLine[1].second;
     696       177680 :         if (destinationLaneIndex < (int)currentEdge.getLanes().size()) {
     697       177319 :             if (currentLaneIndex > destinationLaneIndex) {
     698              :                 changeRequest = REQUEST_RIGHT;
     699       176236 :             } else if (currentLaneIndex < destinationLaneIndex) {
     700              :                 changeRequest = REQUEST_LEFT;
     701              :             } else {
     702              :                 changeRequest = REQUEST_HOLD;
     703              :             }
     704          361 :         } else if (currentEdge.getLanes().back()->getOpposite() != nullptr) { // change to opposite direction driving
     705              :             changeRequest = REQUEST_LEFT;
     706          361 :             state = state | LCA_TRACI;
     707              :         }
     708              :     }
     709              :     // check whether the current reason shall be canceled / overridden
     710      2815542 :     if ((state & LCA_WANTS_LANECHANGE_OR_STAY) != 0) {
     711              :         // flags for the current reason
     712              :         LaneChangeMode mode = LC_NEVER;
     713      1589592 :         if ((state & LCA_TRACI) != 0 && myLatDist != 0) {
     714              :             // security checks
     715         2825 :             if ((myTraciLaneChangePriority == LCP_ALWAYS)
     716          670 :                     || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     717         2685 :                 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     718              :             }
     719              :             // continue sublane change manoeuvre
     720         2825 :             return state;
     721      1586767 :         } else if ((state & LCA_STRATEGIC) != 0) {
     722       480032 :             mode = myStrategicLC;
     723      1106735 :         } else if ((state & LCA_COOPERATIVE) != 0) {
     724          172 :             mode = myCooperativeLC;
     725      1106563 :         } else if ((state & LCA_SPEEDGAIN) != 0) {
     726        42364 :             mode = mySpeedGainLC;
     727      1064199 :         } else if ((state & LCA_KEEPRIGHT) != 0) {
     728         5828 :             mode = myRightDriveLC;
     729      1058371 :         } else if ((state & LCA_SUBLANE) != 0) {
     730      1058369 :             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      1586765 :         if (mode == LC_NEVER) {
     737              :             // cancel all lcModel requests
     738              :             state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     739        44249 :             state &= ~LCA_URGENT;
     740        44249 :             if (changeRequest == REQUEST_NONE) {
     741              :                 // also remove all reasons except TRACI
     742        43685 :                 state &= ~LCA_CHANGE_REASONS | LCA_TRACI;
     743              :             }
     744      1542518 :         } else if (mode == LC_NOCONFLICT && changeRequest != REQUEST_NONE) {
     745         6869 :             if (
     746         6869 :                 ((state & LCA_LEFT) != 0 && changeRequest != REQUEST_LEFT) ||
     747         6619 :                 ((state & LCA_RIGHT) != 0 && changeRequest != REQUEST_RIGHT) ||
     748         6098 :                 ((state & LCA_STAY) != 0 && changeRequest != REQUEST_HOLD)) {
     749              :                 // cancel conflicting lcModel request
     750              :                 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
     751          935 :                 state &= ~LCA_URGENT;
     752              :             }
     753      1535649 :         } else if (mode == LC_ALWAYS) {
     754              :             // ignore any TraCI requests
     755              :             return state;
     756              :         }
     757              :     }
     758              :     // apply traci requests
     759      2806293 :     if (changeRequest == REQUEST_NONE) {
     760      2635493 :         return state;
     761              :     } else {
     762       177214 :         state |= LCA_TRACI;
     763              :         // security checks
     764       177214 :         if ((myTraciLaneChangePriority == LCP_ALWAYS)
     765       174945 :                 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
     766         2761 :             state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
     767              :         }
     768       177214 :         if (changeRequest != REQUEST_HOLD && myTraciLaneChangePriority != LCP_OPPORTUNISTIC) {
     769         2531 :             state |= LCA_URGENT;
     770              :         }
     771         2560 :         switch (changeRequest) {
     772              :             case REQUEST_HOLD:
     773       174654 :                 return state | LCA_STAY;
     774         1577 :             case REQUEST_LEFT:
     775         1577 :                 return state | LCA_LEFT;
     776          983 :             case REQUEST_RIGHT:
     777          983 :                 return state | LCA_RIGHT;
     778              :             default:
     779              :                 throw ProcessError(TL("should not happen"));
     780              :         }
     781              :     }
     782              : }
     783              : 
     784              : 
     785              : double
     786          442 : MSVehicle::Influencer::changeRequestRemainingSeconds(const SUMOTime currentTime) const {
     787              :     assert(myLaneTimeLine.size() >= 2);
     788              :     assert(currentTime >= myLaneTimeLine[0].first);
     789          442 :     return STEPS2TIME(myLaneTimeLine[1].first - currentTime);
     790              : }
     791              : 
     792              : 
     793              : void
     794         5063 : MSVehicle::Influencer::setSpeedMode(int speedMode) {
     795         5063 :     myConsiderSafeVelocity = ((speedMode & 1) != 0);
     796         5063 :     myConsiderMaxAcceleration = ((speedMode & 2) != 0);
     797         5063 :     myConsiderMaxDeceleration = ((speedMode & 4) != 0);
     798         5063 :     myRespectJunctionPriority = ((speedMode & 8) != 0);
     799         5063 :     myEmergencyBrakeRedLight = ((speedMode & 16) != 0);
     800         5063 :     myRespectJunctionLeaderPriority = ((speedMode & 32) == 0); // inverted!
     801         5063 :     myConsiderSpeedLimit = ((speedMode & 64) == 0); // inverted!
     802         5063 : }
     803              : 
     804              : 
     805              : void
     806        18513 : MSVehicle::Influencer::setLaneChangeMode(int value) {
     807        18513 :     myStrategicLC = (LaneChangeMode)(value & (1 + 2));
     808        18513 :     myCooperativeLC = (LaneChangeMode)((value & (4 + 8)) >> 2);
     809        18513 :     mySpeedGainLC = (LaneChangeMode)((value & (16 + 32)) >> 4);
     810        18513 :     myRightDriveLC = (LaneChangeMode)((value & (64 + 128)) >> 6);
     811        18513 :     myTraciLaneChangePriority = (TraciLaneChangePriority)((value & (256 + 512)) >> 8);
     812        18513 :     mySublaneLC = (LaneChangeMode)((value & (1024 + 2048)) >> 10);
     813        18513 : }
     814              : 
     815              : 
     816              : void
     817         7800 : MSVehicle::Influencer::setRemoteControlled(Position xyPos, MSLane* l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector& route, SUMOTime t) {
     818         7800 :     myRemoteXYPos = xyPos;
     819         7800 :     myRemoteLane = l;
     820         7800 :     myRemotePos = pos;
     821         7800 :     myRemotePosLat = posLat;
     822         7800 :     myRemoteAngle = angle;
     823         7800 :     myRemoteEdgeOffset = edgeOffset;
     824         7800 :     myRemoteRoute = route;
     825         7800 :     myLastRemoteAccess = t;
     826         7800 : }
     827              : 
     828              : 
     829              : bool
     830      1023799 : MSVehicle::Influencer::isRemoteControlled() const {
     831      1023799 :     return myLastRemoteAccess == MSNet::getInstance()->getCurrentTimeStep();
     832              : }
     833              : 
     834              : 
     835              : bool
     836       488103 : MSVehicle::Influencer::isRemoteAffected(SUMOTime t) const {
     837       488103 :     return myLastRemoteAccess >= t - TIME2STEPS(10);
     838              : }
     839              : 
     840              : 
     841              : void
     842       493531 : MSVehicle::Influencer::updateRemoteControlRoute(MSVehicle* v) {
     843       493531 :     if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
     844              :         // only replace route at this time if the vehicle is moving with the flow
     845           62 :         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           10 :             v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     851           10 :             v->updateBestLanes();
     852              :         }
     853              :     }
     854       493531 : }
     855              : 
     856              : 
     857              : void
     858         7775 : MSVehicle::Influencer::postProcessRemoteControl(MSVehicle* v) {
     859         7775 :     const bool wasOnRoad = v->isOnRoad();
     860         7775 :     const bool withinLane = myRemoteLane != nullptr && fabs(myRemotePosLat) < 0.5 * (myRemoteLane->getWidth() + v->getVehicleType().getWidth());
     861         7775 :     const bool keepLane = wasOnRoad && v->getLane() == myRemoteLane;
     862         7775 :     if (v->isOnRoad() && !(keepLane && withinLane)) {
     863          150 :         if (myRemoteLane != nullptr && &v->getLane()->getEdge() == &myRemoteLane->getEdge()) {
     864              :             // correct odometer which gets incremented via onRemovalFromNet->leaveLane
     865           71 :             v->myOdometer -= v->getLane()->getLength();
     866              :         }
     867          150 :         v->onRemovalFromNet(MSMoveReminder::NOTIFICATION_TELEPORT);
     868          150 :         v->getMutableLane()->removeVehicle(v, MSMoveReminder::NOTIFICATION_TELEPORT, false);
     869              :     }
     870         7775 :     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           67 :         const_cast<SUMOVehicleParameter&>(v->getParameter()).stops.clear();
     883          134 :         v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
     884              :         myRemoteRoute.clear();
     885              :     }
     886         7775 :     v->myCurrEdge = v->getRoute().begin() + myRemoteEdgeOffset;
     887         7775 :     if (myRemoteLane != nullptr && myRemotePos > myRemoteLane->getLength()) {
     888            0 :         myRemotePos = myRemoteLane->getLength();
     889              :     }
     890         7775 :     if (myRemoteLane != nullptr && withinLane) {
     891         7593 :         if (keepLane) {
     892              :             // TODO this handles only the case when the new vehicle is completely on the edge
     893         7415 :             const bool needFurtherUpdate = v->myState.myPos < v->getVehicleType().getLength() && myRemotePos >= v->getVehicleType().getLength();
     894         7415 :             v->myState.myPos = myRemotePos;
     895         7415 :             v->myState.myPosLat = myRemotePosLat;
     896         7415 :             if (needFurtherUpdate) {
     897            5 :                 v->myState.myBackPos = v->updateFurtherLanes(v->myFurtherLanes, v->myFurtherLanesPosLat, std::vector<MSLane*>());
     898              :             }
     899              :         } else {
     900          178 :             MSMoveReminder::Notification notify = v->getDeparture() == NOT_YET_DEPARTED
     901          178 :                                                   ? MSMoveReminder::NOTIFICATION_DEPARTED
     902              :                                                   : MSMoveReminder::NOTIFICATION_TELEPORT_ARRIVED;
     903          178 :             if (!v->isOnRoad()) {
     904          178 :                 MSVehicleTransfer::getInstance()->remove(v);  // TODO may need optimization, this is linear in the number of vehicles in transfer
     905              :             }
     906          178 :             myRemoteLane->forceVehicleInsertion(v, myRemotePos, notify, myRemotePosLat);
     907          178 :             v->updateBestLanes();
     908              :         }
     909         7593 :         if (!wasOnRoad) {
     910           65 :             v->drawOutsideNetwork(false);
     911              :         }
     912              :         //std::cout << "on road network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << " pos=" << myRemotePos << " posLat=" << myRemotePosLat << "\n";
     913         7593 :         myRemoteLane->requireCollisionCheck();
     914              :     } else {
     915          182 :         if (v->getDeparture() == NOT_YET_DEPARTED) {
     916            5 :             v->onDepart();
     917              :         }
     918          182 :         v->drawOutsideNetwork(true);
     919              :         // see updateState
     920          182 :         double vNext = v->processTraCISpeedControl(
     921          182 :                            v->getMaxSpeed(), v->getSpeed());
     922          182 :         v->setBrakingSignals(vNext);
     923          182 :         v->myState.myPreviousSpeed = v->getSpeed();
     924          182 :         v->myAcceleration = SPEED2ACCEL(vNext - v->getSpeed());
     925          182 :         v->myState.mySpeed = vNext;
     926          182 :         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         7775 :     v->setRemoteState(myRemoteXYPos);
     931         7775 :     v->setAngle(GeomHelper::fromNaviDegree(myRemoteAngle));
     932         7775 : }
     933              : 
     934              : 
     935              : double
     936         7752 : MSVehicle::Influencer::implicitSpeedRemote(const MSVehicle* veh, double oldSpeed) {
     937         7752 :     if (veh->getPosition() == Position::INVALID) {
     938           10 :         return oldSpeed;
     939              :     }
     940         7742 :     double dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
     941         7742 :     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         7600 :         const double distAlongRoute = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     947         7600 :         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         7742 :     const double minSpeed = myConsiderMaxDeceleration ?
     953         5034 :                             veh->getCarFollowModel().minNextSpeedEmergency(oldSpeed, veh) : 0;
     954         7742 :     const double maxSpeed = (myRemoteLane != nullptr
     955         7742 :                              ? myRemoteLane->getVehicleMaxSpeed(veh)
     956          142 :                              : (veh->getLane() != nullptr
     957          142 :                                 ? veh->getLane()->getVehicleMaxSpeed(veh)
     958            5 :                                 : veh->getMaxSpeed()));
     959         7742 :     return MIN2(maxSpeed, MAX2(minSpeed, DIST2SPEED(dist)));
     960              : }
     961              : 
     962              : 
     963              : double
     964         7580 : MSVehicle::Influencer::implicitDeltaPosRemote(const MSVehicle* veh) {
     965              :     double dist = 0;
     966         7580 :     if (myRemoteLane == nullptr) {
     967            6 :         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         7574 :         dist = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
     975              :     }
     976         7580 :     if (dist == std::numeric_limits<double>::max()) {
     977              :         return 0;
     978              :     } else {
     979         7339 :         if (DIST2SPEED(dist) > veh->getMaxSpeed() * 1.1) {
     980           48 :             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           16 :             dist = MIN2(dist, SPEED2DIST(veh->getMaxSpeed() * 2));
     984              :         }
     985         7339 :         return dist;
     986              :     }
     987              : }
     988              : 
     989              : 
     990              : /* -------------------------------------------------------------------------
     991              :  * MSVehicle-methods
     992              :  * ----------------------------------------------------------------------- */
     993      4586388 : MSVehicle::MSVehicle(SUMOVehicleParameter* pars, ConstMSRoutePtr route,
     994      4586388 :                      MSVehicleType* type, const double speedFactor) :
     995              :     MSBaseVehicle(pars, route, type, speedFactor),
     996      4586388 :     myWaitingTime(0),
     997      4586388 :     myWaitingTimeCollector(),
     998      4586388 :     myTimeLoss(0),
     999      4586388 :     myState(0, 0, 0, 0, 0),
    1000      4586388 :     myDriverState(nullptr),
    1001      4586388 :     myActionStep(true),
    1002      4586388 :     myLastActionTime(0),
    1003      4586388 :     myLane(nullptr),
    1004      4586388 :     myLaneChangeModel(nullptr),
    1005      4586388 :     myLastBestLanesEdge(nullptr),
    1006      4586388 :     myLastBestLanesInternalLane(nullptr),
    1007      4586388 :     myAcceleration(0),
    1008              :     myNextTurn(0., nullptr),
    1009      4586388 :     mySignals(0),
    1010      4586388 :     myAmOnNet(false),
    1011      4586388 :     myAmIdling(false),
    1012      4586388 :     myHaveToWaitOnNextLink(false),
    1013      4586388 :     myAngle(0),
    1014      4586388 :     myStopDist(std::numeric_limits<double>::max()),
    1015      4586388 :     myCollisionImmunity(-1),
    1016      4586388 :     myCachedPosition(Position::INVALID),
    1017      4586388 :     myJunctionEntryTime(SUMOTime_MAX),
    1018      4586388 :     myJunctionEntryTimeNeverYield(SUMOTime_MAX),
    1019      4586388 :     myJunctionConflictEntryTime(SUMOTime_MAX),
    1020      4586388 :     myTimeSinceStartup(TIME2STEPS(3600 * 24)),
    1021      4586388 :     myHaveStoppedFor(nullptr),
    1022     13759164 :     myInfluencer(nullptr) {
    1023      4586388 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    1024      4586388 :     myNextDriveItem = myLFLinkLanes.begin();
    1025      4586388 : }
    1026              : 
    1027              : 
    1028      8673656 : MSVehicle::~MSVehicle() {
    1029      4586300 :     cleanupFurtherLanes();
    1030      4586300 :     delete myLaneChangeModel;
    1031      4586300 :     if (myType->isVehicleSpecific()) {
    1032          309 :         MSNet::getInstance()->getVehicleControl().removeVType(myType);
    1033              :     }
    1034      4586300 :     delete myInfluencer;
    1035      4586300 :     delete myCFVariables;
    1036     13259956 : }
    1037              : 
    1038              : 
    1039              : void
    1040      4586862 : MSVehicle::cleanupFurtherLanes() {
    1041      4589144 :     for (MSLane* further : myFurtherLanes) {
    1042         2282 :         further->resetPartialOccupation(this);
    1043         2282 :         if (further->getBidiLane() != nullptr
    1044         2282 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    1045            0 :             further->getBidiLane()->resetPartialOccupation(this);
    1046              :         }
    1047              :     }
    1048      4586862 :     if (myLaneChangeModel != nullptr) {
    1049      4586828 :         removeApproachingInformation(myLFLinkLanes);
    1050      4586828 :         myLaneChangeModel->cleanupShadowLane();
    1051      4586828 :         myLaneChangeModel->cleanupTargetLane();
    1052              :         // still needed when calling resetPartialOccupation (getShadowLane) and when removing
    1053              :         // approach information from parallel links
    1054              :     }
    1055              :     myFurtherLanes.clear();
    1056              :     myFurtherLanesPosLat.clear();
    1057      4586862 : }
    1058              : 
    1059              : 
    1060              : void
    1061      3455634 : MSVehicle::onRemovalFromNet(const MSMoveReminder::Notification reason) {
    1062              : #ifdef DEBUG_ACTIONSTEPS
    1063              :     if (DEBUG_COND) {
    1064              :         std::cout << SIMTIME << " Removing vehicle '" << getID() << "' (reason: " << toString(reason) << ")" << std::endl;
    1065              :     }
    1066              : #endif
    1067      3455634 :     MSVehicleTransfer::getInstance()->remove(this);
    1068      3455634 :     removeApproachingInformation(myLFLinkLanes);
    1069      3455634 :     leaveLane(reason);
    1070      3455634 :     if (reason == MSMoveReminder::NOTIFICATION_VAPORIZED_COLLISION) {
    1071          562 :         cleanupFurtherLanes();
    1072              :     }
    1073      3455634 : }
    1074              : 
    1075              : 
    1076              : void
    1077      4586388 : MSVehicle::initDevices() {
    1078      4586388 :     MSBaseVehicle::initDevices();
    1079      4586376 :     myLaneChangeModel = MSAbstractLaneChangeModel::build(myType->getLaneChangeModel(), *this);
    1080      4586354 :     myDriverState = static_cast<MSDevice_DriverState*>(getDevice(typeid(MSDevice_DriverState)));
    1081      4586354 :     myFrictionDevice = static_cast<MSDevice_Friction*>(getDevice(typeid(MSDevice_Friction)));
    1082      4586354 : }
    1083              : 
    1084              : 
    1085              : // ------------ interaction with the route
    1086              : bool
    1087   6972191833 : MSVehicle::hasValidRouteStart(std::string& msg) {
    1088              :     // note: not a const method because getDepartLane may call updateBestLanes
    1089   6972191833 :     if (!(*myCurrEdge)->isTazConnector()) {
    1090   6971761501 :         if (myParameter->departLaneProcedure == DepartLaneDefinition::GIVEN) {
    1091     50427626 :             if ((*myCurrEdge)->getDepartLane(*this) == nullptr) {
    1092          122 :                 msg = "Invalid departlane definition for vehicle '" + getID() + "'.";
    1093           61 :                 if (myParameter->departLane >= (int)(*myCurrEdge)->getLanes().size()) {
    1094           11 :                     myRouteValidity |= ROUTE_START_INVALID_LANE;
    1095              :                 } else {
    1096           50 :                     myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
    1097              :                 }
    1098           61 :                 return false;
    1099              :             }
    1100              :         } else {
    1101   6921333875 :             if ((*myCurrEdge)->allowedLanes(getVClass(), ignoreTransientPermissions()) == nullptr) {
    1102          146 :                 msg = "Vehicle '" + getID() + "' is not allowed to depart on any lane of edge '" + (*myCurrEdge)->getID() + "'.";
    1103           73 :                 myRouteValidity |= ROUTE_START_INVALID_PERMISSIONS;
    1104           73 :                 return false;
    1105              :             }
    1106              :         }
    1107   6971761367 :         if (myParameter->departSpeedProcedure == DepartSpeedDefinition::GIVEN && myParameter->departSpeed > myType->getMaxSpeed() + SPEED_EPS) {
    1108           38 :             msg = "Departure speed for vehicle '" + getID() + "' is too high for the vehicle type '" + myType->getID() + "'.";
    1109           19 :             myRouteValidity |= ROUTE_START_INVALID_LANE;
    1110           19 :             return false;
    1111              :         }
    1112              :     }
    1113   6972191680 :     myRouteValidity &= ~(ROUTE_START_INVALID_LANE | ROUTE_START_INVALID_PERMISSIONS);
    1114   6972191680 :     return true;
    1115              : }
    1116              : 
    1117              : 
    1118              : bool
    1119    701415126 : MSVehicle::hasArrived() const {
    1120    701415126 :     return hasArrivedInternal(false);
    1121              : }
    1122              : 
    1123              : 
    1124              : bool
    1125   1411349891 : MSVehicle::hasArrivedInternal(bool oppositeTransformed) const {
    1126   2286465187 :     return ((myCurrEdge == myRoute->end() - 1 || (myParameter->arrivalEdge >= 0 && getRoutePosition() >= myParameter->arrivalEdge))
    1127    536283684 :             && (myStops.empty() || myStops.front().edge != myCurrEdge || myStops.front().getSpeed() > 0)
    1128   1004385036 :             && ((myLaneChangeModel->isOpposite() && !oppositeTransformed) ? myLane->getLength() - myState.myPos : myState.myPos) > MIN2(myLane->getLength(), myArrivalPos) - POSITION_EPS
    1129   1423311259 :             && !isRemoteControlled());
    1130              : }
    1131              : 
    1132              : 
    1133              : bool
    1134      1704317 : MSVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
    1135      3408634 :     if (MSBaseVehicle::replaceRoute(newRoute, info, onInit, offset, addRouteStops, removeStops, msgReturn)) {
    1136              :         // update best lanes (after stops were added)
    1137      1704299 :         myLastBestLanesEdge = nullptr;
    1138      1704299 :         myLastBestLanesInternalLane = nullptr;
    1139      1704299 :         updateBestLanes(true, onInit ? (*myCurrEdge)->getLanes().front() : 0);
    1140              :         assert(!removeStops || haveValidStopEdges());
    1141      1704299 :         if (myStops.size() == 0) {
    1142      1671533 :             myStopDist = std::numeric_limits<double>::max();
    1143              :         }
    1144      1704299 :         return true;
    1145              :     }
    1146              :     return false;
    1147              : }
    1148              : 
    1149              : 
    1150              : // ------------ Interaction with move reminders
    1151              : void
    1152    687199929 : MSVehicle::workOnMoveReminders(double oldPos, double newPos, double newSpeed) {
    1153              :     // This erasure-idiom works for all stl-sequence-containers
    1154              :     // See Meyers: Effective STL, Item 9
    1155   1818020867 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    1156              :         // XXX: calling notifyMove with newSpeed seems not the best choice. For the ballistic update, the average speed is calculated and used
    1157              :         //      although a higher order quadrature-formula might be more adequate.
    1158              :         //      For the euler case (where the speed is considered constant for each time step) it is conceivable that
    1159              :         //      the current calculations may lead to systematic errors for large time steps (compared to reality). Refs. #2579
    1160   2261641876 :         if (!rem->first->notifyMove(*this, oldPos + rem->second, newPos + rem->second, MAX2(0., newSpeed))) {
    1161              : #ifdef _DEBUG
    1162              :             if (myTraceMoveReminders) {
    1163              :                 traceMoveReminder("notifyMove", rem->first, rem->second, false);
    1164              :             }
    1165              : #endif
    1166              :             rem = myMoveReminders.erase(rem);
    1167              :         } else {
    1168              : #ifdef _DEBUG
    1169              :             if (myTraceMoveReminders) {
    1170              :                 traceMoveReminder("notifyMove", rem->first, rem->second, true);
    1171              :             }
    1172              : #endif
    1173              :             ++rem;
    1174              :         }
    1175              :     }
    1176    687199929 :     if (myEnergyParams != nullptr) {
    1177              :         // TODO make the vehicle energy params a derived class which is a move reminder
    1178    129234770 :         myEnergyParams->setDynamicValues(isStopped() ? getNextStop().duration : -1, isParking(), getWaitingTime(), getAngle());
    1179              :     }
    1180    687199929 : }
    1181              : 
    1182              : 
    1183              : void
    1184       106321 : MSVehicle::workOnIdleReminders() {
    1185       106321 :     updateWaitingTime(0.);   // cf issue 2233
    1186              : 
    1187              :     // vehicle move reminders
    1188       132071 :     for (const auto& rem : myMoveReminders) {
    1189        25750 :         rem.first->notifyIdle(*this);
    1190              :     }
    1191              : 
    1192              :     // lane move reminders - for aggregated values
    1193       242827 :     for (MSMoveReminder* rem : getLane()->getMoveReminders()) {
    1194       136506 :         rem->notifyIdle(*this);
    1195              :     }
    1196       106321 : }
    1197              : 
    1198              : // XXX: consider renaming...
    1199              : void
    1200     19767725 : MSVehicle::adaptLaneEntering2MoveReminder(const MSLane& enteredLane) {
    1201              :     // save the old work reminders, patching the position information
    1202              :     //  add the information about the new offset to the old lane reminders
    1203     19767725 :     const double oldLaneLength = myLane->getLength();
    1204     55894153 :     for (auto& rem : myMoveReminders) {
    1205     36126428 :         rem.second += oldLaneLength;
    1206              : #ifdef _DEBUG
    1207              : //        if (rem->first==0) std::cout << "Null reminder (?!)" << std::endl;
    1208              : //        std::cout << "Adapted MoveReminder on lane " << ((rem->first->getLane()==0) ? "NULL" : rem->first->getLane()->getID()) <<" position to " << rem->second << std::endl;
    1209              :         if (myTraceMoveReminders) {
    1210              :             traceMoveReminder("adaptedPos", rem.first, rem.second, true);
    1211              :         }
    1212              : #endif
    1213              :     }
    1214     34136441 :     for (MSMoveReminder* const rem : enteredLane.getMoveReminders()) {
    1215     14368716 :         addReminder(rem);
    1216              :     }
    1217     19767725 : }
    1218              : 
    1219              : 
    1220              : // ------------ Other getter methods
    1221              : double
    1222    157608303 : MSVehicle::getSlope() const {
    1223    157608303 :     if (isParking() && getStops().begin()->parkingarea != nullptr) {
    1224         3901 :         return getStops().begin()->parkingarea->getVehicleSlope(*this);
    1225              :     }
    1226    157604402 :     if (myLane == nullptr) {
    1227              :         return 0;
    1228              :     }
    1229    157604402 :     const double posLat = myState.myPosLat; // @todo get rid of the '-'
    1230    157604402 :     Position p1 = getPosition();
    1231    157604402 :     Position p2 = getBackPosition();
    1232              :     if (p2 == Position::INVALID) {
    1233              :         // Handle special case of vehicle's back reaching out of the network
    1234            6 :         if (myFurtherLanes.size() > 0) {
    1235            6 :             p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
    1236              :             if (p2 == Position::INVALID) {
    1237              :                 // unsuitable lane geometry
    1238            0 :                 p2 = myLane->geometryPositionAtOffset(0, posLat);
    1239              :             }
    1240              :         } else {
    1241            0 :             p2 = myLane->geometryPositionAtOffset(0, posLat);
    1242              :         }
    1243              :     }
    1244    157604402 :     return (p1 != p2 ? RAD2DEG(p2.slopeTo2D(p1)) : myLane->getShape().slopeDegreeAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1245              : }
    1246              : 
    1247              : 
    1248              : Position
    1249    911079915 : MSVehicle::getPosition(const double offset) const {
    1250    911079915 :     if (myLane == nullptr) {
    1251              :         // when called in the context of GUI-Drawing, the simulation step is already incremented
    1252          174 :         if (myInfluencer != nullptr && myInfluencer->isRemoteAffected(MSNet::getInstance()->getCurrentTimeStep())) {
    1253           50 :             return myCachedPosition;
    1254              :         } else {
    1255          124 :             return Position::INVALID;
    1256              :         }
    1257              :     }
    1258    911079741 :     if (isParking()) {
    1259      4067170 :         if (myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() > getNextStopParameter()->started) {
    1260          153 :             return myCachedPosition;
    1261              :         }
    1262      4067017 :         if (myStops.begin()->parkingarea != nullptr) {
    1263        22395 :             return myStops.begin()->parkingarea->getVehiclePosition(*this);
    1264              :         } else {
    1265              :             // position beside the road
    1266      4044622 :             PositionVector shp = myLane->getEdge().getLanes()[0]->getShape();
    1267      8089124 :             shp.move2side(SUMO_const_laneWidth * (MSGlobals::gLefthand ? -1 : 1));
    1268      4044622 :             return shp.positionAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane() + offset));
    1269      4044622 :         }
    1270              :     }
    1271    907012571 :     const bool changingLanes = myLaneChangeModel->isChangingLanes();
    1272   1803874597 :     const double posLat = (MSGlobals::gLefthand ? 1 : -1) * getLateralPositionOnLane();
    1273    907012571 :     if (offset == 0. && !changingLanes) {
    1274              :         if (myCachedPosition == Position::INVALID) {
    1275    691616652 :             myCachedPosition = validatePosition(myLane->geometryPositionAtOffset(myState.myPos, posLat));
    1276    691616652 :             if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1277        58610 :                 interpolateLateralZ(myCachedPosition, myState.myPos, posLat);
    1278              :             }
    1279              :         }
    1280    900419811 :         return myCachedPosition;
    1281              :     }
    1282      6592760 :     Position result = validatePosition(myLane->geometryPositionAtOffset(getPositionOnLane() + offset, posLat), offset);
    1283      6592760 :     interpolateLateralZ(result, getPositionOnLane() + offset, posLat);
    1284      6592760 :     return result;
    1285              : }
    1286              : 
    1287              : 
    1288              : void
    1289      6932605 : MSVehicle::interpolateLateralZ(Position& pos, double offset, double posLat) const {
    1290      6932605 :     const MSLane* shadow = myLaneChangeModel->getShadowLane();
    1291      6932605 :     if (shadow != nullptr && pos != Position::INVALID) {
    1292              :         // ignore negative offset
    1293              :         const Position shadowPos = shadow->geometryPositionAtOffset(MAX2(0.0, offset));
    1294        58284 :         if (shadowPos != Position::INVALID && pos.z() != shadowPos.z()) {
    1295          133 :             const double centerDist = (myLane->getWidth() + shadow->getWidth()) * 0.5;
    1296          133 :             double relOffset = fabs(posLat) / centerDist;
    1297          133 :             double newZ = (1 - relOffset) * pos.z() + relOffset * shadowPos.z();
    1298              :             pos.setz(newZ);
    1299              :         }
    1300              :     }
    1301      6932605 : }
    1302              : 
    1303              : 
    1304              : double
    1305        93474 : MSVehicle::getDistanceToLeaveJunction() const {
    1306        93474 :     double result = getLength() - getPositionOnLane();
    1307        93474 :     if (myLane->isNormal()) {
    1308              :         return MAX2(0.0, result);
    1309              :     }
    1310          376 :     const MSLane* lane = myLane;
    1311          752 :     while (lane->isInternal()) {
    1312          376 :         result += lane->getLength();
    1313          376 :         lane = lane->getCanonicalSuccessorLane();
    1314              :     }
    1315              :     return result;
    1316              : }
    1317              : 
    1318              : 
    1319              : Position
    1320       103258 : MSVehicle::getPositionAlongBestLanes(double offset) const {
    1321              :     assert(MSGlobals::gUsingInternalLanes);
    1322       103258 :     if (!isOnRoad()) {
    1323            0 :         return Position::INVALID;
    1324              :     }
    1325       103258 :     const std::vector<MSLane*>& bestLanes = getBestLanesContinuation();
    1326              :     auto nextBestLane = bestLanes.begin();
    1327       103258 :     const bool opposite = myLaneChangeModel->isOpposite();
    1328       103258 :     double pos = opposite ? myLane->getLength() - myState.myPos : myState.myPos;
    1329       103258 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : getLane();
    1330              :     assert(lane != 0);
    1331              :     bool success = true;
    1332              : 
    1333       304861 :     while (offset > 0) {
    1334              :         // take into account lengths along internal lanes
    1335       308239 :         while (lane->isInternal() && offset > 0) {
    1336       106636 :             if (offset > lane->getLength() - pos) {
    1337         3569 :                 offset -= lane->getLength() - pos;
    1338         3569 :                 lane = lane->getLinkCont()[0]->getViaLaneOrLane();
    1339              :                 pos = 0.;
    1340         3569 :                 if (lane == nullptr) {
    1341              :                     success = false;
    1342              :                     offset = 0.;
    1343              :                 }
    1344              :             } else {
    1345       103067 :                 pos += offset;
    1346              :                 offset = 0;
    1347              :             }
    1348              :         }
    1349              :         // set nextBestLane to next non-internal lane
    1350       206740 :         while (nextBestLane != bestLanes.end() && *nextBestLane == nullptr) {
    1351              :             ++nextBestLane;
    1352              :         }
    1353       201603 :         if (offset > 0) {
    1354              :             assert(!lane->isInternal());
    1355              :             assert(lane == *nextBestLane);
    1356        98536 :             if (offset > lane->getLength() - pos) {
    1357        98353 :                 offset -= lane->getLength() - pos;
    1358              :                 ++nextBestLane;
    1359              :                 assert(nextBestLane == bestLanes.end() || *nextBestLane != 0);
    1360        98353 :                 if (nextBestLane == bestLanes.end()) {
    1361              :                     success = false;
    1362              :                     offset = 0.;
    1363              :                 } else {
    1364        98353 :                     const MSLink* link = lane->getLinkTo(*nextBestLane);
    1365              :                     assert(link != nullptr);
    1366              :                     lane = link->getViaLaneOrLane();
    1367              :                     pos = 0.;
    1368              :                 }
    1369              :             } else {
    1370          183 :                 pos += offset;
    1371              :                 offset = 0;
    1372              :             }
    1373              :         }
    1374              : 
    1375              :     }
    1376              : 
    1377       103258 :     if (success) {
    1378       103258 :         return lane->geometryPositionAtOffset(pos, -getLateralPositionOnLane());
    1379              :     } else {
    1380            0 :         return Position::INVALID;
    1381              :     }
    1382              : }
    1383              : 
    1384              : 
    1385              : double
    1386       709058 : MSVehicle::getMaxSpeedOnLane() const {
    1387       709058 :     if (myLane != nullptr) {
    1388       709058 :         return myLane->getVehicleMaxSpeed(this);
    1389              :     }
    1390            0 :     return myType->getMaxSpeed();
    1391              : }
    1392              : 
    1393              : 
    1394              : Position
    1395    698209412 : MSVehicle::validatePosition(Position result, double offset) const {
    1396              :     int furtherIndex = 0;
    1397    698209412 :     double lastLength = getPositionOnLane();
    1398    698209412 :     while (result == Position::INVALID) {
    1399       270841 :         if (furtherIndex >= (int)myFurtherLanes.size()) {
    1400              :             //WRITE_WARNINGF(TL("Could not compute position for vehicle '%', time=%."), getID(), time2string(MSNet::getInstance()->getCurrentTimeStep()));
    1401              :             break;
    1402              :         }
    1403              :         //std::cout << SIMTIME << " veh=" << getID() << " lane=" << myLane->getID() << " pos=" << getPositionOnLane() << " posLat=" << getLateralPositionOnLane() << " offset=" << offset << " result=" << result << " i=" << furtherIndex << " further=" << myFurtherLanes.size() << "\n";
    1404       192075 :         MSLane* further = myFurtherLanes[furtherIndex];
    1405       192075 :         offset += lastLength;
    1406       192075 :         result = further->geometryPositionAtOffset(further->getLength() + offset, -getLateralPositionOnLane());
    1407              :         lastLength = further->getLength();
    1408       192075 :         furtherIndex++;
    1409              :         //std::cout << SIMTIME << "   newResult=" << result << "\n";
    1410              :     }
    1411    698209412 :     return result;
    1412              : }
    1413              : 
    1414              : 
    1415              : ConstMSEdgeVector::const_iterator
    1416      2937779 : MSVehicle::getRerouteOrigin() const {
    1417              :     // too close to the next junction, so avoid an emergency brake here
    1418      2937779 :     if (myLane != nullptr && (myCurrEdge + 1) != myRoute->end() && !isRailway(getVClass())) {
    1419       917752 :         if (myLane->isInternal()) {
    1420              :             return myCurrEdge + 1;
    1421              :         }
    1422       910774 :         if (myState.myPos > myLane->getLength() - getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)) {
    1423              :             return myCurrEdge + 1;
    1424              :         }
    1425       908098 :         if (myLane->getEdge().hasChangeProhibitions(getVClass(), myLane->getIndex())) {
    1426              :             return myCurrEdge + 1;
    1427              :         }
    1428              :     }
    1429      2928013 :     return myCurrEdge;
    1430              : }
    1431              : 
    1432              : void
    1433      5168858 : MSVehicle::setAngle(double angle, bool straightenFurther) {
    1434              : #ifdef DEBUG_FURTHER
    1435              :     if (DEBUG_COND) {
    1436              :         std::cout << SIMTIME << " veh '" << getID() << " setAngle(" << angle <<  ") straightenFurther=" << straightenFurther << std::endl;
    1437              :     }
    1438              : #endif
    1439      5168858 :     myAngle = angle;
    1440      5168858 :     MSLane* next = myLane;
    1441      5168858 :     if (straightenFurther && myFurtherLanesPosLat.size() > 0) {
    1442       196805 :         for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    1443       101062 :             MSLane* further = myFurtherLanes[i];
    1444       101062 :             const MSLink* link = further->getLinkTo(next);
    1445       101062 :             if (link  != nullptr) {
    1446       100681 :                 myFurtherLanesPosLat[i] = getLateralPositionOnLane() - link->getLateralShift();
    1447              :                 next = further;
    1448              :             } else {
    1449              :                 break;
    1450              :             }
    1451              :         }
    1452              :     }
    1453      5168858 : }
    1454              : 
    1455              : 
    1456              : void
    1457       406490 : MSVehicle::setActionStepLength(double actionStepLength, bool resetOffset) {
    1458       406490 :     SUMOTime actionStepLengthMillisecs = SUMOVehicleParserHelper::processActionStepLength(actionStepLength);
    1459              :     SUMOTime previousActionStepLength = getActionStepLength();
    1460              :     const bool newActionStepLength = actionStepLengthMillisecs != previousActionStepLength;
    1461       406490 :     if (newActionStepLength) {
    1462            7 :         getSingularType().setActionStepLength(actionStepLengthMillisecs, resetOffset);
    1463            7 :         if (!resetOffset) {
    1464            1 :             updateActionOffset(previousActionStepLength, actionStepLengthMillisecs);
    1465              :         }
    1466              :     }
    1467       406484 :     if (resetOffset) {
    1468            6 :         resetActionOffset();
    1469              :     }
    1470       406490 : }
    1471              : 
    1472              : 
    1473              : bool
    1474    291758583 : MSVehicle::congested() const {
    1475    291758583 :     return myState.mySpeed < (60.0 / 3.6) || myLane->getSpeedLimit() < (60.1 / 3.6);
    1476              : }
    1477              : 
    1478              : 
    1479              : double
    1480    694275475 : MSVehicle::computeAngle() const {
    1481              :     Position p1;
    1482    694275475 :     const double posLat = -myState.myPosLat; // @todo get rid of the '-'
    1483    694275475 :     const double lefthandSign = (MSGlobals::gLefthand ? -1 : 1);
    1484              : 
    1485              :     // if parking manoeuvre is happening then rotate vehicle on each step
    1486    694275475 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    1487          450 :         return getAngle() + myManoeuvre.getGUIIncrement();
    1488              :     }
    1489              : 
    1490    694275025 :     if (isParking()) {
    1491        27422 :         if (myStops.begin()->parkingarea != nullptr) {
    1492        15491 :             return myStops.begin()->parkingarea->getVehicleAngle(*this);
    1493              :         } else {
    1494        11931 :             return myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane()));
    1495              :         }
    1496              :     }
    1497    694247603 :     if (myLaneChangeModel->isChangingLanes()) {
    1498              :         // cannot use getPosition() because it already includes the offset to the side and thus messes up the angle
    1499      1125256 :         p1 = myLane->geometryPositionAtOffset(myState.myPos, lefthandSign * posLat);
    1500           12 :         if (p1 == Position::INVALID && myLane->getShape().length2D() == 0. && myLane->isInternal()) {
    1501              :             // workaround: extrapolate the preceding lane shape
    1502           12 :             MSLane* predecessorLane = myLane->getCanonicalPredecessorLane();
    1503           12 :             p1 = predecessorLane->geometryPositionAtOffset(predecessorLane->getLength() + myState.myPos, lefthandSign * posLat);
    1504              :         }
    1505              :     } else {
    1506    693122347 :         p1 = getPosition();
    1507              :     }
    1508              : 
    1509              :     Position p2;
    1510    694247603 :     if (getVehicleType().getParameter().locomotiveLength > 0) {
    1511              :         // articulated vehicle should use the heading of the first part
    1512      1708630 :         const double locoLength = MIN2(getVehicleType().getParameter().locomotiveLength, getLength());
    1513      1708630 :         p2 = getPosition(-locoLength);
    1514              :     } else {
    1515    692538973 :         p2 = getBackPosition();
    1516              :     }
    1517              :     if (p2 == Position::INVALID) {
    1518              :         // Handle special case of vehicle's back reaching out of the network
    1519          849 :         if (myFurtherLanes.size() > 0) {
    1520          129 :             p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
    1521              :             if (p2 == Position::INVALID) {
    1522              :                 // unsuitable lane geometry
    1523           81 :                 p2 = myLane->geometryPositionAtOffset(0, posLat);
    1524              :             }
    1525              :         } else {
    1526          720 :             p2 = myLane->geometryPositionAtOffset(0, posLat);
    1527              :         }
    1528              :     }
    1529              :     double result = (p1 != p2 ? p2.angleTo2D(p1) :
    1530        89616 :                      myLane->getShape().rotationAtOffset(myLane->interpolateLanePosToGeometryPos(getPositionOnLane())));
    1531              : 
    1532    694247603 :     result += lefthandSign * myLaneChangeModel->calcAngleOffset();
    1533              : 
    1534              : #ifdef DEBUG_FURTHER
    1535              :     if (DEBUG_COND) {
    1536              :         std::cout << SIMTIME << " computeAngle veh=" << getID() << " p1=" << p1 << " p2=" << p2 << " angle=" << RAD2DEG(result) << " naviDegree=" << GeomHelper::naviDegree(result) << "\n";
    1537              :     }
    1538              : #endif
    1539    694247603 :     return result;
    1540              : }
    1541              : 
    1542              : 
    1543              : const Position
    1544    857121403 : MSVehicle::getBackPosition() const {
    1545    857121403 :     const double posLat = MSGlobals::gLefthand ? myState.myPosLat : -myState.myPosLat;
    1546              :     Position result;
    1547    857121403 :     if (myState.myPos >= myType->getLength()) {
    1548              :         // vehicle is fully on the new lane
    1549    839865515 :         result = myLane->geometryPositionAtOffset(myState.myPos - myType->getLength(), posLat);
    1550              :     } else {
    1551     17255888 :         if (myLaneChangeModel->isChangingLanes() && myFurtherLanes.size() > 0 && myLaneChangeModel->getShadowLane(myFurtherLanes.back()) == nullptr) {
    1552              :             // special case where the target lane has no predecessor
    1553              : #ifdef DEBUG_FURTHER
    1554              :             if (DEBUG_COND) {
    1555              :                 std::cout << "    getBackPosition veh=" << getID() << " specialCase using myLane=" << myLane->getID() << " pos=0 posLat=" << myState.myPosLat << " result=" << myLane->geometryPositionAtOffset(0, posLat) << "\n";
    1556              :             }
    1557              : #endif
    1558         1692 :             result = myLane->geometryPositionAtOffset(0, posLat);
    1559              :         } else {
    1560              : #ifdef DEBUG_FURTHER
    1561              :             if (DEBUG_COND) {
    1562              :                 std::cout << "    getBackPosition veh=" << getID() << " myLane=" << myLane->getID() << " further=" << toString(myFurtherLanes) << " myFurtherLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
    1563              :             }
    1564              : #endif
    1565     17254196 :             if (myFurtherLanes.size() > 0 && !myLaneChangeModel->isChangingLanes()) {
    1566              :                 // truncate to 0 if vehicle starts on an edge that is shorter than its length
    1567     16842820 :                 const double backPos = MAX2(0.0, getBackPositionOnLane(myFurtherLanes.back()));
    1568     33388487 :                 result = myFurtherLanes.back()->geometryPositionAtOffset(backPos, -myFurtherLanesPosLat.back() * (MSGlobals::gLefthand ? -1 : 1));
    1569              :             } else {
    1570       411376 :                 result = myLane->geometryPositionAtOffset(0, posLat);
    1571              :             }
    1572              :         }
    1573              :     }
    1574    857121403 :     if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
    1575       281235 :         interpolateLateralZ(result, myState.myPos - myType->getLength(), posLat);
    1576              :     }
    1577    857121403 :     return result;
    1578              : }
    1579              : 
    1580              : 
    1581              : bool
    1582       381427 : MSVehicle::willStop() const {
    1583       381427 :     return !isStopped() && !myStops.empty() && myLane != nullptr && &myStops.front().lane->getEdge() == &myLane->getEdge();
    1584              : }
    1585              : 
    1586              : bool
    1587    366284296 : MSVehicle::isStoppedOnLane() const {
    1588    366284296 :     return isStopped() && myStops.front().lane == myLane;
    1589              : }
    1590              : 
    1591              : bool
    1592     30557247 : MSVehicle::keepStopping(bool afterProcessing) const {
    1593     30557247 :     if (isStopped()) {
    1594              :         // when coming out of vehicleTransfer we must shift the time forward
    1595     36145555 :         return (myStops.front().duration - (afterProcessing ? DELTA_T : 0) > 0 || isStoppedTriggered() || myStops.front().pars.collision
    1596     30358890 :                 || myStops.front().pars.breakDown || (myStops.front().getSpeed() > 0
    1597        37148 :                         && (myState.myPos < MIN2(myStops.front().pars.endPos, myStops.front().lane->getLength() - POSITION_EPS))
    1598        31150 :                         && (myStops.front().pars.parking == ParkingType::ONROAD || getSpeed() >= SUMO_const_haltingSpeed)));
    1599              :     } else {
    1600              :         return false;
    1601              :     }
    1602              : }
    1603              : 
    1604              : 
    1605              : SUMOTime
    1606        15903 : MSVehicle::remainingStopDuration() const {
    1607        15903 :     if (isStopped()) {
    1608        15903 :         return myStops.front().duration;
    1609              :     }
    1610              :     return 0;
    1611              : }
    1612              : 
    1613              : 
    1614              : SUMOTime
    1615    666654843 : MSVehicle::collisionStopTime() const {
    1616    666654843 :     return (myStops.empty() || !myStops.front().pars.collision) ? myCollisionImmunity : MAX2((SUMOTime)0, myStops.front().duration);
    1617              : }
    1618              : 
    1619              : 
    1620              : bool
    1621    666433656 : MSVehicle::brokeDown() const {
    1622    666433656 :     return isStopped() && !myStops.empty() && myStops.front().pars.breakDown;
    1623              : }
    1624              : 
    1625              : 
    1626              : bool
    1627       240335 : MSVehicle::ignoreCollision() const {
    1628       240335 :     return myCollisionImmunity > 0;
    1629              : }
    1630              : 
    1631              : 
    1632              : double
    1633    630687248 : MSVehicle::processNextStop(double currentVelocity) {
    1634    630687248 :     if (myStops.empty()) {
    1635              :         // no stops; pass
    1636              :         return currentVelocity;
    1637              :     }
    1638              : 
    1639              : #ifdef DEBUG_STOPS
    1640              :     if (DEBUG_COND) {
    1641              :         std::cout << "\nPROCESS_NEXT_STOP\n" << SIMTIME << " vehicle '" << getID() << "'" << std::endl;
    1642              :     }
    1643              : #endif
    1644              : 
    1645              :     MSStop& stop = myStops.front();
    1646     40918644 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1647     40918644 :     if (stop.reached) {
    1648     25830783 :         stop.duration -= getActionStepLength();
    1649              : 
    1650              : #ifdef DEBUG_STOPS
    1651              :         if (DEBUG_COND) {
    1652              :             std::cout << SIMTIME << " vehicle '" << getID() << "' reached stop.\n"
    1653              :                       << "Remaining duration: " << STEPS2TIME(stop.duration) << std::endl;
    1654              :             if (stop.getSpeed() > 0) {
    1655              :                 std::cout << " waypointSpeed=" << stop.getSpeed() << " vehPos=" << myState.myPos << " endPos=" << stop.pars.endPos << "\n";
    1656              :             }
    1657              :         }
    1658              : #endif
    1659     25830783 :         if (stop.duration <= 0 && stop.pars.join != "") {
    1660              :             // join this train (part) to another one
    1661        37459 :             MSVehicle* joinVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.join));
    1662          969 :             if (joinVeh && joinVeh->hasDeparted() && (joinVeh->joinTrainPart(this) || joinVeh->joinTrainPartFront(this))) {
    1663           36 :                 stop.joinTriggered = false;
    1664           36 :                 if (myAmRegisteredAsWaiting) {
    1665           21 :                     MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1666           21 :                     myAmRegisteredAsWaiting = false;
    1667              :                 }
    1668              :                 // avoid collision warning before this vehicle is removed (joinVeh was already made longer)
    1669           36 :                 myCollisionImmunity = TIME2STEPS(100);
    1670              :                 // mark this vehicle as arrived
    1671           36 :                 myArrivalPos = getPositionOnLane();
    1672           36 :                 const_cast<SUMOVehicleParameter*>(myParameter)->arrivalEdge = getRoutePosition();
    1673              :                 // handle transportables that want to continue in the other vehicle
    1674           36 :                 if (myPersonDevice != nullptr) {
    1675            3 :                     myPersonDevice->transferAtSplitOrJoin(joinVeh);
    1676              :                 }
    1677           36 :                 if (myContainerDevice != nullptr) {
    1678            3 :                     myContainerDevice->transferAtSplitOrJoin(joinVeh);
    1679              :                 }
    1680              :             }
    1681              :         }
    1682     25830783 :         boardTransportables(stop);
    1683     21806003 :         if (time > stop.endBoarding) {
    1684              :             // for taxi: cancel customers
    1685       133261 :             MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1686              :             if (taxiDevice != nullptr) {
    1687              :                 // may invalidate stops including the current reference
    1688           64 :                 taxiDevice->cancelCurrentCustomers();
    1689           64 :                 resumeFromStopping();
    1690           64 :                 return currentVelocity;
    1691              :             }
    1692              :         }
    1693     21805939 :         if (!keepStopping() && isOnRoad()) {
    1694              : #ifdef DEBUG_STOPS
    1695              :             if (DEBUG_COND) {
    1696              :                 std::cout << SIMTIME << " vehicle '" << getID() << "' resumes from stopping." << std::endl;
    1697              :             }
    1698              : #endif
    1699        42565 :             resumeFromStopping();
    1700        42565 :             if (isRail() && hasStops()) {
    1701              :                 // stay on the current lane in case of a double stop
    1702         2794 :                 const MSStop& nextStop = getNextStop();
    1703         2794 :                 if (nextStop.edge == myCurrEdge) {
    1704         1033 :                     const double stopSpeed = getCarFollowModel().stopSpeed(this, getSpeed(), nextStop.pars.endPos - myState.myPos);
    1705              :                     //std::cout << SIMTIME << " veh=" << getID() << " resumedFromStopping currentVelocity=" << currentVelocity << " stopSpeed=" << stopSpeed << "\n";
    1706         1033 :                     return stopSpeed;
    1707              :                 }
    1708              :             }
    1709              :         } else {
    1710     21763374 :             if (stop.triggered) {
    1711      2838335 :                 if (getVehicleType().getPersonCapacity() == getPersonNumber()) {
    1712           30 :                     WRITE_WARNINGF(TL("Vehicle '%' ignores triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
    1713           10 :                     stop.triggered = false;
    1714      2838325 :                 } else if (!myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
    1715              :                     // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
    1716         3294 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1717         3294 :                     myAmRegisteredAsWaiting = true;
    1718              : #ifdef DEBUG_STOPS
    1719              :                     if (DEBUG_COND) {
    1720              :                         std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for person." << std::endl;
    1721              :                     }
    1722              : #endif
    1723              :                 }
    1724              :             }
    1725     21763374 :             if (stop.containerTriggered) {
    1726        39500 :                 if (getVehicleType().getContainerCapacity() == getContainerNumber()) {
    1727         1332 :                     WRITE_WARNINGF(TL("Vehicle '%' ignores container triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
    1728          444 :                     stop.containerTriggered = false;
    1729        39056 :                 } else if (stop.containerTriggered && !myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
    1730              :                     // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
    1731           92 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1732           92 :                     myAmRegisteredAsWaiting = true;
    1733              : #ifdef DEBUG_STOPS
    1734              :                     if (DEBUG_COND) {
    1735              :                         std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for container." << std::endl;
    1736              :                     }
    1737              : #endif
    1738              :                 }
    1739              :             }
    1740              :             // joining only takes place after stop duration is over
    1741     21763374 :             if (stop.joinTriggered && !myAmRegisteredAsWaiting
    1742         7164 :                     && stop.duration <= (stop.pars.extension >= 0 ? -stop.pars.extension : 0)) {
    1743          100 :                 if (stop.pars.extension >= 0) {
    1744          105 :                     WRITE_WARNINGF(TL("Vehicle '%' aborts joining after extension of %s at time %."), getID(), STEPS2TIME(stop.pars.extension), time2string(SIMSTEP));
    1745           35 :                     stop.joinTriggered = false;
    1746              :                 } else {
    1747              :                     // keep stopping indefinitely but ensure that simulation terminates
    1748           65 :                     MSNet::getInstance()->getVehicleControl().registerOneWaiting();
    1749           65 :                     myAmRegisteredAsWaiting = true;
    1750              :                 }
    1751              :             }
    1752     21763374 :             if (stop.getSpeed() > 0) {
    1753              :                 //waypoint mode
    1754       152802 :                 if (stop.duration == 0) {
    1755          264 :                     return stop.getSpeed();
    1756              :                 } else {
    1757              :                     // stop for 'until' (computed in planMove)
    1758              :                     return currentVelocity;
    1759              :                 }
    1760              :             } else {
    1761              :                 // brake
    1762     21610572 :                 if (MSGlobals::gSemiImplicitEulerUpdate || stop.getSpeed() > 0) {
    1763     21344340 :                     return 0;
    1764              :                 } else {
    1765              :                     // ballistic:
    1766       266232 :                     return getSpeed() - getCarFollowModel().getMaxDecel();
    1767              :                 }
    1768              :             }
    1769              :         }
    1770              :     } else {
    1771              : 
    1772              : #ifdef DEBUG_STOPS
    1773              :         if (DEBUG_COND) {
    1774              :             std::cout << SIMTIME << " vehicle '" << getID() << "' hasn't reached next stop." << std::endl;
    1775              :         }
    1776              : #endif
    1777              :         //std::cout << SIMTIME <<  " myStopDist=" << myStopDist << " bGap=" << getBrakeGap(myLane->getVehicleMaxSpeed(this)) << "\n";
    1778     15151461 :         if (stop.pars.onDemand && !stop.skipOnDemand && myStopDist <= getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this))) {
    1779          572 :             MSNet* const net = MSNet::getInstance();
    1780           44 :             const bool noExits = ((myPersonDevice == nullptr || !myPersonDevice->anyLeavingAtStop(stop))
    1781          582 :                                   && (myContainerDevice == nullptr || !myContainerDevice->anyLeavingAtStop(stop)));
    1782           83 :             const bool noEntries = ((!net->hasPersons() || !net->getPersonControl().hasAnyWaiting(stop.getEdge(), this))
    1783          621 :                                     && (!net->hasContainers() || !net->getContainerControl().hasAnyWaiting(stop.getEdge(), this)));
    1784          572 :             if (noExits && noEntries) {
    1785              :                 //std::cout << " skipOnDemand\n";
    1786          504 :                 stop.skipOnDemand = true;
    1787              :             }
    1788              :         }
    1789              :         // is the next stop on the current lane?
    1790     15087861 :         if (stop.edge == myCurrEdge) {
    1791              :             // get the stopping position
    1792      5420012 :             bool useStoppingPlace = stop.busstop != nullptr || stop.containerstop != nullptr || stop.parkingarea != nullptr;
    1793              :             bool fitsOnStoppingPlace = true;
    1794      5420012 :             if (!stop.skipOnDemand) {  // no need to check available space if we skip it anyway
    1795      5418041 :                 if (stop.busstop != nullptr) {
    1796      1656390 :                     fitsOnStoppingPlace &= stop.busstop->fits(myState.myPos, *this);
    1797              :                 }
    1798      5418041 :                 if (stop.containerstop != nullptr) {
    1799        21788 :                     fitsOnStoppingPlace &= stop.containerstop->fits(myState.myPos, *this);
    1800              :                 }
    1801              :                 // if the stop is a parking area we check if there is a free position on the area
    1802      5418041 :                 if (stop.parkingarea != nullptr) {
    1803       651171 :                     fitsOnStoppingPlace &= myState.myPos > stop.parkingarea->getBeginLanePosition();
    1804       651171 :                     if (stop.parkingarea->getOccupancy() >= stop.parkingarea->getCapacity()) {
    1805              :                         fitsOnStoppingPlace = false;
    1806              :                         // trigger potential parkingZoneReroute
    1807       425940 :                         MSParkingArea* oldParkingArea = stop.parkingarea;
    1808       456515 :                         for (MSMoveReminder* rem : myLane->getMoveReminders()) {
    1809        30575 :                             if (rem->isParkingRerouter()) {
    1810         9351 :                                 rem->notifyEnter(*this, MSMoveReminder::NOTIFICATION_PARKING_REROUTE, myLane);
    1811              :                             }
    1812              :                         }
    1813       425940 :                         if (myStops.empty() || myStops.front().parkingarea != oldParkingArea) {
    1814              :                             // rerouted, keep driving
    1815              :                             return currentVelocity;
    1816              :                         }
    1817       225231 :                     } else if (stop.parkingarea->getOccupancyIncludingReservations(this) >= stop.parkingarea->getCapacity()) {
    1818              :                         fitsOnStoppingPlace = false;
    1819       101221 :                     } else if (stop.parkingarea->parkOnRoad() && stop.parkingarea->getLotIndex(this) < 0) {
    1820              :                         fitsOnStoppingPlace = false;
    1821              :                     }
    1822              :                 }
    1823              :             }
    1824      5418019 :             const double targetPos = myState.myPos + myStopDist + (stop.getSpeed() > 0 ? (stop.pars.startPos - stop.pars.endPos) : 0);
    1825      5418019 :             const double reachedThreshold = (useStoppingPlace ? targetPos - STOPPING_PLACE_OFFSET : stop.getReachedThreshold()) - NUMERICAL_EPS;
    1826              : #ifdef DEBUG_STOPS
    1827              :             if (DEBUG_COND) {
    1828              :                 std::cout <<  "   pos=" << myState.pos() << " speed=" << currentVelocity << " targetPos=" << targetPos << " fits=" << fitsOnStoppingPlace
    1829              :                           << " reachedThresh=" << reachedThreshold
    1830              :                           << " myLane=" << Named::getIDSecure(myLane)
    1831              :                           << " stopLane=" << Named::getIDSecure(stop.lane)
    1832              :                           << "\n";
    1833              :             }
    1834              : #endif
    1835      5418019 :             const bool posReached = myState.pos() >= reachedThreshold && currentVelocity <= stop.getSpeed() + SUMO_const_haltingSpeed && myLane == stop.lane;
    1836      5418019 :             if (posReached && !fitsOnStoppingPlace && MSStopOut::active()) {
    1837         4558 :                 MSStopOut::getInstance()->stopBlocked(this, time);
    1838              :             }
    1839      5418019 :             if (fitsOnStoppingPlace && posReached && (!MSGlobals::gModelParkingManoeuver || myManoeuvre.entryManoeuvreIsComplete(this))) {
    1840              :                 // ok, we may stop (have reached the stop)  and either we are not modelling maneuvering or have completed entry
    1841        53700 :                 stop.reached = true;
    1842        53700 :                 if (!stop.startedFromState) {
    1843        53484 :                     stop.pars.started = time;
    1844              :                 }
    1845              : #ifdef DEBUG_STOPS
    1846              :                 if (DEBUG_COND) {
    1847              :                     std::cout << SIMTIME << " vehicle '" << getID() << "' reached next stop." << std::endl;
    1848              :                 }
    1849              : #endif
    1850        53700 :                 if (MSStopOut::active()) {
    1851         4980 :                     MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), time);
    1852              :                 }
    1853        53700 :                 myLane->getEdge().addWaiting(this);
    1854        53700 :                 MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::STARTING_STOP);
    1855        53700 :                 MSNet::getInstance()->getVehicleControl().registerStopStarted();
    1856              :                 // compute stopping time
    1857        53700 :                 stop.duration = stop.getMinDuration(time);
    1858        53700 :                 stop.endBoarding = stop.pars.extension >= 0 ? time + stop.duration + stop.pars.extension : SUMOTime_MAX;
    1859        53700 :                 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
    1860         2697 :                 if (taxiDevice != nullptr && stop.pars.extension >= 0) {
    1861              :                     // earliestPickupTime is set with waitUntil
    1862           84 :                     stop.endBoarding = MAX2(time, stop.pars.waitUntil) + stop.pars.extension;
    1863              :                 }
    1864        53700 :                 if (stop.getSpeed() > 0) {
    1865              :                     // ignore duration parameter in waypoint mode unless 'until' or 'ended' are set
    1866         3358 :                     if (stop.getUntil() > time) {
    1867          334 :                         stop.duration = stop.getUntil() - time;
    1868              :                     } else {
    1869         3024 :                         stop.duration = 0;
    1870              :                     }
    1871              :                 }
    1872        53700 :                 if (stop.busstop != nullptr) {
    1873              :                     // let the bus stop know the vehicle
    1874        18076 :                     stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1875              :                 }
    1876        53700 :                 if (stop.containerstop != nullptr) {
    1877              :                     // let the container stop know the vehicle
    1878          569 :                     stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1879              :                 }
    1880        53700 :                 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    1881              :                     // let the parking area know the vehicle
    1882         8814 :                     stop.parkingarea->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1883              :                 }
    1884        53700 :                 if (stop.chargingStation != nullptr) {
    1885              :                     // let the container stop know the vehicle
    1886         3482 :                     stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    1887              :                 }
    1888              : 
    1889        53700 :                 if (stop.pars.tripId != "") {
    1890         2920 :                     ((SUMOVehicleParameter&)getParameter()).setParameter("tripId", stop.pars.tripId);
    1891              :                 }
    1892        53700 :                 if (stop.pars.line != "") {
    1893         1464 :                     ((SUMOVehicleParameter&)getParameter()).line = stop.pars.line;
    1894              :                 }
    1895        53700 :                 if (stop.pars.split != "") {
    1896              :                     // split the train
    1897         1239 :                     MSVehicle* splitVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.split));
    1898           24 :                     if (splitVeh == nullptr) {
    1899         3645 :                         WRITE_WARNINGF(TL("Vehicle '%' to split from vehicle '%' is not known. time=%."), stop.pars.split, getID(), SIMTIME)
    1900              :                     } else {
    1901           24 :                         MSNet::getInstance()->getInsertionControl().add(splitVeh);
    1902           24 :                         splitVeh->getRoute().getEdges()[0]->removeWaiting(splitVeh);
    1903           24 :                         MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1904           24 :                         const double newLength = MAX2(myType->getLength() - splitVeh->getVehicleType().getLength(),
    1905           24 :                                                       myType->getParameter().locomotiveLength);
    1906           24 :                         getSingularType().setLength(newLength);
    1907              :                         // handle transportables that want to continue in the split part
    1908           24 :                         if (myPersonDevice != nullptr) {
    1909            0 :                             myPersonDevice->transferAtSplitOrJoin(splitVeh);
    1910              :                         }
    1911           24 :                         if (myContainerDevice != nullptr) {
    1912            6 :                             myContainerDevice->transferAtSplitOrJoin(splitVeh);
    1913              :                         }
    1914           24 :                         if (splitVeh->getParameter().departPosProcedure == DepartPosDefinition::SPLIT_FRONT) {
    1915            3 :                             const double backShift = splitVeh->getLength() + getVehicleType().getMinGap();
    1916            3 :                             myState.myPos -= backShift;
    1917            3 :                             myState.myBackPos -= backShift;
    1918              :                         }
    1919              :                     }
    1920              :                 }
    1921              : 
    1922        53700 :                 boardTransportables(stop);
    1923        53696 :                 if (stop.pars.posLat != INVALID_DOUBLE) {
    1924          232 :                     myState.myPosLat = stop.pars.posLat;
    1925              :                 }
    1926              :             }
    1927              :         }
    1928              :     }
    1929              :     return currentVelocity;
    1930              : }
    1931              : 
    1932              : 
    1933              : void
    1934     25884483 : MSVehicle::boardTransportables(MSStop& stop) {
    1935     25884483 :     if (stop.skipOnDemand) {
    1936              :         return;
    1937              :     }
    1938              :     // we have reached the stop
    1939              :     // any waiting persons may board now
    1940     25747737 :     const SUMOTime time = MSNet::getInstance()->getCurrentTimeStep();
    1941     25747737 :     MSNet* const net = MSNet::getInstance();
    1942     25747737 :     const bool boarded = (time <= stop.endBoarding
    1943     25745661 :                           && net->hasPersons()
    1944      1186510 :                           && net->getPersonControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToBoardNextPerson, stop.duration)
    1945     25752276 :                           && stop.numExpectedPerson == 0);
    1946              :     // load containers
    1947     25747737 :     const bool loaded = (time <= stop.endBoarding
    1948     25745661 :                          && net->hasContainers()
    1949      4127202 :                          && net->getContainerControl().loadAnyWaiting(&myLane->getEdge(), this, stop.timeToLoadNextContainer, stop.duration)
    1950     25748312 :                          && stop.numExpectedContainer == 0);
    1951              : 
    1952              :     bool unregister = false;
    1953     21722953 :     if (time > stop.endBoarding) {
    1954         2076 :         stop.triggered = false;
    1955         2076 :         stop.containerTriggered = false;
    1956         2076 :         if (myAmRegisteredAsWaiting) {
    1957              :             unregister = true;
    1958          325 :             myAmRegisteredAsWaiting = false;
    1959              :         }
    1960              :     }
    1961     21722953 :     if (boarded) {
    1962              :         // the triggering condition has been fulfilled. Maybe we want to wait a bit longer for additional riders (car pooling)
    1963         4407 :         if (myAmRegisteredAsWaiting) {
    1964              :             unregister = true;
    1965              :         }
    1966         4407 :         stop.triggered = false;
    1967         4407 :         myAmRegisteredAsWaiting = false;
    1968              :     }
    1969     21722953 :     if (loaded) {
    1970              :         // the triggering condition has been fulfilled
    1971          555 :         if (myAmRegisteredAsWaiting) {
    1972              :             unregister = true;
    1973              :         }
    1974          555 :         stop.containerTriggered = false;
    1975          555 :         myAmRegisteredAsWaiting = false;
    1976              :     }
    1977              : 
    1978     21722953 :     if (unregister) {
    1979          410 :         MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    1980              : #ifdef DEBUG_STOPS
    1981              :         if (DEBUG_COND) {
    1982              :             std::cout << SIMTIME << " vehicle '" << getID() << "' unregisters as waiting for transportable." << std::endl;
    1983              :         }
    1984              : #endif
    1985              :     }
    1986              : }
    1987              : 
    1988              : bool
    1989          921 : MSVehicle::joinTrainPart(MSVehicle* veh) {
    1990              :     // check if veh is close enough to be joined to the rear of this vehicle
    1991          921 :     MSLane* backLane = myFurtherLanes.size() == 0 ? myLane : myFurtherLanes.back();
    1992          921 :     double gap = getBackPositionOnLane() - veh->getPositionOnLane();
    1993         1144 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == veh->getLane()
    1994          951 :             && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
    1995           15 :         const double newLength = myType->getLength() + veh->getVehicleType().getLength();
    1996           15 :         getSingularType().setLength(newLength);
    1997           15 :         myStops.begin()->joinTriggered = false;
    1998           15 :         if (myAmRegisteredAsWaiting) {
    1999            0 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2000            0 :             myAmRegisteredAsWaiting = false;
    2001              :         }
    2002              :         return true;
    2003              :     } else {
    2004          906 :         return false;
    2005              :     }
    2006              : }
    2007              : 
    2008              : 
    2009              : bool
    2010          906 : MSVehicle::joinTrainPartFront(MSVehicle* veh) {
    2011              :     // check if veh is close enough to be joined to the front of this vehicle
    2012          906 :     MSLane* backLane = veh->myFurtherLanes.size() == 0 ? veh->myLane : veh->myFurtherLanes.back();
    2013          906 :     double gap = veh->getBackPositionOnLane(backLane) - getPositionOnLane();
    2014         1114 :     if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == getLane()
    2015          930 :             && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
    2016              :         double skippedLaneLengths = 0;
    2017           24 :         if (veh->myFurtherLanes.size() > 0) {
    2018            9 :             skippedLaneLengths += getLane()->getLength();
    2019              :             // this vehicle must be moved to the lane of veh
    2020              :             // ensure that lane and furtherLanes of veh match our route
    2021            9 :             int routeIndex = getRoutePosition();
    2022            9 :             if (myLane->isInternal()) {
    2023            0 :                 routeIndex++;
    2024              :             }
    2025           27 :             for (int i = (int)veh->myFurtherLanes.size() - 1; i >= 0; i--) {
    2026           18 :                 MSEdge* edge = &veh->myFurtherLanes[i]->getEdge();
    2027           18 :                 if (edge->isInternal()) {
    2028            9 :                     continue;
    2029              :                 }
    2030            9 :                 if (!edge->isInternal() && edge != myRoute->getEdges()[routeIndex]) {
    2031            0 :                     std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
    2032            0 :                     WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
    2033              :                     return false;
    2034              :                 }
    2035            9 :                 routeIndex++;
    2036              :             }
    2037            9 :             if (veh->getCurrentEdge()->getNormalSuccessor() != myRoute->getEdges()[routeIndex]) {
    2038            3 :                 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
    2039            9 :                 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
    2040              :                 return false;
    2041              :             }
    2042           12 :             for (int i = (int)veh->myFurtherLanes.size() - 2; i >= 0; i--) {
    2043            6 :                 skippedLaneLengths += veh->myFurtherLanes[i]->getLength();
    2044              :             }
    2045              :         }
    2046              : 
    2047           21 :         const double newLength = myType->getLength() + veh->getVehicleType().getLength();
    2048           21 :         getSingularType().setLength(newLength);
    2049              :         // lane will be advanced just as for regular movement
    2050           21 :         myState.myPos = skippedLaneLengths + veh->getPositionOnLane();
    2051           21 :         myStops.begin()->joinTriggered = false;
    2052           21 :         if (myAmRegisteredAsWaiting) {
    2053            8 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    2054            8 :             myAmRegisteredAsWaiting = false;
    2055              :         }
    2056           21 :         return true;
    2057              :     } else {
    2058          882 :         return false;
    2059              :     }
    2060              : }
    2061              : 
    2062              : double
    2063      8359920 : MSVehicle::getBrakeGap(bool delayed) const {
    2064      8359920 :     return getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), delayed ? getCarFollowModel().getHeadwayTime() : 0);
    2065              : }
    2066              : 
    2067              : 
    2068              : bool
    2069    691010757 : MSVehicle::checkActionStep(const SUMOTime t) {
    2070    691010757 :     myActionStep = isActionStep(t);
    2071    691010757 :     if (myActionStep) {
    2072    619374397 :         myLastActionTime = t;
    2073              :     }
    2074    691010757 :     return myActionStep;
    2075              : }
    2076              : 
    2077              : 
    2078              : void
    2079         1596 : MSVehicle::resetActionOffset(const SUMOTime timeUntilNextAction) {
    2080         1596 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + timeUntilNextAction;
    2081         1596 : }
    2082              : 
    2083              : 
    2084              : void
    2085            1 : MSVehicle::updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength) {
    2086            1 :     SUMOTime now = MSNet::getInstance()->getCurrentTimeStep();
    2087            1 :     SUMOTime timeSinceLastAction = now - myLastActionTime;
    2088            1 :     if (timeSinceLastAction == 0) {
    2089              :         // Action was scheduled now, may be delayed be new action step length
    2090              :         timeSinceLastAction = oldActionStepLength;
    2091              :     }
    2092            1 :     if (timeSinceLastAction >= newActionStepLength) {
    2093              :         // Action point required in this step
    2094            0 :         myLastActionTime = now;
    2095              :     } else {
    2096            1 :         SUMOTime timeUntilNextAction = newActionStepLength - timeSinceLastAction;
    2097            1 :         resetActionOffset(timeUntilNextAction);
    2098              :     }
    2099            1 : }
    2100              : 
    2101              : 
    2102              : 
    2103              : void
    2104    691010757 : MSVehicle::planMove(const SUMOTime t, const MSLeaderInfo& ahead, const double lengthsInFront) {
    2105              : #ifdef DEBUG_PLAN_MOVE
    2106              :     if (DEBUG_COND) {
    2107              :         std::cout
    2108              :                 << "\nPLAN_MOVE\n"
    2109              :                 << SIMTIME
    2110              :                 << std::setprecision(gPrecision)
    2111              :                 << " veh=" << getID()
    2112              :                 << " lane=" << myLane->getID()
    2113              :                 << " pos=" << getPositionOnLane()
    2114              :                 << " posLat=" << getLateralPositionOnLane()
    2115              :                 << " speed=" << getSpeed()
    2116              :                 << "\n";
    2117              :     }
    2118              : #endif
    2119              :     // Update the driver state
    2120    691010757 :     if (hasDriverState()) {
    2121       406476 :         myDriverState->update();
    2122       812952 :         setActionStepLength(myDriverState->getDriverState()->getActionStepLength(), false);
    2123              :     }
    2124              : 
    2125    691010757 :     if (!checkActionStep(t)) {
    2126              : #ifdef DEBUG_ACTIONSTEPS
    2127              :         if (DEBUG_COND) {
    2128              :             std::cout << STEPS2TIME(t) << " vehicle '" << getID() << "' skips action." << std::endl;
    2129              :         }
    2130              : #endif
    2131              :         // During non-action passed drive items still need to be removed
    2132              :         // @todo rather work with updating myCurrentDriveItem (refs #3714)
    2133     71636360 :         removePassedDriveItems();
    2134     71636360 :         return;
    2135              :     } else {
    2136              : #ifdef DEBUG_ACTIONSTEPS
    2137              :         if (DEBUG_COND) {
    2138              :             std::cout << STEPS2TIME(t) << " vehicle = '" << getID() << "' takes action." << std::endl;
    2139              :         }
    2140              : #endif
    2141    619374397 :         myLFLinkLanesPrev = myLFLinkLanes;
    2142    619374397 :         if (myInfluencer != nullptr) {
    2143       493531 :             myInfluencer->updateRemoteControlRoute(this);
    2144              :         }
    2145    619374397 :         planMoveInternal(t, ahead, myLFLinkLanes, myStopDist, myNextTurn);
    2146              : #ifdef DEBUG_PLAN_MOVE
    2147              :         if (DEBUG_COND) {
    2148              :             DriveItemVector::iterator i;
    2149              :             for (i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
    2150              :                 std::cout
    2151              :                         << " vPass=" << (*i).myVLinkPass
    2152              :                         << " vWait=" << (*i).myVLinkWait
    2153              :                         << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
    2154              :                         << " request=" << (*i).mySetRequest
    2155              :                         << "\n";
    2156              :             }
    2157              :         }
    2158              : #endif
    2159    619374397 :         checkRewindLinkLanes(lengthsInFront, myLFLinkLanes);
    2160    619374397 :         myNextDriveItem = myLFLinkLanes.begin();
    2161              :         // ideally would only do this with the call inside planMoveInternal - but that needs a const method
    2162              :         //   so this is a kludge here - nuisance as it adds an extra check in a busy loop
    2163    619374397 :         if (MSGlobals::gModelParkingManoeuver) {
    2164         2971 :             if (getManoeuvreType() == MSVehicle::MANOEUVRE_EXIT && manoeuvreIsComplete()) {
    2165           30 :                 setManoeuvreType(MSVehicle::MANOEUVRE_NONE);
    2166              :             }
    2167              :         }
    2168              :     }
    2169    619374397 :     myLaneChangeModel->resetChanged();
    2170              : }
    2171              : 
    2172              : 
    2173              : bool
    2174    169067500 : MSVehicle::brakeForOverlap(const MSLink* link, const MSLane* lane) const {
    2175              :     // @review needed
    2176              :     //const double futurePosLat = getLateralPositionOnLane() + link->getLateralShift();
    2177              :     //const double overlap = getLateralOverlap(futurePosLat, link->getViaLaneOrLane());
    2178              :     //const double edgeWidth = link->getViaLaneOrLane()->getEdge().getWidth();
    2179    169067500 :     const double futurePosLat = getLateralPositionOnLane() + (
    2180    169067500 :                                     lane != myLane && lane->isInternal() ? lane->getIncomingLanes()[0].viaLink->getLateralShift() : 0);
    2181    169067500 :     const double overlap = getLateralOverlap(futurePosLat, lane);
    2182              :     const double edgeWidth = lane->getEdge().getWidth();
    2183              :     const bool result = (overlap > POSITION_EPS
    2184              :                          // do not get stuck on narrow edges
    2185      3074256 :                          && getVehicleType().getWidth() <= edgeWidth
    2186      3069971 :                          && link->getViaLane() == nullptr
    2187              :                          // this is the exit link of a junction. The normal edge should support the shadow
    2188      1491422 :                          && ((myLaneChangeModel->getShadowLane(link->getLane()) == nullptr)
    2189              :                              // the shadow lane must be permitted
    2190      1116824 :                              || !myLaneChangeModel->getShadowLane(link->getLane())->allowsVehicleClass(getVClass())
    2191              :                              // the internal lane after an internal junction has no parallel lane. make sure there is no shadow before continuing
    2192      1056183 :                              || (lane->getEdge().isInternal() && lane->getIncomingLanes()[0].lane->getEdge().isInternal()))
    2193              :                          // ignore situations where the shadow lane is part of a double-connection with the current lane
    2194       451299 :                          && (myLaneChangeModel->getShadowLane() == nullptr
    2195       247409 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().size() == 0
    2196       233092 :                              || myLaneChangeModel->getShadowLane()->getLinkCont().front()->getLane() != link->getLane())
    2197              :                          // emergency vehicles may do some crazy stuff
    2198    169457221 :                          && !myLaneChangeModel->hasBlueLight());
    2199              : 
    2200              : #ifdef DEBUG_PLAN_MOVE
    2201              :     if (DEBUG_COND) {
    2202              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getDescription() << " lane=" << lane->getID()
    2203              :                   << " linkLane=" << link->getLane()->getID()
    2204              :                   << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    2205              :                   << " shift=" << link->getLateralShift()
    2206              :                   << " fpLat=" << futurePosLat << " overlap=" << overlap << " w=" << getVehicleType().getWidth()
    2207              :                   << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane(link->getLane()))
    2208              :                   << " result=" << result << "\n";
    2209              :     }
    2210              : #endif
    2211    169067500 :     return result;
    2212              : }
    2213              : 
    2214              : 
    2215              : 
    2216              : void
    2217    619374397 : MSVehicle::planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector& lfLinks, double& newStopDist, std::pair<double, const MSLink*>& nextTurn) const {
    2218              :     lfLinks.clear();
    2219    619374397 :     newStopDist = std::numeric_limits<double>::max();
    2220              :     //
    2221              :     const MSCFModel& cfModel = getCarFollowModel();
    2222    619374397 :     const double vehicleLength = getVehicleType().getLength();
    2223    619374397 :     const double maxV = cfModel.maxNextSpeed(myState.mySpeed, this);
    2224    619374397 :     const double maxVD = MAX2(getMaxSpeed(), MIN2(maxV, getDesiredMaxSpeed()));
    2225    619374397 :     const bool opposite = myLaneChangeModel->isOpposite();
    2226              :     // maxVD is possibly higher than vType-maxSpeed and in this case laneMaxV may be higher as well
    2227    619374397 :     double laneMaxV = myLane->getVehicleMaxSpeed(this, maxVD);
    2228    619374397 :     const double vMinComfortable = cfModel.minNextSpeed(getSpeed(), this);
    2229              :     double lateralShift = 0;
    2230    619374397 :     if (isRail()) {
    2231              :         // speed limits must hold for the whole length of the train
    2232      1563263 :         for (MSLane* l : myFurtherLanes) {
    2233       341991 :             laneMaxV = MIN2(laneMaxV, l->getVehicleMaxSpeed(this, maxVD));
    2234              : #ifdef DEBUG_PLAN_MOVE
    2235              :             if (DEBUG_COND) {
    2236              :                 std::cout << "   laneMaxV=" << laneMaxV << " lane=" << l->getID() << "\n";
    2237              :             }
    2238              : #endif
    2239              :         }
    2240              :     }
    2241              :     //  speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
    2242              :     laneMaxV = MAX2(laneMaxV, vMinComfortable);
    2243    619867896 :     if (myInfluencer && !myInfluencer->considerSpeedLimit()) {
    2244              :         laneMaxV = std::numeric_limits<double>::max();
    2245              :     }
    2246              :     // v is the initial maximum velocity of this vehicle in this step
    2247    619374397 :     double v = cfModel.maximumLaneSpeedCF(this, maxV, laneMaxV);
    2248              :     // if we are modelling parking then we dawdle until the manoeuvre is complete - by setting a very low max speed
    2249              :     //   in practice this only applies to exit manoeuvre because entry manoeuvre just delays setting stop.reached - when the vehicle is virtually stopped
    2250    619374397 :     if (MSGlobals::gModelParkingManoeuver && !manoeuvreIsComplete()) {
    2251          420 :         v = NUMERICAL_EPS_SPEED;
    2252              :     }
    2253              : 
    2254    619374397 :     if (myInfluencer != nullptr) {
    2255       493531 :         const double vMin = MAX2(0., cfModel.minNextSpeed(myState.mySpeed, this));
    2256              : #ifdef DEBUG_TRACI
    2257              :         if (DEBUG_COND) {
    2258              :             std::cout << SIMTIME << " veh=" << getID() << " speedBeforeTraci=" << v;
    2259              :         }
    2260              : #endif
    2261       493531 :         v = myInfluencer->influenceSpeed(t, v, v, vMin, maxV);
    2262              : #ifdef DEBUG_TRACI
    2263              :         if (DEBUG_COND) {
    2264              :             std::cout << " influencedSpeed=" << v;
    2265              :         }
    2266              : #endif
    2267       493531 :         v = myInfluencer->gapControlSpeed(t, this, v, v, vMin, maxV);
    2268              : #ifdef DEBUG_TRACI
    2269              :         if (DEBUG_COND) {
    2270              :             std::cout << " gapControlSpeed=" << v << "\n";
    2271              :         }
    2272              : #endif
    2273              :     }
    2274              :     // all links within dist are taken into account (potentially)
    2275    619374397 :     const double dist = SPEED2DIST(maxV) + cfModel.brakeGap(maxV);
    2276              : 
    2277    619374397 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation();
    2278              : #ifdef DEBUG_PLAN_MOVE
    2279              :     if (DEBUG_COND) {
    2280              :         std::cout << "   dist=" << dist << " bestLaneConts=" << toString(bestLaneConts)
    2281              :                   << "\n   maxV=" << maxV << " laneMaxV=" << laneMaxV << " v=" << v << "\n";
    2282              :     }
    2283              : #endif
    2284              :     assert(bestLaneConts.size() > 0);
    2285              :     bool hadNonInternal = false;
    2286              :     // the distance already "seen"; in the following always up to the end of the current "lane"
    2287    619374397 :     double seen = opposite ? myState.myPos : myLane->getLength() - myState.myPos;
    2288    619374397 :     nextTurn.first = seen;
    2289    619374397 :     nextTurn.second = nullptr;
    2290    619374397 :     bool encounteredTurn = (MSGlobals::gLateralResolution <= 0); // next turn is only needed for sublane
    2291              :     double seenNonInternal = 0;
    2292    619374397 :     double seenInternal = myLane->isInternal() ? seen : 0;
    2293    619374397 :     double vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(seen, v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    2294              :     int view = 0;
    2295              :     DriveProcessItem* lastLink = nullptr;
    2296              :     bool slowedDownForMinor = false; // whether the vehicle already had to slow down on approach to a minor link
    2297              :     double mustSeeBeforeReversal = 0;
    2298              :     // iterator over subsequent lanes and fill lfLinks until stopping distance or stopped
    2299    619374397 :     const MSLane* lane = opposite ? myLane->getParallelOpposite() : myLane;
    2300              :     assert(lane != 0);
    2301    619374397 :     const MSLane* leaderLane = myLane;
    2302    619374397 :     bool foundRailSignal = !isRail();
    2303              :     bool planningToStop = false;
    2304              : #ifdef PARALLEL_STOPWATCH
    2305              :     myLane->getStopWatch()[0].start();
    2306              : #endif
    2307              : 
    2308              :     // optionally slow down to match arrival time
    2309    619374397 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    2310    619363644 :     if (v > vMinComfortable && hasStops() && myStops.front().pars.arrival >= 0 && sfp > 0
    2311         4279 :             && v > myLane->getSpeedLimit() * sfp
    2312    619377433 :             && !myStops.front().reached) {
    2313         2786 :         const double vSlowDown = slowDownForSchedule(vMinComfortable);
    2314         5403 :         v = MIN2(v, vSlowDown);
    2315              :     }
    2316              :     auto stopIt = myStops.begin();
    2317              :     while (true) {
    2318              :         // check leader on lane
    2319              :         //  leader is given for the first edge only
    2320   1179679420 :         if (opposite &&
    2321              :                 (leaderLane->getVehicleNumberWithPartials() > 1
    2322       101210 :                  || (leaderLane != myLane && leaderLane->getVehicleNumber() > 0))) {
    2323       396287 :             ahead.clear();
    2324              :             // find opposite-driving leader that must be respected on the currently looked at lane
    2325              :             // (only looking at one lane at a time)
    2326       396287 :             const double backOffset = leaderLane == myLane ? getPositionOnLane() : leaderLane->getLength();
    2327       396287 :             const double gapOffset = leaderLane == myLane ? 0 : seen - leaderLane->getLength();
    2328       396287 :             const MSLeaderDistanceInfo cands = leaderLane->getFollowersOnConsecutive(this, backOffset, true, backOffset, MSLane::MinorLinkMode::FOLLOW_NEVER);
    2329       396287 :             MSLeaderDistanceInfo oppositeLeaders(leaderLane->getWidth(), this, 0.);
    2330       396287 :             const double minTimeToLeaveLane = MSGlobals::gSublane ? MAX2(TS, (0.5 *  myLane->getWidth() - getLateralPositionOnLane()) / getVehicleType().getMaxSpeedLat()) : TS;
    2331      1053237 :             for (int i = 0; i < cands.numSublanes(); i++) {
    2332       656950 :                 CLeaderDist cand = cands[i];
    2333       656950 :                 if (cand.first != 0) {
    2334       560257 :                     if ((cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() != leaderLane)
    2335       560731 :                             || (!cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() == leaderLane)) {
    2336              :                         // respect leaders that also drive in the opposite direction (fully or with some overlap)
    2337       354311 :                         oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - getVehicleType().getMinGap() + cand.first->getVehicleType().getMinGap() - cand.first->getVehicleType().getLength());
    2338              :                     } else {
    2339              :                         // avoid frontal collision
    2340       379058 :                         const bool assumeStopped = cand.first->isStopped() || cand.first->getWaitingSeconds() > 1;
    2341       205946 :                         const double predMaxDist = cand.first->getSpeed() + (assumeStopped ? 0 : cand.first->getCarFollowModel().getMaxAccel()) * minTimeToLeaveLane;
    2342       205946 :                         if (cand.second >= 0 && (cand.second - v * minTimeToLeaveLane - predMaxDist < 0 || assumeStopped)) {
    2343        44656 :                             oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - predMaxDist - getVehicleType().getMinGap());
    2344              :                         }
    2345              :                     }
    2346              :                 }
    2347              :             }
    2348              : #ifdef DEBUG_PLAN_MOVE
    2349              :             if (DEBUG_COND) {
    2350              :                 std::cout <<  " leaderLane=" << leaderLane->getID() << " gapOffset=" << gapOffset << " minTimeToLeaveLane=" << minTimeToLeaveLane
    2351              :                           << " cands=" << cands.toString() << " oppositeLeaders=" <<  oppositeLeaders.toString() << "\n";
    2352              :             }
    2353              : #endif
    2354       396287 :             adaptToLeaderDistance(oppositeLeaders, 0, seen, lastLink, v, vLinkPass);
    2355       396287 :         } else {
    2356   1179283133 :             if (MSGlobals::gLateralResolution > 0 && myLaneChangeModel->getShadowLane() == nullptr) {
    2357    190816397 :                 const double rightOL = getRightSideOnLane(lane) + lateralShift;
    2358    190816397 :                 const double leftOL = getLeftSideOnLane(lane) + lateralShift;
    2359              :                 const bool outsideLeft = leftOL > lane->getWidth();
    2360              : #ifdef DEBUG_PLAN_MOVE
    2361              :                 if (DEBUG_COND) {
    2362              :                     std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " rightOL=" << rightOL << " leftOL=" << leftOL << "\n";
    2363              :                 }
    2364              : #endif
    2365    190816397 :                 if (rightOL < 0 || outsideLeft) {
    2366      1265080 :                     MSLeaderInfo outsideLeaders(lane->getWidth());
    2367              :                     // if ego is driving outside lane bounds we must consider
    2368              :                     // potential leaders that are also outside bounds
    2369              :                     int sublaneOffset = 0;
    2370      1265080 :                     if (outsideLeft) {
    2371       531633 :                         sublaneOffset = MIN2(-1, -(int)ceil((leftOL - lane->getWidth()) / MSGlobals::gLateralResolution));
    2372              :                     } else {
    2373       733447 :                         sublaneOffset = MAX2(1, (int)ceil(-rightOL / MSGlobals::gLateralResolution));
    2374              :                     }
    2375      1265080 :                     outsideLeaders.setSublaneOffset(sublaneOffset);
    2376              : #ifdef DEBUG_PLAN_MOVE
    2377              :                     if (DEBUG_COND) {
    2378              :                         std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " sublaneOffset=" << sublaneOffset << " outsideLeft=" << outsideLeft << "\n";
    2379              :                     }
    2380              : #endif
    2381      5326244 :                     for (const MSVehicle* cand : lane->getVehiclesSecure()) {
    2382      1486823 :                         if ((lane != myLane || cand->getPositionOnLane() > getPositionOnLane())
    2383      4696681 :                                 && ((!outsideLeft && cand->getLeftSideOnEdge() < 0)
    2384      3209696 :                                     || (outsideLeft && cand->getLeftSideOnEdge() > lane->getEdge().getWidth()))) {
    2385        97506 :                             outsideLeaders.addLeader(cand, true);
    2386              : #ifdef DEBUG_PLAN_MOVE
    2387              :                             if (DEBUG_COND) {
    2388              :                                 std::cout << " outsideLeader=" << cand->getID() << " ahead=" << outsideLeaders.toString() << "\n";
    2389              :                             }
    2390              : #endif
    2391              :                         }
    2392              :                     }
    2393      1265080 :                     lane->releaseVehicles();
    2394      1265080 :                     if (outsideLeaders.hasVehicles()) {
    2395        26311 :                         adaptToLeaders(outsideLeaders, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2396              :                     }
    2397      1265080 :                 }
    2398              :             }
    2399   1179283133 :             adaptToLeaders(ahead, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
    2400              :         }
    2401   1179679420 :         if (lastLink != nullptr) {
    2402   1050664632 :             lastLink->myVLinkWait = MIN2(lastLink->myVLinkWait, v);
    2403              :         }
    2404              : #ifdef DEBUG_PLAN_MOVE
    2405              :         if (DEBUG_COND) {
    2406              :             std::cout << "\nv = " << v << "\n";
    2407              : 
    2408              :         }
    2409              : #endif
    2410              :         // XXX efficiently adapt to shadow leaders using neighAhead by iteration over the whole edge in parallel (lanechanger-style)
    2411   1179679420 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    2412              :             // also slow down for leaders on the shadowLane relative to the current lane
    2413      4989427 :             const MSLane* shadowLane = myLaneChangeModel->getShadowLane(leaderLane);
    2414              :             if (shadowLane != nullptr
    2415      4989427 :                     && (MSGlobals::gLateralResolution > 0 || getLateralOverlap() > POSITION_EPS
    2416              :                         // continous lane change cannot be stopped so we must adapt to the leader on the target lane
    2417       191044 :                         || myLaneChangeModel->getLaneChangeCompletion() < 0.5)) {
    2418      4448579 :                 if ((&shadowLane->getEdge() == &leaderLane->getEdge() || myLaneChangeModel->isOpposite())) {
    2419      4406406 :                     double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    2420      4406406 :                     if (myLaneChangeModel->isOpposite()) {
    2421              :                         // ego posLat is added when retrieving sublanes but it
    2422              :                         // should be negated (subtract twice to compensate)
    2423       137926 :                         latOffset = ((myLane->getWidth() + shadowLane->getWidth()) * 0.5
    2424       137926 :                                      - 2 * getLateralPositionOnLane());
    2425              : 
    2426              :                     }
    2427      4406406 :                     MSLeaderInfo shadowLeaders = shadowLane->getLastVehicleInformation(this, latOffset, lane->getLength() - seen);
    2428              : #ifdef DEBUG_PLAN_MOVE
    2429              :                     if (DEBUG_COND && myLaneChangeModel->isOpposite()) {
    2430              :                         std::cout << SIMTIME << " opposite veh=" << getID() << " shadowLane=" << shadowLane->getID() << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
    2431              :                     }
    2432              : #endif
    2433      4406406 :                     if (myLaneChangeModel->isOpposite()) {
    2434              :                         // ignore oncoming vehicles on the shadow lane
    2435       137926 :                         shadowLeaders.removeOpposite(shadowLane);
    2436              :                     }
    2437      4406406 :                     const double turningDifference = MAX2(0.0, leaderLane->getLength() - shadowLane->getLength());
    2438      4406406 :                     adaptToLeaders(shadowLeaders, latOffset, seen - turningDifference, lastLink, shadowLane, v, vLinkPass);
    2439      4448579 :                 } else if (shadowLane == myLaneChangeModel->getShadowLane() && leaderLane == myLane) {
    2440              :                     // check for leader vehicles driving in the opposite direction on the opposite-direction shadow lane
    2441              :                     // (and thus in the same direction as ego)
    2442        30313 :                     MSLeaderDistanceInfo shadowLeaders = shadowLane->getFollowersOnConsecutive(this, myLane->getOppositePos(getPositionOnLane()), true);
    2443              :                     const double latOffset = 0;
    2444              : #ifdef DEBUG_PLAN_MOVE
    2445              :                     if (DEBUG_COND) {
    2446              :                         std::cout << SIMTIME << " opposite shadows veh=" << getID() << " shadowLane=" << shadowLane->getID()
    2447              :                                   << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
    2448              :                     }
    2449              : #endif
    2450        30313 :                     shadowLeaders.fixOppositeGaps(true);
    2451              : #ifdef DEBUG_PLAN_MOVE
    2452              :                     if (DEBUG_COND) {
    2453              :                         std::cout << "   shadowLeadersFixed=" << shadowLeaders.toString() << "\n";
    2454              :                     }
    2455              : #endif
    2456        30313 :                     adaptToLeaderDistance(shadowLeaders, latOffset, seen, lastLink, v, vLinkPass);
    2457        30313 :                 }
    2458              :             }
    2459              :         }
    2460              :         // adapt to pedestrians on the same lane
    2461   1179679420 :         if (lane->getEdge().getPersons().size() > 0 && lane->hasPedestrians()) {
    2462       194950 :             const double relativePos = lane->getLength() - seen;
    2463              : #ifdef DEBUG_PLAN_MOVE
    2464              :             if (DEBUG_COND) {
    2465              :                 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
    2466              :             }
    2467              : #endif
    2468       194950 :             const double stopTime = MAX2(1.0, ceil(getSpeed() / cfModel.getMaxDecel()));
    2469       194950 :             PersonDist leader = lane->nextBlocking(relativePos,
    2470       194950 :                                                    getRightSideOnLane(lane), getRightSideOnLane(lane) + getVehicleType().getWidth(), stopTime);
    2471       194950 :             if (leader.first != 0) {
    2472        20798 :                 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
    2473        29468 :                 v = MIN2(v, stopSpeed);
    2474              : #ifdef DEBUG_PLAN_MOVE
    2475              :                 if (DEBUG_COND) {
    2476              :                     std::cout << SIMTIME << "    pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
    2477              :                 }
    2478              : #endif
    2479              :             }
    2480              :         }
    2481   1179679420 :         if (lane->getBidiLane() != nullptr) {
    2482              :             // adapt to pedestrians on the bidi lane
    2483      3788514 :             const MSLane* bidiLane = lane->getBidiLane();
    2484      3788514 :             if (bidiLane->getEdge().getPersons().size() > 0 && bidiLane->hasPedestrians()) {
    2485         1028 :                 const double relativePos = seen;
    2486              : #ifdef DEBUG_PLAN_MOVE
    2487              :                 if (DEBUG_COND) {
    2488              :                     std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
    2489              :                 }
    2490              : #endif
    2491         1028 :                 const double stopTime = ceil(getSpeed() / cfModel.getMaxDecel());
    2492         1028 :                 const double leftSideOnLane = bidiLane->getWidth() - getRightSideOnLane(lane);
    2493         1028 :                 PersonDist leader = bidiLane->nextBlocking(relativePos,
    2494         1028 :                                     leftSideOnLane - getVehicleType().getWidth(), leftSideOnLane, stopTime, true);
    2495         1028 :                 if (leader.first != 0) {
    2496          267 :                     const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
    2497          516 :                     v = MIN2(v, stopSpeed);
    2498              : #ifdef DEBUG_PLAN_MOVE
    2499              :                     if (DEBUG_COND) {
    2500              :                         std::cout << SIMTIME << "    pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
    2501              :                     }
    2502              : #endif
    2503              :                 }
    2504              :             }
    2505              :         }
    2506              :         // adapt to vehicles blocked from (urgent) lane-changing
    2507   1179679420 :         if (!opposite && lane->getEdge().hasLaneChanger()) {
    2508    582491097 :             const double vHelp = myLaneChangeModel->getCooperativeHelpSpeed(lane, seen);
    2509              : #ifdef DEBUG_PLAN_MOVE
    2510              :             if (DEBUG_COND && vHelp < v) {
    2511              :                 std::cout << SIMTIME << "   applying cooperativeHelpSpeed v=" << vHelp << "\n";
    2512              :             }
    2513              : #endif
    2514    582539660 :             v = MIN2(v, vHelp);
    2515              :         }
    2516              : 
    2517              :         // process all stops and waypoints on the current edge
    2518              :         bool foundRealStop = false;
    2519              :         while (stopIt != myStops.end()
    2520     57577631 :                 && ((&stopIt->lane->getEdge() == &lane->getEdge())
    2521     29040973 :                     || (stopIt->isOpposite && stopIt->lane->getEdge().getOppositeEdge() == &lane->getEdge()))
    2522              :                 // ignore stops that occur later in a looped route
    2523   1227123532 :                 && stopIt->edge == myCurrEdge + view) {
    2524     28490296 :             double stopDist = std::numeric_limits<double>::max();
    2525              :             const MSStop& stop = *stopIt;
    2526              :             const bool isFirstStop = stopIt == myStops.begin();
    2527              :             stopIt++;
    2528     28490296 :             if (!stop.reached || (stop.getSpeed() > 0 && keepStopping())) {
    2529              :                 // we are approaching a stop on the edge; must not drive further
    2530     10892490 :                 bool isWaypoint = stop.getSpeed() > 0;
    2531     10892490 :                 double endPos = stop.getEndPos(*this) + NUMERICAL_EPS;
    2532     10892490 :                 if (stop.parkingarea != nullptr) {
    2533              :                     // leave enough space so parking vehicles can exit
    2534      1532849 :                     const double brakePos = getBrakeGap() + lane->getLength() - seen;
    2535      1532849 :                     endPos = stop.parkingarea->getLastFreePosWithReservation(t, *this, brakePos);
    2536      9359641 :                 } else if (isWaypoint && !stop.reached) {
    2537       105009 :                     endPos = stop.pars.startPos;
    2538              :                 }
    2539     10892490 :                 stopDist = seen + endPos - lane->getLength();
    2540              : #ifdef DEBUG_STOPS
    2541              :                 if (DEBUG_COND) {
    2542              :                     std::cout << SIMTIME << " veh=" << getID() <<  " stopDist=" << stopDist << " stopLane=" << stop.lane->getID() << " stopEndPos=" << endPos << "\n";
    2543              :                 }
    2544              : #endif
    2545              :                 // regular stops are not emergencies
    2546              :                 double stopSpeed = laneMaxV;
    2547     10892490 :                 if (isWaypoint) {
    2548              :                     bool waypointWithStop = false;
    2549       120743 :                     if (stop.getUntil() > t) {
    2550              :                         // check if we have to slow down or even stop
    2551              :                         SUMOTime time2end = 0;
    2552         4051 :                         if (stop.reached) {
    2553          800 :                             time2end = TIME2STEPS((stop.pars.endPos - myState.myPos) / stop.getSpeed());
    2554              :                         } else {
    2555         3437 :                             time2end = TIME2STEPS(
    2556              :                                            // time to reach waypoint start
    2557              :                                            stopDist / ((getSpeed() + stop.getSpeed()) / 2)
    2558              :                                            // time to reach waypoint end
    2559              :                                            + (stop.pars.endPos - stop.pars.startPos) / stop.getSpeed());
    2560              :                         }
    2561         4051 :                         if (stop.getUntil() > t + time2end) {
    2562              :                             // we need to stop
    2563              :                             double distToEnd = stopDist;
    2564         3915 :                             if (!stop.reached) {
    2565         3191 :                                 distToEnd += stop.pars.endPos - stop.pars.startPos;
    2566              :                             }
    2567         3915 :                             stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), distToEnd), vMinComfortable);
    2568              :                             waypointWithStop = true;
    2569              :                         }
    2570              :                     }
    2571       120743 :                     if (stop.reached) {
    2572        14981 :                         stopSpeed = MIN2(stop.getSpeed(), stopSpeed);
    2573        14981 :                         if (myState.myPos >= stop.pars.endPos && !waypointWithStop) {
    2574          281 :                             stopDist = std::numeric_limits<double>::max();
    2575              :                         }
    2576              :                     } else {
    2577       105762 :                         stopSpeed = MIN2(MAX2(cfModel.freeSpeed(this, getSpeed(), stopDist, stop.getSpeed()), vMinComfortable), stopSpeed);
    2578       105762 :                         if (!stop.reached) {
    2579       105762 :                             stopDist += stop.pars.endPos - stop.pars.startPos;
    2580              :                         }
    2581       105762 :                         if (lastLink != nullptr) {
    2582        67542 :                             lastLink->adaptLeaveSpeed(cfModel.freeSpeed(this, vLinkPass, endPos, stop.getSpeed(), false, MSCFModel::CalcReason::FUTURE));
    2583              :                         }
    2584              :                     }
    2585              :                 } else {
    2586     10771747 :                     stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), stopDist), vMinComfortable);
    2587     10771747 :                     if (lastLink != nullptr) {
    2588      5224475 :                         lastLink->adaptLeaveSpeed(cfModel.stopSpeed(this, vLinkPass, endPos, MSCFModel::CalcReason::FUTURE));
    2589              :                     }
    2590              :                 }
    2591     10892490 :                 v = MIN2(v, stopSpeed);
    2592     10892490 :                 if (lane->isInternal()) {
    2593         6738 :                     std::vector<MSLink*>::const_iterator exitLink = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2594              :                     assert(!lane->isLinkEnd(exitLink));
    2595              :                     bool dummySetRequest;
    2596              :                     double dummyVLinkWait;
    2597         6738 :                     checkLinkLeaderCurrentAndParallel(*exitLink, lane, seen, lastLink, v, vLinkPass, dummyVLinkWait, dummySetRequest);
    2598              :                 }
    2599              : 
    2600              : #ifdef DEBUG_PLAN_MOVE
    2601              :                 if (DEBUG_COND) {
    2602              :                     std::cout << "\n" << SIMTIME << " next stop: distance = " << stopDist << " requires stopSpeed = " << stopSpeed << "\n";
    2603              : 
    2604              :                 }
    2605              : #endif
    2606     10892490 :                 if (isFirstStop) {
    2607      9976309 :                     newStopDist = stopDist;
    2608              :                     // if the vehicle is going to stop we don't need to look further
    2609              :                     // (except for trains that make use of further link-approach registration for safety purposes)
    2610      9976309 :                     if (!isWaypoint) {
    2611              :                         planningToStop = true;
    2612      9890143 :                         if (!isRail()) {
    2613      9586003 :                             lfLinks.emplace_back(v, stopDist);
    2614              :                             foundRealStop = true;
    2615      9586003 :                             break;
    2616              :                         }
    2617              :                     }
    2618              :                 }
    2619              :             }
    2620              :         }
    2621              :         if (foundRealStop) {
    2622              :             break;
    2623              :         }
    2624              : 
    2625              :         // move to next lane
    2626              :         //  get the next link used
    2627   1170093417 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
    2628   1170093417 :         if (lane->isLinkEnd(link) && myLaneChangeModel->hasBlueLight() && myCurrEdge != myRoute->end() - 1) {
    2629              :             // emergency vehicle is on the wrong lane. Obtain the link that it would use from the correct turning lane
    2630              :             const int currentIndex = lane->getIndex();
    2631              :             const MSLane* bestJump = nullptr;
    2632       193987 :             for (const LaneQ& preb : getBestLanes()) {
    2633       127580 :                 if (preb.allowsContinuation &&
    2634              :                         (bestJump == nullptr
    2635         3212 :                          || abs(currentIndex - preb.lane->getIndex()) < abs(currentIndex - bestJump->getIndex()))) {
    2636        67411 :                     bestJump = preb.lane;
    2637              :                 }
    2638              :             }
    2639        66407 :             if (bestJump != nullptr) {
    2640        66407 :                 const MSEdge* nextEdge = *(myCurrEdge + 1);
    2641       122629 :                 for (auto cand_it = bestJump->getLinkCont().begin(); cand_it != bestJump->getLinkCont().end(); cand_it++) {
    2642       117256 :                     if (&(*cand_it)->getLane()->getEdge() == nextEdge) {
    2643              :                         link = cand_it;
    2644              :                         break;
    2645              :                     }
    2646              :                 }
    2647              :             }
    2648              :         }
    2649              : 
    2650              :         // Check whether this is a turn (to save info about the next upcoming turn)
    2651   1170093417 :         if (!encounteredTurn) {
    2652    185775901 :             if (!lane->isLinkEnd(link) && lane->getLinkCont().size() > 1) {
    2653     18458104 :                 LinkDirection linkDir = (*link)->getDirection();
    2654     18458104 :                 switch (linkDir) {
    2655              :                     case LinkDirection::STRAIGHT:
    2656              :                     case LinkDirection::NODIR:
    2657              :                         break;
    2658      6793307 :                     default:
    2659      6793307 :                         nextTurn.first = seen;
    2660      6793307 :                         nextTurn.second = *link;
    2661              :                         encounteredTurn = true;
    2662              : #ifdef DEBUG_NEXT_TURN
    2663              :                         if (DEBUG_COND) {
    2664              :                             std::cout << SIMTIME << " veh '" << getID() << "' nextTurn: " << toString(linkDir)
    2665              :                                       << " at " << nextTurn.first << "m." << std::endl;
    2666              :                         }
    2667              : #endif
    2668              :                 }
    2669              :             }
    2670              :         }
    2671              : 
    2672              :         //  check whether the vehicle is on its final edge
    2673   2015007228 :         if (myCurrEdge + view + 1 == myRoute->end()
    2674   1170093417 :                 || (myParameter->arrivalEdge >= 0 && getRoutePosition() + view == myParameter->arrivalEdge)) {
    2675    325179606 :             const double arrivalSpeed = (myParameter->arrivalSpeedProcedure == ArrivalSpeedDefinition::GIVEN ?
    2676              :                                          myParameter->arrivalSpeed : laneMaxV);
    2677              :             // subtract the arrival speed from the remaining distance so we get one additional driving step with arrival speed
    2678              :             // XXX: This does not work for ballistic update refs #2579
    2679    325179606 :             const double distToArrival = seen + myArrivalPos - lane->getLength() - SPEED2DIST(arrivalSpeed);
    2680    325179606 :             const double va = MAX2(NUMERICAL_EPS, cfModel.freeSpeed(this, getSpeed(), distToArrival, arrivalSpeed));
    2681    325179606 :             v = MIN2(v, va);
    2682    325179606 :             if (lastLink != nullptr) {
    2683              :                 lastLink->adaptLeaveSpeed(va);
    2684              :             }
    2685    325179606 :             lfLinks.push_back(DriveProcessItem(v, seen, lane->getEdge().isFringe() ? 1000 : 0));
    2686    325179606 :             break;
    2687              :         }
    2688              :         // check whether the lane or the shadowLane is a dead end (allow some leeway on intersections)
    2689              :         if (lane->isLinkEnd(link)
    2690    832199931 :                 || (MSGlobals::gSublane && brakeForOverlap(*link, lane))
    2691   1676776062 :                 || (opposite && (*link)->getViaLaneOrLane()->getParallelOpposite() == nullptr
    2692       212743 :                     && !myLaneChangeModel->hasBlueLight())) {
    2693     13303065 :             double va = cfModel.stopSpeed(this, getSpeed(), seen);
    2694     13303065 :             if (lastLink != nullptr) {
    2695              :                 lastLink->adaptLeaveSpeed(va);
    2696              :             }
    2697     13303065 :             if (myLaneChangeModel->getCommittedSpeed() > 0) {
    2698       351955 :                 v = MIN2(myLaneChangeModel->getCommittedSpeed(), v);
    2699              :             } else {
    2700     25299159 :                 v = MIN2(va, v);
    2701              :             }
    2702              : #ifdef DEBUG_PLAN_MOVE
    2703              :             if (DEBUG_COND) {
    2704              :                 std::cout << "   braking for link end lane=" << lane->getID() << " seen=" << seen
    2705              :                           << " overlap=" << getLateralOverlap() << " va=" << va << " committed=" << myLaneChangeModel->getCommittedSpeed() << " v=" << v << "\n";
    2706              : 
    2707              :             }
    2708              : #endif
    2709     13303065 :             if (lane->isLinkEnd(link)) {
    2710     12713880 :                 lfLinks.emplace_back(v, seen);
    2711              :                 break;
    2712              :             }
    2713              :         }
    2714    832199931 :         lateralShift += (*link)->getLateralShift();
    2715    832199931 :         const bool yellowOrRed = (*link)->haveRed() || (*link)->haveYellow();
    2716              :         // We distinguish 3 cases when determining the point at which a vehicle stops:
    2717              :         // - allway_stop: the vehicle should stop close to the stop line but may stop at larger distance
    2718              :         // - red/yellow light: here the vehicle 'knows' that it will have priority eventually and does not need to stop on a precise spot
    2719              :         // - other types of minor links: the vehicle needs to stop as close to the junction as necessary
    2720              :         //   to minimize the time window for passing the junction. If the
    2721              :         //   vehicle 'decides' to accelerate and cannot enter the junction in
    2722              :         //   the next step, new foes may appear and cause a collision (see #1096)
    2723              :         // - major links: stopping point is irrelevant
    2724              :         double laneStopOffset;
    2725    832199931 :         const double majorStopOffset = MAX2(getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, DIST_TO_STOPLINE_EXPECT_PRIORITY), lane->getVehicleStopOffset(this));
    2726              :         // override low desired decel at yellow and red
    2727    832199931 :         const double stopDecel = yellowOrRed && !isRail() ? MAX2(MIN2(MSGlobals::gTLSYellowMinDecel, cfModel.getEmergencyDecel()), cfModel.getMaxDecel()) : cfModel.getMaxDecel();
    2728    832199931 :         const double brakeDist = cfModel.brakeGap(myState.mySpeed, stopDecel, 0);
    2729    832199931 :         const bool canBrakeBeforeLaneEnd = seen >= brakeDist;
    2730    832199931 :         const bool canBrakeBeforeStopLine = seen - lane->getVehicleStopOffset(this) >= brakeDist;
    2731    832199931 :         if (yellowOrRed) {
    2732              :             // Wait at red traffic light with full distance if possible
    2733              :             laneStopOffset = majorStopOffset;
    2734    777012183 :         } else if ((*link)->havePriority()) {
    2735              :             // On priority link, we should never stop below visibility distance
    2736    737270424 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, majorStopOffset);
    2737              :         } else {
    2738     39741759 :             double minorStopOffset = MAX2(lane->getVehicleStopOffset(this),
    2739     39741759 :                                           getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_CROSSING_GAP, MSPModel::SAFETY_GAP) - (*link)->getDistToFoePedCrossing());
    2740              : #ifdef DEBUG_PLAN_MOVE
    2741              :             if (DEBUG_COND) {
    2742              :                 std::cout << "  minorStopOffset=" << minorStopOffset << " distToFoePedCrossing=" << (*link)->getDistToFoePedCrossing() << "\n";
    2743              :             }
    2744              : #endif
    2745     39741759 :             if ((*link)->getState() == LINKSTATE_ALLWAY_STOP) {
    2746      1361777 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, 0));
    2747              :             } else {
    2748     38379982 :                 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP_MINOR, 0));
    2749              :             }
    2750              :             // On minor link, we should likewise never stop below visibility distance
    2751     39741759 :             laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, minorStopOffset);
    2752              :         }
    2753              : #ifdef DEBUG_PLAN_MOVE
    2754              :         if (DEBUG_COND) {
    2755              :             std::cout << SIMTIME << " veh=" << getID() << " desired stopOffset on lane '" << lane->getID() << "' is " << laneStopOffset << "\n";
    2756              :         }
    2757              : #endif
    2758    832199931 :         if (canBrakeBeforeLaneEnd) {
    2759              :             // avoid emergency braking if possible
    2760    804471571 :             laneStopOffset = MIN2(laneStopOffset, seen - brakeDist);
    2761              :         }
    2762              :         laneStopOffset = MAX2(POSITION_EPS, laneStopOffset);
    2763    832199931 :         double stopDist = MAX2(0., seen - laneStopOffset);
    2764     55187748 :         if (yellowOrRed && getDevice(typeid(MSDevice_GLOSA)) != nullptr
    2765          508 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->getOverrideSafety()
    2766    832199931 :                 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->isSpeedAdviceActive()) {
    2767              :             stopDist = std::numeric_limits<double>::max();
    2768              :         }
    2769    832199931 :         if (newStopDist != std::numeric_limits<double>::max()) {
    2770              :             stopDist = MAX2(stopDist, newStopDist);
    2771              :         }
    2772              : #ifdef DEBUG_PLAN_MOVE
    2773              :         if (DEBUG_COND) {
    2774              :             std::cout << SIMTIME << " veh=" << getID() << " effective stopOffset on lane '" << lane->getID()
    2775              :                       << "' is " << laneStopOffset << " (-> stopDist=" << stopDist << ")" << std::endl;
    2776              :         }
    2777              : #endif
    2778    832199931 :         if (isRail()
    2779    832199931 :                 && !lane->isInternal()) {
    2780              :             // check for train direction reversal
    2781      2949689 :             if (lane->getBidiLane() != nullptr
    2782      2949689 :                     && (*link)->getLane()->getBidiLane() == lane) {
    2783       629981 :                 double vMustReverse = getCarFollowModel().stopSpeed(this, getSpeed(), seen - POSITION_EPS);
    2784       629981 :                 if (seen < 1) {
    2785         2261 :                     mustSeeBeforeReversal = 2 * seen + getLength();
    2786              :                 }
    2787      1219258 :                 v = MIN2(v, vMustReverse);
    2788              :             }
    2789              :             // signal that is passed in the current step does not count
    2790      5899378 :             foundRailSignal |= ((*link)->getTLLogic() != nullptr
    2791       640466 :                                 && (*link)->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL
    2792      3500980 :                                 && seen > SPEED2DIST(v));
    2793              :         }
    2794              : 
    2795    832199931 :         bool canReverseEventually = false;
    2796    832199931 :         const double vReverse = checkReversal(canReverseEventually, laneMaxV, seen);
    2797    832199931 :         v = MIN2(v, vReverse);
    2798              : #ifdef DEBUG_PLAN_MOVE
    2799              :         if (DEBUG_COND) {
    2800              :             std::cout << SIMTIME << " veh=" << getID() << " canReverseEventually=" << canReverseEventually << " v=" << v << "\n";
    2801              :         }
    2802              : #endif
    2803              : 
    2804              :         // check whether we need to slow down in order to finish a continuous lane change
    2805    832199931 :         if (myLaneChangeModel->isChangingLanes()) {
    2806              :             if (    // slow down to finish lane change before a turn lane
    2807       160597 :                 ((*link)->getDirection() == LinkDirection::LEFT || (*link)->getDirection() == LinkDirection::RIGHT) ||
    2808              :                 // slow down to finish lane change before the shadow lane ends
    2809       137198 :                 (myLaneChangeModel->getShadowLane() != nullptr &&
    2810       137198 :                  (*link)->getViaLaneOrLane()->getParallelLane(myLaneChangeModel->getShadowDirection()) == nullptr)) {
    2811              :                 // XXX maybe this is too harsh. Vehicles could cut some corners here
    2812        46405 :                 const double timeRemaining = STEPS2TIME(myLaneChangeModel->remainingTime());
    2813              :                 assert(timeRemaining != 0);
    2814              :                 // XXX: Euler-logic (#860), but I couldn't identify problems from this yet (Leo). Refs. #2575
    2815        46405 :                 const double va = MAX2(cfModel.stopSpeed(this, getSpeed(), seen - POSITION_EPS),
    2816        46405 :                                        (seen - POSITION_EPS) / timeRemaining);
    2817              : #ifdef DEBUG_PLAN_MOVE
    2818              :                 if (DEBUG_COND) {
    2819              :                     std::cout << SIMTIME << " veh=" << getID() << " slowing down to finish continuous change before"
    2820              :                               << " link=" << (*link)->getViaLaneOrLane()->getID()
    2821              :                               << " timeRemaining=" << timeRemaining
    2822              :                               << " v=" << v
    2823              :                               << " va=" << va
    2824              :                               << std::endl;
    2825              :                 }
    2826              : #endif
    2827        92609 :                 v = MIN2(va, v);
    2828              :             }
    2829              :         }
    2830              : 
    2831              :         // - always issue a request to leave the intersection we are currently on
    2832    832199931 :         const bool leavingCurrentIntersection = myLane->getEdge().isInternal() && lastLink == nullptr;
    2833              :         // - do not issue a request to enter an intersection after we already slowed down for an earlier one
    2834    832199931 :         const bool abortRequestAfterMinor = slowedDownForMinor && (*link)->getInternalLaneBefore() == nullptr;
    2835              :         // - even if red, if we cannot break we should issue a request
    2836    832199931 :         bool setRequest = (v > NUMERICAL_EPS_SPEED && !abortRequestAfterMinor) || (leavingCurrentIntersection);
    2837              : 
    2838    832199931 :         double stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist, stopDecel, MSCFModel::CalcReason::CURRENT_WAIT);
    2839    832199931 :         double vLinkWait = MIN2(v, stopSpeed);
    2840              : #ifdef DEBUG_PLAN_MOVE
    2841              :         if (DEBUG_COND) {
    2842              :             std::cout
    2843              :                     << " stopDist=" << stopDist
    2844              :                     << " stopDecel=" << stopDecel
    2845              :                     << " vLinkWait=" << vLinkWait
    2846              :                     << " brakeDist=" << brakeDist
    2847              :                     << " seen=" << seen
    2848              :                     << " leaveIntersection=" << leavingCurrentIntersection
    2849              :                     << " setRequest=" << setRequest
    2850              :                     //<< std::setprecision(16)
    2851              :                     //<< " v=" << v
    2852              :                     //<< " speedEps=" << NUMERICAL_EPS_SPEED
    2853              :                     //<< std::setprecision(gPrecision)
    2854              :                     << "\n";
    2855              :         }
    2856              : #endif
    2857              : 
    2858    832199931 :         if (yellowOrRed && canBrakeBeforeStopLine && !ignoreRed(*link, canBrakeBeforeStopLine) && seen >= mustSeeBeforeReversal) {
    2859     55128177 :             if (lane->isInternal()) {
    2860        42351 :                 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2861              :             }
    2862              :             // arrivalSpeed / arrivalTime when braking for red light is only relevent for rail signal switching
    2863     55128177 :             const SUMOTime arrivalTime = getArrivalTime(t, seen, v, vLinkPass);
    2864              :             // the vehicle is able to brake in front of a yellow/red traffic light
    2865     55128177 :             lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, false, arrivalTime, vLinkWait, 0, seen, -1));
    2866              :             //lfLinks.push_back(DriveProcessItem(0, vLinkWait, vLinkWait, false, 0, 0, stopDist));
    2867     55128177 :             break;
    2868              :         }
    2869              : 
    2870    777071754 :         const MSLink* entryLink = (*link)->getCorrespondingEntryLink();
    2871    777071754 :         if (entryLink->haveRed() && ignoreRed(*link, canBrakeBeforeStopLine) && STEPS2TIME(t - entryLink->getLastStateChange()) > 2) {
    2872              :             // restrict speed when ignoring a red light
    2873       118293 :             const double redSpeed = MIN2(v, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_RED_SPEED, v));
    2874       118293 :             const double va = MAX2(redSpeed, cfModel.freeSpeed(this, getSpeed(), seen, redSpeed));
    2875       236138 :             v = MIN2(va, v);
    2876              : #ifdef DEBUG_PLAN_MOVE
    2877              :             if (DEBUG_COND) std::cout
    2878              :                         << "   ignoreRed spent=" << STEPS2TIME(t - (*link)->getLastStateChange())
    2879              :                         << " redSpeed=" << redSpeed
    2880              :                         << " va=" << va
    2881              :                         << " v=" << v
    2882              :                         << "\n";
    2883              : #endif
    2884              :         }
    2885              : 
    2886    777071754 :         checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    2887              : 
    2888    777071754 :         if (lastLink != nullptr) {
    2889              :             lastLink->adaptLeaveSpeed(laneMaxV);
    2890              :         }
    2891    777071754 :         double arrivalSpeed = vLinkPass;
    2892              :         // vehicles should decelerate when approaching a minor link
    2893              :         // - unless they are close enough to have clear visibility of all relevant foe lanes and may start to accelerate again
    2894              :         // - and unless they are so close that stopping is impossible (i.e. when a green light turns to yellow when close to the junction)
    2895              : 
    2896              :         // whether the vehicle/driver is close enough to the link to see all possible foes #2123
    2897    777071754 :         const double visibilityDistance = (*link)->getFoeVisibilityDistance();
    2898    777071754 :         const double determinedFoePresence = seen <= visibilityDistance;
    2899              : //        // VARIANT: account for time needed to recognize whether relevant vehicles are on the foe lanes. (Leo)
    2900              : //        double foeRecognitionTime = 0.0;
    2901              : //        double determinedFoePresence = seen < visibilityDistance - myState.mySpeed*foeRecognitionTime;
    2902              : 
    2903              : #ifdef DEBUG_PLAN_MOVE
    2904              :         if (DEBUG_COND) {
    2905              :             std::cout << " approaching link=" << (*link)->getViaLaneOrLane()->getID() << " prio=" << (*link)->havePriority() << " seen=" << seen << " visibilityDistance=" << visibilityDistance << " brakeDist=" << brakeDist << "\n";
    2906              :         }
    2907              : #endif
    2908              : 
    2909    777071754 :         const bool couldBrakeForMinor = !(*link)->havePriority() && brakeDist < seen && !(*link)->lastWasContMajor();
    2910     39262864 :         if (couldBrakeForMinor && !determinedFoePresence) {
    2911              :             // vehicle decelerates just enough to be able to stop if necessary and then accelerates
    2912     36647118 :             double maxSpeedAtVisibilityDist = cfModel.maximumSafeStopSpeed(visibilityDistance, cfModel.getMaxDecel(), myState.mySpeed, false, 0., false);
    2913              :             // XXX: estimateSpeedAfterDistance does not use euler-logic (thus returns a lower value than possible here...)
    2914     36647118 :             double maxArrivalSpeed = cfModel.estimateSpeedAfterDistance(visibilityDistance, maxSpeedAtVisibilityDist, cfModel.getMaxAccel());
    2915     36647118 :             arrivalSpeed = MIN2(vLinkPass, maxArrivalSpeed);
    2916              :             slowedDownForMinor = true;
    2917              : #ifdef DEBUG_PLAN_MOVE
    2918              :             if (DEBUG_COND) {
    2919              :                 std::cout << "   slowedDownForMinor maxSpeedAtVisDist=" << maxSpeedAtVisibilityDist << " maxArrivalSpeed=" << maxArrivalSpeed << " arrivalSpeed=" << arrivalSpeed << "\n";
    2920              :             }
    2921              : #endif
    2922    740424636 :         } else if ((*link)->getState() == LINKSTATE_EQUAL && myWaitingTime > 0) {
    2923              :             // check for deadlock (circular yielding)
    2924              :             //std::cout << SIMTIME << " veh=" << getID() << " check rbl-deadlock\n";
    2925         2867 :             std::pair<const SUMOVehicle*, const MSLink*> blocker = (*link)->getFirstApproachingFoe(*link);
    2926              :             //std::cout << "   blocker=" << Named::getIDSecure(blocker.first) << "\n";
    2927              :             int n = 100;
    2928         5680 :             while (blocker.second != nullptr && blocker.second != *link && n > 0) {
    2929         2813 :                 blocker = blocker.second->getFirstApproachingFoe(*link);
    2930         2813 :                 n--;
    2931              :                 //std::cout << "   blocker=" << Named::getIDSecure(blocker.first) << "\n";
    2932              :             }
    2933         2867 :             if (n == 0) {
    2934            0 :                 WRITE_WARNINGF(TL("Suspicious right_before_left junction '%'."), lane->getEdge().getToJunction()->getID());
    2935              :             }
    2936              :             //std::cout << "   blockerLink=" << blocker.second << " link=" << *link << "\n";
    2937         2867 :             if (blocker.second == *link) {
    2938          488 :                 const double threshold = (*link)->getDirection() == LinkDirection::STRAIGHT ? 0.25 : 0.75;
    2939          488 :                 if (RandHelper::rand(getRNG()) < threshold) {
    2940              :                     //std::cout << "   abort request, threshold=" << threshold << "\n";
    2941          310 :                     setRequest = false;
    2942              :                 }
    2943              :             }
    2944              :         }
    2945              : 
    2946    777071754 :         const SUMOTime arrivalTime = getArrivalTime(t, seen, v, arrivalSpeed);
    2947    777071754 :         if (couldBrakeForMinor && determinedFoePresence && (*link)->getLane()->getEdge().isRoundabout()) {
    2948       880000 :             const bool wasOpened = (*link)->opened(arrivalTime, arrivalSpeed, arrivalSpeed,
    2949       880000 :                                                    getLength(), getImpatience(),
    2950              :                                                    getCarFollowModel().getMaxDecel(),
    2951       880000 :                                                    getWaitingTime(), getLateralPositionOnLane(),
    2952              :                                                    nullptr, false, this);
    2953       880000 :             if (!wasOpened) {
    2954              :                 slowedDownForMinor = true;
    2955              :             }
    2956              : #ifdef DEBUG_PLAN_MOVE
    2957              :             if (DEBUG_COND) {
    2958              :                 std::cout << "   slowedDownForMinor at roundabout=" << (!wasOpened) << "\n";
    2959              :             }
    2960              : #endif
    2961              :         }
    2962              : 
    2963              :         // compute arrival speed and arrival time if vehicle starts braking now
    2964              :         // if stopping is possible, arrivalTime can be arbitrarily large. A small value keeps fractional times (impatience) meaningful
    2965              :         double arrivalSpeedBraking = 0;
    2966    777071754 :         const double bGap = cfModel.brakeGap(v);
    2967    777071754 :         if (seen < bGap && !isStopped() && !planningToStop) { // XXX: should this use the current speed (at least for the ballistic case)? (Leo) Refs. #2575
    2968              :             // vehicle cannot come to a complete stop in time
    2969     57207433 :             if (MSGlobals::gSemiImplicitEulerUpdate) {
    2970     54540287 :                 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeedEuler(seen, v);
    2971              :                 // due to discrete/continuous mismatch (when using Euler update) we have to ensure that braking actually helps
    2972              :                 arrivalSpeedBraking = MIN2(arrivalSpeedBraking, arrivalSpeed);
    2973              :             } else {
    2974      2667146 :                 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeed(seen, myState.mySpeed);
    2975              :             }
    2976              :         }
    2977              : 
    2978              :         // estimate leave speed for passing time computation
    2979              :         // l=linkLength, a=accel, t=continuousTime, v=vLeave
    2980              :         // l=v*t + 0.5*a*t^2, solve for t and multiply with a, then add v
    2981   1153040738 :         const double estimatedLeaveSpeed = MIN2((*link)->getViaLaneOrLane()->getVehicleMaxSpeed(this, maxVD),
    2982    777071754 :                                                 getCarFollowModel().estimateSpeedAfterDistance((*link)->getLength(), arrivalSpeed, getVehicleType().getCarFollowModel().getMaxAccel()));
    2983    777071754 :         lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, setRequest,
    2984              :                                            arrivalTime, arrivalSpeed,
    2985              :                                            arrivalSpeedBraking,
    2986              :                                            seen, estimatedLeaveSpeed));
    2987    777071754 :         if ((*link)->getViaLane() == nullptr) {
    2988              :             hadNonInternal = true;
    2989              :             ++view;
    2990              :         }
    2991              : #ifdef DEBUG_PLAN_MOVE
    2992              :         if (DEBUG_COND) {
    2993              :             std::cout << "   checkAbort setRequest=" << setRequest << " v=" << v << " seen=" << seen << " dist=" << dist
    2994              :                       << " seenNonInternal=" << seenNonInternal
    2995              :                       << " seenInternal=" << seenInternal << " length=" << vehicleLength << "\n";
    2996              :         }
    2997              : #endif
    2998              :         // we need to look ahead far enough to see available space for checkRewindLinkLanes
    2999    801234282 :         if ((!setRequest || v <= 0 || seen > dist) && hadNonInternal && seenNonInternal > MAX2(vehicleLength * CRLL_LOOK_AHEAD, vehicleLength + seenInternal) && foundRailSignal) {
    3000              :             break;
    3001              :         }
    3002              :         // get the following lane
    3003              :         lane = (*link)->getViaLaneOrLane();
    3004    560515680 :         laneMaxV = lane->getVehicleMaxSpeed(this, maxVD);
    3005    560915643 :         if (myInfluencer && !myInfluencer->considerSpeedLimit()) {
    3006              :             laneMaxV = std::numeric_limits<double>::max();
    3007              :         }
    3008              :         // the link was passed
    3009              :         // compute the velocity to use when the link is not blocked by other vehicles
    3010              :         //  the vehicle shall be not faster when reaching the next lane than allowed
    3011              :         //  speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
    3012    560515680 :         const double va = MAX2(cfModel.freeSpeed(this, getSpeed(), seen, laneMaxV), vMinComfortable);
    3013   1109764017 :         v = MIN2(va, v);
    3014              : #ifdef DEBUG_PLAN_MOVE
    3015              :         if (DEBUG_COND) {
    3016              :             std::cout << "   laneMaxV=" << laneMaxV << " freeSpeed=" << va << " v=" << v << "\n";
    3017              :         }
    3018              : #endif
    3019    560515680 :         if (lane->getEdge().isInternal()) {
    3020    242439368 :             seenInternal += lane->getLength();
    3021              :         } else {
    3022    318076312 :             seenNonInternal += lane->getLength();
    3023              :         }
    3024              :         // do not restrict results to the current vehicle to allow caching for the current time step
    3025    560515680 :         leaderLane = opposite ? lane->getParallelOpposite() : lane;
    3026    560515680 :         if (leaderLane == nullptr) {
    3027              : 
    3028              :             break;
    3029              :         }
    3030   1120610046 :         ahead = opposite ? MSLeaderInfo(leaderLane->getWidth()) : leaderLane->getLastVehicleInformation(nullptr, 0);
    3031    560305023 :         seen += lane->getLength();
    3032   1120610046 :         vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(lane->getLength(), v, cfModel.getMaxAccel()), laneMaxV); // upper bound
    3033              :         lastLink = &lfLinks.back();
    3034    560305023 :     }
    3035              : 
    3036              : //#ifdef DEBUG_PLAN_MOVE
    3037              : //    if(DEBUG_COND){
    3038              : //        std::cout << "planMoveInternal found safe speed v = " << v << std::endl;
    3039              : //    }
    3040              : //#endif
    3041              : 
    3042              : #ifdef PARALLEL_STOPWATCH
    3043              :     myLane->getStopWatch()[0].stop();
    3044              : #endif
    3045    619374397 : }
    3046              : 
    3047              : 
    3048              : double
    3049         2786 : MSVehicle::slowDownForSchedule(double vMinComfortable) const {
    3050         2786 :     const double sfp = getVehicleType().getParameter().speedFactorPremature;
    3051              :     const MSStop& stop = myStops.front();
    3052         2786 :     std::pair<double, double> timeDist = estimateTimeToNextStop();
    3053         2786 :     double arrivalDelay = SIMTIME + timeDist.first - STEPS2TIME(stop.pars.arrival);
    3054         2786 :     double t = STEPS2TIME(stop.pars.arrival - SIMSTEP);
    3055         5572 :     if (stop.pars.hasParameter(toString(SUMO_ATTR_FLEX_ARRIVAL))) {
    3056          150 :         SUMOTime flexStart = string2time(stop.pars.getParameter(toString(SUMO_ATTR_FLEX_ARRIVAL)));
    3057           75 :         arrivalDelay += STEPS2TIME(stop.pars.arrival - flexStart);
    3058           75 :         t = STEPS2TIME(flexStart - SIMSTEP);
    3059         2711 :     } else if (stop.pars.started >= 0 && MSGlobals::gUseStopStarted) {
    3060          200 :         arrivalDelay += STEPS2TIME(stop.pars.arrival - stop.pars.started);
    3061          200 :         t = STEPS2TIME(stop.pars.started - SIMSTEP);
    3062              :     }
    3063         2786 :     if (arrivalDelay < 0 && sfp < getChosenSpeedFactor()) {
    3064              :         // we can slow down to better match the schedule (and increase energy efficiency)
    3065         2721 :         const double vSlowDownMin = MAX2(myLane->getSpeedLimit() * sfp, vMinComfortable);
    3066         2721 :         const double s = timeDist.second;
    3067              :         const double b = getCarFollowModel().getMaxDecel();
    3068              :         // x = speed for arriving in t seconds
    3069              :         // u = time at full speed
    3070              :         // u * x + (t - u) * 0.5 * x = s
    3071              :         // t - u = x / b
    3072              :         // eliminate u, solve x
    3073         2721 :         const double radicand = 4 * t * t * b * b - 8 * s * b;
    3074         2721 :         const double x = radicand >= 0 ? t * b - sqrt(radicand) * 0.5 : vSlowDownMin;
    3075         2721 :         double vSlowDown = x < vSlowDownMin ? vSlowDownMin : x;
    3076              : #ifdef DEBUG_PLAN_MOVE
    3077              :         if (DEBUG_COND) {
    3078              :             std::cout << SIMTIME << " veh=" << getID() << " ad=" << arrivalDelay << " t=" << t << " vsm=" << vSlowDownMin
    3079              :                       << " r=" << radicand << " vs=" << vSlowDown << "\n";
    3080              :         }
    3081              : #endif
    3082         2721 :         return vSlowDown;
    3083           65 :     } else if (arrivalDelay > 0 && sfp > getChosenSpeedFactor()) {
    3084              :         // in principle we could up to catch up with the schedule
    3085              :         // but at this point we can only lower the speed, the
    3086              :         // information would have to be used when computing getVehicleMaxSpeed
    3087              :     }
    3088           65 :     return getMaxSpeed();
    3089              : }
    3090              : 
    3091              : SUMOTime
    3092    832199931 : MSVehicle::getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const {
    3093              :     const MSCFModel& cfModel = getCarFollowModel();
    3094              :     SUMOTime arrivalTime;
    3095    832199931 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3096              :         // @note intuitively it would make sense to compare arrivalSpeed with getSpeed() instead of v
    3097              :         // however, due to the current position update rule (ticket #860) the vehicle moves with v in this step
    3098              :         // subtract DELTA_T because t is the time at the end of this step and the movement is not carried out yet
    3099    775960906 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, v, arrivalSpeed);
    3100              :     } else {
    3101     56239025 :         arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, myState.mySpeed, arrivalSpeed);
    3102              :     }
    3103    832199931 :     if (isStopped()) {
    3104      2346633 :         arrivalTime += MAX2((SUMOTime)0, myStops.front().duration);
    3105              :     }
    3106    832199931 :     return arrivalTime;
    3107              : }
    3108              : 
    3109              : 
    3110              : void
    3111   1184647080 : MSVehicle::adaptToLeaders(const MSLeaderInfo& ahead, double latOffset,
    3112              :                           const double seen, DriveProcessItem* const lastLink,
    3113              :                           const MSLane* const lane, double& v, double& vLinkPass) const {
    3114              :     int rightmost;
    3115              :     int leftmost;
    3116   1184647080 :     ahead.getSubLanes(this, latOffset, rightmost, leftmost);
    3117              : #ifdef DEBUG_PLAN_MOVE
    3118              :     if (DEBUG_COND) std::cout << SIMTIME
    3119              :                                   << "\nADAPT_TO_LEADERS\nveh=" << getID()
    3120              :                                   << " lane=" << lane->getID()
    3121              :                                   << " latOffset=" << latOffset
    3122              :                                   << " rm=" << rightmost
    3123              :                                   << " lm=" << leftmost
    3124              :                                   << " shift=" << ahead.getSublaneOffset()
    3125              :                                   << " ahead=" << ahead.toString()
    3126              :                                   << "\n";
    3127              : #endif
    3128              :     /*
    3129              :     if (myLaneChangeModel->getCommittedSpeed() > 0) {
    3130              :         v = MIN2(v, myLaneChangeModel->getCommittedSpeed());
    3131              :         vLinkPass = MIN2(vLinkPass, myLaneChangeModel->getCommittedSpeed());
    3132              :     #ifdef DEBUG_PLAN_MOVE
    3133              :         if (DEBUG_COND) std::cout << "   hasCommitted=" << myLaneChangeModel->getCommittedSpeed() << "\n";
    3134              :     #endif
    3135              :         return;
    3136              :     }
    3137              :     */
    3138   2903619189 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3139   1718972109 :         const MSVehicle* pred = ahead[sublane];
    3140   1718972109 :         if (pred != nullptr && pred != this) {
    3141              :             // @todo avoid multiple adaptations to the same leader
    3142   1260322227 :             const double predBack = pred->getBackPositionOnLane(lane);
    3143              :             double gap = (lastLink == nullptr
    3144   1805040921 :                           ? predBack - myState.myPos - getVehicleType().getMinGap()
    3145    544718694 :                           : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3146              :             bool oncoming = false;
    3147   1260322227 :             if (myLaneChangeModel->isOpposite()) {
    3148        26799 :                 if (pred->getLaneChangeModel().isOpposite() || lane == pred->getLaneChangeModel().getShadowLane()) {
    3149              :                     // ego might and leader are driving against lane
    3150              :                     gap = (lastLink == nullptr
    3151            0 :                            ? myState.myPos - predBack - getVehicleType().getMinGap()
    3152            0 :                            : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3153              :                 } else {
    3154              :                     // ego and leader are driving in the same direction as lane (shadowlane for ego)
    3155              :                     gap = (lastLink == nullptr
    3156        27500 :                            ? predBack - (myLane->getLength() - myState.myPos) - getVehicleType().getMinGap()
    3157          701 :                            : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
    3158              :                 }
    3159   1260295428 :             } else if (pred->getLaneChangeModel().isOpposite() && pred->getLaneChangeModel().getShadowLane() != lane) {
    3160              :                 // must react to stopped / dangerous oncoming vehicles
    3161       188583 :                 gap += -pred->getVehicleType().getLength() + getVehicleType().getMinGap() - MAX2(getVehicleType().getMinGap(), pred->getVehicleType().getMinGap());
    3162              :                 // try to avoid collision in the next second
    3163       188583 :                 const double predMaxDist = pred->getSpeed() + pred->getCarFollowModel().getMaxAccel();
    3164              : #ifdef DEBUG_PLAN_MOVE
    3165              :                 if (DEBUG_COND) {
    3166              :                     std::cout << "    fixedGap=" << gap << " predMaxDist=" << predMaxDist << "\n";
    3167              :                 }
    3168              : #endif
    3169       188583 :                 if (gap < predMaxDist + getSpeed() || pred->getLane() == lane->getBidiLane()) {
    3170        20602 :                     gap -= predMaxDist;
    3171              :                 }
    3172   1260106845 :             } else if (pred->getLane() == lane->getBidiLane()) {
    3173        46867 :                 gap -= pred->getVehicleType().getLengthWithGap();
    3174              :                 oncoming = true;
    3175              :             }
    3176              : #ifdef DEBUG_PLAN_MOVE
    3177              :             if (DEBUG_COND) {
    3178              :                 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";
    3179              :             }
    3180              : #endif
    3181        46867 :             if (oncoming && gap >= 0) {
    3182        46856 :                 adaptToOncomingLeader(std::make_pair(pred, gap), lastLink, v, vLinkPass);
    3183              :             } else {
    3184   1260275371 :                 adaptToLeader(std::make_pair(pred, gap), seen, lastLink, v, vLinkPass);
    3185              :             }
    3186              :         }
    3187              :     }
    3188   1184647080 : }
    3189              : 
    3190              : void
    3191       426600 : MSVehicle::adaptToLeaderDistance(const MSLeaderDistanceInfo& ahead, double latOffset,
    3192              :                                  double seen,
    3193              :                                  DriveProcessItem* const lastLink,
    3194              :                                  double& v, double& vLinkPass) const {
    3195              :     int rightmost;
    3196              :     int leftmost;
    3197       426600 :     ahead.getSubLanes(this, latOffset, rightmost, leftmost);
    3198              : #ifdef DEBUG_PLAN_MOVE
    3199              :     if (DEBUG_COND) std::cout << SIMTIME
    3200              :                                   << "\nADAPT_TO_LEADERS_DISTANCE\nveh=" << getID()
    3201              :                                   << " latOffset=" << latOffset
    3202              :                                   << " rm=" << rightmost
    3203              :                                   << " lm=" << leftmost
    3204              :                                   << " ahead=" << ahead.toString()
    3205              :                                   << "\n";
    3206              : #endif
    3207      1045810 :     for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
    3208       619210 :         CLeaderDist predDist = ahead[sublane];
    3209       619210 :         const MSVehicle* pred = predDist.first;
    3210       619210 :         if (pred != nullptr && pred != this) {
    3211              : #ifdef DEBUG_PLAN_MOVE
    3212              :             if (DEBUG_COND) {
    3213              :                 std::cout << "     pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << predDist.second << "\n";
    3214              :             }
    3215              : #endif
    3216       392816 :             adaptToLeader(predDist, seen, lastLink, v, vLinkPass);
    3217              :         }
    3218              :     }
    3219       426600 : }
    3220              : 
    3221              : 
    3222              : void
    3223   1260668187 : MSVehicle::adaptToLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3224              :                          double seen,
    3225              :                          DriveProcessItem* const lastLink,
    3226              :                          double& v, double& vLinkPass) const {
    3227   1260668187 :     if (leaderInfo.first != 0) {
    3228   1260668187 :         if (ignoreFoe(leaderInfo.first)) {
    3229              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3230              :             if (DEBUG_COND) {
    3231              :                 std::cout << "  foe ignored\n";
    3232              :             }
    3233              : #endif
    3234              :             return;
    3235              :         }
    3236              :         const MSCFModel& cfModel = getCarFollowModel();
    3237              :         double vsafeLeader = 0;
    3238   1260667367 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3239              :             vsafeLeader = -std::numeric_limits<double>::max();
    3240              :         }
    3241              :         bool backOnRoute = true;
    3242   1260667367 :         if (leaderInfo.second < 0 && lastLink != nullptr && lastLink->myLink != nullptr) {
    3243              :             backOnRoute = false;
    3244              :             // this can either be
    3245              :             // a) a merging situation (leader back is is not our route) or
    3246              :             // b) a minGap violation / collision
    3247              :             MSLane* current = lastLink->myLink->getViaLaneOrLane();
    3248       256155 :             if (leaderInfo.first->getBackLane() == current) {
    3249              :                 backOnRoute = true;
    3250              :             } else {
    3251       600719 :                 for (MSLane* lane : getBestLanesContinuation()) {
    3252       546708 :                     if (lane == current) {
    3253              :                         break;
    3254              :                     }
    3255       397021 :                     if (leaderInfo.first->getBackLane() == lane) {
    3256              :                         backOnRoute = true;
    3257              :                     }
    3258              :                 }
    3259              :             }
    3260              : #ifdef DEBUG_PLAN_MOVE
    3261              :             if (DEBUG_COND) {
    3262              :                 std::cout << SIMTIME << " current=" << current->getID() << " leaderBackLane=" << leaderInfo.first->getBackLane()->getID() << " backOnRoute=" << backOnRoute << "\n";
    3263              :             }
    3264              : #endif
    3265       203698 :             if (!backOnRoute) {
    3266       118232 :                 double stopDist = seen - current->getLength() - POSITION_EPS;
    3267       118232 :                 if (lastLink->myLink->getInternalLaneBefore() != nullptr) {
    3268              :                     // do not drive onto the junction conflict area
    3269       100265 :                     stopDist -= lastLink->myLink->getInternalLaneBefore()->getLength();
    3270              :                 }
    3271       118232 :                 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), stopDist);
    3272              :             }
    3273              :         }
    3274       170689 :         if (backOnRoute) {
    3275   1260549135 :             vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3276              :         }
    3277   1260667367 :         if (lastLink != nullptr) {
    3278    544711455 :             const double futureVSafe = cfModel.followSpeed(this, lastLink->accelV, leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first, MSCFModel::CalcReason::FUTURE);
    3279              :             lastLink->adaptLeaveSpeed(futureVSafe);
    3280              : #ifdef DEBUG_PLAN_MOVE
    3281              :             if (DEBUG_COND) {
    3282              :                 std::cout << "   vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
    3283              :             }
    3284              : #endif
    3285              :         }
    3286   1260667367 :         v = MIN2(v, vsafeLeader);
    3287   2169399864 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3288              : #ifdef DEBUG_PLAN_MOVE
    3289              :         if (DEBUG_COND) std::cout
    3290              :                     << SIMTIME
    3291              :                     //std::cout << std::setprecision(10);
    3292              :                     << " veh=" << getID()
    3293              :                     << " lead=" << leaderInfo.first->getID()
    3294              :                     << " leadSpeed=" << leaderInfo.first->getSpeed()
    3295              :                     << " gap=" << leaderInfo.second
    3296              :                     << " leadLane=" << leaderInfo.first->getLane()->getID()
    3297              :                     << " predPos=" << leaderInfo.first->getPositionOnLane()
    3298              :                     << " myLane=" << myLane->getID()
    3299              :                     << " v=" << v
    3300              :                     << " vSafeLeader=" << vsafeLeader
    3301              :                     << " vLinkPass=" << vLinkPass
    3302              :                     << "\n";
    3303              : #endif
    3304              :     }
    3305              : }
    3306              : 
    3307              : 
    3308              : void
    3309     17559258 : MSVehicle::adaptToJunctionLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3310              :                                  const double seen, DriveProcessItem* const lastLink,
    3311              :                                  const MSLane* const lane, double& v, double& vLinkPass,
    3312              :                                  double distToCrossing) const {
    3313     17559258 :     if (leaderInfo.first != 0) {
    3314     17559258 :         if (ignoreFoe(leaderInfo.first)) {
    3315              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3316              :             if (DEBUG_COND) {
    3317              :                 std::cout << "  junction foe ignored\n";
    3318              :             }
    3319              : #endif
    3320              :             return;
    3321              :         }
    3322              :         const MSCFModel& cfModel = getCarFollowModel();
    3323              :         double vsafeLeader = 0;
    3324     17559222 :         if (!MSGlobals::gSemiImplicitEulerUpdate) {
    3325              :             vsafeLeader = -std::numeric_limits<double>::max();
    3326              :         }
    3327     17559222 :         if (leaderInfo.second >= 0) {
    3328     14476303 :             if (hasDeparted()) {
    3329     14471834 :                 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3330              :             } else {
    3331              :                 // called in the context of MSLane::isInsertionSuccess
    3332         4469 :                 vsafeLeader = cfModel.insertionFollowSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
    3333              :             }
    3334      3082919 :         } else if (leaderInfo.first != this) {
    3335              :             // the leading, in-lapping vehicle is occupying the complete next lane
    3336              :             // stop before entering this lane
    3337      2661770 :             vsafeLeader = cfModel.stopSpeed(this, getSpeed(), seen - lane->getLength() - POSITION_EPS);
    3338              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3339              :             if (DEBUG_COND) {
    3340              :                 std::cout << SIMTIME << " veh=" << getID() << "  stopping before junction: lane=" << lane->getID() << " seen=" << seen
    3341              :                           << " laneLength=" << lane->getLength()
    3342              :                           << " stopDist=" << seen - lane->getLength()  - POSITION_EPS
    3343              :                           << " vsafeLeader=" << vsafeLeader
    3344              :                           << " distToCrossing=" << distToCrossing
    3345              :                           << "\n";
    3346              :             }
    3347              : #endif
    3348              :         }
    3349     17559222 :         if (distToCrossing >= 0) {
    3350              :             // can the leader still stop in the way?
    3351      5255007 :             const double vStop = cfModel.stopSpeed(this, getSpeed(), distToCrossing - getVehicleType().getMinGap());
    3352      5255007 :             if (leaderInfo.first == this) {
    3353              :                 // braking for pedestrian
    3354       409830 :                 const double vStopCrossing = cfModel.stopSpeed(this, getSpeed(), distToCrossing);
    3355              :                 vsafeLeader = vStopCrossing;
    3356              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3357              :                 if (DEBUG_COND) {
    3358              :                     std::cout << "  breaking for pedestrian distToCrossing=" << distToCrossing << " vStopCrossing=" << vStopCrossing << "\n";
    3359              :                 }
    3360              : #endif
    3361       409830 :                 if (lastLink != nullptr) {
    3362              :                     lastLink->adaptStopSpeed(vsafeLeader);
    3363              :                 }
    3364      4845177 :             } else if (leaderInfo.second == -std::numeric_limits<double>::max()) {
    3365              :                 // drive up to the crossing point and stop
    3366              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3367              :                 if (DEBUG_COND) {
    3368              :                     std::cout << "  stop at crossing point for critical leader vStop=" << vStop << "\n";
    3369              :                 };
    3370              : #endif
    3371              :                 vsafeLeader = MAX2(vsafeLeader, vStop);
    3372              :             } else {
    3373      4786955 :                 const double leaderDistToCrossing = distToCrossing - leaderInfo.second;
    3374              :                 // estimate the time at which the leader has gone past the crossing point
    3375      4786955 :                 const double leaderPastCPTime = leaderDistToCrossing / MAX2(leaderInfo.first->getSpeed(), SUMO_const_haltingSpeed);
    3376              :                 // reach distToCrossing after that time
    3377              :                 // avgSpeed * leaderPastCPTime = distToCrossing
    3378              :                 // ballistic: avgSpeed = (getSpeed + vFinal) / 2
    3379      4786955 :                 const double vFinal = MAX2(getSpeed(), 2 * (distToCrossing - getVehicleType().getMinGap()) / leaderPastCPTime - getSpeed());
    3380      4786955 :                 const double v2 = getSpeed() + ACCEL2SPEED((vFinal - getSpeed()) / leaderPastCPTime);
    3381              :                 vsafeLeader = MAX2(vsafeLeader, MIN2(v2, vStop));
    3382              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3383              :                 if (DEBUG_COND) {
    3384              :                     std::cout << "    driving up to the crossing point (distToCrossing=" << distToCrossing << ")"
    3385              :                               << " leaderPastCPTime=" << leaderPastCPTime
    3386              :                               << " vFinal=" << vFinal
    3387              :                               << " v2=" << v2
    3388              :                               << " vStop=" << vStop
    3389              :                               << " vsafeLeader=" << vsafeLeader << "\n";
    3390              :                 }
    3391              : #endif
    3392              :             }
    3393              :         }
    3394     17149392 :         if (lastLink != nullptr) {
    3395              :             lastLink->adaptLeaveSpeed(vsafeLeader);
    3396              :         }
    3397     17559222 :         v = MIN2(v, vsafeLeader);
    3398     32786100 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3399              : #ifdef DEBUG_PLAN_MOVE
    3400              :         if (DEBUG_COND) std::cout
    3401              :                     << SIMTIME
    3402              :                     //std::cout << std::setprecision(10);
    3403              :                     << " veh=" << getID()
    3404              :                     << " lead=" << leaderInfo.first->getID()
    3405              :                     << " leadSpeed=" << leaderInfo.first->getSpeed()
    3406              :                     << " gap=" << leaderInfo.second
    3407              :                     << " leadLane=" << leaderInfo.first->getLane()->getID()
    3408              :                     << " predPos=" << leaderInfo.first->getPositionOnLane()
    3409              :                     << " seen=" << seen
    3410              :                     << " lane=" << lane->getID()
    3411              :                     << " myLane=" << myLane->getID()
    3412              :                     << " dTC=" << distToCrossing
    3413              :                     << " v=" << v
    3414              :                     << " vSafeLeader=" << vsafeLeader
    3415              :                     << " vLinkPass=" << vLinkPass
    3416              :                     << "\n";
    3417              : #endif
    3418              :     }
    3419              : }
    3420              : 
    3421              : 
    3422              : void
    3423        46856 : MSVehicle::adaptToOncomingLeader(const std::pair<const MSVehicle*, double> leaderInfo,
    3424              :                                  DriveProcessItem* const lastLink,
    3425              :                                  double& v, double& vLinkPass) const {
    3426        46856 :     if (leaderInfo.first != 0) {
    3427        46856 :         if (ignoreFoe(leaderInfo.first)) {
    3428              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3429              :             if (DEBUG_COND) {
    3430              :                 std::cout << "  oncoming foe ignored\n";
    3431              :             }
    3432              : #endif
    3433              :             return;
    3434              :         }
    3435              :         const MSCFModel& cfModel = getCarFollowModel();
    3436              :         const MSVehicle* lead = leaderInfo.first;
    3437              :         const MSCFModel& cfModelL = lead->getCarFollowModel();
    3438              :         // assume the leader reacts symmetrically (neither stopping instantly nor ignoring ego)
    3439        46737 :         const double leaderBrakeGap = cfModelL.brakeGap(lead->getSpeed(), cfModelL.getMaxDecel(), 0);
    3440        46737 :         const double egoBrakeGap = cfModel.brakeGap(getSpeed(), cfModel.getMaxDecel(), 0);
    3441        46737 :         const double gapSum = leaderBrakeGap + egoBrakeGap;
    3442              :         // ensure that both vehicles can leave an intersection if they are currently on it
    3443        46737 :         double egoExit = getDistanceToLeaveJunction();
    3444        46737 :         const double leaderExit = lead->getDistanceToLeaveJunction();
    3445              :         double gap = leaderInfo.second;
    3446        46737 :         if (egoExit + leaderExit < gap) {
    3447        42973 :             gap -= egoExit + leaderExit;
    3448              :         } else {
    3449              :             egoExit = 0;
    3450              :         }
    3451              :         // split any distance in excess of brakeGaps evenly
    3452        46737 :         const double freeGap = MAX2(0.0, gap - gapSum);
    3453              :         const double splitGap = MIN2(gap, gapSum);
    3454              :         // assume remaining distance is allocated in proportion to braking distance
    3455        46737 :         const double gapRatio = gapSum > 0 ? egoBrakeGap / gapSum : 0.5;
    3456        46737 :         const double vsafeLeader = cfModel.stopSpeed(this, getSpeed(), splitGap * gapRatio + egoExit + 0.5 * freeGap);
    3457        46737 :         if (lastLink != nullptr) {
    3458        27133 :             const double futureVSafe = cfModel.stopSpeed(this, lastLink->accelV, leaderInfo.second, MSCFModel::CalcReason::FUTURE);
    3459              :             lastLink->adaptLeaveSpeed(futureVSafe);
    3460              : #ifdef DEBUG_PLAN_MOVE
    3461              :             if (DEBUG_COND) {
    3462              :                 std::cout << "   vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
    3463              :             }
    3464              : #endif
    3465              :         }
    3466        46737 :         v = MIN2(v, vsafeLeader);
    3467        92274 :         vLinkPass = MIN2(vLinkPass, vsafeLeader);
    3468              : #ifdef DEBUG_PLAN_MOVE
    3469              :         if (DEBUG_COND) std::cout
    3470              :                     << SIMTIME
    3471              :                     //std::cout << std::setprecision(10);
    3472              :                     << " veh=" << getID()
    3473              :                     << " oncomingLead=" << lead->getID()
    3474              :                     << " leadSpeed=" << lead->getSpeed()
    3475              :                     << " gap=" << leaderInfo.second
    3476              :                     << " gap2=" << gap
    3477              :                     << " gapRatio=" << gapRatio
    3478              :                     << " leadLane=" << lead->getLane()->getID()
    3479              :                     << " predPos=" << lead->getPositionOnLane()
    3480              :                     << " myLane=" << myLane->getID()
    3481              :                     << " v=" << v
    3482              :                     << " vSafeLeader=" << vsafeLeader
    3483              :                     << " vLinkPass=" << vLinkPass
    3484              :                     << "\n";
    3485              : #endif
    3486              :     }
    3487              : }
    3488              : 
    3489              : 
    3490              : void
    3491    777120843 : MSVehicle::checkLinkLeaderCurrentAndParallel(const MSLink* link, const MSLane* lane, double seen,
    3492              :         DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest) const {
    3493    777120843 :     if (MSGlobals::gUsingInternalLanes && (myInfluencer == nullptr || myInfluencer->getRespectJunctionLeaderPriority())) {
    3494              :         // we want to pass the link but need to check for foes on internal lanes
    3495    777014883 :         checkLinkLeader(link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
    3496    777014883 :         if (myLaneChangeModel->getShadowLane() != nullptr) {
    3497      3135197 :             const MSLink* const parallelLink = link->getParallelLink(myLaneChangeModel->getShadowDirection());
    3498      3135197 :             if (parallelLink != nullptr) {
    3499      2179087 :                 checkLinkLeader(parallelLink, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest, true);
    3500              :             }
    3501              :         }
    3502              :     }
    3503              : 
    3504    777120843 : }
    3505              : 
    3506              : void
    3507    779429540 : MSVehicle::checkLinkLeader(const MSLink* link, const MSLane* lane, double seen,
    3508              :                            DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest,
    3509              :                            bool isShadowLink) const {
    3510              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3511              :     if (DEBUG_COND) {
    3512              :         gDebugFlag1 = true;    // See MSLink::getLeaderInfo
    3513              :     }
    3514              : #endif
    3515    779429540 :     const MSLink::LinkLeaders linkLeaders = link->getLeaderInfo(this, seen, nullptr, isShadowLink);
    3516              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3517              :     if (DEBUG_COND) {
    3518              :         gDebugFlag1 = false;    // See MSLink::getLeaderInfo
    3519              :     }
    3520              : #endif
    3521    797940040 :     for (MSLink::LinkLeaders::const_iterator it = linkLeaders.begin(); it != linkLeaders.end(); ++it) {
    3522              :         // the vehicle to enter the junction first has priority
    3523     18510500 :         const MSVehicle* leader = (*it).vehAndGap.first;
    3524     18510500 :         if (leader == nullptr) {
    3525              :             // leader is a pedestrian. Passing 'this' as a dummy.
    3526              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3527              :             if (DEBUG_COND) {
    3528              :                 std::cout << SIMTIME << " veh=" << getID() << " is blocked on link to " << link->getViaLaneOrLane()->getID() << " by pedestrian. dist=" << it->distToCrossing << "\n";
    3529              :             }
    3530              : #endif
    3531       421845 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3532       421845 :                     && getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) >= RandHelper::rand(getRNG())) {
    3533              : #ifdef DEBUG_PLAN_MOVE
    3534              :                 if (DEBUG_COND) {
    3535              :                     std::cout << SIMTIME << " veh=" << getID() << " is ignoring pedestrian (jmIgnoreJunctionFoeProb)\n";
    3536              :                 }
    3537              : #endif
    3538          696 :                 continue;
    3539              :             }
    3540       421149 :             adaptToJunctionLeader(std::make_pair(this, -1), seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3541              :             // if blocked by a pedestrian for too long we must yield our request
    3542       421149 :             if (v < SUMO_const_haltingSpeed && getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME)) {
    3543        75340 :                 setRequest = false;
    3544              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3545              :                 if (DEBUG_COND) {
    3546              :                     std::cout << "   aborting request\n";
    3547              :                 }
    3548              : #endif
    3549              :             }
    3550     18088655 :         } else if (isLeader(link, leader, (*it).vehAndGap.second) || (*it).inTheWay()) {
    3551     18040682 :             if (getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) > 0
    3552     18040682 :                     && getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB, 0) >= RandHelper::rand(getRNG())) {
    3553              : #ifdef DEBUG_PLAN_MOVE
    3554              :                 if (DEBUG_COND) {
    3555              :                     std::cout << SIMTIME << " veh=" << getID() << " is ignoring linkLeader=" << leader->getID() << " (jmIgnoreJunctionFoeProb)\n";
    3556              :                 }
    3557              : #endif
    3558         2209 :                 continue;
    3559              :             }
    3560     24840639 :             if (MSGlobals::gLateralResolution > 0 &&
    3561              :                     // sibling link (XXX: could also be partial occupator where this check fails)
    3562      6802166 :                     &leader->getLane()->getEdge() == &lane->getEdge()) {
    3563              :                 // check for sublane obstruction (trivial for sibling link leaders)
    3564              :                 const MSLane* conflictLane = link->getInternalLaneBefore();
    3565       931230 :                 MSLeaderInfo linkLeadersAhead = MSLeaderInfo(conflictLane->getWidth());
    3566       931230 :                 linkLeadersAhead.addLeader(leader, false, 0); // assume sibling lane has the same geometry as the leader lane
    3567       931230 :                 const double latOffset = isShadowLink ? (getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge()) : 0;
    3568              :                 // leader is neither on lane nor conflictLane (the conflict is only established geometrically)
    3569       931230 :                 adaptToLeaders(linkLeadersAhead, latOffset, seen, lastLink, leader->getLane(), v, vLinkPass);
    3570              : #ifdef DEBUG_PLAN_MOVE
    3571              :                 if (DEBUG_COND) {
    3572              :                     std::cout << SIMTIME << " veh=" << getID()
    3573              :                               << " siblingFoe link=" << link->getViaLaneOrLane()->getID()
    3574              :                               << " isShadowLink=" << isShadowLink
    3575              :                               << " lane=" << lane->getID()
    3576              :                               << " foe=" << leader->getID()
    3577              :                               << " foeLane=" << leader->getLane()->getID()
    3578              :                               << " latOffset=" << latOffset
    3579              :                               << " latOffsetFoe=" << leader->getLatOffset(lane)
    3580              :                               << " linkLeadersAhead=" << linkLeadersAhead.toString()
    3581              :                               << "\n";
    3582              :                 }
    3583              : #endif
    3584       931230 :             } else {
    3585              : #ifdef DEBUG_PLAN_MOVE
    3586              :                 if (DEBUG_COND) {
    3587              :                     std::cout << SIMTIME << " veh=" << getID() << " linkLeader=" << leader->getID() << " gap=" << it->vehAndGap.second
    3588              :                               << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
    3589              :                               << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
    3590              :                               << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
    3591              :                               << "\n";
    3592              :                 }
    3593              : #endif
    3594     17107243 :                 adaptToJunctionLeader(it->vehAndGap, seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
    3595              :             }
    3596     18038473 :             if (lastLink != nullptr) {
    3597              :                 // we are not yet on the junction with this linkLeader.
    3598              :                 // at least we can drive up to the previous link and stop there
    3599     34678614 :                 v = MAX2(v, lastLink->myVLinkWait);
    3600              :             }
    3601              :             // if blocked by a leader from the same or next lane we must yield our request
    3602              :             // also, if blocked by a stopped or blocked leader
    3603     18038473 :             if (v < SUMO_const_haltingSpeed
    3604              :                     //&& leader->getSpeed() < SUMO_const_haltingSpeed
    3605     18038473 :                     && (leader->getLane()->getLogicalPredecessorLane() == myLane->getLogicalPredecessorLane()
    3606      9921747 :                         || leader->getLane()->getLogicalPredecessorLane() == myLane
    3607      7744811 :                         || leader->isStopped()
    3608      7666340 :                         || leader->getWaitingTime() > TIME2STEPS(JUNCTION_BLOCKAGE_TIME))) {
    3609      4164232 :                 setRequest = false;
    3610              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3611              :                 if (DEBUG_COND) {
    3612              :                     std::cout << "   aborting request\n";
    3613              :                 }
    3614              : #endif
    3615      4164232 :                 if (lastLink != nullptr && leader->getLane()->getLogicalPredecessorLane() == myLane) {
    3616              :                     // we are not yet on the junction so must abort that request as well
    3617              :                     // (or maybe we are already on the junction and the leader is a partial occupator beyond)
    3618      2165153 :                     lastLink->mySetRequest = false;
    3619              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3620              :                     if (DEBUG_COND) {
    3621              :                         std::cout << "      aborting previous request\n";
    3622              :                     }
    3623              : #endif
    3624              :                 }
    3625              :             }
    3626              :         }
    3627              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    3628              :         else {
    3629              :             if (DEBUG_COND) {
    3630              :                 std::cout << SIMTIME << " veh=" << getID() << " ignoring leader " << leader->getID() << " gap=" << (*it).vehAndGap.second << " dtC=" << (*it).distToCrossing
    3631              :                           << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
    3632              :                           << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
    3633              :                           << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
    3634              :                           << "\n";
    3635              :             }
    3636              :         }
    3637              : #endif
    3638              :     }
    3639              :     // if this is the link between two internal lanes we may have to slow down for pedestrians
    3640    779429540 :     vLinkWait = MIN2(vLinkWait, v);
    3641    779429540 : }
    3642              : 
    3643              : 
    3644              : double
    3645     99104991 : MSVehicle::getDeltaPos(const double accel) const {
    3646     99104991 :     double vNext = myState.mySpeed + ACCEL2SPEED(accel);
    3647     99104991 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3648              :         // apply implicit Euler positional update
    3649            0 :         return SPEED2DIST(MAX2(vNext, 0.));
    3650              :     } else {
    3651              :         // apply ballistic update
    3652     99104991 :         if (vNext >= 0) {
    3653              :             // assume constant acceleration during this time step
    3654     98484977 :             return SPEED2DIST(myState.mySpeed + 0.5 * ACCEL2SPEED(accel));
    3655              :         } else {
    3656              :             // negative vNext indicates a stop within the middle of time step
    3657              :             // The corresponding stop time is s = mySpeed/deceleration \in [0,dt], and the
    3658              :             // covered distance is therefore deltaPos = mySpeed*s - 0.5*deceleration*s^2.
    3659              :             // Here, deceleration = (myState.mySpeed - vNext)/dt is the constant deceleration
    3660              :             // until the vehicle stops.
    3661       620014 :             return -SPEED2DIST(0.5 * myState.mySpeed * myState.mySpeed / ACCEL2SPEED(accel));
    3662              :         }
    3663              :     }
    3664              : }
    3665              : 
    3666              : void
    3667    619374397 : MSVehicle::processLinkApproaches(double& vSafe, double& vSafeMin, double& vSafeMinDist) {
    3668              : 
    3669              :     // Speed limit due to zipper merging
    3670              :     double vSafeZipper = std::numeric_limits<double>::max();
    3671              : 
    3672    619374397 :     myHaveToWaitOnNextLink = false;
    3673              :     bool canBrakeVSafeMin = false;
    3674              : 
    3675              :     // Get safe velocities from DriveProcessItems.
    3676              :     assert(myLFLinkLanes.size() != 0 || isRemoteControlled());
    3677   1239741678 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    3678   1065673401 :         MSLink* const link = dpi.myLink;
    3679              : 
    3680              : #ifdef DEBUG_EXEC_MOVE
    3681              :         if (DEBUG_COND) {
    3682              :             std::cout
    3683              :                     << SIMTIME
    3684              :                     << " veh=" << getID()
    3685              :                     << " link=" << (link == 0 ? "NULL" : link->getViaLaneOrLane()->getID())
    3686              :                     << " req=" << dpi.mySetRequest
    3687              :                     << " vP=" << dpi.myVLinkPass
    3688              :                     << " vW=" << dpi.myVLinkWait
    3689              :                     << " d=" << dpi.myDistance
    3690              :                     << "\n";
    3691              :             gDebugFlag1 = true; // See MSLink_DEBUG_OPENED
    3692              :         }
    3693              : #endif
    3694              : 
    3695              :         // the vehicle must change the lane on one of the next lanes (XXX: refs to code further below???, Leo)
    3696   1065673401 :         if (link != nullptr && dpi.mySetRequest) {
    3697              : 
    3698              :             const LinkState ls = link->getState();
    3699              :             // vehicles should brake when running onto a yellow light if the distance allows to halt in front
    3700              :             const bool yellow = link->haveYellow();
    3701    640480137 :             const bool canBrake = (dpi.myDistance > getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)
    3702    640480137 :                                    || (MSGlobals::gSemiImplicitEulerUpdate && myState.mySpeed < ACCEL2SPEED(getCarFollowModel().getMaxDecel())));
    3703              :             assert(link->getLaneBefore() != nullptr);
    3704    640480137 :             const bool beyondStopLine = dpi.myDistance < link->getLaneBefore()->getVehicleStopOffset(this);
    3705    640480137 :             const bool ignoreRedLink = ignoreRed(link, canBrake) || beyondStopLine;
    3706    640480137 :             if (yellow && canBrake && !ignoreRedLink) {
    3707           10 :                 vSafe = dpi.myVLinkWait;
    3708           10 :                 myHaveToWaitOnNextLink = true;
    3709              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3710              :                 if (DEBUG_COND) {
    3711              :                     std::cout << SIMTIME << " veh=" << getID() << " haveToWait (yellow)\n";
    3712              :                 }
    3713              : #endif
    3714     20112856 :                 break;
    3715              :             }
    3716    640480127 :             const bool influencerPrio = (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority());
    3717              :             MSLink::BlockingFoes collectFoes;
    3718    640480127 :             bool opened = (yellow || influencerPrio
    3719   1921119953 :                            || link->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3720    640319913 :                                            getVehicleType().getLength(),
    3721    612614057 :                                            canBrake ? getImpatience() : 1,
    3722              :                                            getCarFollowModel().getMaxDecel(),
    3723    640319913 :                                            getWaitingTimeFor(link), getLateralPositionOnLane(),
    3724              :                                            ls == LINKSTATE_ZIPPER ? &collectFoes : nullptr,
    3725    640319913 :                                            ignoreRedLink, this, dpi.myDistance));
    3726    635226186 :             if (opened && myLaneChangeModel->getShadowLane() != nullptr) {
    3727      1903194 :                 const MSLink* const parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    3728      1903194 :                 if (parallelLink != nullptr) {
    3729      1179518 :                     const double shadowLatPos = getLateralPositionOnLane() - myLaneChangeModel->getShadowDirection() * 0.5 * (
    3730      1179518 :                                                     myLane->getWidth() + myLaneChangeModel->getShadowLane()->getWidth());
    3731      2358233 :                     opened = yellow || influencerPrio || (opened && parallelLink->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    3732      1178715 :                                                           getVehicleType().getLength(), getImpatience(),
    3733              :                                                           getCarFollowModel().getMaxDecel(),
    3734              :                                                           getWaitingTimeFor(link), shadowLatPos, nullptr,
    3735      1178715 :                                                           ignoreRedLink, this, dpi.myDistance));
    3736              : #ifdef DEBUG_EXEC_MOVE
    3737              :                     if (DEBUG_COND) {
    3738              :                         std::cout << SIMTIME
    3739              :                                   << " veh=" << getID()
    3740              :                                   << " shadowLane=" << myLaneChangeModel->getShadowLane()->getID()
    3741              :                                   << " shadowDir=" << myLaneChangeModel->getShadowDirection()
    3742              :                                   << " parallelLink=" << (parallelLink == 0 ? "NULL" : parallelLink->getViaLaneOrLane()->getID())
    3743              :                                   << " opened=" << opened
    3744              :                                   << "\n";
    3745              :                     }
    3746              : #endif
    3747              :                 }
    3748              :             }
    3749              :             // vehicles should decelerate when approaching a minor link
    3750              : #ifdef DEBUG_EXEC_MOVE
    3751              :             if (DEBUG_COND) {
    3752              :                 std::cout << SIMTIME
    3753              :                           << "   opened=" << opened
    3754              :                           << " influencerPrio=" << influencerPrio
    3755              :                           << " linkPrio=" << link->havePriority()
    3756              :                           << " lastContMajor=" << link->lastWasContMajor()
    3757              :                           << " isCont=" << link->isCont()
    3758              :                           << " ignoreRed=" << ignoreRedLink
    3759              :                           << "\n";
    3760              :             }
    3761              : #endif
    3762              :             double visibilityDistance = link->getFoeVisibilityDistance();
    3763    640480127 :             bool determinedFoePresence = dpi.myDistance <= visibilityDistance;
    3764    640480127 :             if (opened && !influencerPrio && !link->havePriority() && !link->lastWasContMajor() && !link->isCont() && !ignoreRedLink) {
    3765     16963382 :                 if (!determinedFoePresence && (canBrake || !yellow)) {
    3766     16021574 :                     vSafe = dpi.myVLinkWait;
    3767     16021574 :                     myHaveToWaitOnNextLink = true;
    3768              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3769              :                     if (DEBUG_COND) {
    3770              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (minor)\n";
    3771              :                     }
    3772              : #endif
    3773     16021574 :                     break;
    3774              :                 } else {
    3775              :                     // past the point of no return. we need to drive fast enough
    3776              :                     // to make it across the link. However, minor slowdowns
    3777              :                     // should be permissible to follow leading traffic safely
    3778              :                     // basically, this code prevents dawdling
    3779              :                     // (it's harder to do this later using
    3780              :                     // SUMO_ATTR_JM_SIGMA_MINOR because we don't know whether the
    3781              :                     // vehicle is already too close to stop at that part of the code)
    3782              :                     //
    3783              :                     // XXX: There is a problem in subsecond simulation: If we cannot
    3784              :                     // make it across the minor link in one step, new traffic
    3785              :                     // could appear on a major foe link and cause a collision. Refs. #1845, #2123
    3786       941808 :                     vSafeMinDist = dpi.myDistance; // distance that must be covered
    3787       941808 :                     if (MSGlobals::gSemiImplicitEulerUpdate) {
    3788      1719678 :                         vSafeMin = MIN3((double)DIST2SPEED(vSafeMinDist + POSITION_EPS), dpi.myVLinkPass, getCarFollowModel().maxNextSafeMin(getSpeed(), this));
    3789              :                     } else {
    3790       163938 :                         vSafeMin = MIN3((double)DIST2SPEED(2 * vSafeMinDist + NUMERICAL_EPS) - getSpeed(), dpi.myVLinkPass, getCarFollowModel().maxNextSafeMin(getSpeed(), this));
    3791              :                     }
    3792              :                     canBrakeVSafeMin = canBrake;
    3793              : #ifdef DEBUG_EXEC_MOVE
    3794              :                     if (DEBUG_COND) {
    3795              :                         std::cout << "     vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << " canBrake=" << canBrake << "\n";
    3796              :                     }
    3797              : #endif
    3798              :                 }
    3799              :             }
    3800              :             // have waited; may pass if opened...
    3801    624458553 :             if (opened) {
    3802    619183648 :                 vSafe = dpi.myVLinkPass;
    3803    619183648 :                 if (vSafe < getCarFollowModel().getMaxDecel() && vSafe <= dpi.myVLinkWait && vSafe < getCarFollowModel().maxNextSpeed(getSpeed(), this)) {
    3804              :                     // this vehicle is probably not gonna drive across the next junction (heuristic)
    3805     53484346 :                     myHaveToWaitOnNextLink = true;
    3806              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3807              :                     if (DEBUG_COND) {
    3808              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (very slow)\n";
    3809              :                     }
    3810              : #endif
    3811              :                 }
    3812    619183648 :                 if (link->mustStop() && determinedFoePresence && myHaveStoppedFor == nullptr) {
    3813        19922 :                     myHaveStoppedFor = link;
    3814              :                 }
    3815      5274905 :             } else if (link->getState() == LINKSTATE_ZIPPER) {
    3816      1183391 :                 vSafeZipper = MIN2(vSafeZipper,
    3817      1183391 :                                    link->getZipperSpeed(this, dpi.myDistance, dpi.myVLinkPass, dpi.myArrivalTime, &collectFoes));
    3818              :             } else if (!canBrake
    3819              :                        // always brake hard for traffic lights (since an emergency stop is necessary anyway)
    3820         1754 :                        && link->getTLLogic() == nullptr
    3821              :                        // cannot brake even with emergency deceleration
    3822      4092424 :                        && dpi.myDistance < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0.)) {
    3823              : #ifdef DEBUG_EXEC_MOVE
    3824              :                 if (DEBUG_COND) {
    3825              :                     std::cout << SIMTIME << " too fast to brake for closed link\n";
    3826              :                 }
    3827              : #endif
    3828          242 :                 vSafe = dpi.myVLinkPass;
    3829              :             } else {
    3830      4091272 :                 vSafe = dpi.myVLinkWait;
    3831      4091272 :                 myHaveToWaitOnNextLink = true;
    3832              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3833              :                 if (DEBUG_COND) {
    3834              :                     std::cout << SIMTIME << " veh=" << getID() << " haveToWait (closed)\n";
    3835              :                 }
    3836              : #endif
    3837              : #ifdef DEBUG_EXEC_MOVE
    3838              :                 if (DEBUG_COND) {
    3839              :                     std::cout << SIMTIME << " braking for closed link=" << link->getViaLaneOrLane()->getID() << "\n";
    3840              :                 }
    3841              : #endif
    3842      4091272 :                 break;
    3843              :             }
    3844    620367281 :             if (myLane->isInternal() && myJunctionEntryTime == SUMOTime_MAX) {
    3845              :                 // request was renewed, restoring entry time
    3846              :                 // @note: using myJunctionEntryTimeNeverYield could lead to inconsistencies with other vehicles already on the junction
    3847        77521 :                 myJunctionEntryTime = SIMSTEP;;
    3848              :             }
    3849    640480127 :         } else {
    3850    425193264 :             if (link != nullptr && link->getInternalLaneBefore() != nullptr && myLane->isInternal() && link->getJunction() == myLane->getEdge().getToJunction()) {
    3851              :                 // blocked on the junction. yield request so other vehicles may
    3852              :                 // become junction leader
    3853              : #ifdef DEBUG_EXEC_MOVE
    3854              :                 if (DEBUG_COND) {
    3855              :                     std::cout << SIMTIME << " resetting junctionEntryTime at junction '" << link->getJunction()->getID() << "' beause of non-request exitLink\n";
    3856              :                 }
    3857              : #endif
    3858       241747 :                 myJunctionEntryTime = SUMOTime_MAX;
    3859       241747 :                 myJunctionConflictEntryTime = SUMOTime_MAX;
    3860              :             }
    3861              :             // we have: i->link == 0 || !i->setRequest
    3862    425193264 :             vSafe = dpi.myVLinkWait;
    3863    425193264 :             if (link != nullptr || myStopDist < (myLane->getLength() - getPositionOnLane())) {
    3864     98636283 :                 if (vSafe < getSpeed()) {
    3865     14860462 :                     myHaveToWaitOnNextLink = true;
    3866              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3867              :                     if (DEBUG_COND) {
    3868              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, braking) vSafe=" << vSafe << "\n";
    3869              :                     }
    3870              : #endif
    3871     83775821 :                 } else if (vSafe < SUMO_const_haltingSpeed) {
    3872     58588332 :                     myHaveToWaitOnNextLink = true;
    3873              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3874              :                     if (DEBUG_COND) {
    3875              :                         std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, stopping)\n";
    3876              :                     }
    3877              : #endif
    3878              :                 }
    3879              :             }
    3880    330857616 :             if (link == nullptr && myLFLinkLanes.size() == 1
    3881    267412022 :                     && getBestLanesContinuation().size() > 1
    3882       274663 :                     && getBestLanesContinuation()[1]->hadPermissionChanges()
    3883    425329788 :                     && myLane->getFirstAnyVehicle() == this) {
    3884              :                 // temporal lane closing without notification, visible to the
    3885              :                 // vehicle at the front of the queue
    3886        34552 :                 updateBestLanes(true);
    3887              :                 //std::cout << SIMTIME << " veh=" << getID() << " updated bestLanes=" << toString(getBestLanesContinuation()) << "\n";
    3888              :             }
    3889              :             break;
    3890              :         }
    3891              :     }
    3892              : 
    3893              : //#ifdef DEBUG_EXEC_MOVE
    3894              : //    if (DEBUG_COND) {
    3895              : //        std::cout << "\nvCurrent = " << toString(getSpeed(), 24) << "" << std::endl;
    3896              : //        std::cout << "vSafe = " << toString(vSafe, 24) << "" << std::endl;
    3897              : //        std::cout << "vSafeMin = " << toString(vSafeMin, 24) << "" << std::endl;
    3898              : //        std::cout << "vSafeMinDist = " << toString(vSafeMinDist, 24) << "" << std::endl;
    3899              : //
    3900              : //        double gap = getLeader().second;
    3901              : //        std::cout << "gap = " << toString(gap, 24) << std::endl;
    3902              : //        std::cout << "vSafeStoppedLeader = " << toString(getCarFollowModel().stopSpeed(this, getSpeed(), gap, MSCFModel::CalcReason::FUTURE), 24)
    3903              : //                << "\n" << std::endl;
    3904              : //    }
    3905              : //#endif
    3906              : 
    3907    619374397 :     if ((MSGlobals::gSemiImplicitEulerUpdate && vSafe + NUMERICAL_EPS < vSafeMin)
    3908    619159565 :             || (!MSGlobals::gSemiImplicitEulerUpdate && (vSafe + NUMERICAL_EPS < vSafeMin && vSafeMin != 0))) { // this might be good for the euler case as well
    3909              :         // XXX: (Leo) This often called stopSpeed with vSafeMinDist==0 (for the ballistic update), since vSafe can become negative
    3910              :         //      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
    3911              : #ifdef DEBUG_EXEC_MOVE
    3912              :         if (DEBUG_COND) {
    3913              :             std::cout << "vSafeMin Problem? vSafe=" << vSafe << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << std::endl;
    3914              :         }
    3915              : #endif
    3916       254982 :         if (canBrakeVSafeMin && vSafe < getSpeed()) {
    3917              :             // cannot drive across a link so we need to stop before it
    3918       124910 :             vSafe = MIN2(vSafe, MAX2(getCarFollowModel().minNextSpeed(getSpeed(), this),
    3919        62455 :                                      getCarFollowModel().stopSpeed(this, getSpeed(), vSafeMinDist)));
    3920        62455 :             vSafeMin = 0;
    3921        62455 :             myHaveToWaitOnNextLink = true;
    3922              : #ifdef DEBUG_CHECKREWINDLINKLANES
    3923              :             if (DEBUG_COND) {
    3924              :                 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (vSafe=" << vSafe << " < vSafeMin=" << vSafeMin << ")\n";
    3925              :             }
    3926              : #endif
    3927              :         } else {
    3928              :             // if the link is yellow or visibility distance is large
    3929              :             // then we might not make it across the link in one step anyway..
    3930              :             // Possibly, the lane after the intersection has a lower speed limit so
    3931              :             // we really need to drive slower already
    3932              :             // -> keep driving without dawdling
    3933       192527 :             vSafeMin = vSafe;
    3934              :         }
    3935              :     }
    3936              : 
    3937              :     // vehicles inside a roundabout should maintain their requests
    3938    619374397 :     if (myLane->getEdge().isRoundabout()) {
    3939      2659156 :         myHaveToWaitOnNextLink = false;
    3940              :     }
    3941              : 
    3942    619374397 :     vSafe = MIN2(vSafe, vSafeZipper);
    3943    619374397 : }
    3944              : 
    3945              : 
    3946              : double
    3947    686986155 : MSVehicle::processTraCISpeedControl(double vSafe, double vNext) {
    3948    686986155 :     if (myInfluencer != nullptr) {
    3949       500112 :         myInfluencer->setOriginalSpeed(vNext);
    3950              : #ifdef DEBUG_TRACI
    3951              :         if DEBUG_COND2(this) {
    3952              :             std::cout << SIMTIME << " MSVehicle::processTraCISpeedControl() for vehicle '" << getID() << "'"
    3953              :                       << " vSafe=" << vSafe << " (init)vNext=" << vNext << " keepStopping=" << keepStopping();
    3954              :         }
    3955              : #endif
    3956       500112 :         if (myInfluencer->isRemoteControlled()) {
    3957         7752 :             vNext = myInfluencer->implicitSpeedRemote(this, myState.mySpeed);
    3958              :         }
    3959       500112 :         const double vMax = getVehicleType().getCarFollowModel().maxNextSpeed(myState.mySpeed, this);
    3960       500112 :         double vMin = getVehicleType().getCarFollowModel().minNextSpeed(myState.mySpeed, this);
    3961       500112 :         if (MSGlobals::gSemiImplicitEulerUpdate) {
    3962              :             vMin = MAX2(0., vMin);
    3963              :         }
    3964       500112 :         vNext = myInfluencer->influenceSpeed(MSNet::getInstance()->getCurrentTimeStep(), vNext, vSafe, vMin, vMax);
    3965       500112 :         if (keepStopping() && myStops.front().getSpeed() == 0) {
    3966              :             // avoid driving while stopped (unless it's actually a waypoint
    3967         3746 :             vNext = myInfluencer->getOriginalSpeed();
    3968              :         }
    3969              : #ifdef DEBUG_TRACI
    3970              :         if DEBUG_COND2(this) {
    3971              :             std::cout << " (processed)vNext=" << vNext << std::endl;
    3972              :         }
    3973              : #endif
    3974              :     }
    3975    686986155 :     return vNext;
    3976              : }
    3977              : 
    3978              : 
    3979              : void
    3980     71636360 : MSVehicle::removePassedDriveItems() {
    3981              : #ifdef DEBUG_ACTIONSTEPS
    3982              :     if (DEBUG_COND) {
    3983              :         std::cout << SIMTIME << " veh=" << getID() << " removePassedDriveItems()\n"
    3984              :                   << "    Current items: ";
    3985              :         for (auto& j : myLFLinkLanes) {
    3986              :             if (j.myLink == 0) {
    3987              :                 std::cout << "\n    Stop at distance " << j.myDistance;
    3988              :             } else {
    3989              :                 const MSLane* to = j.myLink->getViaLaneOrLane();
    3990              :                 const MSLane* from = j.myLink->getLaneBefore();
    3991              :                 std::cout << "\n    Link at distance " << j.myDistance << ": '"
    3992              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    3993              :             }
    3994              :         }
    3995              :         std::cout << "\n    myNextDriveItem: ";
    3996              :         if (myLFLinkLanes.size() != 0) {
    3997              :             if (myNextDriveItem->myLink == 0) {
    3998              :                 std::cout << "\n    Stop at distance " << myNextDriveItem->myDistance;
    3999              :             } else {
    4000              :                 const MSLane* to = myNextDriveItem->myLink->getViaLaneOrLane();
    4001              :                 const MSLane* from = myNextDriveItem->myLink->getLaneBefore();
    4002              :                 std::cout << "\n    Link at distance " << myNextDriveItem->myDistance << ": '"
    4003              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    4004              :             }
    4005              :         }
    4006              :         std::cout << std::endl;
    4007              :     }
    4008              : #endif
    4009     71962589 :     for (auto j = myLFLinkLanes.begin(); j != myNextDriveItem; ++j) {
    4010              : #ifdef DEBUG_ACTIONSTEPS
    4011              :         if (DEBUG_COND) {
    4012              :             std::cout << "    Removing item: ";
    4013              :             if (j->myLink == 0) {
    4014              :                 std::cout << "Stop at distance " << j->myDistance;
    4015              :             } else {
    4016              :                 const MSLane* to = j->myLink->getViaLaneOrLane();
    4017              :                 const MSLane* from = j->myLink->getLaneBefore();
    4018              :                 std::cout << "Link at distance " << j->myDistance << ": '"
    4019              :                           << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
    4020              :             }
    4021              :             std::cout << std::endl;
    4022              :         }
    4023              : #endif
    4024       326229 :         if (j->myLink != nullptr) {
    4025       326156 :             j->myLink->removeApproaching(this);
    4026              :         }
    4027              :     }
    4028     71636360 :     myLFLinkLanes.erase(myLFLinkLanes.begin(), myNextDriveItem);
    4029     71636360 :     myNextDriveItem = myLFLinkLanes.begin();
    4030     71636360 : }
    4031              : 
    4032              : 
    4033              : void
    4034      1108371 : MSVehicle::updateDriveItems() {
    4035              : #ifdef DEBUG_ACTIONSTEPS
    4036              :     if (DEBUG_COND) {
    4037              :         std::cout << SIMTIME << " updateDriveItems(), veh='" << getID() << "' (lane: '" << getLane()->getID() << "')\nCurrent drive items:" << std::endl;
    4038              :         for (const auto& dpi : myLFLinkLanes) {
    4039              :             std::cout
    4040              :                     << " vPass=" << dpi.myVLinkPass
    4041              :                     << " vWait=" << dpi.myVLinkWait
    4042              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    4043              :                     << " request=" << dpi.mySetRequest
    4044              :                     << "\n";
    4045              :         }
    4046              :         std::cout << " myNextDriveItem's linked lane: " << (myNextDriveItem->myLink == 0 ? "NULL" : myNextDriveItem->myLink->getViaLaneOrLane()->getID()) << std::endl;
    4047              :     }
    4048              : #endif
    4049      1108371 :     if (myLFLinkLanes.size() == 0) {
    4050              :         // nothing to update
    4051              :         return;
    4052              :     }
    4053              :     const MSLink* nextPlannedLink = nullptr;
    4054              : //    auto i = myLFLinkLanes.begin();
    4055      1108371 :     auto i = myNextDriveItem;
    4056      2216696 :     while (i != myLFLinkLanes.end() && nextPlannedLink == nullptr) {
    4057      1108325 :         nextPlannedLink = i->myLink;
    4058              :         ++i;
    4059              :     }
    4060              : 
    4061      1108371 :     if (nextPlannedLink == nullptr) {
    4062              :         // No link for upcoming item -> no need for an update
    4063              : #ifdef DEBUG_ACTIONSTEPS
    4064              :         if (DEBUG_COND) {
    4065              :             std::cout << "Found no link-related drive item." << std::endl;
    4066              :         }
    4067              : #endif
    4068              :         return;
    4069              :     }
    4070              : 
    4071       539302 :     if (getLane() == nextPlannedLink->getLaneBefore()) {
    4072              :         // Current lane approaches the stored next link, i.e. no LC happend and no update is required.
    4073              : #ifdef DEBUG_ACTIONSTEPS
    4074              :         if (DEBUG_COND) {
    4075              :             std::cout << "Continuing on planned lane sequence, no update required." << std::endl;
    4076              :         }
    4077              : #endif
    4078              :         return;
    4079              :     }
    4080              :     // Lane must have been changed, determine the change direction
    4081       529361 :     const MSLink* parallelLink = nextPlannedLink->getParallelLink(1);
    4082       529361 :     if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4083              :         // lcDir = 1;
    4084              :     } else {
    4085       263106 :         parallelLink = nextPlannedLink->getParallelLink(-1);
    4086       263106 :         if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
    4087              :             // lcDir = -1;
    4088              :         } else {
    4089              :             // If the vehicle's current lane is not the approaching lane for the next
    4090              :             // drive process item's link, it is expected to lead to a parallel link,
    4091              :             // XXX: What if the lc was an overtaking maneuver and there is no upcoming link?
    4092              :             //      Then a stop item should be scheduled! -> TODO!
    4093              :             //assert(false);
    4094        71767 :             return;
    4095              :         }
    4096              :     }
    4097              : #ifdef DEBUG_ACTIONSTEPS
    4098              :     if (DEBUG_COND) {
    4099              :         std::cout << "Changed lane. Drive items will be updated along the current lane continuation." << std::endl;
    4100              :     }
    4101              : #endif
    4102              :     // Trace link sequence along current best lanes and transfer drive items to the corresponding links
    4103              : //        DriveItemVector::iterator driveItemIt = myLFLinkLanes.begin();
    4104       457594 :     DriveItemVector::iterator driveItemIt = myNextDriveItem;
    4105              :     // In the loop below, lane holds the currently considered lane on the vehicles continuation (including internal lanes)
    4106       457594 :     const MSLane* lane = myLane;
    4107              :     assert(myLane == parallelLink->getLaneBefore());
    4108              :     // *lit is a pointer to the next lane in best continuations for the current lane (always non-internal)
    4109       457594 :     std::vector<MSLane*>::const_iterator bestLaneIt = getBestLanesContinuation().begin() + 1;
    4110              :     // Pointer to the new link for the current drive process item
    4111              :     MSLink* newLink = nullptr;
    4112      1710089 :     while (driveItemIt != myLFLinkLanes.end()) {
    4113      1281367 :         if (driveItemIt->myLink == nullptr) {
    4114              :             // Items not related to a specific link are not updated
    4115              :             // (XXX: when a stop item corresponded to a dead end, which is overcome by the LC that made
    4116              :             //       the update necessary, this may slow down the vehicle's continuation on the new lane...)
    4117              :             ++driveItemIt;
    4118       157991 :             continue;
    4119              :         }
    4120              :         // Continuation links for current best lanes are less than for the former drive items (myLFLinkLanes)
    4121              :         // We just remove the leftover link-items, as they cannot be mapped to new links.
    4122      1123376 :         if (bestLaneIt == getBestLanesContinuation().end()) {
    4123              : #ifdef DEBUG_ACTIONSTEPS
    4124              :             if (DEBUG_COND) {
    4125              :                 std::cout << "Reached end of the new continuation sequence. Erasing leftover link-items." << std::endl;
    4126              :             }
    4127              : #endif
    4128        91347 :             while (driveItemIt != myLFLinkLanes.end()) {
    4129        62475 :                 if (driveItemIt->myLink == nullptr) {
    4130              :                     ++driveItemIt;
    4131        14210 :                     continue;
    4132              :                 } else {
    4133        48265 :                     driveItemIt->myLink->removeApproaching(this);
    4134              :                     driveItemIt = myLFLinkLanes.erase(driveItemIt);
    4135              :                 }
    4136              :             }
    4137              :             break;
    4138              :         }
    4139              :         // Do the actual link-remapping for the item. And un/register approaching information on the corresponding links
    4140      1094504 :         const MSLane* const target = *bestLaneIt;
    4141              :         assert(!target->isInternal());
    4142              :         newLink = nullptr;
    4143      1210445 :         for (MSLink* const link : lane->getLinkCont()) {
    4144      1210445 :             if (link->getLane() == target) {
    4145              :                 newLink = link;
    4146              :                 break;
    4147              :             }
    4148              :         }
    4149              : 
    4150      1094504 :         if (newLink == driveItemIt->myLink) {
    4151              :             // new continuation merged into previous - stop update
    4152              : #ifdef DEBUG_ACTIONSTEPS
    4153              :             if (DEBUG_COND) {
    4154              :                 std::cout << "Old and new continuation sequences merge at link\n"
    4155              :                           << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'"
    4156              :                           << "\nNo update beyond merge required." << std::endl;
    4157              :             }
    4158              : #endif
    4159              :             break;
    4160              :         }
    4161              : 
    4162              : #ifdef DEBUG_ACTIONSTEPS
    4163              :         if (DEBUG_COND) {
    4164              :             std::cout << "lane=" << lane->getID() << "\nUpdating link\n    '" << driveItemIt->myLink->getLaneBefore()->getID() << "'->'" << driveItemIt->myLink->getViaLaneOrLane()->getID() << "'"
    4165              :                       << "==> " << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'" << std::endl;
    4166              :         }
    4167              : #endif
    4168      1094504 :         newLink->setApproaching(this, driveItemIt->myLink->getApproaching(this));
    4169      1094504 :         driveItemIt->myLink->removeApproaching(this);
    4170      1094504 :         driveItemIt->myLink = newLink;
    4171              :         lane = newLink->getViaLaneOrLane();
    4172              :         ++driveItemIt;
    4173      1094504 :         if (!lane->isInternal()) {
    4174              :             ++bestLaneIt;
    4175              :         }
    4176              :     }
    4177              : #ifdef DEBUG_ACTIONSTEPS
    4178              :     if (DEBUG_COND) {
    4179              :         std::cout << "Updated drive items:" << std::endl;
    4180              :         for (const auto& dpi : myLFLinkLanes) {
    4181              :             std::cout
    4182              :                     << " vPass=" << dpi.myVLinkPass
    4183              :                     << " vWait=" << dpi.myVLinkWait
    4184              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    4185              :                     << " request=" << dpi.mySetRequest
    4186              :                     << "\n";
    4187              :         }
    4188              :     }
    4189              : #endif
    4190              : }
    4191              : 
    4192              : 
    4193              : void
    4194    686986155 : MSVehicle::setBrakingSignals(double vNext) {
    4195              :     // To avoid casual blinking brake lights at high speeds due to dawdling of the
    4196              :     // leading vehicle, we don't show brake lights when the deceleration could be caused
    4197              :     // by frictional forces and air resistance (i.e. proportional to v^2, coefficient could be adapted further)
    4198    686986155 :     double pseudoFriction = (0.05 +  0.005 * getSpeed()) * getSpeed();
    4199    686986155 :     bool brakelightsOn = vNext < getSpeed() - ACCEL2SPEED(pseudoFriction);
    4200              : 
    4201    686986155 :     if (vNext <= SUMO_const_haltingSpeed) {
    4202              :         brakelightsOn = true;
    4203              :     }
    4204    686986155 :     if (brakelightsOn && !isStopped()) {
    4205              :         switchOnSignal(VEH_SIGNAL_BRAKELIGHT);
    4206              :     } else {
    4207              :         switchOffSignal(VEH_SIGNAL_BRAKELIGHT);
    4208              :     }
    4209    686986155 : }
    4210              : 
    4211              : 
    4212              : void
    4213    687092476 : MSVehicle::updateWaitingTime(double vNext) {
    4214    687092476 :     if (vNext <= SUMO_const_haltingSpeed && (!isStopped() || isIdling()) && myAcceleration <= accelThresholdForWaiting())  {
    4215     84997431 :         myWaitingTime += DELTA_T;
    4216     84997431 :         myWaitingTimeCollector.passTime(DELTA_T, true);
    4217              :     } else {
    4218    602095045 :         myWaitingTime = 0;
    4219    602095045 :         myWaitingTimeCollector.passTime(DELTA_T, false);
    4220    602095045 :         if (hasInfluencer()) {
    4221       275415 :             getInfluencer().setExtraImpatience(0);
    4222              :         }
    4223              :     }
    4224    687092476 : }
    4225              : 
    4226              : 
    4227              : void
    4228    686985973 : MSVehicle::updateTimeLoss(double vNext) {
    4229              :     // update time loss (depends on the updated edge)
    4230    686985973 :     if (!isStopped()) {
    4231    673339597 :         const double vmax = myLane->getVehicleMaxSpeed(this);
    4232    673339597 :         if (vmax > 0) {
    4233    673332214 :             myTimeLoss += TS * (vmax - vNext) / vmax;
    4234              :         }
    4235              :     }
    4236    686985973 : }
    4237              : 
    4238              : 
    4239              : double
    4240   1519399860 : MSVehicle::checkReversal(bool& canReverse, double speedThreshold, double seen) const {
    4241     52956054 :     const bool stopOk = (myStops.empty() || myStops.front().edge != myCurrEdge
    4242   1541364696 :                          || (myStops.front().getSpeed() > 0 && myState.myPos > myStops.front().pars.endPos - 2 * POSITION_EPS));
    4243              : #ifdef DEBUG_REVERSE_BIDI
    4244              :     if (DEBUG_COND) std::cout << SIMTIME  << " checkReversal lane=" << myLane->getID()
    4245              :                                   << " pos=" << myState.myPos
    4246              :                                   << " speed=" << std::setprecision(6) << getPreviousSpeed() << std::setprecision(gPrecision)
    4247              :                                   << " speedThreshold=" << speedThreshold
    4248              :                                   << " seen=" << seen
    4249              :                                   << " isRail=" << isRail()
    4250              :                                   << " speedOk=" << (getPreviousSpeed() <= speedThreshold)
    4251              :                                   << " posOK=" << (myState.myPos <= myLane->getLength())
    4252              :                                   << " normal=" << !myLane->isInternal()
    4253              :                                   << " routeOK=" << ((myCurrEdge + 1) != myRoute->end())
    4254              :                                   << " bidi=" << (myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1))
    4255              :                                   << " stopOk=" << stopOk
    4256              :                                   << "\n";
    4257              : #endif
    4258   1519399860 :     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4259      6630779 :             && getPreviousSpeed() <= speedThreshold
    4260      5657770 :             && myState.myPos <= myLane->getLength()
    4261      5656770 :             && !myLane->isInternal()
    4262      5591686 :             && (myCurrEdge + 1) != myRoute->end()
    4263      5502874 :             && myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1)
    4264              :             // ensure there are no further stops on this edge
    4265   1520246459 :             && stopOk
    4266              :        ) {
    4267              :         //if (isSelected()) std::cout << "   check1 passed\n";
    4268              : 
    4269              :         // ensure that the vehicle is fully on bidi edges that allow reversal
    4270       177789 :         const int neededFutureRoute = 1 + (int)(MSGlobals::gUsingInternalLanes
    4271              :                                                 ? myFurtherLanes.size()
    4272          504 :                                                 : ceil((double)myFurtherLanes.size() / 2.0));
    4273       177789 :         const int remainingRoute = int(myRoute->end() - myCurrEdge) - 1;
    4274       177789 :         if (remainingRoute < neededFutureRoute) {
    4275              : #ifdef DEBUG_REVERSE_BIDI
    4276              :             if (DEBUG_COND) {
    4277              :                 std::cout << "    fail: remainingEdges=" << ((int)(myRoute->end() - myCurrEdge)) << " further=" << myFurtherLanes.size() << "\n";
    4278              :             }
    4279              : #endif
    4280         3570 :             return getMaxSpeed();
    4281              :         }
    4282              :         //if (isSelected()) std::cout << "   check2 passed\n";
    4283              : 
    4284              :         // ensure that the turn-around connection exists from the current edge to its bidi-edge
    4285       174219 :         const MSEdgeVector& succ = myLane->getEdge().getSuccessors();
    4286       174219 :         if (std::find(succ.begin(), succ.end(), myLane->getEdge().getBidiEdge()) == succ.end()) {
    4287              : #ifdef DEBUG_REVERSE_BIDI
    4288              :             if (DEBUG_COND) {
    4289              :                 std::cout << "    noTurn (bidi=" << myLane->getEdge().getBidiEdge()->getID() << " succ=" << toString(succ) << "\n";
    4290              :             }
    4291              : #endif
    4292          909 :             return getMaxSpeed();
    4293              :         }
    4294              :         //if (isSelected()) std::cout << "   check3 passed\n";
    4295              : 
    4296              :         // ensure that the vehicle front will not move past a stop on the bidi edge of the current edge
    4297       173310 :         if (!myStops.empty() && myStops.front().edge == (myCurrEdge + 1)) {
    4298       160006 :             const double stopPos = myStops.front().getEndPos(*this);
    4299       160006 :             const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
    4300       160006 :             const double newPos = myLane->getLength() - (getBackPositionOnLane() + brakeDist);
    4301       160006 :             if (newPos > stopPos) {
    4302              : #ifdef DEBUG_REVERSE_BIDI
    4303              :                 if (DEBUG_COND) {
    4304              :                     std::cout << "    reversal would go past stop on " << myLane->getBidiLane()->getID() << "\n";
    4305              :                 }
    4306              : #endif
    4307       158332 :                 if (seen > MAX2(brakeDist, 1.0)) {
    4308       157202 :                     return getMaxSpeed();
    4309              :                 } else {
    4310              : #ifdef DEBUG_REVERSE_BIDI
    4311              :                     if (DEBUG_COND) {
    4312              :                         std::cout << "    train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
    4313              :                     }
    4314              : #endif
    4315              :                 }
    4316              :             }
    4317              :         }
    4318              :         //if (isSelected()) std::cout << "   check4 passed\n";
    4319              : 
    4320              :         // ensure that bidi-edges exist for all further edges
    4321              :         // and that no stops will be skipped when reversing
    4322              :         // and that the train will not be on top of a red rail signal after reversal
    4323        16108 :         const MSLane* bidi = myLane->getBidiLane();
    4324              :         int view = 2;
    4325        32828 :         for (MSLane* further : myFurtherLanes) {
    4326        18277 :             if (!further->getEdge().isInternal()) {
    4327         9709 :                 if (further->getEdge().getBidiEdge() != *(myCurrEdge + view)) {
    4328              : #ifdef DEBUG_REVERSE_BIDI
    4329              :                     if (DEBUG_COND) {
    4330              :                         std::cout << "    noBidi view=" << view << " further=" << further->getID() << " furtherBidi=" << Named::getIDSecure(further->getEdge().getBidiEdge()) << " future=" << (*(myCurrEdge + view))->getID() << "\n";
    4331              :                     }
    4332              : #endif
    4333         1398 :                     return getMaxSpeed();
    4334              :                 }
    4335         8311 :                 const MSLane* nextBidi = further->getBidiLane();
    4336         8311 :                 const MSLink* toNext = bidi->getLinkTo(nextBidi);
    4337         8311 :                 if (toNext == nullptr) {
    4338              :                     // can only happen if the route is invalid
    4339            0 :                     return getMaxSpeed();
    4340              :                 }
    4341         8311 :                 if (toNext->haveRed()) {
    4342              : #ifdef DEBUG_REVERSE_BIDI
    4343              :                     if (DEBUG_COND) {
    4344              :                         std::cout << "    do not reverse on a red signal\n";
    4345              :                     }
    4346              : #endif
    4347            0 :                     return getMaxSpeed();
    4348              :                 }
    4349              :                 bidi = nextBidi;
    4350         8311 :                 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + view)) {
    4351          453 :                     const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
    4352          453 :                     const double stopPos = myStops.front().getEndPos(*this);
    4353          453 :                     const double newPos = further->getLength() - (getBackPositionOnLane(further) + brakeDist);
    4354          453 :                     if (newPos > stopPos) {
    4355              : #ifdef DEBUG_REVERSE_BIDI
    4356              :                         if (DEBUG_COND) {
    4357              :                             std::cout << "    reversal would go past stop on further-opposite lane " << further->getBidiLane()->getID() << "\n";
    4358              :                         }
    4359              : #endif
    4360          171 :                         if (seen > MAX2(brakeDist, 1.0)) {
    4361          159 :                             canReverse = false;
    4362          159 :                             return getMaxSpeed();
    4363              :                         } else {
    4364              : #ifdef DEBUG_REVERSE_BIDI
    4365              :                             if (DEBUG_COND) {
    4366              :                                 std::cout << "    train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
    4367              :                             }
    4368              : #endif
    4369              :                         }
    4370              :                     }
    4371              :                 }
    4372         8152 :                 view++;
    4373              :             }
    4374              :         }
    4375              :         // reverse as soon as comfortably possible
    4376        14551 :         const double vMinComfortable = getCarFollowModel().minNextSpeed(getSpeed(), this);
    4377              : #ifdef DEBUG_REVERSE_BIDI
    4378              :         if (DEBUG_COND) {
    4379              :             std::cout << SIMTIME << " seen=" << seen  << " vReverseOK=" << vMinComfortable << "\n";
    4380              :         }
    4381              : #endif
    4382        14551 :         canReverse = true;
    4383        14551 :         return vMinComfortable;
    4384              :     }
    4385   1519222071 :     return getMaxSpeed();
    4386              : }
    4387              : 
    4388              : 
    4389              : void
    4390    687199929 : MSVehicle::processLaneAdvances(std::vector<MSLane*>& passedLanes, std::string& emergencyReason) {
    4391    702729149 :     for (std::vector<MSLane*>::reverse_iterator i = myFurtherLanes.rbegin(); i != myFurtherLanes.rend(); ++i) {
    4392     15529220 :         passedLanes.push_back(*i);
    4393              :     }
    4394    687199929 :     if (passedLanes.size() == 0 || passedLanes.back() != myLane) {
    4395    687199929 :         passedLanes.push_back(myLane);
    4396              :     }
    4397              :     // let trains reverse direction
    4398    687199929 :     bool reverseTrain = false;
    4399    687199929 :     checkReversal(reverseTrain);
    4400    687199929 :     if (reverseTrain) {
    4401              :         // Train is 'reversing' so toggle the logical state
    4402          772 :         myAmReversed = !myAmReversed;
    4403              :         // add some slack to ensure that the back of train does appear looped
    4404          772 :         myState.myPos += 2 * (myLane->getLength() - myState.myPos) + myType->getLength() + NUMERICAL_EPS;
    4405          772 :         myState.mySpeed = 0;
    4406              : #ifdef DEBUG_REVERSE_BIDI
    4407              :         if (DEBUG_COND) {
    4408              :             std::cout << SIMTIME << " reversing train=" << getID() << " newPos=" << myState.myPos << "\n";
    4409              :         }
    4410              : #endif
    4411              :     }
    4412              :     // move on lane(s)
    4413    687199929 :     if (myState.myPos > myLane->getLength()) {
    4414              :         // The vehicle has moved at least to the next lane (maybe it passed even more than one)
    4415     20356220 :         if (myCurrEdge != myRoute->end() - 1) {
    4416     17157921 :             MSLane* approachedLane = myLane;
    4417              :             // move the vehicle forward
    4418     17157921 :             myNextDriveItem = myLFLinkLanes.begin();
    4419     36888230 :             while (myNextDriveItem != myLFLinkLanes.end() && approachedLane != nullptr && myState.myPos > approachedLane->getLength()) {
    4420     19754863 :                 const MSLink* link = myNextDriveItem->myLink;
    4421     19754863 :                 const double linkDist = myNextDriveItem->myDistance;
    4422              :                 ++myNextDriveItem;
    4423              :                 // check whether the vehicle was allowed to enter lane
    4424              :                 //  otherwise it is decelerated and we do not need to test for it's
    4425              :                 //  approach on the following lanes when a lane changing is performed
    4426              :                 // proceed to the next lane
    4427     19754863 :                 if (approachedLane->mustCheckJunctionCollisions()) {
    4428              :                     // vehicle moves past approachedLane within a single step, collision checking must still be done
    4429        60772 :                     MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(approachedLane);
    4430              :                 }
    4431     19754863 :                 if (link != nullptr) {
    4432     19750758 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4433        39974 :                             && !myLane->isInternal()
    4434        21152 :                             && myLane->getBidiLane() != nullptr
    4435        12059 :                             && link->getLane()->getBidiLane() == myLane
    4436     19751527 :                             && !reverseTrain) {
    4437              :                         emergencyReason = " because it must reverse direction";
    4438              :                         approachedLane = nullptr;
    4439              :                         break;
    4440              :                     }
    4441     19750755 :                     if ((getVClass() & SVC_RAIL_CLASSES) != 0
    4442        39971 :                             && myState.myPos < myLane->getLength() + NUMERICAL_EPS
    4443     19750980 :                             && hasStops() && getNextStop().edge == myCurrEdge) {
    4444              :                         // avoid skipping stop due to numerical instability
    4445              :                         // this is a special case for rail vehicles because they
    4446              :                         // continue myLFLinkLanes past stops
    4447          200 :                         approachedLane = myLane;
    4448          200 :                         myState.myPos = myLane->getLength();
    4449          200 :                         break;
    4450              :                     }
    4451     19750555 :                     approachedLane = link->getViaLaneOrLane();
    4452     19750555 :                     if (myInfluencer == nullptr || myInfluencer->getEmergencyBrakeRedLight()) {
    4453     19748967 :                         bool beyondStopLine = linkDist < link->getLaneBefore()->getVehicleStopOffset(this);
    4454     19748967 :                         if (link->haveRed() && !ignoreRed(link, false) && !beyondStopLine && !reverseTrain) {
    4455              :                             emergencyReason = " because of a red traffic light";
    4456              :                             break;
    4457              :                         }
    4458              :                     }
    4459     19750493 :                     if (reverseTrain && approachedLane->isInternal()) {
    4460              :                         // avoid getting stuck on a slow turn-around internal lane
    4461          842 :                         myState.myPos += approachedLane->getLength();
    4462              :                     }
    4463         4105 :                 } else if (myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4464              :                     // avoid warning due to numerical instability
    4465          163 :                     approachedLane = myLane;
    4466          163 :                     myState.myPos = myLane->getLength();
    4467         3942 :                 } else if (reverseTrain) {
    4468            0 :                     approachedLane = (*(myCurrEdge + 1))->getLanes()[0];
    4469            0 :                     link = myLane->getLinkTo(approachedLane);
    4470              :                     assert(link != 0);
    4471            0 :                     while (link->getViaLane() != nullptr) {
    4472            0 :                         link = link->getViaLane()->getLinkCont()[0];
    4473              :                     }
    4474              :                     --myNextDriveItem;
    4475              :                 } else {
    4476              :                     emergencyReason = " because there is no connection to the next edge";
    4477              :                     approachedLane = nullptr;
    4478              :                     break;
    4479              :                 }
    4480     19750656 :                 if (approachedLane != myLane && approachedLane != nullptr) {
    4481     19750493 :                     leaveLane(MSMoveReminder::NOTIFICATION_JUNCTION, approachedLane);
    4482     19750493 :                     myState.myPos -= myLane->getLength();
    4483              :                     assert(myState.myPos > 0);
    4484     19750493 :                     enterLaneAtMove(approachedLane);
    4485     19750493 :                     if (link->isEntryLink()) {
    4486      7815995 :                         myJunctionEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4487      7815995 :                         myJunctionEntryTimeNeverYield = myJunctionEntryTime;
    4488      7815995 :                         myHaveStoppedFor = nullptr;
    4489              :                     }
    4490     19750493 :                     if (link->isConflictEntryLink()) {
    4491      7815556 :                         myJunctionConflictEntryTime = MSNet::getInstance()->getCurrentTimeStep();
    4492              :                         // renew yielded request
    4493      7815556 :                         myJunctionEntryTime = myJunctionEntryTimeNeverYield;
    4494              :                     }
    4495     19750493 :                     if (link->isExitLink()) {
    4496              :                         // passed junction, reset for approaching the next one
    4497      7756195 :                         myJunctionEntryTime = SUMOTime_MAX;
    4498      7756195 :                         myJunctionEntryTimeNeverYield = SUMOTime_MAX;
    4499      7756195 :                         myJunctionConflictEntryTime = SUMOTime_MAX;
    4500              :                     }
    4501              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    4502              :                     if (DEBUG_COND) {
    4503              :                         std::cout << "Update junctionTimes link=" << link->getViaLaneOrLane()->getID()
    4504              :                                   << " entry=" << link->isEntryLink() << " conflict=" << link->isConflictEntryLink() << " exit=" << link->isExitLink()
    4505              :                                   << " ET=" << myJunctionEntryTime
    4506              :                                   << " ETN=" << myJunctionEntryTimeNeverYield
    4507              :                                   << " CET=" << myJunctionConflictEntryTime
    4508              :                                   << "\n";
    4509              :                     }
    4510              : #endif
    4511     19750493 :                     if (hasArrivedInternal()) {
    4512              :                         break;
    4513              :                     }
    4514     19730902 :                     if (myLaneChangeModel->isChangingLanes()) {
    4515         6570 :                         if (link->getDirection() == LinkDirection::LEFT || link->getDirection() == LinkDirection::RIGHT) {
    4516              :                             // abort lane change
    4517            0 :                             WRITE_WARNING("Vehicle '" + getID() + "' could not finish continuous lane change (turn lane) time=" +
    4518              :                                           time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    4519            0 :                             myLaneChangeModel->endLaneChangeManeuver();
    4520              :                         }
    4521              :                     }
    4522     19730902 :                     if (approachedLane->getEdge().isVaporizing()) {
    4523          756 :                         leaveLane(MSMoveReminder::NOTIFICATION_VAPORIZED_VAPORIZER);
    4524              :                         break;
    4525              :                     }
    4526     19730146 :                     passedLanes.push_back(approachedLane);
    4527              :                 }
    4528              :             }
    4529              :             // NOTE: Passed drive items will be erased in the next simstep's planMove()
    4530              : 
    4531              : #ifdef DEBUG_ACTIONSTEPS
    4532              :             if (DEBUG_COND && myNextDriveItem != myLFLinkLanes.begin()) {
    4533              :                 std::cout << "Updated drive items:" << std::endl;
    4534              :                 for (DriveItemVector::iterator i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
    4535              :                     std::cout
    4536              :                             << " vPass=" << (*i).myVLinkPass
    4537              :                             << " vWait=" << (*i).myVLinkWait
    4538              :                             << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
    4539              :                             << " request=" << (*i).mySetRequest
    4540              :                             << "\n";
    4541              :                 }
    4542              :             }
    4543              : #endif
    4544      3198299 :         } else if (!hasArrivedInternal() && myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
    4545              :             // avoid warning due to numerical instability when stopping at the end of the route
    4546           58 :             myState.myPos = myLane->getLength();
    4547              :         }
    4548              : 
    4549              :     }
    4550    687199929 : }
    4551              : 
    4552              : 
    4553              : 
    4554              : bool
    4555    691010757 : MSVehicle::executeMove() {
    4556              : #ifdef DEBUG_EXEC_MOVE
    4557              :     if (DEBUG_COND) {
    4558              :         std::cout << "\nEXECUTE_MOVE\n"
    4559              :                   << SIMTIME
    4560              :                   << " veh=" << getID()
    4561              :                   << " speed=" << getSpeed() // toString(getSpeed(), 24)
    4562              :                   << std::endl;
    4563              :     }
    4564              : #endif
    4565              : 
    4566              : 
    4567              :     // Maximum safe velocity
    4568    691010757 :     double vSafe = std::numeric_limits<double>::max();
    4569              :     // Minimum safe velocity (lower bound).
    4570    691010757 :     double vSafeMin = -std::numeric_limits<double>::max();
    4571              :     // The distance to a link, which should either be crossed this step
    4572              :     // or in front of which we need to stop.
    4573    691010757 :     double vSafeMinDist = 0;
    4574              : 
    4575    691010757 :     if (myActionStep) {
    4576              :         // Actuate control (i.e. choose bounds for safe speed in current simstep (euler), resp. after current sim step (ballistic))
    4577    619374397 :         processLinkApproaches(vSafe, vSafeMin, vSafeMinDist);
    4578              : #ifdef DEBUG_ACTIONSTEPS
    4579              :         if (DEBUG_COND) {
    4580              :             std::cout << SIMTIME << " vehicle '" << getID() << "'\n"
    4581              :                       "   vsafe from processLinkApproaches(): vsafe " << vSafe << std::endl;
    4582              :         }
    4583              : #endif
    4584              :     } else {
    4585              :         // Continue with current acceleration
    4586     71636360 :         vSafe = getSpeed() + ACCEL2SPEED(myAcceleration);
    4587              : #ifdef DEBUG_ACTIONSTEPS
    4588              :         if (DEBUG_COND) {
    4589              :             std::cout << SIMTIME << " vehicle '" << getID() << "' skips processLinkApproaches()\n"
    4590              :                       "   continues with constant accel " <<  myAcceleration << "...\n"
    4591              :                       << "speed: "  << getSpeed() << " -> " << vSafe << std::endl;
    4592              :         }
    4593              : #endif
    4594              :     }
    4595              : 
    4596              : 
    4597              : //#ifdef DEBUG_EXEC_MOVE
    4598              : //    if (DEBUG_COND) {
    4599              : //        std::cout << "vSafe = " << toString(vSafe,12) << "\n" << std::endl;
    4600              : //    }
    4601              : //#endif
    4602              : 
    4603              :     // Determine vNext = speed after current sim step (ballistic), resp. in current simstep (euler)
    4604              :     // Call to finalizeSpeed applies speed reduction due to dawdling / lane changing but ensures minimum safe speed
    4605    691010757 :     double vNext = vSafe;
    4606    691010757 :     const double rawAccel = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4607    691010757 :     if (vNext <= SUMO_const_haltingSpeed * TS && myWaitingTime > MSGlobals::gStartupWaitThreshold && rawAccel <= accelThresholdForWaiting() && myActionStep) {
    4608     69204560 :         myTimeSinceStartup = 0;
    4609    621806197 :     } else if (isStopped()) {
    4610              :         // do not apply startupDelay for waypoints
    4611     17660064 :         if (getCarFollowModel().startupDelayStopped() && getNextStop().pars.speed <= 0) {
    4612        13772 :             myTimeSinceStartup = DELTA_T;
    4613              :         } else {
    4614              :             // do not apply startupDelay but signal that a stop has taken place
    4615     17646292 :             myTimeSinceStartup = getCarFollowModel().getStartupDelay() + DELTA_T;
    4616              :         }
    4617              :     } else {
    4618              :         // identify potential startup (before other effects reduce the speed again)
    4619    604146133 :         myTimeSinceStartup += DELTA_T;
    4620              :     }
    4621    691010757 :     if (myActionStep) {
    4622    619374397 :         vNext = getCarFollowModel().finalizeSpeed(this, vSafe);
    4623    615349613 :         if (vNext > 0) {
    4624    574252428 :             vNext = MAX2(vNext, vSafeMin);
    4625              :         }
    4626              :     }
    4627              :     // (Leo) to avoid tiny oscillations (< 1e-10) of vNext in a standing vehicle column (observed for ballistic update), we cap off vNext
    4628              :     //       (We assure to do this only for vNext<<NUMERICAL_EPS since otherwise this would nullify the workaround for #2995
    4629              :     // (Jakob) We also need to make sure to reach a stop at the start of the next edge
    4630    686985973 :     if (fabs(vNext) < NUMERICAL_EPS_SPEED && (myStopDist > POSITION_EPS || (hasStops() && myCurrEdge == getNextStop().edge))) {
    4631              :         vNext = 0.;
    4632              :     }
    4633              : #ifdef DEBUG_EXEC_MOVE
    4634              :     if (DEBUG_COND) {
    4635              :         std::cout << SIMTIME << " finalizeSpeed vSafe=" << vSafe << " vSafeMin=" << (vSafeMin == -std::numeric_limits<double>::max() ? "-Inf" : toString(vSafeMin))
    4636              :                   << " vNext=" << vNext << " (i.e. accel=" << SPEED2ACCEL(vNext - getSpeed()) << ")" << std::endl;
    4637              :     }
    4638              : #endif
    4639              : 
    4640              :     // vNext may be higher than vSafe without implying a bug:
    4641              :     //  - when approaching a green light that suddenly switches to yellow
    4642              :     //  - when using unregulated junctions
    4643              :     //  - when using tau < step-size
    4644              :     //  - when using unsafe car following models
    4645              :     //  - when using TraCI and some speedMode / laneChangeMode settings
    4646              :     //if (vNext > vSafe + NUMERICAL_EPS) {
    4647              :     //    WRITE_WARNING("vehicle '" + getID() + "' cannot brake hard enough to reach safe speed "
    4648              :     //            + toString(vSafe, 4) + ", moving at " + toString(vNext, 4) + " instead. time="
    4649              :     //            + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    4650              :     //}
    4651              : 
    4652    686985973 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4653              :         vNext = MAX2(vNext, 0.);
    4654              :     } else {
    4655              :         // (Leo) Ballistic: negative vNext can be used to indicate a stop within next step.
    4656              :     }
    4657              : 
    4658              :     // Check for speed advices from the traci client
    4659    686985973 :     vNext = processTraCISpeedControl(vSafe, vNext);
    4660              : 
    4661              :     // the acceleration of a vehicle equipped with the elecHybrid device is restricted by the maximal power of the electric drive as well
    4662    686985973 :     MSDevice_ElecHybrid* elecHybridOfVehicle = dynamic_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid)));
    4663         1135 :     if (elecHybridOfVehicle != nullptr) {
    4664              :         // this is the consumption given by the car following model-computed acceleration
    4665         1135 :         elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4666              :         // but the maximum power of the electric motor may be lower
    4667              :         // it needs to be converted from [W] to [Wh/s] (3600s / 1h) so that TS can be taken into account
    4668         1135 :         double maxPower = getEmissionParameters()->getDoubleOptional(SUMO_ATTR_MAXIMUMPOWER, 100000.) / 3600;
    4669         1135 :         if (elecHybridOfVehicle->getConsum() / TS > maxPower) {
    4670              :             // no, we cannot accelerate that fast, recompute the maximum possible acceleration
    4671           70 :             double accel = elecHybridOfVehicle->acceleration(*this, maxPower, this->getSpeed());
    4672              :             // and update the speed of the vehicle
    4673           70 :             vNext = MIN2(vNext, this->getSpeed() + accel * TS);
    4674              :             vNext = MAX2(vNext, 0.);
    4675              :             // and set the vehicle consumption to reflect this
    4676           70 :             elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
    4677              :         }
    4678              :     }
    4679              : 
    4680    686985973 :     setBrakingSignals(vNext);
    4681              : 
    4682              :     // update position and speed
    4683    686985973 :     int oldLaneOffset = myLane->getEdge().getNumLanes() - myLane->getIndex();
    4684              :     const MSLane* oldLaneMaybeOpposite = myLane;
    4685    686985973 :     if (myLaneChangeModel->isOpposite()) {
    4686              :         // transform to the forward-direction lane, move and then transform back
    4687       405278 :         myState.myPos = myLane->getOppositePos(myState.myPos);
    4688       405278 :         myLane = myLane->getParallelOpposite();
    4689              :     }
    4690    686985973 :     updateState(vNext);
    4691    686985973 :     updateWaitingTime(vNext);
    4692              : 
    4693              :     // Lanes, which the vehicle touched at some moment of the executed simstep
    4694              :     std::vector<MSLane*> passedLanes;
    4695              :     // remember previous lane (myLane is updated in processLaneAdvances)
    4696    686985973 :     const MSLane* oldLane = myLane;
    4697              :     // Reason for a possible emergency stop
    4698              :     std::string emergencyReason;
    4699    686985973 :     processLaneAdvances(passedLanes, emergencyReason);
    4700              : 
    4701    686985973 :     updateTimeLoss(vNext);
    4702    686985973 :     myCollisionImmunity = MAX2((SUMOTime) - 1, myCollisionImmunity - DELTA_T);
    4703              : 
    4704    686985973 :     if (!hasArrivedInternal() && !myLane->getEdge().isVaporizing()) {
    4705    683577852 :         if (myState.myPos > myLane->getLength()) {
    4706          348 :             if (emergencyReason == "") {
    4707           31 :                 emergencyReason = TL(" for unknown reasons");
    4708              :             }
    4709         1392 :             WRITE_WARNINGF(TL("Vehicle '%' performs emergency stop at the end of lane '%'% (decel=%, offset=%), time=%."),
    4710              :                            getID(), myLane->getID(), emergencyReason, myAcceleration - myState.mySpeed,
    4711              :                            myState.myPos - myLane->getLength(), time2string(SIMSTEP));
    4712          348 :             MSNet::getInstance()->getVehicleControl().registerEmergencyStop();
    4713          348 :             MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::EMERGENCYSTOP);
    4714          348 :             myState.myPos = myLane->getLength();
    4715          348 :             myState.mySpeed = 0;
    4716          348 :             myAcceleration = 0;
    4717              :         }
    4718    683577852 :         const MSLane* oldBackLane = getBackLane();
    4719    683577852 :         if (myLaneChangeModel->isOpposite()) {
    4720              :             passedLanes.clear(); // ignore back occupation
    4721              :         }
    4722              : #ifdef DEBUG_ACTIONSTEPS
    4723              :         if (DEBUG_COND) {
    4724              :             std::cout << SIMTIME << " veh '" << getID() << "' updates further lanes." << std::endl;
    4725              :         }
    4726              : #endif
    4727    683577852 :         myState.myBackPos = updateFurtherLanes(myFurtherLanes, myFurtherLanesPosLat, passedLanes);
    4728    683577852 :         if (passedLanes.size() > 1 && isRail()) {
    4729       735982 :             for (auto pi = passedLanes.rbegin(); pi != passedLanes.rend(); ++pi) {
    4730       558292 :                 MSLane* pLane = *pi;
    4731       558292 :                 if (pLane != myLane && std::find(myFurtherLanes.begin(), myFurtherLanes.end(), pLane) == myFurtherLanes.end()) {
    4732        39658 :                     leaveLaneBack(MSMoveReminder::NOTIFICATION_JUNCTION, *pi);
    4733              :                 }
    4734              :             }
    4735              :         }
    4736              :         // bestLanes need to be updated before lane changing starts. NOTE: This call is also a presumption for updateDriveItems()
    4737    683577852 :         updateBestLanes();
    4738    683577852 :         if (myLane != oldLane || oldBackLane != getBackLane()) {
    4739     25160583 :             if (myLaneChangeModel->getShadowLane() != nullptr || getLateralOverlap() > POSITION_EPS) {
    4740              :                 // shadow lane must be updated if the front or back lane changed
    4741              :                 // either if we already have a shadowLane or if there is lateral overlap
    4742       504169 :                 myLaneChangeModel->updateShadowLane();
    4743              :             }
    4744     25160583 :             if (MSGlobals::gLateralResolution > 0 && !myLaneChangeModel->isOpposite()) {
    4745              :                 // The vehicles target lane must be also be updated if the front or back lane changed
    4746      4292701 :                 myLaneChangeModel->updateTargetLane();
    4747              :             }
    4748              :         }
    4749    683577852 :         setBlinkerInformation(); // needs updated bestLanes
    4750              :         //change the blue light only for emergency vehicles SUMOVehicleClass
    4751    683577852 :         if (myType->getVehicleClass() == SVC_EMERGENCY) {
    4752        85748 :             setEmergencyBlueLight(MSNet::getInstance()->getCurrentTimeStep());
    4753              :         }
    4754              :         // must be done before angle computation
    4755              :         // State needs to be reset for all vehicles before the next call to MSEdgeControl::changeLanes
    4756    683577852 :         if (myActionStep) {
    4757              :             // check (#2681): Can this be skipped?
    4758    611962700 :             myLaneChangeModel->prepareStep();
    4759              :         } else {
    4760     71615152 :             myLaneChangeModel->resetSpeedLat();
    4761              : #ifdef DEBUG_ACTIONSTEPS
    4762              :             if (DEBUG_COND) {
    4763              :                 std::cout << SIMTIME << " veh '" << getID() << "' skips LCM->prepareStep()." << std::endl;
    4764              :             }
    4765              : #endif
    4766              :         }
    4767    683577852 :         myLaneChangeModel->setPreviousAngleOffset(myLaneChangeModel->getAngleOffset());
    4768    683577852 :         myAngle = computeAngle();
    4769              :     }
    4770              : 
    4771              : #ifdef DEBUG_EXEC_MOVE
    4772              :     if (DEBUG_COND) {
    4773              :         std::cout << SIMTIME << " executeMove finished veh=" << getID() << " lane=" << myLane->getID() << " myPos=" << getPositionOnLane() << " myPosLat=" << getLateralPositionOnLane() << "\n";
    4774              :         gDebugFlag1 = false; // See MSLink_DEBUG_OPENED
    4775              :     }
    4776              : #endif
    4777    686985973 :     if (myLaneChangeModel->isOpposite()) {
    4778              :         // transform back to the opposite-direction lane
    4779              :         MSLane* newOpposite = nullptr;
    4780       405278 :         const MSEdge* newOppositeEdge = myLane->getEdge().getOppositeEdge();
    4781       405278 :         if (newOppositeEdge != nullptr) {
    4782       405228 :             newOpposite = newOppositeEdge->getLanes()[newOppositeEdge->getNumLanes() - MAX2(1, oldLaneOffset)];
    4783              : #ifdef DEBUG_EXEC_MOVE
    4784              :             if (DEBUG_COND) {
    4785              :                 std::cout << SIMTIME << "   newOppositeEdge=" << newOppositeEdge->getID() << " oldLaneOffset=" << oldLaneOffset << " leftMost=" << newOppositeEdge->getNumLanes() - 1 << " newOpposite=" << Named::getIDSecure(newOpposite) << "\n";
    4786              :             }
    4787              : #endif
    4788              :         }
    4789       405228 :         if (newOpposite == nullptr) {
    4790           50 :             if (!myLaneChangeModel->hasBlueLight()) {
    4791              :                 // unusual overtaking at junctions is ok for emergency vehicles
    4792            0 :                 WRITE_WARNINGF(TL("Unexpected end of opposite lane for vehicle '%' at lane '%', time=%."),
    4793              :                                getID(), myLane->getID(), time2string(SIMSTEP));
    4794              :             }
    4795           50 :             myLaneChangeModel->changedToOpposite();
    4796           50 :             if (myState.myPos < getLength()) {
    4797              :                 // further lanes is always cleared during opposite driving
    4798           50 :                 MSLane* oldOpposite = oldLane->getOpposite();
    4799           50 :                 if (oldOpposite != nullptr) {
    4800           50 :                     myFurtherLanes.push_back(oldOpposite);
    4801           50 :                     myFurtherLanesPosLat.push_back(0);
    4802              :                     // small value since the lane is going in the other direction
    4803           50 :                     myState.myBackPos = getLength() - myState.myPos;
    4804           50 :                     myAngle = computeAngle();
    4805              :                 } else {
    4806              :                     SOFT_ASSERT(false);
    4807              :                 }
    4808              :             }
    4809              :         } else {
    4810       405228 :             myState.myPos = myLane->getOppositePos(myState.myPos);
    4811       405228 :             myLane = newOpposite;
    4812              :             oldLane = oldLaneMaybeOpposite;
    4813              :             //std::cout << SIMTIME << " updated myLane=" << Named::getIDSecure(myLane) << " oldLane=" << oldLane->getID() << "\n";
    4814       405228 :             myCachedPosition = Position::INVALID;
    4815       405228 :             myLaneChangeModel->updateShadowLane();
    4816              :         }
    4817              :     }
    4818    686985973 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4819              :     // Return whether the vehicle did move to another lane
    4820   1373971946 :     return myLane != oldLane;
    4821    686985973 : }
    4822              : 
    4823              : void
    4824       213956 : MSVehicle::executeFractionalMove(double dist) {
    4825       213956 :     myState.myPos += dist;
    4826       213956 :     myState.myLastCoveredDist = dist;
    4827       213956 :     myCachedPosition = Position::INVALID;
    4828              : 
    4829       213956 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(dist);
    4830       213956 :     const SUMOTime t = MSNet::getInstance()->getCurrentTimeStep();
    4831       443917 :     for (int i = 0; i < (int)lanes.size(); i++) {
    4832       229961 :         MSLink* link = nullptr;
    4833       229961 :         if (i + 1 < (int)lanes.size()) {
    4834        16005 :             const MSLane* const to = lanes[i + 1];
    4835        16005 :             const bool internal = to->isInternal();
    4836        16010 :             for (MSLink* const l : lanes[i]->getLinkCont()) {
    4837        16010 :                 if ((internal && l->getViaLane() == to) || (!internal && l->getLane() == to)) {
    4838        16005 :                     link = l;
    4839        16005 :                     break;
    4840              :                 }
    4841              :             }
    4842              :         }
    4843       229961 :         myLFLinkLanes.emplace_back(link, getSpeed(), getSpeed(), true, t, getSpeed(), 0, 0, dist);
    4844              :     }
    4845              :     // minimum execute move:
    4846              :     std::vector<MSLane*> passedLanes;
    4847              :     // Reason for a possible emergency stop
    4848       213956 :     if (lanes.size() > 1) {
    4849         4005 :         myLane->removeVehicle(this, MSMoveReminder::NOTIFICATION_JUNCTION, false);
    4850              :     }
    4851              :     std::string emergencyReason;
    4852       213956 :     processLaneAdvances(passedLanes, emergencyReason);
    4853              : #ifdef DEBUG_EXTRAPOLATE_DEPARTPOS
    4854              :     if (DEBUG_COND) {
    4855              :         std::cout << SIMTIME << " veh=" << getID() << " executeFractionalMove dist=" << dist
    4856              :                   << " passedLanes=" << toString(passedLanes) << " lanes=" << toString(lanes)
    4857              :                   << " finalPos=" << myState.myPos
    4858              :                   << " speed=" << getSpeed()
    4859              :                   << " myFurtherLanes=" << toString(myFurtherLanes)
    4860              :                   << "\n";
    4861              :     }
    4862              : #endif
    4863       213956 :     workOnMoveReminders(myState.myPos - myState.myLastCoveredDist, myState.myPos, myState.mySpeed);
    4864       213956 :     if (lanes.size() > 1) {
    4865         4010 :         for (std::vector<MSLane*>::iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    4866              : #ifdef DEBUG_FURTHER
    4867              :             if (DEBUG_COND) {
    4868              :                 std::cout << SIMTIME << " leaveLane \n";
    4869              :             }
    4870              : #endif
    4871            5 :             (*i)->resetPartialOccupation(this);
    4872              :         }
    4873              :         myFurtherLanes.clear();
    4874              :         myFurtherLanesPosLat.clear();
    4875         4005 :         myLane->forceVehicleInsertion(this, getPositionOnLane(), MSMoveReminder::NOTIFICATION_JUNCTION, getLateralPositionOnLane());
    4876              :     }
    4877       213956 : }
    4878              : 
    4879              : 
    4880              : void
    4881    695203978 : MSVehicle::updateState(double vNext, bool parking) {
    4882              :     // update position and speed
    4883              :     double deltaPos; // positional change
    4884    695203978 :     if (MSGlobals::gSemiImplicitEulerUpdate) {
    4885              :         // euler
    4886    596098987 :         deltaPos = SPEED2DIST(vNext);
    4887              :     } else {
    4888              :         // ballistic
    4889     99104991 :         deltaPos = getDeltaPos(SPEED2ACCEL(vNext - myState.mySpeed));
    4890              :     }
    4891              : 
    4892              :     // the *mean* acceleration during the next step (probably most appropriate for emission calculation)
    4893              :     // NOTE: for the ballistic update vNext may be negative, indicating a stop.
    4894    695203978 :     myAcceleration = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
    4895              : 
    4896              : #ifdef DEBUG_EXEC_MOVE
    4897              :     if (DEBUG_COND) {
    4898              :         std::cout << SIMTIME << " updateState() for veh '" << getID() << "': deltaPos=" << deltaPos
    4899              :                   << " pos=" << myState.myPos << " newPos=" << myState.myPos + deltaPos << std::endl;
    4900              :     }
    4901              : #endif
    4902    695203978 :     double decelPlus = -myAcceleration - getCarFollowModel().getMaxDecel() - NUMERICAL_EPS;
    4903    695203978 :     if (decelPlus > 0) {
    4904       420914 :         const double previousAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    4905       420914 :         if (myAcceleration + NUMERICAL_EPS < previousAcceleration) {
    4906              :             // vehicle brakes beyond wished maximum deceleration (only warn at the start of the braking manoeuvre)
    4907       287928 :             decelPlus += 2 * NUMERICAL_EPS;
    4908       287928 :             const double emergencyFraction = decelPlus / MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel());
    4909       287928 :             if (emergencyFraction >= MSGlobals::gEmergencyDecelWarningThreshold) {
    4910        93945 :                 WRITE_WARNINGF(TL("Vehicle '%' performs emergency braking on lane '%' with decel=%, wished=%, severity=%, time=%."),
    4911              :                                //+ " decelPlus=" + toString(decelPlus)
    4912              :                                //+ " prevAccel=" + toString(previousAcceleration)
    4913              :                                //+ " reserve=" + toString(MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel()))
    4914              :                                getID(), myLane->getID(), -myAcceleration, getCarFollowModel().getMaxDecel(), emergencyFraction, time2string(SIMSTEP));
    4915        31315 :                 MSNet::getInstance()->getVehicleControl().registerEmergencyBraking();
    4916              :             }
    4917              :         }
    4918              :     }
    4919              : 
    4920    695203978 :     myState.myPreviousSpeed = myState.mySpeed;
    4921    695203978 :     myState.mySpeed = MAX2(vNext, 0.);
    4922              : 
    4923    695203978 :     if (isRemoteControlled()) {
    4924         7580 :         deltaPos = myInfluencer->implicitDeltaPosRemote(this);
    4925              :     }
    4926              : 
    4927    695203978 :     myState.myPos += deltaPos;
    4928    695203978 :     myState.myLastCoveredDist = deltaPos;
    4929    695203978 :     myNextTurn.first -= deltaPos;
    4930              : 
    4931    695203978 :     if (!parking) {
    4932    686985973 :         myCachedPosition = Position::INVALID;
    4933              :     }
    4934    695203978 : }
    4935              : 
    4936              : void
    4937      8218005 : MSVehicle::updateParkingState() {
    4938      8218005 :     updateState(0, true);
    4939              :     // deboard while parked
    4940      8218005 :     if (myPersonDevice != nullptr) {
    4941       586422 :         myPersonDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    4942              :     }
    4943      8218005 :     if (myContainerDevice != nullptr) {
    4944        59887 :         myContainerDevice->notifyMove(*this, getPositionOnLane(), getPositionOnLane(), 0);
    4945              :     }
    4946     16499583 :     for (MSVehicleDevice* const dev : myDevices) {
    4947      8281578 :         dev->notifyParking();
    4948              :     }
    4949      8218005 : }
    4950              : 
    4951              : 
    4952              : void
    4953        30625 : MSVehicle::replaceVehicleType(const MSVehicleType* type) {
    4954        30625 :     MSBaseVehicle::replaceVehicleType(type);
    4955        30625 :     delete myCFVariables;
    4956        30625 :     myCFVariables = type->getCarFollowModel().createVehicleVariables();
    4957        30625 : }
    4958              : 
    4959              : 
    4960              : const MSLane*
    4961   1350892680 : MSVehicle::getBackLane() const {
    4962   1350892680 :     if (myFurtherLanes.size() > 0) {
    4963     18361528 :         return myFurtherLanes.back();
    4964              :     } else {
    4965   1332531152 :         return myLane;
    4966              :     }
    4967              : }
    4968              : 
    4969              : 
    4970              : double
    4971    688905863 : MSVehicle::updateFurtherLanes(std::vector<MSLane*>& furtherLanes, std::vector<double>& furtherLanesPosLat,
    4972              :                               const std::vector<MSLane*>& passedLanes) {
    4973              : #ifdef DEBUG_SETFURTHER
    4974              :     if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID()
    4975              :                                   << " updateFurtherLanes oldFurther=" << toString(furtherLanes)
    4976              :                                   << " oldFurtherPosLat=" << toString(furtherLanesPosLat)
    4977              :                                   << " passed=" << toString(passedLanes)
    4978              :                                   << "\n";
    4979              : #endif
    4980    704462854 :     for (MSLane* further : furtherLanes) {
    4981     15556991 :         further->resetPartialOccupation(this);
    4982     15556991 :         if (further->getBidiLane() != nullptr
    4983     15556991 :                 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    4984        25723 :             further->getBidiLane()->resetPartialOccupation(this);
    4985              :         }
    4986              :     }
    4987              : 
    4988              :     std::vector<MSLane*> newFurther;
    4989              :     std::vector<double> newFurtherPosLat;
    4990    688905863 :     double backPosOnPreviousLane = myState.myPos - getLength();
    4991              :     bool widthShift = myFurtherLanesPosLat.size() > myFurtherLanes.size();
    4992    688905863 :     if (passedLanes.size() > 1) {
    4993              :         // There are candidates for further lanes. (passedLanes[-1] is the current lane, or current shadow lane in context of updateShadowLanes())
    4994              :         std::vector<MSLane*>::const_iterator fi = furtherLanes.begin();
    4995              :         std::vector<double>::const_iterator fpi = furtherLanesPosLat.begin();
    4996     44396344 :         for (auto pi = passedLanes.rbegin() + 1; pi != passedLanes.rend() && backPosOnPreviousLane < 0; ++pi) {
    4997              :             // As long as vehicle back reaches into passed lane, add it to the further lanes
    4998     15491557 :             MSLane* further = *pi;
    4999     15491557 :             newFurther.push_back(further);
    5000     15491557 :             backPosOnPreviousLane += further->setPartialOccupation(this);
    5001     15491557 :             if (further->getBidiLane() != nullptr
    5002     15491557 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5003        25238 :                 further->getBidiLane()->setPartialOccupation(this);
    5004              :             }
    5005     15491557 :             if (fi != furtherLanes.end() && further == *fi) {
    5006              :                 // Lateral position on this lane is already known. Assume constant and use old value.
    5007      5128134 :                 newFurtherPosLat.push_back(*fpi);
    5008              :                 ++fi;
    5009              :                 ++fpi;
    5010              :             } else {
    5011              :                 // The lane *pi was not in furtherLanes before.
    5012              :                 // If it is downstream, we assume as lateral position the current position
    5013              :                 // If it is a new lane upstream (can appear as shadow further in case of LC-maneuvering, e.g.)
    5014              :                 // we assign the last known lateral position.
    5015     10363423 :                 if (newFurtherPosLat.size() == 0) {
    5016      9763963 :                     if (widthShift) {
    5017      1447323 :                         newFurtherPosLat.push_back(myFurtherLanesPosLat.back());
    5018              :                     } else {
    5019      8316640 :                         newFurtherPosLat.push_back(myState.myPosLat);
    5020              :                     }
    5021              :                 } else {
    5022       599460 :                     newFurtherPosLat.push_back(newFurtherPosLat.back());
    5023              :                 }
    5024              :             }
    5025              : #ifdef DEBUG_SETFURTHER
    5026              :             if (DEBUG_COND) {
    5027              :                 std::cout << SIMTIME << " updateFurtherLanes \n"
    5028              :                           << "    further lane '" << further->getID() << "' backPosOnPreviousLane=" << backPosOnPreviousLane
    5029              :                           << std::endl;
    5030              :             }
    5031              : #endif
    5032              :         }
    5033     28904787 :         furtherLanes = newFurther;
    5034     28904787 :         furtherLanesPosLat = newFurtherPosLat;
    5035              :     } else {
    5036              :         furtherLanes.clear();
    5037              :         furtherLanesPosLat.clear();
    5038              :     }
    5039              : #ifdef DEBUG_SETFURTHER
    5040              :     if (DEBUG_COND) std::cout
    5041              :                 << " newFurther=" << toString(furtherLanes)
    5042              :                 << " newFurtherPosLat=" << toString(furtherLanesPosLat)
    5043              :                 << " newBackPos=" << backPosOnPreviousLane
    5044              :                 << "\n";
    5045              : #endif
    5046    688905863 :     return backPosOnPreviousLane;
    5047    688905863 : }
    5048              : 
    5049              : 
    5050              : double
    5051  33877254404 : MSVehicle::getBackPositionOnLane(const MSLane* lane, bool calledByGetPosition) const {
    5052              : #ifdef DEBUG_FURTHER
    5053              :     if (DEBUG_COND) {
    5054              :         std::cout << SIMTIME
    5055              :                   << " getBackPositionOnLane veh=" << getID()
    5056              :                   << " lane=" << Named::getIDSecure(lane)
    5057              :                   << " cbgP=" << calledByGetPosition
    5058              :                   << " pos=" << myState.myPos
    5059              :                   << " backPos=" << myState.myBackPos
    5060              :                   << " myLane=" << myLane->getID()
    5061              :                   << " myLaneBidi=" << Named::getIDSecure(myLane->getBidiLane())
    5062              :                   << " further=" << toString(myFurtherLanes)
    5063              :                   << " furtherPosLat=" << toString(myFurtherLanesPosLat)
    5064              :                   << "\n     shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    5065              :                   << " shadowFurther=" << toString(myLaneChangeModel->getShadowFurtherLanes())
    5066              :                   << " shadowFurtherPosLat=" << toString(myLaneChangeModel->getShadowFurtherLanesPosLat())
    5067              :                   << "\n     targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    5068              :                   << " furtherTargets=" << toString(myLaneChangeModel->getFurtherTargetLanes())
    5069              :                   << std::endl;
    5070              :     }
    5071              : #endif
    5072  33877254404 :     if (lane == myLane
    5073   8372876431 :             || lane == myLaneChangeModel->getShadowLane()
    5074  38791003812 :             || lane == myLaneChangeModel->getTargetLane()) {
    5075  28965080029 :         if (myLaneChangeModel->isOpposite()) {
    5076    231218817 :             if (lane == myLaneChangeModel->getShadowLane()) {
    5077    199114316 :                 return lane->getLength() - myState.myPos - myType->getLength();
    5078              :             } else {
    5079     36893982 :                 return myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5080              :             }
    5081  28733861212 :         } else if (&lane->getEdge() != &myLane->getEdge()) {
    5082     20714784 :             return lane->getLength() - myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
    5083              :         } else {
    5084              :             // account for parallel lanes of different lengths in the most conservative manner (i.e. while turning)
    5085  57426992962 :             return myState.myPos - myType->getLength() + MIN2(0.0, lane->getLength() - myLane->getLength());
    5086              :         }
    5087   4912174375 :     } else if (lane == myLane->getBidiLane()) {
    5088      3965086 :         return lane->getLength() - myState.myPos + myType->getLength() * (calledByGetPosition ? -1 : 1);
    5089   4909713458 :     } else if (myFurtherLanes.size() > 0 && lane == myFurtherLanes.back()) {
    5090   4862997096 :         return myState.myBackPos;
    5091     46716362 :     } else if ((myLaneChangeModel->getShadowFurtherLanes().size() > 0 && lane == myLaneChangeModel->getShadowFurtherLanes().back())
    5092     47294223 :                || (myLaneChangeModel->getFurtherTargetLanes().size() > 0 && lane == myLaneChangeModel->getFurtherTargetLanes().back())) {
    5093              :         assert(myFurtherLanes.size() > 0);
    5094     18864054 :         if (lane->getLength() == myFurtherLanes.back()->getLength()) {
    5095     18199967 :             return myState.myBackPos;
    5096              :         } else {
    5097              :             // interpolate
    5098              :             //if (DEBUG_COND) {
    5099              :             //if (myFurtherLanes.back()->getLength() != lane->getLength()) {
    5100              :             //    std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " further=" << myFurtherLanes.back()->getID()
    5101              :             //        << " len=" << lane->getLength() << " fLen=" << myFurtherLanes.back()->getLength()
    5102              :             //        << " backPos=" << myState.myBackPos << " result=" << myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength() << "\n";
    5103              :             //}
    5104       664087 :             return myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength();
    5105              :         }
    5106              :     } else {
    5107              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherLanes=" << toString(myFurtherLanes) << "\n";
    5108     27852308 :         double leftLength = myType->getLength() - myState.myPos;
    5109              : 
    5110              :         std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin();
    5111     29826176 :         while (leftLength > 0 && i != myFurtherLanes.end()) {
    5112     29800574 :             leftLength -= (*i)->getLength();
    5113              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5114     29800574 :             if (*i == lane) {
    5115     27538242 :                 return -leftLength;
    5116      2262332 :             } else if (*i == lane->getBidiLane()) {
    5117       288464 :                 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
    5118              :             }
    5119              :             ++i;
    5120              :         }
    5121              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    5122        25602 :         leftLength = myType->getLength() - myState.myPos;
    5123        25602 :         i = myLaneChangeModel->getShadowFurtherLanes().begin();
    5124        25602 :         while (leftLength > 0 && i != myLaneChangeModel->getShadowFurtherLanes().end()) {
    5125        25600 :             leftLength -= (*i)->getLength();
    5126              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5127        25600 :             if (*i == lane) {
    5128        25600 :                 return -leftLength;
    5129              :             }
    5130              :             ++i;
    5131              :         }
    5132              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherTargetLanes=" << toString(myLaneChangeModel->getFurtherTargetLanes()) << "\n";
    5133              :         leftLength = myType->getLength() - myState.myPos;
    5134              :         i = getFurtherLanes().begin();
    5135            2 :         const std::vector<MSLane*> furtherTargetLanes = myLaneChangeModel->getFurtherTargetLanes();
    5136              :         auto j = furtherTargetLanes.begin();
    5137            3 :         while (leftLength > 0 && j != furtherTargetLanes.end()) {
    5138            3 :             leftLength -= (*i)->getLength();
    5139              :             // if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    5140            3 :             if (*j == lane) {
    5141            2 :                 return -leftLength;
    5142              :             }
    5143              :             ++i;
    5144              :             ++j;
    5145              :         }
    5146            0 :         WRITE_WARNING("Request backPos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane)
    5147              :                       + "' time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".")
    5148              :         SOFT_ASSERT(false);
    5149            0 :         return  myState.myBackPos;
    5150            2 :     }
    5151              : }
    5152              : 
    5153              : 
    5154              : double
    5155  27270903175 : MSVehicle::getPositionOnLane(const MSLane* lane) const {
    5156  27270903175 :     return getBackPositionOnLane(lane, true) + myType->getLength();
    5157              : }
    5158              : 
    5159              : 
    5160              : bool
    5161    417463763 : MSVehicle::isFrontOnLane(const MSLane* lane) const {
    5162    417463763 :     return lane == myLane || lane == myLaneChangeModel->getShadowLane() || lane == myLane->getBidiLane();
    5163              : }
    5164              : 
    5165              : 
    5166              : void
    5167    619374397 : MSVehicle::checkRewindLinkLanes(const double lengthsInFront, DriveItemVector& lfLinks) const {
    5168    619374397 :     if (MSGlobals::gUsingInternalLanes && !myLane->getEdge().isRoundabout() && !myLaneChangeModel->isOpposite()) {
    5169    616188556 :         double seenSpace = -lengthsInFront;
    5170              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5171              :         if (DEBUG_COND) {
    5172              :             std::cout << "\nCHECK_REWIND_LINKLANES\n" << " veh=" << getID() << " lengthsInFront=" << lengthsInFront << "\n";
    5173              :         };
    5174              : #endif
    5175    616188556 :         bool foundStopped = false;
    5176              :         // compute available space until a stopped vehicle is found
    5177              :         // this is the sum of non-interal lane length minus in-between vehicle lengths
    5178   1788064354 :         for (int i = 0; i < (int)lfLinks.size(); ++i) {
    5179              :             // skip unset links
    5180   1171875798 :             DriveProcessItem& item = lfLinks[i];
    5181              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5182              :             if (DEBUG_COND) std::cout << SIMTIME
    5183              :                                           << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5184              :                                           << " foundStopped=" << foundStopped;
    5185              : #endif
    5186   1171875798 :             if (item.myLink == nullptr || foundStopped) {
    5187    389397488 :                 if (!foundStopped) {
    5188    339616163 :                     item.availableSpace += seenSpace;
    5189              :                 } else {
    5190     49781325 :                     item.availableSpace = seenSpace;
    5191              :                 }
    5192              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5193              :                 if (DEBUG_COND) {
    5194              :                     std::cout << " avail=" << item.availableSpace << "\n";
    5195              :                 }
    5196              : #endif
    5197    389397488 :                 continue;
    5198              :             }
    5199              :             // get the next lane, determine whether it is an internal lane
    5200              :             const MSLane* approachedLane = item.myLink->getViaLane();
    5201    782478310 :             if (approachedLane != nullptr) {
    5202    424696796 :                 if (keepClear(item.myLink)) {
    5203    124571572 :                     seenSpace = seenSpace - approachedLane->getBruttoVehLenSum();
    5204    124571572 :                     if (approachedLane == myLane) {
    5205        51446 :                         seenSpace += getVehicleType().getLengthWithGap();
    5206              :                     }
    5207              :                 } else {
    5208    300125224 :                     seenSpace = seenSpace + approachedLane->getSpaceTillLastStanding(this, foundStopped);// - approachedLane->getBruttoVehLenSum() + approachedLane->getLength();
    5209              :                 }
    5210    424696796 :                 item.availableSpace = seenSpace;
    5211              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5212              :                 if (DEBUG_COND) std::cout
    5213              :                             << " approached=" << approachedLane->getID()
    5214              :                             << " approachedBrutto=" << approachedLane->getBruttoVehLenSum()
    5215              :                             << " avail=" << item.availableSpace
    5216              :                             << " seenSpace=" << seenSpace
    5217              :                             << " hadStoppedVehicle=" << item.hadStoppedVehicle
    5218              :                             << " lengthsInFront=" << lengthsInFront
    5219              :                             << "\n";
    5220              : #endif
    5221    424696796 :                 continue;
    5222              :             }
    5223              :             approachedLane = item.myLink->getLane();
    5224    357781514 :             const MSVehicle* last = approachedLane->getLastAnyVehicle();
    5225    357781514 :             if (last == nullptr || last == this) {
    5226     54474925 :                 if (approachedLane->getLength() > getVehicleType().getLength()
    5227     54474925 :                         || keepClear(item.myLink)) {
    5228     52163361 :                     seenSpace += approachedLane->getLength();
    5229              :                 }
    5230     54474925 :                 item.availableSpace = seenSpace;
    5231              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5232              :                 if (DEBUG_COND) {
    5233              :                     std::cout << " last=" << Named::getIDSecure(last) << " laneLength=" << approachedLane->getLength() << " avail=" << item.availableSpace << "\n";
    5234              :                 }
    5235              : #endif
    5236              :             } else {
    5237    303306589 :                 bool foundStopped2 = false;
    5238    303306589 :                 double spaceTillLastStanding = approachedLane->getSpaceTillLastStanding(this, foundStopped2);
    5239    303306589 :                 if (approachedLane->getBidiLane() != nullptr) {
    5240        76039 :                     const MSVehicle* oncomingVeh = approachedLane->getBidiLane()->getFirstFullVehicle();
    5241        76039 :                     if (oncomingVeh) {
    5242        24164 :                         const double oncomingGap = approachedLane->getLength() - oncomingVeh->getPositionOnLane();
    5243        24164 :                         const double oncomingBGap = oncomingVeh->getBrakeGap(true);
    5244              :                         // oncoming movement until ego enters the junction
    5245        24164 :                         const double oncomingMove = STEPS2TIME(item.myArrivalTime - SIMSTEP) * oncomingVeh->getSpeed();
    5246        24164 :                         const double spaceTillOncoming = oncomingGap - oncomingBGap - oncomingMove;
    5247              :                         spaceTillLastStanding = MIN2(spaceTillLastStanding, spaceTillOncoming);
    5248        24164 :                         if (spaceTillOncoming <= getVehicleType().getLengthWithGap()) {
    5249        19465 :                             foundStopped = true;
    5250              :                         }
    5251              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5252              :                         if (DEBUG_COND) {
    5253              :                             std::cout << " oVeh=" << oncomingVeh->getID()
    5254              :                                       << " oGap=" << oncomingGap
    5255              :                                       << " bGap=" << oncomingBGap
    5256              :                                       << " mGap=" << oncomingMove
    5257              :                                       << " sto=" << spaceTillOncoming;
    5258              :                         }
    5259              : #endif
    5260              :                     }
    5261              :                 }
    5262    303306589 :                 seenSpace += spaceTillLastStanding;
    5263    303306589 :                 if (foundStopped2) {
    5264     19177083 :                     foundStopped = true;
    5265     19177083 :                     item.hadStoppedVehicle = true;
    5266              :                 }
    5267    303306589 :                 item.availableSpace = seenSpace;
    5268    303306589 :                 if (last->myHaveToWaitOnNextLink || last->isStopped()) {
    5269     29602716 :                     foundStopped = true;
    5270     29602716 :                     item.hadStoppedVehicle = true;
    5271              :                 }
    5272              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5273              :                 if (DEBUG_COND) std::cout
    5274              :                             << " approached=" << approachedLane->getID()
    5275              :                             << " last=" << last->getID()
    5276              :                             << " lastHasToWait=" << last->myHaveToWaitOnNextLink
    5277              :                             << " lastBrakeLight=" << last->signalSet(VEH_SIGNAL_BRAKELIGHT)
    5278              :                             << " lastBrakeGap=" << last->getCarFollowModel().brakeGap(last->getSpeed())
    5279              :                             << " lastGap=" << (last->getBackPositionOnLane(approachedLane) + last->getCarFollowModel().brakeGap(last->getSpeed()) - last->getSpeed() * last->getCarFollowModel().getHeadwayTime()
    5280              :                                                // gap of last up to the next intersection
    5281              :                                                - last->getVehicleType().getMinGap())
    5282              :                             << " stls=" << spaceTillLastStanding
    5283              :                             << " avail=" << item.availableSpace
    5284              :                             << " seenSpace=" << seenSpace
    5285              :                             << " foundStopped=" << foundStopped
    5286              :                             << " foundStopped2=" << foundStopped2
    5287              :                             << "\n";
    5288              : #endif
    5289              :             }
    5290              :         }
    5291              : 
    5292              :         // check which links allow continuation and add pass available to the previous item
    5293   1171875798 :         for (int i = ((int)lfLinks.size() - 1); i > 0; --i) {
    5294    555687242 :             DriveProcessItem& item = lfLinks[i - 1];
    5295    555687242 :             DriveProcessItem& nextItem = lfLinks[i];
    5296    555687242 :             const bool canLeaveJunction = item.myLink->getViaLane() == nullptr || nextItem.myLink == nullptr || nextItem.mySetRequest;
    5297              :             const bool opened = (item.myLink != nullptr
    5298    555687242 :                                  && (canLeaveJunction || (
    5299              :                                          // indirect bicycle turn
    5300     25810453 :                                          nextItem.myLink != nullptr && nextItem.myLink->isInternalJunctionLink() && nextItem.myLink->haveRed()))
    5301    529890851 :                                  && (
    5302    529890851 :                                      item.myLink->havePriority()
    5303     25494646 :                                      || i == 1 // the upcoming link (item 0) is checked in executeMove anyway. No need to use outdata approachData here
    5304      4626007 :                                      || (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority())
    5305      4596574 :                                      || item.myLink->opened(item.myArrivalTime, item.myArrivalSpeed,
    5306      4596574 :                                              item.getLeaveSpeed(), getVehicleType().getLength(),
    5307      4596574 :                                              getImpatience(), getCarFollowModel().getMaxDecel(), getWaitingTime(), getLateralPositionOnLane(), nullptr, false, this)));
    5308    555687242 :             bool allowsContinuation = (item.myLink == nullptr || item.myLink->isCont() || opened) && !item.hadStoppedVehicle;
    5309              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5310              :             if (DEBUG_COND) std::cout
    5311              :                         << "   link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5312              :                         << " canLeave=" << canLeaveJunction
    5313              :                         << " opened=" << opened
    5314              :                         << " allowsContinuation=" << allowsContinuation
    5315              :                         << " foundStopped=" << foundStopped
    5316              :                         << "\n";
    5317              : #endif
    5318    555687242 :             if (!opened && item.myLink != nullptr) {
    5319     26378496 :                 foundStopped = true;
    5320     26378496 :                 if (i > 1) {
    5321      4122218 :                     DriveProcessItem& item2 = lfLinks[i - 2];
    5322      4122218 :                     if (item2.myLink != nullptr && item2.myLink->isCont()) {
    5323              :                         allowsContinuation = true;
    5324              :                     }
    5325              :                 }
    5326              :             }
    5327    553271449 :             if (allowsContinuation) {
    5328    499388939 :                 item.availableSpace = nextItem.availableSpace;
    5329              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5330              :                 if (DEBUG_COND) std::cout
    5331              :                             << "   link=" << (item.myLink == nullptr ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5332              :                             << " copy nextAvail=" << nextItem.availableSpace
    5333              :                             << "\n";
    5334              : #endif
    5335              :             }
    5336              :         }
    5337              : 
    5338              :         // find removalBegin
    5339              :         int removalBegin = -1;
    5340    737085852 :         for (int i = 0; foundStopped && i < (int)lfLinks.size() && removalBegin < 0; ++i) {
    5341              :             // skip unset links
    5342    120897296 :             const DriveProcessItem& item = lfLinks[i];
    5343    120897296 :             if (item.myLink == nullptr) {
    5344      6128072 :                 continue;
    5345              :             }
    5346              :             /*
    5347              :             double impatienceCorrection = MAX2(0., double(double(myWaitingTime)));
    5348              :             if (seenSpace<getVehicleType().getLengthWithGap()-impatienceCorrection/10.&&nextSeenNonInternal!=0) {
    5349              :                 removalBegin = lastLinkToInternal;
    5350              :             }
    5351              :             */
    5352              : 
    5353    114769224 :             const double leftSpace = item.availableSpace - getVehicleType().getLengthWithGap();
    5354              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5355              :             if (DEBUG_COND) std::cout
    5356              :                         << SIMTIME
    5357              :                         << " veh=" << getID()
    5358              :                         << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
    5359              :                         << " avail=" << item.availableSpace
    5360              :                         << " leftSpace=" << leftSpace
    5361              :                         << "\n";
    5362              : #endif
    5363    114769224 :             if (leftSpace < 0/* && item.myLink->willHaveBlockedFoe()*/) {
    5364              :                 double impatienceCorrection = 0;
    5365              :                 /*
    5366              :                 if(item.myLink->getState()==LINKSTATE_MINOR) {
    5367              :                     impatienceCorrection = MAX2(0., STEPS2TIME(myWaitingTime));
    5368              :                 }
    5369              :                 */
    5370              :                 // may ignore keepClear rules
    5371     73663919 :                 if (leftSpace < -impatienceCorrection / 10. && keepClear(item.myLink)) {
    5372              :                     removalBegin = i;
    5373              :                 }
    5374              :                 //removalBegin = i;
    5375              :             }
    5376              :         }
    5377              :         // abort requests
    5378    616188556 :         if (removalBegin != -1 && !(removalBegin == 0 && myLane->getEdge().isInternal())) {
    5379     29146735 :             const double brakeGap = getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.);
    5380     99931673 :             while (removalBegin < (int)(lfLinks.size())) {
    5381     75373063 :                 DriveProcessItem& dpi = lfLinks[removalBegin];
    5382     75373063 :                 if (dpi.myLink == nullptr) {
    5383              :                     break;
    5384              :                 }
    5385     70784938 :                 dpi.myVLinkPass = dpi.myVLinkWait;
    5386              : #ifdef DEBUG_CHECKREWINDLINKLANES
    5387              :                 if (DEBUG_COND) {
    5388              :                     std::cout << " removalBegin=" << removalBegin << " brakeGap=" << brakeGap << " dist=" << dpi.myDistance << " speed=" << myState.mySpeed << " a2s=" << ACCEL2SPEED(getCarFollowModel().getMaxDecel()) << "\n";
    5389              :                 }
    5390              : #endif
    5391     70784938 :                 if (dpi.myDistance >= brakeGap + POSITION_EPS) {
    5392              :                     // always leave junctions after requesting to enter
    5393     70776474 :                     if (!dpi.myLink->isExitLink() || !lfLinks[removalBegin - 1].mySetRequest) {
    5394     70769009 :                         dpi.mySetRequest = false;
    5395              :                     }
    5396              :                 }
    5397     70784938 :                 ++removalBegin;
    5398              :             }
    5399              :         }
    5400              :     }
    5401    619374397 : }
    5402              : 
    5403              : 
    5404              : void
    5405    691010757 : MSVehicle::setApproachingForAllLinks() {
    5406    691010757 :     if (!myActionStep) {
    5407              :         return;
    5408              :     }
    5409    619374397 :     removeApproachingInformation(myLFLinkLanesPrev);
    5410   1799053817 :     for (DriveProcessItem& dpi : myLFLinkLanes) {
    5411   1179679420 :         if (dpi.myLink != nullptr) {
    5412    832199931 :             if (dpi.myLink->getState() == LINKSTATE_ALLWAY_STOP) {
    5413      2723554 :                 dpi.myArrivalTime += (SUMOTime)RandHelper::rand((int)2, getRNG()); // tie braker
    5414              :             }
    5415    832199931 :             dpi.myLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5416    832199931 :                                        dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance, getLateralPositionOnLane());
    5417              :         }
    5418              :     }
    5419    619374397 :     if (isRail()) {
    5420      7498445 :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5421      6277173 :             if (dpi.myLink != nullptr && dpi.myLink->getTLLogic() != nullptr && dpi.myLink->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
    5422       551291 :                 MSRailSignalControl::getInstance().notifyApproach(dpi.myLink);
    5423              :             }
    5424              :         }
    5425              :     }
    5426    619374397 :     if (myLaneChangeModel->getShadowLane() != nullptr) {
    5427              :         // register on all shadow links
    5428      7525506 :         for (const DriveProcessItem& dpi : myLFLinkLanes) {
    5429      4989427 :             if (dpi.myLink != nullptr) {
    5430      3410620 :                 MSLink* parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
    5431      3410620 :                 if (parallelLink == nullptr && getLaneChangeModel().isOpposite() && dpi.myLink->isEntryLink()) {
    5432              :                     // register on opposite direction entry link to warn foes at minor side road
    5433       169386 :                     parallelLink = dpi.myLink->getOppositeDirectionLink();
    5434              :                 }
    5435      3410620 :                 if (parallelLink != nullptr) {
    5436      2431268 :                     const double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
    5437      2431268 :                     parallelLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
    5438      2431268 :                                                  dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance,
    5439              :                                                  latOffset);
    5440      2431268 :                     myLaneChangeModel->setShadowApproachingInformation(parallelLink);
    5441              :                 }
    5442              :             }
    5443              :         }
    5444              :     }
    5445              : #ifdef DEBUG_PLAN_MOVE
    5446              :     if (DEBUG_COND) {
    5447              :         std::cout << SIMTIME
    5448              :                   << " veh=" << getID()
    5449              :                   << " after checkRewindLinkLanes\n";
    5450              :         for (DriveProcessItem& dpi : myLFLinkLanes) {
    5451              :             std::cout
    5452              :                     << " vPass=" << dpi.myVLinkPass
    5453              :                     << " vWait=" << dpi.myVLinkWait
    5454              :                     << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
    5455              :                     << " request=" << dpi.mySetRequest
    5456              :                     << " atime=" << dpi.myArrivalTime
    5457              :                     << "\n";
    5458              :         }
    5459              :     }
    5460              : #endif
    5461              : }
    5462              : 
    5463              : 
    5464              : void
    5465         1675 : MSVehicle::registerInsertionApproach(MSLink* link, double dist) {
    5466              :     DriveProcessItem dpi(0, dist);
    5467         1675 :     dpi.myLink = link;
    5468         1675 :     const double arrivalSpeedBraking = getCarFollowModel().getMinimalArrivalSpeedEuler(dist, getSpeed());
    5469         1675 :     link->setApproaching(this, SUMOTime_MAX, 0, 0, false, arrivalSpeedBraking, 0, dpi.myDistance, 0);
    5470              :     // ensure cleanup in the next step
    5471         1675 :     myLFLinkLanes.push_back(dpi);
    5472         1675 :     MSRailSignalControl::getInstance().notifyApproach(link);
    5473         1675 : }
    5474              : 
    5475              : 
    5476              : void
    5477     19767725 : MSVehicle::enterLaneAtMove(MSLane* enteredLane, bool onTeleporting) {
    5478     19767725 :     myAmOnNet = !onTeleporting;
    5479              :     // vaporizing edge?
    5480              :     /*
    5481              :     if (enteredLane->getEdge().isVaporizing()) {
    5482              :         // yep, let's do the vaporization...
    5483              :         myLane = enteredLane;
    5484              :         return true;
    5485              :     }
    5486              :     */
    5487              :     // Adjust MoveReminder offset to the next lane
    5488     19767725 :     adaptLaneEntering2MoveReminder(*enteredLane);
    5489              :     // set the entered lane as the current lane
    5490     19767725 :     MSLane* oldLane = myLane;
    5491     19767725 :     myLane = enteredLane;
    5492     19767725 :     myLastBestLanesEdge = nullptr;
    5493              : 
    5494              :     // internal edges are not a part of the route...
    5495     19767725 :     if (!enteredLane->getEdge().isInternal()) {
    5496              :         ++myCurrEdge;
    5497              :         assert(myLaneChangeModel->isOpposite() || haveValidStopEdges());
    5498              :     }
    5499     19767725 :     if (myInfluencer != nullptr) {
    5500         9036 :         myInfluencer->adaptLaneTimeLine(myLane->getIndex() - oldLane->getIndex());
    5501              :     }
    5502     19767725 :     if (!onTeleporting) {
    5503     19750493 :         activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION, enteredLane);
    5504     19750493 :         if (MSGlobals::gLateralResolution > 0) {
    5505      3737911 :             myFurtherLanesPosLat.push_back(myState.myPosLat);
    5506              :             // transform lateral position when the lane width changes
    5507              :             assert(oldLane != nullptr);
    5508      3737911 :             const MSLink* const link = oldLane->getLinkTo(myLane);
    5509      3737911 :             if (link != nullptr) {
    5510      3737870 :                 myState.myPosLat += link->getLateralShift();
    5511              :             } else {
    5512           41 :                 myState.myPosLat += (oldLane->getCenterOnEdge() - myLane->getCanonicalPredecessorLane()->getRightSideOnEdge()) / 2;
    5513              :             }
    5514     16012582 :         } else if (fabs(myState.myPosLat) > NUMERICAL_EPS) {
    5515       355430 :             const double overlap = MAX2(0.0, getLateralOverlap(myState.myPosLat, oldLane));
    5516       355430 :             const double range = (oldLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
    5517       355430 :             const double range2 = (myLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
    5518       355430 :             myState.myPosLat *= range2 / range;
    5519              :         }
    5520     19750493 :         if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5521              :             // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
    5522              :             // (unless the lane is shared with cars)
    5523         9462 :             myLane->getBidiLane()->setPartialOccupation(this);
    5524              :         }
    5525              :     } else {
    5526              :         // normal move() isn't called so reset position here. must be done
    5527              :         // before calling reminders
    5528        17232 :         myState.myPos = 0;
    5529        17232 :         myCachedPosition = Position::INVALID;
    5530        17232 :         activateReminders(MSMoveReminder::NOTIFICATION_TELEPORT, enteredLane);
    5531              :     }
    5532              :     // update via
    5533     19767725 :     if (myParameter->via.size() > 0 &&  myLane->getEdge().getID() == myParameter->via.front()) {
    5534         7139 :         myParameter->via.erase(myParameter->via.begin());
    5535              :     }
    5536     19767725 : }
    5537              : 
    5538              : 
    5539              : void
    5540      1064108 : MSVehicle::enterLaneAtLaneChange(MSLane* enteredLane) {
    5541      1064108 :     myAmOnNet = true;
    5542      1064108 :     myLane = enteredLane;
    5543      1064108 :     myCachedPosition = Position::INVALID;
    5544              :     // need to update myCurrentLaneInBestLanes
    5545      1064108 :     updateBestLanes();
    5546              :     // switch to and activate the new lane's reminders
    5547              :     // keep OldLaneReminders
    5548      1258569 :     for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5549       194461 :         addReminder(*rem);
    5550              :     }
    5551      1064108 :     activateReminders(MSMoveReminder::NOTIFICATION_LANE_CHANGE, enteredLane);
    5552      1064108 :     MSLane* lane = myLane;
    5553      1064108 :     double leftLength = getVehicleType().getLength() - myState.myPos;
    5554              :     int deleteFurther = 0;
    5555              : #ifdef DEBUG_SETFURTHER
    5556              :     if (DEBUG_COND) {
    5557              :         std::cout << SIMTIME << " enterLaneAtLaneChange entered=" << Named::getIDSecure(enteredLane) << " oldFurther=" << toString(myFurtherLanes) << "\n";
    5558              :     }
    5559              : #endif
    5560      1064108 :     if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5561              :         // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
    5562              :         // (unless the lane is shared with cars)
    5563         8187 :         myLane->getBidiLane()->setPartialOccupation(this);
    5564              :     }
    5565      1147292 :     for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
    5566        83184 :         if (lane != nullptr) {
    5567        80147 :             lane = lane->getLogicalPredecessorLane(myFurtherLanes[i]->getEdge());
    5568              :         }
    5569              : #ifdef DEBUG_SETFURTHER
    5570              :         if (DEBUG_COND) {
    5571              :             std::cout << "  enterLaneAtLaneChange i=" << i << " lane=" << Named::getIDSecure(lane) << " leftLength=" << leftLength << "\n";
    5572              :         }
    5573              : #endif
    5574        83184 :         if (leftLength > 0) {
    5575        82624 :             if (lane != nullptr) {
    5576        33020 :                 myFurtherLanes[i]->resetPartialOccupation(this);
    5577        33020 :                 if (myFurtherLanes[i]->getBidiLane() != nullptr
    5578        33020 :                         && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5579           60 :                     myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
    5580              :                 }
    5581              :                 // lane changing onto longer lanes may reduce the number of
    5582              :                 // remaining further lanes
    5583        33020 :                 myFurtherLanes[i] = lane;
    5584        33020 :                 myFurtherLanesPosLat[i] = myState.myPosLat;
    5585        33020 :                 leftLength -= lane->setPartialOccupation(this);
    5586        33020 :                 if (lane->getBidiLane() != nullptr
    5587        33020 :                         && (!isRailway(getVClass()) || (lane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5588          540 :                     lane->getBidiLane()->setPartialOccupation(this);
    5589              :                 }
    5590        33020 :                 myState.myBackPos = -leftLength;
    5591              : #ifdef DEBUG_SETFURTHER
    5592              :                 if (DEBUG_COND) {
    5593              :                     std::cout << SIMTIME << "   newBackPos=" << myState.myBackPos << "\n";
    5594              :                 }
    5595              : #endif
    5596              :             } else {
    5597              :                 // keep the old values, but ensure there is no shadow
    5598        49604 :                 if (myLaneChangeModel->isChangingLanes()) {
    5599            0 :                     myLaneChangeModel->setNoShadowPartialOccupator(myFurtherLanes[i]);
    5600              :                 }
    5601        49604 :                 if (myState.myBackPos < 0) {
    5602           44 :                     myState.myBackPos += myFurtherLanes[i]->getLength();
    5603              :                 }
    5604              : #ifdef DEBUG_SETFURTHER
    5605              :                 if (DEBUG_COND) {
    5606              :                     std::cout << SIMTIME << "   i=" << i << " further=" << myFurtherLanes[i]->getID() << " newBackPos=" << myState.myBackPos << "\n";
    5607              :                 }
    5608              : #endif
    5609              :             }
    5610              :         } else {
    5611          560 :             myFurtherLanes[i]->resetPartialOccupation(this);
    5612          560 :             if (myFurtherLanes[i]->getBidiLane() != nullptr
    5613          560 :                     && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5614            0 :                 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
    5615              :             }
    5616          560 :             deleteFurther++;
    5617              :         }
    5618              :     }
    5619      1064108 :     if (deleteFurther > 0) {
    5620              : #ifdef DEBUG_SETFURTHER
    5621              :         if (DEBUG_COND) {
    5622              :             std::cout << SIMTIME << " veh=" << getID() << " shortening myFurtherLanes by " << deleteFurther << "\n";
    5623              :         }
    5624              : #endif
    5625          529 :         myFurtherLanes.erase(myFurtherLanes.end() - deleteFurther, myFurtherLanes.end());
    5626          529 :         myFurtherLanesPosLat.erase(myFurtherLanesPosLat.end() - deleteFurther, myFurtherLanesPosLat.end());
    5627              :     }
    5628              : #ifdef DEBUG_SETFURTHER
    5629              :     if (DEBUG_COND) {
    5630              :         std::cout << SIMTIME << " enterLaneAtLaneChange new furtherLanes=" << toString(myFurtherLanes)
    5631              :                   << " furterLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
    5632              :     }
    5633              : #endif
    5634      1064108 :     myAngle = computeAngle();
    5635      1064108 : }
    5636              : 
    5637              : 
    5638              : void
    5639      3619265 : MSVehicle::computeFurtherLanes(MSLane* enteredLane, double pos, bool collision) {
    5640              :     // build the list of lanes the vehicle is lapping into
    5641      3619265 :     if (!myLaneChangeModel->isOpposite()) {
    5642      3597033 :         double leftLength = myType->getLength() - pos;
    5643      3597033 :         MSLane* clane = enteredLane;
    5644      3597033 :         int routeIndex = getRoutePosition();
    5645      3702785 :         while (leftLength > 0) {
    5646       244077 :             if (routeIndex > 0 && clane->getEdge().isNormal()) {
    5647              :                 // get predecessor lane that corresponds to prior route
    5648         4380 :                 routeIndex--;
    5649         4380 :                 const MSEdge* fromRouteEdge = myRoute->getEdges()[routeIndex];
    5650              :                 MSLane* target = clane;
    5651         4380 :                 clane = nullptr;
    5652         5743 :                 for (auto ili : target->getIncomingLanes()) {
    5653         5736 :                     if (ili.lane->getEdge().getNormalBefore() == fromRouteEdge) {
    5654         4373 :                         clane = ili.lane;
    5655         4373 :                         break;
    5656              :                     }
    5657              :                 }
    5658              :             } else {
    5659       239697 :                 clane = clane->getLogicalPredecessorLane();
    5660              :             }
    5661       154793 :             if (clane == nullptr || clane == myLane || clane == myLane->getBidiLane()
    5662       398862 :                     || (clane->isInternal() && (
    5663       131778 :                             clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN
    5664        82745 :                             || clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN_LEFTHAND))) {
    5665              :                 break;
    5666              :             }
    5667       105752 :             if (!collision || std::find(myFurtherLanes.begin(), myFurtherLanes.end(), clane) == myFurtherLanes.end()) {
    5668       105349 :                 myFurtherLanes.push_back(clane);
    5669       105349 :                 myFurtherLanesPosLat.push_back(myState.myPosLat);
    5670       105349 :                 clane->setPartialOccupation(this);
    5671       105349 :                 if (clane->getBidiLane() != nullptr
    5672       105349 :                         && (!isRailway(getVClass()) || (clane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5673            5 :                     clane->getBidiLane()->setPartialOccupation(this);
    5674              :                 }
    5675              :             }
    5676       105752 :             leftLength -= clane->getLength();
    5677              :         }
    5678      3597033 :         myState.myBackPos = -leftLength;
    5679              : #ifdef DEBUG_SETFURTHER
    5680              :         if (DEBUG_COND) {
    5681              :             std::cout << SIMTIME << " computeFurtherLanes veh=" << getID() << " pos=" << pos << " myFurtherLanes=" << toString(myFurtherLanes) << " backPos=" << myState.myBackPos << "\n";
    5682              :         }
    5683              : #endif
    5684              :     } else {
    5685              :         // clear partial occupation
    5686        22657 :         for (MSLane* further : myFurtherLanes) {
    5687              : #ifdef DEBUG_SETFURTHER
    5688              :             if (DEBUG_COND) {
    5689              :                 std::cout << SIMTIME << " opposite: resetPartialOccupation " << further->getID() << " \n";
    5690              :             }
    5691              : #endif
    5692          425 :             further->resetPartialOccupation(this);
    5693          425 :             if (further->getBidiLane() != nullptr
    5694          425 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5695            0 :                 further->getBidiLane()->resetPartialOccupation(this);
    5696              :             }
    5697              :         }
    5698              :         myFurtherLanes.clear();
    5699              :         myFurtherLanesPosLat.clear();
    5700              :     }
    5701      3619265 : }
    5702              : 
    5703              : 
    5704              : void
    5705      3618849 : MSVehicle::enterLaneAtInsertion(MSLane* enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification) {
    5706      3618849 :     myState = State(pos, speed, posLat, pos - getVehicleType().getLength(), hasDeparted() ? myState.myPreviousSpeed : speed);
    5707      3618849 :     if (myDeparture == NOT_YET_DEPARTED) {
    5708      3546061 :         onDepart();
    5709              :     }
    5710      3618849 :     myCachedPosition = Position::INVALID;
    5711              :     assert(myState.myPos >= 0);
    5712              :     assert(myState.mySpeed >= 0);
    5713      3618849 :     myLane = enteredLane;
    5714      3618849 :     myAmOnNet = true;
    5715              :     // schedule action for the next timestep
    5716      3618849 :     myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + DELTA_T;
    5717      3618849 :     if (notification != MSMoveReminder::NOTIFICATION_TELEPORT) {
    5718      3607889 :         if (notification == MSMoveReminder::NOTIFICATION_PARKING && myInfluencer != nullptr) {
    5719           13 :             drawOutsideNetwork(false);
    5720              :         }
    5721              :         // set and activate the new lane's reminders, teleports already did that at enterLaneAtMove
    5722      7989593 :         for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
    5723      4381704 :             addReminder(*rem);
    5724              :         }
    5725      3607889 :         activateReminders(notification, enteredLane);
    5726              :     } else {
    5727        10960 :         myLastBestLanesEdge = nullptr;
    5728        10960 :         myLastBestLanesInternalLane = nullptr;
    5729        10960 :         myLaneChangeModel->resetState();
    5730        12065 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()
    5731        11658 :                 && myStops.front().pars.endPos < pos) {
    5732            0 :             WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5733              :                            time2string(MSNet::getInstance()->getCurrentTimeStep()));
    5734            0 :             myStops.pop_front();
    5735              :         }
    5736              :         // avoid startup-effects after teleport
    5737        10960 :         myTimeSinceStartup = getCarFollowModel().getStartupDelay() + DELTA_T;
    5738              : 
    5739              :     }
    5740      3618847 :     computeFurtherLanes(enteredLane, pos);
    5741      3618847 :     if (MSGlobals::gLateralResolution > 0) {
    5742       499360 :         myLaneChangeModel->updateShadowLane();
    5743       499360 :         myLaneChangeModel->updateTargetLane();
    5744      3119487 :     } else if (MSGlobals::gLaneChangeDuration > 0) {
    5745        34035 :         myLaneChangeModel->updateShadowLane();
    5746              :     }
    5747      3618847 :     if (notification != MSMoveReminder::NOTIFICATION_LOAD_STATE) {
    5748      3617271 :         myAngle = computeAngle();
    5749      3617271 :         if (myLaneChangeModel->isOpposite()) {
    5750        22232 :             myAngle += M_PI;
    5751              :         }
    5752              :     }
    5753      3618847 :     if (MSNet::getInstance()->hasPersons()) {
    5754        55580 :         for (MSLane* further : myFurtherLanes) {
    5755          709 :             if (further->mustCheckJunctionCollisions()) {
    5756            4 :                 MSNet::getInstance()->getEdgeControl().checkCollisionForInactive(further);
    5757              :             }
    5758              :         }
    5759              :     }
    5760      3618847 : }
    5761              : 
    5762              : 
    5763              : void
    5764     24339028 : MSVehicle::leaveLane(const MSMoveReminder::Notification reason, const MSLane* approachedLane) {
    5765     67342350 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5766     43003322 :         if (rem->first->notifyLeave(*this, myState.myPos + rem->second, reason, approachedLane)) {
    5767              : #ifdef _DEBUG
    5768              :             if (myTraceMoveReminders) {
    5769              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, true);
    5770              :             }
    5771              : #endif
    5772              :             ++rem;
    5773              :         } else {
    5774              : #ifdef _DEBUG
    5775              :             if (myTraceMoveReminders) {
    5776              :                 traceMoveReminder("notifyLeave", rem->first, rem->second, false);
    5777              :             }
    5778              : #endif
    5779              :             rem = myMoveReminders.erase(rem);
    5780              :         }
    5781              :     }
    5782     24339028 :     if ((reason == MSMoveReminder::NOTIFICATION_JUNCTION
    5783     24339028 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT
    5784      4576970 :             || reason == MSMoveReminder::NOTIFICATION_TELEPORT_CONTINUATION)
    5785     19767985 :             && myLane != nullptr) {
    5786     19767955 :         myOdometer += getLane()->getLength();
    5787              :     }
    5788     24338998 :     if (myLane != nullptr && myLane->getBidiLane() != nullptr && myAmOnNet
    5789     24379733 :             && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5790        18188 :         myLane->getBidiLane()->resetPartialOccupation(this);
    5791              :     }
    5792     24339028 :     if (reason != MSMoveReminder::NOTIFICATION_JUNCTION && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5793              :         // @note. In case of lane change, myFurtherLanes and partial occupation
    5794              :         // are handled in enterLaneAtLaneChange()
    5795      3516482 :         for (MSLane* further : myFurtherLanes) {
    5796              : #ifdef DEBUG_FURTHER
    5797              :             if (DEBUG_COND) {
    5798              :                 std::cout << SIMTIME << " leaveLane \n";
    5799              :             }
    5800              : #endif
    5801        36318 :             further->resetPartialOccupation(this);
    5802        36318 :             if (further->getBidiLane() != nullptr
    5803        36318 :                     && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
    5804            0 :                 further->getBidiLane()->resetPartialOccupation(this);
    5805              :             }
    5806              :         }
    5807              :         myFurtherLanes.clear();
    5808              :         myFurtherLanesPosLat.clear();
    5809              :     }
    5810      3480164 :     if (reason >= MSMoveReminder::NOTIFICATION_TELEPORT) {
    5811      3480164 :         myAmOnNet = false;
    5812      3480164 :         myWaitingTime = 0;
    5813              :     }
    5814     24339028 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && resumeFromStopping()) {
    5815          546 :         myStopDist = std::numeric_limits<double>::max();
    5816          546 :         if (myPastStops.back().speed <= 0) {
    5817          984 :             WRITE_WARNINGF(TL("Vehicle '%' aborts stop."), getID());
    5818              :         }
    5819              :     }
    5820     24339028 :     if (reason != MSMoveReminder::NOTIFICATION_PARKING && reason != MSMoveReminder::NOTIFICATION_LANE_CHANGE) {
    5821     23216556 :         while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()) {
    5822         1416 :             if (myStops.front().getSpeed() <= 0) {
    5823         3297 :                 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
    5824              :                                time2string(MSNet::getInstance()->getCurrentTimeStep()))
    5825         1099 :                 if (MSStopOut::active()) {
    5826              :                     // clean up if stopBlocked was called
    5827            5 :                     MSStopOut::getInstance()->stopNotStarted(this);
    5828              :                 }
    5829         1099 :                 myStops.pop_front();
    5830              :             } else {
    5831              :                 MSStop& stop = myStops.front();
    5832              :                 // passed waypoint at the end of the lane
    5833          317 :                 if (!stop.reached) {
    5834          317 :                     if (MSStopOut::active()) {
    5835           12 :                         MSStopOut::getInstance()->stopStarted(this, getPersonNumber(), getContainerNumber(), MSNet::getInstance()->getCurrentTimeStep());
    5836              :                     }
    5837          317 :                     stop.reached = true;
    5838              :                     // enter stopping place so leaveFrom works as expected
    5839          317 :                     if (stop.busstop != nullptr) {
    5840              :                         // let the bus stop know the vehicle
    5841           25 :                         stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5842              :                     }
    5843          317 :                     if (stop.containerstop != nullptr) {
    5844              :                         // let the container stop know the vehicle
    5845           13 :                         stop.containerstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5846              :                     }
    5847              :                     // do not enter parkingarea!
    5848          317 :                     if (stop.chargingStation != nullptr) {
    5849              :                         // let the container stop know the vehicle
    5850          121 :                         stop.chargingStation->enter(this, stop.pars.parking == ParkingType::OFFROAD);
    5851              :                     }
    5852              :                 }
    5853          317 :                 resumeFromStopping();
    5854              :             }
    5855         1416 :             myStopDist = std::numeric_limits<double>::max();
    5856              :         }
    5857              :     }
    5858     24339028 : }
    5859              : 
    5860              : 
    5861              : void
    5862        39658 : MSVehicle::leaveLaneBack(const MSMoveReminder::Notification reason, const MSLane* leftLane) {
    5863       164236 :     for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
    5864       124578 :         if (rem->first->notifyLeaveBack(*this, reason, leftLane)) {
    5865              : #ifdef _DEBUG
    5866              :             if (myTraceMoveReminders) {
    5867              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, true);
    5868              :             }
    5869              : #endif
    5870              :             ++rem;
    5871              :         } else {
    5872              : #ifdef _DEBUG
    5873              :             if (myTraceMoveReminders) {
    5874              :                 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, false);
    5875              :             }
    5876              : #endif
    5877              :             rem = myMoveReminders.erase(rem);
    5878              :         }
    5879              :     }
    5880              : #ifdef DEBUG_MOVEREMINDERS
    5881              :     if (DEBUG_COND) {
    5882              :         std::cout << SIMTIME << " veh=" << getID() << " myReminders:";
    5883              :         for (auto rem : myMoveReminders) {
    5884              :             std::cout << rem.first->getDescription() << " ";
    5885              :         }
    5886              :         std::cout << "\n";
    5887              :     }
    5888              : #endif
    5889        39658 : }
    5890              : 
    5891              : 
    5892              : MSAbstractLaneChangeModel&
    5893  10164805996 : MSVehicle::getLaneChangeModel() {
    5894  10164805996 :     return *myLaneChangeModel;
    5895              : }
    5896              : 
    5897              : 
    5898              : const MSAbstractLaneChangeModel&
    5899   4825687101 : MSVehicle::getLaneChangeModel() const {
    5900   4825687101 :     return *myLaneChangeModel;
    5901              : }
    5902              : 
    5903              : bool
    5904       516403 : MSVehicle::isOppositeLane(const MSLane* lane) const {
    5905       516403 :     return (lane->isInternal()
    5906       516403 :             ? & (lane->getLinkCont()[0]->getLane()->getEdge()) != *(myCurrEdge + 1)
    5907       514650 :             : &lane->getEdge() != *myCurrEdge);
    5908              : }
    5909              : 
    5910              : const std::vector<MSVehicle::LaneQ>&
    5911    499420984 : MSVehicle::getBestLanes() const {
    5912    499420984 :     return *myBestLanes.begin();
    5913              : }
    5914              : 
    5915              : 
    5916              : void
    5917   1021693840 : MSVehicle::updateBestLanes(bool forceRebuild, const MSLane* startLane) {
    5918              : #ifdef DEBUG_BESTLANES
    5919              :     if (DEBUG_COND) {
    5920              :         std::cout << SIMTIME << " updateBestLanes veh=" << getID() << " force=" << forceRebuild << " startLane1=" << Named::getIDSecure(startLane) << " myLane=" << Named::getIDSecure(myLane) << "\n";
    5921              :     }
    5922              : #endif
    5923   1021693840 :     if (startLane == nullptr) {
    5924    971188657 :         startLane = myLane;
    5925              :     }
    5926              :     assert(startLane != 0);
    5927   1021693840 :     if (myLaneChangeModel->isOpposite()) {
    5928              :         // depending on the calling context, startLane might be the forward lane
    5929              :         // or the reverse-direction lane. In the latter case we need to
    5930              :         // transform it to the forward lane.
    5931       516403 :         if (isOppositeLane(startLane)) {
    5932              :             // use leftmost lane of forward edge
    5933       110951 :             startLane = startLane->getEdge().getOppositeEdge()->getLanes().back();
    5934              :             assert(startLane != 0);
    5935              : #ifdef DEBUG_BESTLANES
    5936              :             if (DEBUG_COND) {
    5937              :                 std::cout << "   startLaneIsOpposite newStartLane=" << startLane->getID() << "\n";
    5938              :             }
    5939              : #endif
    5940              :         }
    5941              :     }
    5942   1021693840 :     if (forceRebuild) {
    5943      1883989 :         myLastBestLanesEdge = nullptr;
    5944      1883989 :         myLastBestLanesInternalLane = nullptr;
    5945              :     }
    5946   1021693840 :     if (myBestLanes.size() > 0 && !forceRebuild && myLastBestLanesEdge == &startLane->getEdge()) {
    5947    991112805 :         updateOccupancyAndCurrentBestLane(startLane);
    5948              : #ifdef DEBUG_BESTLANES
    5949              :         if (DEBUG_COND) {
    5950              :             std::cout << "  only updateOccupancyAndCurrentBestLane\n";
    5951              :         }
    5952              : #endif
    5953    991112805 :         return;
    5954              :     }
    5955     30581035 :     if (startLane->getEdge().isInternal()) {
    5956     14319797 :         if (myBestLanes.size() == 0 || forceRebuild) {
    5957              :             // rebuilt from previous non-internal lane (may backtrack twice if behind an internal junction)
    5958         2317 :             updateBestLanes(true, startLane->getLogicalPredecessorLane());
    5959              :         }
    5960     14319797 :         if (myLastBestLanesInternalLane == startLane && !forceRebuild) {
    5961              : #ifdef DEBUG_BESTLANES
    5962              :             if (DEBUG_COND) {
    5963              :                 std::cout << "  nothing to do on internal\n";
    5964              :             }
    5965              : #endif
    5966              :             return;
    5967              :         }
    5968              :         // adapt best lanes to fit the current internal edge:
    5969              :         // keep the entries that are reachable from this edge
    5970      5467480 :         const MSEdge* nextEdge = startLane->getNextNormal();
    5971              :         assert(!nextEdge->isInternal());
    5972     10806277 :         for (std::vector<std::vector<LaneQ> >::iterator it = myBestLanes.begin(); it != myBestLanes.end();) {
    5973              :             std::vector<LaneQ>& lanes = *it;
    5974              :             assert(lanes.size() > 0);
    5975     10806277 :             if (&(lanes[0].lane->getEdge()) == nextEdge) {
    5976              :                 // keep those lanes which are successors of internal lanes from the edge of startLane
    5977      5467480 :                 std::vector<LaneQ> oldLanes = lanes;
    5978              :                 lanes.clear();
    5979              :                 const std::vector<MSLane*>& sourceLanes = startLane->getEdge().getLanes();
    5980     12241365 :                 for (std::vector<MSLane*>::const_iterator it_source = sourceLanes.begin(); it_source != sourceLanes.end(); ++it_source) {
    5981     11721678 :                     for (std::vector<LaneQ>::iterator it_lane = oldLanes.begin(); it_lane != oldLanes.end(); ++it_lane) {
    5982     11721678 :                         if ((*it_source)->getLinkCont()[0]->getLane() == (*it_lane).lane) {
    5983      6773885 :                             lanes.push_back(*it_lane);
    5984              :                             break;
    5985              :                         }
    5986              :                     }
    5987              :                 }
    5988              :                 assert(lanes.size() == startLane->getEdge().getLanes().size());
    5989              :                 // patch invalid bestLaneOffset and updated myCurrentLaneInBestLanes
    5990     12241365 :                 for (int i = 0; i < (int)lanes.size(); ++i) {
    5991      6773885 :                     if (i + lanes[i].bestLaneOffset < 0) {
    5992       105762 :                         lanes[i].bestLaneOffset = -i;
    5993              :                     }
    5994      6773885 :                     if (i + lanes[i].bestLaneOffset >= (int)lanes.size()) {
    5995        23447 :                         lanes[i].bestLaneOffset = (int)lanes.size() - i - 1;
    5996              :                     }
    5997              :                     assert(i + lanes[i].bestLaneOffset >= 0);
    5998              :                     assert(i + lanes[i].bestLaneOffset < (int)lanes.size());
    5999      6773885 :                     if (lanes[i].bestContinuations[0] != 0) {
    6000              :                         // patch length of bestContinuation to match expectations (only once)
    6001      6604553 :                         lanes[i].bestContinuations.insert(lanes[i].bestContinuations.begin(), (MSLane*)nullptr);
    6002              :                     }
    6003      6773885 :                     if (startLane->getLinkCont()[0]->getLane() == lanes[i].lane) {
    6004      5508633 :                         myCurrentLaneInBestLanes = lanes.begin() + i;
    6005              :                     }
    6006              :                     assert(&(lanes[i].lane->getEdge()) == nextEdge);
    6007              :                 }
    6008      5467480 :                 myLastBestLanesInternalLane = startLane;
    6009      5467480 :                 updateOccupancyAndCurrentBestLane(startLane);
    6010              : #ifdef DEBUG_BESTLANES
    6011              :                 if (DEBUG_COND) {
    6012              :                     std::cout << "  updated for internal\n";
    6013              :                 }
    6014              : #endif
    6015              :                 return;
    6016      5467480 :             } else {
    6017              :                 // remove passed edges
    6018      5338797 :                 it = myBestLanes.erase(it);
    6019              :             }
    6020              :         }
    6021              :         assert(false); // should always find the next edge
    6022              :     }
    6023              :     // start rebuilding
    6024     16261238 :     myLastBestLanesInternalLane = nullptr;
    6025     16261238 :     myLastBestLanesEdge = &startLane->getEdge();
    6026              :     myBestLanes.clear();
    6027              : 
    6028              :     // get information about the next stop
    6029     16261238 :     MSRouteIterator nextStopEdge = myRoute->end();
    6030              :     const MSLane* nextStopLane = nullptr;
    6031              :     double nextStopPos = 0;
    6032              :     bool nextStopIsWaypoint = false;
    6033     16261238 :     if (!myStops.empty()) {
    6034              :         const MSStop& nextStop = myStops.front();
    6035       240886 :         nextStopLane = nextStop.lane;
    6036       240886 :         if (nextStop.isOpposite) {
    6037              :             // target leftmost lane in forward direction
    6038          340 :             nextStopLane = nextStopLane->getEdge().getOppositeEdge()->getLanes().back();
    6039              :         }
    6040       240886 :         nextStopEdge = nextStop.edge;
    6041       240886 :         nextStopPos = nextStop.pars.startPos;
    6042       240886 :         nextStopIsWaypoint = nextStop.getSpeed() > 0;
    6043              :     }
    6044              :     // myArrivalTime = -1 in the context of validating departSpeed with departLane=best
    6045     16261238 :     if (myParameter->arrivalLaneProcedure >= ArrivalLaneDefinition::GIVEN && nextStopEdge == myRoute->end() && myArrivalLane >= 0) {
    6046       336694 :         nextStopEdge = (myRoute->end() - 1);
    6047       336694 :         nextStopLane = (*nextStopEdge)->getLanes()[myArrivalLane];
    6048       336694 :         nextStopPos = myArrivalPos;
    6049              :     }
    6050     16261238 :     if (nextStopEdge != myRoute->end()) {
    6051              :         // make sure that the "wrong" lanes get a penalty. (penalty needs to be
    6052              :         // large enough to overcome a magic threshold in MSLaneChangeModel::DK2004.cpp:383)
    6053       577580 :         nextStopPos = MAX2(POSITION_EPS, MIN2((double)nextStopPos, (double)(nextStopLane->getLength() - 2 * POSITION_EPS)));
    6054       577580 :         if (nextStopLane->isInternal()) {
    6055              :             // switch to the correct lane before entering the intersection
    6056          172 :             nextStopPos = (*nextStopEdge)->getLength();
    6057              :         }
    6058              :     }
    6059              : 
    6060              :     // go forward along the next lanes;
    6061              :     // trains do not have to deal with lane-changing for stops but their best
    6062              :     // lanes lookahead is needed for rail signal control
    6063     16261238 :     const bool continueAfterStop = nextStopIsWaypoint || isRailway(getVClass());
    6064              :     int seen = 0;
    6065              :     double seenLength = 0;
    6066              :     bool progress = true;
    6067              :     // bestLanes must cover the braking distance even when at the very end of the current lane to avoid unecessary slow down
    6068     32522476 :     const double maxBrakeDist = startLane->getLength() + getCarFollowModel().getHeadwayTime() * getMaxSpeed() + getCarFollowModel().brakeGap(getMaxSpeed()) + getVehicleType().getMinGap();
    6069     16261238 :     const double lookahead = getLaneChangeModel().getStrategicLookahead();
    6070     80837855 :     for (MSRouteIterator ce = myCurrEdge; progress;) {
    6071              :         std::vector<LaneQ> currentLanes;
    6072              :         const std::vector<MSLane*>* allowed = nullptr;
    6073              :         const MSEdge* nextEdge = nullptr;
    6074     64576617 :         if (ce != myRoute->end() && ce + 1 != myRoute->end()) {
    6075     52471127 :             nextEdge = *(ce + 1);
    6076     52471127 :             allowed = (*ce)->allowedLanes(*nextEdge, myType->getVehicleClass());
    6077              :         }
    6078     64576617 :         const std::vector<MSLane*>& lanes = (*ce)->getLanes();
    6079    163972838 :         for (std::vector<MSLane*>::const_iterator i = lanes.begin(); i != lanes.end(); ++i) {
    6080              :             LaneQ q;
    6081     99396221 :             MSLane* cl = *i;
    6082     99396221 :             q.lane = cl;
    6083     99396221 :             q.bestContinuations.push_back(cl);
    6084     99396221 :             q.bestLaneOffset = 0;
    6085     99396221 :             q.length = cl->allowsVehicleClass(myType->getVehicleClass()) ? (*ce)->getLength() : 0;
    6086     99396221 :             q.currentLength = q.length;
    6087              :             // if all lanes are forbidden (i.e. due to a dynamic closing) we want to express no preference
    6088     99396221 :             q.allowsContinuation = allowed == nullptr || std::find(allowed->begin(), allowed->end(), cl) != allowed->end();
    6089     99396221 :             q.occupation = 0;
    6090     99396221 :             q.nextOccupation = 0;
    6091     99396221 :             currentLanes.push_back(q);
    6092              :         }
    6093              :         //
    6094              :         if (nextStopEdge == ce
    6095              :                 // already past the stop edge
    6096     64576617 :                 && !(ce == myCurrEdge && myLane != nullptr && myLane->isInternal())) {
    6097       570216 :             if (!nextStopLane->isInternal() && !continueAfterStop) {
    6098              :                 progress = false;
    6099              :             }
    6100       570216 :             const MSLane* normalStopLane = nextStopLane->getNormalPredecessorLane();
    6101      1824529 :             for (std::vector<LaneQ>::iterator q = currentLanes.begin(); q != currentLanes.end(); ++q) {
    6102      1254313 :                 if (nextStopLane != nullptr && normalStopLane != (*q).lane) {
    6103       684097 :                     (*q).allowsContinuation = false;
    6104       684097 :                     (*q).length = nextStopPos;
    6105       684097 :                     (*q).currentLength = (*q).length;
    6106              :                 }
    6107              :             }
    6108              :         }
    6109              : 
    6110     64576617 :         myBestLanes.push_back(currentLanes);
    6111     64576617 :         ++seen;
    6112     64576617 :         seenLength += currentLanes[0].lane->getLength();
    6113              :         ++ce;
    6114     64576617 :         if (lookahead >= 0) {
    6115           45 :             progress &= (seen <= 2 || seenLength < lookahead); // custom (but we need to look at least one edge ahead)
    6116              :         } else {
    6117     85413566 :             progress &= (seen <= 4 || seenLength < MAX2(maxBrakeDist, 3000.0)); // motorway
    6118     69328843 :             progress &= (seen <= 8 || seenLength < MAX2(maxBrakeDist, 200.0) || isRailway(getVClass()));  // urban
    6119              :         }
    6120     64576617 :         progress &= ce != myRoute->end();
    6121              :         /*
    6122              :         if(progress) {
    6123              :           progress &= (currentLanes.size()!=1||(*ce)->getLanes().size()!=1);
    6124              :         }
    6125              :         */
    6126     64576617 :     }
    6127              : 
    6128              :     // we are examining the last lane explicitly
    6129     16261238 :     if (myBestLanes.size() != 0) {
    6130              :         double bestLength = -1;
    6131              :         // minimum and maximum lane index with best length
    6132              :         int bestThisIndex = 0;
    6133              :         int bestThisMaxIndex = 0;
    6134              :         int index = 0;
    6135              :         std::vector<LaneQ>& last = myBestLanes.back();
    6136     42745684 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6137     26484446 :             if ((*j).length > bestLength) {
    6138              :                 bestLength = (*j).length;
    6139              :                 bestThisIndex = index;
    6140              :                 bestThisMaxIndex = index;
    6141      5948258 :             } else if ((*j).length == bestLength) {
    6142              :                 bestThisMaxIndex = index;
    6143              :             }
    6144              :         }
    6145              :         index = 0;
    6146              :         bool requiredChangeRightForbidden = false;
    6147              :         int requireChangeToLeftForbidden = -1;
    6148     42745684 :         for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
    6149     26484446 :             if ((*j).length < bestLength) {
    6150      4690892 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6151       122979 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6152              :                 } else {
    6153      4567913 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6154              :                 }
    6155      4690892 :                 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6156       300655 :                                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6157       296062 :                                                 || requiredChangeRightForbidden)) {
    6158              :                     // this lane and all further lanes to the left cannot be used
    6159              :                     requiredChangeRightForbidden = true;
    6160         4603 :                     (*j).length = 0;
    6161      4686289 :                 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6162      4390196 :                                                        || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6163              :                     // this lane and all previous lanes to the right cannot be used
    6164        32106 :                     requireChangeToLeftForbidden = (*j).lane->getIndex();
    6165              :                 }
    6166              :             }
    6167              :         }
    6168     16293399 :         for (int i = requireChangeToLeftForbidden; i >= 0; i--) {
    6169        32161 :             if (last[i].bestLaneOffset > 0) {
    6170        32121 :                 last[i].length = 0;
    6171              :             }
    6172              :         }
    6173              : #ifdef DEBUG_BESTLANES
    6174              :         if (DEBUG_COND) {
    6175              :             std::cout << "   last edge=" << last.front().lane->getEdge().getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6176              :             std::vector<LaneQ>& laneQs = myBestLanes.back();
    6177              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6178              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << "\n";
    6179              :             }
    6180              :         }
    6181              : #endif
    6182              :     }
    6183              :     // go backward through the lanes
    6184              :     // track back best lane and compute the best prior lane(s)
    6185     64576617 :     for (std::vector<std::vector<LaneQ> >::reverse_iterator i = myBestLanes.rbegin() + 1; i != myBestLanes.rend(); ++i) {
    6186              :         std::vector<LaneQ>& nextLanes = (*(i - 1));
    6187              :         std::vector<LaneQ>& clanes = (*i);
    6188     48315379 :         MSEdge* const cE = &clanes[0].lane->getEdge();
    6189              :         int index = 0;
    6190              :         double bestConnectedLength = -1;
    6191              :         double bestLength = -1;
    6192    120627274 :         for (const LaneQ& j : nextLanes) {
    6193    144623790 :             if (j.lane->isApproachedFrom(cE) && bestConnectedLength < j.length) {
    6194              :                 bestConnectedLength = j.length;
    6195              :             }
    6196     72311895 :             if (bestLength < j.length) {
    6197              :                 bestLength = j.length;
    6198              :             }
    6199              :         }
    6200              :         // compute index of the best lane (highest length and least offset from the best next lane)
    6201              :         int bestThisIndex = 0;
    6202              :         int bestThisMaxIndex = 0;
    6203     48315379 :         if (bestConnectedLength > 0) {
    6204              :             index = 0;
    6205    121205220 :             for (LaneQ& j : clanes) {
    6206              :                 const LaneQ* bestConnectedNext = nullptr;
    6207     72898041 :                 if (j.allowsContinuation) {
    6208    173094107 :                     for (const LaneQ& m : nextLanes) {
    6209    120513093 :                         if ((m.lane->allowsVehicleClass(getVClass()) || m.lane->hadPermissionChanges())
    6210    110299133 :                                 && m.lane->isApproachedFrom(cE, j.lane)) {
    6211     64607947 :                             if (betterContinuation(bestConnectedNext, m)) {
    6212              :                                 bestConnectedNext = &m;
    6213              :                             }
    6214              :                         }
    6215              :                     }
    6216     62850683 :                     if (bestConnectedNext != nullptr) {
    6217     62850679 :                         if (bestConnectedNext->length == bestConnectedLength && abs(bestConnectedNext->bestLaneOffset) < 2) {
    6218     61181665 :                             j.length += bestLength;
    6219              :                         } else {
    6220      1669014 :                             j.length += bestConnectedNext->length;
    6221              :                         }
    6222     62850679 :                         j.bestLaneOffset = bestConnectedNext->bestLaneOffset;
    6223              :                     }
    6224              :                 }
    6225     62850679 :                 if (bestConnectedNext != nullptr && (bestConnectedNext->allowsContinuation || bestConnectedNext->length > 0)) {
    6226     62825418 :                     copy(bestConnectedNext->bestContinuations.begin(), bestConnectedNext->bestContinuations.end(), back_inserter(j.bestContinuations));
    6227              :                 } else {
    6228     10072623 :                     j.allowsContinuation = false;
    6229              :                 }
    6230     72898041 :                 if (clanes[bestThisIndex].length < j.length
    6231     65345760 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) > abs(j.bestLaneOffset))
    6232    199548941 :                         || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset) &&
    6233     61434983 :                             nextLinkPriority(clanes[bestThisIndex].bestContinuations) < nextLinkPriority(j.bestContinuations))
    6234              :                    ) {
    6235              :                     bestThisIndex = index;
    6236              :                     bestThisMaxIndex = index;
    6237     65204086 :                 } else if (clanes[bestThisIndex].length == j.length
    6238     61423279 :                            && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset)
    6239    126627238 :                            && nextLinkPriority(clanes[bestThisIndex].bestContinuations) == nextLinkPriority(j.bestContinuations)) {
    6240              :                     bestThisMaxIndex = index;
    6241              :                 }
    6242     72898041 :                 index++;
    6243              :             }
    6244              : 
    6245              :             //vehicle with elecHybrid device prefers running under an overhead wire
    6246     48307179 :             if (getDevice(typeid(MSDevice_ElecHybrid)) != nullptr) {
    6247              :                 index = 0;
    6248          221 :                 for (const LaneQ& j : clanes) {
    6249          159 :                     std::string overheadWireSegmentID = MSNet::getInstance()->getStoppingPlaceID(j.lane, j.currentLength / 2., SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6250          159 :                     if (overheadWireSegmentID != "") {
    6251              :                         bestThisIndex = index;
    6252              :                         bestThisMaxIndex = index;
    6253              :                     }
    6254          159 :                     index++;
    6255              :                 }
    6256              :             }
    6257              : 
    6258              :         } else {
    6259              :             // only needed in case of disconnected routes
    6260              :             int bestNextIndex = 0;
    6261         8200 :             int bestDistToNeeded = (int) clanes.size();
    6262              :             index = 0;
    6263        21934 :             for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6264        13734 :                 if ((*j).allowsContinuation) {
    6265              :                     int nextIndex = 0;
    6266        30300 :                     for (std::vector<LaneQ>::const_iterator m = nextLanes.begin(); m != nextLanes.end(); ++m, ++nextIndex) {
    6267        16764 :                         if ((*m).lane->isApproachedFrom(cE, (*j).lane)) {
    6268         5895 :                             if (bestDistToNeeded > abs((*m).bestLaneOffset)) {
    6269              :                                 bestDistToNeeded = abs((*m).bestLaneOffset);
    6270              :                                 bestThisIndex = index;
    6271              :                                 bestThisMaxIndex = index;
    6272              :                                 bestNextIndex = nextIndex;
    6273              :                             }
    6274              :                         }
    6275              :                     }
    6276              :                 }
    6277              :             }
    6278         8200 :             clanes[bestThisIndex].length += nextLanes[bestNextIndex].length;
    6279         8200 :             copy(nextLanes[bestNextIndex].bestContinuations.begin(), nextLanes[bestNextIndex].bestContinuations.end(), back_inserter(clanes[bestThisIndex].bestContinuations));
    6280              : 
    6281              :         }
    6282              :         // set bestLaneOffset for all lanes
    6283              :         index = 0;
    6284              :         bool requiredChangeRightForbidden = false;
    6285              :         int requireChangeToLeftForbidden = -1;
    6286    121227154 :         for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6287     72911775 :             if ((*j).length < clanes[bestThisIndex].length
    6288     61197284 :                     || ((*j).length == clanes[bestThisIndex].length && abs((*j).bestLaneOffset) > abs(clanes[bestThisIndex].bestLaneOffset))
    6289    134108855 :                     || (nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)
    6290              :                ) {
    6291     11889833 :                 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
    6292       732504 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6293              :                 } else {
    6294     11157329 :                     (*j).bestLaneOffset = bestThisMaxIndex - index;
    6295              :                 }
    6296     11889833 :                 if ((nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)) {
    6297              :                     // try to move away from the lower-priority lane before it ends
    6298     10267761 :                     (*j).length = (*j).currentLength;
    6299              :                 }
    6300     11889833 :                 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
    6301      3476774 :                                                 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
    6302      3461148 :                                                 || requiredChangeRightForbidden)) {
    6303              :                     // this lane and all further lanes to the left cannot be used
    6304              :                     requiredChangeRightForbidden = true;
    6305        32962 :                     if ((*j).length == (*j).currentLength) {
    6306        29938 :                         (*j).length = 0;
    6307              :                     }
    6308     11856871 :                 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
    6309      8356155 :                                                        || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
    6310              :                     // this lane and all previous lanes to the right cannot be used
    6311        97171 :                     requireChangeToLeftForbidden = (*j).lane->getIndex();
    6312              :                 }
    6313              :             } else {
    6314     61021942 :                 (*j).bestLaneOffset = 0;
    6315              :             }
    6316              :         }
    6317     48421759 :         for (int idx = requireChangeToLeftForbidden; idx >= 0; idx--) {
    6318       106380 :             if (clanes[idx].length == clanes[idx].currentLength) {
    6319       100706 :                 clanes[idx].length = 0;
    6320              :             };
    6321              :         }
    6322              : 
    6323              :         //vehicle with elecHybrid device prefers running under an overhead wire
    6324     48315379 :         if (static_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid))) != 0) {
    6325              :             index = 0;
    6326           62 :             std::string overheadWireID = MSNet::getInstance()->getStoppingPlaceID(clanes[bestThisIndex].lane, (clanes[bestThisIndex].currentLength) / 2, SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
    6327           62 :             if (overheadWireID != "") {
    6328          211 :                 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
    6329          153 :                     (*j).bestLaneOffset = bestThisIndex - index;
    6330              :                 }
    6331              :             }
    6332              :         }
    6333              : 
    6334              : #ifdef DEBUG_BESTLANES
    6335              :         if (DEBUG_COND) {
    6336              :             std::cout << "   edge=" << cE->getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
    6337              :             std::vector<LaneQ>& laneQs = clanes;
    6338              :             for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
    6339              :                 std::cout << "     lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << " allowCont=" << (*j).allowsContinuation << "\n";
    6340              :             }
    6341              :         }
    6342              : #endif
    6343              : 
    6344              :     }
    6345     16261238 :     updateOccupancyAndCurrentBestLane(startLane);
    6346              : #ifdef DEBUG_BESTLANES
    6347              :     if (DEBUG_COND) {
    6348              :         std::cout << SIMTIME << " veh=" << getID() << " bestCont=" << toString(getBestLanesContinuation()) << "\n";
    6349              :     }
    6350              : #endif
    6351              : }
    6352              : 
    6353              : void
    6354          261 : MSVehicle::updateLaneBruttoSum() {
    6355          261 :     if (myLane != nullptr) {
    6356          261 :         myLane->markRecalculateBruttoSum();
    6357              :     }
    6358          261 : }
    6359              : 
    6360              : bool
    6361     64607947 : MSVehicle::betterContinuation(const LaneQ* bestConnectedNext, const LaneQ& m) const {
    6362     64607947 :     if (bestConnectedNext == nullptr) {
    6363              :         return true;
    6364      1757268 :     } else if (m.lane->getBidiLane() != nullptr && bestConnectedNext->lane->getBidiLane() == nullptr) {
    6365              :         return false;
    6366      1756530 :     } else if (bestConnectedNext->lane->getBidiLane() != nullptr && m.lane->getBidiLane() == nullptr) {
    6367              :         return true;
    6368      1756530 :     } else if (bestConnectedNext->length < m.length) {
    6369              :         return true;
    6370      1505463 :     } else if (bestConnectedNext->length == m.length) {
    6371      1127061 :         if (abs(bestConnectedNext->bestLaneOffset) > abs(m.bestLaneOffset)) {
    6372              :             return true;
    6373              :         }
    6374      1029267 :         const double contRight = getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_CONTRIGHT, 1);
    6375              :         if (contRight < 1
    6376              :                 // if we don't check for adjacency, the rightmost line will get
    6377              :                 // multiple chances to be better which leads to an uninituitve distribution
    6378         1008 :                 && (m.lane->getIndex() - bestConnectedNext->lane->getIndex()) == 1
    6379      1030048 :                 && RandHelper::rand(getRNG()) > contRight) {
    6380              :             return true;
    6381              :         }
    6382              :     }
    6383              :     return false;
    6384              : }
    6385              : 
    6386              : 
    6387              : int
    6388    391890096 : MSVehicle::nextLinkPriority(const std::vector<MSLane*>& conts) {
    6389    391890096 :     if (conts.size() < 2) {
    6390              :         return -1;
    6391              :     } else {
    6392    354652953 :         const MSLink* const link = conts[0]->getLinkTo(conts[1]);
    6393    354652953 :         if (link != nullptr) {
    6394    354646625 :             return link->havePriority() ? 1 : 0;
    6395              :         } else {
    6396              :             // disconnected route
    6397              :             return -1;
    6398              :         }
    6399              :     }
    6400              : }
    6401              : 
    6402              : 
    6403              : void
    6404   1012841523 : MSVehicle::updateOccupancyAndCurrentBestLane(const MSLane* startLane) {
    6405              :     std::vector<LaneQ>& currLanes = *myBestLanes.begin();
    6406              :     std::vector<LaneQ>::iterator i;
    6407   2824243481 :     for (i = currLanes.begin(); i != currLanes.end(); ++i) {
    6408              :         double nextOccupation = 0;
    6409   4251958490 :         for (std::vector<MSLane*>::const_iterator j = (*i).bestContinuations.begin() + 1; j != (*i).bestContinuations.end(); ++j) {
    6410   2440556532 :             nextOccupation += (*j)->getBruttoVehLenSum();
    6411              :         }
    6412   1811401958 :         (*i).nextOccupation = nextOccupation;
    6413              : #ifdef DEBUG_BESTLANES
    6414              :         if (DEBUG_COND) {
    6415              :             std::cout << "     lane=" << (*i).lane->getID() << " nextOccupation=" << nextOccupation << "\n";
    6416              :         }
    6417              : #endif
    6418   1811401958 :         if ((*i).lane == startLane) {
    6419   1007374014 :             myCurrentLaneInBestLanes = i;
    6420              :         }
    6421              :     }
    6422   1012841523 : }
    6423              : 
    6424              : 
    6425              : const std::vector<MSLane*>&
    6426   2005709588 : MSVehicle::getBestLanesContinuation() const {
    6427   2005709588 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6428              :         return myEmptyLaneVector;
    6429              :     }
    6430   2005709588 :     return (*myCurrentLaneInBestLanes).bestContinuations;
    6431              : }
    6432              : 
    6433              : 
    6434              : const std::vector<MSLane*>&
    6435     69471349 : MSVehicle::getBestLanesContinuation(const MSLane* const l) const {
    6436              :     const MSLane* lane = l;
    6437              :     // XXX: shouldn't this be a "while" to cover more than one internal lane? (Leo) Refs. #2575
    6438     69471349 :     if (lane->getEdge().isInternal()) {
    6439              :         // internal edges are not kept inside the bestLanes structure
    6440      4708075 :         lane = lane->getLinkCont()[0]->getLane();
    6441              :     }
    6442     69471349 :     if (myBestLanes.size() == 0) {
    6443              :         return myEmptyLaneVector;
    6444              :     }
    6445    115832426 :     for (std::vector<LaneQ>::const_iterator i = myBestLanes[0].begin(); i != myBestLanes[0].end(); ++i) {
    6446    115820311 :         if ((*i).lane == lane) {
    6447     69459234 :             return (*i).bestContinuations;
    6448              :         }
    6449              :     }
    6450              :     return myEmptyLaneVector;
    6451              : }
    6452              : 
    6453              : const std::vector<const MSLane*>
    6454       286202 : MSVehicle::getUpcomingLanesUntil(double distance) const {
    6455              :     std::vector<const MSLane*> lanes;
    6456              : 
    6457       286202 :     if (distance <= 0. || hasArrived()) {
    6458              :         // WRITE_WARNINGF(TL("MSVehicle::getUpcomingLanesUntil(): distance ('%') should be greater than 0."), distance);
    6459              :         return lanes;
    6460              :     }
    6461              : 
    6462       285997 :     if (!myLaneChangeModel->isOpposite()) {
    6463       282671 :         distance += getPositionOnLane();
    6464              :     } else {
    6465         3326 :         distance += myLane->getOppositePos(getPositionOnLane());
    6466              :     }
    6467       285997 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6468       294019 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6469         8022 :         lanes.insert(lanes.end(), lane);
    6470         8022 :         distance -= lane->getLength();
    6471        13493 :         lane = lane->getLinkCont().front()->getViaLaneOrLane();
    6472              :     }
    6473              : 
    6474       285997 :     const std::vector<MSLane*>& contLanes = getBestLanesContinuation();
    6475       285997 :     if (contLanes.empty()) {
    6476              :         return lanes;
    6477              :     }
    6478              :     auto contLanesIt = contLanes.begin();
    6479       285997 :     MSRouteIterator routeIt = myCurrEdge;  // keep track of covered edges in myRoute
    6480       612401 :     while (distance > 0.) {
    6481       334174 :         MSLane* l = nullptr;
    6482       334174 :         if (contLanesIt != contLanes.end()) {
    6483       318317 :             l = *contLanesIt;
    6484              :             if (l != nullptr) {
    6485              :                 assert(l->getEdge().getID() == (*routeIt)->getLanes().front()->getEdge().getID());
    6486              :             }
    6487              :             ++contLanesIt;
    6488       318317 :             if (l != nullptr || myLane->isInternal()) {
    6489              :                 ++routeIt;
    6490              :             }
    6491       318317 :             if (l == nullptr) {
    6492         5467 :                 continue;
    6493              :             }
    6494        15857 :         } else if (routeIt != myRoute->end()) {  // bestLanes didn't get us far enough
    6495              :             // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6496         8970 :             l = (*routeIt)->getLanes().back();
    6497              :             ++routeIt;
    6498              :         } else {  // the search distance goes beyond our route
    6499              :             break;
    6500              :         }
    6501              : 
    6502              :         assert(l != nullptr);
    6503              : 
    6504              :         // insert internal lanes if applicable
    6505       321820 :         const MSLane* internalLane = lanes.size() > 0 ? lanes.back()->getInternalFollowingLane(l) : nullptr;
    6506       365891 :         while ((internalLane != nullptr) && internalLane->isInternal() && (distance > 0.)) {
    6507        44071 :             lanes.insert(lanes.end(), internalLane);
    6508        44071 :             distance -= internalLane->getLength();
    6509        70434 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6510              :         }
    6511       321820 :         if (distance <= 0.) {
    6512              :             break;
    6513              :         }
    6514              : 
    6515       320937 :         lanes.insert(lanes.end(), l);
    6516       320937 :         distance -= l->getLength();
    6517              :     }
    6518              : 
    6519              :     return lanes;
    6520            0 : }
    6521              : 
    6522              : const std::vector<const MSLane*>
    6523         6664 : MSVehicle::getPastLanesUntil(double distance) const {
    6524              :     std::vector<const MSLane*> lanes;
    6525              : 
    6526         6664 :     if (distance <= 0.) {
    6527              :         // WRITE_WARNINGF(TL("MSVehicle::getPastLanesUntil(): distance ('%') should be greater than 0."), distance);
    6528              :         return lanes;
    6529              :     }
    6530              : 
    6531         6556 :     MSRouteIterator routeIt = myCurrEdge;
    6532         6556 :     if (!myLaneChangeModel->isOpposite()) {
    6533         6532 :         distance += myLane->getLength() - getPositionOnLane();
    6534              :     } else {
    6535           24 :         distance += myLane->getParallelOpposite()->getLength() - myLane->getOppositePos(getPositionOnLane());
    6536              :     }
    6537         6556 :     MSLane* lane = myLaneChangeModel->isOpposite() ? myLane->getParallelOpposite() : myLane;
    6538         6574 :     while (lane->isInternal() && (distance > 0.)) {  // include initial internal lanes
    6539           18 :         lanes.insert(lanes.end(), lane);
    6540           18 :         distance -= lane->getLength();
    6541           18 :         lane = lane->getLogicalPredecessorLane();
    6542              :     }
    6543              : 
    6544        10076 :     while (distance > 0.) {
    6545              :         // choose left-most lane as default (avoid sidewalks, bike lanes etc)
    6546         8755 :         MSLane* l = (*routeIt)->getLanes().back();
    6547              : 
    6548              :         // insert internal lanes if applicable
    6549         8755 :         const MSEdge* internalEdge = lanes.size() > 0 ? (*routeIt)->getInternalFollowingEdge(&(lanes.back()->getEdge()), getVClass()) : nullptr;
    6550         8773 :         const MSLane* internalLane = internalEdge != nullptr ? internalEdge->getLanes().front() : nullptr;
    6551              :         std::vector<const MSLane*> internalLanes;
    6552        10968 :         while ((internalLane != nullptr) && internalLane->isInternal()) {  // collect all internal successor lanes
    6553         2213 :             internalLanes.insert(internalLanes.begin(), internalLane);
    6554         4412 :             internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
    6555              :         }
    6556        10968 :         for (auto it = internalLanes.begin(); (it != internalLanes.end()) && (distance > 0.); ++it) {  // check remaining distance in correct order
    6557         2213 :             lanes.insert(lanes.end(), *it);
    6558         2213 :             distance -= (*it)->getLength();
    6559              :         }
    6560         8755 :         if (distance <= 0.) {
    6561              :             break;
    6562              :         }
    6563              : 
    6564         8742 :         lanes.insert(lanes.end(), l);
    6565         8742 :         distance -= l->getLength();
    6566              : 
    6567              :         // NOTE: we're going backwards with the (bi-directional) Iterator
    6568              :         // TODO: consider make reverse_iterator() when moving on to C++14 or later
    6569         8742 :         if (routeIt != myRoute->begin()) {
    6570              :             --routeIt;
    6571              :         } else {  // we went backwards to begin() and already processed the first and final element
    6572              :             break;
    6573              :         }
    6574         8755 :     }
    6575              : 
    6576              :     return lanes;
    6577            0 : }
    6578              : 
    6579              : 
    6580              : const std::vector<MSLane*>
    6581         6355 : MSVehicle::getUpstreamOppositeLanes() const {
    6582         6355 :     const std::vector<const MSLane*> routeLanes = getPastLanesUntil(myLane->getMaximumBrakeDist());
    6583              :     std::vector<MSLane*> result;
    6584        15441 :     for (const MSLane* lane : routeLanes) {
    6585         9859 :         MSLane* opposite = lane->getOpposite();
    6586         9859 :         if (opposite != nullptr) {
    6587         9086 :             result.push_back(opposite);
    6588              :         } else {
    6589              :             break;
    6590              :         }
    6591              :     }
    6592         6355 :     return result;
    6593         6355 : }
    6594              : 
    6595              : 
    6596              : int
    6597    298122066 : MSVehicle::getBestLaneOffset() const {
    6598    298122066 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6599              :         return 0;
    6600              :     } else {
    6601    297811360 :         return (*myCurrentLaneInBestLanes).bestLaneOffset;
    6602              :     }
    6603              : }
    6604              : 
    6605              : double
    6606        20137 : MSVehicle::getBestLaneDist() const {
    6607        20137 :     if (myBestLanes.empty() || myBestLanes[0].empty()) {
    6608              :         return -1;
    6609              :     } else {
    6610        20137 :         return (*myCurrentLaneInBestLanes).length;
    6611              :     }
    6612              : }
    6613              : 
    6614              : 
    6615              : 
    6616              : void
    6617    626319880 : MSVehicle::adaptBestLanesOccupation(int laneIndex, double density) {
    6618              :     std::vector<MSVehicle::LaneQ>& preb = myBestLanes.front();
    6619              :     assert(laneIndex < (int)preb.size());
    6620    626319880 :     preb[laneIndex].occupation = density + preb[laneIndex].nextOccupation;
    6621    626319880 : }
    6622              : 
    6623              : 
    6624              : void
    6625        63310 : MSVehicle::fixPosition() {
    6626        63310 :     if (MSGlobals::gLaneChangeDuration > 0 && !myLaneChangeModel->isChangingLanes()) {
    6627        33637 :         myState.myPosLat = 0;
    6628              :     }
    6629        63310 : }
    6630              : 
    6631              : std::pair<const MSLane*, double>
    6632          255 : MSVehicle::getLanePosAfterDist(double distance) const {
    6633          255 :     if (distance == 0) {
    6634          227 :         return std::make_pair(myLane, getPositionOnLane());
    6635              :     }
    6636           28 :     const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(distance);
    6637           28 :     distance += getPositionOnLane();
    6638           28 :     for (const MSLane* lane : lanes) {
    6639           28 :         if (lane->getLength() > distance) {
    6640              :             return std::make_pair(lane, distance);
    6641              :         }
    6642            0 :         distance -= lane->getLength();
    6643              :     }
    6644            0 :     return std::make_pair(nullptr, -1);
    6645           28 : }
    6646              : 
    6647              : 
    6648              : double
    6649        16920 : MSVehicle::getDistanceToPosition(double destPos, const MSLane* destLane) const {
    6650        16920 :     if (isOnRoad() && destLane != nullptr) {
    6651        16874 :         return myRoute->getDistanceBetween(getPositionOnLane(), destPos, myLane, destLane);
    6652              :     }
    6653              :     return std::numeric_limits<double>::max();
    6654              : }
    6655              : 
    6656              : 
    6657              : std::pair<const MSVehicle* const, double>
    6658     76413180 : MSVehicle::getLeader(double dist, bool considerCrossingFoes) const {
    6659     76413180 :     if (myLane == nullptr) {
    6660            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6661              :     }
    6662     76413180 :     if (dist == 0) {
    6663         2474 :         dist = getCarFollowModel().brakeGap(getSpeed()) + getVehicleType().getMinGap();
    6664              :     }
    6665              :     const MSVehicle* lead = nullptr;
    6666     76413180 :     const MSLane* lane = myLane; // ensure lane does not change between getVehiclesSecure and releaseVehicles;
    6667     76413180 :     const MSLane::VehCont& vehs = lane->getVehiclesSecure();
    6668              :     // vehicle might be outside the road network
    6669     76413180 :     MSLane::VehCont::const_iterator it = std::find(vehs.begin(), vehs.end(), this);
    6670     76413180 :     if (it != vehs.end() && it + 1 != vehs.end()) {
    6671     72699967 :         lead = *(it + 1);
    6672              :     }
    6673     72699967 :     if (lead != nullptr) {
    6674              :         std::pair<const MSVehicle* const, double> result(
    6675     72699967 :             lead, lead->getBackPositionOnLane(myLane) - getPositionOnLane() - getVehicleType().getMinGap());
    6676     72699967 :         lane->releaseVehicles();
    6677     72699967 :         return result;
    6678              :     }
    6679      3713213 :     const double seen = myLane->getLength() - getPositionOnLane();
    6680      3713213 :     const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(myLane);
    6681      3713213 :     std::pair<const MSVehicle* const, double> result = myLane->getLeaderOnConsecutive(dist, seen, getSpeed(), *this, bestLaneConts, considerCrossingFoes);
    6682      3713213 :     lane->releaseVehicles();
    6683      3713213 :     return result;
    6684              : }
    6685              : 
    6686              : 
    6687              : std::pair<const MSVehicle* const, double>
    6688      2007491 : MSVehicle::getFollower(double dist) const {
    6689      2007491 :     if (myLane == nullptr) {
    6690            0 :         return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
    6691              :     }
    6692      2007491 :     if (dist == 0) {
    6693       546453 :         dist = getCarFollowModel().brakeGap(myLane->getEdge().getSpeedLimit() * 2, 4.5, 0);
    6694              :     }
    6695      2007491 :     return myLane->getFollower(this, getPositionOnLane(), dist, MSLane::MinorLinkMode::FOLLOW_NEVER);
    6696              : }
    6697              : 
    6698              : 
    6699              : double
    6700            0 : MSVehicle::getTimeGapOnLane() const {
    6701              :     // calling getLeader with 0 would induce a dist calculation but we only want to look for the leaders on the current lane
    6702            0 :     std::pair<const MSVehicle* const, double> leaderInfo = getLeader(-1);
    6703            0 :     if (leaderInfo.first == nullptr || getSpeed() == 0) {
    6704            0 :         return -1;
    6705              :     }
    6706            0 :     return (leaderInfo.second + getVehicleType().getMinGap()) / getSpeed();
    6707              : }
    6708              : 
    6709              : 
    6710              : void
    6711      4035675 : MSVehicle::addTransportable(MSTransportable* transportable) {
    6712      4035675 :     MSBaseVehicle::addTransportable(transportable);
    6713        10891 :     if (myStops.size() > 0 && myStops.front().reached) {
    6714         7691 :         if (transportable->isPerson()) {
    6715         7112 :             if (myStops.front().triggered && myStops.front().numExpectedPerson > 0) {
    6716         1504 :                 myStops.front().numExpectedPerson -= (int)myStops.front().pars.awaitedPersons.count(transportable->getID());
    6717              :             }
    6718              :         } else {
    6719          579 :             if (myStops.front().pars.containerTriggered && myStops.front().numExpectedContainer > 0) {
    6720           20 :                 myStops.front().numExpectedContainer -= (int)myStops.front().pars.awaitedContainers.count(transportable->getID());
    6721              :             }
    6722              :         }
    6723              :     }
    6724        10891 : }
    6725              : 
    6726              : 
    6727              : void
    6728    683577852 : MSVehicle::setBlinkerInformation() {
    6729              :     switchOffSignal(VEH_SIGNAL_BLINKER_RIGHT | VEH_SIGNAL_BLINKER_LEFT);
    6730    683577852 :     int state = myLaneChangeModel->getOwnState();
    6731              :     // do not set blinker for sublane changes or when blocked from changing to the right
    6732    683577852 :     const bool blinkerManoeuvre = (((state & LCA_SUBLANE) == 0) && (
    6733    594617888 :                                        (state & LCA_KEEPRIGHT) == 0 || (state & LCA_BLOCKED) == 0));
    6734              :     Signalling left = VEH_SIGNAL_BLINKER_LEFT;
    6735              :     Signalling right = VEH_SIGNAL_BLINKER_RIGHT;
    6736    683577852 :     if (MSGlobals::gLefthand) {
    6737              :         // lane indices increase from left to right
    6738              :         std::swap(left, right);
    6739              :     }
    6740    683577852 :     if ((state & LCA_LEFT) != 0 && blinkerManoeuvre) {
    6741     19478198 :         switchOnSignal(left);
    6742    664099654 :     } else if ((state & LCA_RIGHT) != 0 && blinkerManoeuvre) {
    6743      5618202 :         switchOnSignal(right);
    6744    658481452 :     } else if (myLaneChangeModel->isChangingLanes()) {
    6745       248275 :         if (myLaneChangeModel->getLaneChangeDirection() == 1) {
    6746       159178 :             switchOnSignal(left);
    6747              :         } else {
    6748        89097 :             switchOnSignal(right);
    6749              :         }
    6750              :     } else {
    6751    658233177 :         const MSLane* lane = getLane();
    6752    658233177 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, 1, *lane, getBestLanesContinuation());
    6753    658233177 :         if (link != lane->getLinkCont().end() && lane->getLength() - getPositionOnLane() < lane->getVehicleMaxSpeed(this) * (double) 7.) {
    6754    162278468 :             switch ((*link)->getDirection()) {
    6755              :                 case LinkDirection::TURN:
    6756              :                 case LinkDirection::LEFT:
    6757              :                 case LinkDirection::PARTLEFT:
    6758              :                     switchOnSignal(VEH_SIGNAL_BLINKER_LEFT);
    6759              :                     break;
    6760              :                 case LinkDirection::RIGHT:
    6761              :                 case LinkDirection::PARTRIGHT:
    6762              :                     switchOnSignal(VEH_SIGNAL_BLINKER_RIGHT);
    6763              :                     break;
    6764              :                 default:
    6765              :                     break;
    6766              :             }
    6767              :         }
    6768              :     }
    6769              :     // stopping related signals
    6770    683577852 :     if (hasStops()
    6771    683577852 :             && (myStops.begin()->reached ||
    6772     15069575 :                 (myStopDist < (myLane->getLength() - getPositionOnLane())
    6773      4157098 :                  && myStopDist < getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this), getCarFollowModel().getMaxDecel(), 3)))) {
    6774     16771803 :         if (myStops.begin()->lane->getIndex() > 0 && myStops.begin()->lane->getParallelLane(-1)->allowsVehicleClass(getVClass())) {
    6775              :             // not stopping on the right. Activate emergency blinkers
    6776              :             switchOnSignal(VEH_SIGNAL_BLINKER_LEFT | VEH_SIGNAL_BLINKER_RIGHT);
    6777     16544661 :         } else if (!myStops.begin()->reached && (myStops.begin()->pars.parking == ParkingType::OFFROAD)) {
    6778              :             // signal upcoming parking stop on the current lane when within braking distance (~2 seconds before braking)
    6779      1582402 :             switchOnSignal(MSGlobals::gLefthand ? VEH_SIGNAL_BLINKER_LEFT : VEH_SIGNAL_BLINKER_RIGHT);
    6780              :         }
    6781              :     }
    6782    683577852 :     if (myInfluencer != nullptr && myInfluencer->getSignals() >= 0) {
    6783           15 :         mySignals = myInfluencer->getSignals();
    6784              :         myInfluencer->setSignals(-1); // overwrite computed signals only once
    6785              :     }
    6786    683577852 : }
    6787              : 
    6788              : void
    6789        85748 : MSVehicle::setEmergencyBlueLight(SUMOTime currentTime) {
    6790              : 
    6791              :     //TODO look if timestep ist SIMSTEP
    6792        85748 :     if (currentTime % 1000 == 0) {
    6793        25958 :         if (signalSet(VEH_SIGNAL_EMERGENCY_BLUE)) {
    6794              :             switchOffSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6795              :         } else {
    6796              :             switchOnSignal(VEH_SIGNAL_EMERGENCY_BLUE);
    6797              :         }
    6798              :     }
    6799        85748 : }
    6800              : 
    6801              : 
    6802              : int
    6803     22684940 : MSVehicle::getLaneIndex() const {
    6804     22684940 :     return myLane == nullptr ? -1 : myLane->getIndex();
    6805              : }
    6806              : 
    6807              : 
    6808              : void
    6809     15277532 : MSVehicle::setTentativeLaneAndPosition(MSLane* lane, double pos, double posLat) {
    6810     15277532 :     myLane = lane;
    6811     15277532 :     myState.myPos = pos;
    6812     15277532 :     myState.myPosLat = posLat;
    6813     15277532 :     myState.myBackPos = pos - getVehicleType().getLength();
    6814     15277532 : }
    6815              : 
    6816              : 
    6817              : double
    6818    380143321 : MSVehicle::getRightSideOnLane() const {
    6819    380143321 :     return myState.myPosLat + 0.5 * myLane->getWidth() - 0.5 * getVehicleType().getWidth();
    6820              : }
    6821              : 
    6822              : 
    6823              : double
    6824    375012226 : MSVehicle::getLeftSideOnLane() const {
    6825    375012226 :     return myState.myPosLat + 0.5 * myLane->getWidth() + 0.5 * getVehicleType().getWidth();
    6826              : }
    6827              : 
    6828              : 
    6829              : double
    6830    300999159 : MSVehicle::getRightSideOnLane(const MSLane* lane) const {
    6831    300999159 :     return myState.myPosLat + 0.5 * lane->getWidth() - 0.5 * getVehicleType().getWidth();
    6832              : }
    6833              : 
    6834              : 
    6835              : double
    6836    300506521 : MSVehicle::getLeftSideOnLane(const MSLane* lane) const {
    6837    300506521 :     return myState.myPosLat + 0.5 * lane->getWidth() + 0.5 * getVehicleType().getWidth();
    6838              : }
    6839              : 
    6840              : 
    6841              : double
    6842    240615459 : MSVehicle::getRightSideOnEdge(const MSLane* lane) const {
    6843    240615459 :     return getCenterOnEdge(lane) - 0.5 * getVehicleType().getWidth();
    6844              : }
    6845              : 
    6846              : 
    6847              : double
    6848     29737471 : MSVehicle::getLeftSideOnEdge(const MSLane* lane) const {
    6849     29737471 :     return getCenterOnEdge(lane) + 0.5 * getVehicleType().getWidth();
    6850              : }
    6851              : 
    6852              : 
    6853              : double
    6854    704513644 : MSVehicle::getCenterOnEdge(const MSLane* lane) const {
    6855    704513644 :     if (lane == nullptr || &lane->getEdge() == &myLane->getEdge()) {
    6856    704048417 :         return myLane->getRightSideOnEdge() + myState.myPosLat + 0.5 * myLane->getWidth();
    6857       465227 :     } else if (lane == myLaneChangeModel->getShadowLane()) {
    6858        13709 :         if (myLaneChangeModel->isOpposite() && &lane->getEdge() != &myLane->getEdge()) {
    6859        13702 :             return lane->getRightSideOnEdge() + lane->getWidth() - myState.myPosLat + 0.5 * myLane->getWidth();
    6860              :         }
    6861            7 :         if (myLaneChangeModel->getShadowDirection() == -1) {
    6862            0 :             return lane->getRightSideOnEdge() + lane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6863              :         } else {
    6864            7 :             return lane->getRightSideOnEdge() - myLane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
    6865              :         }
    6866       451518 :     } else if (lane == myLane->getBidiLane()) {
    6867         1679 :         return lane->getRightSideOnEdge() - myState.myPosLat + 0.5 * lane->getWidth();
    6868              :     } else {
    6869              :         assert(myFurtherLanes.size() == myFurtherLanesPosLat.size());
    6870       525575 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6871       499089 :             if (myFurtherLanes[i] == lane) {
    6872              : #ifdef DEBUG_FURTHER
    6873              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat=" << myFurtherLanesPosLat[i]
    6874              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6875              :                                               << "\n";
    6876              : #endif
    6877       423280 :                 return lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6878        75809 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    6879              : #ifdef DEBUG_FURTHER
    6880              :                 if (DEBUG_COND) std::cout << "    getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat(bidi)=" << myFurtherLanesPosLat[i]
    6881              :                                               << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
    6882              :                                               << "\n";
    6883              : #endif
    6884           73 :                 return lane->getRightSideOnEdge() - myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
    6885              :             }
    6886              :         }
    6887              :         //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    6888        26486 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    6889        26753 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    6890              :             //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
    6891        26753 :             if (shadowFurther[i] == lane) {
    6892              :                 assert(myLaneChangeModel->getShadowLane() != 0);
    6893        26486 :                 return (lane->getRightSideOnEdge() + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
    6894        26486 :                         + (myLane->getCenterOnEdge() - myLaneChangeModel->getShadowLane()->getCenterOnEdge()));
    6895              :             }
    6896              :         }
    6897              :         assert(false);
    6898            0 :         throw ProcessError("Request lateral pos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    6899              :     }
    6900              : }
    6901              : 
    6902              : 
    6903              : double
    6904   3268406852 : MSVehicle::getLatOffset(const MSLane* lane) const {
    6905              :     assert(lane != 0);
    6906   3268406852 :     if (&lane->getEdge() == &myLane->getEdge()) {
    6907   3219795693 :         return myLane->getRightSideOnEdge() - lane->getRightSideOnEdge();
    6908     48611159 :     } else if (myLane->getParallelOpposite() == lane) {
    6909      2159478 :         return (myLane->getWidth() + lane->getWidth()) * 0.5 - 2 * getLateralPositionOnLane();
    6910     46451681 :     } else if (myLane->getBidiLane() == lane) {
    6911       179386 :         return -2 * getLateralPositionOnLane();
    6912              :     } else {
    6913              :         // Check whether the lane is a further lane for the vehicle
    6914     52203345 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6915     51235869 :             if (myFurtherLanes[i] == lane) {
    6916              : #ifdef DEBUG_FURTHER
    6917              :                 if (DEBUG_COND) {
    6918              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherLat=" << myFurtherLanesPosLat[i] << "\n";
    6919              :                 }
    6920              : #endif
    6921     45278600 :                 return myFurtherLanesPosLat[i] - myState.myPosLat;
    6922      5957269 :             } else if (myFurtherLanes[i]->getBidiLane() == lane) {
    6923              : #ifdef DEBUG_FURTHER
    6924              :                 if (DEBUG_COND) {
    6925              :                     std::cout << "    getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
    6926              :                 }
    6927              : #endif
    6928        26219 :                 return -2 * (myFurtherLanesPosLat[i] - myState.myPosLat);
    6929              :             }
    6930              :         }
    6931              : #ifdef DEBUG_FURTHER
    6932              :         if (DEBUG_COND) {
    6933              :             std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
    6934              :         }
    6935              : #endif
    6936              :         // Check whether the lane is a "shadow further lane" for the vehicle
    6937       967476 :         const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
    6938       978497 :         for (int i = 0; i < (int)shadowFurther.size(); ++i) {
    6939       975959 :             if (shadowFurther[i] == lane) {
    6940              : #ifdef DEBUG_FURTHER
    6941              :                 if (DEBUG_COND) std::cout << "    getLatOffset veh=" << getID()
    6942              :                                               << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
    6943              :                                               << " lane=" << lane->getID()
    6944              :                                               << " i=" << i
    6945              :                                               << " posLat=" << myState.myPosLat
    6946              :                                               << " shadowPosLat=" << getLatOffset(myLaneChangeModel->getShadowLane())
    6947              :                                               << " shadowFurtherLat=" << myLaneChangeModel->getShadowFurtherLanesPosLat()[i]
    6948              :                                               <<  "\n";
    6949              : #endif
    6950       964938 :                 return getLatOffset(myLaneChangeModel->getShadowLane()) + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] - myState.myPosLat;
    6951              :             }
    6952              :         }
    6953              :         // Check whether the vehicle issued a maneuverReservation on the lane.
    6954              :         const std::vector<MSLane*>& furtherTargets = myLaneChangeModel->getFurtherTargetLanes();
    6955         2876 :         for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
    6956              :             // Further target lanes are just neighboring lanes of the vehicle's further lanes, @see MSAbstractLaneChangeModel::updateTargetLane()
    6957         2876 :             MSLane* targetLane = furtherTargets[i];
    6958         2876 :             if (targetLane == lane) {
    6959         2538 :                 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
    6960         2538 :                 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
    6961              : #ifdef DEBUG_TARGET_LANE
    6962              :                 if (DEBUG_COND) {
    6963              :                     std::cout << "    getLatOffset veh=" << getID()
    6964              :                               << " wrt targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
    6965              :                               << "\n    i=" << i
    6966              :                               << " posLat=" << myState.myPosLat
    6967              :                               << " furtherPosLat=" << myFurtherLanesPosLat[i]
    6968              :                               << " maneuverDist=" << myLaneChangeModel->getManeuverDist()
    6969              :                               << " targetDir=" << targetDir
    6970              :                               << " latOffset=" << latOffset
    6971              :                               <<  std::endl;
    6972              :                 }
    6973              : #endif
    6974         2538 :                 return latOffset;
    6975              :             }
    6976              :         }
    6977              :         assert(false);
    6978            0 :         throw ProcessError("Request lateral offset of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
    6979              :     }
    6980              : }
    6981              : 
    6982              : 
    6983              : double
    6984     34780383 : MSVehicle::lateralDistanceToLane(const int offset) const {
    6985              :     // compute the distance when changing to the neighboring lane
    6986              :     // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
    6987              :     assert(offset == 0 || offset == 1 || offset == -1);
    6988              :     assert(myLane != nullptr);
    6989              :     assert(myLane->getParallelLane(offset) != nullptr || myLane->getParallelOpposite() != nullptr);
    6990     34780383 :     const double halfCurrentLaneWidth = 0.5 * myLane->getWidth();
    6991     34780383 :     const double halfVehWidth = 0.5 * (getWidth() + NUMERICAL_EPS);
    6992     34780383 :     const double latPos = getLateralPositionOnLane();
    6993     34780383 :     const double oppositeSign = getLaneChangeModel().isOpposite() ? -1 : 1;
    6994     34780383 :     double leftLimit = halfCurrentLaneWidth - halfVehWidth - oppositeSign * latPos;
    6995     34780383 :     double rightLimit = -halfCurrentLaneWidth + halfVehWidth - oppositeSign * latPos;
    6996              :     double latLaneDist = 0;  // minimum distance to move the vehicle fully onto the new lane
    6997     34780383 :     if (offset == 0) {
    6998           10 :         if (latPos + halfVehWidth > halfCurrentLaneWidth) {
    6999              :             // correct overlapping left
    7000            5 :             latLaneDist = halfCurrentLaneWidth - latPos - halfVehWidth;
    7001            5 :         } else if (latPos - halfVehWidth < -halfCurrentLaneWidth) {
    7002              :             // correct overlapping right
    7003            5 :             latLaneDist = -halfCurrentLaneWidth - latPos + halfVehWidth;
    7004              :         }
    7005           10 :         latLaneDist *= oppositeSign;
    7006     34780373 :     } else if (offset == -1) {
    7007     15764679 :         latLaneDist = rightLimit - (getWidth() + NUMERICAL_EPS);
    7008     19015694 :     } else if (offset == 1) {
    7009     19015694 :         latLaneDist = leftLimit + (getWidth() + NUMERICAL_EPS);
    7010              :     }
    7011              : #ifdef DEBUG_ACTIONSTEPS
    7012              :     if (DEBUG_COND) {
    7013              :         std::cout << SIMTIME
    7014              :                   << " veh=" << getID()
    7015              :                   << " halfCurrentLaneWidth=" << halfCurrentLaneWidth
    7016              :                   << " halfVehWidth=" << halfVehWidth
    7017              :                   << " latPos=" << latPos
    7018              :                   << " latLaneDist=" << latLaneDist
    7019              :                   << " leftLimit=" << leftLimit
    7020              :                   << " rightLimit=" << rightLimit
    7021              :                   << "\n";
    7022              :     }
    7023              : #endif
    7024     34780383 :     return latLaneDist;
    7025              : }
    7026              : 
    7027              : 
    7028              : double
    7029   4970577927 : MSVehicle::getLateralOverlap(double posLat, const MSLane* lane) const {
    7030   4970577927 :     return (fabs(posLat) + 0.5 * getVehicleType().getWidth()
    7031   4970577927 :             - 0.5 * lane->getWidth());
    7032              : }
    7033              : 
    7034              : double
    7035            0 : MSVehicle::getLateralOverlap(const MSLane* lane) const {
    7036            0 :     return getLateralOverlap(getLateralPositionOnLane(), lane);
    7037              : }
    7038              : 
    7039              : double
    7040   4782786625 : MSVehicle::getLateralOverlap() const {
    7041   4782786625 :     return getLateralOverlap(getLateralPositionOnLane(), myLane);
    7042              : }
    7043              : 
    7044              : 
    7045              : void
    7046    627416859 : MSVehicle::removeApproachingInformation(const DriveItemVector& lfLinks) const {
    7047   1810457670 :     for (const DriveProcessItem& dpi : lfLinks) {
    7048   1183040811 :         if (dpi.myLink != nullptr) {
    7049    831914572 :             dpi.myLink->removeApproaching(this);
    7050              :         }
    7051              :     }
    7052              :     // unregister on all shadow links
    7053    627416859 :     myLaneChangeModel->removeShadowApproachingInformation();
    7054    627416859 : }
    7055              : 
    7056              : 
    7057              : bool
    7058       826585 : MSVehicle::unsafeLinkAhead(const MSLane* lane, double zipperDist) const {
    7059              :     // the following links are unsafe:
    7060              :     // - zipper links if they are close enough and have approaching vehicles in the relevant time range
    7061              :     // - unprioritized links if the vehicle is currently approaching a prioritzed link and unable to stop in time
    7062       826585 :     double seen = myLane->getLength() - getPositionOnLane();
    7063       826585 :     const double dist = MAX2(zipperDist, getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0));
    7064       826585 :     if (seen < dist) {
    7065        70574 :         const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(lane);
    7066              :         int view = 1;
    7067        70574 :         std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7068              :         DriveItemVector::const_iterator di = myLFLinkLanes.begin();
    7069       117003 :         while (!lane->isLinkEnd(link) && seen <= dist) {
    7070        70655 :             if ((!lane->isInternal()
    7071        48414 :                     && (((*link)->getState() == LINKSTATE_ZIPPER && seen < (*link)->getFoeVisibilityDistance())
    7072        26220 :                         || !(*link)->havePriority()))
    7073        96673 :                     || (lane->isInternal() && zipperDist > 0)) {
    7074              :                 // find the drive item corresponding to this link
    7075              :                 bool found = false;
    7076        51400 :                 while (di != myLFLinkLanes.end() && !found) {
    7077        26634 :                     if ((*di).myLink != nullptr) {
    7078              :                         const MSLane* diPredLane = (*di).myLink->getLaneBefore();
    7079        26634 :                         if (diPredLane != nullptr) {
    7080        26634 :                             if (&diPredLane->getEdge() == &lane->getEdge()) {
    7081              :                                 found = true;
    7082              :                             }
    7083              :                         }
    7084              :                     }
    7085        26634 :                     if (!found) {
    7086              :                         di++;
    7087              :                     }
    7088              :                 }
    7089        24766 :                 if (found) {
    7090        24766 :                     const SUMOTime leaveTime = (*link)->getLeaveTime((*di).myArrivalTime, (*di).myArrivalSpeed,
    7091        24766 :                                                (*di).getLeaveSpeed(), getVehicleType().getLength());
    7092        24766 :                     const MSLink* entry = (*link)->getCorrespondingEntryLink();
    7093              :                     //if (DEBUG_COND) {
    7094              :                     //    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";
    7095              :                     //}
    7096        24766 :                     if (entry->hasApproachingFoe((*di).myArrivalTime, leaveTime, (*di).myArrivalSpeed, getCarFollowModel().getMaxDecel())) {
    7097              :                         //std::cout << SIMTIME << " veh=" << getID() << " aborting changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << "\n";
    7098              :                         return true;
    7099              :                     }
    7100              :                 }
    7101              :                 // no drive item is found if the vehicle aborts its request within dist
    7102              :             }
    7103        46429 :             lane = (*link)->getViaLaneOrLane();
    7104        46429 :             if (!lane->getEdge().isInternal()) {
    7105        24260 :                 view++;
    7106              :             }
    7107        46429 :             seen += lane->getLength();
    7108        46429 :             link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
    7109              :         }
    7110              :     }
    7111              :     return false;
    7112              : }
    7113              : 
    7114              : 
    7115              : PositionVector
    7116      6719253 : MSVehicle::getBoundingBox(double offset) const {
    7117      6719253 :     PositionVector centerLine;
    7118      6719253 :     Position pos = getPosition();
    7119      6719253 :     centerLine.push_back(pos);
    7120      6719253 :     switch (myType->getGuiShape()) {
    7121         1730 :         case SUMOVehicleShape::BUS_FLEXIBLE:
    7122              :         case SUMOVehicleShape::RAIL:
    7123              :         case SUMOVehicleShape::RAIL_CAR:
    7124              :         case SUMOVehicleShape::RAIL_CARGO:
    7125              :         case SUMOVehicleShape::TRUCK_SEMITRAILER:
    7126              :         case SUMOVehicleShape::TRUCK_1TRAILER: {
    7127         4460 :             for (MSLane* lane : myFurtherLanes) {
    7128         2730 :                 centerLine.push_back(lane->getShape().back());
    7129              :             }
    7130              :             break;
    7131              :         }
    7132              :         default:
    7133              :             break;
    7134              :     }
    7135      6719253 :     double l = getLength();
    7136      6719253 :     Position backPos = getBackPosition();
    7137      6719253 :     if (pos.distanceTo2D(backPos) > l + NUMERICAL_EPS) {
    7138              :         // getBackPosition may not match the visual back in networks without internal lanes
    7139       358047 :         double a = getAngle() + M_PI; // angle pointing backwards
    7140       358047 :         backPos = pos + Position(l * cos(a), l * sin(a));
    7141              :     }
    7142      6719253 :     centerLine.push_back(backPos);
    7143      6719253 :     if (offset != 0) {
    7144         6543 :         centerLine.extrapolate2D(offset);
    7145              :     }
    7146              :     PositionVector result = centerLine;
    7147     13434216 :     result.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7148     13434216 :     centerLine.move2side(MIN2(0.0, -0.5 * myType->getWidth() - offset));
    7149      6719253 :     result.append(centerLine.reverse(), POSITION_EPS);
    7150      6719253 :     return result;
    7151      6719253 : }
    7152              : 
    7153              : 
    7154              : PositionVector
    7155        72802 : MSVehicle::getBoundingPoly(double offset) const {
    7156        72802 :     switch (myType->getGuiShape()) {
    7157        72318 :         case SUMOVehicleShape::PASSENGER:
    7158              :         case SUMOVehicleShape::PASSENGER_SEDAN:
    7159              :         case SUMOVehicleShape::PASSENGER_HATCHBACK:
    7160              :         case SUMOVehicleShape::PASSENGER_WAGON:
    7161              :         case SUMOVehicleShape::PASSENGER_VAN: {
    7162              :             // box with corners cut off
    7163        72318 :             PositionVector result;
    7164        72318 :             PositionVector centerLine;
    7165        72318 :             centerLine.push_back(getPosition());
    7166        72318 :             centerLine.push_back(getBackPosition());
    7167        72318 :             if (offset != 0) {
    7168         1600 :                 centerLine.extrapolate2D(offset);
    7169              :             }
    7170              :             PositionVector line1 = centerLine;
    7171              :             PositionVector line2 = centerLine;
    7172       144636 :             line1.move2side(MAX2(0.0, 0.3 * myType->getWidth() + offset));
    7173       144636 :             line2.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
    7174        72318 :             line2.scaleRelative(0.8);
    7175        72318 :             result.push_back(line1[0]);
    7176        72318 :             result.push_back(line2[0]);
    7177        72318 :             result.push_back(line2[1]);
    7178        72318 :             result.push_back(line1[1]);
    7179       144636 :             line1.move2side(MIN2(0.0, -0.6 * myType->getWidth() - offset));
    7180       144636 :             line2.move2side(MIN2(0.0, -1.0 * myType->getWidth() - offset));
    7181        72318 :             result.push_back(line1[1]);
    7182        72318 :             result.push_back(line2[1]);
    7183        72318 :             result.push_back(line2[0]);
    7184        72318 :             result.push_back(line1[0]);
    7185              :             return result;
    7186        72318 :         }
    7187          484 :         default:
    7188          484 :             return getBoundingBox();
    7189              :     }
    7190              : }
    7191              : 
    7192              : 
    7193              : bool
    7194       561919 : MSVehicle::onFurtherEdge(const MSEdge* edge) const {
    7195       647478 :     for (std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
    7196       179060 :         if (&(*i)->getEdge() == edge) {
    7197              :             return true;
    7198              :         }
    7199              :     }
    7200              :     return false;
    7201              : }
    7202              : 
    7203              : 
    7204              : bool
    7205   7465628184 : MSVehicle::isBidiOn(const MSLane* lane) const {
    7206   7466747956 :     return lane->getBidiLane() != nullptr && (
    7207      1119772 :                myLane == lane->getBidiLane()
    7208       561919 :                || onFurtherEdge(&lane->getBidiLane()->getEdge()));
    7209              : }
    7210              : 
    7211              : 
    7212              : bool
    7213           20 : MSVehicle::rerouteParkingArea(const std::string& parkingAreaID, std::string& errorMsg) {
    7214              :     // this function is based on MSTriggeredRerouter::rerouteParkingArea in order to keep
    7215              :     // consistency in the behaviour.
    7216              : 
    7217              :     // get vehicle params
    7218           20 :     MSParkingArea* destParkArea = getNextParkingArea();
    7219           20 :     const MSRoute& route = getRoute();
    7220           20 :     const MSEdge* lastEdge = route.getLastEdge();
    7221              : 
    7222           20 :     if (destParkArea == nullptr) {
    7223              :         // not driving towards a parking area
    7224            0 :         errorMsg = "Vehicle " + getID() + " is not driving to a parking area so it cannot be rerouted.";
    7225            0 :         return false;
    7226              :     }
    7227              : 
    7228              :     // if the current route ends at the parking area, the new route will also and at the new area
    7229           20 :     bool newDestination = (&destParkArea->getLane().getEdge() == route.getLastEdge()
    7230           10 :                            && getArrivalPos() >= destParkArea->getBeginLanePosition()
    7231           30 :                            && getArrivalPos() <= destParkArea->getEndLanePosition());
    7232              : 
    7233              :     // retrieve info on the new parking area
    7234           20 :     MSParkingArea* newParkingArea = (MSParkingArea*) MSNet::getInstance()->getStoppingPlace(
    7235              :                                         parkingAreaID, SumoXMLTag::SUMO_TAG_PARKING_AREA);
    7236              : 
    7237           20 :     if (newParkingArea == nullptr) {
    7238            0 :         errorMsg = "Parking area ID " + toString(parkingAreaID) + " not found in the network.";
    7239            0 :         return false;
    7240              :     }
    7241              : 
    7242           20 :     const MSEdge* newEdge = &(newParkingArea->getLane().getEdge());
    7243           20 :     SUMOAbstractRouter<MSEdge, SUMOVehicle>& router = getRouterTT();
    7244              : 
    7245              :     // Compute the route from the current edge to the parking area edge
    7246              :     ConstMSEdgeVector edgesToPark;
    7247           20 :     router.compute(getEdge(), getPositionOnLane(), newEdge, newParkingArea->getEndLanePosition(), this, MSNet::getInstance()->getCurrentTimeStep(), edgesToPark);
    7248              : 
    7249              :     // Compute the route from the parking area edge to the end of the route
    7250              :     ConstMSEdgeVector edgesFromPark;
    7251           20 :     if (!newDestination) {
    7252           15 :         router.compute(newEdge, lastEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesFromPark);
    7253              :     } else {
    7254              :         // adapt plans of any riders
    7255           10 :         for (MSTransportable* p : getPersons()) {
    7256            5 :             p->rerouteParkingArea(getNextParkingArea(), newParkingArea);
    7257              :         }
    7258              :     }
    7259              : 
    7260              :     // we have a new destination, let's replace the vehicle route
    7261           20 :     ConstMSEdgeVector edges = edgesToPark;
    7262           20 :     if (edgesFromPark.size() > 0) {
    7263           15 :         edges.insert(edges.end(), edgesFromPark.begin() + 1, edgesFromPark.end());
    7264              :     }
    7265              : 
    7266           20 :     if (newDestination) {
    7267            5 :         SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
    7268            5 :         *newParameter = getParameter();
    7269            5 :         newParameter->arrivalPosProcedure = ArrivalPosDefinition::GIVEN;
    7270            5 :         newParameter->arrivalPos = newParkingArea->getEndLanePosition();
    7271            5 :         replaceParameter(newParameter);
    7272              :     }
    7273           20 :     const double routeCost = router.recomputeCosts(edges, this, MSNet::getInstance()->getCurrentTimeStep());
    7274           20 :     ConstMSEdgeVector prevEdges(myCurrEdge, myRoute->end());
    7275           20 :     const double savings = router.recomputeCosts(prevEdges, this, MSNet::getInstance()->getCurrentTimeStep());
    7276           20 :     if (replaceParkingArea(newParkingArea, errorMsg)) {
    7277           20 :         const bool onInit = myLane == nullptr;
    7278           40 :         replaceRouteEdges(edges, routeCost, savings, "TraCI:" + toString(SUMO_TAG_PARKING_AREA_REROUTE), onInit, false, false);
    7279              :     } else {
    7280            0 :         WRITE_WARNING("Vehicle '" + getID() + "' could not reroute to new parkingArea '" + newParkingArea->getID()
    7281              :                       + "' reason=" + errorMsg + ", time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
    7282            0 :         return false;
    7283              :     }
    7284           20 :     return true;
    7285           20 : }
    7286              : 
    7287              : 
    7288              : bool
    7289        46380 : MSVehicle::addTraciStop(SUMOVehicleParameter::Stop stop, std::string& errorMsg) {
    7290        46380 :     const int numStops = (int)myStops.size();
    7291        46380 :     const bool result = MSBaseVehicle::addTraciStop(stop, errorMsg);
    7292        46380 :     if (myLane != nullptr && numStops != (int)myStops.size()) {
    7293        44760 :         updateBestLanes(true);
    7294              :     }
    7295        46380 :     return result;
    7296              : }
    7297              : 
    7298              : 
    7299              : bool
    7300         3130 : MSVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
    7301         3130 :     if (myCurrEdge == stop.edge && distToStop + POSITION_EPS < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0)) {
    7302         1431 :         if (distToStop < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)) {
    7303         1001 :             double vNew = getCarFollowModel().maximumSafeStopSpeed(distToStop, getCarFollowModel().getMaxDecel(), getSpeed(), false, 0);
    7304              :             //std::cout << SIMTIME << " veh=" << getID() << " v=" << myState.mySpeed << " distToStop=" << distToStop
    7305              :             //    << " vMinNex=" << getCarFollowModel().minNextSpeed(getSpeed(), this)
    7306              :             //    << " bg1=" << getCarFollowModel().brakeGap(myState.mySpeed)
    7307              :             //    << " bg2=" << getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)
    7308              :             //    << " vNew=" << vNew
    7309              :             //    << "\n";
    7310         1001 :             myState.mySpeed = MIN2(myState.mySpeed, vNew + ACCEL2SPEED(getCarFollowModel().getEmergencyDecel()));
    7311         1001 :             myState.myPos = MIN2(myState.myPos, stop.pars.endPos);
    7312         1001 :             myCachedPosition = Position::INVALID;
    7313         1001 :             if (myState.myPos < myType->getLength()) {
    7314          418 :                 computeFurtherLanes(myLane, myState.myPos, true);
    7315          418 :                 myAngle = computeAngle();
    7316          418 :                 if (myLaneChangeModel->isOpposite()) {
    7317            0 :                     myAngle += M_PI;
    7318              :                 }
    7319              :             }
    7320              :         }
    7321              :     }
    7322         3130 :     return true;
    7323              : }
    7324              : 
    7325              : 
    7326              : bool
    7327     24369809 : MSVehicle::resumeFromStopping() {
    7328     24369809 :     if (isStopped()) {
    7329        46424 :         if (myAmRegisteredAsWaiting) {
    7330          118 :             MSNet::getInstance()->getVehicleControl().unregisterOneWaiting();
    7331          118 :             myAmRegisteredAsWaiting = false;
    7332              :         }
    7333              :         MSStop& stop = myStops.front();
    7334              :         // we have waited long enough and fulfilled any passenger-requirements
    7335        46424 :         if (stop.busstop != nullptr) {
    7336              :             // inform bus stop about leaving it
    7337        17900 :             stop.busstop->leaveFrom(this);
    7338              :         }
    7339              :         // we have waited long enough and fulfilled any container-requirements
    7340        46424 :         if (stop.containerstop != nullptr) {
    7341              :             // inform container stop about leaving it
    7342          528 :             stop.containerstop->leaveFrom(this);
    7343              :         }
    7344        46424 :         if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
    7345              :             // inform parking area about leaving it
    7346         7497 :             stop.parkingarea->leaveFrom(this);
    7347              :         }
    7348        46424 :         if (stop.chargingStation != nullptr) {
    7349              :             // inform charging station about leaving it
    7350         3506 :             stop.chargingStation->leaveFrom(this);
    7351              :         }
    7352              :         // the current stop is no longer valid
    7353        46424 :         myLane->getEdge().removeWaiting(this);
    7354              :         // MSStopOut needs to know whether the stop had a loaded 'ended' value so we call this before replacing the value
    7355        46424 :         if (stop.pars.started == -1) {
    7356              :             // waypoint edge was passed in a single step
    7357          317 :             stop.pars.started = MSNet::getInstance()->getCurrentTimeStep();
    7358              :         }
    7359        46424 :         if (MSStopOut::active()) {
    7360         3663 :             MSStopOut::getInstance()->stopEnded(this, stop.pars, stop.lane->getID());
    7361              :         }
    7362        46424 :         stop.pars.ended = MSNet::getInstance()->getCurrentTimeStep();
    7363       101904 :         for (const auto& rem : myMoveReminders) {
    7364        55480 :             rem.first->notifyStopEnded();
    7365              :         }
    7366        46424 :         if (stop.pars.collision && MSLane::getCollisionAction() == MSLane::COLLISION_ACTION_WARN) {
    7367          425 :             myCollisionImmunity = TIME2STEPS(5); // leave the conflict area
    7368              :         }
    7369        46424 :         if (stop.pars.posLat != INVALID_DOUBLE && MSGlobals::gLateralResolution <= 0) {
    7370              :             // reset lateral position to default
    7371          194 :             myState.myPosLat = 0;
    7372              :         }
    7373        46424 :         myPastStops.push_back(stop.pars);
    7374        46424 :         myPastStops.back().routeIndex = (int)(stop.edge - myRoute->begin());
    7375        46424 :         myStops.pop_front();
    7376        46424 :         myStopDist = std::numeric_limits<double>::max();
    7377              :         // do not count the stopping time towards gridlock time.
    7378              :         // Other outputs use an independent counter and are not affected.
    7379        46424 :         myWaitingTime = 0;
    7380              :         // maybe the next stop is on the same edge; let's rebuild best lanes
    7381        46424 :         updateBestLanes(true);
    7382              :         // continue as wished...
    7383        46424 :         MSNet::getInstance()->informVehicleStateListener(this, MSNet::VehicleState::ENDING_STOP);
    7384        46424 :         MSNet::getInstance()->getVehicleControl().registerStopEnded();
    7385        46424 :         return true;
    7386              :     }
    7387              :     return false;
    7388              : }
    7389              : 
    7390              : 
    7391              : MSVehicle::Influencer&
    7392      4558561 : MSVehicle::getInfluencer() {
    7393      4558561 :     if (myInfluencer == nullptr) {
    7394         3530 :         myInfluencer = new Influencer();
    7395              :     }
    7396      4558561 :     return *myInfluencer;
    7397              : }
    7398              : 
    7399              : MSVehicle::BaseInfluencer&
    7400           24 : MSVehicle::getBaseInfluencer() {
    7401           24 :     return getInfluencer();
    7402              : }
    7403              : 
    7404              : 
    7405              : const MSVehicle::Influencer*
    7406            0 : MSVehicle::getInfluencer() const {
    7407            0 :     return myInfluencer;
    7408              : }
    7409              : 
    7410              : const MSVehicle::BaseInfluencer*
    7411       237449 : MSVehicle::getBaseInfluencer() const {
    7412       237449 :     return myInfluencer;
    7413              : }
    7414              : 
    7415              : 
    7416              : double
    7417         4090 : MSVehicle::getSpeedWithoutTraciInfluence() const {
    7418         4090 :     if (myInfluencer != nullptr && myInfluencer->getOriginalSpeed() >= 0) {
    7419              :         // influencer original speed is -1 on initialization
    7420         1666 :         return myInfluencer->getOriginalSpeed();
    7421              :     }
    7422         2424 :     return myState.mySpeed;
    7423              : }
    7424              : 
    7425              : 
    7426              : int
    7427    969990026 : MSVehicle::influenceChangeDecision(int state) {
    7428    969990026 :     if (hasInfluencer()) {
    7429      2815542 :         state = getInfluencer().influenceChangeDecision(
    7430              :                     MSNet::getInstance()->getCurrentTimeStep(),
    7431      2815542 :                     myLane->getEdge(),
    7432              :                     getLaneIndex(),
    7433              :                     state);
    7434              :     }
    7435    969990026 :     return state;
    7436              : }
    7437              : 
    7438              : 
    7439              : void
    7440         7775 : MSVehicle::setRemoteState(Position xyPos) {
    7441         7775 :     myCachedPosition = xyPos;
    7442         7775 : }
    7443              : 
    7444              : 
    7445              : bool
    7446    778116360 : MSVehicle::isRemoteControlled() const {
    7447    778116360 :     return myInfluencer != nullptr && myInfluencer->isRemoteControlled();
    7448              : }
    7449              : 
    7450              : 
    7451              : bool
    7452        21149 : MSVehicle::wasRemoteControlled(SUMOTime lookBack) const {
    7453        21149 :     return myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() + lookBack >= MSNet::getInstance()->getCurrentTimeStep();
    7454              : }
    7455              : 
    7456              : 
    7457              : bool
    7458    500674628 : MSVehicle::keepClear(const MSLink* link) const {
    7459    500674628 :     if (link->hasFoes() && link->keepClear() /* && item.myLink->willHaveBlockedFoe()*/) {
    7460    155348281 :         const double keepClearTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, -1);
    7461              :         //std::cout << SIMTIME << " veh=" << getID() << " keepClearTime=" << keepClearTime << " accWait=" << getAccumulatedWaitingSeconds() << " keepClear=" << (keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime) << "\n";
    7462    156770464 :         return keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime;
    7463              :     } else {
    7464              :         return false;
    7465              :     }
    7466              : }
    7467              : 
    7468              : 
    7469              : bool
    7470    701991179 : MSVehicle::ignoreRed(const MSLink* link, bool canBrake) const {
    7471    701991179 :     if ((myInfluencer != nullptr && !myInfluencer->getEmergencyBrakeRedLight())) {
    7472              :         return true;
    7473              :     }
    7474    701683912 :     const double ignoreRedTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, -1);
    7475              : #ifdef DEBUG_IGNORE_RED
    7476              :     if (DEBUG_COND) {
    7477              :         std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID() << " state=" << toString(link->getState()) << "\n";
    7478              :     }
    7479              : #endif
    7480    701683912 :     if (ignoreRedTime < 0) {
    7481    701678513 :         const double ignoreYellowTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, 0);
    7482    701678513 :         if (ignoreYellowTime > 0 && link->haveYellow()) {
    7483              :             assert(link->getTLLogic() != 0);
    7484           52 :             const double yellowDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7485              :             // when activating ignoreYellow behavior, vehicles will drive if they cannot brake
    7486           92 :             return !canBrake || ignoreYellowTime > yellowDuration;
    7487              :         } else {
    7488              :             return false;
    7489              :         }
    7490         5399 :     } else if (link->haveYellow()) {
    7491              :         // always drive at yellow when ignoring red
    7492              :         return true;
    7493         5243 :     } else if (link->haveRed()) {
    7494              :         assert(link->getTLLogic() != 0);
    7495         3832 :         const double redDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
    7496              : #ifdef DEBUG_IGNORE_RED
    7497              :         if (DEBUG_COND) {
    7498              :             std::cout
    7499              :             // << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID()
    7500              :                     << "   ignoreRedTime=" << ignoreRedTime
    7501              :                     << " spentRed=" << redDuration
    7502              :                     << " canBrake=" << canBrake << "\n";
    7503              :         }
    7504              : #endif
    7505              :         // when activating ignoreRed behavior, vehicles will always drive if they cannot brake
    7506         6356 :         return !canBrake || ignoreRedTime > redDuration;
    7507              :     } else {
    7508              :         return false;
    7509              :     }
    7510              : }
    7511              : 
    7512              : bool
    7513   1278274301 : MSVehicle::ignoreFoe(const SUMOTrafficObject* foe) const {
    7514   1278274301 :     if (!getParameter().wasSet(VEHPARS_CFMODEL_PARAMS_SET)) {
    7515              :         return false;
    7516              :     }
    7517         2768 :     for (const std::string& typeID : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_TYPES), "")).getVector()) {
    7518          398 :         if (typeID == foe->getVehicleType().getID()) {
    7519              :             return true;
    7520              :         }
    7521         1384 :     }
    7522         2381 :     for (const std::string& id : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_IDS), "")).getVector()) {
    7523          986 :         if (id == foe->getID()) {
    7524              :             return true;
    7525              :         }
    7526          986 :     }
    7527          409 :     return false;
    7528              : }
    7529              : 
    7530              : bool
    7531    537322521 : MSVehicle::passingMinor() const {
    7532              :     // either on an internal lane that was entered via minor link
    7533              :     // or on approach to minor link below visibility distance
    7534    537322521 :     if (myLane == nullptr) {
    7535              :         return false;
    7536              :     }
    7537    537322521 :     if (myLane->getEdge().isInternal()) {
    7538     10159912 :         return !myLane->getIncomingLanes().front().viaLink->havePriority();
    7539    527162609 :     } else if (myLFLinkLanes.size() > 0 && myLFLinkLanes.front().myLink != nullptr) {
    7540              :         MSLink* link = myLFLinkLanes.front().myLink;
    7541    270235137 :         return !link->havePriority() && myLFLinkLanes.front().myDistance <= link->getFoeVisibilityDistance();
    7542              :     }
    7543              :     return false;
    7544              : }
    7545              : 
    7546              : bool
    7547     20116911 : MSVehicle::isLeader(const MSLink* link, const MSVehicle* veh, const double gap) const {
    7548              :     assert(link->fromInternalLane());
    7549     20116911 :     if (veh == nullptr) {
    7550              :         return false;
    7551              :     }
    7552     20116911 :     if (!myLane->isInternal() || myLane->getEdge().getToJunction() != link->getJunction()) {
    7553              :         // if this vehicle is not yet on the junction, every vehicle is a leader
    7554              :         return true;
    7555              :     }
    7556      1816155 :     if (veh->getLaneChangeModel().hasBlueLight()) {
    7557              :         // blue light device automatically gets right of way
    7558              :         return true;
    7559              :     }
    7560      1815872 :     const MSLane* foeLane = veh->getLane();
    7561      1815872 :     if (foeLane->isInternal()) {
    7562      1350967 :         if (foeLane->getEdge().getFromJunction() == link->getJunction()) {
    7563      1334166 :             SUMOTime egoET = myJunctionConflictEntryTime;
    7564      1334166 :             SUMOTime foeET = veh->myJunctionEntryTime;
    7565              :             // check relationship between link and foeLane
    7566      1334166 :             if (foeLane->getNormalPredecessorLane() == link->getInternalLaneBefore()->getNormalPredecessorLane()) {
    7567              :                 // we are entering the junction from the same lane
    7568       454421 :                 egoET = myJunctionEntryTimeNeverYield;
    7569       454421 :                 foeET = veh->myJunctionEntryTimeNeverYield;
    7570       454421 :                 if (link->isExitLinkAfterInternalJunction() && link->getInternalLaneBefore()->getLogicalPredecessorLane()->getEntryLink()->isIndirect()) {
    7571        91633 :                     egoET = myJunctionConflictEntryTime;
    7572              :                 }
    7573              :             } else {
    7574       879745 :                 const MSLink* foeLink = foeLane->getIncomingLanes()[0].viaLink;
    7575       879745 :                 const MSJunctionLogic* logic = link->getJunction()->getLogic();
    7576              :                 assert(logic != nullptr);
    7577              :                 // determine who has right of way
    7578              :                 bool response; // ego response to foe
    7579              :                 bool response2; // foe response to ego
    7580              :                 // attempt 1: tlLinkState
    7581       879745 :                 const MSLink* entry = link->getCorrespondingEntryLink();
    7582       879745 :                 const MSLink* foeEntry = foeLink->getCorrespondingEntryLink();
    7583       879745 :                 if (entry->haveRed() || foeEntry->haveRed()) {
    7584              :                     // ensure that vehicles which are stuck on the intersection may exit
    7585       115610 :                     if (!foeEntry->haveRed() && veh->getSpeed() > SUMO_const_haltingSpeed && gap < 0) {
    7586              :                         // foe might be oncoming, don't drive unless foe can still brake safely
    7587        11467 :                         const double foeNextSpeed = veh->getSpeed() + ACCEL2SPEED(veh->getCarFollowModel().getMaxAccel());
    7588        11467 :                         const double foeBrakeGap = veh->getCarFollowModel().brakeGap(
    7589        11467 :                                                        foeNextSpeed, veh->getCarFollowModel().getMaxDecel(), veh->getCarFollowModel().getHeadwayTime());
    7590              :                         // the minGap was subtracted from gap in MSLink::getLeaderInfo (enlarging the negative gap)
    7591              :                         // so the -2* makes it point in the right direction
    7592        11467 :                         const double foeGap = -gap - veh->getLength() - 2 * getVehicleType().getMinGap();
    7593              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7594              :                         if (DEBUG_COND) {
    7595              :                             std::cout << " foeGap=" << foeGap << " foeBGap=" << foeBrakeGap << "\n";
    7596              : 
    7597              :                         }
    7598              : #endif
    7599        11467 :                         if (foeGap < foeBrakeGap) {
    7600              :                             response = true;
    7601              :                             response2 = false;
    7602              :                         } else {
    7603              :                             response = false;
    7604              :                             response2 = true;
    7605              :                         }
    7606              :                     } else {
    7607              :                         // let conflict entry time decide
    7608              :                         response = true;
    7609              :                         response2 = true;
    7610              :                     }
    7611       764135 :                 } else if (entry->havePriority() != foeEntry->havePriority()) {
    7612       560219 :                     response = !entry->havePriority();
    7613       560219 :                     response2 = !foeEntry->havePriority();
    7614       203916 :                 } else if (entry->haveYellow() && foeEntry->haveYellow()) {
    7615              :                     // let the faster vehicle keep moving
    7616         5153 :                     response = veh->getSpeed() >= getSpeed();
    7617         5153 :                     response2 = getSpeed() >= veh->getSpeed();
    7618              :                 } else {
    7619              :                     // fallback if pedestrian crossings are involved
    7620       198763 :                     response = logic->getResponseFor(link->getIndex()).test(foeLink->getIndex());
    7621       198763 :                     response2 = logic->getResponseFor(foeLink->getIndex()).test(link->getIndex());
    7622              :                 }
    7623              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7624              :                 if (DEBUG_COND) {
    7625              :                     std::cout << SIMTIME
    7626              :                               << " foeLane=" << foeLane->getID()
    7627              :                               << " foeLink=" << foeLink->getViaLaneOrLane()->getID()
    7628              :                               << " linkIndex=" << link->getIndex()
    7629              :                               << " foeLinkIndex=" << foeLink->getIndex()
    7630              :                               << " entryState=" << toString(entry->getState())
    7631              :                               << " entryState2=" << toString(foeEntry->getState())
    7632              :                               << " response=" << response
    7633              :                               << " response2=" << response2
    7634              :                               << "\n";
    7635              :                 }
    7636              : #endif
    7637       879745 :                 if (!response) {
    7638              :                     // if we have right of way over the foe, entryTime does not matter
    7639        77668 :                     foeET = veh->myJunctionConflictEntryTime;
    7640        77668 :                     egoET = myJunctionEntryTime;
    7641       802077 :                 } else if (response && response2) {
    7642              :                     // in a mutual conflict scenario, use entry time to avoid deadlock
    7643       127385 :                     foeET = veh->myJunctionConflictEntryTime;
    7644       127385 :                     egoET = myJunctionConflictEntryTime;
    7645              :                 }
    7646              :             }
    7647      1334166 :             if (egoET == foeET) {
    7648              :                 // try to use speed as tie braker
    7649       106210 :                 if (getSpeed() == veh->getSpeed()) {
    7650              :                     // use ID as tie braker
    7651              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7652              :                     if (DEBUG_COND) {
    7653              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7654              :                                   << " foeIsLeaderByID=" << (getID() < veh->getID()) << "\n";
    7655              :                     }
    7656              : #endif
    7657        57319 :                     return getID() < veh->getID();
    7658              :                 } else {
    7659              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7660              :                     if (DEBUG_COND) {
    7661              :                         std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
    7662              :                                   << " foeIsLeaderBySpeed=" << (getSpeed() < veh->getSpeed())
    7663              :                                   << " v=" << getSpeed() << " foeV=" << veh->getSpeed()
    7664              :                                   << "\n";
    7665              :                     }
    7666              : #endif
    7667        48891 :                     return getSpeed() < veh->getSpeed();
    7668              :                 }
    7669              :             } else {
    7670              :                 // leader was on the junction first
    7671              : #ifdef DEBUG_PLAN_MOVE_LEADERINFO
    7672              :                 if (DEBUG_COND) {
    7673              :                     std::cout << SIMTIME << " veh=" << getID() << " egoET " << egoET << " with foe " << veh->getID()
    7674              :                               << " foeET=" << foeET  << " isLeader=" << (egoET > foeET) << "\n";
    7675              :                 }
    7676              : #endif
    7677      1227956 :                 return egoET > foeET;
    7678              :             }
    7679              :         } else {
    7680              :             // vehicle can only be partially on the junction. Must be a leader
    7681              :             return true;
    7682              :         }
    7683              :     } else {
    7684              :         // vehicle can only be partially on the junction. Must be a leader
    7685              :         return true;
    7686              :     }
    7687              : }
    7688              : 
    7689              : void
    7690         2477 : MSVehicle::saveState(OutputDevice& out) {
    7691         2477 :     MSBaseVehicle::saveState(out);
    7692              :     // here starts the vehicle internal part (see loading)
    7693              :     std::vector<std::string> internals;
    7694         2477 :     internals.push_back(toString(myParameter->parametersSet));
    7695         2477 :     internals.push_back(toString(myDeparture));
    7696         2477 :     internals.push_back(toString(distance(myRoute->begin(), myCurrEdge)));
    7697         2477 :     internals.push_back(toString(myDepartPos));
    7698         2477 :     internals.push_back(toString(myWaitingTime));
    7699         2477 :     internals.push_back(toString(myTimeLoss));
    7700         2477 :     internals.push_back(toString(myLastActionTime));
    7701         2477 :     internals.push_back(toString(isStopped()));
    7702         2477 :     internals.push_back(toString(myPastStops.size()));
    7703         2477 :     out.writeAttr(SUMO_ATTR_STATE, internals);
    7704         2477 :     out.writeAttr(SUMO_ATTR_POSITION, std::vector<double> { myState.myPos, myState.myBackPos, myState.myLastCoveredDist });
    7705         2477 :     out.writeAttr(SUMO_ATTR_SPEED, std::vector<double> { myState.mySpeed, myState.myPreviousSpeed });
    7706         2477 :     out.writeAttr(SUMO_ATTR_ANGLE, GeomHelper::naviDegree(myAngle));
    7707         2477 :     out.writeAttr(SUMO_ATTR_POSITION_LAT, myState.myPosLat);
    7708         2477 :     out.writeAttr(SUMO_ATTR_WAITINGTIME, myWaitingTimeCollector.getState());
    7709         2477 :     myLaneChangeModel->saveState(out);
    7710              :     // save past stops
    7711         5404 :     for (SUMOVehicleParameter::Stop stop : myPastStops) {
    7712         2927 :         stop.write(out, false);
    7713              :         // do not write started and ended twice
    7714         2927 :         if ((stop.parametersSet & STOP_STARTED_SET) == 0) {
    7715         5844 :             out.writeAttr(SUMO_ATTR_STARTED, time2string(stop.started));
    7716              :         }
    7717         2927 :         if ((stop.parametersSet & STOP_ENDED_SET) == 0) {
    7718         5844 :             out.writeAttr(SUMO_ATTR_ENDED, time2string(stop.ended));
    7719              :         }
    7720         2927 :         stop.writeParams(out);
    7721         2927 :         out.closeTag();
    7722         2927 :     }
    7723              :     // save upcoming stops
    7724         2939 :     for (MSStop& stop : myStops) {
    7725          462 :         stop.write(out);
    7726              :     }
    7727              :     // save parameters and device states
    7728         2477 :     myParameter->writeParams(out);
    7729         6255 :     for (MSVehicleDevice* const dev : myDevices) {
    7730         3778 :         dev->saveState(out);
    7731              :     }
    7732         2477 :     out.closeTag();
    7733         2477 : }
    7734              : 
    7735              : void
    7736         4160 : MSVehicle::loadState(const SUMOSAXAttributes& attrs, const SUMOTime offset) {
    7737         4160 :     if (!attrs.hasAttribute(SUMO_ATTR_POSITION)) {
    7738            0 :         throw ProcessError(TL("Error: Invalid vehicles in state (may be a meso state)!"));
    7739              :     }
    7740              :     int routeOffset;
    7741              :     bool stopped;
    7742              :     int pastStops;
    7743              : 
    7744         4160 :     std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
    7745         4160 :     bis >> myParameter->parametersSet;
    7746         4160 :     bis >> myDeparture;
    7747         4160 :     bis >> routeOffset;
    7748         4160 :     bis >> myDepartPos;
    7749         4160 :     bis >> myWaitingTime;
    7750         4160 :     bis >> myTimeLoss;
    7751         4160 :     bis >> myLastActionTime;
    7752              :     bis >> stopped;
    7753         4160 :     bis >> pastStops;
    7754              : 
    7755         4160 :     if (attrs.hasAttribute(SUMO_ATTR_ARRIVALPOS_RANDOMIZED)) {
    7756              :         bool ok;
    7757            4 :         myArrivalPos = attrs.get<double>(SUMO_ATTR_ARRIVALPOS_RANDOMIZED, getID().c_str(), ok);
    7758              :     }
    7759              :     // load stops
    7760              :     myStops.clear();
    7761         4160 :     addStops(!MSGlobals::gCheckRoutes, &myCurrEdge, false);
    7762              : 
    7763         4160 :     if (hasDeparted()) {
    7764         1784 :         myCurrEdge = myRoute->begin() + routeOffset;
    7765         1784 :         myDeparture -= offset;
    7766              :         // fix stops
    7767         4685 :         while (pastStops > 0) {
    7768         2901 :             myPastStops.push_back(myStops.front().pars);
    7769         2901 :             myPastStops.back().routeIndex = (int)(myStops.front().edge - myRoute->begin());
    7770         2901 :             myStops.pop_front();
    7771         2901 :             pastStops--;
    7772              :         }
    7773              :         // see MSBaseVehicle constructor
    7774         1784 :         if (myParameter->wasSet(VEHPARS_FORCE_REROUTE)) {
    7775         1385 :             calculateArrivalParams(true);
    7776              :         }
    7777              :         // a (tentative lane is needed for calling hasArrivedInternal
    7778         1784 :         myLane = (*myCurrEdge)->getLanes()[0];
    7779              :     }
    7780         4160 :     if (getActionStepLength() == DELTA_T && !isActionStep(SIMSTEP)) {
    7781            1 :         myLastActionTime -= (myLastActionTime - SIMSTEP) % DELTA_T;
    7782            3 :         WRITE_WARNINGF(TL("Action steps are out of sync for loaded vehicle '%'."), getID());
    7783              :     }
    7784         4160 :     std::istringstream pis(attrs.getString(SUMO_ATTR_POSITION));
    7785         4160 :     pis >> myState.myPos >> myState.myBackPos >> myState.myLastCoveredDist;
    7786         4160 :     std::istringstream sis(attrs.getString(SUMO_ATTR_SPEED));
    7787         4160 :     sis >> myState.mySpeed >> myState.myPreviousSpeed;
    7788         4160 :     myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7789         4160 :     myAngle = GeomHelper::fromNaviDegree(attrs.getFloat(SUMO_ATTR_ANGLE));
    7790         4160 :     myState.myPosLat = attrs.getFloat(SUMO_ATTR_POSITION_LAT);
    7791         4160 :     std::istringstream dis(attrs.getString(SUMO_ATTR_DISTANCE));
    7792         4160 :     dis >> myOdometer >> myNumberReroutes;
    7793         4160 :     myWaitingTimeCollector.setState(attrs.getString(SUMO_ATTR_WAITINGTIME));
    7794         4160 :     if (stopped) {
    7795          216 :         myStops.front().startedFromState = true;
    7796          216 :         myStopDist = 0;
    7797              :     }
    7798         4160 :     myLaneChangeModel->loadState(attrs);
    7799              :     // no need to reset myCachedPosition here since state loading happens directly after creation
    7800         4160 : }
    7801              : 
    7802              : void
    7803           37 : MSVehicle::loadPreviousApproaching(MSLink* link, bool setRequest,
    7804              :                                    SUMOTime arrivalTime, double arrivalSpeed,
    7805              :                                    double arrivalSpeedBraking,
    7806              :                                    double dist, double leaveSpeed) {
    7807              :     // ensure that approach information is reset on the next call to setApproachingForAllLinks
    7808           37 :     myLFLinkLanes.push_back(DriveProcessItem(link, 0, 0, setRequest,
    7809              :                             arrivalTime, arrivalSpeed, arrivalSpeedBraking, dist, leaveSpeed));
    7810              : 
    7811           37 : }
    7812              : 
    7813              : 
    7814              : std::shared_ptr<MSSimpleDriverState>
    7815      2436121 : MSVehicle::getDriverState() const {
    7816      2436121 :     return myDriverState->getDriverState();
    7817              : }
    7818              : 
    7819              : 
    7820              : double
    7821    609580216 : MSVehicle::getFriction() const {
    7822    609580216 :     return myFrictionDevice == nullptr ? 1. : myFrictionDevice->getMeasuredFriction();
    7823              : }
    7824              : 
    7825              : 
    7826              : void
    7827          241 : MSVehicle::setPreviousSpeed(double prevSpeed, double prevAcceleration) {
    7828          241 :     myState.mySpeed = MAX2(0., prevSpeed);
    7829              :     // also retcon acceleration
    7830          241 :     if (prevAcceleration != std::numeric_limits<double>::min()) {
    7831            8 :         myAcceleration = prevAcceleration;
    7832              :     } else {
    7833          233 :         myAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
    7834              :     }
    7835          241 : }
    7836              : 
    7837              : 
    7838              : double
    7839   1819744671 : MSVehicle::getCurrentApparentDecel() const {
    7840              :     //return MAX2(-myAcceleration, getCarFollowModel().getApparentDecel());
    7841   1819744671 :     return getCarFollowModel().getApparentDecel();
    7842              : }
    7843              : 
    7844              : /****************************************************************************/
    7845              : bool
    7846           32 : MSVehicle::setExitManoeuvre() {
    7847           32 :     return (myManoeuvre.configureExitManoeuvre(this));
    7848              : }
    7849              : 
    7850              : /* -------------------------------------------------------------------------
    7851              :  * methods of MSVehicle::manoeuvre
    7852              :  * ----------------------------------------------------------------------- */
    7853              : 
    7854      4586388 : MSVehicle::Manoeuvre::Manoeuvre() : myManoeuvreStop(""), myManoeuvreStartTime(0), myManoeuvreCompleteTime(0), myManoeuvreType(MSVehicle::MANOEUVRE_NONE), myGUIIncrement(0) {}
    7855              : 
    7856              : 
    7857            0 : MSVehicle::Manoeuvre::Manoeuvre(const Manoeuvre& manoeuvre) {
    7858            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    7859            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    7860            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    7861            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    7862            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    7863            0 : }
    7864              : 
    7865              : 
    7866              : MSVehicle::Manoeuvre&
    7867            0 : MSVehicle::Manoeuvre::operator=(const Manoeuvre& manoeuvre) {
    7868            0 :     myManoeuvreStop = manoeuvre.myManoeuvreStop;
    7869            0 :     myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
    7870            0 :     myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
    7871            0 :     myManoeuvreType = manoeuvre.myManoeuvreType;
    7872            0 :     myGUIIncrement = manoeuvre.myGUIIncrement;
    7873            0 :     return *this;
    7874              : }
    7875              : 
    7876              : 
    7877              : bool
    7878            0 : MSVehicle::Manoeuvre::operator!=(const Manoeuvre& manoeuvre) {
    7879            0 :     return (myManoeuvreStop != manoeuvre.myManoeuvreStop ||
    7880            0 :             myManoeuvreStartTime != manoeuvre.myManoeuvreStartTime ||
    7881            0 :             myManoeuvreCompleteTime != manoeuvre.myManoeuvreCompleteTime ||
    7882            0 :             myManoeuvreType != manoeuvre.myManoeuvreType ||
    7883            0 :             myGUIIncrement != manoeuvre.myGUIIncrement
    7884            0 :            );
    7885              : }
    7886              : 
    7887              : 
    7888              : double
    7889          450 : MSVehicle::Manoeuvre::getGUIIncrement() const {
    7890          450 :     return (myGUIIncrement);
    7891              : }
    7892              : 
    7893              : 
    7894              : MSVehicle::ManoeuvreType
    7895         2971 : MSVehicle::Manoeuvre::getManoeuvreType() const {
    7896         2971 :     return (myManoeuvreType);
    7897              : }
    7898              : 
    7899              : 
    7900              : MSVehicle::ManoeuvreType
    7901         2971 : MSVehicle::getManoeuvreType() const {
    7902         2971 :     return (myManoeuvre.getManoeuvreType());
    7903              : }
    7904              : 
    7905              : 
    7906              : void
    7907           30 : MSVehicle::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    7908           30 :     myManoeuvre.setManoeuvreType(mType);
    7909           30 : }
    7910              : 
    7911              : 
    7912              : void
    7913           30 : MSVehicle::Manoeuvre::setManoeuvreType(const MSVehicle::ManoeuvreType mType) {
    7914           30 :     myManoeuvreType = mType;
    7915           30 : }
    7916              : 
    7917              : 
    7918              : bool
    7919           30 : MSVehicle::Manoeuvre::configureEntryManoeuvre(MSVehicle* veh) {
    7920           30 :     if (!veh->hasStops()) {
    7921              :         return false;    // should never happen - checked before call
    7922              :     }
    7923              : 
    7924           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    7925           30 :     const MSStop& stop = veh->getNextStop();
    7926              : 
    7927           30 :     int manoeuverAngle = stop.parkingarea->getLastFreeLotAngle();
    7928           30 :     double GUIAngle = stop.parkingarea->getLastFreeLotGUIAngle();
    7929           30 :     if (abs(GUIAngle) < 0.1) {
    7930              :         GUIAngle = -0.1;    // Wiggle vehicle on parallel entry
    7931              :     }
    7932           30 :     myManoeuvreVehicleID = veh->getID();
    7933           30 :     myManoeuvreStop = stop.parkingarea->getID();
    7934           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_ENTRY;
    7935           30 :     myManoeuvreStartTime = currentTime;
    7936           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getEntryManoeuvreTime(manoeuverAngle);
    7937           30 :     myGUIIncrement = GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    7938              : 
    7939              : #ifdef DEBUG_STOPS
    7940              :     if (veh->isSelected()) {
    7941              :         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 <<
    7942              :                   " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    7943              :     }
    7944              : #endif
    7945              : 
    7946           30 :     return (true);
    7947              : }
    7948              : 
    7949              : 
    7950              : bool
    7951           32 : MSVehicle::Manoeuvre::configureExitManoeuvre(MSVehicle* veh) {
    7952              :     // At the moment we only want to set for parking areas
    7953           32 :     if (!veh->hasStops()) {
    7954              :         return true;
    7955              :     }
    7956           32 :     if (veh->getNextStop().parkingarea == nullptr) {
    7957              :         return true;
    7958              :     }
    7959              : 
    7960           30 :     if (myManoeuvreType != MSVehicle::MANOEUVRE_NONE) {
    7961              :         return (false);
    7962              :     }
    7963              : 
    7964           30 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    7965              : 
    7966           30 :     int manoeuverAngle = veh->getCurrentParkingArea()->getManoeuverAngle(*veh);
    7967           30 :     double GUIAngle = veh->getCurrentParkingArea()->getGUIAngle(*veh);
    7968           30 :     if (abs(GUIAngle) < 0.1) {
    7969              :         GUIAngle = 0.1;    // Wiggle vehicle on parallel exit
    7970              :     }
    7971              : 
    7972           30 :     myManoeuvreVehicleID = veh->getID();
    7973           30 :     myManoeuvreStop = veh->getCurrentParkingArea()->getID();
    7974           30 :     myManoeuvreType = MSVehicle::MANOEUVRE_EXIT;
    7975           30 :     myManoeuvreStartTime = currentTime;
    7976           30 :     myManoeuvreCompleteTime = currentTime + veh->myType->getExitManoeuvreTime(manoeuverAngle);
    7977           30 :     myGUIIncrement = -GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
    7978           30 :     if (veh->remainingStopDuration() > 0) {
    7979           20 :         myManoeuvreCompleteTime += veh->remainingStopDuration();
    7980              :     }
    7981              : 
    7982              : #ifdef DEBUG_STOPS
    7983              :     if (veh->isSelected()) {
    7984              :         std::cout << "EXIT manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle  << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime
    7985              :                   << " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
    7986              :     }
    7987              : #endif
    7988              : 
    7989              :     return (true);
    7990              : }
    7991              : 
    7992              : 
    7993              : bool
    7994          222 : MSVehicle::Manoeuvre::entryManoeuvreIsComplete(MSVehicle* veh) {
    7995              :     // At the moment we only want to consider parking areas - need to check because we could be setting up a manoeuvre
    7996          222 :     if (!veh->hasStops()) {
    7997              :         return (true);
    7998              :     }
    7999              :     MSStop* currentStop = &veh->myStops.front();
    8000          222 :     if (currentStop->parkingarea == nullptr) {
    8001              :         return true;
    8002          220 :     } else if (currentStop->parkingarea->getID() != myManoeuvreStop || MSVehicle::MANOEUVRE_ENTRY != myManoeuvreType) {
    8003           30 :         if (configureEntryManoeuvre(veh)) {
    8004           30 :             MSNet::getInstance()->informVehicleStateListener(veh, MSNet::VehicleState::MANEUVERING);
    8005           30 :             return (false);
    8006              :         } else { // cannot configure entry so stop trying
    8007              :             return true;
    8008              :         }
    8009          190 :     } else if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8010              :         return false;
    8011              :     } else { // manoeuvre complete
    8012           30 :         myManoeuvreType = MSVehicle::MANOEUVRE_NONE;
    8013           30 :         return true;
    8014              :     }
    8015              : }
    8016              : 
    8017              : 
    8018              : bool
    8019            0 : MSVehicle::Manoeuvre::manoeuvreIsComplete(const ManoeuvreType checkType) const {
    8020            0 :     if (checkType != myManoeuvreType) {
    8021              :         return true;    // we're not maneuvering / wrong manoeuvre
    8022              :     }
    8023              : 
    8024            0 :     if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
    8025              :         return false;
    8026              :     } else {
    8027              :         return true;
    8028              :     }
    8029              : }
    8030              : 
    8031              : 
    8032              : bool
    8033         6266 : MSVehicle::Manoeuvre::manoeuvreIsComplete() const {
    8034         6266 :     return (MSNet::getInstance()->getCurrentTimeStep() >= myManoeuvreCompleteTime);
    8035              : }
    8036              : 
    8037              : 
    8038              : bool
    8039         6266 : MSVehicle::manoeuvreIsComplete() const {
    8040         6266 :     return (myManoeuvre.manoeuvreIsComplete());
    8041              : }
    8042              : 
    8043              : 
    8044              : std::pair<double, double>
    8045         7058 : MSVehicle::estimateTimeToNextStop() const {
    8046         7058 :     if (hasStops()) {
    8047         7058 :         MSLane* lane = myLane;
    8048         7058 :         if (lane == nullptr) {
    8049              :             // not in network
    8050           84 :             lane = getEdge()->getLanes()[0];
    8051              :         }
    8052              :         const MSStop& stop = myStops.front();
    8053              :         auto it = myCurrEdge + 1;
    8054              :         // drive to end of current edge
    8055         7058 :         double dist = (lane->getLength() - getPositionOnLane());
    8056         7058 :         double travelTime = lane->getEdge().getMinimumTravelTime(this) * dist / lane->getLength();
    8057              :         // drive until stop edge
    8058         8414 :         while (it != myRoute->end() && it < stop.edge) {
    8059         1356 :             travelTime += (*it)->getMinimumTravelTime(this);
    8060         1356 :             dist += (*it)->getLength();
    8061              :             it++;
    8062              :         }
    8063              :         // drive up to the stop position
    8064         7058 :         const double stopEdgeDist = stop.pars.endPos - (lane == stop.lane ? lane->getLength() : 0);
    8065         7058 :         dist += stopEdgeDist;
    8066         7058 :         travelTime += stop.lane->getEdge().getMinimumTravelTime(this) * (stopEdgeDist / stop.lane->getLength());
    8067              :         // estimate time loss due to acceleration and deceleration
    8068              :         // maximum speed is limited by available distance:
    8069              :         const double a = getCarFollowModel().getMaxAccel();
    8070              :         const double b = getCarFollowModel().getMaxDecel();
    8071         7058 :         const double c = getSpeed();
    8072              :         const double d = dist;
    8073         7058 :         const double len = getVehicleType().getLength();
    8074         7058 :         const double vs = MIN2(MAX2(stop.getSpeed(), 0.0), stop.lane->getVehicleMaxSpeed(this));
    8075              :         // distAccel = (v - c)^2 / (2a)
    8076              :         // distDecel = (v + vs)*(v - vs) / 2b = (v^2 - vs^2) / (2b)
    8077              :         // distAccel + distDecel < d
    8078         7058 :         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))))
    8079        13848 :                                             + pow((a * vs), 2))))) * 0.5) + (c * b)) / (b + a));
    8080         7058 :         it = myCurrEdge;
    8081              :         double v0 = c;
    8082         7058 :         bool v0Stable = getAcceleration() == 0 && v0 > 0;
    8083              :         double timeLossAccel = 0;
    8084              :         double timeLossDecel = 0;
    8085              :         double timeLossLength = 0;
    8086        16848 :         while (it != myRoute->end() && it <= stop.edge) {
    8087         9790 :             double v = MIN2(maxVD, (*it)->getVehicleMaxSpeed(this));
    8088         9790 :             double edgeLength = (it == stop.edge ? stop.pars.endPos : (*it)->getLength()) - (it == myCurrEdge ? getPositionOnLane() : 0);
    8089         9790 :             if (edgeLength <= len && v0Stable && v0 < v) {
    8090              :                 const double lengthDist = MIN2(len, edgeLength);
    8091           20 :                 const double dTL = lengthDist / v0 - lengthDist / v;
    8092              :                 //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " el=" << edgeLength << " lDist=" << lengthDist << " newTLL=" << dTL<< "\n";
    8093           20 :                 timeLossLength += dTL;
    8094              :             }
    8095         9790 :             if (edgeLength > len) {
    8096         8698 :                 const double dv = v - v0;
    8097         8698 :                 if (dv > 0) {
    8098              :                     // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8099         6350 :                     const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8100              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8101         6350 :                     timeLossAccel += dTA;
    8102              :                     // time loss from vehicle length
    8103         2348 :                 } else if (dv < 0) {
    8104              :                     // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8105          540 :                     const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8106              :                     //std::cout << "   e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8107          540 :                     timeLossDecel += dTD;
    8108              :                 }
    8109              :                 v0 = v;
    8110              :                 v0Stable = true;
    8111              :             }
    8112              :             it++;
    8113              :         }
    8114              :         // final deceleration to stop (may also be acceleration or deceleration to waypoint speed)
    8115              :         double v = vs;
    8116         7058 :         const double dv = v - v0;
    8117         7058 :         if (dv > 0) {
    8118              :             // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
    8119          144 :             const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
    8120              :             //std::cout << "  final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
    8121          144 :             timeLossAccel += dTA;
    8122              :             // time loss from vehicle length
    8123         6914 :         } else if (dv < 0) {
    8124              :             // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
    8125         6890 :             const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
    8126              :             //std::cout << "  final  e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
    8127         6890 :             timeLossDecel += dTD;
    8128              :         }
    8129         7058 :         const double result = travelTime + timeLossAccel + timeLossDecel + timeLossLength;
    8130              :         //std::cout << SIMTIME << " v=" << c << " a=" << a << " b=" << b << " maxVD=" << maxVD << " tt=" << travelTime
    8131              :         //    << " ta=" << timeLossAccel << " td=" << timeLossDecel << " tl=" << timeLossLength << " res=" << result << "\n";
    8132         7058 :         return {MAX2(0.0, result), dist};
    8133              :     } else {
    8134            0 :         return {INVALID_DOUBLE, INVALID_DOUBLE};
    8135              :     }
    8136              : }
    8137              : 
    8138              : 
    8139              : double
    8140         1675 : MSVehicle::getStopDelay() const {
    8141         1675 :     if (hasStops() && myStops.front().pars.until >= 0) {
    8142              :         const MSStop& stop = myStops.front();
    8143         1392 :         SUMOTime estimatedDepart = MSNet::getInstance()->getCurrentTimeStep() - DELTA_T;
    8144         1392 :         if (stop.reached) {
    8145          732 :             return STEPS2TIME(estimatedDepart + stop.duration - stop.pars.until);
    8146              :         }
    8147          660 :         if (stop.pars.duration > 0) {
    8148          588 :             estimatedDepart += stop.pars.duration;
    8149              :         }
    8150          660 :         estimatedDepart += TIME2STEPS(estimateTimeToNextStop().first);
    8151          660 :         const double result = MAX2(0.0, STEPS2TIME(estimatedDepart - stop.pars.until));
    8152          660 :         return result;
    8153              :     } else {
    8154              :         // vehicles cannot drive before 'until' so stop delay can never be
    8155              :         // negative and we can use -1 to signal "undefined"
    8156              :         return -1;
    8157              :     }
    8158              : }
    8159              : 
    8160              : 
    8161              : double
    8162         5430 : MSVehicle::getStopArrivalDelay() const {
    8163         5430 :     if (hasStops() && myStops.front().pars.arrival >= 0) {
    8164              :         const MSStop& stop = myStops.front();
    8165         4252 :         if (stop.reached) {
    8166         1304 :             return STEPS2TIME(stop.pars.started - stop.pars.arrival);
    8167              :         } else {
    8168         2948 :             return STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) + estimateTimeToNextStop().first - STEPS2TIME(stop.pars.arrival);
    8169              :         }
    8170              :     } else {
    8171              :         // vehicles can arrival earlier than planned so arrival delay can be negative
    8172              :         return INVALID_DOUBLE;
    8173              :     }
    8174              : }
    8175              : 
    8176              : 
    8177              : const MSEdge*
    8178   3019160903 : MSVehicle::getCurrentEdge() const {
    8179   3019160903 :     return myLane != nullptr ? &myLane->getEdge() : getEdge();
    8180              : }
    8181              : 
    8182              : 
    8183              : const MSEdge*
    8184         3896 : MSVehicle::getNextEdgePtr() const {
    8185         3896 :     if (myLane == nullptr || (myCurrEdge + 1) == myRoute->end()) {
    8186            8 :         return nullptr;
    8187              :     }
    8188         3888 :     if (myLane->isInternal()) {
    8189          568 :         return &myLane->getCanonicalSuccessorLane()->getEdge();
    8190              :     } else {
    8191         3320 :         const MSEdge* nextNormal = succEdge(1);
    8192         3320 :         const MSEdge* nextInternal = myLane->getEdge().getInternalFollowingEdge(nextNormal, getVClass());
    8193         3320 :         return nextInternal ? nextInternal : nextNormal;
    8194              :     }
    8195              : }
    8196              : 
    8197              : 
    8198              : const MSLane*
    8199         1601 : MSVehicle::getPreviousLane(const MSLane* current, int& furtherIndex) const {
    8200         1601 :     if (furtherIndex < (int)myFurtherLanes.size()) {
    8201         1224 :         return myFurtherLanes[furtherIndex++];
    8202              :     } else {
    8203              :         // try to use route information
    8204          377 :         int routeIndex = getRoutePosition();
    8205              :         bool resultInternal;
    8206          377 :         if (MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()) {
    8207            0 :             if (myLane->isInternal()) {
    8208            0 :                 if (furtherIndex % 2 == 0) {
    8209            0 :                     routeIndex -= (furtherIndex + 0) / 2;
    8210              :                     resultInternal = false;
    8211              :                 } else {
    8212            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8213              :                     resultInternal = false;
    8214              :                 }
    8215              :             } else {
    8216            0 :                 if (furtherIndex % 2 != 0) {
    8217            0 :                     routeIndex -= (furtherIndex + 1) / 2;
    8218              :                     resultInternal = false;
    8219              :                 } else {
    8220            0 :                     routeIndex -= (furtherIndex + 2) / 2;
    8221              :                     resultInternal = true;
    8222              :                 }
    8223              :             }
    8224              :         } else {
    8225          377 :             routeIndex -= furtherIndex;
    8226              :             resultInternal = false;
    8227              :         }
    8228          377 :         furtherIndex++;
    8229          377 :         if (routeIndex >= 0) {
    8230          163 :             if (resultInternal) {
    8231            0 :                 const MSEdge* prevNormal = myRoute->getEdges()[routeIndex];
    8232            0 :                 for (MSLane* cand : prevNormal->getLanes()) {
    8233            0 :                     for (MSLink* link : cand->getLinkCont()) {
    8234            0 :                         if (link->getLane() == current) {
    8235            0 :                             if (link->getViaLane() != nullptr) {
    8236              :                                 return link->getViaLane();
    8237              :                             } else {
    8238            0 :                                 return const_cast<MSLane*>(link->getLaneBefore());
    8239              :                             }
    8240              :                         }
    8241              :                     }
    8242              :                 }
    8243              :             } else {
    8244          163 :                 return myRoute->getEdges()[routeIndex]->getLanes()[0];
    8245              :             }
    8246              :         }
    8247              :     }
    8248              :     return current;
    8249              : }
    8250              : 
    8251              : SUMOTime
    8252   1476129827 : MSVehicle::getWaitingTimeFor(const MSLink* link) const {
    8253              :     // this vehicle currently has the highest priority on the allway_stop
    8254   1476129827 :     return link == myHaveStoppedFor ? SUMOTime_MAX : getWaitingTime();
    8255              : }
    8256              : 
    8257              : 
    8258              : void
    8259          655 : MSVehicle::resetApproachOnReroute() {
    8260              :     bool diverged = false;
    8261              :     const ConstMSEdgeVector& route = myRoute->getEdges();
    8262          655 :     int ri = getRoutePosition();
    8263         2890 :     for (const DriveProcessItem& dpi : myLFLinkLanes) {
    8264         2235 :         if (dpi.myLink != nullptr) {
    8265         2232 :             if (!diverged) {
    8266         1999 :                 const MSEdge* next = route[ri + 1];
    8267         1999 :                 if (&dpi.myLink->getLane()->getEdge() != next) {
    8268              :                     diverged = true;
    8269              :                 } else {
    8270         1933 :                     if (dpi.myLink->getViaLane() == nullptr) {
    8271              :                         ri++;
    8272              :                     }
    8273              :                 }
    8274              :             }
    8275              :             if (diverged) {
    8276          299 :                 dpi.myLink->removeApproaching(this);
    8277              :             }
    8278              :         }
    8279              :     }
    8280          655 : }
    8281              : 
    8282              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1