LCOV - code coverage report
Current view: top level - src/microsim/lcmodels - MSLCM_SL2015.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 91.7 % 1395 1279
Test Date: 2025-12-06 15:35:27 Functions: 100.0 % 61 61

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2013-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    MSLCM_SL2015.cpp
      15              : /// @author  Jakob Erdmann
      16              : /// @date    Tue, 06.10.2015
      17              : ///
      18              : // A lane change model for heterogeneous traffic (based on sub-lanes)
      19              : /****************************************************************************/
      20              : #include <config.h>
      21              : 
      22              : #include <iostream>
      23              : #include <utils/common/RandHelper.h>
      24              : #include <utils/common/StringUtils.h>
      25              : #include <microsim/MSEdge.h>
      26              : #include <microsim/MSLane.h>
      27              : #include <microsim/MSLink.h>
      28              : #include <microsim/MSNet.h>
      29              : #include <microsim/MSDriverState.h>
      30              : #include <microsim/MSGlobals.h>
      31              : #include <microsim/MSStop.h>
      32              : #include <microsim/transportables/MSTransportableControl.h>
      33              : #include <microsim/transportables/MSPModel.h>
      34              : #include "MSLCHelper.h"
      35              : #include "MSLCM_SL2015.h"
      36              : 
      37              : // ===========================================================================
      38              : // variable definitions
      39              : // ===========================================================================
      40              : #define MAGIC_OFFSET  1.
      41              : #define LOOK_FORWARD 10.
      42              : 
      43              : #define JAM_FACTOR 1.
      44              : 
      45              : #define LCA_RIGHT_IMPATIENCE -1.
      46              : #define CUT_IN_LEFT_SPEED_THRESHOLD 27.
      47              : #define MAX_ONRAMP_LENGTH 200.
      48              : 
      49              : #define LOOK_AHEAD_MIN_SPEED 0.0
      50              : #define LOOK_AHEAD_SPEED_MEMORY 0.9
      51              : 
      52              : #define HELP_DECEL_FACTOR 1.0
      53              : 
      54              : #define HELP_OVERTAKE  (10.0 / 3.6)
      55              : #define MIN_FALLBEHIND  (7.0 / 3.6)
      56              : 
      57              : #define URGENCY 2.0
      58              : 
      59              : #define KEEP_RIGHT_TIME 5.0 // the number of seconds after which a vehicle should move to the right lane
      60              : 
      61              : #define RELGAIN_NORMALIZATION_MIN_SPEED 10.0
      62              : 
      63              : #define TURN_LANE_DIST 200.0 // the distance at which a lane leading elsewhere is considered to be a turn-lane that must be avoided
      64              : #define GAIN_PERCEPTION_THRESHOLD 0.05 // the minimum relative speed gain which affects the behavior
      65              : 
      66              : #define ARRIVALPOS_LAT_THRESHOLD 100.0
      67              : 
      68              : // the speed at which the desired lateral gap grows now further
      69              : #define LATGAP_SPEED_THRESHOLD (50 / 3.6)
      70              : // the speed at which the desired lateral gap shrinks now further.
      71              : // @note: when setting LATGAP_SPEED_THRESHOLD = LATGAP_SPEED_THRESHOLD2, no speed-specif reduction of minGapLat is done
      72              : #define LATGAP_SPEED_THRESHOLD2 (50 / 3.6)
      73              : 
      74              : // intention to change decays over time
      75              : #define SPEEDGAIN_DECAY_FACTOR 0.5
      76              : // exponential averaging factor for expected sublane speeds
      77              : #define SPEEDGAIN_MEMORY_FACTOR 0.5
      78              : 
      79              : #define REACT_TO_STOPPED_DISTANCE 100
      80              : 
      81              : 
      82              : // ===========================================================================
      83              : // Debug flags
      84              : // ===========================================================================
      85              : //#define DEBUG_MANEUVER
      86              : //#define DEBUG_WANTSCHANGE
      87              : //#define DEBUG_DECISION
      88              : //#define DEBUG_STRATEGIC_CHANGE
      89              : //#define DEBUG_KEEP_LATGAP
      90              : //#define DEBUG_STATE
      91              : //#define DEBUG_ACTIONSTEPS
      92              : //#define DEBUG_COMMITTED_SPEED
      93              : //#define DEBUG_PATCHSPEED
      94              : //#define DEBUG_INFORM
      95              : //#define DEBUG_ROUNDABOUTS
      96              : //#define DEBUG_COOPERATE
      97              : //#define DEBUG_SLOWDOWN
      98              : //#define DEBUG_SAVE_BLOCKER_LENGTH
      99              : //#define DEBUG_BLOCKING
     100              : //#define DEBUG_TRACI
     101              : //#define DEBUG_EXPECTED_SLSPEED
     102              : //#define DEBUG_SLIDING
     103              : //#define DEBUG_COND (myVehicle.getID() == "moped.18" || myVehicle.getID() == "moped.16")
     104              : //#define DEBUG_COND (myVehicle.getID() == "Togliatti_71_0")
     105              : #define DEBUG_COND (myVehicle.isSelected())
     106              : //#define DEBUG_COND (myVehicle.getID() == "pkw150478" || myVehicle.getID() == "pkw150494" || myVehicle.getID() == "pkw150289")
     107              : //#define DEBUG_COND (myVehicle.getID() == "A" || myVehicle.getID() == "B") // fail change to left
     108              : //#define DEBUG_COND (myVehicle.getID() == "disabled") // test stops_overtaking
     109              : //#define DEBUG_COND true
     110              : 
     111              : 
     112              : // ===========================================================================
     113              : // member method definitions
     114              : // ===========================================================================
     115       807565 : MSLCM_SL2015::MSLCM_SL2015(MSVehicle& v) :
     116              :     MSAbstractLaneChangeModel(v, LaneChangeModel::SL2015),
     117       807565 :     mySpeedGainProbabilityRight(0),
     118       807565 :     mySpeedGainProbabilityLeft(0),
     119       807565 :     myKeepRightProbability(0),
     120       807565 :     myLeadingBlockerLength(0),
     121       807565 :     myLeftSpace(0),
     122       807565 :     myLookAheadSpeed(LOOK_AHEAD_MIN_SPEED),
     123       807565 :     myLastEdge(nullptr),
     124       807565 :     myCanChangeFully(true),
     125       807565 :     mySafeLatDistRight(0),
     126       807565 :     mySafeLatDistLeft(0),
     127       807565 :     myStrategicParam(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_STRATEGIC_PARAM, 1)),
     128       807565 :     myCooperativeParam(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_COOPERATIVE_PARAM, 1)),
     129       807565 :     mySpeedGainParam(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_SPEEDGAIN_PARAM, 1)),
     130       807565 :     myKeepRightParam(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_KEEPRIGHT_PARAM, 1)),
     131       807565 :     myOppositeParam(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_OPPOSITE_PARAM, 1)),
     132       807565 :     mySublaneParam(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_SUBLANE_PARAM, 1)),
     133              :     // by default use SUMO_ATTR_LCA_PUSHY. If that is not set, try SUMO_ATTR_LCA_PUSHYGAP
     134       807565 :     myMinGapLat(v.getVehicleType().getMinGapLat()),
     135       807565 :     myPushy(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_PUSHY,
     136      1615033 :             1 - (v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_PUSHYGAP,
     137       807565 :                     MAX2(NUMERICAL_EPS, myMinGapLat)) /
     138       807565 :                  MAX2(NUMERICAL_EPS, myMinGapLat)))),
     139       807565 :     myImpatience(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_IMPATIENCE, 0)),
     140       807565 :     myMinImpatience(myImpatience),
     141       807565 :     myTimeToImpatience(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_TIME_TO_IMPATIENCE, std::numeric_limits<double>::max())),
     142       807565 :     myAccelLat(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_ACCEL_LAT, 1.0)),
     143       807565 :     myTurnAlignmentDist(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_TURN_ALIGNMENT_DISTANCE, 0.0)),
     144       807565 :     myLookaheadLeft(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_LOOKAHEADLEFT, 2.0)),
     145       807565 :     mySpeedGainRight(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_SPEEDGAINRIGHT, 0.1)),
     146       807565 :     myLaneDiscipline(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_LANE_DISCIPLINE, 0.0)),
     147       807565 :     mySpeedGainLookahead(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_SPEEDGAIN_LOOKAHEAD, 5)),
     148       807565 :     mySpeedGainRemainTime(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_SPEEDGAIN_REMAIN_TIME, 20)),
     149       807565 :     myRoundaboutBonus(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_COOPERATIVE_ROUNDABOUT, myCooperativeParam)),
     150       807565 :     myCooperativeSpeed(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_COOPERATIVE_SPEED, myCooperativeParam)),
     151       807565 :     myKeepRightAcceptanceTime(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_KEEPRIGHT_ACCEPTANCE_TIME, -1)),
     152       807565 :     myOvertakeDeltaSpeedFactor(v.getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_OVERTAKE_DELTASPEED_FACTOR, 0)),
     153       807565 :     mySigmaState(0) {
     154       807565 :     initDerivedParameters();
     155       807565 : }
     156              : 
     157      1615114 : MSLCM_SL2015::~MSLCM_SL2015() {
     158       807557 :     changed();
     159      1615114 : }
     160              : 
     161              : 
     162              : void
     163      1085857 : MSLCM_SL2015::initDerivedParameters() {
     164      1085857 :     if (mySpeedGainParam <= 0) {
     165         2235 :         myChangeProbThresholdRight = std::numeric_limits<double>::max();
     166         2235 :         myChangeProbThresholdLeft = std::numeric_limits<double>::max();
     167              :     } else {
     168      1083622 :         myChangeProbThresholdRight = (0.2 / mySpeedGainRight) / mySpeedGainParam;
     169      1083622 :         myChangeProbThresholdLeft = 0.2 / mySpeedGainParam;
     170              :     }
     171      1085857 :     mySpeedLossProbThreshold = (-0.1 + (1 - mySublaneParam));
     172      1085857 : }
     173              : 
     174              : 
     175              : bool
     176        15254 : MSLCM_SL2015::debugVehicle() const {
     177        15254 :     return DEBUG_COND;
     178              : }
     179              : 
     180              : 
     181              : int
     182    115562710 : MSLCM_SL2015::wantsChangeSublane(
     183              :     int laneOffset,
     184              :     LaneChangeAction alternatives,
     185              :     const MSLeaderDistanceInfo& leaders,
     186              :     const MSLeaderDistanceInfo& followers,
     187              :     const MSLeaderDistanceInfo& blockers,
     188              :     const MSLeaderDistanceInfo& neighLeaders,
     189              :     const MSLeaderDistanceInfo& neighFollowers,
     190              :     const MSLeaderDistanceInfo& neighBlockers,
     191              :     const MSLane& neighLane,
     192              :     const std::vector<MSVehicle::LaneQ>& preb,
     193              :     MSVehicle** lastBlocked,
     194              :     MSVehicle** firstBlocked,
     195              :     double& latDist, double& maneuverDist, int& blocked) {
     196              : 
     197    115562710 :     gDebugFlag2 = DEBUG_COND;
     198    195580008 :     const std::string changeType = laneOffset == -1 ? "right" : (laneOffset == 1 ? "left" : "current");
     199              : 
     200              : #ifdef DEBUG_MANEUVER
     201              :     if (gDebugFlag2) {
     202              :         std::cout << "\n" << SIMTIME
     203              :                   << std::setprecision(gPrecision)
     204              :                   << " veh=" << myVehicle.getID()
     205              :                   << " lane=" << myVehicle.getLane()->getID()
     206              :                   << " neigh=" << neighLane.getID()
     207              :                   << " pos=" << myVehicle.getPositionOnLane()
     208              :                   << " posLat=" << myVehicle.getLateralPositionOnLane()
     209              :                   << " posLatError=" << mySigmaState
     210              :                   << " speed=" << myVehicle.getSpeed()
     211              :                   << " considerChangeTo=" << changeType
     212              :                   << "\n";
     213              :     }
     214              : #endif
     215              : 
     216    115562710 :     int result = _wantsChangeSublane(laneOffset,
     217              :                                      alternatives,
     218              :                                      leaders, followers, blockers,
     219              :                                      neighLeaders, neighFollowers, neighBlockers,
     220              :                                      neighLane, preb,
     221              :                                      lastBlocked, firstBlocked, latDist, maneuverDist, blocked);
     222              : 
     223    115562710 :     result = keepLatGap(result, leaders, followers, blockers,
     224              :                         neighLeaders, neighFollowers, neighBlockers,
     225              :                         neighLane, laneOffset, latDist, maneuverDist, blocked);
     226              : 
     227    115562710 :     result |= getLCA(result, latDist);
     228              :     // take into account lateral acceleration
     229              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_STATE)
     230              :     double latDistTmp = latDist;
     231              : #endif
     232    115562710 :     latDist = SPEED2DIST(computeSpeedLat(latDist, maneuverDist, (result & LCA_URGENT) != 0));
     233              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_STATE)
     234              :     if (gDebugFlag2 && latDist != latDistTmp) {
     235              :         std::cout << SIMTIME << " veh=" << myVehicle.getID() << " maneuverDist=" << maneuverDist << " latDist=" << latDistTmp << " mySpeedPrev=" << mySpeedLat << " speedLat=" << DIST2SPEED(latDist) << " latDist2=" << latDist << "\n";
     236              :     }
     237              : 
     238              :     if (gDebugFlag2) {
     239              :         if (result & LCA_WANTS_LANECHANGE) {
     240              :             std::cout << SIMTIME
     241              :                       << " veh=" << myVehicle.getID()
     242              :                       << " wantsChangeTo=" << changeType
     243              :                       << " latDist=" << latDist
     244              :                       << " maneuverDist=" << maneuverDist
     245              :                       << " state=" << toString((LaneChangeAction)result)
     246              :                       << ((blocked & LCA_BLOCKED) ? " (blocked)" : "")
     247              :                       << ((blocked & LCA_OVERLAPPING) ? " (overlap)" : "")
     248              :                       << "\n\n";
     249              :         } else {
     250              :             std::cout << SIMTIME
     251              :                       << " veh=" << myVehicle.getID()
     252              :                       << " wantsNoChangeTo=" << changeType
     253              :                       << " state=" << toString((LaneChangeAction)result)
     254              :                       << "\n\n";
     255              :         }
     256              :     }
     257              : #endif
     258    115562710 :     gDebugFlag2 = false;
     259    115562710 :     return result;
     260              : }
     261              : 
     262              : void
     263     80077588 : MSLCM_SL2015::setOwnState(const int state) {
     264     80077588 :     MSAbstractLaneChangeModel::setOwnState(state);
     265     80077588 :     if (myVehicle.isActive()) {
     266     80077568 :         if ((state & (LCA_STRATEGIC | LCA_SPEEDGAIN)) != 0 && (state & LCA_BLOCKED) != 0) {
     267      7915915 :             myImpatience = MIN2(1.0, myImpatience + myVehicle.getActionStepLengthSecs() / myTimeToImpatience);
     268              :         } else {
     269              :             // impatience decays only to the driver-specific level
     270     79084709 :             myImpatience = MAX2(myMinImpatience, myImpatience - myVehicle.getActionStepLengthSecs() / myTimeToImpatience);
     271              :         }
     272              : #ifdef DEBUG_STATE
     273              :         if (DEBUG_COND) {
     274              :             std::cout << SIMTIME << " veh=" << myVehicle.getID()
     275              :                       << " setOwnState=" << toString((LaneChangeAction)state)
     276              :                       << " myMinImpatience=" << myMinImpatience
     277              :                       << " myImpatience=" << myImpatience
     278              :                       << "\n";
     279              :         }
     280              : #endif
     281     80077568 :         if ((state & LCA_STAY) != 0) {
     282     70054755 :             myCanChangeFully = true;
     283              : //            if (DEBUG_COND) {
     284              : //                std::cout << "    myCanChangeFully=true\n";
     285              : //            }
     286              :         }
     287              :     }
     288     80077588 : }
     289              : 
     290              : 
     291              : void
     292      3953211 : MSLCM_SL2015::updateSafeLatDist(const double travelledLatDist) {
     293      3953211 :     mySafeLatDistLeft -= travelledLatDist;
     294      3953211 :     mySafeLatDistRight += travelledLatDist;
     295              : 
     296      3953211 :     if (fabs(mySafeLatDistLeft) < NUMERICAL_EPS) {
     297        54667 :         mySafeLatDistLeft = 0.;
     298              :     }
     299      3953211 :     if (fabs(mySafeLatDistRight) < NUMERICAL_EPS) {
     300        91690 :         mySafeLatDistRight = 0.;
     301              :     }
     302      3953211 : }
     303              : 
     304              : 
     305              : double
     306     81409918 : MSLCM_SL2015::patchSpeed(const double min, const double wanted, const double max, const MSCFModel& cfModel) {
     307     81409918 :     gDebugFlag2 = DEBUG_COND;
     308              :     // negative min speed may be passed when using ballistic updated
     309     81409918 :     const double newSpeed = _patchSpeed(MAX2(min, 0.0), wanted, max, cfModel);
     310              : #ifdef DEBUG_PATCHSPEED
     311              :     if (gDebugFlag2) {
     312              :         const std::string patched = (wanted != newSpeed ? " patched=" + toString(newSpeed) : "");
     313              :         std::cout << SIMTIME
     314              :                   << " veh=" << myVehicle.getID()
     315              :                   << " lane=" << myVehicle.getLane()->getID()
     316              :                   << " pos=" << myVehicle.getPositionOnLane()
     317              :                   << " v=" << myVehicle.getSpeed()
     318              :                   << " min=" << min
     319              :                   << " wanted=" << wanted
     320              :                   << " max=" << max
     321              :                   << patched
     322              :                   << "\n\n";
     323              :     }
     324              : #endif
     325     81409918 :     gDebugFlag2 = false;
     326     81409918 :     return newSpeed;
     327              : }
     328              : 
     329              : 
     330              : double
     331     81409918 : MSLCM_SL2015::_patchSpeed(double min, const double wanted, double max, const MSCFModel& cfModel) {
     332     81409918 :     if (wanted <= 0) {
     333              :         return wanted;
     334              :     }
     335              : 
     336     77495576 :     int state = myOwnState;
     337              : 
     338              :     double nVSafe = wanted;
     339              :     bool gotOne = false;
     340              :     // letting vehicles merge in at the end of the lane in case of counter-lane change, step#2
     341              :     //   if we want to change and have a blocking leader and there is enough room for him in front of us
     342     77495576 :     if (myLeadingBlockerLength != 0) {
     343       343535 :         double space = myLeftSpace - myLeadingBlockerLength - MAGIC_OFFSET - myVehicle.getVehicleType().getMinGap();
     344              : #ifdef DEBUG_PATCHSPEED
     345              :         if (gDebugFlag2) {
     346              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " myLeadingBlockerLength=" << myLeadingBlockerLength << " space=" << space << "\n";
     347              :         }
     348              : #endif
     349       343535 :         if (space >= 0) { // XXX space > -MAGIC_OFFSET
     350              :             // compute speed for decelerating towards a place which allows the blocking leader to merge in in front
     351       339587 :             double safe = cfModel.stopSpeed(&myVehicle, myVehicle.getSpeed(), space, MSCFModel::CalcReason::LANE_CHANGE);
     352              :             max = MIN2(max, safe);
     353              :             // if we are approaching this place
     354       339587 :             if (safe < wanted) {
     355        52631 :                 if (safe < min) {
     356         4024 :                     const double vMinEmergency = myVehicle.getCarFollowModel().minNextSpeedEmergency(myVehicle.getSpeed(), &myVehicle);
     357         4024 :                     if (safe >= vMinEmergency) {
     358              :                         // permit harder braking if needed and helpful
     359              :                         min = MAX2(vMinEmergency, safe);
     360              :                     }
     361              :                 }
     362              : #ifdef DEBUG_PATCHSPEED
     363              :                 if (gDebugFlag2) {
     364              :                     std::cout << SIMTIME << " veh=" << myVehicle.getID() << " slowing down for leading blocker, safe=" << safe << (safe + NUMERICAL_EPS < min ? " (not enough)" : "") << "\n";
     365              :                 }
     366              : #endif
     367              :                 nVSafe = MAX2(min, safe);
     368              :                 gotOne = true;
     369              :             }
     370              :         }
     371              :     }
     372     77495576 :     const double coopWeight = MAX2(0.0, MIN2(1.0, myCooperativeSpeed));
     373     99396305 :     for (auto i : myLCAccelerationAdvices) {
     374              :         double accel = i.first;
     375     21900729 :         double v = myVehicle.getSpeed() + ACCEL2SPEED(accel);
     376     21900729 :         if (v >= min && v <= max) {
     377      7198407 :             if (i.second) {
     378              :                 // own advice, no scaling needed
     379              :                 nVSafe = MIN2(v, nVSafe);
     380              :             } else {
     381      3327228 :                 nVSafe = MIN2(v * coopWeight + (1 - coopWeight) * wanted, nVSafe);
     382              :             }
     383              :             gotOne = true;
     384              : #ifdef DEBUG_PATCHSPEED
     385              :             if (gDebugFlag2) {
     386              :                 std::cout << SIMTIME << " veh=" << myVehicle.getID() << " got accel=" << accel << " nVSafe=" << nVSafe << "\n";
     387              :             }
     388              : #endif
     389              :         } else {
     390              : #ifdef DEBUG_PATCHSPEED
     391              :             if (v < min) {
     392              :                 if (gDebugFlag2) {
     393              :                     std::cout << SIMTIME << " veh=" << myVehicle.getID() << " ignoring low nVSafe=" << v << " (accel=" << accel << ") min=" << min << "\n";
     394              :                 }
     395              :             } else {
     396              :                 if (gDebugFlag2) {
     397              :                     std::cout << SIMTIME << " veh=" << myVehicle.getID() << " ignoring high nVSafe=" << v << " (accel=" << accel << ") max=" << max << "\n";
     398              :                 }
     399              :             }
     400              : #endif
     401              :         }
     402              :     }
     403              : 
     404     77495576 :     if (gotOne && !myDontBrake) {
     405              : #ifdef DEBUG_PATCHSPEED
     406              :         if (gDebugFlag2) {
     407              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " got vSafe\n";
     408              :         }
     409              : #endif
     410              :         return nVSafe;
     411              :     }
     412              : 
     413              :     // check whether the vehicle is blocked
     414     75517822 :     if ((state & LCA_WANTS_LANECHANGE) != 0 && (state & LCA_BLOCKED) != 0) {
     415      4878661 :         if ((state & LCA_STRATEGIC) != 0) {
     416              :             // necessary decelerations are controlled via vSafe. If there are
     417              :             // none it means we should speed up
     418              : #if defined(DEBUG_PATCHSPEED) || defined(DEBUG_STATE)
     419              :             if (gDebugFlag2) {
     420              :                 std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_WANTS_LANECHANGE (strat, no vSafe)\n";
     421              :             }
     422              : #endif
     423       505514 :             return (max + wanted) / 2.0;
     424      4373147 :         } else if ((state & LCA_COOPERATIVE) != 0) {
     425              :             // only minor adjustments in speed should be done
     426       412631 :             if ((state & LCA_BLOCKED_BY_LEADER) != 0) {
     427              : #if defined(DEBUG_PATCHSPEED) || defined(DEBUG_STATE)
     428              :                 if (gDebugFlag2) {
     429              :                     std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_BLOCKED_BY_LEADER (coop)\n";
     430              :                 }
     431              : #endif
     432       377314 :                 return (min + wanted) / 2.0;
     433              :             }
     434        35317 :             if ((state & LCA_BLOCKED_BY_FOLLOWER) != 0) {
     435              : #if defined(DEBUG_PATCHSPEED) || defined(DEBUG_STATE)
     436              :                 if (gDebugFlag2) {
     437              :                     std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_BLOCKED_BY_FOLLOWER (coop)\n";
     438              :                 }
     439              : #endif
     440        35317 :                 return (max + wanted) / 2.0;
     441              :             }
     442              :             //} else { // VARIANT_16
     443              :             //    // only accelerations should be performed
     444              :             //    if ((state & LCA_BLOCKED_BY_FOLLOWER) != 0) {
     445              :             //        if (gDebugFlag2) std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_BLOCKED_BY_FOLLOWER\n";
     446              :             //        return (max + wanted) / 2.0;
     447              :             //    }
     448              :         }
     449              :     }
     450              : 
     451              :     /*
     452              :     // decelerate if being a blocking follower
     453              :     //  (and does not have to change lanes)
     454              :     if ((state & LCA_AMBLOCKINGFOLLOWER) != 0) {
     455              :         if (fabs(max - myVehicle.getCarFollowModel().maxNextSpeed(myVehicle.getSpeed(), &myVehicle)) < 0.001 && min == 0) { // !!! was standing
     456              :             if (gDebugFlag2) std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_AMBLOCKINGFOLLOWER (standing)\n";
     457              :             return 0;
     458              :         }
     459              :         if (gDebugFlag2) std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_AMBLOCKINGFOLLOWER\n";
     460              : 
     461              :         //return min; // VARIANT_3 (brakeStrong)
     462              :         return (min + wanted) / 2.0;
     463              :     }
     464              :     if ((state & LCA_AMBACKBLOCKER) != 0) {
     465              :         if (max <= myVehicle.getCarFollowModel().maxNextSpeed(myVehicle.getSpeed(), &myVehicle) && min == 0) { // !!! was standing
     466              :             if (gDebugFlag2) std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_AMBACKBLOCKER (standing)\n";
     467              :             //return min; VARIANT_9 (backBlockVSafe)
     468              :             return nVSafe;
     469              :         }
     470              :     }
     471              :     if ((state & LCA_AMBACKBLOCKER_STANDING) != 0) {
     472              :         if (gDebugFlag2) std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_AMBACKBLOCKER_STANDING\n";
     473              :         //return min;
     474              :         return nVSafe;
     475              :     }
     476              :     */
     477              : 
     478              :     // accelerate if being a blocking leader or blocking follower not able to brake
     479              :     //  (and does not have to change lanes)
     480     74599677 :     if ((state & LCA_AMBLOCKINGLEADER) != 0) {
     481              : #if defined(DEBUG_PATCHSPEED) || defined(DEBUG_STATE)
     482              :         if (gDebugFlag2) {
     483              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_AMBLOCKINGLEADER\n";
     484              :         }
     485              : #endif
     486       779096 :         return (max + wanted) / 2.0;
     487              :     }
     488              : 
     489              :     if ((state & LCA_AMBLOCKINGFOLLOWER_DONTBRAKE) != 0) {
     490              : #if defined(DEBUG_PATCHSPEED) || defined(DEBUG_STATE)
     491              :         if (gDebugFlag2) {
     492              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " LCA_AMBLOCKINGFOLLOWER_DONTBRAKE\n";
     493              :         }
     494              : #endif
     495              :         /*
     496              :         // VARIANT_4 (dontbrake)
     497              :         if (max <= myVehicle.getCarFollowModel().maxNextSpeed(myVehicle.getSpeed(), &myVehicle) && min == 0) { // !!! was standing
     498              :             return wanted;
     499              :         }
     500              :         return (min + wanted) / 2.0;
     501              :         */
     502              :     }
     503              :     return wanted;
     504              : }
     505              : 
     506              : 
     507              : void*
     508      9739453 : MSLCM_SL2015::inform(void* info, MSVehicle* sender) {
     509              :     Info* pinfo = (Info*) info;
     510      9739453 :     if (pinfo->first >= 0) {
     511      6112219 :         addLCSpeedAdvice(pinfo->first, false);
     512              :     }
     513              :     //myOwnState &= 0xffffffff; // reset all bits of MyLCAEnum but only those
     514      9739453 :     myOwnState |= pinfo->second;
     515              : #ifdef DEBUG_INFORM
     516              :     if (gDebugFlag2 || DEBUG_COND || sender->getLaneChangeModel().debugVehicle()) {
     517              :         std::cout << SIMTIME
     518              :                   << " veh=" << myVehicle.getID()
     519              :                   << " informedBy=" << sender->getID()
     520              :                   << " info=" << pinfo->second
     521              :                   << " vSafe=" << pinfo->first
     522              :                   << "\n";
     523              :     }
     524              : #else
     525              :     UNUSED_PARAMETER(sender);
     526              : #endif
     527      9739453 :     delete pinfo;
     528      9739453 :     return (void*) true;
     529              : }
     530              : 
     531              : 
     532              : void
     533      9739453 : MSLCM_SL2015::msg(const CLeaderDist& cld, double speed, int state) {
     534              :     assert(cld.first != 0);
     535      9739453 :     ((MSVehicle*)cld.first)->getLaneChangeModel().inform(new Info(speed, state), &myVehicle);
     536      9739453 : }
     537              : 
     538              : 
     539              : double
     540      6242858 : MSLCM_SL2015::informLeader(int blocked,
     541              :                            int dir,
     542              :                            const CLeaderDist& neighLead,
     543              :                            double remainingSeconds) {
     544     12485716 :     double plannedSpeed = MIN2(myVehicle.getSpeed(),
     545      6242858 :                                myVehicle.getCarFollowModel().stopSpeed(&myVehicle, myVehicle.getSpeed(), myLeftSpace - myLeadingBlockerLength));
     546     16568029 :     for (auto i : myLCAccelerationAdvices) {
     547     10325171 :         double v = myVehicle.getSpeed() + ACCEL2SPEED(i.first);
     548     10325171 :         if (v >= myVehicle.getSpeed() - ACCEL2SPEED(myVehicle.getCarFollowModel().getMaxDecel())) {
     549              :             plannedSpeed = MIN2(plannedSpeed, v);
     550              :         }
     551              :     }
     552              : #ifdef DEBUG_INFORM
     553              :     if (gDebugFlag2) {
     554              :         std::cout << " informLeader speed=" <<  myVehicle.getSpeed() << " planned=" << plannedSpeed << "\n";
     555              :     }
     556              : #endif
     557              : 
     558      6242858 :     if ((blocked & LCA_BLOCKED_BY_LEADER) != 0 && neighLead.first != 0) {
     559              :         const MSVehicle* nv = neighLead.first;
     560      5143799 :         if (MSLCHelper::divergentRoute(myVehicle, *nv)) {
     561              :             //std::cout << SIMTIME << " ego=" << myVehicle.getID() << " ignoresDivergentBlockingLeader=" << nv->getID() << "\n";
     562              :             return plannedSpeed;
     563              :         }
     564              : #ifdef DEBUG_INFORM
     565              :         if (gDebugFlag2) std::cout << " blocked by leader nv=" <<  nv->getID() << " nvSpeed=" << nv->getSpeed() << " needGap="
     566              :                                        << myVehicle.getCarFollowModel().getSecureGap(&myVehicle, nv, myVehicle.getSpeed(), nv->getSpeed(), nv->getCarFollowModel().getMaxDecel()) << "\n";
     567              : #endif
     568              :         // decide whether we want to overtake the leader or follow it
     569      5139453 :         const double dv = plannedSpeed - nv->getSpeed();
     570      5139453 :         const double overtakeDist = (neighLead.second // drive to back of follower
     571      5139453 :                                      + nv->getVehicleType().getLengthWithGap() // drive to front of follower
     572      5139453 :                                      + myVehicle.getVehicleType().getLength() // ego back reaches follower front
     573     15418359 :                                      + nv->getCarFollowModel().getSecureGap( // save gap to follower
     574      5139453 :                                          nv, &myVehicle, nv->getSpeed(), myVehicle.getSpeed(), myVehicle.getCarFollowModel().getMaxDecel()));
     575              : 
     576      5139453 :         if ((dv < myOvertakeDeltaSpeedFactor * myVehicle.getLane()->getSpeedLimit() + NUMERICAL_EPS
     577              :                 // overtaking on the right on an uncongested highway is forbidden (noOvertakeLCLeft)
     578      1893631 :                 || (dir == LCA_MLEFT && !myVehicle.congested() && !myAllowOvertakingRight)
     579              :                 // not enough space to overtake? (we will start to brake when approaching a dead end)
     580      3760432 :                 || myLeftSpace - myLeadingBlockerLength - myVehicle.getCarFollowModel().brakeGap(myVehicle.getSpeed()) < overtakeDist
     581              :                 // not enough time to overtake?
     582      1748265 :                 || dv * remainingSeconds < overtakeDist)
     583      5523218 :                 && (!neighLead.first->isStopped() || (isOpposite() && neighLead.second >= 0))) {
     584              :             // cannot overtake
     585      3625043 :             msg(neighLead, -1, dir | LCA_AMBLOCKINGLEADER);
     586              :             // slow down smoothly to follow leader
     587      3625043 :             const double targetSpeed = getCarFollowModel().followSpeed(
     588      3625043 :                                            &myVehicle, myVehicle.getSpeed(), neighLead.second, nv->getSpeed(), nv->getCarFollowModel().getMaxDecel());
     589      3625043 :             if (targetSpeed < myVehicle.getSpeed()) {
     590              :                 // slow down smoothly to follow leader
     591       905011 :                 const double decel = ACCEL2SPEED(MIN2(myVehicle.getCarFollowModel().getMaxDecel(),
     592              :                                                       MAX2(MIN_FALLBEHIND, (myVehicle.getSpeed() - targetSpeed) / remainingSeconds)));
     593              :                 //const double nextSpeed = MAX2(0., MIN2(plannedSpeed, myVehicle.getSpeed() - decel));
     594       677765 :                 const double nextSpeed = MIN2(plannedSpeed, MAX2(0.0, myVehicle.getSpeed() - decel));
     595              : #ifdef DEBUG_INFORM
     596              :                 if (gDebugFlag2) {
     597              :                     std::cout << SIMTIME
     598              :                               << " cannot overtake leader nv=" << nv->getID()
     599              :                               << " dv=" << dv
     600              :                               << " remainingSeconds=" << remainingSeconds
     601              :                               << " targetSpeed=" << targetSpeed
     602              :                               << " nextSpeed=" << nextSpeed
     603              :                               << "\n";
     604              :                 }
     605              : #endif
     606       677765 :                 addLCSpeedAdvice(nextSpeed);
     607       677765 :                 return nextSpeed;
     608              :             } else {
     609              :                 // leader is fast enough anyway
     610              : #ifdef DEBUG_INFORM
     611              :                 if (gDebugFlag2) {
     612              :                     std::cout << SIMTIME
     613              :                               << " cannot overtake fast leader nv=" << nv->getID()
     614              :                               << " dv=" << dv
     615              :                               << " remainingSeconds=" << remainingSeconds
     616              :                               << " targetSpeed=" << targetSpeed
     617              :                               << "\n";
     618              :                 }
     619              : #endif
     620      2947278 :                 addLCSpeedAdvice(targetSpeed);
     621      2947278 :                 return plannedSpeed;
     622              :             }
     623              :         } else {
     624              : #ifdef DEBUG_INFORM
     625              :             if (gDebugFlag2) {
     626              :                 std::cout << SIMTIME
     627              :                           << " wants to overtake leader nv=" << nv->getID()
     628              :                           << " dv=" << dv
     629              :                           << " remainingSeconds=" << remainingSeconds
     630              :                           << " currentGap=" << neighLead.second
     631              :                           << " secureGap=" << nv->getCarFollowModel().getSecureGap(nv, &myVehicle, nv->getSpeed(), myVehicle.getSpeed(), myVehicle.getCarFollowModel().getMaxDecel())
     632              :                           << " overtakeDist=" << overtakeDist
     633              :                           << " leftSpace=" << myLeftSpace
     634              :                           << " blockerLength=" << myLeadingBlockerLength
     635              :                           << "\n";
     636              :             }
     637              : #endif
     638              :             // overtaking, leader should not accelerate
     639      1514410 :             msg(neighLead, nv->getSpeed(), dir | LCA_AMBLOCKINGLEADER);
     640      1514410 :             return -1;
     641              :         }
     642      1099059 :     } else if (neighLead.first != 0) { // (remainUnblocked)
     643              :         // we are not blocked now. make sure we stay far enough from the leader
     644              :         const MSVehicle* nv = neighLead.first;
     645              :         double dv, nextNVSpeed;
     646      1099059 :         if (MSGlobals::gSemiImplicitEulerUpdate) {
     647              :             // XXX: the decrement (HELP_OVERTAKE) should be scaled with timestep length, I think.
     648              :             //      It seems to function as an estimate nv's speed in the next simstep!? (so HELP_OVERTAKE should be an acceleration value.)
     649       915020 :             nextNVSpeed = nv->getSpeed() - HELP_OVERTAKE; // conservative
     650       915020 :             dv = SPEED2DIST(myVehicle.getSpeed() - nextNVSpeed);
     651              :         } else {
     652              :             // Estimate neigh's speed after actionstep length
     653              :             // @note The possible breaking can be underestimated by the formula, so this is a potential
     654              :             //       source of collisions if actionsteplength>simsteplength.
     655              :             const double nvMaxDecel = HELP_OVERTAKE;
     656       184039 :             nextNVSpeed = nv->getSpeed() - nvMaxDecel * myVehicle.getActionStepLengthSecs(); // conservative
     657              :             // Estimated gap reduction until next action step if own speed stays constant
     658       184039 :             dv = SPEED2DIST(myVehicle.getSpeed() - nextNVSpeed);
     659              :         }
     660      1099059 :         const double targetSpeed = getCarFollowModel().followSpeed(
     661      1099059 :                                        &myVehicle, myVehicle.getSpeed(), neighLead.second - dv, nextNVSpeed, nv->getCarFollowModel().getMaxDecel());
     662      1099059 :         addLCSpeedAdvice(targetSpeed);
     663              : #ifdef DEBUG_INFORM
     664              :         if (gDebugFlag2) {
     665              :             std::cout << " not blocked by leader nv=" <<  nv->getID()
     666              :                       << " nvSpeed=" << nv->getSpeed()
     667              :                       << " gap=" << neighLead.second
     668              :                       << " nextGap=" << neighLead.second - dv
     669              :                       << " needGap=" << myVehicle.getCarFollowModel().getSecureGap(&myVehicle, nv, myVehicle.getSpeed(), nv->getSpeed(), nv->getCarFollowModel().getMaxDecel())
     670              :                       << " targetSpeed=" << targetSpeed
     671              :                       << "\n";
     672              :         }
     673              : #endif
     674              :         return MIN2(targetSpeed, plannedSpeed);
     675              :     } else {
     676              :         // not overtaking
     677              :         return plannedSpeed;
     678              :     }
     679              : }
     680              : 
     681              : 
     682              : void
     683      4600272 : MSLCM_SL2015::informFollower(int blocked,
     684              :                              int dir,
     685              :                              const CLeaderDist& neighFollow,
     686              :                              double remainingSeconds,
     687              :                              double plannedSpeed) {
     688      4600272 :     if ((blocked & LCA_BLOCKED_BY_FOLLOWER) != 0 && neighFollow.first != 0) {
     689              :         const MSVehicle* nv = neighFollow.first;
     690      3315333 :         if (MSLCHelper::divergentRoute(myVehicle, *nv)) {
     691              :             //std::cout << SIMTIME << " ego=" << myVehicle.getID() << " ignoresDivergentBlockingFollower=" << nv->getID() << "\n";
     692              :             return;
     693              :         }
     694              : #ifdef DEBUG_INFORM
     695              :         if (gDebugFlag2) std::cout << " blocked by follower nv=" <<  nv->getID() << " nvSpeed=" << nv->getSpeed() << " needGap="
     696              :                                        << nv->getCarFollowModel().getSecureGap(nv, &myVehicle, nv->getSpeed(), myVehicle.getSpeed(), myVehicle.getCarFollowModel().getMaxDecel()) << "\n";
     697              : #endif
     698              : 
     699              :         // are we fast enough to cut in without any help?
     700      3315061 :         if (plannedSpeed - nv->getSpeed() >= HELP_OVERTAKE) {
     701       188618 :             const double neededGap = nv->getCarFollowModel().getSecureGap(nv, &myVehicle, nv->getSpeed(), plannedSpeed, myVehicle.getCarFollowModel().getMaxDecel());
     702       188618 :             if ((neededGap - neighFollow.second) / remainingSeconds < (plannedSpeed - nv->getSpeed())) {
     703              : #ifdef DEBUG_INFORM
     704              :                 if (gDebugFlag2) {
     705              :                     std::cout << " wants to cut in before  nv=" << nv->getID() << " without any help neededGap=" << neededGap << "\n";
     706              :                 }
     707              : #endif
     708              :                 // follower might even accelerate but not to much
     709       168561 :                 msg(neighFollow, plannedSpeed - HELP_OVERTAKE, dir | LCA_AMBLOCKINGFOLLOWER);
     710       168561 :                 return;
     711              :             }
     712              :         }
     713              :         // decide whether we will request help to cut in before the follower or allow to be overtaken
     714              : 
     715              :         // PARAMETERS
     716              :         // assume other vehicle will assume the equivalent of 1 second of
     717              :         // maximum deceleration to help us (will probably be spread over
     718              :         // multiple seconds)
     719              :         // -----------
     720              :         const double helpDecel = nv->getCarFollowModel().getMaxDecel() * HELP_DECEL_FACTOR ;
     721              : 
     722              :         // change in the gap between ego and blocker over 1 second (not STEP!)
     723      3146500 :         const double neighNewSpeed = MAX2(0., nv->getSpeed() - ACCEL2SPEED(helpDecel));
     724      3146500 :         const double neighNewSpeed1s = MAX2(0., nv->getSpeed() - helpDecel);
     725      3146500 :         const double dv = plannedSpeed - neighNewSpeed1s;
     726              :         // new gap between follower and self in case the follower does brake for 1s
     727      3146500 :         const double decelGap = neighFollow.second + dv;
     728      3146500 :         const double secureGap = nv->getCarFollowModel().getSecureGap(nv, &myVehicle, neighNewSpeed1s, plannedSpeed, myVehicle.getCarFollowModel().getMaxDecel());
     729              : #ifdef DEBUG_INFORM
     730              :         if (gDebugFlag2) {
     731              :             std::cout << SIMTIME
     732              :                       << " egoV=" << myVehicle.getSpeed()
     733              :                       << " egoNV=" << plannedSpeed
     734              :                       << " nvNewSpeed=" << neighNewSpeed
     735              :                       << " nvNewSpeed1s=" << neighNewSpeed1s
     736              :                       << " deltaGap=" << dv
     737              :                       << " decelGap=" << decelGap
     738              :                       << " secGap=" << secureGap
     739              :                       << "\n";
     740              :         }
     741              : #endif
     742      3146500 :         if (decelGap > 0 && decelGap >= secureGap) {
     743              :             // if the blocking neighbor brakes it could actually help
     744              :             // how hard does it actually need to be?
     745              :             // to be safe in the next step the following equation has to hold:
     746              :             //   vsafe <= followSpeed(gap=currentGap - SPEED2DIST(vsafe), ...)
     747              :             // we compute an upper bound on vsafe by doing the computation twice
     748       533386 :             const double vsafe1 = MAX2(neighNewSpeed, nv->getCarFollowModel().followSpeed(
     749       533386 :                                            nv, nv->getSpeed(), neighFollow.second + SPEED2DIST(plannedSpeed), plannedSpeed, myVehicle.getCarFollowModel().getMaxDecel()));
     750       533386 :             const double vsafe = MAX2(neighNewSpeed, nv->getCarFollowModel().followSpeed(
     751       533386 :                                           nv, nv->getSpeed(), neighFollow.second + SPEED2DIST(plannedSpeed - vsafe1), plannedSpeed, myVehicle.getCarFollowModel().getMaxDecel()));
     752              :             // the following assertion cannot be guaranteed because the CFModel handles small gaps differently, see MSCFModel::maximumSafeStopSpeed
     753              :             // assert(vsafe <= vsafe1);
     754       533386 :             msg(neighFollow, vsafe, dir | LCA_AMBLOCKINGFOLLOWER);
     755              : #ifdef DEBUG_INFORM
     756              :             if (gDebugFlag2) {
     757              :                 std::cout << " wants to cut in before nv=" << nv->getID()
     758              :                           << " vsafe1=" << vsafe1
     759              :                           << " vsafe=" << vsafe
     760              :                           << " newSecGap=" << nv->getCarFollowModel().getSecureGap(nv, &myVehicle, vsafe, plannedSpeed, myVehicle.getCarFollowModel().getMaxDecel())
     761              :                           << "\n";
     762              :             }
     763              : #endif
     764      3146500 :         } else if (dv > 0 && dv * remainingSeconds > (secureGap - decelGap + POSITION_EPS)) {
     765              :             // decelerating once is sufficient to open up a large enough gap in time
     766       144301 :             msg(neighFollow, neighNewSpeed, dir | LCA_AMBLOCKINGFOLLOWER);
     767              : #ifdef DEBUG_INFORM
     768              :             if (gDebugFlag2) {
     769              :                 std::cout << " wants to cut in before nv=" << nv->getID() << " (eventually)\n";
     770              :             }
     771              : #endif
     772      2468813 :         } else if (dir == LCA_MRIGHT && !myAllowOvertakingRight && !nv->congested()) {
     773              :             const double vhelp = MAX2(neighNewSpeed, HELP_OVERTAKE);
     774         2078 :             msg(neighFollow, vhelp, dir | LCA_AMBLOCKINGFOLLOWER);
     775              : #ifdef DEBUG_INFORM
     776              :             if (gDebugFlag2) {
     777              :                 std::cout << " wants to cut in before nv=" << nv->getID() << " (nv cannot overtake right)\n";
     778              :             }
     779              : #endif
     780              :         } else {
     781      2466735 :             double vhelp = MAX2(nv->getSpeed(), myVehicle.getSpeed() + HELP_OVERTAKE);
     782      2466735 :             if (nv->getSpeed() > myVehicle.getSpeed() &&
     783       425327 :                     ((dir == LCA_MRIGHT && myVehicle.getWaitingSeconds() > LCA_RIGHT_IMPATIENCE)
     784       306006 :                      || (dir == LCA_MLEFT && plannedSpeed > CUT_IN_LEFT_SPEED_THRESHOLD) // VARIANT_22 (slowDownLeft)
     785              :                      // XXX this is a hack to determine whether the vehicles is on an on-ramp. This information should be retrieved from the network itself
     786       301297 :                      || (dir == LCA_MLEFT && myLeftSpace > MAX_ONRAMP_LENGTH)
     787              :                     )) {
     788              :                 // let the follower slow down to increase the likelyhood that later vehicles will be slow enough to help
     789              :                 // follower should still be fast enough to open a gap
     790       435897 :                 vhelp = MAX2(neighNewSpeed, myVehicle.getSpeed() + HELP_OVERTAKE);
     791              : #ifdef DEBUG_INFORM
     792              :                 if (gDebugFlag2) {
     793              :                     std::cout << " wants right follower to slow down a bit\n";
     794              :                 }
     795              : #endif
     796       435897 :                 if ((nv->getSpeed() - myVehicle.getSpeed()) / helpDecel < remainingSeconds) {
     797              : #ifdef DEBUG_INFORM
     798              :                     if (gDebugFlag2) {
     799              :                         std::cout << " wants to cut in before right follower nv=" << nv->getID() << " (eventually)\n";
     800              :                     }
     801              : #endif
     802       423023 :                     msg(neighFollow, vhelp, dir | LCA_AMBLOCKINGFOLLOWER);
     803       423023 :                     return;
     804              :                 }
     805              :             }
     806      2043712 :             msg(neighFollow, vhelp, dir | LCA_AMBLOCKINGFOLLOWER);
     807              :             // this follower is supposed to overtake us. slow down smoothly to allow this
     808      2043712 :             const double overtakeDist = (neighFollow.second // follower reaches ego back
     809      2043712 :                                          + myVehicle.getVehicleType().getLengthWithGap() // follower reaches ego front
     810      2043712 :                                          + nv->getVehicleType().getLength() // follower back at ego front
     811      2043712 :                                          + myVehicle.getCarFollowModel().getSecureGap( // follower has safe dist to ego
     812      2043712 :                                              &myVehicle, nv, plannedSpeed, vhelp, nv->getCarFollowModel().getMaxDecel()));
     813              :             // speed difference to create a sufficiently large gap
     814      2043712 :             const double needDV = overtakeDist / remainingSeconds;
     815              :             // make sure the deceleration is not to strong
     816      2207133 :             addLCSpeedAdvice(MAX2(vhelp - needDV, myVehicle.getSpeed() - ACCEL2SPEED(myVehicle.getCarFollowModel().getMaxDecel())));
     817              : 
     818              : #ifdef DEBUG_INFORM
     819              :             if (gDebugFlag2) {
     820              :                 std::cout << SIMTIME
     821              :                           << " veh=" << myVehicle.getID()
     822              :                           << " wants to be overtaken by=" << nv->getID()
     823              :                           << " overtakeDist=" << overtakeDist
     824              :                           << " vneigh=" << nv->getSpeed()
     825              :                           << " vhelp=" << vhelp
     826              :                           << " needDV=" << needDV
     827              :                           << " vsafe=" << myVehicle.getSpeed() + ACCEL2SPEED(myLCAccelerationAdvices.back().first)
     828              :                           << "\n";
     829              :             }
     830              : #endif
     831              :         }
     832      1284939 :     } else if (neighFollow.first != 0) {
     833      1284939 :         const double vsafe = MSLCHelper::getSpeedPreservingSecureGap(myVehicle, *neighFollow.first, neighFollow.second, plannedSpeed);
     834      1284939 :         msg(neighFollow, vsafe, dir | LCA_AMBLOCKINGFOLLOWER);
     835              : #ifdef DEBUG_INFORM
     836              :         if (gDebugFlag2) {
     837              :             std::cout << " wants to cut in before non-blocking follower nv=" << neighFollow.first->getID() << "\n";
     838              :         }
     839              : #endif
     840              :     }
     841              : }
     842              : 
     843              : double
     844      2207649 : MSLCM_SL2015::informLeaders(int blocked, int dir,
     845              :                             const std::vector<CLeaderDist>& blockers,
     846              :                             double remainingSeconds) {
     847      2207649 :     double plannedSpeed = myVehicle.getSpeed();
     848      2207649 :     double space = myLeftSpace;
     849      2207649 :     if (myLeadingBlockerLength != 0) {
     850              :         // see patchSpeed @todo: refactor
     851       341615 :         space -= myLeadingBlockerLength - MAGIC_OFFSET - myVehicle.getVehicleType().getMinGap();
     852       341615 :         if (space <= 0) {
     853              :             // ignore leading blocker
     854          315 :             space = myLeftSpace;
     855              :         }
     856              :     }
     857      2207649 :     double safe = myVehicle.getCarFollowModel().stopSpeed(&myVehicle, myVehicle.getSpeed(), space);
     858              :     plannedSpeed = MIN2(plannedSpeed, safe);
     859              : 
     860      8450507 :     for (std::vector<CLeaderDist>::const_iterator it = blockers.begin(); it != blockers.end(); ++it) {
     861      6242858 :         plannedSpeed = MIN2(plannedSpeed, informLeader(blocked, dir, *it, remainingSeconds));
     862              :     }
     863      2207649 :     return plannedSpeed;
     864              : }
     865              : 
     866              : 
     867              : void
     868      1818636 : MSLCM_SL2015::informFollowers(int blocked, int dir,
     869              :                               const std::vector<CLeaderDist>& blockers,
     870              :                               double remainingSeconds,
     871              :                               double plannedSpeed) {
     872              :     // #3727
     873      6418908 :     for (std::vector<CLeaderDist>::const_iterator it = blockers.begin(); it != blockers.end(); ++it) {
     874      4600272 :         informFollower(blocked, dir, *it, remainingSeconds, plannedSpeed);
     875              :     }
     876      1818636 : }
     877              : 
     878              : 
     879              : void
     880     80959966 : MSLCM_SL2015::prepareStep() {
     881     80959966 :     MSAbstractLaneChangeModel::prepareStep();
     882              :     // keep information about strategic change direction
     883     80959966 :     myOwnState = (myOwnState & (LCA_STRATEGIC | LCA_COOPERATIVE)) ? (myOwnState & LCA_WANTS_LANECHANGE) : 0;
     884              : #ifdef DEBUG_INFORM
     885              :     if (debugVehicle()) {
     886              :         std::cout << SIMTIME
     887              :                   << " veh=" << myVehicle.getID()
     888              :                   << " prepareStep"
     889              :                   << " myCanChangeFully=" << myCanChangeFully
     890              :                   << "\n";
     891              :     }
     892              : #endif
     893     80959966 :     myLeadingBlockerLength = 0;
     894     80959966 :     myLeftSpace = 0;
     895              :     myLCAccelerationAdvices.clear();
     896     80959966 :     myDontBrake = false;
     897              :     myCFRelated.clear();
     898     80959966 :     myCFRelatedReady = false;
     899     80959966 :     const double halfWidth = getWidth() * 0.5;
     900              :     // only permit changing within lane bounds but open up the range depending on the checked duration in _wantsChangeSublane()
     901     80959966 :     mySafeLatDistRight = myVehicle.getLane()->getWidth() * 0.5 + myVehicle.getLateralPositionOnLane() - halfWidth;
     902     80959966 :     mySafeLatDistLeft = myVehicle.getLane()->getWidth() * 0.5 - myVehicle.getLateralPositionOnLane() - halfWidth;
     903     80959966 :     if (isOpposite()) {
     904              :         std::swap(mySafeLatDistLeft, mySafeLatDistRight);
     905              :     }
     906              :     // truncate to work around numerical instability between different builds
     907     80959966 :     mySpeedGainProbabilityRight = ceil(mySpeedGainProbabilityRight * 100000.0) * 0.00001;
     908     80959966 :     mySpeedGainProbabilityLeft = ceil(mySpeedGainProbabilityLeft * 100000.0) * 0.00001;
     909     80959966 :     myKeepRightProbability = ceil(myKeepRightProbability * 100000.0) * 0.00001;
     910              :     // updated myExpectedSublaneSpeeds
     911              :     // XXX only do this when (sub)lane changing is possible
     912              :     std::vector<double> newExpectedSpeeds;
     913              : #ifdef DEBUG_INFORM
     914              :     if (DEBUG_COND) {
     915              :         std::cout << SIMTIME << " veh=" << myVehicle.getID() << " myExpectedSublaneSpeeds=" << toString(myExpectedSublaneSpeeds) << "\n";
     916              :     }
     917              : #endif
     918    161919932 :     if (myExpectedSublaneSpeeds.size() != myVehicle.getLane()->getEdge().getSubLaneSides().size()) {
     919              :         // initialize
     920      1108321 :         const MSEdge* currEdge = &myVehicle.getLane()->getEdge();
     921              :         const std::vector<MSLane*>& lanes = currEdge->getLanes();
     922      3041435 :         for (std::vector<MSLane*>::const_iterator it_lane = lanes.begin(); it_lane != lanes.end(); ++it_lane) {
     923      1933114 :             const int subLanes = MAX2(1, int(ceil((*it_lane)->getWidth() / MSGlobals::gLateralResolution)));
     924     10301105 :             for (int i = 0; i < subLanes; ++i) {
     925      8367991 :                 newExpectedSpeeds.push_back((*it_lane)->getVehicleMaxSpeed(&myVehicle));
     926              :             }
     927              :         }
     928      1108321 :         if (currEdge->canChangeToOpposite()) {
     929        11301 :             MSLane* opposite = lanes.back()->getOpposite();
     930        11301 :             const int subLanes = MAX2(1, int(ceil(opposite->getWidth() / MSGlobals::gLateralResolution)));
     931        62039 :             for (int i = 0; i < subLanes; ++i) {
     932        50738 :                 newExpectedSpeeds.push_back(lanes.back()->getVehicleMaxSpeed(&myVehicle));
     933              :             }
     934              :         }
     935      1108321 :         if (myExpectedSublaneSpeeds.size() > 0) {
     936              :             // copy old values
     937              :             assert(myLastEdge != 0);
     938       618334 :             if (myLastEdge->getSubLaneSides().size() == myExpectedSublaneSpeeds.size()) {
     939       618334 :                 const int subLaneShift = computeSublaneShift(myLastEdge, currEdge);
     940       618334 :                 if (subLaneShift < std::numeric_limits<int>::max()) {
     941      2577423 :                     for (int i = 0; i < (int)myExpectedSublaneSpeeds.size(); ++i) {
     942      2230032 :                         const int newI = i + subLaneShift;
     943      2230032 :                         if (newI > 0 && newI < (int)newExpectedSpeeds.size()) {
     944      1532227 :                             newExpectedSpeeds[newI] = myExpectedSublaneSpeeds[i];
     945              :                         }
     946              :                     }
     947              :                 }
     948              :             }
     949              :         }
     950      1108321 :         myExpectedSublaneSpeeds = newExpectedSpeeds;
     951      1108321 :         myLastEdge = currEdge;
     952              :     }
     953              :     assert(myExpectedSublaneSpeeds.size() == myVehicle.getLane()->getEdge().getSubLaneSides().size());
     954     80959966 :     if (mySigma > 0) {
     955        55319 :         mySigmaState += getLateralDrift();
     956              :     }
     957     80959966 : }
     958              : 
     959              : double
     960        55319 : MSLCM_SL2015::getLateralDrift() {
     961              :     //OUProcess::step(double state, double dt, double timeScale, double noiseIntensity)
     962        55319 :     const double deltaState = OUProcess::step(mySigmaState,
     963        55319 :                               myVehicle.getActionStepLengthSecs(),
     964        55319 :                               MAX2(NUMERICAL_EPS, (1 - mySigma) * 100), mySigma) - mySigmaState;
     965        55319 :     const double scaledDelta = deltaState * myVehicle.getSpeed() / myVehicle.getLane()->getSpeedLimit();
     966        55319 :     return scaledDelta;
     967              : }
     968              : 
     969              : double
     970     93809116 : MSLCM_SL2015::getPosLat() {
     971     93809116 :     return myVehicle.getLateralPositionOnLane() + mySigmaState;
     972              : }
     973              : 
     974              : int
     975       618334 : MSLCM_SL2015::computeSublaneShift(const MSEdge* prevEdge, const MSEdge* curEdge) {
     976              :     // find the first lane that targets the new edge
     977              :     int prevShift = 0;
     978      1235271 :     for (const MSLane* const lane : prevEdge->getLanes()) {
     979      1800182 :         for (const MSLink* const link : lane->getLinkCont()) {
     980      1183245 :             if (&link->getLane()->getEdge() == curEdge) {
     981              :                 int curShift = 0;
     982              :                 const MSLane* target = link->getLane();
     983              :                 const std::vector<MSLane*>& lanes2 = curEdge->getLanes();
     984       485058 :                 for (std::vector<MSLane*>::const_iterator it_lane2 = lanes2.begin(); it_lane2 != lanes2.end(); ++it_lane2) {
     985       485058 :                     const MSLane* lane2 = *it_lane2;
     986       485058 :                     if (lane2 == target) {
     987       347391 :                         return prevShift + curShift;
     988              :                     }
     989       137667 :                     MSLeaderInfo ahead(lane2->getWidth());
     990       137667 :                     curShift += ahead.numSublanes();
     991       137667 :                 }
     992              :                 assert(false);
     993              :             }
     994              :         }
     995       616937 :         MSLeaderInfo ahead(lane->getWidth());
     996       616937 :         prevShift -= ahead.numSublanes();
     997       616937 :     }
     998              :     return std::numeric_limits<int>::max();
     999              : }
    1000              : 
    1001              : 
    1002              : void
    1003      1188274 : MSLCM_SL2015::changed() {
    1004      1188274 :     if (!myCanChangeFully) {
    1005              :         // do not reset state yet so we can continue our maneuver but acknowledge
    1006              :         // a change to the right (movement should continue due to lane alignment desire)
    1007       365325 :         if (getManeuverDist() < 0) {
    1008       169335 :             myKeepRightProbability = 0;
    1009              :         }
    1010              : #ifdef DEBUG_STATE
    1011              :         if (DEBUG_COND) {
    1012              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " state not reset. maneuverDist=" << getManeuverDist() << "\n";
    1013              :         }
    1014              : #endif
    1015       365325 :         return;
    1016              :     }
    1017       822949 :     myOwnState = 0;
    1018              :     // XX do not reset values for unfinished maneuvers
    1019       822949 :     mySpeedGainProbabilityRight = 0;
    1020       822949 :     mySpeedGainProbabilityLeft = 0;
    1021       822949 :     myKeepRightProbability = 0;
    1022              : 
    1023       822949 :     if (myVehicle.getBestLaneOffset() == 0) {
    1024              :         // if we are not yet on our best lane there might still be unseen blockers
    1025              :         // (during patchSpeed)
    1026       802944 :         myLeadingBlockerLength = 0;
    1027       802944 :         myLeftSpace = 0;
    1028              :     }
    1029       822949 :     myLookAheadSpeed = LOOK_AHEAD_MIN_SPEED;
    1030              :     myLCAccelerationAdvices.clear();
    1031       822949 :     myDontBrake = false;
    1032              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_STATE)
    1033              :     if (DEBUG_COND) {
    1034              :         std::cout << SIMTIME << " veh=" << myVehicle.getID() << " changed()\n";
    1035              :     }
    1036              : #endif
    1037              : }
    1038              : 
    1039              : 
    1040              : void
    1041         2922 : MSLCM_SL2015::resetState() {
    1042         2922 :     myOwnState = 0;
    1043         2922 :     mySpeedGainProbabilityRight = 0;
    1044         2922 :     mySpeedGainProbabilityLeft = 0;
    1045         2922 :     myKeepRightProbability = 0;
    1046         2922 :     myLeadingBlockerLength = 0;
    1047         2922 :     myLeftSpace = 0;
    1048         2922 :     myLookAheadSpeed = LOOK_AHEAD_MIN_SPEED;
    1049              :     myLCAccelerationAdvices.clear();
    1050         2922 :     myDontBrake = false;
    1051         2922 : }
    1052              : 
    1053              : 
    1054              : int
    1055    115565969 : MSLCM_SL2015::_wantsChangeSublane(
    1056              :     int laneOffset,
    1057              :     LaneChangeAction alternatives,
    1058              :     const MSLeaderDistanceInfo& leaders,
    1059              :     const MSLeaderDistanceInfo& followers,
    1060              :     const MSLeaderDistanceInfo& blockers,
    1061              :     const MSLeaderDistanceInfo& neighLeaders,
    1062              :     const MSLeaderDistanceInfo& neighFollowers,
    1063              :     const MSLeaderDistanceInfo& neighBlockers,
    1064              :     const MSLane& neighLane,
    1065              :     const std::vector<MSVehicle::LaneQ>& preb,
    1066              :     MSVehicle** lastBlocked,
    1067              :     MSVehicle** firstBlocked,
    1068              :     double& latDist, double& maneuverDist, int& blocked) {
    1069              : 
    1070    115565969 :     if (laneOffset != 0) {
    1071              :         // update mySafeLatDist w.r.t. the direction being checkd
    1072     35548671 :         const double halfWidth = getWidth() * 0.5;
    1073     35548671 :         double center = getVehicleCenter();
    1074     35548671 :         if (laneOffset < 0) {
    1075     15641274 :             mySafeLatDistRight = center - halfWidth;
    1076              :         } else  {
    1077     19907397 :             mySafeLatDistLeft = getLeftBorder() - center - halfWidth;
    1078              :         }
    1079              :     }
    1080              : 
    1081    115565969 :     const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
    1082              :     // compute bestLaneOffset
    1083              :     MSVehicle::LaneQ curr, neigh, best;
    1084              :     int bestLaneOffset = 0;
    1085    115565969 :     double currentDist = 0;
    1086              :     double neighDist = 0;
    1087    115565969 :     const MSLane* prebLane = myVehicle.getLane();
    1088    115565969 :     if (prebLane->getEdge().isInternal()) {
    1089              :         // internal edges are not kept inside the bestLanes structure
    1090      2256181 :         if (isOpposite()) {
    1091          478 :             prebLane = prebLane->getNormalPredecessorLane();
    1092              :         } else {
    1093      2255703 :             prebLane = prebLane->getLinkCont()[0]->getLane();
    1094              :         }
    1095              :     }
    1096              :     // special case: vehicle considers changing to the opposite direction edge
    1097    115565969 :     const bool checkOpposite = &neighLane.getEdge() != &myVehicle.getLane()->getEdge();
    1098    115565969 :     const int prebOffset = (checkOpposite ? 0 : laneOffset);
    1099    157219058 :     for (int p = 0; p < (int) preb.size(); ++p) {
    1100    157219058 :         if (preb[p].lane == prebLane && p + laneOffset >= 0) {
    1101              :             assert(p + prebOffset < (int)preb.size());
    1102              :             curr = preb[p];
    1103    115565969 :             neigh = preb[p + prebOffset];
    1104    115565969 :             currentDist = curr.length;
    1105    115565969 :             neighDist = neigh.length;
    1106    115565969 :             bestLaneOffset = curr.bestLaneOffset;
    1107              :             // VARIANT_13 (equalBest)
    1108    115565969 :             if (bestLaneOffset == 0 && preb[p + prebOffset].bestLaneOffset == 0 && !checkOpposite) {
    1109              : #ifdef DEBUG_WANTSCHANGE
    1110              :                 if (gDebugFlag2) {
    1111              :                     std::cout << STEPS2TIME(currentTime)
    1112              :                               << " veh=" << myVehicle.getID()
    1113              :                               << " bestLaneOffsetOld=" << bestLaneOffset
    1114              :                               << " bestLaneOffsetNew=" << laneOffset
    1115              :                               << "\n";
    1116              :                 }
    1117              : #endif
    1118              :                 bestLaneOffset = prebOffset;
    1119              :             }
    1120    115565969 :             best = preb[p + bestLaneOffset];
    1121              :             break;
    1122              :         }
    1123              :     }
    1124              :     assert(curr.lane != nullptr);
    1125              :     assert(neigh.lane != nullptr);
    1126              :     assert(best.lane != nullptr);
    1127              :     double driveToNextStop = -std::numeric_limits<double>::max();
    1128              :     UNUSED_PARAMETER(driveToNextStop); // XXX use when computing usableDist
    1129    115565969 :     if (myVehicle.nextStopDist() < std::numeric_limits<double>::max()
    1130    115565969 :             && &myVehicle.getNextStop().lane->getEdge() == &myVehicle.getLane()->getEdge()) {
    1131              :         // vehicle can always drive up to stop distance
    1132              :         // @note this information is dynamic and thus not available in updateBestLanes()
    1133              :         // @note: nextStopDist was compute before the vehicle moved
    1134              :         driveToNextStop = myVehicle.nextStopDist();
    1135      3420880 :         const double stopPos = getForwardPos() + myVehicle.nextStopDist() - myVehicle.getLastStepDist();
    1136              : #ifdef DEBUG_WANTS_CHANGE
    1137              :         if (DEBUG_COND) {
    1138              :             std::cout << SIMTIME << std::setprecision(gPrecision) << " veh=" << myVehicle.getID()
    1139              :                       << " stopDist=" << myVehicle.nextStopDist()
    1140              :                       << " lastDist=" << myVehicle.getLastStepDist()
    1141              :                       << " stopPos=" << stopPos
    1142              :                       << " currentDist=" << currentDist
    1143              :                       << " neighDist=" << neighDist
    1144              :                       << "\n";
    1145              :         }
    1146              : #endif
    1147      4172075 :         currentDist = MAX2(currentDist, stopPos);
    1148              :         neighDist = MAX2(neighDist, stopPos);
    1149              :     }
    1150              :     // direction specific constants
    1151    115565969 :     const bool right = (laneOffset == -1);
    1152    115565969 :     const bool left = (laneOffset == 1);
    1153    115565969 :     const int myLca = (right ? LCA_MRIGHT : (left ? LCA_MLEFT : 0));
    1154     99924695 :     const int lcaCounter = (right ? LCA_LEFT : (left ? LCA_RIGHT : LCA_NONE));
    1155    115565969 :     const bool changeToBest = (right && bestLaneOffset < 0) || (left && bestLaneOffset > 0) || (laneOffset == 0 && bestLaneOffset == 0);
    1156              :     // keep information about being a leader/follower but remove information
    1157              :     // about previous lane change request or urgency
    1158    115565969 :     int ret = (myOwnState & 0xffff0000);
    1159              : 
    1160              :     // compute the distance when changing to the neighboring lane
    1161              :     // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
    1162              :     // minimum distance to move the vehicle fully onto the new lane
    1163    115565969 :     double latLaneDist = laneOffset == 0 ? 0. : myVehicle.lateralDistanceToLane(laneOffset);
    1164              : 
    1165              :     // VARIANT_5 (disableAMBACKBLOCKER1)
    1166              :     /*
    1167              :     if (leader.first != 0
    1168              :             && (myOwnState & LCA_AMBLOCKINGFOLLOWER_DONTBRAKE) != 0
    1169              :             && (leader.first->getLaneChangeModel().getOwnState() & LCA_AMBLOCKINGFOLLOWER_DONTBRAKE) != 0) {
    1170              : 
    1171              :         myOwnState &= (0xffffffff - LCA_AMBLOCKINGFOLLOWER_DONTBRAKE);
    1172              :         if (myVehicle.getSpeed() > SUMO_const_haltingSpeed) {
    1173              :             myOwnState |= LCA_AMBACKBLOCKER;
    1174              :         } else {
    1175              :             ret |= LCA_AMBACKBLOCKER;
    1176              :             myDontBrake = true;
    1177              :         }
    1178              :     }
    1179              :     */
    1180              : 
    1181              : #ifdef DEBUG_WANTSCHANGE
    1182              :     if (gDebugFlag2) {
    1183              :         std::cout << STEPS2TIME(currentTime)
    1184              :                   << " veh=" << myVehicle.getID()
    1185              :                   << " myState=" << toString((LaneChangeAction)myOwnState)
    1186              :                   << " firstBlocked=" << Named::getIDSecure(*firstBlocked)
    1187              :                   << " lastBlocked=" << Named::getIDSecure(*lastBlocked)
    1188              :                   << "\n         leaders=" << leaders.toString()
    1189              :                   << "\n       followers=" << followers.toString()
    1190              :                   << "\n        blockers=" << blockers.toString()
    1191              :                   << "\n    neighLeaders=" << neighLeaders.toString()
    1192              :                   << "\n  neighFollowers=" << neighFollowers.toString()
    1193              :                   << "\n   neighBlockers=" << neighBlockers.toString()
    1194              :                   << "\n   changeToBest=" << changeToBest
    1195              :                   << " latLaneDist=" << latLaneDist
    1196              :                   << " alts=" << toString((LaneChangeAction)alternatives)
    1197              :                   << "\n   expectedSpeeds=" << toString(myExpectedSublaneSpeeds)
    1198              :                   << std::endl;
    1199              :     }
    1200              : #endif
    1201              : 
    1202    115565969 :     ret = slowDownForBlocked(lastBlocked, ret);
    1203              :     // VARIANT_14 (furtherBlock)
    1204    115565969 :     if (lastBlocked != firstBlocked) {
    1205    115565969 :         ret = slowDownForBlocked(firstBlocked, ret);
    1206              :     }
    1207              : 
    1208              : 
    1209              :     // we try to estimate the distance which is necessary to get on a lane
    1210              :     //  we have to get on in order to keep our route
    1211              :     // we assume we need something that depends on our velocity
    1212              :     // and compare this with the free space on our wished lane
    1213              :     //
    1214              :     // if the free space is somehow less than the space we need, we should
    1215              :     //  definitely try to get to the desired lane
    1216              :     //
    1217              :     // this rule forces our vehicle to change the lane if a lane changing is necessary soon
    1218              :     // lookAheadDistance:
    1219              :     // we do not want the lookahead distance to change all the time so we discrectize the speed a bit
    1220              : 
    1221              :     // VARIANT_18 (laHyst)
    1222    115565969 :     if (myVehicle.getSpeed() > myLookAheadSpeed) {
    1223     20047849 :         myLookAheadSpeed = myVehicle.getSpeed();
    1224              :     } else {
    1225              :         // FIXME: This strongly dependent on the value of TS, see LC2013 for the fix (l.1153, currently)
    1226     95518120 :         myLookAheadSpeed = MAX2(LOOK_AHEAD_MIN_SPEED,
    1227     95518120 :                                 (LOOK_AHEAD_SPEED_MEMORY * myLookAheadSpeed + (1 - LOOK_AHEAD_SPEED_MEMORY) * myVehicle.getSpeed()));
    1228              :     }
    1229              :     //myLookAheadSpeed = myVehicle.getLane()->getVehicleMaxSpeed(&myVehicle);
    1230              : 
    1231              :     //double laDist = laSpeed > LOOK_FORWARD_SPEED_DIVIDER
    1232              :     //              ? laSpeed *  LOOK_FORWARD_FAR
    1233              :     //              : laSpeed *  LOOK_FORWARD_NEAR;
    1234    115565969 :     double laDist = myLookAheadSpeed * LOOK_FORWARD * myStrategicParam * (right ? 1 : myLookaheadLeft);
    1235    115565969 :     laDist += myVehicle.getVehicleType().getLengthWithGap() * 2.;
    1236              :     // aggressive drivers may elect to use reduced strategic lookahead to optimize speed
    1237              :     /*
    1238              :     if (mySpeedGainProbabilityRight > myChangeProbThresholdRight
    1239              :             || mySpeedGainProbabilityLeft > myChangeProbThresholdLeft) {
    1240              :         laDist *= MAX2(0.0, (1 - myPushy));
    1241              :         laDist *= MAX2(0,0, (1 - myAssertive));
    1242              :         laDist *= MAX2(0,0, (2 - mySpeedGainParam));
    1243              :     }
    1244              :     */
    1245              : 
    1246              :     // react to a stopped leader on the current lane
    1247    115565969 :     if (bestLaneOffset == 0 && leaders.hasStoppedVehicle()) {
    1248              :         // value is doubled for the check since we change back and forth
    1249              :         // laDist = 0.5 * (myVehicle.getVehicleType().getLengthWithGap() + leader.first->getVehicleType().getLengthWithGap());
    1250              :         // XXX determine length of longest stopped vehicle
    1251       219822 :         laDist = myVehicle.getVehicleType().getLengthWithGap();
    1252    115346147 :     } else if (checkOpposite && isOpposite() && neighLeaders.hasStoppedVehicle()) {
    1253              :         // compute exact distance to overtake stopped vehicle
    1254              :         laDist = 0;
    1255        45405 :         for (int i = 0; i < neighLeaders.numSublanes(); ++i) {
    1256        36324 :             CLeaderDist vehDist = neighLeaders[i];
    1257        36324 :             if (vehDist.first != nullptr && vehDist.first->isStopped()) {
    1258        29472 :                 laDist = MAX2(laDist, myVehicle.getVehicleType().getMinGap() + vehDist.second + vehDist.first->getVehicleType().getLengthWithGap());
    1259              :             }
    1260              :         }
    1261         9081 :         laDist += myVehicle.getVehicleType().getLength();
    1262              :     }
    1263    115565969 :     if (myStrategicParam < 0) {
    1264              :         laDist = -1e3; // never perform strategic change
    1265              :     }
    1266              : 
    1267              :     // free space that is available for changing
    1268              :     //const double neighSpeed = (neighLead.first != 0 ? neighLead.first->getSpeed() :
    1269              :     //        neighFollow.first != 0 ? neighFollow.first->getSpeed() :
    1270              :     //        best.lane->getSpeedLimit());
    1271              :     // @note: while this lets vehicles change earlier into the correct direction
    1272              :     // it also makes the vehicles more "selfish" and prevents changes which are necessary to help others
    1273              : 
    1274    115565969 :     const double roundaboutBonus = MSLCHelper::getRoundaboutDistBonus(myVehicle, myRoundaboutBonus, curr, neigh, best);
    1275    115565969 :     currentDist += roundaboutBonus;
    1276    115565969 :     neighDist += roundaboutBonus;
    1277              : 
    1278    115565969 :     ret = checkStrategicChange(ret,
    1279              :                                neighLane,
    1280              :                                laneOffset,
    1281              :                                leaders,
    1282              :                                neighLeaders,
    1283              :                                curr, neigh, best,
    1284              :                                bestLaneOffset,
    1285              :                                changeToBest,
    1286              :                                currentDist,
    1287              :                                neighDist,
    1288              :                                laDist,
    1289              :                                roundaboutBonus,
    1290              :                                latLaneDist,
    1291              :                                checkOpposite,
    1292              :                                latDist);
    1293              : 
    1294              : 
    1295    115565969 :     if ((ret & LCA_STAY) != 0 && latDist == 0) {
    1296              :         // ensure that mySafeLatDistLeft / mySafeLatDistRight are up to date for the
    1297              :         // subsquent check with laneOffset = 0
    1298     11486355 :         const double center = myVehicle.getCenterOnEdge();
    1299     11486355 :         const double neighRight = getNeighRight(neighLane);
    1300     11486355 :         updateGaps(neighLeaders, neighRight, center, 1.0, mySafeLatDistRight, mySafeLatDistLeft);
    1301     11486355 :         updateGaps(neighFollowers, neighRight, center, 1.0, mySafeLatDistRight, mySafeLatDistLeft);
    1302              :         // remove TraCI flags because it should not be included in "state-without-traci"
    1303     11486355 :         ret = getCanceledState(laneOffset);
    1304     11486355 :         return ret;
    1305              :     }
    1306    104079614 :     if ((ret & LCA_URGENT) != 0) {
    1307              :         // prepare urgent lane change maneuver
    1308      2055230 :         if (changeToBest && abs(bestLaneOffset) > 1
    1309      2274515 :                 && curr.bestContinuations.back()->getLinkCont().size() != 0
    1310              :            ) {
    1311              :             // there might be a vehicle which needs to counter-lane-change one lane further and we cannot see it yet
    1312        47621 :             const double reserve = MIN2(myLeftSpace - MAGIC_OFFSET - myVehicle.getVehicleType().getMinGap(), getExtraReservation(bestLaneOffset, neighDist - currentDist));
    1313        49074 :             myLeadingBlockerLength = MAX2(reserve, myLeadingBlockerLength);
    1314              : #ifdef DEBUG_WANTSCHANGE
    1315              :             if (gDebugFlag2) {
    1316              :                 std::cout << "  reserving space for unseen blockers myLeadingBlockerLength=" << myLeadingBlockerLength << "\n";
    1317              :             }
    1318              : #endif
    1319              :         }
    1320              : 
    1321              :         // letting vehicles merge in at the end of the lane in case of counter-lane change, step#1
    1322              :         //   if there is a leader and he wants to change to the opposite direction
    1323      2207649 :         MSVehicle* neighLeadLongest = const_cast<MSVehicle*>(getLongest(neighLeaders).first);
    1324      2207649 :         const bool canContinue = curr.bestContinuations.size() > 1;
    1325              : #ifdef DEBUG_WANTSCHANGE
    1326              :         if (DEBUG_COND) {
    1327              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " neighLeaders=" << neighLeaders.toString() << " longest=" << Named::getIDSecure(neighLeadLongest) << " firstBlocked=" << Named::getIDSecure(*firstBlocked) << "\n";
    1328              :         }
    1329              : #endif
    1330      2207649 :         bool canReserve = MSLCHelper::updateBlockerLength(myVehicle, neighLeadLongest, lcaCounter, myLeftSpace - MAGIC_OFFSET, canContinue, myLeadingBlockerLength);
    1331      2207649 :         if (*firstBlocked != neighLeadLongest && tieBrakeLeader(*firstBlocked)) {
    1332        79357 :             canReserve &= MSLCHelper::updateBlockerLength(myVehicle, *firstBlocked, lcaCounter, myLeftSpace - MAGIC_OFFSET, canContinue, myLeadingBlockerLength);
    1333              :         }
    1334      2207649 :         if (!canReserve && !isOpposite()) {
    1335              :             // we have a low-priority relief connection
    1336              :             // std::cout << SIMTIME << " veh=" << myVehicle.getID() << " cannotReserve for blockers\n";
    1337         2980 :             myDontBrake = canContinue;
    1338              :         }
    1339              : 
    1340              :         std::vector<CLeaderDist> collectLeadBlockers;
    1341              :         std::vector<CLeaderDist> collectFollowBlockers;
    1342      2207649 :         int blockedFully = 0; // wether execution of the full maneuver is blocked
    1343      2207649 :         maneuverDist = latDist;
    1344      2207649 :         const double gapFactor = computeGapFactor(LCA_STRATEGIC);
    1345      2207649 :         blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    1346              :                                 leaders, followers, blockers,
    1347              :                                 neighLeaders, neighFollowers, neighBlockers, &collectLeadBlockers, &collectFollowBlockers,
    1348              :                                 false, gapFactor, &blockedFully);
    1349              : 
    1350      2207649 :         const double absLaneOffset = fabs(bestLaneOffset != 0 ? bestLaneOffset : latDist / SUMO_const_laneWidth);
    1351      2207649 :         const double remainingSeconds = ((ret & LCA_TRACI) == 0 ?
    1352      2576218 :                                          MAX2(STEPS2TIME(TS), myLeftSpace / MAX2(myLookAheadSpeed, NUMERICAL_EPS) / absLaneOffset / URGENCY) :
    1353          222 :                                          myVehicle.getInfluencer().changeRequestRemainingSeconds(currentTime));
    1354      2207649 :         const double plannedSpeed = informLeaders(blocked, myLca, collectLeadBlockers, remainingSeconds);
    1355              :         // coordinate with direct obstructions
    1356      2207649 :         if (plannedSpeed >= 0) {
    1357              :             // maybe we need to deal with a blocking follower
    1358      1818636 :             informFollowers(blocked, myLca, collectFollowBlockers, remainingSeconds, plannedSpeed);
    1359              :         }
    1360      1818636 :         if (plannedSpeed > 0) {
    1361       902046 :             commitManoeuvre(blocked, blockedFully, leaders, neighLeaders, neighLane, maneuverDist);
    1362              :         }
    1363              : #if defined(DEBUG_WANTSCHANGE) || defined(DEBUG_STATE)
    1364              :         if (gDebugFlag2) {
    1365              :             std::cout << STEPS2TIME(currentTime)
    1366              :                       << " veh=" << myVehicle.getID()
    1367              :                       << " myLeftSpace=" << myLeftSpace
    1368              :                       << " changeFully=" << myCanChangeFully
    1369              :                       << " blockedFully=" << toString((LaneChangeAction)blockedFully)
    1370              :                       << " remainingSeconds=" << remainingSeconds
    1371              :                       << " plannedSpeed=" << plannedSpeed
    1372              :                       << " mySafeLatDistRight=" << mySafeLatDistRight
    1373              :                       << " mySafeLatDistLeft=" << mySafeLatDistLeft
    1374              :                       << "\n";
    1375              :         }
    1376              : #endif
    1377              :         // remove TraCI flags because it should not be included in "state-without-traci"
    1378      2207649 :         ret = getCanceledState(laneOffset);
    1379              :         return ret;
    1380      2207649 :     }
    1381              :     // VARIANT_15
    1382    101871965 :     if (roundaboutBonus > 0) {
    1383              : 
    1384              : #ifdef DEBUG_WANTS_CHANGE
    1385              :         if (DEBUG_COND) {
    1386              :             std::cout << STEPS2TIME(currentTime)
    1387              :                       << " veh=" << myVehicle.getID()
    1388              :                       << " roundaboutBonus=" << roundaboutBonus
    1389              :                       << " myLeftSpace=" << myLeftSpace
    1390              :                       << "\n";
    1391              :         }
    1392              : #endif
    1393              :         // try to use the inner lanes of a roundabout to increase throughput
    1394              :         // unless we are approaching the exit
    1395      5295940 :         if (left) {
    1396       512555 :             ret |= LCA_COOPERATIVE;
    1397       512555 :             if (!cancelRequest(ret | LCA_LEFT, laneOffset)) {
    1398       512555 :                 if ((ret & LCA_STAY) == 0) {
    1399       512555 :                     latDist = latLaneDist;
    1400       512555 :                     maneuverDist = latLaneDist;
    1401       512555 :                     blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    1402              :                                             leaders, followers, blockers,
    1403              :                                             neighLeaders, neighFollowers, neighBlockers);
    1404              :                 }
    1405       512555 :                 return ret;
    1406              :             } else {
    1407              :                 ret &= ~LCA_COOPERATIVE;
    1408              :             }
    1409              :         } else {
    1410      4783385 :             myKeepRightProbability = 0;
    1411              :         }
    1412              :     }
    1413              : 
    1414              :     // --------
    1415              : 
    1416              :     // -------- make place on current lane if blocking follower
    1417              :     //if (amBlockingFollowerPlusNB()) {
    1418              :     //    std::cout << myVehicle.getID() << ", " << currentDistAllows(neighDist, bestLaneOffset, laDist)
    1419              :     //        << " neighDist=" << neighDist
    1420              :     //        << " currentDist=" << currentDist
    1421              :     //        << "\n";
    1422              :     //}
    1423              :     const double inconvenience = (latLaneDist < 0
    1424    101359410 :                                   ? -mySpeedGainProbabilityRight / myChangeProbThresholdRight
    1425     90692240 :                                   : -mySpeedGainProbabilityLeft / myChangeProbThresholdLeft);
    1426              : #ifdef DEBUG_COOPERATE
    1427              :     if (gDebugFlag2) {
    1428              :         std::cout << STEPS2TIME(currentTime)
    1429              :                   << " veh=" << myVehicle.getID()
    1430              :                   << " amBlocking=" << amBlockingFollowerPlusNB()
    1431              :                   << " state=" << toString((LaneChangeAction)myOwnState)
    1432              :                   << " myLca=" << toString((LaneChangeAction)myLca)
    1433              :                   << " prevState=" << toString((LaneChangeAction)myPreviousState)
    1434              :                   << " inconvenience=" << inconvenience
    1435              :                   << " origLatDist=" << getManeuverDist()
    1436              :                   << " wantsChangeToHelp=" << (right ? "right" : "left")
    1437              :                   << " state=" << myOwnState
    1438              :                   << "\n";
    1439              :     }
    1440              : #endif
    1441              : 
    1442              :     if (laneOffset != 0
    1443     21401449 :             && ((amBlockingFollowerPlusNB()
    1444              :                  // VARIANT_6 : counterNoHelp
    1445       238770 :                  && ((myOwnState & myLca) != 0))
    1446     21334799 :                 ||
    1447              :                 // continue previous cooperative change
    1448     21334799 :                 ((myPreviousState & LCA_COOPERATIVE) != 0
    1449        86508 :                  && !myCanChangeFully
    1450              :                  // change is in the right direction
    1451        48903 :                  && (laneOffset * getManeuverDist() > 0)))
    1452        68825 :             && (inconvenience < myCooperativeParam)
    1453    101426744 :             && (changeToBest || currentDistAllows(neighDist, abs(bestLaneOffset) + 1, laDist))) {
    1454              : 
    1455              :         // VARIANT_2 (nbWhenChangingToHelp)
    1456              : #ifdef DEBUG_COOPERATE
    1457              :         if (gDebugFlag2) {
    1458              :             std::cout << "   wants cooperative change\n";
    1459              :         }
    1460              : #endif
    1461              : 
    1462        67331 :         ret |= LCA_COOPERATIVE | LCA_URGENT ;//| LCA_CHANGE_TO_HELP;
    1463        67331 :         if (!cancelRequest(ret | getLCA(ret, latLaneDist), laneOffset)) {
    1464        67331 :             latDist = amBlockingFollowerPlusNB() ? latLaneDist : getManeuverDist();
    1465        67331 :             maneuverDist = latDist;
    1466        67331 :             blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    1467              :                                     leaders, followers, blockers,
    1468              :                                     neighLeaders, neighFollowers, neighBlockers);
    1469        67331 :             return ret;
    1470              :         } else {
    1471              :             ret &= ~(LCA_COOPERATIVE | LCA_URGENT);
    1472              :         }
    1473              :     }
    1474              : 
    1475              :     // --------
    1476              : 
    1477              : 
    1478              :     //// -------- security checks for krauss
    1479              :     ////  (vsafe fails when gap<0)
    1480              :     //if ((blocked & LCA_BLOCKED) != 0) {
    1481              :     //    return ret;
    1482              :     //}
    1483              :     //// --------
    1484              : 
    1485              :     // -------- higher speed
    1486              :     //if ((congested(neighLead.first) && neighLead.second < 20) || predInteraction(leader.first)) { //!!!
    1487              :     //    return ret;
    1488              :     //}
    1489              : 
    1490              :     // iterate over all possible combinations of sublanes this vehicle might cover and check the potential speed
    1491    101292079 :     const MSEdge& edge = (isOpposite() ? myVehicle.getLane()->getParallelOpposite() : myVehicle.getLane())->getEdge();
    1492              :     const std::vector<double>& sublaneSides = edge.getSubLaneSides();
    1493              :     assert(sublaneSides.size() == myExpectedSublaneSpeeds.size());
    1494    101292079 :     const double vehWidth = getWidth();
    1495    101292079 :     const double rightVehSide = getVehicleCenter() - 0.5 * vehWidth;
    1496    101292079 :     const double leftVehSide = rightVehSide + vehWidth;
    1497              :     // figure out next speed when staying where we are
    1498              :     double defaultNextSpeed = std::numeric_limits<double>::max();
    1499              :     /// determine the leftmost and rightmost sublanes currently occupied
    1500    101292079 :     int leftmostOnEdge = (int)sublaneSides.size() - 1;
    1501    300388388 :     while (leftmostOnEdge > 0 && sublaneSides[leftmostOnEdge] > leftVehSide) {
    1502    199096309 :         leftmostOnEdge--;
    1503              :     }
    1504              :     int rightmostOnEdge = leftmostOnEdge;
    1505    376289642 :     while (rightmostOnEdge > 0 && sublaneSides[rightmostOnEdge] > rightVehSide + NUMERICAL_EPS) {
    1506    274997563 :         defaultNextSpeed = MIN2(defaultNextSpeed, myExpectedSublaneSpeeds[rightmostOnEdge]);
    1507              : #ifdef DEBUG_WANTSCHANGE
    1508              :         if (gDebugFlag2) {
    1509              :             std::cout << "   adapted to current sublane=" << rightmostOnEdge << " defaultNextSpeed=" << defaultNextSpeed << "\n";
    1510              :             std::cout << "   sublaneSides[rightmostOnEdge]=" << sublaneSides[rightmostOnEdge] << " rightVehSide=" << rightVehSide << "\n";
    1511              :         }
    1512              : #endif
    1513    274997563 :         rightmostOnEdge--;
    1514              :     }
    1515    101292079 :     defaultNextSpeed = MIN2(defaultNextSpeed, myExpectedSublaneSpeeds[rightmostOnEdge]);
    1516              : #ifdef DEBUG_WANTSCHANGE
    1517              :     if (gDebugFlag2) {
    1518              :         std::cout << "   adapted to current sublane=" << rightmostOnEdge << " defaultNextSpeed=" << defaultNextSpeed << "\n";
    1519              :         std::cout << "   sublaneSides[rightmostOnEdge]=" << sublaneSides[rightmostOnEdge] << " rightVehSide=" << rightVehSide << "\n";
    1520              :     }
    1521              : #endif
    1522              :     double maxGain = -std::numeric_limits<double>::max();
    1523              :     double maxGainRight = -std::numeric_limits<double>::max();
    1524              :     double maxGainLeft = -std::numeric_limits<double>::max();
    1525              :     double latDistNice = std::numeric_limits<double>::max();
    1526              : 
    1527    101292079 :     const int iMin = MIN2(myVehicle.getLane()->getRightmostSublane(), neighLane.getRightmostSublane());
    1528    101292079 :     double leftMax = MAX2(
    1529    101292079 :                          myVehicle.getLane()->getRightSideOnEdge() + myVehicle.getLane()->getWidth(),
    1530              :                          neighLane.getRightSideOnEdge() + neighLane.getWidth());
    1531    101292079 :     double rightMin = MIN2(myVehicle.getLane()->getRightSideOnEdge(), neighLane.getRightSideOnEdge());
    1532    101292079 :     if (checkOpposite || isOpposite()) {
    1533       138420 :         leftMax = getLeftBorder();
    1534              :     } else {
    1535              :         assert(leftMax <= edge.getWidth());
    1536              :     }
    1537    101292079 :     int sublaneCompact = MAX2(iMin, rightmostOnEdge - 1); // try to compactify to the right by default
    1538              : 
    1539    101292079 :     const double laneBoundary = laneOffset < 0 ? myVehicle.getLane()->getRightSideOnEdge() : neighLane.getRightSideOnEdge();
    1540              :     // if there is a neighboring lane we could change to, check sublanes on all lanes of the edge
    1541              :     // but restrict maneuver to the currently visible lanes (current, neigh) to ensure safety
    1542              :     // This way we can discover a fast lane beyond the immediate neighbor lane
    1543    101292079 :     const double maxLatDist = leftMax - leftVehSide;
    1544    101292079 :     const double minLatDist = rightMin - rightVehSide;
    1545    101292079 :     const int iStart = laneOffset == 0 ? iMin : 0;
    1546     21334118 :     const double rightEnd = laneOffset == 0 ? leftMax : (checkOpposite ? getLeftBorder() : edge.getWidth());
    1547              : #ifdef DEBUG_WANTSCHANGE
    1548              :     if (gDebugFlag2) std::cout
    1549              :                 << "  checking sublanes rightmostOnEdge=" << rightmostOnEdge
    1550              :                 << " rightEnd=" << rightEnd
    1551              :                 << " leftmostOnEdge=" << leftmostOnEdge
    1552              :                 << " iStart=" << iStart
    1553              :                 << " iMin=" << iMin
    1554              :                 << " sublaneSides=" << sublaneSides.size()
    1555              :                 << " leftMax=" << leftMax
    1556              :                 << " minLatDist=" << minLatDist
    1557              :                 << " maxLatDist=" << maxLatDist
    1558              :                 << " sublaneCompact=" << sublaneCompact
    1559              :                 << "\n";
    1560              : #endif
    1561    755648241 :     for (int i = iStart; i < (int)sublaneSides.size(); ++i) {
    1562    654356162 :         if (sublaneSides[i] + vehWidth < rightEnd) {
    1563              :             // i is the rightmost sublane and the left side of vehicles still fits on the edge,
    1564              :             // compute min speed of all sublanes covered by the vehicle in this case
    1565    345983018 :             double vMin = myExpectedSublaneSpeeds[i];
    1566              :             //std::cout << "   i=" << i << "\n";
    1567              :             int j = i;
    1568   1346441277 :             while (vMin > 0 && j < (int)sublaneSides.size() && sublaneSides[j] < sublaneSides[i] + vehWidth) {
    1569   1000458259 :                 vMin = MIN2(vMin, myExpectedSublaneSpeeds[j]);
    1570              : #ifdef DEBUG_WANTSCHANGE
    1571              :                 if (gDebugFlag2) {
    1572              :                     //std::cout << "     j=" << j << " vMin=" << vMin << " sublaneSides[j]=" << sublaneSides[j] << " leftVehSide=" << leftVehSide << " rightVehSide=" << rightVehSide << "\n";
    1573              :                 }
    1574              : #endif
    1575   1000458259 :                 ++j;
    1576              :             }
    1577              :             // check whether the vehicle is between lanes
    1578    345983018 :             if (laneOffset != 0 && overlap(sublaneSides[i], sublaneSides[i] + vehWidth, laneBoundary, laneBoundary)) {
    1579     40196142 :                 vMin *= (1 - myLaneDiscipline);
    1580              :             }
    1581    489191526 :             double relativeGain = (vMin - defaultNextSpeed) / MAX2(vMin, RELGAIN_NORMALIZATION_MIN_SPEED);
    1582    345983018 :             double currentLatDist = sublaneSides[i] - rightVehSide;
    1583    345983018 :             if ((laneOffset == 0 && (currentLatDist > maxLatDist || currentLatDist < minLatDist))
    1584    345983018 :                     || (laneOffset < 0 && currentLatDist > maxLatDist)
    1585    338972785 :                     || (laneOffset > 0 && currentLatDist < minLatDist)) {
    1586              : #ifdef DEBUG_WANTSCHANGE
    1587              :                 if (gDebugFlag2) {
    1588              :                     std::cout << "      i=" << i << " currentLatDist=" << currentLatDist << " outOfBounds\n";
    1589              :                 }
    1590              : #endif
    1591     15401379 :                 continue;
    1592              :             }
    1593              :             currentLatDist = MIN2(MAX2(currentLatDist, minLatDist), maxLatDist);
    1594    330581639 :             if (currentLatDist > 0 && myVehicle.getLane()->getBidiLane() != nullptr) {
    1595              :                 // penalize overtaking on the left if the lane is used in both
    1596              :                 // directions
    1597       224853 :                 relativeGain *= 0.5;
    1598              :             }
    1599              :             // @note only consider change if it is compatible with the current direction (same sign or laneOffset == 0)
    1600    330581639 :             if (relativeGain > maxGain && currentLatDist * laneOffset >= 0) {
    1601              :                 maxGain = relativeGain;
    1602    125512918 :                 if (maxGain > GAIN_PERCEPTION_THRESHOLD) {
    1603              :                     sublaneCompact = i;
    1604      7992420 :                     latDist = currentLatDist;
    1605              : #ifdef DEBUG_WANTSCHANGE
    1606              :                     if (gDebugFlag2) {
    1607              :                         std::cout << "      i=" << i << " vMin=" << vMin << " newLatDist=" << latDist << " relGain=" << relativeGain << "\n";
    1608              :                     }
    1609              : #endif
    1610              :                 }
    1611              :             } else {
    1612              :                 // if anticipated gains to the left are higher then to the right and current gains are equal, prefer left
    1613    205068721 :                 if (currentLatDist > 0
    1614              :                         //&& latDist < 0 // #7184 compensates for #7185
    1615    137326453 :                         && mySpeedGainProbabilityLeft > mySpeedGainProbabilityRight
    1616     35300165 :                         && relativeGain > GAIN_PERCEPTION_THRESHOLD
    1617      3573218 :                         && maxGain - relativeGain < NUMERICAL_EPS) {
    1618      2867241 :                     latDist = currentLatDist;
    1619              :                 }
    1620              :             }
    1621              : #ifdef DEBUG_WANTSCHANGE
    1622              :             if (gDebugFlag2) {
    1623              :                 std::cout << "    i=" << i << " rightmostOnEdge=" << rightmostOnEdge << " vMin=" << vMin << " relGain=" << relativeGain << " sublaneCompact=" << sublaneCompact << " curLatDist=" << currentLatDist << "\n";
    1624              :             }
    1625              : #endif
    1626    330581639 :             if (currentLatDist < -NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) {
    1627              :                 maxGainRight = MAX2(maxGainRight, relativeGain);
    1628    164393797 :             } else if (currentLatDist > NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) {
    1629              :                 maxGainLeft = MAX2(maxGainLeft, relativeGain);
    1630              :             }
    1631    330581639 :             const double subAlignDist = sublaneSides[i] - rightVehSide;
    1632    330581639 :             if (fabs(subAlignDist) < fabs(latDistNice)) {
    1633              :                 latDistNice = subAlignDist;
    1634              : #ifdef DEBUG_WANTSCHANGE
    1635              :                 if (gDebugFlag2) std::cout
    1636              :                             << "    nicest sublane=" << i
    1637              :                             << " side=" << sublaneSides[i]
    1638              :                             << " rightSide=" << rightVehSide
    1639              :                             << " latDistNice=" << latDistNice
    1640              :                             << " maxGainR=" << (maxGainRight == -std::numeric_limits<double>::max() ? "n/a" : toString(maxGainRight))
    1641              :                             << " maxGainL=" << (maxGainLeft == -std::numeric_limits<double>::max() ? "n/a" : toString(maxGainLeft))
    1642              :                             << "\n";
    1643              : #endif
    1644              :             }
    1645              :         }
    1646              :     }
    1647              :     // updated change probabilities
    1648    101292079 :     if (maxGainRight != -std::numeric_limits<double>::max()) {
    1649              : #ifdef DEBUG_WANTSCHANGE
    1650              :         if (gDebugFlag2) {
    1651              :             std::cout << "  speedGainR_old=" << mySpeedGainProbabilityRight;
    1652              :         }
    1653              : #endif
    1654     96521825 :         mySpeedGainProbabilityRight += myVehicle.getActionStepLengthSecs() * maxGainRight;
    1655              : #ifdef DEBUG_WANTSCHANGE
    1656              :         if (gDebugFlag2) {
    1657              :             std::cout << "  speedGainR_new=" << mySpeedGainProbabilityRight << "\n";
    1658              :         }
    1659              : #endif
    1660              :     }
    1661    101292079 :     if (maxGainLeft != -std::numeric_limits<double>::max()) {
    1662              : #ifdef DEBUG_WANTSCHANGE
    1663              :         if (gDebugFlag2) {
    1664              :             std::cout << "  speedGainL_old=" << mySpeedGainProbabilityLeft;
    1665              :         }
    1666              : #endif
    1667     94241743 :         mySpeedGainProbabilityLeft += myVehicle.getActionStepLengthSecs() * maxGainLeft;
    1668              : #ifdef DEBUG_WANTSCHANGE
    1669              :         if (gDebugFlag2) {
    1670              :             std::cout << "  speedGainL_new=" << mySpeedGainProbabilityLeft << "\n";
    1671              :         }
    1672              : #endif
    1673              :     }
    1674              :     // decay if there is no reason for or against changing (only if we have enough information)
    1675    101292079 :     if ((fabs(maxGainRight) < NUMERICAL_EPS || maxGainRight == -std::numeric_limits<double>::max())
    1676     95759110 :             && (right || (alternatives & LCA_RIGHT) == 0)) {
    1677     79448190 :         mySpeedGainProbabilityRight *= pow(SPEEDGAIN_DECAY_FACTOR, myVehicle.getActionStepLengthSecs());
    1678              :     }
    1679    101292079 :     if ((fabs(maxGainLeft) < NUMERICAL_EPS || maxGainLeft == -std::numeric_limits<double>::max())
    1680     92377200 :             && (left || (alternatives & LCA_LEFT) == 0)) {
    1681     72222144 :         mySpeedGainProbabilityLeft *= pow(SPEEDGAIN_DECAY_FACTOR, myVehicle.getActionStepLengthSecs());
    1682              :     }
    1683              : 
    1684              : 
    1685              : #ifdef DEBUG_WANTSCHANGE
    1686              :     if (gDebugFlag2) std::cout << SIMTIME
    1687              :                                    << " veh=" << myVehicle.getID()
    1688              :                                    << " defaultNextSpeed=" << defaultNextSpeed
    1689              :                                    << " maxGain=" << maxGain
    1690              :                                    << " maxGainRight=" << maxGainRight
    1691              :                                    << " maxGainLeft=" << maxGainLeft
    1692              :                                    << " probRight=" << mySpeedGainProbabilityRight
    1693              :                                    << " probLeft=" << mySpeedGainProbabilityLeft
    1694              :                                    << " latDist=" << latDist
    1695              :                                    << " latDistNice=" << latDistNice
    1696              :                                    << " sublaneCompact=" << sublaneCompact
    1697              :                                    << "\n";
    1698              : #endif
    1699              : 
    1700    101292079 :     if (!left) {
    1701              :         // ONLY FOR CHANGING TO THE RIGHT
    1702              :         // start keepRight maneuver when no speed loss is expected and continue
    1703              :         // started maneuvers if the loss isn't too big
    1704     90558168 :         if (right && myVehicle.getSpeed() > 0 && (maxGainRight >= 0
    1705       143345 :                 || ((myPreviousState & LCA_KEEPRIGHT) != 0 && maxGainRight >= -myKeepRightParam))) {
    1706              :             // honor the obligation to keep right (Rechtsfahrgebot)
    1707      8559772 :             const double vMax = myVehicle.getLane()->getVehicleMaxSpeed(&myVehicle);
    1708      8559772 :             const double roadSpeedFactor = vMax / myVehicle.getLane()->getSpeedLimit(); // differse from speedFactor if vMax < speedLimit
    1709              :             double acceptanceTime;
    1710      8559772 :             if (myKeepRightAcceptanceTime == -1) {
    1711              :                 // legacy behavior: scale acceptance time with current speed and
    1712              :                 // use old hard-coded constant
    1713     17119010 :                 acceptanceTime = 7 * roadSpeedFactor * MAX2(1.0, myVehicle.getSpeed());
    1714              :             } else {
    1715          267 :                 acceptanceTime = myKeepRightAcceptanceTime * roadSpeedFactor;
    1716          267 :                 if (followers.hasVehicles()) {
    1717              :                     // reduce acceptanceTime if a follower vehicle is faster or wants to drive faster
    1718              :                     double minFactor = 1.0;
    1719          220 :                     for (int i = 0; i < followers.numSublanes(); ++i) {
    1720          176 :                         CLeaderDist follower = followers[i];
    1721          352 :                         if (follower.first != nullptr && follower.second < 2 * follower.first->getCarFollowModel().brakeGap(follower.first->getSpeed())) {
    1722          176 :                             if (follower.first->getSpeed() >= myVehicle.getSpeed()) {
    1723          352 :                                 double factor = MAX2(1.0, myVehicle.getSpeed()) / MAX2(1.0, follower.first->getSpeed());
    1724          176 :                                 const double fRSF = follower.first->getLane()->getVehicleMaxSpeed(follower.first) / follower.first->getLane()->getSpeedLimit();
    1725          176 :                                 if (fRSF > roadSpeedFactor) {
    1726          100 :                                     factor /= fRSF;
    1727              :                                 }
    1728          176 :                                 if (factor < minFactor) {
    1729              :                                     minFactor = factor;
    1730              :                                 }
    1731              :                             }
    1732              :                         }
    1733              :                     }
    1734           44 :                     acceptanceTime *= minFactor;
    1735              :                 }
    1736              :             }
    1737      8559772 :             double fullSpeedGap = MAX2(0., neighDist - myVehicle.getCarFollowModel().brakeGap(vMax));
    1738      8559772 :             double fullSpeedDrivingSeconds = MIN2(acceptanceTime, fullSpeedGap / vMax);
    1739      8559772 :             CLeaderDist neighLead = getSlowest(neighLeaders);
    1740      8559772 :             if (neighLead.first != 0 && neighLead.first->getSpeed() < vMax) {
    1741      7081120 :                 fullSpeedGap = MAX2(0., MIN2(fullSpeedGap,
    1742      7081120 :                                              neighLead.second - myVehicle.getCarFollowModel().getSecureGap(&myVehicle, neighLead.first,
    1743      7081120 :                                                      vMax, neighLead.first->getSpeed(), neighLead.first->getCarFollowModel().getMaxDecel())));
    1744      7081120 :                 fullSpeedDrivingSeconds = MIN2(fullSpeedDrivingSeconds, fullSpeedGap / (vMax - neighLead.first->getSpeed()));
    1745              :             }
    1746      8559772 :             const double deltaProb = (myChangeProbThresholdRight * (fullSpeedDrivingSeconds / acceptanceTime) / KEEP_RIGHT_TIME) * myVehicle.getActionStepLengthSecs();
    1747      8559772 :             const bool isSlide = preventSliding(latLaneDist);
    1748              :             // stay below threshold
    1749      9654766 :             if (!isSlide || !wantsKeepRight(myKeepRightProbability + deltaProb)) {
    1750      8523163 :                 myKeepRightProbability += deltaProb;
    1751              :             }
    1752              : 
    1753              : #ifdef DEBUG_WANTSCHANGE
    1754              :             if (gDebugFlag2) {
    1755              :                 std::cout << STEPS2TIME(currentTime)
    1756              :                           << " considering keepRight:"
    1757              :                           << " vMax=" << vMax
    1758              :                           << " neighDist=" << neighDist
    1759              :                           << " brakeGap=" << myVehicle.getCarFollowModel().brakeGap(myVehicle.getSpeed())
    1760              :                           << " leaderSpeed=" << (neighLead.first == 0 ? -1 : neighLead.first->getSpeed())
    1761              :                           << " secGap=" << (neighLead.first == 0 ? -1 : myVehicle.getCarFollowModel().getSecureGap(&myVehicle, neighLead.first,
    1762              :                                             myVehicle.getSpeed(), neighLead.first->getSpeed(), neighLead.first->getCarFollowModel().getMaxDecel()))
    1763              :                           << " acceptanceTime=" << acceptanceTime
    1764              :                           << " fullSpeedGap=" << fullSpeedGap
    1765              :                           << " fullSpeedDrivingSeconds=" << fullSpeedDrivingSeconds
    1766              :                           << " dProb=" << deltaProb
    1767              :                           << " isSlide=" << isSlide
    1768              :                           << " keepRight=" << myKeepRightProbability
    1769              :                           << " speedGainL=" << mySpeedGainProbabilityLeft
    1770              :                           << "\n";
    1771              :             }
    1772              : #endif
    1773      8559772 :             if (wantsKeepRight(myKeepRightProbability)
    1774              :                     /*&& latLaneDist <= -NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()*/) {
    1775       538737 :                 ret |= LCA_KEEPRIGHT;
    1776              :                 assert(myVehicle.getLane()->getIndex() > neighLane.getIndex() || isOpposite());
    1777       538737 :                 if (!cancelRequest(ret | LCA_RIGHT, laneOffset)) {
    1778       537790 :                     latDist = latLaneDist;
    1779       537790 :                     maneuverDist = latLaneDist;
    1780       537790 :                     blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    1781              :                                             leaders, followers, blockers,
    1782              :                                             neighLeaders, neighFollowers, neighBlockers);
    1783       537790 :                     return ret;
    1784              :                 } else {
    1785              :                     ret &= ~LCA_KEEPRIGHT;
    1786              :                 }
    1787              :             }
    1788              :         }
    1789              : 
    1790     90020378 :         const double bidiRightFactor = myVehicle.getLane()->getBidiLane() == nullptr && !isOpposite() ? 1 : 0.05;
    1791              : #ifdef DEBUG_WANTSCHANGE
    1792              :         if (gDebugFlag2) {
    1793              :             std::cout << STEPS2TIME(currentTime)
    1794              :                       << " speedGainR=" << mySpeedGainProbabilityRight
    1795              :                       << " speedGainL=" << mySpeedGainProbabilityLeft
    1796              :                       << " neighDist=" << neighDist
    1797              :                       << " neighTime=" << neighDist / MAX2(.1, myVehicle.getSpeed())
    1798              :                       << " rThresh=" << myChangeProbThresholdRight
    1799              :                       << " rThresh2=" << myChangeProbThresholdRight* bidiRightFactor
    1800              :                       << " latDist=" << latDist
    1801              :                       << "\n";
    1802              :         }
    1803              : #endif
    1804              : 
    1805              :         // make changing on the right more attractive on bidi edges
    1806      2759047 :         if (latDist < 0 && mySpeedGainProbabilityRight >= myChangeProbThresholdRight * bidiRightFactor
    1807     92105674 :                 && neighDist / MAX2(.1, myVehicle.getSpeed()) > mySpeedGainRemainTime) {
    1808      1002685 :             ret |= LCA_SPEEDGAIN;
    1809      1002685 :             if (!cancelRequest(ret | getLCA(ret, latDist), laneOffset)) {
    1810       989970 :                 int blockedFully = 0;
    1811       989970 :                 maneuverDist = latDist;
    1812       989970 :                 blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    1813              :                                         leaders, followers, blockers,
    1814              :                                         neighLeaders, neighFollowers, neighBlockers,
    1815              :                                         nullptr, nullptr, false, 0, &blockedFully);
    1816              :                 //commitManoeuvre(blocked, blockedFully, leaders, neighLeaders, neighLane);
    1817              :                 return ret;
    1818              :             } else {
    1819              :                 // @note: restore ret so subsequent calls to cancelRequest work correctly
    1820        12715 :                 latDist = 0;
    1821              :                 ret &= ~LCA_SPEEDGAIN;
    1822              :             }
    1823              :         }
    1824              :     }
    1825     99764319 :     if (!right || isOpposite()) {
    1826              : 
    1827     90536951 :         const bool stayInLane = myVehicle.getLateralPositionOnLane() + latDist < 0.5 * myVehicle.getLane()->getWidth();
    1828              : #ifdef DEBUG_WANTSCHANGE
    1829              :         if (gDebugFlag2) {
    1830              :             std::cout << STEPS2TIME(currentTime)
    1831              :                       << " speedGainL=" << mySpeedGainProbabilityLeft
    1832              :                       << " speedGainR=" << mySpeedGainProbabilityRight
    1833              :                       << " latDist=" << latDist
    1834              :                       << " neighDist=" << neighDist
    1835              :                       << " neighTime=" << neighDist / MAX2(.1, myVehicle.getSpeed())
    1836              :                       << " lThresh=" << myChangeProbThresholdLeft
    1837              :                       << " stayInLane=" << stayInLane
    1838              :                       << "\n";
    1839              :         }
    1840              : #endif
    1841              : 
    1842     90536951 :         if (latDist > 0 && mySpeedGainProbabilityLeft > myChangeProbThresholdLeft &&
    1843              :                 // if we leave our lane, we should be able to stay in the new
    1844              :                 // lane for some time
    1845      3974654 :                 (stayInLane || neighDist / MAX2(.1, myVehicle.getSpeed()) > mySpeedGainRemainTime)) {
    1846      2765097 :             ret |= LCA_SPEEDGAIN;
    1847      2765097 :             if (!cancelRequest(ret + getLCA(ret, latDist), laneOffset)) {
    1848      2746072 :                 int blockedFully = 0;
    1849      2746072 :                 maneuverDist = latDist;
    1850      2746072 :                 blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    1851              :                                         leaders, followers, blockers,
    1852              :                                         neighLeaders, neighFollowers, neighBlockers,
    1853              :                                         nullptr, nullptr, false, 0, &blockedFully);
    1854              :                 //commitManoeuvre(blocked, blockedFully, leaders, neighLeaders, neighLane);
    1855              :                 return ret;
    1856              :             } else {
    1857        19025 :                 latDist = 0;
    1858              :                 ret &= ~LCA_SPEEDGAIN;
    1859              :             }
    1860              :         }
    1861              :     }
    1862              : 
    1863              :     double latDistSublane = 0.;
    1864     97018247 :     const double halfLaneWidth = myVehicle.getLane()->getWidth() * 0.5;
    1865     97018247 :     const double halfVehWidth = getWidth() * 0.5;
    1866     97018247 :     if (myVehicle.getParameter().arrivalPosLatProcedure != ArrivalPosLatDefinition::DEFAULT
    1867         4816 :             && myVehicle.getRoute().getLastEdge() == &myVehicle.getLane()->getEdge()
    1868         4816 :             && bestLaneOffset == 0
    1869     97023063 :             && (myVehicle.getArrivalPos() - getForwardPos()) < ARRIVALPOS_LAT_THRESHOLD) {
    1870              :         // vehicle is on its final edge, on the correct lane and close to
    1871              :         // its arrival position. Change to the desired lateral position
    1872          891 :         switch (myVehicle.getParameter().arrivalPosLatProcedure) {
    1873            0 :             case ArrivalPosLatDefinition::GIVEN:
    1874            0 :                 latDistSublane = myVehicle.getParameter().arrivalPosLat - myVehicle.getLateralPositionOnLane();
    1875            0 :                 break;
    1876          891 :             case ArrivalPosLatDefinition::RIGHT:
    1877          891 :                 latDistSublane = -halfLaneWidth + halfVehWidth - myVehicle.getLateralPositionOnLane();
    1878          891 :                 break;
    1879            0 :             case ArrivalPosLatDefinition::CENTER:
    1880            0 :                 latDistSublane = -myVehicle.getLateralPositionOnLane();
    1881            0 :                 break;
    1882            0 :             case ArrivalPosLatDefinition::LEFT:
    1883            0 :                 latDistSublane = halfLaneWidth - halfVehWidth - myVehicle.getLateralPositionOnLane();
    1884            0 :                 break;
    1885              :             default:
    1886              :                 assert(false);
    1887              :         }
    1888              : #ifdef DEBUG_WANTSCHANGE
    1889              :         if (gDebugFlag2) std::cout << SIMTIME
    1890              :                                        << " arrivalPosLatProcedure=" << (int)myVehicle.getParameter().arrivalPosLatProcedure
    1891              :                                        << " arrivalPosLat=" << myVehicle.getParameter().arrivalPosLat << "\n";
    1892              : #endif
    1893              : 
    1894              :     } else {
    1895              : 
    1896     97017356 :         LatAlignmentDefinition align = getDesiredAlignment();
    1897     97017356 :         switch (align) {
    1898      4152704 :             case LatAlignmentDefinition::RIGHT:
    1899      4152704 :                 latDistSublane = -halfLaneWidth + halfVehWidth - getPosLat();
    1900      4152704 :                 break;
    1901       155447 :             case LatAlignmentDefinition::LEFT:
    1902       155447 :                 latDistSublane = halfLaneWidth - halfVehWidth - getPosLat();
    1903       155447 :                 break;
    1904     89472410 :             case LatAlignmentDefinition::CENTER:
    1905              :             case LatAlignmentDefinition::DEFAULT:
    1906     89472410 :                 latDistSublane = -getPosLat();
    1907     89472410 :                 break;
    1908              :             case LatAlignmentDefinition::NICE:
    1909              :                 latDistSublane = latDistNice;
    1910              :                 break;
    1911      2936076 :             case LatAlignmentDefinition::COMPACT:
    1912      2936076 :                 latDistSublane = sublaneSides[sublaneCompact] - rightVehSide;
    1913      2936076 :                 break;
    1914        28114 :             case LatAlignmentDefinition::ARBITRARY: {
    1915        28114 :                 latDistSublane = myVehicle.getLateralPositionOnLane() - getPosLat();
    1916        28114 :                 const double hLW = myVehicle.getLane()->getWidth() * 0.5;
    1917        28114 :                 const double posLat = myVehicle.getLateralPositionOnLane();
    1918        28114 :                 if (fabs(posLat) > hLW) {
    1919              :                     // vehicle is not within it's current lane
    1920           37 :                     if (posLat > 0) {
    1921           32 :                         latDistSublane -= (posLat - hLW);
    1922              :                     } else {
    1923            5 :                         latDistSublane += (-posLat - hLW);
    1924              :                     }
    1925              :                 } else {
    1926        28077 :                     const double edgeWidth = myVehicle.getCurrentEdge()->getWidth();
    1927        28077 :                     if (getWidth() < edgeWidth) {
    1928        28077 :                         if (rightVehSide < 0) {
    1929         2957 :                             latDistSublane -= rightVehSide;
    1930        25120 :                         } else if (leftVehSide > edgeWidth) {
    1931         1409 :                             latDistSublane -= leftVehSide - edgeWidth;
    1932              :                         }
    1933              :                     }
    1934              :                 }
    1935              :                 break;
    1936              :             }
    1937          441 :             case LatAlignmentDefinition::GIVEN: {
    1938              :                 // sublane alignment should not cause the vehicle to leave the lane
    1939          441 :                 const double hw = myVehicle.getLane()->getWidth() / 2 - NUMERICAL_EPS;
    1940          882 :                 const double offset = MAX2(-hw, MIN2(hw, myVehicle.getVehicleType().getPreferredLateralAlignmentOffset()));
    1941          441 :                 latDistSublane = -getPosLat() + offset;
    1942              :             }
    1943          441 :             break;
    1944              :             default:
    1945              :                 break;
    1946              :         }
    1947              :     }
    1948              :     // only factor in preferred lateral alignment if there is no speedGain motivation or it runs in the same direction
    1949     97018247 :     if (fabs(latDist) <= NUMERICAL_EPS * myVehicle.getActionStepLengthSecs() ||
    1950      2889924 :             latDistSublane * latDist > 0) {
    1951              : 
    1952              : #if defined(DEBUG_WANTSCHANGE) || defined(DEBUG_STATE) || defined(DEBUG_MANEUVER)
    1953              :         if (gDebugFlag2) std::cout << SIMTIME
    1954              :                                        << " alignment=" << toString(myVehicle.getVehicleType().getPreferredLateralAlignment())
    1955              :                                        << " mySpeedGainR=" << mySpeedGainProbabilityRight
    1956              :                                        << " mySpeedGainL=" << mySpeedGainProbabilityLeft
    1957              :                                        << " latDist=" << latDist
    1958              :                                        << " latDistSublane=" << latDistSublane
    1959              :                                        << " relGainSublane=" << computeSpeedGain(latDistSublane, defaultNextSpeed)
    1960              :                                        << " maneuverDist=" << maneuverDist
    1961              :                                        << " myCanChangeFully=" << myCanChangeFully
    1962              :                                        << " myTurnAlignmentDist=" << myTurnAlignmentDist
    1963              :                                        << " nextTurn=" << myVehicle.getNextTurn().first << ":" << toString(myVehicle.getNextTurn().second)
    1964              :                                        << " prevState=" << toString((LaneChangeAction)myPreviousState)
    1965              :                                        << "\n";
    1966              : #endif
    1967              : 
    1968     10103679 :         if ((latDistSublane < 0 && mySpeedGainProbabilityRight < mySpeedLossProbThreshold)
    1969     94494442 :                 || (latDistSublane > 0 && mySpeedGainProbabilityLeft < mySpeedLossProbThreshold)
    1970    187499481 :                 || computeSpeedGain(latDistSublane, defaultNextSpeed) < -mySublaneParam) {
    1971              :             // do not risk losing speed
    1972              : #if defined(DEBUG_WANTSCHANGE)
    1973              :             if (gDebugFlag2) std::cout << "   aborting sublane change to avoid speed loss (mySpeedLossProbThreshold=" << mySpeedLossProbThreshold
    1974              :                                            << " speedGain=" << computeSpeedGain(latDistSublane, defaultNextSpeed) << ")\n";
    1975              : #endif
    1976              :             latDistSublane = 0;
    1977              :         }
    1978              :         // Ignore preferred lateral alignment if we are in the middle of an unfinished non-alignment maneuver into the opposite direction
    1979     95346861 :         if (!myCanChangeFully
    1980      7411260 :                 && (myPreviousState & (LCA_STRATEGIC | LCA_COOPERATIVE | LCA_KEEPRIGHT | LCA_SPEEDGAIN)) != 0
    1981    100654513 :                 && ((getManeuverDist() < 0 && latDistSublane > 0) || (getManeuverDist() > 0 && latDistSublane < 0))) {
    1982              : #if defined(DEBUG_WANTSCHANGE)
    1983              :             if (gDebugFlag2) {
    1984              :                 std::cout << "   aborting sublane change due to prior maneuver\n";
    1985              :             }
    1986              : #endif
    1987              :             latDistSublane = 0;
    1988              :         }
    1989     95346861 :         latDist = latDistSublane * (isOpposite() ? -1 : 1);
    1990              :         // XXX first compute preferred adaptation and then override with speed
    1991              :         // (this way adaptation is still done if changing for speedgain is
    1992              :         // blocked)
    1993     95346861 :         if (fabs(latDist) >= NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) {
    1994              : #ifdef DEBUG_WANTSCHANGE
    1995              :             if (gDebugFlag2) std::cout << SIMTIME
    1996              :                                            << " adapting to preferred alignment=" << toString(myVehicle.getVehicleType().getPreferredLateralAlignment())
    1997              :                                            << " latDist=" << latDist
    1998              :                                            << "\n";
    1999              : #endif
    2000      8170851 :             ret |= LCA_SUBLANE;
    2001              :             // include prior motivation when sublane-change is part of finishing an ongoing maneuver in the same direction
    2002      8170851 :             if (getPreviousManeuverDist() * latDist > 0) {
    2003       921977 :                 int priorReason = (myPreviousState & LCA_CHANGE_REASONS & ~LCA_SUBLANE);
    2004       921977 :                 ret |= priorReason;
    2005              : #ifdef DEBUG_WANTSCHANGE
    2006              :                 if (gDebugFlag2 && priorReason != 0) std::cout << "   including prior reason " << toString((LaneChangeAction)priorReason)
    2007              :                             << " prevManeuverDist=" << getPreviousManeuverDist() << "\n";
    2008              : #endif
    2009              :             }
    2010      8170851 :             if (!cancelRequest(ret + getLCA(ret, latDist), laneOffset)) {
    2011      8167243 :                 maneuverDist = latDist;
    2012      8167243 :                 blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset,
    2013              :                                         leaders, followers, blockers,
    2014              :                                         neighLeaders, neighFollowers, neighBlockers);
    2015      8167243 :                 return ret;
    2016              :             } else {
    2017         3608 :                 ret &= ~LCA_SUBLANE;
    2018              :             }
    2019              :         } else {
    2020     87176010 :             return ret | LCA_SUBLANE | LCA_STAY;
    2021              :         }
    2022              :     }
    2023      1674994 :     latDist = 0;
    2024              : 
    2025              : 
    2026              :     // --------
    2027              :     /*
    2028              :     if (changeToBest && bestLaneOffset == curr.bestLaneOffset && laneOffset != 0
    2029              :             && (right
    2030              :                 ? mySpeedGainProbabilityRight > MAX2(0., mySpeedGainProbabilityLeft)
    2031              :                 : mySpeedGainProbabilityLeft  > MAX2(0., mySpeedGainProbabilityRight))) {
    2032              :         // change towards the correct lane, speedwise it does not hurt
    2033              :         ret |= LCA_STRATEGIC;
    2034              :         if (!cancelRequest(ret, laneOffset)) {
    2035              :             latDist = latLaneDist;
    2036              :             blocked = checkBlocking(neighLane, latDist, laneOffset,
    2037              :                     leaders, followers, blockers,
    2038              :                     neighLeaders, neighFollowers, neighBlockers);
    2039              :             return ret;
    2040              :         }
    2041              :     }
    2042              :     */
    2043              : #ifdef DEBUG_WANTSCHANGE
    2044              :     if (gDebugFlag2) {
    2045              :         std::cout << STEPS2TIME(currentTime)
    2046              :                   << " veh=" << myVehicle.getID()
    2047              :                   << " mySpeedGainR=" << mySpeedGainProbabilityRight
    2048              :                   << " mySpeedGainL=" << mySpeedGainProbabilityLeft
    2049              :                   << " myKeepRight=" << myKeepRightProbability
    2050              :                   << "\n";
    2051              :     }
    2052              : #endif
    2053      1674994 :     return ret;
    2054    101292079 : }
    2055              : 
    2056              : 
    2057              : int
    2058    231131938 : MSLCM_SL2015::slowDownForBlocked(MSVehicle** blocked, int state) {
    2059              :     //  if this vehicle is blocking someone in front, we maybe decelerate to let him in
    2060    231131938 :     if ((*blocked) != nullptr) {
    2061     14776930 :         double gap = (*blocked)->getPositionOnLane() - (*blocked)->getVehicleType().getLength() - myVehicle.getPositionOnLane() - myVehicle.getVehicleType().getMinGap();
    2062              : #ifdef DEBUG_SLOWDOWN
    2063              :         if (gDebugFlag2) {
    2064              :             std::cout << SIMTIME
    2065              :                       << " veh=" << myVehicle.getID()
    2066              :                       << " blocked=" << Named::getIDSecure(*blocked)
    2067              :                       << " gap=" << gap
    2068              :                       << "\n";
    2069              :         }
    2070              : #endif
    2071     14776930 :         if (gap > POSITION_EPS) {
    2072              :             //const bool blockedWantsUrgentRight = (((*blocked)->getLaneChangeModel().getOwnState() & LCA_RIGHT != 0)
    2073              :             //    && ((*blocked)->getLaneChangeModel().getOwnState() & LCA_URGENT != 0));
    2074              : 
    2075     11944648 :             if (myVehicle.getSpeed() < myVehicle.getCarFollowModel().getMaxDecel()
    2076              :                     //|| blockedWantsUrgentRight  // VARIANT_10 (helpblockedRight)
    2077              :                ) {
    2078     10228904 :                 if ((*blocked)->getSpeed() < SUMO_const_haltingSpeed) {
    2079      5825107 :                     state |= LCA_AMBACKBLOCKER_STANDING;
    2080              :                 } else {
    2081      4403797 :                     state |= LCA_AMBACKBLOCKER;
    2082              :                 }
    2083     20457808 :                 addLCSpeedAdvice(getCarFollowModel().followSpeed(
    2084     10228904 :                                      &myVehicle, myVehicle.getSpeed(),
    2085     10228904 :                                      (gap - POSITION_EPS), (*blocked)->getSpeed(),
    2086     10228904 :                                      (*blocked)->getCarFollowModel().getMaxDecel()), false);
    2087              :                 //(*blocked) = 0; // VARIANT_14 (furtherBlock)
    2088              :             }
    2089              :         }
    2090              :     }
    2091    231131938 :     return state;
    2092              : }
    2093              : 
    2094              : 
    2095              : bool
    2096       106728 : MSLCM_SL2015::isBidi(const MSLane* lane) const {
    2097       106728 :     if (!MSNet::getInstance()->hasBidiEdges()) {
    2098              :         return false;
    2099              :     }
    2100       106728 :     if (lane == myVehicle.getLane()->getBidiLane()) {
    2101              :         return true;
    2102              :     }
    2103       204753 :     for (const MSLane* cand : myVehicle.getBestLanesContinuation()) {
    2104       178072 :         if (cand != nullptr && cand->getBidiLane() == lane) {
    2105              :             return true;
    2106              :         }
    2107              :     }
    2108              :     return false;
    2109              : }
    2110              : 
    2111              : void
    2112    125273320 : MSLCM_SL2015::updateExpectedSublaneSpeeds(const MSLeaderDistanceInfo& ahead, int sublaneOffset, int laneIndex) {
    2113    125273320 :     const std::vector<MSLane*>& lanes = myVehicle.getLane()->getEdge().getLanes();
    2114    125273320 :     const std::vector<MSVehicle::LaneQ>& preb = myVehicle.getBestLanes();
    2115    125273320 :     const MSLane* lane = isOpposite() ? myVehicle.getLane()->getParallelOpposite() : lanes[laneIndex];
    2116    125273320 :     const MSLane* next = myVehicle.getBestLanesContinuation().size() > 1 ? myVehicle.getBestLanesContinuation()[1] : nullptr;
    2117    104198922 :     const MSLink* link = next != nullptr ? lane->getLinkTo(next) : nullptr;
    2118    125273320 :     const double shift = link != nullptr ? link->getLateralShift() + 0.5 * (lane->getWidth() - next->getWidth()) : 0;
    2119    125273320 :     const MSLane* bidi = myVehicle.getLane()->getBidiLane();
    2120    125273320 :     const double vMax = lane->getVehicleMaxSpeed(&myVehicle);
    2121              :     assert(preb.size() == lanes.size() || isOpposite());
    2122              : #ifdef DEBUG_EXPECTED_SLSPEED
    2123              :     if (DEBUG_COND) {
    2124              :         std::cout << SIMTIME << " veh=" << myVehicle.getID() << " updateExpectedSublaneSpeeds opposite=" << isOpposite()
    2125              :                   << " sublaneOffset=" << sublaneOffset << " laneIndex=" << laneIndex << " lane=" << lane->getID() << " ahead=" << ahead.toString() << "\n";
    2126              :     }
    2127              : #endif
    2128              : 
    2129    651110198 :     for (int sublane = 0; sublane < (int)ahead.numSublanes(); ++sublane) {
    2130    525836878 :         const int edgeSublane = sublane + sublaneOffset;
    2131    525836878 :         if (edgeSublane >= (int)myExpectedSublaneSpeeds.size()) {
    2132              :             // this may happen if a sibling lane is wider than the changer lane
    2133          170 :             continue;
    2134              :         }
    2135    525836708 :         if (link != nullptr && lane->getWidth() > next->getWidth() + NUMERICAL_EPS && MSGlobals::gLateralResolution > 0 && sublaneEnds(sublane, next, shift)) {
    2136              :             // sublane does not continue, discourage from use
    2137      2917617 :             myExpectedSublaneSpeeds[edgeSublane] = 0;
    2138              : #ifdef DEBUG_EXPECTED_SLSPEED
    2139              :             if (DEBUG_COND) {
    2140              :                 std::cout << "   updateExpectedSublaneSpeeds sublane=" << sublane << " doesNotContinue\n";
    2141              :             }
    2142              : #endif
    2143      2917617 :             continue;
    2144    522919091 :         } else if (lane->allowsVehicleClass(myVehicle.getVehicleType().getVehicleClass())) {
    2145              :             // lane allowed, find potential leaders and compute safe speeds
    2146              :             // XXX anticipate future braking if leader has a lower speed than myVehicle
    2147    517069534 :             const MSVehicle* leader = ahead[sublane].first;
    2148    517069534 :             const double gap = ahead[sublane].second;
    2149              :             double vSafe;
    2150    517069534 :             if (leader == nullptr) {
    2151    105111045 :                 if (hasBlueLight()) {
    2152              :                     // can continue from any lane if necessary
    2153              :                     vSafe = vMax;
    2154              :                 } else {
    2155    104880381 :                     const int prebIndex = isOpposite() ? (int)preb.size() - 1 : laneIndex;
    2156    104880381 :                     const double dist = preb[prebIndex].length - myVehicle.getPositionOnLane();
    2157    104880381 :                     vSafe = getCarFollowModel().followSpeed(&myVehicle, vMax, dist, 0, 0);
    2158              :                 }
    2159    411958489 :             } else if (bidi != nullptr && leader->getLane()->getBidiLane() != nullptr && isBidi(leader->getLane())) {
    2160              :                 // oncoming
    2161        80047 :                 if (gap < (1 + mySpeedGainLookahead * 2) * (vMax + leader->getSpeed())) {
    2162              :                     vSafe = 0;
    2163              :                 } else {
    2164              :                     vSafe = vMax;
    2165              :                 }
    2166              : #ifdef DEBUG_EXPECTED_SLSPEED
    2167              :                 if (DEBUG_COND) {
    2168              :                     std::cout << SIMTIME << " updateExpectedSublaneSpeeds sublane=" << sublane << " leader=" << leader->getID() << " bidi=" << bidi->getID() << " gap=" << gap << " vSafe=" << vSafe << "\n";
    2169              :                 }
    2170              : #endif
    2171              :             } else {
    2172    411878442 :                 if (leader->getAcceleration() > 0.5 * leader->getCarFollowModel().getMaxAccel()) {
    2173              :                     // assume that the leader will continue accelerating to its maximum speed
    2174     47196589 :                     vSafe = leader->getLane()->getVehicleMaxSpeed(leader);
    2175              :                 } else {
    2176    364681853 :                     vSafe = getCarFollowModel().followSpeed(
    2177    364681853 :                                 &myVehicle, vMax, gap, leader->getSpeed(), leader->getCarFollowModel().getMaxDecel());
    2178              : #ifdef DEBUG_EXPECTED_SLSPEED
    2179              :                     if (DEBUG_COND) {
    2180              :                         std::cout << "   updateExpectedSublaneSpeeds edgeSublane=" << edgeSublane << " leader=" << leader->getID() << " gap=" << gap << " vSafe=" << vSafe << "\n";
    2181              :                     }
    2182              : #endif
    2183    364681853 :                     vSafe = forecastAverageSpeed(vSafe, vMax, gap, leader->getSpeed());
    2184              :                 }
    2185              :             }
    2186              :             // take pedestrians into account
    2187    517069534 :             if (lane->getEdge().getPersons().size() > 0 && lane->hasPedestrians()) {
    2188              :                 /// XXX this could be done faster by checking all sublanes at once (but would complicate the MSPModel API)
    2189              :                 double foeRight, foeLeft;
    2190       280452 :                 ahead.getSublaneBorders(sublane, 0, foeRight, foeLeft);
    2191              :                 // get all leaders ahead or overlapping
    2192       280452 :                 const PersonDist pedLeader = lane->nextBlocking(myVehicle.getPositionOnLane() - myVehicle.getVehicleType().getLength(), foeRight, foeLeft);
    2193       280452 :                 if (pedLeader.first != 0) {
    2194        77844 :                     const double pedGap = pedLeader.second - myVehicle.getVehicleType().getMinGap() - myVehicle.getVehicleType().getLength();
    2195              :                     // we do not know the walking direction here so we take the pedestrian speed as 0
    2196        77844 :                     vSafe = MIN2(getCarFollowModel().stopSpeed(&myVehicle, vMax, pedGap),
    2197              :                                  forecastAverageSpeed(vSafe, vMax, pedGap, 0));
    2198              : #ifdef DEBUG_EXPECTED_SLSPEED
    2199              :                     if (DEBUG_COND) {
    2200              :                         std::cout << "   updateExpectedSublaneSpeeds edgeSublane=" << edgeSublane << " pedLeader=" << pedLeader.first->getID() << " gap=" << pedGap << " vSafe=" << vSafe << "\n";
    2201              :                     }
    2202              : #endif
    2203              :                 }
    2204              :             }
    2205              :             // take bidi pedestrians into account
    2206    517069534 :             if (bidi != nullptr && bidi->getEdge().getPersons().size() > 0 && bidi->hasPedestrians()) {
    2207              :                 /// XXX this could be done faster by checking all sublanes at once (but would complicate the MSPModel API)
    2208              :                 double foeRight, foeLeft;
    2209         4277 :                 ahead.getSublaneBorders(sublane, 0, foeRight, foeLeft);
    2210         4277 :                 const double foeRightBidi = bidi->getWidth() - foeLeft;
    2211         4277 :                 const double foeLeftBidi = bidi->getWidth() - foeRight;
    2212              :                 // get all leaders ahead or overlapping
    2213         4277 :                 const double relativeBackPos = myVehicle.getLane()->getLength() - myVehicle.getPositionOnLane() + myVehicle.getLength();
    2214         4277 :                 const double stopTime = ceil(myVehicle.getSpeed() / myVehicle.getCarFollowModel().getMaxDecel());
    2215         4277 :                 PersonDist pedLeader = bidi->nextBlocking(relativeBackPos, foeRightBidi, foeLeftBidi, stopTime, true);
    2216         4277 :                 if (pedLeader.first != 0) {
    2217          719 :                     const double pedGap = pedLeader.second - myVehicle.getVehicleType().getMinGap() - myVehicle.getVehicleType().getLength();
    2218              :                     // we do not know the walking direction here so we take the pedestrian speed as 0
    2219          719 :                     vSafe = MIN2(getCarFollowModel().stopSpeed(&myVehicle, vMax, pedGap),
    2220              :                                  forecastAverageSpeed(vSafe, vMax, pedGap, 0));
    2221              : #ifdef DEBUG_EXPECTED_SLSPEED
    2222              :                     if (DEBUG_COND) {
    2223              :                         std::cout << "   updateExpectedSublaneSpeeds edgeSublane=" << edgeSublane << " pedLeader=" << pedLeader.first->getID() << " (bidi) gap=" << pedGap << " vSafe=" << vSafe << "\n";
    2224              :                     }
    2225              : #endif
    2226              :                 }
    2227              :             }
    2228              :             vSafe = MIN2(vMax, vSafe);
    2229              :             // forget old data when on the opposite side
    2230    517069534 :             const double memoryFactor = isOpposite() ? 0 : pow(SPEEDGAIN_MEMORY_FACTOR, myVehicle.getActionStepLengthSecs());
    2231    517069534 :             myExpectedSublaneSpeeds[edgeSublane] = memoryFactor * myExpectedSublaneSpeeds[edgeSublane] + (1 - memoryFactor) * vSafe;
    2232              :         } else {
    2233              :             // lane forbidden
    2234      5849557 :             myExpectedSublaneSpeeds[edgeSublane] = -1;
    2235              : #ifdef DEBUG_EXPECTED_SLSPEED
    2236              :             if (DEBUG_COND) {
    2237              :                 std::cout << "   updateExpectedSublaneSpeeds edgeSublane=" << edgeSublane << " lane " << lane->getID() << " forbidden\n";
    2238              :             }
    2239              : #endif
    2240              :         }
    2241              :     }
    2242              :     // XXX deal with leaders on subsequent lanes based on preb
    2243    125273320 : }
    2244              : 
    2245              : 
    2246              : bool
    2247      7759595 : MSLCM_SL2015::sublaneEnds(int i, const MSLane* next, double shift) {
    2248      7759595 :     const double side = i * MSGlobals::gLateralResolution + shift;
    2249              :     return ((side < -NUMERICAL_EPS
    2250           13 :                 && (next->getParallelLane(-1) == nullptr || !next->getParallelLane(-1)->allowsVehicleClass(myVehicle.getVClass())))
    2251      7759608 :             || (side + MSGlobals::gLateralResolution > next->getWidth()
    2252      6893730 :                 && (next->getParallelLane(1) == nullptr || !next->getParallelLane(1)->allowsVehicleClass(myVehicle.getVClass()))));
    2253              : }
    2254              : 
    2255              : 
    2256              : double
    2257    364760416 : MSLCM_SL2015::forecastAverageSpeed(double vSafe, double vMax, double gap, double vLeader) const {
    2258    364760416 :     const double deltaV = vMax - vLeader;
    2259    364760416 :     if (deltaV > 0 && gap / deltaV < mySpeedGainLookahead && mySpeedGainLookahead > 0) {
    2260              :         // anticipate future braking by computing the average
    2261              :         // speed over the next few seconds
    2262    211223357 :         const double foreCastTime = mySpeedGainLookahead * 2;
    2263              :         const double gapClosingTime = MAX2(0.0, gap / deltaV);
    2264    211223357 :         const double vSafe2 = (gapClosingTime * vSafe + (foreCastTime - gapClosingTime) * vLeader) / foreCastTime;
    2265              : #ifdef DEBUG_EXPECTED_SLSPEED
    2266              :         if (DEBUG_COND && vSafe2 != vSafe) {
    2267              :             std::cout << "     foreCastTime=" << foreCastTime << " gapClosingTime=" << gapClosingTime << " extrapolated vSafe=" << vSafe2 << "\n";
    2268              :         }
    2269              : #endif
    2270              :         vSafe = vSafe2;
    2271              :     }
    2272    364760416 :     return vSafe;
    2273              : }
    2274              : 
    2275              : 
    2276              : double
    2277     92152620 : MSLCM_SL2015::computeSpeedGain(double latDistSublane, double defaultNextSpeed) const {
    2278              :     double result = std::numeric_limits<double>::max();
    2279     92152620 :     const std::vector<double>& sublaneSides = myVehicle.getLane()->getEdge().getSubLaneSides();
    2280     92152620 :     const double vehWidth = getWidth();
    2281     92152620 :     const double rightVehSide = myVehicle.getCenterOnEdge() - vehWidth * 0.5 + latDistSublane;
    2282     92152620 :     const double leftVehSide = rightVehSide + vehWidth;
    2283    740158355 :     for (int i = 0; i < (int)sublaneSides.size(); ++i) {
    2284    648005735 :         const double leftSide = i + 1 < (int)sublaneSides.size() ? sublaneSides[i + 1] : MAX2(myVehicle.getLane()->getEdge().getWidth(), sublaneSides[i] + POSITION_EPS);
    2285    648005735 :         if (overlap(rightVehSide, leftVehSide, sublaneSides[i], leftSide)) {
    2286    343252711 :             result = MIN2(result, myExpectedSublaneSpeeds[i]);
    2287              :         }
    2288              :         //std::cout << "    i=" << i << " rightVehSide=" << rightVehSide << " leftVehSide=" << leftVehSide << " sublaneR=" << sublaneSides[i] << " sublaneL=" << leftSide << " overlap=" << overlap(rightVehSide, leftVehSide, sublaneSides[i], leftSide) << " speed=" << myExpectedSublaneSpeeds[i] << " result=" << result << "\n";
    2289              :     }
    2290     92152620 :     return result - defaultNextSpeed;
    2291     92152620 : }
    2292              : 
    2293              : 
    2294              : CLeaderDist
    2295      2207649 : MSLCM_SL2015::getLongest(const MSLeaderDistanceInfo& ldi) const {
    2296              :     int iMax = -1;
    2297              :     double maxLength = -1;
    2298     12267949 :     for (int i = 0; i < ldi.numSublanes(); ++i) {
    2299     10060300 :         const MSVehicle* veh = ldi[i].first;
    2300     10060300 :         if (veh) {
    2301      7589343 :             const double length = veh->getVehicleType().getLength();
    2302      7589343 :             if (length > maxLength && tieBrakeLeader(veh)) {
    2303              :                 maxLength = length;
    2304              :                 iMax = i;
    2305              :             }
    2306              :         }
    2307              :     }
    2308      2207649 :     return iMax >= 0 ? ldi[iMax] : std::make_pair(nullptr, -1);
    2309              : }
    2310              : 
    2311              : 
    2312              : bool
    2313      3612498 : MSLCM_SL2015::tieBrakeLeader(const MSVehicle* veh) const {
    2314              :     // tie braker if the leader is at the same lane position
    2315      3612498 :     return veh != nullptr && (veh->getPositionOnLane() != myVehicle.getPositionOnLane()
    2316         9462 :                               || veh->getSpeed() < myVehicle.getSpeed()
    2317         9319 :                               || &veh->getLane()->getEdge() != &myVehicle.getLane()->getEdge()
    2318         9316 :                               || veh->getLane()->getIndex() > myVehicle.getLane()->getIndex());
    2319              : }
    2320              : 
    2321              : 
    2322              : CLeaderDist
    2323     11414300 : MSLCM_SL2015::getSlowest(const MSLeaderDistanceInfo& ldi) {
    2324              :     int iMax = 0;
    2325              :     double minSpeed = std::numeric_limits<double>::max();
    2326     57605422 :     for (int i = 0; i < ldi.numSublanes(); ++i) {
    2327     46191122 :         if (ldi[i].first != 0) {
    2328     41035206 :             const double speed = ldi[i].first->getSpeed();
    2329     41035206 :             if (speed < minSpeed) {
    2330              :                 minSpeed = speed;
    2331              :                 iMax = i;
    2332              :             }
    2333              :         }
    2334              :     }
    2335     11414300 :     return ldi[iMax];
    2336              : }
    2337              : 
    2338              : 
    2339              : int
    2340     19303003 : MSLCM_SL2015::checkBlocking(const MSLane& neighLane, double& latDist, double maneuverDist, int laneOffset,
    2341              :                             const MSLeaderDistanceInfo& leaders,
    2342              :                             const MSLeaderDistanceInfo& followers,
    2343              :                             const MSLeaderDistanceInfo& /*blockers */,
    2344              :                             const MSLeaderDistanceInfo& neighLeaders,
    2345              :                             const MSLeaderDistanceInfo& neighFollowers,
    2346              :                             const MSLeaderDistanceInfo& /* neighBlockers */,
    2347              :                             std::vector<CLeaderDist>* collectLeadBlockers,
    2348              :                             std::vector<CLeaderDist>* collectFollowBlockers,
    2349              :                             bool keepLatGapManeuver,
    2350              :                             double gapFactor,
    2351              :                             int* retBlockedFully) {
    2352              :     // truncate latDist according to maxSpeedLat
    2353     19303003 :     const double maxDist = SPEED2DIST(getMaxSpeedLat2());
    2354     19303003 :     latDist = MAX2(MIN2(latDist, maxDist), -maxDist);
    2355     19303003 :     if (myVehicle.hasInfluencer() && myVehicle.getInfluencer().getLatDist() != 0 && myVehicle.getInfluencer().ignoreOverlap()) {
    2356              :         return 0;
    2357              :     }
    2358              : 
    2359     19300221 :     const double neighRight = getNeighRight(neighLane);
    2360     19300221 :     if (!myCFRelatedReady) {
    2361     11409088 :         updateCFRelated(followers, myVehicle.getLane()->getRightSideOnEdge(), false);
    2362     11409088 :         updateCFRelated(leaders, myVehicle.getLane()->getRightSideOnEdge(), true);
    2363     11409088 :         if (laneOffset != 0) {
    2364      7862028 :             updateCFRelated(neighFollowers, neighRight, false);
    2365      7862028 :             updateCFRelated(neighLeaders, neighRight, true);
    2366              :         }
    2367     11409088 :         myCFRelatedReady = true;
    2368              :     }
    2369              : 
    2370              :     // reduce latDist to avoid blockage with overlapping vehicles (no minGapLat constraints)
    2371     19300221 :     const double center = myVehicle.getCenterOnEdge();
    2372     19300221 :     updateGaps(leaders, myVehicle.getLane()->getRightSideOnEdge(), center, gapFactor, mySafeLatDistRight, mySafeLatDistLeft, false, 0, latDist, collectLeadBlockers);
    2373     19300221 :     updateGaps(followers, myVehicle.getLane()->getRightSideOnEdge(), center, gapFactor, mySafeLatDistRight, mySafeLatDistLeft, false, 0, latDist, collectFollowBlockers);
    2374     19300221 :     if (laneOffset != 0) {
    2375      9470815 :         updateGaps(neighLeaders, neighRight, center, gapFactor, mySafeLatDistRight, mySafeLatDistLeft, false, 0, latDist, collectLeadBlockers);
    2376      9470815 :         updateGaps(neighFollowers, neighRight, center, gapFactor, mySafeLatDistRight, mySafeLatDistLeft, false, 0, latDist, collectFollowBlockers);
    2377              :     }
    2378              : #ifdef DEBUG_BLOCKING
    2379              :     if (gDebugFlag2) {
    2380              :         std::cout << "    checkBlocking latDist=" << latDist << " mySafeLatDistRight=" << mySafeLatDistRight << " mySafeLatDistLeft=" << mySafeLatDistLeft << "\n";
    2381              :     }
    2382              : #endif
    2383              :     // if we can move at least a little bit in the desired direction, do so (rather than block)
    2384     19300221 :     const bool forcedTraCIChange = (myVehicle.hasInfluencer()
    2385        58900 :                                     && myVehicle.getInfluencer().getLatDist() != 0
    2386     19300562 :                                     && myVehicle.getInfluencer().ignoreOverlap());
    2387     19300221 :     if (latDist < 0) {
    2388     10178979 :         if (mySafeLatDistRight <= NUMERICAL_EPS) {
    2389              :             return LCA_BLOCKED_RIGHT | LCA_OVERLAPPING;
    2390      9279325 :         } else if (!forcedTraCIChange) {
    2391     12791290 :             latDist = MAX2(latDist, -mySafeLatDistRight);
    2392              :         }
    2393              :     } else {
    2394      9121242 :         if (mySafeLatDistLeft <= NUMERICAL_EPS) {
    2395              :             return LCA_BLOCKED_LEFT | LCA_OVERLAPPING;
    2396      7302793 :         } else if (!forcedTraCIChange) {
    2397      7302793 :             latDist = MIN2(latDist, mySafeLatDistLeft);
    2398              :         }
    2399              :     }
    2400              : 
    2401     16582118 :     myCanChangeFully = (maneuverDist == 0 || latDist == maneuverDist);
    2402              : #ifdef DEBUG_BLOCKING
    2403              :     if (gDebugFlag2) {
    2404              :         std::cout << "    checkBlocking latDist=" << latDist << " maneuverDist=" << maneuverDist << "\n";
    2405              :     }
    2406              : #endif
    2407              :     // destination sublanes must be safe
    2408              :     // intermediate sublanes must not be blocked by overlapping vehicles
    2409              : 
    2410              :     // XXX avoid checking the same leader multiple times
    2411              :     // XXX ensure that only changes within the same lane are undertaken if laneOffset = 0
    2412              : 
    2413              :     int blocked = 0;
    2414     16582118 :     blocked |= checkBlockingVehicles(&myVehicle, leaders, laneOffset, latDist, myVehicle.getLane()->getRightSideOnEdge(), true,
    2415              :                                      mySafeLatDistRight, mySafeLatDistLeft, collectLeadBlockers);
    2416     16582118 :     blocked |= checkBlockingVehicles(&myVehicle, followers, laneOffset, latDist, myVehicle.getLane()->getRightSideOnEdge(), false,
    2417              :                                      mySafeLatDistRight, mySafeLatDistLeft, collectFollowBlockers);
    2418     16582118 :     if (laneOffset != 0) {
    2419      8313063 :         blocked |= checkBlockingVehicles(&myVehicle, neighLeaders, laneOffset, latDist, neighRight, true,
    2420              :                                          mySafeLatDistRight, mySafeLatDistLeft, collectLeadBlockers);
    2421      8313063 :         blocked |= checkBlockingVehicles(&myVehicle, neighFollowers, laneOffset, latDist, neighRight, false,
    2422              :                                          mySafeLatDistRight, mySafeLatDistLeft, collectFollowBlockers);
    2423              :     }
    2424              : 
    2425              :     int blockedFully = 0;
    2426     16582118 :     blockedFully |= checkBlockingVehicles(&myVehicle, leaders, laneOffset, maneuverDist, myVehicle.getLane()->getRightSideOnEdge(), true,
    2427              :                                           mySafeLatDistRight, mySafeLatDistLeft, collectLeadBlockers);
    2428     16582118 :     blockedFully |= checkBlockingVehicles(&myVehicle, followers, laneOffset, maneuverDist, myVehicle.getLane()->getRightSideOnEdge(), false,
    2429              :                                           mySafeLatDistRight, mySafeLatDistLeft, collectFollowBlockers);
    2430     16582118 :     if (laneOffset != 0) {
    2431      8313063 :         blockedFully |= checkBlockingVehicles(&myVehicle, neighLeaders, laneOffset, maneuverDist, neighRight, true,
    2432              :                                               mySafeLatDistRight, mySafeLatDistLeft, collectLeadBlockers);
    2433      8313063 :         blockedFully |= checkBlockingVehicles(&myVehicle, neighFollowers, laneOffset, maneuverDist, neighRight, false,
    2434              :                                               mySafeLatDistRight, mySafeLatDistLeft, collectFollowBlockers);
    2435              :     }
    2436     16582118 :     if (retBlockedFully != nullptr) {
    2437      5345264 :         *retBlockedFully = blockedFully;
    2438              :     }
    2439              : #ifdef DEBUG_BLOCKING
    2440              :     if (gDebugFlag2) {
    2441              :         std::cout << "    blocked=" << blocked << " (" << toString((LaneChangeAction)blocked) << ") blockedFully=" << toString((LaneChangeAction)blockedFully)
    2442              :             << " canChangeFully=" << myCanChangeFully << " keepLatGapManeuver=" << keepLatGapManeuver << "\n";
    2443              :     }
    2444              : #endif
    2445     16582118 :     if (blocked == 0 && !myCanChangeFully && myPushy == 0 && !keepLatGapManeuver) {
    2446              :         // aggressive drivers immediately start moving towards potential
    2447              :         // blockers and only check that the start of their maneuver (latDist) is safe. In
    2448              :         // contrast, cautious drivers need to check latDist and origLatDist to
    2449              :         // ensure that the maneuver can be finished without encroaching on other vehicles.
    2450      8240513 :         blocked |= blockedFully;
    2451              :     } else {
    2452              :         // XXX: in case of action step length > simulation step length, pushing may lead to collisions,
    2453              :         //      because maneuver is continued until maneuverDist is reached (perhaps set maneuverDist=latDist)
    2454              :     }
    2455              : #ifdef DEBUG_BLOCKING
    2456              :     if (gDebugFlag2) {
    2457              :         std::cout << "    blocked2=" << blocked << " (" << toString((LaneChangeAction)blocked) << ")\n";
    2458              :     }
    2459              : #endif
    2460     16582118 :     if (collectFollowBlockers != nullptr && collectLeadBlockers != nullptr) {
    2461              :         // prevent vehicles from being classified as leader and follower simultaneously
    2462      7373887 :         for (std::vector<CLeaderDist>::const_iterator it2 = collectLeadBlockers->begin(); it2 != collectLeadBlockers->end(); ++it2) {
    2463     27471744 :             for (std::vector<CLeaderDist>::iterator it = collectFollowBlockers->begin(); it != collectFollowBlockers->end();) {
    2464     21906769 :                 if ((*it2).first == (*it).first) {
    2465              : #ifdef DEBUG_BLOCKING
    2466              :                     if (gDebugFlag2) {
    2467              :                         std::cout << "    removed follower " << (*it).first->getID() << " because it is already a leader\n";
    2468              :                     }
    2469              : #endif
    2470              :                     it = collectFollowBlockers->erase(it);
    2471              :                 } else {
    2472              :                     ++it;
    2473              :                 }
    2474              :             }
    2475              :         }
    2476              :     }
    2477              :     return blocked;
    2478              : }
    2479              : 
    2480              : 
    2481              : int
    2482     99580724 : MSLCM_SL2015::checkBlockingVehicles(
    2483              :     const MSVehicle* ego, const MSLeaderDistanceInfo& vehicles,
    2484              :     int laneOffset, double latDist, double foeOffset, bool leaders,
    2485              :     double& safeLatGapRight, double& safeLatGapLeft,
    2486              :     std::vector<CLeaderDist>* collectBlockers) const {
    2487              :     // determine borders where safety/no-overlap conditions must hold
    2488              :     const LaneChangeAction blockType = (laneOffset == 0
    2489     99580724 :                                         ? (leaders ? LCA_BLOCKED_BY_LEADER : LCA_BLOCKED_BY_FOLLOWER)
    2490              :                                         : (laneOffset > 0
    2491     66504504 :                                            ? (leaders ? LCA_BLOCKED_BY_LEFT_LEADER : LCA_BLOCKED_BY_LEFT_FOLLOWER)
    2492     30425008 :                                            : (leaders ? LCA_BLOCKED_BY_RIGHT_LEADER : LCA_BLOCKED_BY_RIGHT_FOLLOWER)));
    2493     99580724 :     const double vehWidth = getWidth();
    2494     99580724 :     const double rightVehSide = ego->getRightSideOnEdge();
    2495     99580724 :     const double leftVehSide = rightVehSide + vehWidth;
    2496     99580724 :     const double rightVehSideDest = rightVehSide + latDist;
    2497     99580724 :     const double leftVehSideDest = leftVehSide + latDist;
    2498              :     const double rightNoOverlap = MIN2(rightVehSideDest, rightVehSide);
    2499              :     const double leftNoOverlap = MAX2(leftVehSideDest, leftVehSide);
    2500              : #ifdef DEBUG_BLOCKING
    2501              :     if (gDebugFlag2) {
    2502              :         std::cout << "  checkBlockingVehicles"
    2503              :                   << " laneOffset=" << laneOffset
    2504              :                   << " latDist=" << latDist
    2505              :                   << " foeOffset=" << foeOffset
    2506              :                   << " vehRight=" << rightVehSide
    2507              :                   << " vehLeft=" << leftVehSide
    2508              :                   << " rightNoOverlap=" << rightNoOverlap
    2509              :                   << " leftNoOverlap=" << leftNoOverlap
    2510              :                   << " destRight=" << rightVehSideDest
    2511              :                   << " destLeft=" << leftVehSideDest
    2512              :                   << " leaders=" << leaders
    2513              :                   << " blockType=" << toString((LaneChangeAction) blockType)
    2514              :                   << "\n";
    2515              :     }
    2516              : #endif
    2517              :     int result = 0;
    2518    512849112 :     for (int i = 0; i < vehicles.numSublanes(); ++i) {
    2519    424851030 :         CLeaderDist vehDist = vehicles[i];
    2520    424851030 :         if (vehDist.first != 0 && myCFRelated.count(vehDist.first) == 0) {
    2521              :             const MSVehicle* leader = vehDist.first;
    2522              :             const MSVehicle* follower = ego;
    2523    162555912 :             if (!leaders) {
    2524              :                 std::swap(leader, follower);
    2525              :             }
    2526              :             // only check the current stripe occupied by foe (transform into edge-coordinates)
    2527              :             double foeRight, foeLeft;
    2528    162555912 :             vehicles.getSublaneBorders(i, foeOffset, foeRight, foeLeft);
    2529    162555912 :             const bool overlapBefore = overlap(rightVehSide, leftVehSide, foeRight, foeLeft);
    2530    162555912 :             const bool overlapDest = overlap(rightVehSideDest, leftVehSideDest, foeRight, foeLeft);
    2531    162555912 :             const bool overlapAny = overlap(rightNoOverlap, leftNoOverlap, foeRight, foeLeft);
    2532              : #ifdef DEBUG_BLOCKING
    2533              :             if (gDebugFlag2) {
    2534              :                 std::cout << "   foe=" << vehDist.first->getID()
    2535              :                           << " gap=" << vehDist.second
    2536              :                           << " secGap=" << follower->getCarFollowModel().getSecureGap(follower, leader, follower->getSpeed(), leader->getSpeed(), leader->getCarFollowModel().getMaxDecel())
    2537              :                           << " foeRight=" << foeRight
    2538              :                           << " foeLeft=" << foeLeft
    2539              :                           << " overlapBefore=" << overlapBefore
    2540              :                           << " overlap=" << overlapAny
    2541              :                           << " overlapDest=" << overlapDest
    2542              :                           << "\n";
    2543              :             }
    2544              : #endif
    2545    162555912 :             if (overlapAny) {
    2546     35341012 :                 if (vehDist.second < 0) {
    2547     10947165 :                     if (overlapBefore && !overlapDest && !outsideEdge()) {
    2548              : #ifdef DEBUG_BLOCKING
    2549              :                         if (gDebugFlag2) {
    2550              :                             std::cout << "    ignoring current overlap to come clear\n";
    2551              :                         }
    2552              : #endif
    2553              :                     } else {
    2554              : #ifdef DEBUG_BLOCKING
    2555              :                         if (gDebugFlag2) {
    2556              :                             std::cout << "    overlap (" << toString((LaneChangeAction)blockType) << ")\n";
    2557              :                         }
    2558              : #endif
    2559     10878950 :                         result |= (blockType | LCA_OVERLAPPING);
    2560     10878950 :                         if (collectBlockers == nullptr) {
    2561     11582642 :                             return result;
    2562              :                         } else {
    2563      4143716 :                             collectBlockers->push_back(vehDist);
    2564              :                         }
    2565              :                     }
    2566     24393847 :                 } else if (overlapDest || !myCanChangeFully) {
    2567              :                     // Estimate state after actionstep (follower may be accelerating!)
    2568              :                     // A comparison between secure gap depending on the expected speeds and the extrapolated gap
    2569              :                     // determines whether the s is blocking the lane change.
    2570              :                     // (Note that the longitudinal state update has already taken effect before LC dynamics (thus "-TS" below), would be affected by #3665)
    2571              : 
    2572              :                     // Use conservative estimate for time until next action step
    2573              :                     // (XXX: how can the ego know the foe's action step length?)
    2574     24372537 :                     const double timeTillAction = MAX2(follower->getActionStepLengthSecs(), leader->getActionStepLengthSecs()) - TS;
    2575              :                     // Ignore decel for follower
    2576     24372537 :                     const double followerAccel = MAX2(0., follower->getAcceleration());
    2577     24372537 :                     const double leaderAccel = leader->getAcceleration();
    2578              :                     // Expected gap after next actionsteps
    2579     24372537 :                     const double expectedGap = MSCFModel::gapExtrapolation(timeTillAction, vehDist.second, leader->getSpeed(), follower->getSpeed(), leaderAccel, followerAccel, std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
    2580              : 
    2581              :                     // Determine expected speeds and corresponding secure gap at the extrapolated timepoint
    2582     24372537 :                     const double followerExpectedSpeed = follower->getSpeed() + timeTillAction * followerAccel;
    2583     24372537 :                     const double leaderExpectedSpeed = MAX2(0., leader->getSpeed() + timeTillAction * leaderAccel);
    2584     24372537 :                     const double expectedSecureGap = follower->getCarFollowModel().getSecureGap(follower, leader, followerExpectedSpeed, leaderExpectedSpeed, leader->getCarFollowModel().getMaxDecel());
    2585              : 
    2586              : #if defined(DEBUG_ACTIONSTEPS) && defined(DEBUG_BLOCKING)
    2587              :                     if (gDebugFlag2) {
    2588              :                         std::cout << "    timeTillAction=" << timeTillAction
    2589              :                                   << " followerAccel=" << followerAccel
    2590              :                                   << " followerExpectedSpeed=" << followerExpectedSpeed
    2591              :                                   << " leaderAccel=" << leaderAccel
    2592              :                                   << " leaderExpectedSpeed=" << leaderExpectedSpeed
    2593              :                                   << "\n    gap=" << vehDist.second
    2594              :                                   << " gapChange=" << (expectedGap - vehDist.second)
    2595              :                                   << " expectedGap=" << expectedGap
    2596              :                                   << " expectedSecureGap=" << expectedSecureGap
    2597              :                                   << " safeLatGapLeft=" << safeLatGapLeft
    2598              :                                   << " safeLatGapRight=" << safeLatGapRight
    2599              :                                   << std::endl;
    2600              :                     }
    2601              : #endif
    2602              : 
    2603              :                     // @note for euler-update, a different value for secureGap2 may be obtained when applying safetyFactor to followerDecel rather than secureGap
    2604     24372537 :                     const double secureGap2 = expectedSecureGap * getSafetyFactor();
    2605     24372537 :                     if (expectedGap < secureGap2) {
    2606              :                         // Foe is a blocker. Update lateral safe gaps accordingly.
    2607      5587464 :                         if (foeRight > leftVehSide) {
    2608      3991626 :                             safeLatGapLeft = MIN2(safeLatGapLeft, foeRight - leftVehSide);
    2609      3234971 :                         } else if (foeLeft < rightVehSide) {
    2610      4951746 :                             safeLatGapRight = MIN2(safeLatGapRight, rightVehSide - foeLeft);
    2611              :                         }
    2612              : 
    2613              : #ifdef DEBUG_BLOCKING
    2614              :                         if (gDebugFlag2) {
    2615              :                             std::cout << "    blocked by " << vehDist.first->getID() << " gap=" << vehDist.second << " expectedGap=" << expectedGap
    2616              :                                       << " expectedSecureGap=" << expectedSecureGap << " secGap2=" << secureGap2 << " safetyFactor=" << getSafetyFactor()
    2617              :                                       << " safeLatGapLeft=" << safeLatGapLeft << " safeLatGapRight=" << safeLatGapRight
    2618              :                                       << "\n";
    2619              :                         }
    2620              : #endif
    2621      5587464 :                         result |= blockType;
    2622      5587464 :                         if (collectBlockers == nullptr) {
    2623      4847408 :                             return result;
    2624              :                         }
    2625              : #ifdef DEBUG_BLOCKING
    2626              :                     } else if (gDebugFlag2 && expectedGap < expectedSecureGap) {
    2627              :                         std::cout << "    ignore blocker " << vehDist.first->getID() << " gap=" << vehDist.second << " expectedGap=" << expectedGap
    2628              :                                   << " expectedSecureGap=" << expectedSecureGap << " secGap2=" << secureGap2 << " safetyFactor=" << getSafetyFactor() << "\n";
    2629              : #endif
    2630              :                     }
    2631     18785073 :                     if (collectBlockers != nullptr) {
    2632              :                         // collect non-blocking followers as well to make sure
    2633              :                         // they remain non-blocking
    2634      4496005 :                         collectBlockers->push_back(vehDist);
    2635              :                     }
    2636              :                 }
    2637              :             }
    2638              :         }
    2639              :     }
    2640              :     return result;
    2641              : 
    2642              : }
    2643              : 
    2644              : 
    2645              : void
    2646     38542232 : MSLCM_SL2015::updateCFRelated(const MSLeaderDistanceInfo& vehicles, double foeOffset, bool leaders) {
    2647              :     // to ensure that we do not ignore the wrong vehicles due to numerical
    2648              :     // instability we slightly reduce the width
    2649     38542232 :     const double vehWidth = myVehicle.getVehicleType().getWidth() - NUMERICAL_EPS;
    2650     38542232 :     const double rightVehSide = myVehicle.getCenterOnEdge() - 0.5 * vehWidth;
    2651     38542232 :     const double leftVehSide = rightVehSide + vehWidth;
    2652              : #ifdef DEBUG_BLOCKING
    2653              :     if (gDebugFlag2) {
    2654              :         std::cout << " updateCFRelated foeOffset=" << foeOffset << " vehicles=" << vehicles.toString() << "\n";
    2655              :     }
    2656              : #endif
    2657    213348352 :     for (int i = 0; i < vehicles.numSublanes(); ++i) {
    2658    174806120 :         CLeaderDist vehDist = vehicles[i];
    2659    214532724 :         if (vehDist.first != 0 && (myCFRelated.count(vehDist.first) == 0 || vehDist.second < 0)) {
    2660              :             double foeRight, foeLeft;
    2661    106331719 :             vehicles.getSublaneBorders(i, foeOffset, foeRight, foeLeft);
    2662              : #ifdef DEBUG_BLOCKING
    2663              :             if (gDebugFlag2) {
    2664              :                 std::cout << "    foe=" << vehDist.first->getID() << " gap=" << vehDist.second
    2665              :                           << " sublane=" << i
    2666              :                           << " foeOffset=" << foeOffset
    2667              :                           << " egoR=" << rightVehSide << " egoL=" << leftVehSide
    2668              :                           << " iR=" << foeRight << " iL=" << foeLeft
    2669              :                           << " egoV=" << myVehicle.getSpeed() << " foeV=" << vehDist.first->getSpeed()
    2670              :                           << " egoE=" << myVehicle.getLane()->getEdge().getID() << " foeE=" << vehDist.first->getLane()->getEdge().getID()
    2671              :                           << "\n";
    2672              :             }
    2673              : #endif
    2674    106331719 :             if (overlap(rightVehSide, leftVehSide, foeRight, foeLeft) && !outsideEdge() && (vehDist.second >= 0
    2675              :                     // avoid deadlock due to #3729
    2676      4055533 :                     || (!leaders
    2677      1589460 :                         && myVehicle.getPositionOnLane() >= myVehicle.getVehicleType().getLength()
    2678      1484284 :                         && myVehicle.getSpeed() < SUMO_const_haltingSpeed
    2679      1477328 :                         && vehDist.first->getSpeed() < SUMO_const_haltingSpeed
    2680      1466569 :                         && -vehDist.second < vehDist.first->getVehicleType().getMinGap()
    2681      1461045 :                         && &(myVehicle.getLane()->getEdge()) != &(vehDist.first->getLane()->getEdge()))
    2682              :                                                                                            )) {
    2683              : #ifdef DEBUG_BLOCKING
    2684              :                 if (gDebugFlag2) {
    2685              :                     std::cout << "       ignoring cfrelated foe=" << vehDist.first->getID()  << "\n";
    2686              :                 }
    2687              : #endif
    2688              :                 myCFRelated.insert(vehDist.first);
    2689              :             } else {
    2690              :                 const int erased = (int)myCFRelated.erase(vehDist.first);
    2691              : #ifdef DEBUG_BLOCKING
    2692              :                 if (gDebugFlag2 && erased > 0) {
    2693              :                     std::cout << "       restoring cfrelated foe=" << vehDist.first->getID()  << "\n";
    2694              :                 }
    2695              : #else
    2696              :                 UNUSED_PARAMETER(erased);
    2697              : #endif
    2698              :             }
    2699              :         }
    2700              :     }
    2701     38542232 : }
    2702              : 
    2703              : 
    2704              : bool
    2705   1409427063 : MSLCM_SL2015::overlap(double right, double left, double right2, double left2) {
    2706              :     assert(right <= left);
    2707              :     assert(right2 <= left2);
    2708   1409427063 :     return left2 >= right + NUMERICAL_EPS && left >= right2 + NUMERICAL_EPS;
    2709              : }
    2710              : 
    2711              : 
    2712              : int
    2713     67995946 : MSLCM_SL2015::lowest_bit(int changeReason) {
    2714     67995946 :     if ((changeReason & LCA_STRATEGIC) != 0) {
    2715              :         return LCA_STRATEGIC;
    2716              :     }
    2717     53633832 :     if ((changeReason & LCA_COOPERATIVE) != 0) {
    2718              :         return LCA_COOPERATIVE;
    2719              :     }
    2720     52965828 :     if ((changeReason & LCA_SPEEDGAIN) != 0) {
    2721              :         return LCA_SPEEDGAIN;
    2722              :     }
    2723     49233420 :     if ((changeReason & LCA_KEEPRIGHT) != 0) {
    2724              :         return LCA_KEEPRIGHT;
    2725              :     }
    2726     48504499 :     if ((changeReason & LCA_TRACI) != 0) {
    2727         5770 :         return LCA_TRACI;
    2728              :     }
    2729              :     return changeReason;
    2730              : }
    2731              : 
    2732              : 
    2733              : MSLCM_SL2015::StateAndDist
    2734    160034596 : MSLCM_SL2015::decideDirection(StateAndDist sd1, StateAndDist sd2) const {
    2735              :     // ignore dummy decisions (returned if mayChange() failes)
    2736    160034596 :     if (sd1.state == 0) {
    2737     65447693 :         return sd2;
    2738     94586903 :     } else if (sd2.state == 0) {
    2739     60588930 :         return sd1;
    2740              :     }
    2741              :     // LCA_SUBLANE is special because LCA_STAY|LCA_SUBLANE may override another LCA_SUBLANE command
    2742     33997973 :     const bool want1 = ((sd1.state & LCA_WANTS_LANECHANGE) != 0) || ((sd1.state & LCA_SUBLANE) != 0 && (sd1.state & LCA_STAY) != 0);
    2743     33997973 :     const bool want2 = ((sd2.state & LCA_WANTS_LANECHANGE) != 0) || ((sd2.state & LCA_SUBLANE) != 0 && (sd2.state & LCA_STAY) != 0);
    2744     33997973 :     const bool can1 = ((sd1.state & LCA_BLOCKED) == 0);
    2745     33997973 :     const bool can2 = ((sd2.state & LCA_BLOCKED) == 0);
    2746     33997973 :     int reason1 = lowest_bit(sd1.state & LCA_CHANGE_REASONS);
    2747     33997973 :     int reason2 = lowest_bit(sd2.state & LCA_CHANGE_REASONS);
    2748              : #ifdef DEBUG_DECISION
    2749              :     if (DEBUG_COND) std::cout << SIMTIME
    2750              :                                   << " veh=" << myVehicle.getID()
    2751              :                                   << " state1=" << toString((LaneChangeAction)sd1.state)
    2752              :                                   << " want1=" << (sd1.state & LCA_WANTS_LANECHANGE)
    2753              :                                   << " dist1=" << sd1.latDist
    2754              :                                   << " dir1=" << sd1.dir
    2755              :                                   << " state2=" << toString((LaneChangeAction)sd2.state)
    2756              :                                   << " want2=" << (sd2.state & LCA_WANTS_LANECHANGE)
    2757              :                                   << " dist2=" << sd2.latDist
    2758              :                                   << " dir2=" << sd2.dir
    2759              :                                   << " reason1=" << toString((LaneChangeAction)reason1)
    2760              :                                   << " reason2=" << toString((LaneChangeAction)reason2)
    2761              :                                   << "\n";
    2762              : #endif
    2763     33997973 :     if (want1) {
    2764     33186120 :         if (want2) {
    2765     22643985 :             if ((sd1.state & LCA_TRACI) != 0 && (sd2.state & LCA_TRACI) != 0) {
    2766              :                 // influencer may assign LCA_WANTS_LANECHANGE despite latDist = 0
    2767         1560 :                 if (sd1.latDist == 0 && sd2.latDist != 0) {
    2768          114 :                     return sd2;
    2769         1446 :                 } else if (sd2.latDist == 0 && sd1.latDist != 0) {
    2770           20 :                     return sd1;
    2771              :                 }
    2772              :             }
    2773              :             // decide whether right or left has higher priority (lower value in enum LaneChangeAction)
    2774     22643851 :             if (reason1 < reason2) {
    2775              :                 //if (DEBUG_COND) std::cout << "   " << (sd1.state & LCA_CHANGE_REASONS) << " < " << (sd2.state & LCA_CHANGE_REASONS) << "\n";
    2776       476677 :                 return (!can1 && can2 && sd1.sameDirection(sd2)) ? sd2 : sd1;
    2777              :                 //return sd1;
    2778     22403007 :             } else if (reason1 > reason2) {
    2779              :                 //if (DEBUG_COND) std::cout << "   " << (sd1.state & LCA_CHANGE_REASONS) << " > " << (sd2.state & LCA_CHANGE_REASONS) << "\n";
    2780     11163554 :                 return (!can2 && can1 && sd1.sameDirection(sd2)) ? sd1 : sd2;
    2781              :                 //return sd2;
    2782              :             } else {
    2783              :                 // same priority.
    2784     16800706 :                 if ((sd1.state & LCA_SUBLANE) != 0) {
    2785              :                     // special treatment: prefer action with dir != 0
    2786     16520965 :                     if (sd1.dir == 0) {
    2787     15778743 :                         return sd2;
    2788       742222 :                     } else if (sd2.dir == 0) {
    2789            0 :                         return sd1;
    2790              :                     } else {
    2791              :                         // prefer action that knows more about the desired direction
    2792              :                         // @note when deciding between right and left, right is always given as sd1
    2793              :                         assert(sd1.dir == -1);
    2794              :                         assert(sd2.dir == 1);
    2795       742222 :                         if (sd1.latDist <= 0) {
    2796       697487 :                             return sd1;
    2797        44735 :                         } else if (sd2.latDist >= 0) {
    2798        44101 :                             return sd2;
    2799              :                         }
    2800              :                         // when in doubt, prefer moving to the right
    2801          634 :                         return sd1.latDist <= sd2.latDist ? sd1 : sd2;
    2802              :                     }
    2803              :                 } else {
    2804       279741 :                     if (can1) {
    2805       167644 :                         if (can2) {
    2806              :                             // break strategic ties with tactial concerns
    2807       111154 :                             if (reason1 == LCA_STRATEGIC) {
    2808         2516 :                                 if (sd1.latDist <= sd2.latDist) {
    2809         4234 :                                     return mySpeedGainProbabilityRight > mySpeedGainProbabilityLeft ? sd1 : sd2;
    2810              :                                 } else {
    2811            7 :                                     return mySpeedGainProbabilityRight > mySpeedGainProbabilityLeft ? sd2 : sd1;
    2812              :                                 }
    2813              :                             } else {
    2814              :                                 // finish the shorter maneuver (i.e. continue the current maneuver)
    2815       191878 :                                 return fabs(sd1.maneuverDist) < fabs(sd2.maneuverDist) ? sd1 : sd2;
    2816              :                             }
    2817              :                         } else {
    2818        56490 :                             return sd1;
    2819              :                         }
    2820              :                     } else {
    2821       112097 :                         return sd2;
    2822              :                     }
    2823              :                 }
    2824              :             }
    2825              :         } else {
    2826     10542135 :             return sd1;
    2827              :         }
    2828              :     } else {
    2829       811853 :         return sd2;
    2830              :     }
    2831              : 
    2832              : }
    2833              : 
    2834              : 
    2835              : LaneChangeAction
    2836    127571933 : MSLCM_SL2015::getLCA(int state, double latDist) {
    2837     26313215 :     return ((latDist == 0 || (state & LCA_CHANGE_REASONS) == 0)
    2838    153884746 :             ? LCA_NONE : (latDist < 0 ? LCA_RIGHT : LCA_LEFT));
    2839              : }
    2840              : 
    2841              : 
    2842              : int
    2843    115565969 : MSLCM_SL2015::checkStrategicChange(int ret,
    2844              :                                    const MSLane& neighLane,
    2845              :                                    int laneOffset,
    2846              :                                    const MSLeaderDistanceInfo& leaders,
    2847              :                                    const MSLeaderDistanceInfo& neighLeaders,
    2848              :                                    const MSVehicle::LaneQ& curr,
    2849              :                                    const MSVehicle::LaneQ& neigh,
    2850              :                                    const MSVehicle::LaneQ& best,
    2851              :                                    int bestLaneOffset,
    2852              :                                    bool changeToBest,
    2853              :                                    double& currentDist,
    2854              :                                    double neighDist,
    2855              :                                    double laDist,
    2856              :                                    double roundaboutBonus,
    2857              :                                    double latLaneDist,
    2858              :                                    bool checkOpposite,
    2859              :                                    double& latDist
    2860              :                                   ) {
    2861    115565969 :     const bool right = (laneOffset == -1);
    2862              :     const bool left = (laneOffset == 1);
    2863              : 
    2864    115565969 :     const double forwardPos = getForwardPos();
    2865    115565969 :     if (laneOffset != 0) {
    2866     35548671 :         myLeftSpace = currentDist - forwardPos;
    2867              :     }
    2868    115565969 :     const double usableDist = (currentDist - forwardPos - best.occupation *  JAM_FACTOR);
    2869              :     //- (best.lane->getVehicleNumber() * neighSpeed)); // VARIANT 9 jfSpeed
    2870    115565969 :     const double maxJam = MAX2(neigh.occupation, curr.occupation);
    2871    115565969 :     const double neighLeftPlace = MAX2(0., neighDist - forwardPos - maxJam);
    2872    115565969 :     const double overlap = myVehicle.getLateralOverlap();
    2873              :     // save the left space
    2874              : 
    2875              : #ifdef DEBUG_STRATEGIC_CHANGE
    2876              :     if (gDebugFlag2) {
    2877              :         std::cout << SIMTIME
    2878              :                   << " veh=" << myVehicle.getID()
    2879              :                   << " forwardPos=" << forwardPos
    2880              :                   << " laSpeed=" << myLookAheadSpeed
    2881              :                   << " laDist=" << laDist
    2882              :                   << " currentDist=" << currentDist
    2883              :                   << " usableDist=" << usableDist
    2884              :                   << " bestLaneOffset=" << bestLaneOffset
    2885              :                   << " best.length=" << best.length
    2886              :                   << " maxJam=" << maxJam
    2887              :                   << " neighLeftPlace=" << neighLeftPlace
    2888              :                   << " myLeftSpace=" << myLeftSpace
    2889              :                   << " overlap=" << overlap
    2890              :                   << "\n";
    2891              :     }
    2892              : #endif
    2893              : 
    2894    115565969 :     if (laneOffset == 0) {
    2895     80017298 :         if (overlap > MAX2(POSITION_EPS, MSGlobals::gLateralResolution)
    2896       367626 :                 && (getShadowLane() == nullptr || !getShadowLane()->allowsVehicleClass(myVehicle.getVClass()))
    2897     80020709 :                 && getWidth() < myVehicle.getLane()->getWidth()) {
    2898              :             // @brief we urgently need to return to within lane bounds
    2899         3324 :             latDist = myVehicle.getLateralPositionOnLane() > 0 ? -overlap : overlap;
    2900         3324 :             ret |= LCA_STRATEGIC | LCA_URGENT;
    2901              : #ifdef DEBUG_STRATEGIC_CHANGE
    2902              :             if (gDebugFlag2) {
    2903              :                 std::cout << SIMTIME << " returnToLaneBounds\n";
    2904              :             }
    2905              : #endif
    2906              :             //std::cout << SIMTIME << " veh=" << myVehicle.getID() << " overlap=" << overlap << " returnToLaneBounds\n";
    2907     80013974 :         } else if (myVehicle.getBestLanesContinuation().size() > 1 && myVehicle.getLane()->getWidth() > myVehicle.getBestLanesContinuation()[1]->getWidth()) {
    2908       890075 :             const MSLane* cur = myVehicle.getLane();
    2909       890075 :             const MSLane* next = myVehicle.getBestLanesContinuation()[1];
    2910       890075 :             const MSLink* link = cur->getLinkTo(next);
    2911       890075 :             const double distOnLane = cur->getLength() - myVehicle.getPositionOnLane();
    2912       890075 :             if (link != nullptr && getWidth() < next->getWidth() && distOnLane < 100) {
    2913       885599 :                 double hwDiff = 0.5 * (cur->getWidth() - next->getWidth());
    2914       885599 :                 double rightVehSide = myVehicle.getRightSideOnLane() + link->getLateralShift() - hwDiff;
    2915       885599 :                 double leftVehSide = myVehicle.getLeftSideOnLane() + link->getLateralShift() - hwDiff;
    2916       885599 :                 const double res = MSGlobals::gLateralResolution > 0 ? MSGlobals::gLateralResolution : next->getWidth();
    2917       885599 :                 if (rightVehSide < -res && (next->getParallelLane(-1) == nullptr || !next->getParallelLane(-1)->allowsVehicleClass(myVehicle.getVClass()))) {
    2918        24050 :                     latDist = -rightVehSide;
    2919        24050 :                     myLeftSpace = distOnLane;
    2920        24050 :                     ret |= LCA_STRATEGIC | LCA_URGENT;
    2921              : #ifdef DEBUG_STRATEGIC_CHANGE
    2922              :                     if (gDebugFlag2) {
    2923              :                         std::cout << SIMTIME << " rightSublaneEnds rVSide=" << myVehicle.getRightSideOnLane()
    2924              :                             << " shift=" << link->getLateralShift() << " rVSide2=" << rightVehSide << " myLeftSpace=" << myLeftSpace << " \n";
    2925              :                     }
    2926              : #endif
    2927       861549 :                 } else if (leftVehSide > next->getWidth() + res && (next->getParallelLane(1) == nullptr || !next->getParallelLane(1)->allowsVehicleClass(myVehicle.getVClass()))) {
    2928        29935 :                     latDist = -(leftVehSide - next->getWidth());
    2929        29935 :                     myLeftSpace = distOnLane;
    2930        29935 :                     ret |= LCA_STRATEGIC | LCA_URGENT;
    2931              : #ifdef DEBUG_STRATEGIC_CHANGE
    2932              :                     if (gDebugFlag2) {
    2933              :                         std::cout << SIMTIME << " leftSublaneEnds lVSide=" << myVehicle.getLeftSideOnLane()
    2934              :                             << " shift=" << link->getLateralShift() << " lVSide2=" << leftVehSide << " myLeftSpace=" << myLeftSpace << "\n";
    2935              :                     }
    2936              : #endif
    2937              :                 }
    2938              :             }
    2939              :         }
    2940     21911527 :     } else if (laneOffset != 0 && changeToBest && bestLaneOffset == curr.bestLaneOffset
    2941     40732866 :             && currentDistDisallows(usableDist, bestLaneOffset, laDist)) {
    2942              :         /// @brief we urgently need to change lanes to follow our route
    2943      1992116 :         if (!mustOvertakeStopped(false, neighLane, neighLeaders, leaders, forwardPos, neighDist, right, latLaneDist, currentDist, latDist)) {
    2944      1977513 :             latDist = latLaneDist;
    2945      1977513 :             ret |= LCA_STRATEGIC | LCA_URGENT;
    2946              : #ifdef DEBUG_STRATEGIC_CHANGE
    2947              :             if (gDebugFlag2) {
    2948              :                 std::cout << SIMTIME << " mustChangeToBest\n";
    2949              :             }
    2950              : #endif
    2951              :         } else {
    2952              : #ifdef DEBUG_STRATEGIC_CHANGE
    2953              :             if (gDebugFlag2) {
    2954              :                 std::cout << " veh=" << myVehicle.getID() << " avoidStoppedNeigh\n";
    2955              :             }
    2956              : #endif
    2957              :         }
    2958              :     } else {
    2959              :         // VARIANT_20 (noOvertakeRight)
    2960     33556555 :         if (left && avoidOvertakeRight() && neighLeaders.hasVehicles()) {
    2961              :             // check for slower leader on the left. we should not overtake but
    2962              :             // rather move left ourselves (unless congested)
    2963              :             // XXX only adapt as much as possible to get a lateral gap
    2964      2854528 :             CLeaderDist cld = getSlowest(neighLeaders);
    2965      2854528 :             const MSVehicle* nv = cld.first;
    2966      2854528 :             if (nv->getSpeed() < myVehicle.getSpeed()) {
    2967       420464 :                 const double vSafe = getCarFollowModel().followSpeed(
    2968       420464 :                                          &myVehicle, myVehicle.getSpeed(), cld.second, nv->getSpeed(), nv->getCarFollowModel().getMaxDecel());
    2969       420464 :                 addLCSpeedAdvice(vSafe);
    2970       420464 :                 if (vSafe < myVehicle.getSpeed()) {
    2971       216728 :                     mySpeedGainProbabilityRight += myVehicle.getActionStepLengthSecs() * myChangeProbThresholdLeft / 3;
    2972              :                 }
    2973              : #ifdef DEBUG_STRATEGIC_CHANGE
    2974              :                 if (gDebugFlag2) {
    2975              :                     std::cout << SIMTIME
    2976              :                               << " avoid overtaking on the right nv=" << nv->getID()
    2977              :                               << " nvSpeed=" << nv->getSpeed()
    2978              :                               << " mySpeedGainProbabilityR=" << mySpeedGainProbabilityRight
    2979              :                               << " plannedSpeed=" << myVehicle.getSpeed() + ACCEL2SPEED(myLCAccelerationAdvices.back().first)
    2980              :                               << "\n";
    2981              :                 }
    2982              : #endif
    2983              :             }
    2984              :         }
    2985              : 
    2986              :         // handling reaction to stopped for opposite direction driving NYI
    2987     33556555 :         const bool noOpposites = &myVehicle.getLane()->getEdge() == &neighLane.getEdge();
    2988     33556555 :         if (laneOffset != 0 && myStrategicParam >= 0 && noOpposites && mustOvertakeStopped(true, neighLane, leaders, neighLeaders, forwardPos, neighDist, right, latLaneDist, currentDist, latDist)) {
    2989              : #ifdef DEBUG_STRATEGIC_CHANGE
    2990              :             if (gDebugFlag2) {
    2991              :                 std::cout << " veh=" << myVehicle.getID() << " mustOvertakeStopped\n";
    2992              :             }
    2993              : #endif
    2994        21971 :             if (latDist == 0) {
    2995            0 :                 ret |= LCA_STAY | LCA_STRATEGIC;
    2996              :             } else {
    2997        21971 :                 ret |= LCA_STRATEGIC | LCA_URGENT;
    2998              :             }
    2999              : 
    3000     33534584 :         } else if (!changeToBest && (currentDistDisallows(neighLeftPlace, abs(bestLaneOffset) + 2, laDist))) {
    3001              :             // the opposite lane-changing direction should be done than the one examined herein
    3002              :             //  we'll check whether we assume we could change anyhow and get back in time...
    3003              :             //
    3004              :             // this rule prevents the vehicle from moving in opposite direction of the best lane
    3005              :             //  unless the way till the end where the vehicle has to be on the best lane
    3006              :             //  is long enough
    3007              : #ifdef DEBUG_STRATEGIC_CHANGE
    3008              :             if (gDebugFlag2) {
    3009              :                 std::cout << " veh=" << myVehicle.getID() << " could not change back and forth in time (1) neighLeftPlace=" << neighLeftPlace << "\n";
    3010              :             }
    3011              : #endif
    3012     10685021 :             ret |= LCA_STAY | LCA_STRATEGIC;
    3013              :         } else if (
    3014              :             laneOffset != 0
    3015     22849563 :             && bestLaneOffset == 0
    3016      2926033 :             && !leaders.hasStoppedVehicle()
    3017      2904138 :             && neigh.bestContinuations.back()->getLinkCont().size() != 0
    3018      2071490 :             && roundaboutBonus == 0
    3019      2071490 :             && !checkOpposite
    3020      1355076 :             && neighDist < TURN_LANE_DIST
    3021     23775575 :             && myStrategicParam >= 0) {
    3022              :             // VARIANT_21 (stayOnBest)
    3023              :             // we do not want to leave the best lane for a lane which leads elsewhere
    3024              :             // unless our leader is stopped or we are approaching a roundabout
    3025              : #ifdef DEBUG_STRATEGIC_CHANGE
    3026              :             if (gDebugFlag2) {
    3027              :                 std::cout << " veh=" << myVehicle.getID() << " does not want to leave the bestLane (neighDist=" << neighDist << ")\n";
    3028              :             }
    3029              : #endif
    3030       922123 :             ret |= LCA_STAY | LCA_STRATEGIC;
    3031              :         } else if (right
    3032     21927440 :                    && bestLaneOffset == 0
    3033       580121 :                    && myVehicle.getLane()->getSpeedLimit() > 80. / 3.6
    3034     21950132 :                    && myLookAheadSpeed > SUMO_const_haltingSpeed
    3035              :                   ) {
    3036              :             // let's also regard the case where the vehicle is driving on a highway...
    3037              :             //  in this case, we do not want to get to the dead-end of an on-ramp
    3038              : #ifdef DEBUG_STRATEGIC_CHANGE
    3039              :             if (gDebugFlag2) {
    3040              :                 std::cout << " veh=" << myVehicle.getID() << " does not want to get stranded on the on-ramp of a highway\n";
    3041              :             }
    3042              : #endif
    3043        22153 :             ret |= LCA_STAY | LCA_STRATEGIC;
    3044              :         }
    3045              :     }
    3046    115565969 :     if (laneOffset != 0 && (ret & LCA_URGENT) == 0 && getShadowLane() != nullptr &&
    3047              :             // ignore overlap if it goes in the correct direction
    3048      1789835 :             bestLaneOffset * myVehicle.getLateralPositionOnLane() <= 0) {
    3049              :         // no decision or decision to stay
    3050              :         // make sure to stay within lane bounds in case the shadow lane ends
    3051              :         //const double requiredDist = MAX2(2 * myVehicle.getLateralOverlap(), getSublaneWidth()) / SUMO_const_laneWidth * laDist;
    3052       900682 :         const double requiredDist = 2 * overlap / SUMO_const_laneWidth * laDist;
    3053       900682 :         double currentShadowDist = -myVehicle.getPositionOnLane();
    3054              :         MSLane* shadowPrev = nullptr;
    3055      1934002 :         for (std::vector<MSLane*>::const_iterator it = curr.bestContinuations.begin(); it != curr.bestContinuations.end(); ++it) {
    3056      1702101 :             if (*it == nullptr) {
    3057        31354 :                 continue;
    3058              :             }
    3059      1670747 :             MSLane* shadow = getShadowLane(*it);
    3060      1670747 :             if (shadow == nullptr || currentShadowDist >= requiredDist) {
    3061              :                 break;
    3062              :             }
    3063      1001966 :             if (shadowPrev != nullptr) {
    3064       112371 :                 currentShadowDist += shadowPrev->getEdge().getInternalFollowingLengthTo(&shadow->getEdge(), myVehicle.getVClass());
    3065              :             }
    3066      1001966 :             currentShadowDist += shadow->getLength();
    3067              :             shadowPrev = shadow;
    3068              : #ifdef DEBUG_STRATEGIC_CHANGE
    3069              :             if (gDebugFlag2) {
    3070              :                 std::cout << "    shadow=" << shadow->getID() << " currentShadowDist=" << currentShadowDist << "\n";
    3071              :             }
    3072              : #endif
    3073              :         }
    3074              : #ifdef DEBUG_STRATEGIC_CHANGE
    3075              :         if (gDebugFlag2) {
    3076              :             std::cout << " veh=" << myVehicle.getID() << " currentShadowDist=" << currentShadowDist << " requiredDist=" << requiredDist << " overlap=" << overlap << "\n";
    3077              :         }
    3078              : #endif
    3079       900682 :         if (currentShadowDist < requiredDist && currentShadowDist < usableDist) {
    3080       150703 :             myLeftSpace = currentShadowDist;
    3081       150703 :             latDist = myVehicle.getLateralPositionOnLane() < 0 ? overlap : -overlap;
    3082              : #ifdef DEBUG_STRATEGIC_CHANGE
    3083              :             if (gDebugFlag2) {
    3084              :                 std::cout << "    must change for shadowLane end latDist=" << latDist << " myLeftSpace=" << myLeftSpace << "\n";
    3085              :             }
    3086              : #endif
    3087       150703 :             ret |= LCA_STRATEGIC | LCA_URGENT | LCA_STAY ;
    3088              :         }
    3089              :     }
    3090              : 
    3091              :     // check for overriding TraCI requests
    3092              : #if defined(DEBUG_STRATEGIC_CHANGE) || defined(DEBUG_TRACI)
    3093              :     if (gDebugFlag2) {
    3094              :         std::cout << SIMTIME << " veh=" << myVehicle.getID() << " ret=" << ret;
    3095              :     }
    3096              : #endif
    3097              :     // store state before canceling
    3098    115565969 :     getCanceledState(laneOffset) |= ret;
    3099    115565969 :     int retTraCI = myVehicle.influenceChangeDecision(ret);
    3100    115565969 :     if ((retTraCI & LCA_TRACI) != 0) {
    3101         4900 :         if ((retTraCI & LCA_STAY) != 0) {
    3102              :             ret = retTraCI;
    3103         4336 :             latDist = 0;
    3104          564 :         } else if (((retTraCI & LCA_RIGHT) != 0 && laneOffset < 0)
    3105          489 :                    || ((retTraCI & LCA_LEFT) != 0 && laneOffset > 0)) {
    3106              :             ret = retTraCI;
    3107          222 :             latDist = latLaneDist;
    3108              :         }
    3109              :     }
    3110              : #if defined(DEBUG_STRATEGIC_CHANGE) || defined(DEBUG_TRACI)
    3111              :     if (gDebugFlag2) {
    3112              :         std::cout << " reqAfterInfluence=" << toString((LaneChangeAction)retTraCI) << " ret=" << toString((LaneChangeAction)ret) << "\n";
    3113              :     }
    3114              : #endif
    3115    115565969 :     return ret;
    3116              : }
    3117              : 
    3118              : 
    3119              : bool
    3120     35301374 : MSLCM_SL2015::mustOvertakeStopped(bool checkCurrent, const MSLane& neighLane, const MSLeaderDistanceInfo& leaders, const MSLeaderDistanceInfo& neighLead,
    3121              :                                   double posOnLane, double neighDist, bool right, double latLaneDist, double& currentDist, double& latDist) {
    3122              :     bool mustOvertake = false;
    3123     35301374 :     const bool checkOverTakeRight = avoidOvertakeRight();
    3124              :     int rightmost;
    3125              :     int leftmost;
    3126     35301374 :     const bool curHasStopped = leaders.hasStoppedVehicle();
    3127     35301374 :     const int dir = latLaneDist < 0 ? -1 : 1;
    3128     35301374 :     const MSLane* neighBeyond = neighLane.getParallelLane(dir);
    3129     35301374 :     const bool hasLaneBeyond = checkCurrent && neighBeyond != nullptr && neighBeyond->allowsVehicleClass(myVehicle.getVClass());
    3130              :     UNUSED_PARAMETER(hasLaneBeyond);
    3131     35301374 :     if (curHasStopped) {
    3132        93623 :         leaders.getSubLanes(&myVehicle, 0, rightmost, leftmost);
    3133       397394 :         for (int i = rightmost; i <= leftmost; i++) {
    3134       303771 :             const CLeaderDist& leader = leaders[i];
    3135       303771 :             if (leader.first != 0 && leader.first->isStopped() && leader.second < REACT_TO_STOPPED_DISTANCE) {
    3136       182597 :                 const double overtakeDist = leader.second + myVehicle.getVehicleType().getLength() + leader.first->getVehicleType().getLengthWithGap();
    3137       182597 :                 const double remaining = MIN2(neighDist, currentDist) - posOnLane;
    3138              : #ifdef DEBUG_STRATEGIC_CHANGE
    3139              :                 if (DEBUG_COND) {
    3140              :                     std::cout << "  overtakeDist=" << overtakeDist << " remaining=" << remaining
    3141              :                               << " minDistToStopped=" << neighLead.getMinDistToStopped()
    3142              :                               << " hasLaneBeyond=" << hasLaneBeyond
    3143              :                               << "\n";
    3144              :                 }
    3145              : #endif
    3146              :                 if (// current destination leaves enough space to overtake the leader
    3147              :                     remaining > overtakeDist
    3148              :                     // maybe do not overtake on the right at high speed
    3149        64437 :                     && (!checkCurrent || !checkOverTakeRight || !right)
    3150       245984 :                     && (!neighLead.hasStoppedVehicle() || neighLead.getMinDistToStopped() > overtakeDist /*|| (hasLaneBeyond && hasFreeLaneBeyond(neighBeyond, dir))*/)
    3151              :                     //&& (neighLead.first == 0 || !neighLead.first->isStopped()
    3152              :                     //    // neighboring stopped vehicle leaves enough space to overtake leader
    3153              :                     //    || neighLead.second > overtakeDist))
    3154              :                 ) {
    3155              :                     // avoid becoming stuck behind a stopped leader
    3156        36591 :                     currentDist = myVehicle.getPositionOnLane() + leader.second;
    3157        36591 :                     myLeftSpace = currentDist - posOnLane;
    3158        36591 :                     latDist = latLaneDist;
    3159              :                     mustOvertake = true;
    3160              : #ifdef DEBUG_STRATEGIC_CHANGE
    3161              :                     if (DEBUG_COND) {
    3162              :                         std::cout << " veh=" << myVehicle.getID() << " overtake stopped leader=" << leader.first->getID()
    3163              :                                   << " newCurrentDist=" << currentDist
    3164              :                                   << " overtakeDist=" << overtakeDist
    3165              :                                   << " remaining=" << remaining
    3166              :                                   << "\n";
    3167              :                     }
    3168              : #endif
    3169              :                 }
    3170              :             }
    3171              : 
    3172              :         }
    3173              :     }
    3174     35301374 :     if (!mustOvertake && !curHasStopped && neighLead.hasStoppedVehicle()) {
    3175              :         // #todo fix this if the neigh lane has a different width
    3176       150116 :         const double offset = (latLaneDist < 0 ? -1 : 1) * myVehicle.getLane()->getWidth();
    3177       126168 :         neighLead.getSubLanes(&myVehicle, offset, rightmost, leftmost);
    3178       626863 :         for (int i = 0; i < leaders.numSublanes(); i++) {
    3179       500695 :             const CLeaderDist& leader = leaders[i];
    3180       500695 :             if (leader.first != 0 && leader.first->isStopped() && leader.second < REACT_TO_STOPPED_DISTANCE) {
    3181              :                 mustOvertake = true;
    3182            0 :                 if (i >= rightmost && i <= leftmost) {
    3183            0 :                     latDist = myVehicle.getLateralOverlap() * (latLaneDist > 0 ? -1 : 1);
    3184            0 :                     break;
    3185              :                 }
    3186              :             }
    3187              :         }
    3188              :     }
    3189     35301374 :     return mustOvertake;
    3190              : }
    3191              : 
    3192              : 
    3193              : double
    3194    117770359 : MSLCM_SL2015::computeGapFactor(int state) const {
    3195    117770359 :     return (state & LCA_STRATEGIC) != 0 ? MAX2(0.0, (1.0 - myPushy * (1 + 0.5 * myImpatience))) : 1.0;
    3196              : }
    3197              : 
    3198              : 
    3199              : int
    3200    115562710 : MSLCM_SL2015::keepLatGap(int state,
    3201              :                          const MSLeaderDistanceInfo& leaders,
    3202              :                          const MSLeaderDistanceInfo& followers,
    3203              :                          const MSLeaderDistanceInfo& blockers,
    3204              :                          const MSLeaderDistanceInfo& neighLeaders,
    3205              :                          const MSLeaderDistanceInfo& neighFollowers,
    3206              :                          const MSLeaderDistanceInfo& neighBlockers,
    3207              :                          const MSLane& neighLane,
    3208              :                          int laneOffset,
    3209              :                          double& latDist,
    3210              :                          double& maneuverDist,
    3211              :                          int& blocked) {
    3212              : 
    3213              :     /* @notes
    3214              :      * vehicles may need to compromise between fulfilling lane change objectives
    3215              :      * (LCA_STRATEGIC, LCA_SPEED etc) and maintaining lateral gap. The minimum
    3216              :      * acceptable lateral gap depends on
    3217              :      * - the cultural context (China vs Europe)
    3218              :      * - the driver agressiveness (willingness to encroach on other vehicles to force them to move laterally as well)
    3219              :      *    - see @note in checkBlocking
    3220              :      * - the vehicle type (car vs motorcycle)
    3221              :      * - the current speed
    3222              :      * - the speed difference
    3223              :      * - the importance / urgency of the desired maneuver
    3224              :      *
    3225              :      * the object of this method is to evaluate the above circumstances and
    3226              :      * either:
    3227              :      * - allow the current maneuver (state, latDist)
    3228              :      * - to override the current maneuver with a distance-keeping maneuver
    3229              :      *
    3230              :      *
    3231              :      * laneChangeModel/driver parameters
    3232              :      * - bool pushy (willingness to encroach)
    3233              :      * - float minGap at 100km/h (to be interpolated for lower speeds (assume 0 at speed 0)
    3234              :      * - gapFactors (a factor for each of the change reasons
    3235              :      *
    3236              :      * further assumptions
    3237              :      * - the maximum of egoSpeed and deltaSpeed can be used when interpolating minGap
    3238              :      * - distance keeping to the edges of the road can be ignored (for now)
    3239              :      *
    3240              :      * currentMinGap = minGap * min(1.0, max(v, abs(v - vOther)) / 100) * gapFactor[lc_reason]
    3241              :      *
    3242              :      * */
    3243              : 
    3244              :     /// XXX to be made configurable
    3245    115562710 :     double gapFactor = computeGapFactor(state);
    3246    115562710 :     const double oldLatDist = latDist;
    3247    115562710 :     const double oldManeuverDist = maneuverDist;
    3248              :     /// passed state is without traci-influence but we need it here
    3249    115562710 :     const int traciState = myVehicle.influenceChangeDecision(state);
    3250              : 
    3251              :     // compute gaps after maneuver
    3252    115562710 :     const double halfWidth = getWidth() * 0.5;
    3253              :     // if the current maneuver is blocked we will stay where we are
    3254    115562710 :     const double oldCenter = myVehicle.getCenterOnEdge();
    3255              :     // surplus gaps. these are used to collect various constraints
    3256              :     // if they do not permit the desired maneuvre, should override it to better maintain distance
    3257              :     // stay within the current edge
    3258    115562710 :     double surplusGapRight = oldCenter - halfWidth;
    3259    115562710 :     double surplusGapLeft = getLeftBorder(laneOffset != 0) - oldCenter - halfWidth;
    3260              :     const bool stayInLane = (laneOffset == 0
    3261    115562710 :                              || ((traciState & LCA_STRATEGIC) != 0
    3262              :                                  && (traciState & LCA_STAY) != 0
    3263              :                                  // permit wide vehicles to stay on the road
    3264     11633550 :                                  && (surplusGapLeft >= 0 && surplusGapRight >= 0)));
    3265              : 
    3266    115562710 :     if (isOpposite()) {
    3267              :         std::swap(surplusGapLeft, surplusGapRight);
    3268              :     }
    3269              : #ifdef DEBUG_KEEP_LATGAP
    3270              :     if (gDebugFlag2) {
    3271              :         std::cout << "\n  " << SIMTIME << " keepLatGap() laneOffset=" << laneOffset
    3272              :                   << " latDist=" << latDist
    3273              :                   << " maneuverDist=" << maneuverDist
    3274              :                   << " state=" << toString((LaneChangeAction)state)
    3275              :                   << " traciState=" << toString((LaneChangeAction)traciState)
    3276              :                   << " blocked=" << toString((LaneChangeAction)blocked)
    3277              :                   << " gapFactor=" << gapFactor
    3278              :                   << " stayInLane=" << stayInLane << "\n"
    3279              :                   << "       stayInEdge: surplusGapRight=" << surplusGapRight << " surplusGapLeft=" << surplusGapLeft << "\n";
    3280              :     }
    3281              : #endif
    3282              :     // staying within the edge overrides all minGap considerations
    3283    115562710 :     if (surplusGapLeft < 0 || surplusGapRight < 0) {
    3284              :         gapFactor = 0;
    3285              :     }
    3286              : 
    3287              :     // maintain gaps to vehicles on the current lane
    3288              :     // ignore vehicles that are too far behind
    3289    115562710 :     const double netOverlap = -myVehicle.getVehicleType().getLength() * 0.5;
    3290    115562710 :     updateGaps(leaders, myVehicle.getLane()->getRightSideOnEdge(), oldCenter, gapFactor, surplusGapRight, surplusGapLeft, true);
    3291    115562710 :     updateGaps(followers, myVehicle.getLane()->getRightSideOnEdge(), oldCenter, gapFactor, surplusGapRight, surplusGapLeft, true, netOverlap);
    3292              : 
    3293    115562710 :     if (laneOffset != 0) {
    3294              :         // maintain gaps to vehicles on the target lane
    3295     35545412 :         const double neighRight = getNeighRight(neighLane);
    3296     35545412 :         updateGaps(neighLeaders, neighRight, oldCenter, gapFactor, surplusGapRight, surplusGapLeft, true);
    3297     35545412 :         updateGaps(neighFollowers, neighRight, oldCenter, gapFactor, surplusGapRight, surplusGapLeft, true, netOverlap);
    3298              :     }
    3299              : #ifdef DEBUG_KEEP_LATGAP
    3300              :     if (gDebugFlag2) {
    3301              :         std::cout << "       minGapLat: surplusGapRight=" << surplusGapRight << " surplusGapLeft=" << surplusGapLeft << "\n"
    3302              :                   << "       lastGaps: right=" << myLastLateralGapRight << " left=" << myLastLateralGapLeft << "\n";
    3303              :     }
    3304              : #endif
    3305              :     // we also need to track the physical gap, in addition to the psychological gap
    3306    115562710 :     double physicalGapLeft = myLastLateralGapLeft == NO_NEIGHBOR ? surplusGapLeft : myLastLateralGapLeft;
    3307    115562710 :     double physicalGapRight = myLastLateralGapRight == NO_NEIGHBOR ? surplusGapRight : myLastLateralGapRight;
    3308              : 
    3309    115562710 :     const double halfLaneWidth = myVehicle.getLane()->getWidth() * 0.5;
    3310    115562710 :     const double posLat = myVehicle.getLateralPositionOnLane() * (isOpposite() ? -1 : 1);
    3311    115562710 :     if (stayInLane || laneOffset == 1) {
    3312              :         // do not move past the right boundary of the current lane (traffic wasn't checked there)
    3313              :         // but assume it's ok to be where we are in case we are already beyond
    3314    300216874 :         surplusGapRight  = MIN2(surplusGapRight,  MAX2(0.0, halfLaneWidth + posLat - halfWidth));
    3315              :         physicalGapRight = MIN2(physicalGapRight, MAX2(0.0, halfLaneWidth + posLat - halfWidth));
    3316              :     }
    3317    115562710 :     if (stayInLane || laneOffset == -1) {
    3318              :         // do not move past the left boundary of the current lane (traffic wasn't checked there)
    3319              :         // but assume it's ok to be where we are in case we are already beyond
    3320    282778494 :         surplusGapLeft  = MIN2(surplusGapLeft,  MAX2(0.0, halfLaneWidth - posLat - halfWidth));
    3321              :         physicalGapLeft = MIN2(physicalGapLeft, MAX2(0.0, halfLaneWidth - posLat - halfWidth));
    3322              :     }
    3323              : #ifdef DEBUG_KEEP_LATGAP
    3324              :     if (gDebugFlag2) {
    3325              :         std::cout << "       stayInLane: surplusGapRight=" << surplusGapRight << " surplusGapLeft=" << surplusGapLeft << "\n";
    3326              :     }
    3327              : #endif
    3328              : 
    3329    115562710 :     if (surplusGapRight + surplusGapLeft < 0) {
    3330              :         // insufficient lateral space to fulfill all requirements. apportion space proportionally
    3331      3351554 :         if ((state & LCA_CHANGE_REASONS) == 0) {
    3332        31756 :             state |= LCA_SUBLANE;
    3333              :         }
    3334      3351554 :         const double equalDeficit = 0.5 * (surplusGapLeft + surplusGapRight);
    3335      3351554 :         if (surplusGapRight < surplusGapLeft) {
    3336              :             // shift further to the left but no further than there is physical space
    3337      1061839 :             const double delta = MIN2(equalDeficit - surplusGapRight, physicalGapLeft);
    3338      1061839 :             latDist = delta;
    3339      1061839 :             maneuverDist = delta;
    3340              : #ifdef DEBUG_KEEP_LATGAP
    3341              :             if (gDebugFlag2) {
    3342              :                 std::cout << "    insufficient latSpace, move left: delta=" << delta << "\n";
    3343              :             }
    3344              : #endif
    3345              :         } else {
    3346              :             // shift further to the right but no further than there is physical space
    3347      2289715 :             const double delta = MIN2(equalDeficit - surplusGapLeft, physicalGapRight);
    3348      2289715 :             latDist = -delta;
    3349      2289715 :             maneuverDist = -delta;
    3350              : #ifdef DEBUG_KEEP_LATGAP
    3351              :             if (gDebugFlag2) {
    3352              :                 std::cout << "    insufficient latSpace, move right: delta=" << delta << "\n";
    3353              :             }
    3354              : #endif
    3355              :         }
    3356              :     } else {
    3357              :         // sufficient space. move as far as the gaps permit
    3358    112211156 :         latDist = MAX2(MIN2(latDist, surplusGapLeft), -surplusGapRight);
    3359    112211156 :         maneuverDist = MAX2(MIN2(maneuverDist, surplusGapLeft), -surplusGapRight);
    3360    112211156 :         if ((state & LCA_KEEPRIGHT) != 0 && maneuverDist != oldManeuverDist) {
    3361              :             // don't start keepRight unless it can be completed
    3362       145427 :             latDist = oldLatDist;
    3363       145427 :             maneuverDist = oldManeuverDist;
    3364              :         }
    3365              : #ifdef DEBUG_KEEP_LATGAP
    3366              :         if (gDebugFlag2) {
    3367              :             std::cout << "     adapted latDist=" << latDist << " maneuverDist=" << maneuverDist << " (old=" << oldLatDist << ")\n";
    3368              :         }
    3369              : #endif
    3370              :     }
    3371              :     // take into account overriding traci sublane-request
    3372    115562710 :     if (myVehicle.hasInfluencer() && myVehicle.getInfluencer().getLatDist() != 0) {
    3373              :         // @note: the influence is reset in MSAbstractLaneChangeModel::setOwnState at the end of the lane-changing code for this vehicle
    3374         2226 :         latDist = myVehicle.getInfluencer().getLatDist();
    3375         2226 :         maneuverDist = myVehicle.getInfluencer().getLatDist();
    3376         2226 :         if (latDist < 0) {
    3377         2465 :             mySafeLatDistRight = MAX2(-latDist, mySafeLatDistRight);
    3378              :         } else {
    3379         1542 :             mySafeLatDistLeft = MAX2(latDist, mySafeLatDistLeft);
    3380              :         }
    3381         2226 :         state |= LCA_TRACI;
    3382              : #ifdef DEBUG_KEEP_LATGAP
    3383              :         if (gDebugFlag2) {
    3384              :             std::cout << "     traci influenced latDist=" << latDist << "\n";
    3385              :         }
    3386              : #endif
    3387              :     }
    3388              :     // if we cannot move in the desired direction, consider the maneuver blocked anyway
    3389    115562710 :     const bool nonSublaneChange = (state & (LCA_STRATEGIC | LCA_COOPERATIVE | LCA_SPEEDGAIN | LCA_KEEPRIGHT)) != 0;
    3390    115562710 :     const bool traciChange = ((state | traciState) & LCA_TRACI) != 0;
    3391    115562710 :     if (nonSublaneChange && !traciChange) {
    3392     19229058 :         if ((latDist < NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) && (oldLatDist > 0)) {
    3393              : #ifdef DEBUG_KEEP_LATGAP
    3394              :             if (gDebugFlag2) {
    3395              :                 std::cout << "     wanted changeToLeft oldLatDist=" << oldLatDist << ", blocked latGap changeToRight\n";
    3396              :             }
    3397              : #endif
    3398      1146153 :             latDist = oldLatDist; // restore old request for usage in decideDirection()
    3399      1146153 :             blocked = LCA_OVERLAPPING | LCA_BLOCKED_LEFT;
    3400     18082905 :         } else if ((latDist > -NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) && (oldLatDist < 0)) {
    3401              : #ifdef DEBUG_KEEP_LATGAP
    3402              :             if (gDebugFlag2) {
    3403              :                 std::cout << "     wanted changeToRight oldLatDist=" << oldLatDist << ", blocked latGap changeToLeft\n";
    3404              :             }
    3405              : #endif
    3406       731592 :             latDist = oldLatDist; // restore old request for usage in decideDirection()
    3407       731592 :             blocked = LCA_OVERLAPPING | LCA_BLOCKED_RIGHT;
    3408              :         }
    3409              :     }
    3410              :     // if we move, even though we wish to stay, update the change reason (except for TraCI)
    3411    115562710 :     if (fabs(latDist) > NUMERICAL_EPS * myVehicle.getActionStepLengthSecs() && oldLatDist == 0) {
    3412       969440 :         state &= (~(LCA_CHANGE_REASONS | LCA_STAY) | LCA_TRACI);
    3413              :     }
    3414              :     // update blocked status
    3415    115562710 :     if (fabs(latDist - oldLatDist) > NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) {
    3416              : #ifdef DEBUG_KEEP_LATGAP
    3417              :         if (gDebugFlag2) {
    3418              :             std::cout << "     latDistUpdated=" << latDist << " oldLatDist=" << oldLatDist << "\n";
    3419              :         }
    3420              : #endif
    3421      4074393 :         blocked = checkBlocking(neighLane, latDist, maneuverDist, laneOffset, leaders, followers, blockers, neighLeaders, neighFollowers, neighBlockers, nullptr, nullptr, nonSublaneChange);
    3422              :     }
    3423    115562710 :     if (fabs(latDist) > NUMERICAL_EPS * myVehicle.getActionStepLengthSecs()) {
    3424     14306609 :         state = (state & ~LCA_STAY);
    3425     14306609 :         if ((state & LCA_CHANGE_REASONS) == 0) {
    3426       968248 :             state |= LCA_SUBLANE;
    3427              :         }
    3428              :     } else {
    3429    101256101 :         if ((state & LCA_SUBLANE) != 0) {
    3430     88325957 :             state |= LCA_STAY;
    3431              :         }
    3432              :         // avoid setting blinker due to numerical issues
    3433    101256101 :         latDist = 0;
    3434              :     }
    3435              : #if defined(DEBUG_KEEP_LATGAP) || defined(DEBUG_STATE)
    3436              :     if (gDebugFlag2) {
    3437              :         std::cout << "       latDist2=" << latDist
    3438              :                   << " state2=" << toString((LaneChangeAction)state)
    3439              :                   << " lastGapLeft=" << myLastLateralGapLeft
    3440              :                   << " lastGapRight=" << myLastLateralGapRight
    3441              :                   << " blockedAfter=" << toString((LaneChangeAction)blocked)
    3442              :                   << "\n";
    3443              :     }
    3444              : #endif
    3445    115562710 :     return state;
    3446              : }
    3447              : 
    3448              : 
    3449              : void
    3450    382731026 : MSLCM_SL2015::updateGaps(const MSLeaderDistanceInfo& others, double foeOffset, double oldCenter, double gapFactor,
    3451              :                          double& surplusGapRight, double& surplusGapLeft,
    3452              :                          bool saveMinGap, double netOverlap,
    3453              :                          double latDist,
    3454              :                          std::vector<CLeaderDist>* collectBlockers) {
    3455    382731026 :     if (others.hasVehicles()) {
    3456    324753231 :         const double halfWidth = getWidth() * 0.5 + NUMERICAL_EPS;
    3457    324753231 :         const double baseMinGap = myMinGapLat;
    3458   1712620099 :         for (int i = 0; i < others.numSublanes(); ++i) {
    3459   2698475368 :             if (others[i].first != 0 && others[i].second <= 0
    3460   1418938592 :                     && myCFRelated.count(others[i].first) == 0
    3461   1588194051 :                     && (netOverlap == 0 || others[i].second + others[i].first->getVehicleType().getMinGap() < netOverlap)) {
    3462              :                 /// foe vehicle occupies full sublanes
    3463    169408803 :                 const MSVehicle* foe = others[i].first;
    3464    169408803 :                 const double res = MSGlobals::gLateralResolution > 0 ? MSGlobals::gLateralResolution : others[i].first->getLane()->getWidth();
    3465              :                 double foeRight, foeLeft;
    3466    169408803 :                 others.getSublaneBorders(i, foeOffset, foeRight, foeLeft);
    3467    169408803 :                 const double foeCenter = foeRight + 0.5 * res;
    3468    169408803 :                 const double gap = MIN2(fabs(foeRight - oldCenter), fabs(foeLeft - oldCenter)) - halfWidth;
    3469    169408803 :                 const double deltaV = MIN2(LATGAP_SPEED_THRESHOLD, MAX3(LATGAP_SPEED_THRESHOLD2, myVehicle.getSpeed(), fabs(myVehicle.getSpeed() - foe->getSpeed())));
    3470    169408803 :                 const double desiredMinGap = baseMinGap * deltaV / LATGAP_SPEED_THRESHOLD;
    3471    169408803 :                 const double currentMinGap = desiredMinGap * gapFactor; // pushy vehicles may accept a lower lateral gap temporarily
    3472              :                 /*
    3473              :                 if (netOverlap != 0) {
    3474              :                     // foe vehicle is follower with its front ahead of the ego midpoint
    3475              :                     // scale gap requirements so it gets lower for foe which are further behind ego
    3476              :                     //
    3477              :                     // relOverlap approaches 0 as the foe gets closer to the midpoint and it equals 1 if the foe is driving head-to-head
    3478              :                     const double relOverlap = 1 - (others[i].second + others[i].first->getVehicleType().getMinGap()) / netOverlap;
    3479              :                     currentMinGap *= currOverlap * relOverlap;
    3480              :                 }
    3481              :                 */
    3482              : #if defined(DEBUG_BLOCKING) || defined(DEBUG_KEEP_LATGAP)
    3483              :                 if (debugVehicle()) {
    3484              :                     std::cout << "  updateGaps"
    3485              :                               << " i=" << i
    3486              :                               << " foe=" << foe->getID()
    3487              :                               << " foeRight=" << foeRight
    3488              :                               << " foeLeft=" << foeLeft
    3489              :                               << " oldCenter=" << oldCenter
    3490              :                               << " gap=" << others[i].second
    3491              :                               << " latgap=" << gap
    3492              :                               << " currentMinGap=" << currentMinGap
    3493              :                               << " surplusGapRight=" << surplusGapRight
    3494              :                               << " surplusGapLeft=" << surplusGapLeft
    3495              :                               << "\n";
    3496              :                 }
    3497              : #endif
    3498              : 
    3499              :                 // If foe is maneuvering towards ego, reserve some additional distance.
    3500              :                 // But don't expect the foe to come closer than currentMinGap if it isn't already there.
    3501              :                 //   (XXX: How can the ego know the foe's maneuver dist?)
    3502    169408803 :                 if (foeCenter < oldCenter) { // && foe->getLaneChangeModel().getSpeedLat() > 0) {
    3503     83818775 :                     const double foeManeuverDist = MAX2(0., foe->getLaneChangeModel().getManeuverDist());
    3504    241799337 :                     surplusGapRight = MIN3(surplusGapRight, gap - currentMinGap, MAX2(currentMinGap, gap - foeManeuverDist));
    3505              :                 } else { //if (foeCenter > oldCenter && foe->getLaneChangeModel().getSpeedLat() < 0) {
    3506     85590028 :                     const double foeManeuverDist = -MIN2(0., foe->getLaneChangeModel().getManeuverDist());
    3507    248234946 :                     surplusGapLeft = MIN3(surplusGapLeft, gap - currentMinGap, MAX2(currentMinGap, gap - foeManeuverDist));
    3508              :                 }
    3509    169408803 :                 if (saveMinGap) {
    3510     82217428 :                     if (foeCenter < oldCenter) {
    3511              : #if defined(DEBUG_BLOCKING) || defined(DEBUG_KEEP_LATGAP)
    3512              :                         if (gDebugFlag2 && gap < myLastLateralGapRight) {
    3513              :                             std::cout << "    new minimum rightGap=" << gap << "\n";
    3514              :                         }
    3515              : #endif
    3516     75297804 :                         myLastLateralGapRight = MIN2(myLastLateralGapRight, gap);
    3517              :                     } else {
    3518              : #if defined(DEBUG_BLOCKING) || defined(DEBUG_KEEP_LATGAP)
    3519              :                         if (gDebugFlag2 && gap < myLastLateralGapLeft) {
    3520              :                             std::cout << "    new minimum leftGap=" << gap << "\n";
    3521              :                         }
    3522              : #endif
    3523     52560164 :                         myLastLateralGapLeft = MIN2(myLastLateralGapLeft, gap);
    3524              :                     }
    3525              :                 }
    3526    169408803 :                 if (collectBlockers != nullptr) {
    3527              :                     // check if the vehicle is blocking a desire lane change
    3528      8584619 :                     if ((foeCenter < oldCenter && latDist < 0 && gap < (desiredMinGap - latDist))
    3529      6114406 :                             || (foeCenter > oldCenter && latDist > 0 && gap < (desiredMinGap + latDist))) {
    3530      7453864 :                         collectBlockers->push_back(others[i]);
    3531              :                     }
    3532              :                 }
    3533              :             }
    3534              :         }
    3535              :     }
    3536    382731026 : }
    3537              : 
    3538              : 
    3539              : double
    3540   1064611484 : MSLCM_SL2015::getWidth() const {
    3541   1064611484 :     return myVehicle.getVehicleType().getWidth() + NUMERICAL_EPS;
    3542              : }
    3543              : 
    3544              : 
    3545              : double
    3546    116373478 : MSLCM_SL2015::computeSpeedLat(double latDist, double& maneuverDist, bool urgent) const {
    3547    116373478 :     int currentDirection = mySpeedLat >= 0 ? 1 : -1;
    3548    116373478 :     int directionWish = latDist >= 0 ? 1 : -1;
    3549    116373478 :     double maxSpeedLat = myVehicle.getVehicleType().getMaxSpeedLat();
    3550    116373478 :     double accelLat = myAccelLat;
    3551    116373478 :     if (!urgent && (myLeftSpace > POSITION_EPS || myMaxSpeedLatFactor < 0)) {
    3552     67186240 :         const double speedBound = myMaxSpeedLatStanding + myMaxSpeedLatFactor * myVehicle.getSpeed();
    3553     67186240 :         if (myMaxSpeedLatFactor >= 0) {
    3554              :             // speedbound increases with speed and needs an upper bound
    3555              :             maxSpeedLat = MIN2(maxSpeedLat, speedBound);
    3556              :         } else {
    3557              :             // speedbound decreases with speed and needs a lower bound
    3558              :             // (only useful if myMaxSpeedLatStanding > maxSpeedLat)
    3559              :             maxSpeedLat = MAX2(maxSpeedLat, speedBound);
    3560              :             // increase (never decrease) lateral acceleration in proportion
    3561          498 :             accelLat *= MAX2(1.0, speedBound / myVehicle.getVehicleType().getMaxSpeedLat());
    3562              :         }
    3563              :     }
    3564    116373478 :     if (getWidth() < myVehicle.getCurrentEdge()->getWidth() && !isOpposite()) {
    3565    116281875 :         const double rightVehSide = myVehicle.getRightSideOnEdge();
    3566    116281875 :         const double edgeOverlap = MAX2(-rightVehSide, rightVehSide + myVehicle.getVehicleType().getWidth() - myVehicle.getCurrentEdge()->getWidth());
    3567              :         // if vehicle is outside edge bounds. Permit stronger lateral maneuvering
    3568    116281875 :         accelLat = MAX2(accelLat, 2 * edgeOverlap);
    3569              :         maxSpeedLat = MAX2(maxSpeedLat, edgeOverlap);
    3570              :     }
    3571              : 
    3572              : #ifdef DEBUG_MANEUVER
    3573              :     if (debugVehicle()) {
    3574              :         std::cout << SIMTIME
    3575              :                   << " veh=" << myVehicle.getID()
    3576              :                   << " computeSpeedLat()"
    3577              :                   << " latDist=" << latDist
    3578              :                   << " maneuverDist=" << maneuverDist
    3579              :                   << " urgent=" << urgent
    3580              :                   << " speedLat=" << mySpeedLat
    3581              :                   << " currentDirection=" << currentDirection
    3582              :                   << " directionWish=" << directionWish
    3583              :                   << " myLeftSpace=" << myLeftSpace
    3584              :                   << " maxSpeedLat=" << maxSpeedLat
    3585              :                   << std::endl;
    3586              :     }
    3587              : #endif
    3588              :     // reduced lateral speed (in the desired direction). Don't change direction against desired.
    3589              :     double speedDecel;
    3590    116373478 :     if (directionWish == 1) {
    3591    108746418 :         speedDecel = MAX2(mySpeedLat - ACCEL2SPEED(accelLat), 0.);
    3592              :     } else {
    3593      7627060 :         speedDecel = MIN2(mySpeedLat + ACCEL2SPEED(accelLat), 0.);
    3594              :     }
    3595              :     // increased lateral speed (in the desired direction)
    3596    116373478 :     double speedAccel = MAX2(MIN2(mySpeedLat + directionWish * ACCEL2SPEED(accelLat), maxSpeedLat), -maxSpeedLat);
    3597              : 
    3598              :     // can we reach the target distance in a single step? (XXX: assumes "Euler" update)
    3599    116373478 :     double speedBound = DIST2SPEED(latDist);
    3600              :     // for lat-gap keeping maneuvres myOrigLatDist may be 0
    3601    226167731 :     const double fullLatDist = latDist > 0 ? MIN2(mySafeLatDistLeft, MAX2(maneuverDist, latDist)) : MAX2(-mySafeLatDistRight, MIN2(maneuverDist, latDist));
    3602              : 
    3603              :     // update maneuverDist, if safety constraints apply in its direction
    3604    116373478 :     if (maneuverDist * latDist > 0) {
    3605     14250457 :         maneuverDist = fullLatDist;
    3606              :     }
    3607              : 
    3608              : #ifdef DEBUG_MANEUVER
    3609              :     if (debugVehicle()) {
    3610              :         std::cout << "     mySafeLatDistRight=" << mySafeLatDistRight
    3611              :                   << " mySafeLatDistLeft=" << mySafeLatDistLeft
    3612              :                   << " fullLatDist=" << fullLatDist
    3613              :                   << " speedAccel=" << speedAccel
    3614              :                   << " speedDecel=" << speedDecel
    3615              :                   << " speedBound=" << speedBound
    3616              :                   << std::endl;
    3617              :     }
    3618              : #endif
    3619    116373478 :     if (speedDecel * speedAccel <= 0 && (
    3620              :                 // speedAccel and speedDecel bracket speed 0. This means we can end the maneuver
    3621    107985371 :                 (latDist >= 0 && speedAccel >= speedBound && speedBound >= speedDecel)
    3622      8705440 :                 || (latDist <= 0 && speedAccel <= speedBound && speedBound <= speedDecel))) {
    3623              :         // we can reach the desired value in this step
    3624              : #ifdef DEBUG_MANEUVER
    3625              :         if (debugVehicle()) {
    3626              :             std::cout << "   computeSpeedLat a)\n";
    3627              :         }
    3628              : #endif
    3629              :         return speedBound;
    3630              :     }
    3631              :     // are we currently moving in the wrong direction?
    3632      3679351 :     if (latDist * mySpeedLat < 0) {
    3633              : #ifdef DEBUG_MANEUVER
    3634              :         if (debugVehicle()) {
    3635              :             std::cout << "   computeSpeedLat b)\n";
    3636              :         }
    3637              : #endif
    3638       445184 :         return emergencySpeedLat(speedAccel);
    3639              :     }
    3640              :     // check if the remaining distance allows to accelerate laterally
    3641      3234167 :     double minDistAccel = SPEED2DIST(speedAccel) + currentDirection * MSCFModel::brakeGapEuler(fabs(speedAccel), accelLat, 0); // most we can move in the target direction
    3642      3234167 :     if ((fabs(minDistAccel) < fabs(fullLatDist)) || (fabs(minDistAccel - fullLatDist) < NUMERICAL_EPS)) {
    3643              : #ifdef DEBUG_MANEUVER
    3644              :         if (debugVehicle()) {
    3645              :             std::cout << "   computeSpeedLat c)\n";
    3646              :         }
    3647              : #endif
    3648              :         return speedAccel;
    3649              :     } else {
    3650              : #ifdef DEBUG_MANEUVER
    3651              :         if (debugVehicle()) {
    3652              :             std::cout << "      minDistAccel=" << minDistAccel << "\n";
    3653              :         }
    3654              : #endif
    3655              :         // check if the remaining distance allows to maintain current lateral speed
    3656       612796 :         double minDistCurrent = SPEED2DIST(mySpeedLat) + currentDirection * MSCFModel::brakeGapEuler(fabs(mySpeedLat), accelLat, 0);
    3657       612796 :         if ((fabs(minDistCurrent) < fabs(fullLatDist)) || (fabs(minDistCurrent - fullLatDist) < NUMERICAL_EPS)) {
    3658              : #ifdef DEBUG_MANEUVER
    3659              :             if (debugVehicle()) {
    3660              :                 std::cout << "   computeSpeedLat d)\n";
    3661              :             }
    3662              : #endif
    3663       145680 :             return mySpeedLat;
    3664              :         }
    3665              :     }
    3666              :     // reduce lateral speed
    3667              : #ifdef DEBUG_MANEUVER
    3668              :     if (debugVehicle()) {
    3669              :         std::cout << "   computeSpeedLat e)\n";
    3670              :     }
    3671              : #endif
    3672       467116 :     return emergencySpeedLat(speedDecel);
    3673              : }
    3674              : 
    3675              : 
    3676              : double
    3677       912300 : MSLCM_SL2015::emergencySpeedLat(double speedLat) const {
    3678              :     // reduce lateral speed for safety purposes
    3679       912300 :     if (speedLat < 0 && SPEED2DIST(-speedLat) > mySafeLatDistRight) {
    3680        14673 :         speedLat = -DIST2SPEED(mySafeLatDistRight);
    3681              : #ifdef DEBUG_MANEUVER
    3682              :         if (debugVehicle()) {
    3683              :             std::cout << "   rightDanger speedLat=" << speedLat << "\n";
    3684              :         }
    3685              : #endif
    3686       897627 :     } else if (speedLat > 0 && SPEED2DIST(speedLat) > mySafeLatDistLeft) {
    3687        24016 :         speedLat = DIST2SPEED(mySafeLatDistLeft);
    3688              : #ifdef DEBUG_MANEUVER
    3689              :         if (debugVehicle()) {
    3690              :             std::cout << "   leftDanger speedLat=" << speedLat << "\n";
    3691              :         }
    3692              : #endif
    3693              :     }
    3694       912300 :     return speedLat;
    3695              : }
    3696              : 
    3697              : 
    3698              : LatAlignmentDefinition
    3699     97017356 : MSLCM_SL2015::getDesiredAlignment() const {
    3700              :     LatAlignmentDefinition align = MSAbstractLaneChangeModel::getDesiredAlignment();
    3701              :     // Check whether the vehicle should adapt its alignment to an upcoming turn
    3702     97017356 :     if (myTurnAlignmentDist > 0) {
    3703       376643 :         const std::pair<double, const MSLink*>& turnInfo = myVehicle.getNextTurn();
    3704       376643 :         const LinkDirection turnDir = turnInfo.second == nullptr ? LinkDirection::NODIR : turnInfo.second->getDirection();
    3705       376643 :         const bool indirect = turnInfo.second == nullptr ? false : turnInfo.second->isIndirect();
    3706       376643 :         if (turnInfo.first < myTurnAlignmentDist) {
    3707              :             // Vehicle is close enough to the link to change its default alignment
    3708       158642 :             switch (turnDir) {
    3709        13757 :                 case LinkDirection::TURN:
    3710              :                 case LinkDirection::LEFT:
    3711              :                 case LinkDirection::PARTLEFT:
    3712        13757 :                     if (myVehicle.getLane()->getBidiLane() == nullptr) {
    3713              :                         // no left alignment on bidi lane to avoid blocking oncoming traffic
    3714        13689 :                         align = MSGlobals::gLefthand != indirect ? LatAlignmentDefinition::RIGHT : LatAlignmentDefinition::LEFT;
    3715              :                     }
    3716              :                     break;
    3717        12791 :                 case LinkDirection::TURN_LEFTHAND:
    3718              :                 case LinkDirection::RIGHT:
    3719              :                 case LinkDirection::PARTRIGHT:
    3720        12791 :                     align = MSGlobals::gLefthand != indirect ? LatAlignmentDefinition::LEFT : LatAlignmentDefinition::RIGHT;
    3721              :                     break;
    3722              :                 case LinkDirection::STRAIGHT:
    3723              :                 case LinkDirection::NODIR:
    3724              :                 default:
    3725              :                     break;
    3726              :             }
    3727              :         }
    3728              :     }
    3729     97017356 :     return align;
    3730              : }
    3731              : 
    3732              : 
    3733              : void
    3734       902046 : MSLCM_SL2015::commitManoeuvre(int blocked, int blockedFully,
    3735              :                               const MSLeaderDistanceInfo& leaders,
    3736              :                               const MSLeaderDistanceInfo& neighLeaders,
    3737              :                               const MSLane& neighLane,
    3738              :                               double maneuverDist) {
    3739       902046 :     if (!blocked && !blockedFully && !myCanChangeFully) {
    3740              :         // round to full action steps
    3741              :         double secondsToLeaveLane;
    3742       477595 :         if (MSGlobals::gSemiImplicitEulerUpdate) {
    3743       408796 :             secondsToLeaveLane = ceil(fabs(maneuverDist) / myVehicle.getVehicleType().getMaxSpeedLat() / myVehicle.getActionStepLengthSecs()) * myVehicle.getActionStepLengthSecs();
    3744              :             // XXX myAccelLat must be taken into account (refs #3601, see ballistic case for solution)
    3745              : 
    3746              :             // XXX This also causes probs: if the difference between the current speed and the committed is higher than the maximal decel,
    3747              :             //     the vehicle may pass myLeftSpace before completing the maneuver.
    3748       817592 :             myCommittedSpeed = MIN3(myLeftSpace / secondsToLeaveLane,
    3749       408796 :                                     myVehicle.getCarFollowModel().maxNextSpeed(myVehicle.getSpeed(), &myVehicle),
    3750       408796 :                                     myVehicle.getLane()->getVehicleMaxSpeed(&myVehicle));
    3751              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3752              :             if (debugVehicle()) {
    3753              :                 std::cout << SIMTIME << " veh=" << myVehicle.getID() << " myCommittedSpeed=" << myCommittedSpeed << " leftSpace=" << myLeftSpace << " secondsToLeave=" << secondsToLeaveLane << "\n";
    3754              :             }
    3755              : #endif
    3756              :         } else {
    3757              : 
    3758              :             // Calculate seconds needed for leaving lane assuming start from lateral speed zero, and lat.accel == -lat.decel
    3759        68799 :             secondsToLeaveLane = MSCFModel::estimateArrivalTime(fabs(maneuverDist), 0., 0., myVehicle.getVehicleType().getMaxSpeedLat(), myAccelLat, myAccelLat);
    3760              :             // round to full action steps
    3761        68799 :             secondsToLeaveLane = ceil(secondsToLeaveLane / myVehicle.getActionStepLengthSecs()) * myVehicle.getActionStepLengthSecs();
    3762              : 
    3763              :             // committed speed will eventually be pushed into a drive item during the next planMove() step. This item
    3764              :             // will not be read before the next action step at current time + actionStepLength-TS, so we need to schedule the corresponding speed.
    3765        68799 :             const double timeTillActionStep = myVehicle.getActionStepLengthSecs() - TS;
    3766        68799 :             const double nextActionStepSpeed = MAX2(0., myVehicle.getSpeed() + timeTillActionStep * myVehicle.getAcceleration());
    3767              :             double nextLeftSpace;
    3768        68442 :             if (nextActionStepSpeed > 0.) {
    3769        68439 :                 nextLeftSpace = myLeftSpace - timeTillActionStep * (myVehicle.getSpeed() + nextActionStepSpeed) * 0.5;
    3770          360 :             } else if (myVehicle.getAcceleration() == 0) {
    3771            0 :                 nextLeftSpace = myLeftSpace;
    3772              :             } else {
    3773              :                 assert(myVehicle.getAcceleration() < 0.);
    3774          360 :                 nextLeftSpace = myLeftSpace + (myVehicle.getSpeed() * myVehicle.getSpeed() / myVehicle.getAcceleration()) * 0.5;
    3775              :             }
    3776        68799 :             const double avoidArrivalSpeed = nextActionStepSpeed + ACCEL2SPEED(MSCFModel::avoidArrivalAccel(
    3777              :                                                  nextLeftSpace, secondsToLeaveLane - timeTillActionStep, nextActionStepSpeed, myVehicle.getCarFollowModel().getEmergencyDecel()));
    3778              : 
    3779       137598 :             myCommittedSpeed = MIN3(avoidArrivalSpeed,
    3780        68799 :                                     myVehicle.getSpeed() + myVehicle.getCarFollowModel().getMaxAccel() * myVehicle.getActionStepLengthSecs(),
    3781        68799 :                                     myVehicle.getLane()->getVehicleMaxSpeed(&myVehicle));
    3782              : 
    3783              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3784              :             if (gDebugFlag2) {
    3785              :                 std::cout << SIMTIME
    3786              :                           << " veh=" << myVehicle.getID()
    3787              :                           << " avoidArrivalSpeed=" << avoidArrivalSpeed
    3788              :                           << " currentSpeed=" << myVehicle.getSpeed()
    3789              :                           << " myLeftSpace=" << myLeftSpace
    3790              :                           << "\n             nextLeftSpace=" << nextLeftSpace
    3791              :                           << " nextActionStepSpeed=" << nextActionStepSpeed
    3792              :                           << " nextActionStepRemainingSeconds=" << secondsToLeaveLane - timeTillActionStep
    3793              :                           << "\n";
    3794              :             }
    3795              : #endif
    3796              :         }
    3797       477595 :         myCommittedSpeed = commitFollowSpeed(myCommittedSpeed, maneuverDist, secondsToLeaveLane, leaders, myVehicle.getLane()->getRightSideOnEdge());
    3798       477595 :         myCommittedSpeed = commitFollowSpeed(myCommittedSpeed, maneuverDist, secondsToLeaveLane, neighLeaders, neighLane.getRightSideOnEdge());
    3799       477595 :         if (myCommittedSpeed < myVehicle.getCarFollowModel().minNextSpeed(myVehicle.getSpeed(), &myVehicle)) {
    3800        71492 :             myCommittedSpeed = 0;
    3801              :         }
    3802              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3803              :         if (gDebugFlag2) {
    3804              :             std::cout << SIMTIME
    3805              :                       << " veh=" << myVehicle.getID()
    3806              :                       << " secondsToLeave=" << secondsToLeaveLane
    3807              :                       << " maxNext=" << myVehicle.getCarFollowModel().maxNextSpeed(myVehicle.getSpeed(), &myVehicle)
    3808              :                       << " committed=" << myCommittedSpeed
    3809              :                       << "\n";
    3810              :         }
    3811              : #endif
    3812              :     }
    3813       902046 : }
    3814              : 
    3815              : double
    3816       955190 : MSLCM_SL2015::commitFollowSpeed(double speed, double latDist, double secondsToLeaveLane, const MSLeaderDistanceInfo& leaders, double foeOffset) const {
    3817       955190 :     if (leaders.hasVehicles()) {
    3818              :         // we distinguish 3 cases
    3819              :         // - vehicles with lateral overlap at the end of the maneuver: try to follow safely
    3820              :         // - vehicles with overlap at the start of the maneuver: avoid collision within secondsToLeaveLane
    3821              :         // - vehicles without overlap: ignore
    3822              : 
    3823       448195 :         const double maxDecel = myVehicle.getCarFollowModel().getMaxDecel();
    3824              :         // temporarily use another decel value
    3825              :         MSCFModel& cfmodel = const_cast<MSCFModel&>(myVehicle.getCarFollowModel());
    3826       448195 :         cfmodel.setMaxDecel(maxDecel / getSafetyFactor());
    3827              : 
    3828       448195 :         const double vehWidth = getWidth();
    3829       448195 :         const double rightVehSide = myVehicle.getCenterOnEdge() - 0.5 * vehWidth;
    3830       448195 :         const double leftVehSide = rightVehSide + vehWidth;
    3831       448195 :         const double rightVehSideDest = rightVehSide + latDist;
    3832       448195 :         const double leftVehSideDest = leftVehSide + latDist;
    3833              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3834              :         if (gDebugFlag2) {
    3835              :             std::cout << "  commitFollowSpeed"
    3836              :                       << " latDist=" << latDist
    3837              :                       << " foeOffset=" << foeOffset
    3838              :                       << " vehRight=" << rightVehSide
    3839              :                       << " vehLeft=" << leftVehSide
    3840              :                       << " destRight=" << rightVehSideDest
    3841              :                       << " destLeft=" << leftVehSideDest
    3842              :                       << "\n";
    3843              :         }
    3844              : #endif
    3845      2524931 :         for (int i = 0; i < leaders.numSublanes(); ++i) {
    3846      2076736 :             CLeaderDist vehDist = leaders[i];
    3847      2076736 :             if (vehDist.first != 0) {
    3848              :                 const MSVehicle* leader = vehDist.first;
    3849              :                 // only check the current stripe occuped by foe (transform into edge-coordinates)
    3850              :                 double foeRight, foeLeft;
    3851      1628557 :                 leaders.getSublaneBorders(i, foeOffset, foeRight, foeLeft);
    3852              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3853              :                 if (gDebugFlag2) {
    3854              :                     std::cout << "   foe=" << vehDist.first->getID()
    3855              :                               << " gap=" << vehDist.second
    3856              :                               << " secGap=" << myVehicle.getCarFollowModel().getSecureGap(&myVehicle, leader, myVehicle.getSpeed(), leader->getSpeed(), leader->getCarFollowModel().getMaxDecel())
    3857              :                               << " foeRight=" << foeRight
    3858              :                               << " foeLeft=" << foeLeft
    3859              :                               << " overlapBefore=" << overlap(rightVehSide, leftVehSide, foeRight, foeLeft)
    3860              :                               << " overlapDest=" << overlap(rightVehSideDest, leftVehSideDest, foeRight, foeLeft)
    3861              :                               << "\n";
    3862              :                 }
    3863              : #endif
    3864      1628557 :                 if (overlap(rightVehSideDest, leftVehSideDest, foeRight, foeLeft)) {
    3865              :                     // case 1
    3866       738702 :                     const double vSafe = myVehicle.getCarFollowModel().followSpeed(
    3867       738702 :                                              &myVehicle, speed, vehDist.second, leader->getSpeed(), leader->getCarFollowModel().getMaxDecel());
    3868              :                     speed = MIN2(speed, vSafe);
    3869              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3870              :                     if (gDebugFlag2) {
    3871              :                         std::cout << "     case1 vsafe=" << vSafe << " speed=" << speed << "\n";
    3872              :                     }
    3873              : #endif
    3874       889855 :                 } else if (overlap(rightVehSide, leftVehSide, foeRight, foeLeft)) {
    3875              :                     // case 2
    3876       446108 :                     const double vSafe = myVehicle.getCarFollowModel().followSpeedTransient(
    3877              :                                              secondsToLeaveLane,
    3878       446108 :                                              &myVehicle, speed, vehDist.second, leader->getSpeed(), leader->getCarFollowModel().getMaxDecel());
    3879              :                     speed = MIN2(speed, vSafe);
    3880              : #if defined(DEBUG_MANEUVER) || defined(DEBUG_COMMITTED_SPEED)
    3881              :                     if (gDebugFlag2) {
    3882              :                         std::cout << "     case2 vsafe=" << vSafe << " speed=" << speed << "\n";
    3883              :                     }
    3884              : #endif
    3885              :                 }
    3886              :             }
    3887              :         }
    3888              :         // restore original deceleration
    3889       448195 :         cfmodel.setMaxDecel(maxDecel);
    3890              : 
    3891              :     }
    3892       955190 :     return speed;
    3893              : }
    3894              : 
    3895              : double
    3896    772785830 : MSLCM_SL2015::getSafetyFactor() const {
    3897    772785830 :     return 1 / ((1 + 0.5 * myImpatience) * myAssertive);
    3898              : }
    3899              : 
    3900              : double
    3901      1831724 : MSLCM_SL2015::getOppositeSafetyFactor() const {
    3902      1831724 :     return myOppositeParam <= 0 ? std::numeric_limits<double>::max() : 1 / myOppositeParam;
    3903              : }
    3904              : 
    3905              : 
    3906              : std::string
    3907          154 : MSLCM_SL2015::getParameter(const std::string& key) const {
    3908          154 :     if (key == toString(SUMO_ATTR_LCA_STRATEGIC_PARAM)) {
    3909           36 :         return toString(myStrategicParam);
    3910          118 :     } else if (key == toString(SUMO_ATTR_LCA_COOPERATIVE_PARAM)) {
    3911           36 :         return toString(myCooperativeParam);
    3912           82 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAIN_PARAM)) {
    3913           36 :         return toString(mySpeedGainParam);
    3914           46 :     } else if (key == toString(SUMO_ATTR_LCA_KEEPRIGHT_PARAM)) {
    3915            0 :         return toString(myKeepRightParam);
    3916           46 :     } else if (key == toString(SUMO_ATTR_LCA_OPPOSITE_PARAM)) {
    3917            0 :         return toString(myOppositeParam);
    3918           46 :     } else if (key == toString(SUMO_ATTR_LCA_SUBLANE_PARAM)) {
    3919            0 :         return toString(mySublaneParam);
    3920           46 :     } else if (key == toString(SUMO_ATTR_MINGAP_LAT)) {
    3921           46 :         return toString(myMinGapLat);
    3922            0 :     } else if (key == toString(SUMO_ATTR_LCA_PUSHY)) {
    3923            0 :         return toString(myPushy);
    3924            0 :     } else if (key == toString(SUMO_ATTR_LCA_PUSHYGAP)) {
    3925            0 :         return toString((myPushy - 1) * myMinGapLat);
    3926            0 :     } else if (key == toString(SUMO_ATTR_LCA_ASSERTIVE)) {
    3927            0 :         return toString(myAssertive);
    3928            0 :     } else if (key == toString(SUMO_ATTR_LCA_IMPATIENCE)) {
    3929            0 :         return toString(myImpatience);
    3930            0 :     } else if (key == toString(SUMO_ATTR_LCA_TIME_TO_IMPATIENCE)) {
    3931            0 :         return toString(myTimeToImpatience);
    3932            0 :     } else if (key == toString(SUMO_ATTR_LCA_ACCEL_LAT)) {
    3933            0 :         return toString(myAccelLat);
    3934            0 :     } else if (key == toString(SUMO_ATTR_LCA_LOOKAHEADLEFT)) {
    3935            0 :         return toString(myLookaheadLeft);
    3936            0 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAINRIGHT)) {
    3937            0 :         return toString(mySpeedGainRight);
    3938            0 :     } else if (key == toString(SUMO_ATTR_LCA_LANE_DISCIPLINE)) {
    3939            0 :         return toString(myLaneDiscipline);
    3940            0 :     } else if (key == toString(SUMO_ATTR_LCA_SIGMA)) {
    3941            0 :         return toString(mySigma);
    3942            0 :     } else if (key == toString(SUMO_ATTR_LCA_KEEPRIGHT_ACCEPTANCE_TIME)) {
    3943            0 :         return toString(myKeepRightAcceptanceTime);
    3944            0 :     } else if (key == toString(SUMO_ATTR_LCA_OVERTAKE_DELTASPEED_FACTOR)) {
    3945            0 :         return toString(myOvertakeDeltaSpeedFactor);
    3946            0 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAIN_LOOKAHEAD)) {
    3947            0 :         return toString(mySpeedGainLookahead);
    3948            0 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAIN_REMAIN_TIME)) {
    3949            0 :         return toString(mySpeedGainRemainTime);
    3950            0 :     } else if (key == toString(SUMO_ATTR_LCA_COOPERATIVE_ROUNDABOUT)) {
    3951            0 :         return toString(myRoundaboutBonus);
    3952            0 :     } else if (key == toString(SUMO_ATTR_LCA_COOPERATIVE_SPEED)) {
    3953            0 :         return toString(myCooperativeSpeed);
    3954            0 :     } else if (key == toString(SUMO_ATTR_LCA_MAXSPEEDLATSTANDING)) {
    3955            0 :         return toString(myMaxSpeedLatStanding);
    3956            0 :     } else if (key == toString(SUMO_ATTR_LCA_MAXSPEEDLATFACTOR)) {
    3957            0 :         return toString(myMaxSpeedLatFactor);
    3958            0 :     } else if (key == toString(SUMO_ATTR_LCA_MAXDISTLATSTANDING)) {
    3959            0 :         return toString(myMaxDistLatStanding);
    3960              :         // access to internal state for debugging in sumo-gui (not documented since it may change at any time)
    3961            0 :     } else if (key == "speedGainProbabilityRight") {
    3962            0 :         return toString(mySpeedGainProbabilityRight);
    3963            0 :     } else if (key == "speedGainProbabilityLeft") {
    3964            0 :         return toString(mySpeedGainProbabilityLeft);
    3965            0 :     } else if (key == "keepRightProbability") {
    3966            0 :         return toString(myKeepRightProbability);
    3967            0 :     } else if (key == "lookAheadSpeed") {
    3968            0 :         return toString(myLookAheadSpeed);
    3969            0 :     } else if (key == "sigmaState") {
    3970            0 :         return toString(mySigmaState);
    3971              :         // motivation relative to threshold
    3972            0 :     } else if (key == "speedGainRP") {
    3973            0 :         return toString(mySpeedGainProbabilityRight / myChangeProbThresholdRight);
    3974            0 :     } else if (key == "speedGainLP") {
    3975            0 :         return toString(mySpeedGainProbabilityLeft / myChangeProbThresholdLeft);
    3976            0 :     } else if (key == "keepRightP") {
    3977            0 :         return toString(myKeepRightProbability * myKeepRightParam / myChangeProbThresholdRight);
    3978              :     }
    3979            0 :     throw InvalidArgument("Parameter '" + key + "' is not supported for laneChangeModel of type '" + toString(myModel) + "'");
    3980              : }
    3981              : 
    3982              : void
    3983       278292 : MSLCM_SL2015::setParameter(const std::string& key, const std::string& value) {
    3984              :     double doubleValue;
    3985              :     try {
    3986       278292 :         doubleValue = StringUtils::toDouble(value);
    3987            0 :     } catch (NumberFormatException&) {
    3988            0 :         throw InvalidArgument("Setting parameter '" + key + "' requires a number for laneChangeModel of type '" + toString(myModel) + "'");
    3989            0 :     }
    3990       278292 :     if (key == toString(SUMO_ATTR_LCA_STRATEGIC_PARAM)) {
    3991        71256 :         myStrategicParam = doubleValue;
    3992       207036 :     } else if (key == toString(SUMO_ATTR_LCA_COOPERATIVE_PARAM)) {
    3993            0 :         myCooperativeParam = doubleValue;
    3994       207036 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAIN_PARAM)) {
    3995            0 :         mySpeedGainParam = doubleValue;
    3996       207036 :     } else if (key == toString(SUMO_ATTR_LCA_KEEPRIGHT_PARAM)) {
    3997            0 :         myKeepRightParam = doubleValue;
    3998       207036 :     } else if (key == toString(SUMO_ATTR_LCA_OPPOSITE_PARAM)) {
    3999            0 :         myOppositeParam = doubleValue;
    4000       207036 :     } else if (key == toString(SUMO_ATTR_LCA_SUBLANE_PARAM)) {
    4001            0 :         mySublaneParam = doubleValue;
    4002       207036 :     } else if (key == toString(SUMO_ATTR_MINGAP_LAT)) {
    4003        69018 :         myMinGapLat = doubleValue;
    4004       138018 :     } else if (key == toString(SUMO_ATTR_LCA_PUSHY)) {
    4005            0 :         myPushy = doubleValue;
    4006       138018 :     } else if (key == toString(SUMO_ATTR_LCA_PUSHYGAP)) {
    4007            0 :         myPushy = 1 - doubleValue / myMinGapLat;
    4008       138018 :     } else if (key == toString(SUMO_ATTR_LCA_ASSERTIVE)) {
    4009            0 :         myAssertive = doubleValue;
    4010       138018 :     } else if (key == toString(SUMO_ATTR_LCA_IMPATIENCE)) {
    4011            0 :         myImpatience = doubleValue;
    4012            0 :         myMinImpatience = doubleValue;
    4013       138018 :     } else if (key == toString(SUMO_ATTR_LCA_TIME_TO_IMPATIENCE)) {
    4014            0 :         myTimeToImpatience = doubleValue;
    4015       138018 :     } else if (key == toString(SUMO_ATTR_LCA_ACCEL_LAT)) {
    4016            0 :         myAccelLat = doubleValue;
    4017       138018 :     } else if (key == toString(SUMO_ATTR_LCA_TURN_ALIGNMENT_DISTANCE)) {
    4018            0 :         myTurnAlignmentDist = doubleValue;
    4019       138018 :     } else if (key == toString(SUMO_ATTR_LCA_LOOKAHEADLEFT)) {
    4020            0 :         myLookaheadLeft = doubleValue;
    4021       138018 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAINRIGHT)) {
    4022            0 :         mySpeedGainRight = doubleValue;
    4023       138018 :     } else if (key == toString(SUMO_ATTR_LCA_LANE_DISCIPLINE)) {
    4024            0 :         myLaneDiscipline = doubleValue;
    4025       138018 :     } else if (key == toString(SUMO_ATTR_LCA_SIGMA)) {
    4026            0 :         mySigma = doubleValue;
    4027       138018 :     } else if (key == toString(SUMO_ATTR_LCA_KEEPRIGHT_ACCEPTANCE_TIME)) {
    4028            0 :         myKeepRightAcceptanceTime = doubleValue;
    4029       138018 :     } else if (key == toString(SUMO_ATTR_LCA_OVERTAKE_DELTASPEED_FACTOR)) {
    4030            0 :         myOvertakeDeltaSpeedFactor = doubleValue;
    4031       138018 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAIN_LOOKAHEAD)) {
    4032        69009 :         mySpeedGainLookahead = doubleValue;
    4033        69009 :     } else if (key == toString(SUMO_ATTR_LCA_SPEEDGAIN_REMAIN_TIME)) {
    4034        69009 :         mySpeedGainRemainTime = doubleValue;
    4035            0 :     } else if (key == toString(SUMO_ATTR_LCA_COOPERATIVE_ROUNDABOUT)) {
    4036            0 :         myRoundaboutBonus = doubleValue;
    4037            0 :     } else if (key == toString(SUMO_ATTR_LCA_COOPERATIVE_SPEED)) {
    4038            0 :         myCooperativeSpeed = doubleValue;
    4039            0 :     } else if (key == toString(SUMO_ATTR_LCA_MAXSPEEDLATSTANDING)) {
    4040            0 :         myMaxSpeedLatStanding = doubleValue;
    4041            0 :     } else if (key == toString(SUMO_ATTR_LCA_MAXSPEEDLATFACTOR)) {
    4042            0 :         myMaxSpeedLatFactor = doubleValue;
    4043            0 :     } else if (key == toString(SUMO_ATTR_LCA_MAXDISTLATSTANDING)) {
    4044            0 :         myMaxDistLatStanding = doubleValue;
    4045              :         // access to internal state
    4046            0 :     } else if (key == "speedGainProbabilityRight") {
    4047            0 :         mySpeedGainProbabilityRight = doubleValue;
    4048            0 :     } else if (key == "speedGainProbabilityLeft") {
    4049            0 :         mySpeedGainProbabilityLeft = doubleValue;
    4050            0 :     } else if (key == "keepRightProbability") {
    4051            0 :         myKeepRightProbability = doubleValue;
    4052            0 :     } else if (key == "lookAheadSpeed") {
    4053            0 :         myLookAheadSpeed = doubleValue;
    4054            0 :     } else if (key == "sigmaState") {
    4055            0 :         mySigmaState = doubleValue;
    4056              :     } else {
    4057            0 :         throw InvalidArgument("Setting parameter '" + key + "' is not supported for laneChangeModel of type '" + toString(myModel) + "'");
    4058              :     }
    4059       278292 :     initDerivedParameters();
    4060       278292 : }
    4061              : 
    4062              : 
    4063              : int
    4064         3259 : MSLCM_SL2015::wantsChange(
    4065              :     int laneOffset,
    4066              :     MSAbstractLaneChangeModel::MSLCMessager& /* msgPass */,
    4067              :     int blocked,
    4068              :     const std::pair<MSVehicle*, double>& leader,
    4069              :     const std::pair<MSVehicle*, double>& follower,
    4070              :     const std::pair<MSVehicle*, double>& neighLead,
    4071              :     const std::pair<MSVehicle*, double>& neighFollow,
    4072              :     const MSLane& neighLane,
    4073              :     const std::vector<MSVehicle::LaneQ>& preb,
    4074              :     MSVehicle** lastBlocked,
    4075              :     MSVehicle** firstBlocked) {
    4076              : 
    4077              :     const LaneChangeAction alternatives = LCA_NONE; // @todo pas this data
    4078              : 
    4079              : #ifdef DEBUG_WANTSCHANGE
    4080              :     if (DEBUG_COND) {
    4081              :         std::cout << "\nWANTS_CHANGE\n" << SIMTIME
    4082              :                   //<< std::setprecision(10)
    4083              :                   << " veh=" << myVehicle.getID()
    4084              :                   << " lane=" << myVehicle.getLane()->getID()
    4085              :                   << " neigh=" << neighLane.getID()
    4086              :                   << " pos=" << myVehicle.getPositionOnLane()
    4087              :                   << " posLat=" << myVehicle.getLateralPositionOnLane()
    4088              :                   << " speed=" << myVehicle.getSpeed()
    4089              :                   << " considerChangeTo=" << (laneOffset == -1  ? "right" : "left")
    4090              :                   << "\n";
    4091              :     }
    4092              : #endif
    4093              : 
    4094         3259 :     double latDist = 0;
    4095         3259 :     const double laneWidth = myVehicle.getLane()->getWidth();
    4096         3259 :     MSLeaderDistanceInfo leaders(leader, laneWidth);
    4097         3259 :     MSLeaderDistanceInfo followers(follower, laneWidth);
    4098         3259 :     MSLeaderDistanceInfo blockers(std::make_pair((MSVehicle*)nullptr, -1), laneWidth);
    4099         3259 :     MSLeaderDistanceInfo neighLeaders(neighLead, laneWidth);
    4100         3259 :     MSLeaderDistanceInfo neighFollowers(neighFollow, laneWidth);
    4101         3259 :     MSLeaderDistanceInfo neighBlockers(std::make_pair((MSVehicle*)nullptr, -1), laneWidth);
    4102              : 
    4103              :     double maneuverDist;
    4104         3259 :     int result = _wantsChangeSublane(laneOffset,
    4105              :                                      alternatives,
    4106              :                                      leaders, followers, blockers,
    4107              :                                      neighLeaders, neighFollowers, neighBlockers,
    4108              :                                      neighLane, preb,
    4109              :                                      lastBlocked, firstBlocked, latDist, maneuverDist, blocked);
    4110              : 
    4111         3259 :     myCanChangeFully = true;
    4112              :     // ignore sublane motivation
    4113         3259 :     result &= ~LCA_SUBLANE;
    4114         3259 :     result |= getLCA(result, latDist);
    4115              : 
    4116              : #if defined(DEBUG_WANTSCHANGE) || defined(DEBUG_STATE)
    4117              :     if (DEBUG_COND) {
    4118              :         if (result & LCA_WANTS_LANECHANGE) {
    4119              :             std::cout << SIMTIME
    4120              :                       << " veh=" << myVehicle.getID()
    4121              :                       << " wantsChangeTo=" << (laneOffset == -1  ? "right" : "left")
    4122              :                       << ((result & LCA_URGENT) ? " (urgent)" : "")
    4123              :                       << ((result & LCA_CHANGE_TO_HELP) ? " (toHelp)" : "")
    4124              :                       << ((result & LCA_STRATEGIC) ? " (strat)" : "")
    4125              :                       << ((result & LCA_COOPERATIVE) ? " (coop)" : "")
    4126              :                       << ((result & LCA_SPEEDGAIN) ? " (speed)" : "")
    4127              :                       << ((result & LCA_KEEPRIGHT) ? " (keepright)" : "")
    4128              :                       << ((result & LCA_TRACI) ? " (traci)" : "")
    4129              :                       << ((blocked & LCA_BLOCKED) ? " (blocked)" : "")
    4130              :                       << ((blocked & LCA_OVERLAPPING) ? " (overlap)" : "")
    4131              :                       << "\n\n\n";
    4132              :         }
    4133              :     }
    4134              : #endif
    4135              : 
    4136         3259 :     return result;
    4137         3259 : }
    4138              : 
    4139              : 
    4140              : double
    4141    135746780 : MSLCM_SL2015::getLeftBorder(bool checkOpposite) const {
    4142    135746780 :     return (myVehicle.getLane()->getEdge().getWidth()
    4143    135746780 :             + ((myVehicle.getLane()->getParallelOpposite() != nullptr && checkOpposite) ? myVehicle.getLane()->getParallelOpposite()->getEdge().getWidth() : 0));
    4144              : }
    4145              : 
    4146              : double
    4147    136840750 : MSLCM_SL2015::getVehicleCenter() const {
    4148    136840750 :     if (isOpposite()) {
    4149       157008 :         return myVehicle.getEdge()->getWidth() + myVehicle.getLane()->getWidth() * 0.5 - myVehicle.getLateralPositionOnLane();
    4150              :     } else {
    4151    136683742 :         return myVehicle.getCenterOnEdge();
    4152              :     }
    4153              : }
    4154              : 
    4155              : double
    4156     66331988 : MSLCM_SL2015::getNeighRight(const MSLane& neighLane) const {
    4157     66331988 :     if (isOpposite()) {
    4158       132868 :         return myVehicle.getLane()->getRightSideOnEdge() - neighLane.getWidth() + 2 * myVehicle.getLateralPositionOnLane();
    4159     66199120 :     } else if ((&myVehicle.getLane()->getEdge() != &neighLane.getEdge())) {
    4160       118368 :         return myVehicle.getLane()->getRightSideOnEdge() + myVehicle.getLane()->getWidth();
    4161              :     } else {
    4162              :         // the normal case
    4163     66080752 :         return neighLane.getRightSideOnEdge();
    4164              :     }
    4165              : }
    4166              : 
    4167              : 
    4168              : bool
    4169      8559772 : MSLCM_SL2015::preventSliding(double maneuverDist) const {
    4170              :     // prevent wide maneuvers with unsufficient forward space
    4171      8559772 :     if (fabs(maneuverDist) > myMaxDistLatStanding) {
    4172              :         // emergency vehicles should not be restricted (TODO solve this with LCA_URGENT)
    4173      8199068 :         if (myVehicle.getVehicleType().getVehicleClass() == SVC_EMERGENCY) {
    4174              :             return false;
    4175              :         }
    4176      8171095 :         const double brakeGap = myVehicle.getCarFollowModel().brakeGap(myVehicle.getSpeed());
    4177      8171095 :         const bool isSlide = fabs(maneuverDist) > myMaxDistLatStanding + brakeGap * fabs(myMaxSpeedLatFactor);
    4178              : #ifdef DEBUG_SLIDING
    4179              :         if (gDebugFlag2) {
    4180              :             std::cout << SIMTIME << " veh=" << myVehicle.getID() << " bgap=" << brakeGap << " maneuverDist=" << maneuverDist
    4181              :                       << " mds=" << myMaxDistLatStanding << " isSlide=" << isSlide << "\n";
    4182              :         }
    4183              : #endif
    4184      8171095 :         return isSlide;
    4185              :     }
    4186              :     return false;
    4187              : }
    4188              : 
    4189              : bool
    4190              : MSLCM_SL2015::wantsKeepRight(double keepRightProb) const {
    4191      9654766 :     return keepRightProb * myKeepRightParam > MAX2(myChangeProbThresholdRight, mySpeedGainProbabilityLeft);
    4192              : }
    4193              : 
    4194              : 
    4195              : bool
    4196        20761 : MSLCM_SL2015::saveBlockerLength(double length, double foeLeftSpace) {
    4197        20761 :     const bool canReserve = MSLCHelper::canSaveBlockerLength(myVehicle, length, myLeftSpace);
    4198        20761 :     if (!isOpposite() && (canReserve || myLeftSpace > foeLeftSpace)) {
    4199        17702 :         myLeadingBlockerLength = MAX2(length, myLeadingBlockerLength);
    4200        17702 :         if (myLeftSpace == 0 && foeLeftSpace < 0) {
    4201              :             // called from opposite overtaking, myLeftSpace must be initialized
    4202          466 :             myLeftSpace = myVehicle.getBestLanes()[myVehicle.getLane()->getIndex()].length - myVehicle.getPositionOnLane();
    4203              :         }
    4204        17702 :         return true;
    4205              :     } else {
    4206              :         return false;
    4207              :     }
    4208              : }
    4209              : 
    4210              : 
    4211              : bool
    4212     26355065 : MSLCM_SL2015::outsideEdge() const {
    4213     26355065 :     return myVehicle.getLeftSideOnEdge() < 0 || myVehicle.getRightSideOnEdge() > myVehicle.getLane()->getEdge().getWidth();
    4214              : }
    4215              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1