Eclipse SUMO - Simulation of Urban MObility
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
MSVehicle.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2025 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
31// Representation of a vehicle in the micro simulation
32/****************************************************************************/
33#include <config.h>
34
35#include <iostream>
36#include <cassert>
37#include <cmath>
38#include <cstdlib>
39#include <algorithm>
40#include <map>
41#include <memory>
71#include "MSEdgeControl.h"
72#include "MSVehicleControl.h"
73#include "MSInsertionControl.h"
74#include "MSVehicleTransfer.h"
75#include "MSGlobals.h"
76#include "MSJunctionLogic.h"
77#include "MSStop.h"
78#include "MSStoppingPlace.h"
79#include "MSParkingArea.h"
80#include "MSMoveReminder.h"
81#include "MSLane.h"
82#include "MSJunction.h"
83#include "MSEdge.h"
84#include "MSVehicleType.h"
85#include "MSNet.h"
86#include "MSRoute.h"
87#include "MSLeaderInfo.h"
88#include "MSDriverState.h"
89#include "MSVehicle.h"
90
91
92//#define DEBUG_PLAN_MOVE
93//#define DEBUG_PLAN_MOVE_LEADERINFO
94//#define DEBUG_CHECKREWINDLINKLANES
95//#define DEBUG_EXEC_MOVE
96//#define DEBUG_FURTHER
97//#define DEBUG_SETFURTHER
98//#define DEBUG_TARGET_LANE
99//#define DEBUG_STOPS
100//#define DEBUG_BESTLANES
101//#define DEBUG_IGNORE_RED
102//#define DEBUG_ACTIONSTEPS
103//#define DEBUG_NEXT_TURN
104//#define DEBUG_TRACI
105//#define DEBUG_REVERSE_BIDI
106//#define DEBUG_EXTRAPOLATE_DEPARTPOS
107//#define DEBUG_REMOTECONTROL
108//#define DEBUG_MOVEREMINDERS
109//#define DEBUG_COND (getID() == "ego")
110//#define DEBUG_COND (true)
111#define DEBUG_COND (isSelected())
112//#define DEBUG_COND2(obj) (obj->getID() == "ego")
113#define DEBUG_COND2(obj) (obj->isSelected())
114
115//#define PARALLEL_STOPWATCH
116
117
118#define STOPPING_PLACE_OFFSET 0.5
119
120#define CRLL_LOOK_AHEAD 5
121
122#define JUNCTION_BLOCKAGE_TIME 5 // s
123
124// @todo Calibrate with real-world values / make configurable
125#define DIST_TO_STOPLINE_EXPECT_PRIORITY 1.0
126
127#define NUMERICAL_EPS_SPEED (0.1 * NUMERICAL_EPS * TS)
128
129// ===========================================================================
130// static value definitions
131// ===========================================================================
132std::vector<MSLane*> MSVehicle::myEmptyLaneVector;
133
134
135// ===========================================================================
136// method definitions
137// ===========================================================================
138/* -------------------------------------------------------------------------
139 * methods of MSVehicle::State
140 * ----------------------------------------------------------------------- */
142 myPos = state.myPos;
143 mySpeed = state.mySpeed;
144 myPosLat = state.myPosLat;
145 myBackPos = state.myBackPos;
148}
149
150
153 myPos = state.myPos;
154 mySpeed = state.mySpeed;
155 myPosLat = state.myPosLat;
156 myBackPos = state.myBackPos;
157 myPreviousSpeed = state.myPreviousSpeed;
158 myLastCoveredDist = state.myLastCoveredDist;
159 return *this;
160}
161
162
163bool
165 return (myPos != state.myPos ||
166 mySpeed != state.mySpeed ||
167 myPosLat != state.myPosLat ||
168 myLastCoveredDist != state.myLastCoveredDist ||
169 myPreviousSpeed != state.myPreviousSpeed ||
170 myBackPos != state.myBackPos);
171}
172
173
174MSVehicle::State::State(double pos, double speed, double posLat, double backPos, double previousSpeed) :
175 myPos(pos), mySpeed(speed), myPosLat(posLat), myBackPos(backPos), myPreviousSpeed(previousSpeed), myLastCoveredDist(SPEED2DIST(speed)) {}
176
177
178
179/* -------------------------------------------------------------------------
180 * methods of MSVehicle::WaitingTimeCollector
181 * ----------------------------------------------------------------------- */
183
184
187 assert(memorySpan <= myMemorySize);
188 if (memorySpan == -1) {
189 memorySpan = myMemorySize;
190 }
191 SUMOTime totalWaitingTime = 0;
192 for (const auto& interval : myWaitingIntervals) {
193 if (interval.second >= memorySpan) {
194 if (interval.first >= memorySpan) {
195 break;
196 } else {
197 totalWaitingTime += memorySpan - interval.first;
198 }
199 } else {
200 totalWaitingTime += interval.second - interval.first;
201 }
202 }
203 return totalWaitingTime;
204}
205
206
207void
209 auto i = myWaitingIntervals.begin();
210 const auto end = myWaitingIntervals.end();
211 const bool startNewInterval = i == end || (i->first != 0);
212 while (i != end) {
213 i->first += dt;
214 if (i->first >= myMemorySize) {
215 break;
216 }
217 i->second += dt;
218 i++;
219 }
220
221 // remove intervals beyond memorySize
222 auto d = std::distance(i, end);
223 while (d > 0) {
224 myWaitingIntervals.pop_back();
225 d--;
226 }
227
228 if (!waiting) {
229 return;
230 } else if (!startNewInterval) {
231 myWaitingIntervals.begin()->first = 0;
232 } else {
233 myWaitingIntervals.push_front(std::make_pair(0, dt));
234 }
235 return;
236}
237
238
239const std::string
241 std::ostringstream state;
242 state << myMemorySize << " " << myWaitingIntervals.size();
243 for (const auto& interval : myWaitingIntervals) {
244 state << " " << interval.first << " " << interval.second;
245 }
246 return state.str();
247}
248
249
250void
252 std::istringstream is(state);
253 int numIntervals;
254 SUMOTime begin, end;
255 is >> myMemorySize >> numIntervals;
256 while (numIntervals-- > 0) {
257 is >> begin >> end;
258 myWaitingIntervals.emplace_back(begin, end);
259 }
260}
261
262
263/* -------------------------------------------------------------------------
264 * methods of MSVehicle::Influencer::GapControlState
265 * ----------------------------------------------------------------------- */
266void
268// std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << ", to=" << to << std::endl;
269 switch (to) {
273 // Vehicle left road
274// Look up reference vehicle in refVehMap and in case deactivate corresponding gap control
275 const MSVehicle* msVeh = static_cast<const MSVehicle*>(vehicle);
276// std::cout << "GapControlVehStateListener::vehicleStateChanged() vehicle=" << vehicle->getID() << " left the road." << std::endl;
277 if (GapControlState::refVehMap.find(msVeh) != end(GapControlState::refVehMap)) {
278// std::cout << "GapControlVehStateListener::deactivating ref vehicle=" << vehicle->getID() << std::endl;
279 GapControlState::refVehMap[msVeh]->deactivate();
280 }
281 }
282 break;
283 default:
284 {};
285 // do nothing, vehicle still on road
286 }
287}
288
289std::map<const MSVehicle*, MSVehicle::Influencer::GapControlState*>
291
293
295 tauOriginal(-1), tauCurrent(-1), tauTarget(-1), addGapCurrent(-1), addGapTarget(-1),
296 remainingDuration(-1), changeRate(-1), maxDecel(-1), referenceVeh(nullptr), active(false), gapAttained(false), prevLeader(nullptr),
297 lastUpdate(-1), timeHeadwayIncrement(0.0), spaceHeadwayIncrement(0.0) {}
298
299
303
304void
306 if (MSNet::hasInstance()) {
307 if (myVehStateListener == nullptr) {
308 //std::cout << "GapControlState::init()" << std::endl;
309 myVehStateListener = new GapControlVehStateListener();
310 MSNet::getInstance()->addVehicleStateListener(myVehStateListener);
311 }
312 } else {
313 WRITE_ERROR("MSVehicle::Influencer::GapControlState::init(): No MSNet instance found!")
314 }
315}
316
317void
319 if (myVehStateListener != nullptr) {
320 MSNet::getInstance()->removeVehicleStateListener(myVehStateListener);
321 delete myVehStateListener;
322 myVehStateListener = nullptr;
323 }
324}
325
326void
327MSVehicle::Influencer::GapControlState::activate(double tauOrig, double tauNew, double additionalGap, double dur, double rate, double decel, const MSVehicle* refVeh) {
329 WRITE_ERROR(TL("No gap control available for meso."))
330 } else {
331 // always deactivate control before activating (triggers clean-up of refVehMap)
332// std::cout << "activate gap control with refVeh=" << (refVeh==nullptr? "NULL" : refVeh->getID()) << std::endl;
333 tauOriginal = tauOrig;
334 tauCurrent = tauOrig;
335 tauTarget = tauNew;
336 addGapCurrent = 0.0;
337 addGapTarget = additionalGap;
338 remainingDuration = dur;
339 changeRate = rate;
340 maxDecel = decel;
341 referenceVeh = refVeh;
342 active = true;
343 gapAttained = false;
344 prevLeader = nullptr;
345 lastUpdate = SIMSTEP - DELTA_T;
346 timeHeadwayIncrement = changeRate * TS * (tauTarget - tauOriginal);
347 spaceHeadwayIncrement = changeRate * TS * addGapTarget;
348
349 if (referenceVeh != nullptr) {
350 // Add refVeh to refVehMap
351 GapControlState::refVehMap[referenceVeh] = this;
352 }
353 }
354}
355
356void
358 active = false;
359 if (referenceVeh != nullptr) {
360 // Remove corresponding refVehMapEntry if appropriate
361 GapControlState::refVehMap.erase(referenceVeh);
362 referenceVeh = nullptr;
363 }
364}
365
366
367/* -------------------------------------------------------------------------
368 * methods of MSVehicle::Influencer
369 * ----------------------------------------------------------------------- */
391
392
394
395void
397 GapControlState::init();
398}
399
400void
402 GapControlState::cleanup();
403}
404
405void
406MSVehicle::Influencer::setSpeedTimeLine(const std::vector<std::pair<SUMOTime, double> >& speedTimeLine) {
407 mySpeedAdaptationStarted = true;
408 mySpeedTimeLine = speedTimeLine;
409}
410
411void
412MSVehicle::Influencer::activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle* refVeh) {
413 if (myGapControlState == nullptr) {
414 myGapControlState = std::make_shared<GapControlState>();
415 init(); // only does things on first call
416 }
417 myGapControlState->activate(originalTau, newTimeHeadway, newSpaceHeadway, duration, changeRate, maxDecel, refVeh);
418}
419
420void
422 if (myGapControlState != nullptr && myGapControlState->active) {
423 myGapControlState->deactivate();
424 }
425}
426
427void
428MSVehicle::Influencer::setLaneTimeLine(const std::vector<std::pair<SUMOTime, int> >& laneTimeLine) {
429 myLaneTimeLine = laneTimeLine;
430}
431
432
433void
435 for (auto& item : myLaneTimeLine) {
436 item.second += indexShift;
437 }
438}
439
440
441void
443 myLatDist = latDist;
444}
445
446int
448 return (1 * myConsiderSafeVelocity +
449 2 * myConsiderMaxAcceleration +
450 4 * myConsiderMaxDeceleration +
451 8 * myRespectJunctionPriority +
452 16 * myEmergencyBrakeRedLight +
453 32 * !myRespectJunctionLeaderPriority + // inverted!
454 64 * !myConsiderSpeedLimit // inverted!
455 );
456}
457
458
459int
461 return (1 * myStrategicLC +
462 4 * myCooperativeLC +
463 16 * mySpeedGainLC +
464 64 * myRightDriveLC +
465 256 * myTraciLaneChangePriority +
466 1024 * mySublaneLC);
467}
468
471 SUMOTime duration = -1;
472 for (std::vector<std::pair<SUMOTime, int>>::iterator i = myLaneTimeLine.begin(); i != myLaneTimeLine.end(); ++i) {
473 if (duration < 0) {
474 duration = i->first;
475 } else {
476 duration -= i->first;
477 }
478 }
479 return -duration;
480}
481
484 if (!myLaneTimeLine.empty()) {
485 return myLaneTimeLine.back().first;
486 } else {
487 return -1;
488 }
489}
490
491
492double
493MSVehicle::Influencer::influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax) {
494 // remove leading commands which are no longer valid
495 while (mySpeedTimeLine.size() == 1 || (mySpeedTimeLine.size() > 1 && currentTime > mySpeedTimeLine[1].first)) {
496 mySpeedTimeLine.erase(mySpeedTimeLine.begin());
497 }
498
499 if (!(mySpeedTimeLine.size() < 2 || currentTime < mySpeedTimeLine[0].first)) {
500 // Speed advice is active -> compute new speed according to speedTimeLine
501 if (!mySpeedAdaptationStarted) {
502 mySpeedTimeLine[0].second = speed;
503 mySpeedAdaptationStarted = true;
504 }
505 currentTime += DELTA_T;
506 const double td = STEPS2TIME(currentTime - mySpeedTimeLine[0].first) / MAX2(TS, STEPS2TIME(mySpeedTimeLine[1].first - mySpeedTimeLine[0].first));
507
508 speed = mySpeedTimeLine[0].second - (mySpeedTimeLine[0].second - mySpeedTimeLine[1].second) * td;
509 if (myConsiderSafeVelocity) {
510 speed = MIN2(speed, vSafe);
511 }
512 if (myConsiderMaxAcceleration) {
513 speed = MIN2(speed, vMax);
514 }
515 if (myConsiderMaxDeceleration) {
516 speed = MAX2(speed, vMin);
517 }
518 }
519 return speed;
520}
521
522double
523MSVehicle::Influencer::gapControlSpeed(SUMOTime currentTime, const SUMOVehicle* veh, double speed, double vSafe, double vMin, double vMax) {
524#ifdef DEBUG_TRACI
525 if DEBUG_COND2(veh) {
526 std::cout << currentTime << " Influencer::gapControlSpeed(): speed=" << speed
527 << ", vSafe=" << vSafe
528 << ", vMin=" << vMin
529 << ", vMax=" << vMax
530 << std::endl;
531 }
532#endif
533 double gapControlSpeed = speed;
534 if (myGapControlState != nullptr && myGapControlState->active) {
535 // Determine leader and the speed that would be chosen by the gap controller
536 const double currentSpeed = veh->getSpeed();
537 const MSVehicle* msVeh = dynamic_cast<const MSVehicle*>(veh);
538 assert(msVeh != nullptr);
539 const double desiredTargetTimeSpacing = myGapControlState->tauTarget * currentSpeed;
540 std::pair<const MSVehicle*, double> leaderInfo;
541 if (myGapControlState->referenceVeh == nullptr) {
542 // No reference vehicle specified -> use current leader as reference
543 const double brakeGap = msVeh->getBrakeGap(true);
544 leaderInfo = msVeh->getLeader(MAX2(desiredTargetTimeSpacing, myGapControlState->addGapCurrent) + MAX2(brakeGap, 20.0));
545#ifdef DEBUG_TRACI
546 if DEBUG_COND2(veh) {
547 std::cout << " --- no refVeh; myGapControlState->addGapCurrent: " << myGapControlState->addGapCurrent << ", brakeGap: " << brakeGap << " in simstep: " << SIMSTEP << std::endl;
548 }
549#endif
550 } else {
551 // Control gap wrt reference vehicle
552 const MSVehicle* leader = myGapControlState->referenceVeh;
553 double dist = msVeh->getDistanceToPosition(leader->getPositionOnLane(), leader->getLane()) - leader->getLength();
554 if (dist > 100000) {
555 // Reference vehicle was not found downstream the ego's route
556 // Maybe, it is behind the ego vehicle
557 dist = - leader->getDistanceToPosition(msVeh->getPositionOnLane(), msVeh->getLane()) - leader->getLength();
558#ifdef DEBUG_TRACI
559 if DEBUG_COND2(veh) {
560 if (dist < -100000) {
561 // also the ego vehicle is not ahead of the reference vehicle -> no CF-relation
562 std::cout << " Ego and reference vehicle are not in CF relation..." << std::endl;
563 } else {
564 std::cout << " Reference vehicle is behind ego..." << std::endl;
565 }
566 }
567#endif
568 }
569 leaderInfo = std::make_pair(leader, dist - msVeh->getVehicleType().getMinGap());
570 }
571 const double fakeDist = MAX2(0.0, leaderInfo.second - myGapControlState->addGapCurrent);
572#ifdef DEBUG_TRACI
573 if DEBUG_COND2(veh) {
574 const double desiredCurrentSpacing = myGapControlState->tauCurrent * currentSpeed;
575 std::cout << " Gap control active:"
576 << " currentSpeed=" << currentSpeed
577 << ", desiredTargetTimeSpacing=" << desiredTargetTimeSpacing
578 << ", desiredCurrentSpacing=" << desiredCurrentSpacing
579 << ", leader=" << (leaderInfo.first == nullptr ? "NULL" : leaderInfo.first->getID())
580 << ", dist=" << leaderInfo.second
581 << ", fakeDist=" << fakeDist
582 << ",\n tauOriginal=" << myGapControlState->tauOriginal
583 << ", tauTarget=" << myGapControlState->tauTarget
584 << ", tauCurrent=" << myGapControlState->tauCurrent
585 << std::endl;
586 }
587#endif
588 if (leaderInfo.first != nullptr) {
589 if (myGapControlState->prevLeader != nullptr && myGapControlState->prevLeader != leaderInfo.first) {
590 // TODO: The leader changed. What to do?
591 }
592 // Remember leader
593 myGapControlState->prevLeader = leaderInfo.first;
594
595 // Calculate desired following speed assuming the alternative headway time
596 MSCFModel* cfm = (MSCFModel*) & (msVeh->getVehicleType().getCarFollowModel());
597 const double origTau = cfm->getHeadwayTime();
598 cfm->setHeadwayTime(myGapControlState->tauCurrent);
599 gapControlSpeed = MIN2(gapControlSpeed,
600 cfm->followSpeed(msVeh, currentSpeed, fakeDist, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first));
601 cfm->setHeadwayTime(origTau);
602#ifdef DEBUG_TRACI
603 if DEBUG_COND2(veh) {
604 std::cout << " -> gapControlSpeed=" << gapControlSpeed;
605 if (myGapControlState->maxDecel > 0) {
606 std::cout << ", with maxDecel bound: " << MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
607 }
608 std::cout << std::endl;
609 }
610#endif
611 if (myGapControlState->maxDecel > 0) {
612 gapControlSpeed = MAX2(gapControlSpeed, currentSpeed - TS * myGapControlState->maxDecel);
613 }
614 }
615
616 // Update gap controller
617 // Check (1) if the gap control has established the desired gap,
618 // and (2) if it has maintained active for the given duration afterwards
619 if (myGapControlState->lastUpdate < currentTime) {
620#ifdef DEBUG_TRACI
621 if DEBUG_COND2(veh) {
622 std::cout << " Updating GapControlState." << std::endl;
623 }
624#endif
625 if (myGapControlState->tauCurrent == myGapControlState->tauTarget && myGapControlState->addGapCurrent == myGapControlState->addGapTarget) {
626 if (!myGapControlState->gapAttained) {
627 // Check if the desired gap was established (add the POSITION_EPS to avoid infinite asymptotic behavior without having established the gap)
628 myGapControlState->gapAttained = leaderInfo.first == nullptr || leaderInfo.second > MAX2(desiredTargetTimeSpacing, myGapControlState->addGapTarget) - POSITION_EPS;
629#ifdef DEBUG_TRACI
630 if DEBUG_COND2(veh) {
631 if (myGapControlState->gapAttained) {
632 std::cout << " Target gap was established." << std::endl;
633 }
634 }
635#endif
636 } else {
637 // Count down remaining time if desired gap was established
638 myGapControlState->remainingDuration -= TS;
639#ifdef DEBUG_TRACI
640 if DEBUG_COND2(veh) {
641 std::cout << " Gap control remaining duration: " << myGapControlState->remainingDuration << std::endl;
642 }
643#endif
644 if (myGapControlState->remainingDuration <= 0) {
645#ifdef DEBUG_TRACI
646 if DEBUG_COND2(veh) {
647 std::cout << " Gap control duration expired, deactivating control." << std::endl;
648 }
649#endif
650 // switch off gap control
651 myGapControlState->deactivate();
652 }
653 }
654 } else {
655 // Adjust current headway values
656 myGapControlState->tauCurrent = MIN2(myGapControlState->tauCurrent + myGapControlState->timeHeadwayIncrement, myGapControlState->tauTarget);
657 myGapControlState->addGapCurrent = MIN2(myGapControlState->addGapCurrent + myGapControlState->spaceHeadwayIncrement, myGapControlState->addGapTarget);
658 }
659 }
660 if (myConsiderSafeVelocity) {
661 gapControlSpeed = MIN2(gapControlSpeed, vSafe);
662 }
663 if (myConsiderMaxAcceleration) {
664 gapControlSpeed = MIN2(gapControlSpeed, vMax);
665 }
666 if (myConsiderMaxDeceleration) {
667 gapControlSpeed = MAX2(gapControlSpeed, vMin);
668 }
669 return MIN2(speed, gapControlSpeed);
670 } else {
671 return speed;
672 }
673}
674
675double
677 return myOriginalSpeed;
678}
679
680void
682 myOriginalSpeed = speed;
683}
684
685
686int
687MSVehicle::Influencer::influenceChangeDecision(const SUMOTime currentTime, const MSEdge& currentEdge, const int currentLaneIndex, int state) {
688 // remove leading commands which are no longer valid
689 while (myLaneTimeLine.size() == 1 || (myLaneTimeLine.size() > 1 && currentTime > myLaneTimeLine[1].first)) {
690 myLaneTimeLine.erase(myLaneTimeLine.begin());
691 }
692 ChangeRequest changeRequest = REQUEST_NONE;
693 // do nothing if the time line does not apply for the current time
694 if (myLaneTimeLine.size() >= 2 && currentTime >= myLaneTimeLine[0].first) {
695 const int destinationLaneIndex = myLaneTimeLine[1].second;
696 if (destinationLaneIndex < (int)currentEdge.getLanes().size()) {
697 if (currentLaneIndex > destinationLaneIndex) {
698 changeRequest = REQUEST_RIGHT;
699 } else if (currentLaneIndex < destinationLaneIndex) {
700 changeRequest = REQUEST_LEFT;
701 } else {
702 changeRequest = REQUEST_HOLD;
703 }
704 } else if (currentEdge.getLanes().back()->getOpposite() != nullptr) { // change to opposite direction driving
705 changeRequest = REQUEST_LEFT;
706 state = state | LCA_TRACI;
707 }
708 }
709 // check whether the current reason shall be canceled / overridden
710 if ((state & LCA_WANTS_LANECHANGE_OR_STAY) != 0) {
711 // flags for the current reason
713 if ((state & LCA_TRACI) != 0 && myLatDist != 0) {
714 // security checks
715 if ((myTraciLaneChangePriority == LCP_ALWAYS)
716 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
717 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
718 }
719 // continue sublane change manoeuvre
720 return state;
721 } else if ((state & LCA_STRATEGIC) != 0) {
722 mode = myStrategicLC;
723 } else if ((state & LCA_COOPERATIVE) != 0) {
724 mode = myCooperativeLC;
725 } else if ((state & LCA_SPEEDGAIN) != 0) {
726 mode = mySpeedGainLC;
727 } else if ((state & LCA_KEEPRIGHT) != 0) {
728 mode = myRightDriveLC;
729 } else if ((state & LCA_SUBLANE) != 0) {
730 mode = mySublaneLC;
731 } else if ((state & LCA_TRACI) != 0) {
732 mode = LC_NEVER;
733 } else {
734 WRITE_WARNINGF(TL("Lane change model did not provide a reason for changing (state=%, time=%\n"), toString(state), time2string(currentTime));
735 }
736 if (mode == LC_NEVER) {
737 // cancel all lcModel requests
738 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
739 state &= ~LCA_URGENT;
740 if (changeRequest == REQUEST_NONE) {
741 // also remove all reasons except TRACI
742 state &= ~LCA_CHANGE_REASONS | LCA_TRACI;
743 }
744 } else if (mode == LC_NOCONFLICT && changeRequest != REQUEST_NONE) {
745 if (
746 ((state & LCA_LEFT) != 0 && changeRequest != REQUEST_LEFT) ||
747 ((state & LCA_RIGHT) != 0 && changeRequest != REQUEST_RIGHT) ||
748 ((state & LCA_STAY) != 0 && changeRequest != REQUEST_HOLD)) {
749 // cancel conflicting lcModel request
750 state &= ~LCA_WANTS_LANECHANGE_OR_STAY;
751 state &= ~LCA_URGENT;
752 }
753 } else if (mode == LC_ALWAYS) {
754 // ignore any TraCI requests
755 return state;
756 }
757 }
758 // apply traci requests
759 if (changeRequest == REQUEST_NONE) {
760 return state;
761 } else {
762 state |= LCA_TRACI;
763 // security checks
764 if ((myTraciLaneChangePriority == LCP_ALWAYS)
765 || (myTraciLaneChangePriority == LCP_NOOVERLAP && (state & LCA_OVERLAPPING) == 0)) {
766 state &= ~(LCA_BLOCKED | LCA_OVERLAPPING);
767 }
768 if (changeRequest != REQUEST_HOLD && myTraciLaneChangePriority != LCP_OPPORTUNISTIC) {
769 state |= LCA_URGENT;
770 }
771 switch (changeRequest) {
772 case REQUEST_HOLD:
773 return state | LCA_STAY;
774 case REQUEST_LEFT:
775 return state | LCA_LEFT;
776 case REQUEST_RIGHT:
777 return state | LCA_RIGHT;
778 default:
779 throw ProcessError(TL("should not happen"));
780 }
781 }
782}
783
784
785double
787 assert(myLaneTimeLine.size() >= 2);
788 assert(currentTime >= myLaneTimeLine[0].first);
789 return STEPS2TIME(myLaneTimeLine[1].first - currentTime);
790}
791
792
793void
795 myConsiderSafeVelocity = ((speedMode & 1) != 0);
796 myConsiderMaxAcceleration = ((speedMode & 2) != 0);
797 myConsiderMaxDeceleration = ((speedMode & 4) != 0);
798 myRespectJunctionPriority = ((speedMode & 8) != 0);
799 myEmergencyBrakeRedLight = ((speedMode & 16) != 0);
800 myRespectJunctionLeaderPriority = ((speedMode & 32) == 0); // inverted!
801 myConsiderSpeedLimit = ((speedMode & 64) == 0); // inverted!
802}
803
804
805void
807 myStrategicLC = (LaneChangeMode)(value & (1 + 2));
808 myCooperativeLC = (LaneChangeMode)((value & (4 + 8)) >> 2);
809 mySpeedGainLC = (LaneChangeMode)((value & (16 + 32)) >> 4);
810 myRightDriveLC = (LaneChangeMode)((value & (64 + 128)) >> 6);
811 myTraciLaneChangePriority = (TraciLaneChangePriority)((value & (256 + 512)) >> 8);
812 mySublaneLC = (LaneChangeMode)((value & (1024 + 2048)) >> 10);
813}
814
815
816void
817MSVehicle::Influencer::setRemoteControlled(Position xyPos, MSLane* l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector& route, SUMOTime t) {
818 myRemoteXYPos = xyPos;
819 myRemoteLane = l;
820 myRemotePos = pos;
821 myRemotePosLat = posLat;
822 myRemoteAngle = angle;
823 myRemoteEdgeOffset = edgeOffset;
824 myRemoteRoute = route;
825 myLastRemoteAccess = t;
826}
827
828
829bool
831 return myLastRemoteAccess == MSNet::getInstance()->getCurrentTimeStep();
832}
833
834
835bool
837 return myLastRemoteAccess >= t - TIME2STEPS(10);
838}
839
840
841void
843 if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
844 // only replace route at this time if the vehicle is moving with the flow
845 const bool isForward = v->getLane() != 0 && &v->getLane()->getEdge() == myRemoteRoute[0];
846#ifdef DEBUG_REMOTECONTROL
847 std::cout << SIMSTEP << " updateRemoteControlRoute veh=" << v->getID() << " old=" << toString(v->getRoute().getEdges()) << " new=" << toString(myRemoteRoute) << " fwd=" << isForward << "\n";
848#endif
849 if (isForward) {
850 v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
851 v->updateBestLanes();
852 }
853 }
854}
855
856
857void
859 const bool wasOnRoad = v->isOnRoad();
860 const bool withinLane = myRemoteLane != nullptr && fabs(myRemotePosLat) < 0.5 * (myRemoteLane->getWidth() + v->getVehicleType().getWidth());
861 const bool keepLane = wasOnRoad && v->getLane() == myRemoteLane;
862 if (v->isOnRoad() && !(keepLane && withinLane)) {
863 if (myRemoteLane != nullptr && &v->getLane()->getEdge() == &myRemoteLane->getEdge()) {
864 // correct odometer which gets incremented via onRemovalFromNet->leaveLane
865 v->myOdometer -= v->getLane()->getLength();
866 }
869 }
870 if (myRemoteRoute.size() != 0 && myRemoteRoute != v->getRoute().getEdges()) {
871 // needed for the insertion step
872#ifdef DEBUG_REMOTECONTROL
873 std::cout << SIMSTEP << " postProcessRemoteControl veh=" << v->getID()
874 << "\n oldLane=" << Named::getIDSecure(v->getLane())
875 << " oldRoute=" << toString(v->getRoute().getEdges())
876 << "\n newLane=" << Named::getIDSecure(myRemoteLane)
877 << " newRoute=" << toString(myRemoteRoute)
878 << " newRouteEdge=" << myRemoteRoute[myRemoteEdgeOffset]->getID()
879 << "\n";
880#endif
881 // clear any prior stops because they cannot apply to the new route
882 const_cast<SUMOVehicleParameter&>(v->getParameter()).stops.clear();
883 v->replaceRouteEdges(myRemoteRoute, -1, 0, "traci:moveToXY", true);
884 myRemoteRoute.clear();
885 }
886 v->myCurrEdge = v->getRoute().begin() + myRemoteEdgeOffset;
887 if (myRemoteLane != nullptr && myRemotePos > myRemoteLane->getLength()) {
888 myRemotePos = myRemoteLane->getLength();
889 }
890 if (myRemoteLane != nullptr && withinLane) {
891 if (keepLane) {
892 // TODO this handles only the case when the new vehicle is completely on the edge
893 const bool needFurtherUpdate = v->myState.myPos < v->getVehicleType().getLength() && myRemotePos >= v->getVehicleType().getLength();
894 v->myState.myPos = myRemotePos;
895 v->myState.myPosLat = myRemotePosLat;
896 if (needFurtherUpdate) {
897 v->myState.myBackPos = v->updateFurtherLanes(v->myFurtherLanes, v->myFurtherLanesPosLat, std::vector<MSLane*>());
898 }
899 } else {
903 if (!v->isOnRoad()) {
904 MSVehicleTransfer::getInstance()->remove(v); // TODO may need optimization, this is linear in the number of vehicles in transfer
905 }
906 myRemoteLane->forceVehicleInsertion(v, myRemotePos, notify, myRemotePosLat);
907 v->updateBestLanes();
908 }
909 if (!wasOnRoad) {
910 v->drawOutsideNetwork(false);
911 }
912 //std::cout << "on road network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << " pos=" << myRemotePos << " posLat=" << myRemotePosLat << "\n";
913 myRemoteLane->requireCollisionCheck();
914 } else {
915 if (v->getDeparture() == NOT_YET_DEPARTED) {
916 v->onDepart();
917 }
918 v->drawOutsideNetwork(true);
919 // see updateState
920 double vNext = v->processTraCISpeedControl(
921 v->getMaxSpeed(), v->getSpeed());
922 v->setBrakingSignals(vNext);
924 v->myAcceleration = SPEED2ACCEL(vNext - v->getSpeed());
925 v->myState.mySpeed = vNext;
926 v->updateWaitingTime(vNext);
927 //std::cout << "outside network p=" << myRemoteXYPos << " a=" << myRemoteAngle << " l=" << Named::getIDSecure(myRemoteLane) << "\n";
928 }
929 // ensure that the position is correct (i.e. when the lanePosition is ambiguous at corners)
930 v->setRemoteState(myRemoteXYPos);
931 v->setAngle(GeomHelper::fromNaviDegree(myRemoteAngle));
932}
933
934
935double
937 if (veh->getPosition() == Position::INVALID) {
938 return oldSpeed;
939 }
940 double dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
941 if (myRemoteLane != nullptr) {
942 // if the vehicles is frequently placed on a new edge, the route may
943 // consist only of a single edge. In this case the new edge may not be
944 // on the route so distAlongRoute will be double::max.
945 // In this case we still want a sensible speed value
946 const double distAlongRoute = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
947 if (distAlongRoute != std::numeric_limits<double>::max()) {
948 dist = distAlongRoute;
949 }
950 }
951 //std::cout << SIMTIME << " veh=" << veh->getID() << " oldPos=" << veh->getPosition() << " traciPos=" << myRemoteXYPos << " dist=" << dist << "\n";
952 const double minSpeed = myConsiderMaxDeceleration ?
953 veh->getCarFollowModel().minNextSpeedEmergency(oldSpeed, veh) : 0;
954 const double maxSpeed = (myRemoteLane != nullptr
955 ? myRemoteLane->getVehicleMaxSpeed(veh)
956 : (veh->getLane() != nullptr
957 ? veh->getLane()->getVehicleMaxSpeed(veh)
958 : veh->getMaxSpeed()));
959 return MIN2(maxSpeed, MAX2(minSpeed, DIST2SPEED(dist)));
960}
961
962
963double
965 double dist = 0;
966 if (myRemoteLane == nullptr) {
967 dist = veh->getPosition().distanceTo2D(myRemoteXYPos);
968 } else {
969 // if the vehicles is frequently placed on a new edge, the route may
970 // consist only of a single edge. In this case the new edge may not be
971 // on the route so getDistanceToPosition will return double::max.
972 // In this case we would rather not move the vehicle in executeMove
973 // (updateState) as it would result in emergency braking
974 dist = veh->getDistanceToPosition(myRemotePos, myRemoteLane);
975 }
976 if (dist == std::numeric_limits<double>::max()) {
977 return 0;
978 } else {
979 if (DIST2SPEED(dist) > veh->getMaxSpeed() * 1.1) {
980 WRITE_WARNINGF(TL("Vehicle '%' moved by TraCI from % to % (dist %) with implied speed of % (exceeding maximum speed %). time=%."),
981 veh->getID(), veh->getPosition(), myRemoteXYPos, dist, DIST2SPEED(dist), veh->getMaxSpeed(), time2string(SIMSTEP));
982 // some sanity check here
983 dist = MIN2(dist, SPEED2DIST(veh->getMaxSpeed() * 2));
984 }
985 return dist;
986 }
987}
988
989
990/* -------------------------------------------------------------------------
991 * MSVehicle-methods
992 * ----------------------------------------------------------------------- */
994 MSVehicleType* type, const double speedFactor) :
995 MSBaseVehicle(pars, route, type, speedFactor),
996 myWaitingTime(0),
998 myTimeLoss(0),
999 myState(0, 0, 0, 0, 0),
1000 myDriverState(nullptr),
1001 myActionStep(true),
1003 myLane(nullptr),
1004 myLaneChangeModel(nullptr),
1005 myLastBestLanesEdge(nullptr),
1007 myAcceleration(0),
1008 myNextTurn(0., nullptr),
1009 mySignals(0),
1010 myAmOnNet(false),
1011 myAmIdling(false),
1013 myAngle(0),
1014 myStopDist(std::numeric_limits<double>::max()),
1020 myTimeSinceStartup(TIME2STEPS(3600 * 24)),
1021 myHaveStoppedFor(nullptr),
1022 myInfluencer(nullptr) {
1025}
1026
1027
1037
1038
1039void
1041 for (MSLane* further : myFurtherLanes) {
1042 further->resetPartialOccupation(this);
1043 if (further->getBidiLane() != nullptr
1044 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
1045 further->getBidiLane()->resetPartialOccupation(this);
1046 }
1047 }
1048 if (myLaneChangeModel != nullptr) {
1052 // still needed when calling resetPartialOccupation (getShadowLane) and when removing
1053 // approach information from parallel links
1054 }
1055 myFurtherLanes.clear();
1056 myFurtherLanesPosLat.clear();
1057}
1058
1059
1060void
1062#ifdef DEBUG_ACTIONSTEPS
1063 if (DEBUG_COND) {
1064 std::cout << SIMTIME << " Removing vehicle '" << getID() << "' (reason: " << toString(reason) << ")" << std::endl;
1065 }
1066#endif
1069 leaveLane(reason);
1072 }
1073}
1074
1075
1076void
1083
1084
1085// ------------ interaction with the route
1086bool
1088 // note: not a const method because getDepartLane may call updateBestLanes
1089 if (!(*myCurrEdge)->isTazConnector()) {
1091 if ((*myCurrEdge)->getDepartLane(*this) == nullptr) {
1092 msg = "Invalid departlane definition for vehicle '" + getID() + "'.";
1093 if (myParameter->departLane >= (int)(*myCurrEdge)->getLanes().size()) {
1095 } else {
1097 }
1098 return false;
1099 }
1100 } else {
1101 if ((*myCurrEdge)->allowedLanes(getVClass()) == nullptr) {
1102 msg = "Vehicle '" + getID() + "' is not allowed to depart on any lane of edge '" + (*myCurrEdge)->getID() + "'.";
1104 return false;
1105 }
1106 }
1108 msg = "Departure speed for vehicle '" + getID() + "' is too high for the vehicle type '" + myType->getID() + "'.";
1110 return false;
1111 }
1112 }
1114 return true;
1115}
1116
1117
1118bool
1120 return hasArrivedInternal(false);
1121}
1122
1123
1124bool
1125MSVehicle::hasArrivedInternal(bool oppositeTransformed) const {
1126 return ((myCurrEdge == myRoute->end() - 1 || (myParameter->arrivalEdge >= 0 && getRoutePosition() >= myParameter->arrivalEdge))
1127 && (myStops.empty() || myStops.front().edge != myCurrEdge || myStops.front().getSpeed() > 0)
1128 && ((myLaneChangeModel->isOpposite() && !oppositeTransformed) ? myLane->getLength() - myState.myPos : myState.myPos) > myArrivalPos - POSITION_EPS
1129 && !isRemoteControlled());
1130}
1131
1132
1133bool
1134MSVehicle::replaceRoute(ConstMSRoutePtr newRoute, const std::string& info, bool onInit, int offset, bool addRouteStops, bool removeStops, std::string* msgReturn) {
1135 if (MSBaseVehicle::replaceRoute(newRoute, info, onInit, offset, addRouteStops, removeStops, msgReturn)) {
1136 // update best lanes (after stops were added)
1137 myLastBestLanesEdge = nullptr;
1139 updateBestLanes(true, onInit ? (*myCurrEdge)->getLanes().front() : 0);
1140 assert(!removeStops || haveValidStopEdges());
1141 if (myStops.size() == 0) {
1142 myStopDist = std::numeric_limits<double>::max();
1143 }
1144 return true;
1145 }
1146 return false;
1147}
1148
1149
1150// ------------ Interaction with move reminders
1151void
1152MSVehicle::workOnMoveReminders(double oldPos, double newPos, double newSpeed) {
1153 // This erasure-idiom works for all stl-sequence-containers
1154 // See Meyers: Effective STL, Item 9
1155 for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
1156 // XXX: calling notifyMove with newSpeed seems not the best choice. For the ballistic update, the average speed is calculated and used
1157 // although a higher order quadrature-formula might be more adequate.
1158 // For the euler case (where the speed is considered constant for each time step) it is conceivable that
1159 // the current calculations may lead to systematic errors for large time steps (compared to reality). Refs. #2579
1160 if (!rem->first->notifyMove(*this, oldPos + rem->second, newPos + rem->second, MAX2(0., newSpeed))) {
1161#ifdef _DEBUG
1162 if (myTraceMoveReminders) {
1163 traceMoveReminder("notifyMove", rem->first, rem->second, false);
1164 }
1165#endif
1166 rem = myMoveReminders.erase(rem);
1167 } else {
1168#ifdef _DEBUG
1169 if (myTraceMoveReminders) {
1170 traceMoveReminder("notifyMove", rem->first, rem->second, true);
1171 }
1172#endif
1173 ++rem;
1174 }
1175 }
1176 if (myEnergyParams != nullptr) {
1177 // TODO make the vehicle energy params a derived class which is a move reminder
1179 }
1180}
1181
1182
1183void
1185 updateWaitingTime(0.); // cf issue 2233
1186
1187 // vehicle move reminders
1188 for (const auto& rem : myMoveReminders) {
1189 rem.first->notifyIdle(*this);
1190 }
1191
1192 // lane move reminders - for aggregated values
1193 for (MSMoveReminder* rem : getLane()->getMoveReminders()) {
1194 rem->notifyIdle(*this);
1195 }
1196}
1197
1198// XXX: consider renaming...
1199void
1201 // save the old work reminders, patching the position information
1202 // add the information about the new offset to the old lane reminders
1203 const double oldLaneLength = myLane->getLength();
1204 for (auto& rem : myMoveReminders) {
1205 rem.second += oldLaneLength;
1206#ifdef _DEBUG
1207// if (rem->first==0) std::cout << "Null reminder (?!)" << std::endl;
1208// std::cout << "Adapted MoveReminder on lane " << ((rem->first->getLane()==0) ? "NULL" : rem->first->getLane()->getID()) <<" position to " << rem->second << std::endl;
1209 if (myTraceMoveReminders) {
1210 traceMoveReminder("adaptedPos", rem.first, rem.second, true);
1211 }
1212#endif
1213 }
1214 for (MSMoveReminder* const rem : enteredLane.getMoveReminders()) {
1215 addReminder(rem);
1216 }
1217}
1218
1219
1220// ------------ Other getter methods
1221double
1223 if (isParking() && getStops().begin()->parkingarea != nullptr) {
1224 return getStops().begin()->parkingarea->getVehicleSlope(*this);
1225 }
1226 if (myLane == nullptr) {
1227 return 0;
1228 }
1229 const double posLat = myState.myPosLat; // @todo get rid of the '-'
1230 Position p1 = getPosition();
1232 if (p2 == Position::INVALID) {
1233 // Handle special case of vehicle's back reaching out of the network
1234 if (myFurtherLanes.size() > 0) {
1235 p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
1236 if (p2 == Position::INVALID) {
1237 // unsuitable lane geometry
1238 p2 = myLane->geometryPositionAtOffset(0, posLat);
1239 }
1240 } else {
1241 p2 = myLane->geometryPositionAtOffset(0, posLat);
1242 }
1243 }
1245}
1246
1247
1249MSVehicle::getPosition(const double offset) const {
1250 if (myLane == nullptr) {
1251 // when called in the context of GUI-Drawing, the simulation step is already incremented
1253 return myCachedPosition;
1254 } else {
1255 return Position::INVALID;
1256 }
1257 }
1258 if (isParking()) {
1259 if (myInfluencer != nullptr && myInfluencer->getLastAccessTimeStep() > getNextStopParameter()->started) {
1260 return myCachedPosition;
1261 }
1262 if (myStops.begin()->parkingarea != nullptr) {
1263 return myStops.begin()->parkingarea->getVehiclePosition(*this);
1264 } else {
1265 // position beside the road
1266 PositionVector shp = myLane->getEdge().getLanes()[0]->getShape();
1269 }
1270 }
1271 const bool changingLanes = myLaneChangeModel->isChangingLanes();
1272 const double posLat = (MSGlobals::gLefthand ? 1 : -1) * getLateralPositionOnLane();
1273 if (offset == 0. && !changingLanes) {
1276 if (MSNet::getInstance()->hasElevation() && MSGlobals::gSublane) {
1278 }
1279 }
1280 return myCachedPosition;
1281 }
1282 Position result = validatePosition(myLane->geometryPositionAtOffset(getPositionOnLane() + offset, posLat), offset);
1283 interpolateLateralZ(result, getPositionOnLane() + offset, posLat);
1284 return result;
1285}
1286
1287
1288void
1289MSVehicle::interpolateLateralZ(Position& pos, double offset, double posLat) const {
1290 const MSLane* shadow = myLaneChangeModel->getShadowLane();
1291 if (shadow != nullptr && pos != Position::INVALID) {
1292 // ignore negative offset
1293 const Position shadowPos = shadow->geometryPositionAtOffset(MAX2(0.0, offset));
1294 if (shadowPos != Position::INVALID && pos.z() != shadowPos.z()) {
1295 const double centerDist = (myLane->getWidth() + shadow->getWidth()) * 0.5;
1296 double relOffset = fabs(posLat) / centerDist;
1297 double newZ = (1 - relOffset) * pos.z() + relOffset * shadowPos.z();
1298 pos.setz(newZ);
1299 }
1300 }
1301}
1302
1303
1304double
1306 double result = getLength() - getPositionOnLane();
1307 if (myLane->isNormal()) {
1308 return MAX2(0.0, result);
1309 }
1310 const MSLane* lane = myLane;
1311 while (lane->isInternal()) {
1312 result += lane->getLength();
1313 lane = lane->getCanonicalSuccessorLane();
1314 }
1315 return result;
1316}
1317
1318
1322 if (!isOnRoad()) {
1323 return Position::INVALID;
1324 }
1325 const std::vector<MSLane*>& bestLanes = getBestLanesContinuation();
1326 auto nextBestLane = bestLanes.begin();
1327 const bool opposite = myLaneChangeModel->isOpposite();
1328 double pos = opposite ? myLane->getLength() - myState.myPos : myState.myPos;
1329 const MSLane* lane = opposite ? myLane->getParallelOpposite() : getLane();
1330 assert(lane != 0);
1331 bool success = true;
1332
1333 while (offset > 0) {
1334 // take into account lengths along internal lanes
1335 while (lane->isInternal() && offset > 0) {
1336 if (offset > lane->getLength() - pos) {
1337 offset -= lane->getLength() - pos;
1338 lane = lane->getLinkCont()[0]->getViaLaneOrLane();
1339 pos = 0.;
1340 if (lane == nullptr) {
1341 success = false;
1342 offset = 0.;
1343 }
1344 } else {
1345 pos += offset;
1346 offset = 0;
1347 }
1348 }
1349 // set nextBestLane to next non-internal lane
1350 while (nextBestLane != bestLanes.end() && *nextBestLane == nullptr) {
1351 ++nextBestLane;
1352 }
1353 if (offset > 0) {
1354 assert(!lane->isInternal());
1355 assert(lane == *nextBestLane);
1356 if (offset > lane->getLength() - pos) {
1357 offset -= lane->getLength() - pos;
1358 ++nextBestLane;
1359 assert(nextBestLane == bestLanes.end() || *nextBestLane != 0);
1360 if (nextBestLane == bestLanes.end()) {
1361 success = false;
1362 offset = 0.;
1363 } else {
1364 const MSLink* link = lane->getLinkTo(*nextBestLane);
1365 assert(link != nullptr);
1366 lane = link->getViaLaneOrLane();
1367 pos = 0.;
1368 }
1369 } else {
1370 pos += offset;
1371 offset = 0;
1372 }
1373 }
1374
1375 }
1376
1377 if (success) {
1379 } else {
1380 return Position::INVALID;
1381 }
1382}
1383
1384
1385double
1387 if (myLane != nullptr) {
1388 return myLane->getVehicleMaxSpeed(this);
1389 }
1390 return myType->getMaxSpeed();
1391}
1392
1393
1395MSVehicle::validatePosition(Position result, double offset) const {
1396 int furtherIndex = 0;
1397 double lastLength = getPositionOnLane();
1398 while (result == Position::INVALID) {
1399 if (furtherIndex >= (int)myFurtherLanes.size()) {
1400 //WRITE_WARNINGF(TL("Could not compute position for vehicle '%', time=%."), getID(), time2string(MSNet::getInstance()->getCurrentTimeStep()));
1401 break;
1402 }
1403 //std::cout << SIMTIME << " veh=" << getID() << " lane=" << myLane->getID() << " pos=" << getPositionOnLane() << " posLat=" << getLateralPositionOnLane() << " offset=" << offset << " result=" << result << " i=" << furtherIndex << " further=" << myFurtherLanes.size() << "\n";
1404 MSLane* further = myFurtherLanes[furtherIndex];
1405 offset += lastLength;
1406 result = further->geometryPositionAtOffset(further->getLength() + offset, -getLateralPositionOnLane());
1407 lastLength = further->getLength();
1408 furtherIndex++;
1409 //std::cout << SIMTIME << " newResult=" << result << "\n";
1410 }
1411 return result;
1412}
1413
1414
1415ConstMSEdgeVector::const_iterator
1417 // too close to the next junction, so avoid an emergency brake here
1418 if (myLane != nullptr && (myCurrEdge + 1) != myRoute->end()) {
1419 if (myLane->isInternal()) {
1420 return myCurrEdge + 1;
1421 }
1422 if (myState.myPos > myLane->getLength() - getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)) {
1423 return myCurrEdge + 1;
1424 }
1426 return myCurrEdge + 1;
1427 }
1428 }
1429 return myCurrEdge;
1430}
1431
1432void
1433MSVehicle::setAngle(double angle, bool straightenFurther) {
1434#ifdef DEBUG_FURTHER
1435 if (DEBUG_COND) {
1436 std::cout << SIMTIME << " veh '" << getID() << " setAngle(" << angle << ") straightenFurther=" << straightenFurther << std::endl;
1437 }
1438#endif
1439 myAngle = angle;
1440 MSLane* next = myLane;
1441 if (straightenFurther && myFurtherLanesPosLat.size() > 0) {
1442 for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
1443 MSLane* further = myFurtherLanes[i];
1444 const MSLink* link = further->getLinkTo(next);
1445 if (link != nullptr) {
1447 next = further;
1448 } else {
1449 break;
1450 }
1451 }
1452 }
1453}
1454
1455
1456void
1457MSVehicle::setActionStepLength(double actionStepLength, bool resetOffset) {
1458 SUMOTime actionStepLengthMillisecs = SUMOVehicleParserHelper::processActionStepLength(actionStepLength);
1459 SUMOTime previousActionStepLength = getActionStepLength();
1460 const bool newActionStepLength = actionStepLengthMillisecs != previousActionStepLength;
1461 if (newActionStepLength) {
1462 getSingularType().setActionStepLength(actionStepLengthMillisecs, resetOffset);
1463 if (!resetOffset) {
1464 updateActionOffset(previousActionStepLength, actionStepLengthMillisecs);
1465 }
1466 }
1467 if (resetOffset) {
1469 }
1470}
1471
1472
1473bool
1475 return myState.mySpeed < (60.0 / 3.6) || myLane->getSpeedLimit() < (60.1 / 3.6);
1476}
1477
1478
1479double
1481 Position p1;
1482 const double posLat = -myState.myPosLat; // @todo get rid of the '-'
1483 const double lefthandSign = (MSGlobals::gLefthand ? -1 : 1);
1484
1485 // if parking manoeuvre is happening then rotate vehicle on each step
1488 }
1489
1490 if (isParking()) {
1491 if (myStops.begin()->parkingarea != nullptr) {
1492 return myStops.begin()->parkingarea->getVehicleAngle(*this);
1493 } else {
1495 }
1496 }
1498 // cannot use getPosition() because it already includes the offset to the side and thus messes up the angle
1499 p1 = myLane->geometryPositionAtOffset(myState.myPos, lefthandSign * posLat);
1500 if (p1 == Position::INVALID && myLane->getShape().length2D() == 0. && myLane->isInternal()) {
1501 // workaround: extrapolate the preceding lane shape
1502 MSLane* predecessorLane = myLane->getCanonicalPredecessorLane();
1503 p1 = predecessorLane->geometryPositionAtOffset(predecessorLane->getLength() + myState.myPos, lefthandSign * posLat);
1504 }
1505 } else {
1506 p1 = getPosition();
1507 }
1508
1509 Position p2;
1510 if (getVehicleType().getParameter().locomotiveLength > 0) {
1511 // articulated vehicle should use the heading of the first part
1512 const double locoLength = MIN2(getVehicleType().getParameter().locomotiveLength, getLength());
1513 p2 = getPosition(-locoLength);
1514 } else {
1515 p2 = getBackPosition();
1516 }
1517 if (p2 == Position::INVALID) {
1518 // Handle special case of vehicle's back reaching out of the network
1519 if (myFurtherLanes.size() > 0) {
1520 p2 = myFurtherLanes.back()->geometryPositionAtOffset(0, -myFurtherLanesPosLat.back());
1521 if (p2 == Position::INVALID) {
1522 // unsuitable lane geometry
1523 p2 = myLane->geometryPositionAtOffset(0, posLat);
1524 }
1525 } else {
1526 p2 = myLane->geometryPositionAtOffset(0, posLat);
1527 }
1528 }
1529 double result = (p1 != p2 ? p2.angleTo2D(p1) :
1531
1532 result += lefthandSign * myLaneChangeModel->calcAngleOffset();
1533
1534#ifdef DEBUG_FURTHER
1535 if (DEBUG_COND) {
1536 std::cout << SIMTIME << " computeAngle veh=" << getID() << " p1=" << p1 << " p2=" << p2 << " angle=" << RAD2DEG(result) << " naviDegree=" << GeomHelper::naviDegree(result) << "\n";
1537 }
1538#endif
1539 return result;
1540}
1541
1542
1543const Position
1545 const double posLat = MSGlobals::gLefthand ? myState.myPosLat : -myState.myPosLat;
1546 Position result;
1547 if (myState.myPos >= myType->getLength()) {
1548 // vehicle is fully on the new lane
1550 } else {
1552 // special case where the target lane has no predecessor
1553#ifdef DEBUG_FURTHER
1554 if (DEBUG_COND) {
1555 std::cout << " getBackPosition veh=" << getID() << " specialCase using myLane=" << myLane->getID() << " pos=0 posLat=" << myState.myPosLat << " result=" << myLane->geometryPositionAtOffset(0, posLat) << "\n";
1556 }
1557#endif
1558 result = myLane->geometryPositionAtOffset(0, posLat);
1559 } else {
1560#ifdef DEBUG_FURTHER
1561 if (DEBUG_COND) {
1562 std::cout << " getBackPosition veh=" << getID() << " myLane=" << myLane->getID() << " further=" << toString(myFurtherLanes) << " myFurtherLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
1563 }
1564#endif
1565 if (myFurtherLanes.size() > 0 && !myLaneChangeModel->isChangingLanes()) {
1566 // truncate to 0 if vehicle starts on an edge that is shorter than its length
1567 const double backPos = MAX2(0.0, getBackPositionOnLane(myFurtherLanes.back()));
1568 result = myFurtherLanes.back()->geometryPositionAtOffset(backPos, -myFurtherLanesPosLat.back() * (MSGlobals::gLefthand ? -1 : 1));
1569 } else {
1570 result = myLane->geometryPositionAtOffset(0, posLat);
1571 }
1572 }
1573 }
1575 interpolateLateralZ(result, myState.myPos - myType->getLength(), posLat);
1576 }
1577 return result;
1578}
1579
1580
1581bool
1583 return !isStopped() && !myStops.empty() && myLane != nullptr && &myStops.front().lane->getEdge() == &myLane->getEdge();
1584}
1585
1586bool
1588 return isStopped() && myStops.front().lane == myLane;
1589}
1590
1591bool
1592MSVehicle::keepStopping(bool afterProcessing) const {
1593 if (isStopped()) {
1594 // when coming out of vehicleTransfer we must shift the time forward
1595 return (myStops.front().duration - (afterProcessing ? DELTA_T : 0) > 0 || isStoppedTriggered() || myStops.front().pars.collision
1596 || myStops.front().pars.breakDown || (myStops.front().getSpeed() > 0
1597 && (myState.myPos < MIN2(myStops.front().pars.endPos, myStops.front().lane->getLength() - POSITION_EPS))
1598 && (myStops.front().pars.parking == ParkingType::ONROAD || getSpeed() >= SUMO_const_haltingSpeed)));
1599 } else {
1600 return false;
1601 }
1602}
1603
1604
1607 if (isStopped()) {
1608 return myStops.front().duration;
1609 }
1610 return 0;
1611}
1612
1613
1616 return (myStops.empty() || !myStops.front().pars.collision) ? myCollisionImmunity : MAX2((SUMOTime)0, myStops.front().duration);
1617}
1618
1619
1620bool
1622 return isStopped() && !myStops.empty() && myStops.front().pars.breakDown;
1623}
1624
1625
1626bool
1628 return myCollisionImmunity > 0;
1629}
1630
1631
1632double
1633MSVehicle::processNextStop(double currentVelocity) {
1634 if (myStops.empty()) {
1635 // no stops; pass
1636 return currentVelocity;
1637 }
1638
1639#ifdef DEBUG_STOPS
1640 if (DEBUG_COND) {
1641 std::cout << "\nPROCESS_NEXT_STOP\n" << SIMTIME << " vehicle '" << getID() << "'" << std::endl;
1642 }
1643#endif
1644
1645 MSStop& stop = myStops.front();
1647 if (stop.reached) {
1648 stop.duration -= getActionStepLength();
1649
1650#ifdef DEBUG_STOPS
1651 if (DEBUG_COND) {
1652 std::cout << SIMTIME << " vehicle '" << getID() << "' reached stop.\n"
1653 << "Remaining duration: " << STEPS2TIME(stop.duration) << std::endl;
1654 if (stop.getSpeed() > 0) {
1655 std::cout << " waypointSpeed=" << stop.getSpeed() << " vehPos=" << myState.myPos << " endPos=" << stop.pars.endPos << "\n";
1656 }
1657 }
1658#endif
1659 if (stop.duration <= 0 && stop.pars.join != "") {
1660 // join this train (part) to another one
1661 MSVehicle* joinVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.join));
1662 if (joinVeh && joinVeh->hasDeparted() && (joinVeh->joinTrainPart(this) || joinVeh->joinTrainPartFront(this))) {
1663 stop.joinTriggered = false;
1667 }
1668 // avoid collision warning before this vehicle is removed (joinVeh was already made longer)
1670 // mark this vehicle as arrived
1672 const_cast<SUMOVehicleParameter*>(myParameter)->arrivalEdge = getRoutePosition();
1673 // handle transportables that want to continue in the other vehicle
1674 if (myPersonDevice != nullptr) {
1676 }
1677 if (myContainerDevice != nullptr) {
1679 }
1680 }
1681 }
1682 boardTransportables(stop);
1683 if (time > stop.endBoarding) {
1684 // for taxi: cancel customers
1685 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
1686 if (taxiDevice != nullptr) {
1687 // may invalidate stops including the current reference
1688 taxiDevice->cancelCurrentCustomers();
1690 return currentVelocity;
1691 }
1692 }
1693 if (!keepStopping() && isOnRoad()) {
1694#ifdef DEBUG_STOPS
1695 if (DEBUG_COND) {
1696 std::cout << SIMTIME << " vehicle '" << getID() << "' resumes from stopping." << std::endl;
1697 }
1698#endif
1700 if (isRail() && hasStops()) {
1701 // stay on the current lane in case of a double stop
1702 const MSStop& nextStop = getNextStop();
1703 if (nextStop.edge == myCurrEdge) {
1704 const double stopSpeed = getCarFollowModel().stopSpeed(this, getSpeed(), nextStop.pars.endPos - myState.myPos);
1705 //std::cout << SIMTIME << " veh=" << getID() << " resumedFromStopping currentVelocity=" << currentVelocity << " stopSpeed=" << stopSpeed << "\n";
1706 return stopSpeed;
1707 }
1708 }
1709 } else {
1710 if (stop.triggered) {
1711 if (getVehicleType().getPersonCapacity() == getPersonNumber()) {
1712 WRITE_WARNINGF(TL("Vehicle '%' ignores triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
1713 stop.triggered = false;
1714 } else if (!myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
1715 // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
1718#ifdef DEBUG_STOPS
1719 if (DEBUG_COND) {
1720 std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for person." << std::endl;
1721 }
1722#endif
1723 }
1724 }
1725 if (stop.containerTriggered) {
1726 if (getVehicleType().getContainerCapacity() == getContainerNumber()) {
1727 WRITE_WARNINGF(TL("Vehicle '%' ignores container triggered stop on lane '%' due to capacity constraints."), getID(), stop.lane->getID());
1728 stop.containerTriggered = false;
1729 } else if (stop.containerTriggered && !myAmRegisteredAsWaiting && stop.duration <= DELTA_T) {
1730 // we can only register after waiting for one step. otherwise we might falsely signal a deadlock
1733#ifdef DEBUG_STOPS
1734 if (DEBUG_COND) {
1735 std::cout << SIMTIME << " vehicle '" << getID() << "' registers as waiting for container." << std::endl;
1736 }
1737#endif
1738 }
1739 }
1740 // joining only takes place after stop duration is over
1742 && stop.duration <= (stop.pars.extension >= 0 ? -stop.pars.extension : 0)) {
1743 if (stop.pars.extension >= 0) {
1744 WRITE_WARNINGF(TL("Vehicle '%' aborts joining after extension of %s at time %."), getID(), STEPS2TIME(stop.pars.extension), time2string(SIMSTEP));
1745 stop.joinTriggered = false;
1746 } else {
1747 // keep stopping indefinitely but ensure that simulation terminates
1750 }
1751 }
1752 if (stop.getSpeed() > 0) {
1753 //waypoint mode
1754 if (stop.duration == 0) {
1755 return stop.getSpeed();
1756 } else {
1757 // stop for 'until' (computed in planMove)
1758 return currentVelocity;
1759 }
1760 } else {
1761 // brake
1763 return 0;
1764 } else {
1765 // ballistic:
1766 return getSpeed() - getCarFollowModel().getMaxDecel();
1767 }
1768 }
1769 }
1770 } else {
1771
1772#ifdef DEBUG_STOPS
1773 if (DEBUG_COND) {
1774 std::cout << SIMTIME << " vehicle '" << getID() << "' hasn't reached next stop." << std::endl;
1775 }
1776#endif
1777 //std::cout << SIMTIME << " myStopDist=" << myStopDist << " bGap=" << getBrakeGap(myLane->getVehicleMaxSpeed(this)) << "\n";
1778 if (stop.pars.onDemand && !stop.skipOnDemand && myStopDist <= getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this))) {
1779 MSNet* const net = MSNet::getInstance();
1780 const bool noExits = ((myPersonDevice == nullptr || !myPersonDevice->anyLeavingAtStop(stop))
1781 && (myContainerDevice == nullptr || !myContainerDevice->anyLeavingAtStop(stop)));
1782 const bool noEntries = ((!net->hasPersons() || !net->getPersonControl().hasAnyWaiting(stop.getEdge(), this))
1783 && (!net->hasContainers() || !net->getContainerControl().hasAnyWaiting(stop.getEdge(), this)));
1784 if (noExits && noEntries) {
1785 //std::cout << " skipOnDemand\n";
1786 stop.skipOnDemand = true;
1787 }
1788 }
1789 // is the next stop on the current lane?
1790 if (stop.edge == myCurrEdge) {
1791 // get the stopping position
1792 bool useStoppingPlace = stop.busstop != nullptr || stop.containerstop != nullptr || stop.parkingarea != nullptr;
1793 bool fitsOnStoppingPlace = true;
1794 if (!stop.skipOnDemand) { // no need to check available space if we skip it anyway
1795 if (stop.busstop != nullptr) {
1796 fitsOnStoppingPlace &= stop.busstop->fits(myState.myPos, *this);
1797 }
1798 if (stop.containerstop != nullptr) {
1799 fitsOnStoppingPlace &= stop.containerstop->fits(myState.myPos, *this);
1800 }
1801 // if the stop is a parking area we check if there is a free position on the area
1802 if (stop.parkingarea != nullptr) {
1803 fitsOnStoppingPlace &= myState.myPos > stop.parkingarea->getBeginLanePosition();
1804 if (stop.parkingarea->getOccupancy() >= stop.parkingarea->getCapacity()) {
1805 fitsOnStoppingPlace = false;
1806 // trigger potential parkingZoneReroute
1807 MSParkingArea* oldParkingArea = stop.parkingarea;
1808 for (MSMoveReminder* rem : myLane->getMoveReminders()) {
1809 if (rem->isParkingRerouter()) {
1810 rem->notifyEnter(*this, MSMoveReminder::NOTIFICATION_PARKING_REROUTE, myLane);
1811 }
1812 }
1813 if (myStops.empty() || myStops.front().parkingarea != oldParkingArea) {
1814 // rerouted, keep driving
1815 return currentVelocity;
1816 }
1817 } else if (stop.parkingarea->getOccupancyIncludingReservations(this) >= stop.parkingarea->getCapacity()) {
1818 fitsOnStoppingPlace = false;
1819 } else if (stop.parkingarea->parkOnRoad() && stop.parkingarea->getLotIndex(this) < 0) {
1820 fitsOnStoppingPlace = false;
1821 }
1822 }
1823 }
1824 const double targetPos = myState.myPos + myStopDist + (stop.getSpeed() > 0 ? (stop.pars.startPos - stop.pars.endPos) : 0);
1825 const double reachedThreshold = (useStoppingPlace ? targetPos - STOPPING_PLACE_OFFSET : stop.getReachedThreshold()) - NUMERICAL_EPS;
1826#ifdef DEBUG_STOPS
1827 if (DEBUG_COND) {
1828 std::cout << " pos=" << myState.pos() << " speed=" << currentVelocity << " targetPos=" << targetPos << " fits=" << fitsOnStoppingPlace
1829 << " reachedThresh=" << reachedThreshold
1830 << " myLane=" << Named::getIDSecure(myLane)
1831 << " stopLane=" << Named::getIDSecure(stop.lane)
1832 << "\n";
1833 }
1834#endif
1835 const bool posReached = myState.pos() >= reachedThreshold && currentVelocity <= stop.getSpeed() + SUMO_const_haltingSpeed && myLane == stop.lane;
1836 if (posReached && !fitsOnStoppingPlace && MSStopOut::active()) {
1837 MSStopOut::getInstance()->stopBlocked(this, time);
1838 }
1839 if (fitsOnStoppingPlace && posReached && (!MSGlobals::gModelParkingManoeuver || myManoeuvre.entryManoeuvreIsComplete(this))) {
1840 // ok, we may stop (have reached the stop) and either we are not modelling maneuvering or have completed entry
1841 stop.reached = true;
1842 if (!stop.startedFromState) {
1843 stop.pars.started = time;
1844 }
1845#ifdef DEBUG_STOPS
1846 if (DEBUG_COND) {
1847 std::cout << SIMTIME << " vehicle '" << getID() << "' reached next stop." << std::endl;
1848 }
1849#endif
1850 if (MSStopOut::active()) {
1852 }
1853 myLane->getEdge().addWaiting(this);
1856 // compute stopping time
1857 stop.duration = stop.getMinDuration(time);
1858 stop.endBoarding = stop.pars.extension >= 0 ? time + stop.duration + stop.pars.extension : SUMOTime_MAX;
1859 MSDevice_Taxi* taxiDevice = static_cast<MSDevice_Taxi*>(getDevice(typeid(MSDevice_Taxi)));
1860 if (taxiDevice != nullptr && stop.pars.extension >= 0) {
1861 // earliestPickupTime is set with waitUntil
1862 stop.endBoarding = MAX2(time, stop.pars.waitUntil) + stop.pars.extension;
1863 }
1864 if (stop.getSpeed() > 0) {
1865 // ignore duration parameter in waypoint mode unless 'until' or 'ended' are set
1866 if (stop.getUntil() > time) {
1867 stop.duration = stop.getUntil() - time;
1868 } else {
1869 stop.duration = 0;
1870 }
1871 }
1872 if (stop.busstop != nullptr) {
1873 // let the bus stop know the vehicle
1874 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
1875 }
1876 if (stop.containerstop != nullptr) {
1877 // let the container stop know the vehicle
1879 }
1880 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
1881 // let the parking area know the vehicle
1882 stop.parkingarea->enter(this);
1883 }
1884 if (stop.chargingStation != nullptr) {
1885 // let the container stop know the vehicle
1887 }
1888
1889 if (stop.pars.tripId != "") {
1890 ((SUMOVehicleParameter&)getParameter()).setParameter("tripId", stop.pars.tripId);
1891 }
1892 if (stop.pars.line != "") {
1893 ((SUMOVehicleParameter&)getParameter()).line = stop.pars.line;
1894 }
1895 if (stop.pars.split != "") {
1896 // split the train
1897 MSVehicle* splitVeh = dynamic_cast<MSVehicle*>(MSNet::getInstance()->getVehicleControl().getVehicle(stop.pars.split));
1898 if (splitVeh == nullptr) {
1899 WRITE_WARNINGF(TL("Vehicle '%' to split from vehicle '%' is not known. time=%."), stop.pars.split, getID(), SIMTIME)
1900 } else {
1902 splitVeh->getRoute().getEdges()[0]->removeWaiting(splitVeh);
1904 const double newLength = MAX2(myType->getLength() - splitVeh->getVehicleType().getLength(),
1906 getSingularType().setLength(newLength);
1907 // handle transportables that want to continue in the split part
1908 if (myPersonDevice != nullptr) {
1910 }
1911 if (myContainerDevice != nullptr) {
1913 }
1915 const double backShift = splitVeh->getLength() + getVehicleType().getMinGap();
1916 myState.myPos -= backShift;
1917 myState.myBackPos -= backShift;
1918 }
1919 }
1920 }
1921
1922 boardTransportables(stop);
1923 if (stop.pars.posLat != INVALID_DOUBLE) {
1924 myState.myPosLat = stop.pars.posLat;
1925 }
1926 }
1927 }
1928 }
1929 return currentVelocity;
1930}
1931
1932
1933void
1935 if (stop.skipOnDemand) {
1936 return;
1937 }
1938 // we have reached the stop
1939 // any waiting persons may board now
1941 MSNet* const net = MSNet::getInstance();
1942 const bool boarded = (time <= stop.endBoarding
1943 && net->hasPersons()
1945 && stop.numExpectedPerson == 0);
1946 // load containers
1947 const bool loaded = (time <= stop.endBoarding
1948 && net->hasContainers()
1950 && stop.numExpectedContainer == 0);
1951
1952 bool unregister = false;
1953 if (time > stop.endBoarding) {
1954 stop.triggered = false;
1955 stop.containerTriggered = false;
1957 unregister = true;
1959 }
1960 }
1961 if (boarded) {
1962 // the triggering condition has been fulfilled. Maybe we want to wait a bit longer for additional riders (car pooling)
1964 unregister = true;
1965 }
1966 stop.triggered = false;
1968 }
1969 if (loaded) {
1970 // the triggering condition has been fulfilled
1972 unregister = true;
1973 }
1974 stop.containerTriggered = false;
1976 }
1977
1978 if (unregister) {
1980#ifdef DEBUG_STOPS
1981 if (DEBUG_COND) {
1982 std::cout << SIMTIME << " vehicle '" << getID() << "' unregisters as waiting for transportable." << std::endl;
1983 }
1984#endif
1985 }
1986}
1987
1988bool
1990 // check if veh is close enough to be joined to the rear of this vehicle
1991 MSLane* backLane = myFurtherLanes.size() == 0 ? myLane : myFurtherLanes.back();
1992 double gap = getBackPositionOnLane() - veh->getPositionOnLane();
1993 if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == veh->getLane()
1994 && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
1995 const double newLength = myType->getLength() + veh->getVehicleType().getLength();
1996 getSingularType().setLength(newLength);
1997 myStops.begin()->joinTriggered = false;
2001 }
2002 return true;
2003 } else {
2004 return false;
2005 }
2006}
2007
2008
2009bool
2011 // check if veh is close enough to be joined to the front of this vehicle
2012 MSLane* backLane = veh->myFurtherLanes.size() == 0 ? veh->myLane : veh->myFurtherLanes.back();
2013 double gap = veh->getBackPositionOnLane(backLane) - getPositionOnLane();
2014 if (isStopped() && myStops.begin()->duration <= DELTA_T && myStops.begin()->joinTriggered && backLane == getLane()
2015 && gap >= 0 && gap <= getVehicleType().getMinGap() + 1) {
2016 double skippedLaneLengths = 0;
2017 if (veh->myFurtherLanes.size() > 0) {
2018 skippedLaneLengths += getLane()->getLength();
2019 // this vehicle must be moved to the lane of veh
2020 // ensure that lane and furtherLanes of veh match our route
2021 int routeIndex = getRoutePosition();
2022 if (myLane->isInternal()) {
2023 routeIndex++;
2024 }
2025 for (int i = (int)veh->myFurtherLanes.size() - 1; i >= 0; i--) {
2026 MSEdge* edge = &veh->myFurtherLanes[i]->getEdge();
2027 if (edge->isInternal()) {
2028 continue;
2029 }
2030 if (!edge->isInternal() && edge != myRoute->getEdges()[routeIndex]) {
2031 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
2032 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
2033 return false;
2034 }
2035 routeIndex++;
2036 }
2037 if (veh->getCurrentEdge()->getNormalSuccessor() != myRoute->getEdges()[routeIndex]) {
2038 std::string warn = TL("Cannot join vehicle '%' to vehicle '%' due to incompatible routes. time=%.");
2039 WRITE_WARNINGF(warn, veh->getID(), getID(), time2string(SIMSTEP));
2040 return false;
2041 }
2042 for (int i = (int)veh->myFurtherLanes.size() - 2; i >= 0; i--) {
2043 skippedLaneLengths += veh->myFurtherLanes[i]->getLength();
2044 }
2045 }
2046
2047 const double newLength = myType->getLength() + veh->getVehicleType().getLength();
2048 getSingularType().setLength(newLength);
2049 // lane will be advanced just as for regular movement
2050 myState.myPos = skippedLaneLengths + veh->getPositionOnLane();
2051 myStops.begin()->joinTriggered = false;
2055 }
2056 return true;
2057 } else {
2058 return false;
2059 }
2060}
2061
2062double
2063MSVehicle::getBrakeGap(bool delayed) const {
2064 return getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), delayed ? getCarFollowModel().getHeadwayTime() : 0);
2065}
2066
2067
2068bool
2071 if (myActionStep) {
2072 myLastActionTime = t;
2073 }
2074 return myActionStep;
2075}
2076
2077
2078void
2079MSVehicle::resetActionOffset(const SUMOTime timeUntilNextAction) {
2080 myLastActionTime = MSNet::getInstance()->getCurrentTimeStep() + timeUntilNextAction;
2081}
2082
2083
2084void
2085MSVehicle::updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength) {
2087 SUMOTime timeSinceLastAction = now - myLastActionTime;
2088 if (timeSinceLastAction == 0) {
2089 // Action was scheduled now, may be delayed be new action step length
2090 timeSinceLastAction = oldActionStepLength;
2091 }
2092 if (timeSinceLastAction >= newActionStepLength) {
2093 // Action point required in this step
2094 myLastActionTime = now;
2095 } else {
2096 SUMOTime timeUntilNextAction = newActionStepLength - timeSinceLastAction;
2097 resetActionOffset(timeUntilNextAction);
2098 }
2099}
2100
2101
2102
2103void
2104MSVehicle::planMove(const SUMOTime t, const MSLeaderInfo& ahead, const double lengthsInFront) {
2105#ifdef DEBUG_PLAN_MOVE
2106 if (DEBUG_COND) {
2107 std::cout
2108 << "\nPLAN_MOVE\n"
2109 << SIMTIME
2110 << std::setprecision(gPrecision)
2111 << " veh=" << getID()
2112 << " lane=" << myLane->getID()
2113 << " pos=" << getPositionOnLane()
2114 << " posLat=" << getLateralPositionOnLane()
2115 << " speed=" << getSpeed()
2116 << "\n";
2117 }
2118#endif
2119 // Update the driver state
2120 if (hasDriverState()) {
2122 setActionStepLength(myDriverState->getDriverState()->getActionStepLength(), false);
2123 }
2124
2125 if (!checkActionStep(t)) {
2126#ifdef DEBUG_ACTIONSTEPS
2127 if (DEBUG_COND) {
2128 std::cout << STEPS2TIME(t) << " vehicle '" << getID() << "' skips action." << std::endl;
2129 }
2130#endif
2131 // During non-action passed drive items still need to be removed
2132 // @todo rather work with updating myCurrentDriveItem (refs #3714)
2134 return;
2135 } else {
2136#ifdef DEBUG_ACTIONSTEPS
2137 if (DEBUG_COND) {
2138 std::cout << STEPS2TIME(t) << " vehicle = '" << getID() << "' takes action." << std::endl;
2139 }
2140#endif
2142 if (myInfluencer != nullptr) {
2144 }
2146#ifdef DEBUG_PLAN_MOVE
2147 if (DEBUG_COND) {
2148 DriveItemVector::iterator i;
2149 for (i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
2150 std::cout
2151 << " vPass=" << (*i).myVLinkPass
2152 << " vWait=" << (*i).myVLinkWait
2153 << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
2154 << " request=" << (*i).mySetRequest
2155 << "\n";
2156 }
2157 }
2158#endif
2159 checkRewindLinkLanes(lengthsInFront, myLFLinkLanes);
2161 // ideally would only do this with the call inside planMoveInternal - but that needs a const method
2162 // so this is a kludge here - nuisance as it adds an extra check in a busy loop
2166 }
2167 }
2168 }
2170}
2171
2172
2173bool
2174MSVehicle::brakeForOverlap(const MSLink* link, const MSLane* lane) const {
2175 // @review needed
2176 //const double futurePosLat = getLateralPositionOnLane() + link->getLateralShift();
2177 //const double overlap = getLateralOverlap(futurePosLat, link->getViaLaneOrLane());
2178 //const double edgeWidth = link->getViaLaneOrLane()->getEdge().getWidth();
2179 const double futurePosLat = getLateralPositionOnLane() + (
2180 lane != myLane && lane->isInternal() ? lane->getIncomingLanes()[0].viaLink->getLateralShift() : 0);
2181 const double overlap = getLateralOverlap(futurePosLat, lane);
2182 const double edgeWidth = lane->getEdge().getWidth();
2183 const bool result = (overlap > POSITION_EPS
2184 // do not get stuck on narrow edges
2185 && getVehicleType().getWidth() <= edgeWidth
2186 && link->getViaLane() == nullptr
2187 // this is the exit link of a junction. The normal edge should support the shadow
2188 && ((myLaneChangeModel->getShadowLane(link->getLane()) == nullptr)
2189 // the internal lane after an internal junction has no parallel lane. make sure there is no shadow before continuing
2190 || (lane->getEdge().isInternal() && lane->getIncomingLanes()[0].lane->getEdge().isInternal()))
2191 // ignore situations where the shadow lane is part of a double-connection with the current lane
2192 && (myLaneChangeModel->getShadowLane() == nullptr
2193 || myLaneChangeModel->getShadowLane()->getLinkCont().size() == 0
2194 || myLaneChangeModel->getShadowLane()->getLinkCont().front()->getLane() != link->getLane()));
2195
2196#ifdef DEBUG_PLAN_MOVE
2197 if (DEBUG_COND) {
2198 std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getDescription() << " lane=" << lane->getID()
2199 << " shift=" << link->getLateralShift()
2200 << " fpLat=" << futurePosLat << " overlap=" << overlap << " w=" << getVehicleType().getWidth() << " result=" << result << "\n";
2201 }
2202#endif
2203 return result;
2204}
2205
2206
2207
2208void
2209MSVehicle::planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector& lfLinks, double& newStopDist, std::pair<double, const MSLink*>& nextTurn) const {
2210 lfLinks.clear();
2211 newStopDist = std::numeric_limits<double>::max();
2212 //
2213 const MSCFModel& cfModel = getCarFollowModel();
2214 const double vehicleLength = getVehicleType().getLength();
2215 const double maxV = cfModel.maxNextSpeed(myState.mySpeed, this);
2216 const bool opposite = myLaneChangeModel->isOpposite();
2217 double laneMaxV = myLane->getVehicleMaxSpeed(this);
2218 const double vMinComfortable = cfModel.minNextSpeed(getSpeed(), this);
2219 double lateralShift = 0;
2220 if (isRail()) {
2221 // speed limits must hold for the whole length of the train
2222 for (MSLane* l : myFurtherLanes) {
2223 laneMaxV = MIN2(laneMaxV, l->getVehicleMaxSpeed(this));
2224#ifdef DEBUG_PLAN_MOVE
2225 if (DEBUG_COND) {
2226 std::cout << " laneMaxV=" << laneMaxV << " lane=" << l->getID() << "\n";
2227 }
2228#endif
2229 }
2230 }
2231 // speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
2232 laneMaxV = MAX2(laneMaxV, vMinComfortable);
2234 laneMaxV = std::numeric_limits<double>::max();
2235 }
2236 // v is the initial maximum velocity of this vehicle in this step
2237 double v = cfModel.maximumLaneSpeedCF(this, maxV, laneMaxV);
2238 // if we are modelling parking then we dawdle until the manoeuvre is complete - by setting a very low max speed
2239 // in practice this only applies to exit manoeuvre because entry manoeuvre just delays setting stop.reached - when the vehicle is virtually stopped
2242 }
2243
2244 if (myInfluencer != nullptr) {
2245 const double vMin = MAX2(0., cfModel.minNextSpeed(myState.mySpeed, this));
2246#ifdef DEBUG_TRACI
2247 if (DEBUG_COND) {
2248 std::cout << SIMTIME << " veh=" << getID() << " speedBeforeTraci=" << v;
2249 }
2250#endif
2251 v = myInfluencer->influenceSpeed(t, v, v, vMin, maxV);
2252#ifdef DEBUG_TRACI
2253 if (DEBUG_COND) {
2254 std::cout << " influencedSpeed=" << v;
2255 }
2256#endif
2257 v = myInfluencer->gapControlSpeed(t, this, v, v, vMin, maxV);
2258#ifdef DEBUG_TRACI
2259 if (DEBUG_COND) {
2260 std::cout << " gapControlSpeed=" << v << "\n";
2261 }
2262#endif
2263 }
2264 // all links within dist are taken into account (potentially)
2265 const double dist = SPEED2DIST(maxV) + cfModel.brakeGap(maxV);
2266
2267 const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation();
2268#ifdef DEBUG_PLAN_MOVE
2269 if (DEBUG_COND) {
2270 std::cout << " dist=" << dist << " bestLaneConts=" << toString(bestLaneConts)
2271 << "\n maxV=" << maxV << " laneMaxV=" << laneMaxV << " v=" << v << "\n";
2272 }
2273#endif
2274 assert(bestLaneConts.size() > 0);
2275 bool hadNonInternal = false;
2276 // the distance already "seen"; in the following always up to the end of the current "lane"
2277 double seen = opposite ? myState.myPos : myLane->getLength() - myState.myPos;
2278 nextTurn.first = seen;
2279 nextTurn.second = nullptr;
2280 bool encounteredTurn = (MSGlobals::gLateralResolution <= 0); // next turn is only needed for sublane
2281 double seenNonInternal = 0;
2282 double seenInternal = myLane->isInternal() ? seen : 0;
2283 double vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(seen, v, cfModel.getMaxAccel()), laneMaxV); // upper bound
2284 int view = 0;
2285 DriveProcessItem* lastLink = nullptr;
2286 bool slowedDownForMinor = false; // whether the vehicle already had to slow down on approach to a minor link
2287 double mustSeeBeforeReversal = 0;
2288 // iterator over subsequent lanes and fill lfLinks until stopping distance or stopped
2289 const MSLane* lane = opposite ? myLane->getParallelOpposite() : myLane;
2290 assert(lane != 0);
2291 const MSLane* leaderLane = myLane;
2292 bool foundRailSignal = !isRail();
2293 bool planningToStop = false;
2294#ifdef PARALLEL_STOPWATCH
2295 myLane->getStopWatch()[0].start();
2296#endif
2297
2298 // optionally slow down to match arrival time
2299 const double sfp = getVehicleType().getParameter().speedFactorPremature;
2300 if (v > vMinComfortable && hasStops() && myStops.front().pars.arrival >= 0 && sfp > 0
2301 && v > myLane->getSpeedLimit() * sfp
2302 && !myStops.front().reached) {
2303 const double vSlowDown = slowDownForSchedule(vMinComfortable);
2304 v = MIN2(v, vSlowDown);
2305 }
2306 auto stopIt = myStops.begin();
2307 while (true) {
2308 // check leader on lane
2309 // leader is given for the first edge only
2310 if (opposite &&
2311 (leaderLane->getVehicleNumberWithPartials() > 1
2312 || (leaderLane != myLane && leaderLane->getVehicleNumber() > 0))) {
2313 ahead.clear();
2314 // find opposite-driving leader that must be respected on the currently looked at lane
2315 // (only looking at one lane at a time)
2316 const double backOffset = leaderLane == myLane ? getPositionOnLane() : leaderLane->getLength();
2317 const double gapOffset = leaderLane == myLane ? 0 : seen - leaderLane->getLength();
2318 const MSLeaderDistanceInfo cands = leaderLane->getFollowersOnConsecutive(this, backOffset, true, backOffset, MSLane::MinorLinkMode::FOLLOW_NEVER);
2319 MSLeaderDistanceInfo oppositeLeaders(leaderLane->getWidth(), this, 0.);
2320 const double minTimeToLeaveLane = MSGlobals::gSublane ? MAX2(TS, (0.5 * myLane->getWidth() - getLateralPositionOnLane()) / getVehicleType().getMaxSpeedLat()) : TS;
2321 for (int i = 0; i < cands.numSublanes(); i++) {
2322 CLeaderDist cand = cands[i];
2323 if (cand.first != 0) {
2324 if ((cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() != leaderLane)
2325 || (!cand.first->myLaneChangeModel->isOpposite() && cand.first->getLaneChangeModel().getShadowLane() == leaderLane)) {
2326 // respect leaders that also drive in the opposite direction (fully or with some overlap)
2327 oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - getVehicleType().getMinGap() + cand.first->getVehicleType().getMinGap() - cand.first->getVehicleType().getLength());
2328 } else {
2329 // avoid frontal collision
2330 const bool assumeStopped = cand.first->isStopped() || cand.first->getWaitingSeconds() > 1;
2331 const double predMaxDist = cand.first->getSpeed() + (assumeStopped ? 0 : cand.first->getCarFollowModel().getMaxAccel()) * minTimeToLeaveLane;
2332 if (cand.second >= 0 && (cand.second - v * minTimeToLeaveLane - predMaxDist < 0 || assumeStopped)) {
2333 oppositeLeaders.addLeader(cand.first, cand.second + gapOffset - predMaxDist - getVehicleType().getMinGap());
2334 }
2335 }
2336 }
2337 }
2338#ifdef DEBUG_PLAN_MOVE
2339 if (DEBUG_COND) {
2340 std::cout << " leaderLane=" << leaderLane->getID() << " gapOffset=" << gapOffset << " minTimeToLeaveLane=" << minTimeToLeaveLane
2341 << " cands=" << cands.toString() << " oppositeLeaders=" << oppositeLeaders.toString() << "\n";
2342 }
2343#endif
2344 adaptToLeaderDistance(oppositeLeaders, 0, seen, lastLink, v, vLinkPass);
2345 } else {
2347 const double rightOL = getRightSideOnLane(lane) + lateralShift;
2348 const double leftOL = getLeftSideOnLane(lane) + lateralShift;
2349 const bool outsideLeft = leftOL > lane->getWidth();
2350#ifdef DEBUG_PLAN_MOVE
2351 if (DEBUG_COND) {
2352 std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " rightOL=" << rightOL << " leftOL=" << leftOL << "\n";
2353 }
2354#endif
2355 if (rightOL < 0 || outsideLeft) {
2356 MSLeaderInfo outsideLeaders(lane->getWidth());
2357 // if ego is driving outside lane bounds we must consider
2358 // potential leaders that are also outside bounds
2359 int sublaneOffset = 0;
2360 if (outsideLeft) {
2361 sublaneOffset = MIN2(-1, -(int)ceil((leftOL - lane->getWidth()) / MSGlobals::gLateralResolution));
2362 } else {
2363 sublaneOffset = MAX2(1, (int)ceil(-rightOL / MSGlobals::gLateralResolution));
2364 }
2365 outsideLeaders.setSublaneOffset(sublaneOffset);
2366#ifdef DEBUG_PLAN_MOVE
2367 if (DEBUG_COND) {
2368 std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " sublaneOffset=" << sublaneOffset << " outsideLeft=" << outsideLeft << "\n";
2369 }
2370#endif
2371 for (const MSVehicle* cand : lane->getVehiclesSecure()) {
2372 if ((lane != myLane || cand->getPositionOnLane() > getPositionOnLane())
2373 && ((!outsideLeft && cand->getLeftSideOnEdge() < 0)
2374 || (outsideLeft && cand->getLeftSideOnEdge() > lane->getEdge().getWidth()))) {
2375 outsideLeaders.addLeader(cand, true);
2376#ifdef DEBUG_PLAN_MOVE
2377 if (DEBUG_COND) {
2378 std::cout << " outsideLeader=" << cand->getID() << " ahead=" << outsideLeaders.toString() << "\n";
2379 }
2380#endif
2381 }
2382 }
2383 lane->releaseVehicles();
2384 if (outsideLeaders.hasVehicles()) {
2385 adaptToLeaders(outsideLeaders, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
2386 }
2387 }
2388 }
2389 adaptToLeaders(ahead, lateralShift, seen, lastLink, leaderLane, v, vLinkPass);
2390 }
2391 if (lastLink != nullptr) {
2392 lastLink->myVLinkWait = MIN2(lastLink->myVLinkWait, v);
2393 }
2394#ifdef DEBUG_PLAN_MOVE
2395 if (DEBUG_COND) {
2396 std::cout << "\nv = " << v << "\n";
2397
2398 }
2399#endif
2400 // XXX efficiently adapt to shadow leaders using neighAhead by iteration over the whole edge in parallel (lanechanger-style)
2401 if (myLaneChangeModel->getShadowLane() != nullptr) {
2402 // also slow down for leaders on the shadowLane relative to the current lane
2403 const MSLane* shadowLane = myLaneChangeModel->getShadowLane(leaderLane);
2404 if (shadowLane != nullptr
2405 && (MSGlobals::gLateralResolution > 0 || getLateralOverlap() > POSITION_EPS
2406 // continous lane change cannot be stopped so we must adapt to the leader on the target lane
2408 if ((&shadowLane->getEdge() == &leaderLane->getEdge() || myLaneChangeModel->isOpposite())) {
2411 // ego posLat is added when retrieving sublanes but it
2412 // should be negated (subtract twice to compensate)
2413 latOffset = ((myLane->getWidth() + shadowLane->getWidth()) * 0.5
2414 - 2 * getLateralPositionOnLane());
2415
2416 }
2417 MSLeaderInfo shadowLeaders = shadowLane->getLastVehicleInformation(this, latOffset, lane->getLength() - seen);
2418#ifdef DEBUG_PLAN_MOVE
2420 std::cout << SIMTIME << " opposite veh=" << getID() << " shadowLane=" << shadowLane->getID() << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
2421 }
2422#endif
2424 // ignore oncoming vehicles on the shadow lane
2425 shadowLeaders.removeOpposite(shadowLane);
2426 }
2427 const double turningDifference = MAX2(0.0, leaderLane->getLength() - shadowLane->getLength());
2428 adaptToLeaders(shadowLeaders, latOffset, seen - turningDifference, lastLink, shadowLane, v, vLinkPass);
2429 } else if (shadowLane == myLaneChangeModel->getShadowLane() && leaderLane == myLane) {
2430 // check for leader vehicles driving in the opposite direction on the opposite-direction shadow lane
2431 // (and thus in the same direction as ego)
2432 MSLeaderDistanceInfo shadowLeaders = shadowLane->getFollowersOnConsecutive(this, myLane->getOppositePos(getPositionOnLane()), true);
2433 const double latOffset = 0;
2434#ifdef DEBUG_PLAN_MOVE
2435 if (DEBUG_COND) {
2436 std::cout << SIMTIME << " opposite shadows veh=" << getID() << " shadowLane=" << shadowLane->getID()
2437 << " latOffset=" << latOffset << " shadowLeaders=" << shadowLeaders.toString() << "\n";
2438 }
2439#endif
2440 shadowLeaders.fixOppositeGaps(true);
2441#ifdef DEBUG_PLAN_MOVE
2442 if (DEBUG_COND) {
2443 std::cout << " shadowLeadersFixed=" << shadowLeaders.toString() << "\n";
2444 }
2445#endif
2446 adaptToLeaderDistance(shadowLeaders, latOffset, seen, lastLink, v, vLinkPass);
2447 }
2448 }
2449 }
2450 // adapt to pedestrians on the same lane
2451 if (lane->getEdge().getPersons().size() > 0 && lane->hasPedestrians()) {
2452 const double relativePos = lane->getLength() - seen;
2453#ifdef DEBUG_PLAN_MOVE
2454 if (DEBUG_COND) {
2455 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
2456 }
2457#endif
2458 const double stopTime = MAX2(1.0, ceil(getSpeed() / cfModel.getMaxDecel()));
2459 PersonDist leader = lane->nextBlocking(relativePos,
2460 getRightSideOnLane(lane), getRightSideOnLane(lane) + getVehicleType().getWidth(), stopTime);
2461 if (leader.first != 0) {
2462 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
2463 v = MIN2(v, stopSpeed);
2464#ifdef DEBUG_PLAN_MOVE
2465 if (DEBUG_COND) {
2466 std::cout << SIMTIME << " pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
2467 }
2468#endif
2469 }
2470 }
2471 if (lane->getBidiLane() != nullptr) {
2472 // adapt to pedestrians on the bidi lane
2473 const MSLane* bidiLane = lane->getBidiLane();
2474 if (bidiLane->getEdge().getPersons().size() > 0 && bidiLane->hasPedestrians()) {
2475 const double relativePos = seen;
2476#ifdef DEBUG_PLAN_MOVE
2477 if (DEBUG_COND) {
2478 std::cout << SIMTIME << " adapt to pedestrians on lane=" << lane->getID() << " relPos=" << relativePos << "\n";
2479 }
2480#endif
2481 const double stopTime = ceil(getSpeed() / cfModel.getMaxDecel());
2482 const double leftSideOnLane = bidiLane->getWidth() - getRightSideOnLane(lane);
2483 PersonDist leader = bidiLane->nextBlocking(relativePos,
2484 leftSideOnLane - getVehicleType().getWidth(), leftSideOnLane, stopTime, true);
2485 if (leader.first != 0) {
2486 const double stopSpeed = cfModel.stopSpeed(this, getSpeed(), leader.second - getVehicleType().getMinGap());
2487 v = MIN2(v, stopSpeed);
2488#ifdef DEBUG_PLAN_MOVE
2489 if (DEBUG_COND) {
2490 std::cout << SIMTIME << " pedLeader=" << leader.first->getID() << " dist=" << leader.second << " v=" << v << "\n";
2491 }
2492#endif
2493 }
2494 }
2495 }
2496
2497 // process all stops and waypoints on the current edge
2498 bool foundRealStop = false;
2499 while (stopIt != myStops.end()
2500 && ((&stopIt->lane->getEdge() == &lane->getEdge())
2501 || (stopIt->isOpposite && stopIt->lane->getEdge().getOppositeEdge() == &lane->getEdge()))
2502 // ignore stops that occur later in a looped route
2503 && stopIt->edge == myCurrEdge + view) {
2504 double stopDist = std::numeric_limits<double>::max();
2505 const MSStop& stop = *stopIt;
2506 const bool isFirstStop = stopIt == myStops.begin();
2507 stopIt++;
2508 if (!stop.reached || (stop.getSpeed() > 0 && keepStopping())) {
2509 // we are approaching a stop on the edge; must not drive further
2510 bool isWaypoint = stop.getSpeed() > 0;
2511 double endPos = stop.getEndPos(*this) + NUMERICAL_EPS;
2512 if (stop.parkingarea != nullptr) {
2513 // leave enough space so parking vehicles can exit
2514 const double brakePos = getBrakeGap() + lane->getLength() - seen;
2515 endPos = stop.parkingarea->getLastFreePosWithReservation(t, *this, brakePos);
2516 } else if (isWaypoint && !stop.reached) {
2517 endPos = stop.pars.startPos;
2518 }
2519 stopDist = seen + endPos - lane->getLength();
2520#ifdef DEBUG_STOPS
2521 if (DEBUG_COND) {
2522 std::cout << SIMTIME << " veh=" << getID() << " stopDist=" << stopDist << " stopLane=" << stop.lane->getID() << " stopEndPos=" << endPos << "\n";
2523 }
2524#endif
2525 // regular stops are not emergencies
2526 double stopSpeed = laneMaxV;
2527 if (isWaypoint) {
2528 bool waypointWithStop = false;
2529 if (stop.getUntil() > t) {
2530 // check if we have to slow down or even stop
2531 SUMOTime time2end = 0;
2532 if (stop.reached) {
2533 time2end = TIME2STEPS((stop.pars.endPos - myState.myPos) / stop.getSpeed());
2534 } else {
2535 time2end = TIME2STEPS(
2536 // time to reach waypoint start
2537 stopDist / ((getSpeed() + stop.getSpeed()) / 2)
2538 // time to reach waypoint end
2539 + (stop.pars.endPos - stop.pars.startPos) / stop.getSpeed());
2540 }
2541 if (stop.getUntil() > t + time2end) {
2542 // we need to stop
2543 double distToEnd = stopDist;
2544 if (!stop.reached) {
2545 distToEnd += stop.pars.endPos - stop.pars.startPos;
2546 }
2547 stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), distToEnd), vMinComfortable);
2548 waypointWithStop = true;
2549 }
2550 }
2551 if (stop.reached) {
2552 stopSpeed = MIN2(stop.getSpeed(), stopSpeed);
2553 if (myState.myPos >= stop.pars.endPos && !waypointWithStop) {
2554 stopDist = std::numeric_limits<double>::max();
2555 }
2556 } else {
2557 stopSpeed = MIN2(MAX2(cfModel.freeSpeed(this, getSpeed(), stopDist, stop.getSpeed()), vMinComfortable), stopSpeed);
2558 if (!stop.reached) {
2559 stopDist += stop.pars.endPos - stop.pars.startPos;
2560 }
2561 if (lastLink != nullptr) {
2562 lastLink->adaptLeaveSpeed(cfModel.freeSpeed(this, vLinkPass, endPos, stop.getSpeed(), false, MSCFModel::CalcReason::FUTURE));
2563 }
2564 }
2565 } else {
2566 stopSpeed = MAX2(cfModel.stopSpeed(this, getSpeed(), stopDist), vMinComfortable);
2567 if (lastLink != nullptr) {
2568 lastLink->adaptLeaveSpeed(cfModel.stopSpeed(this, vLinkPass, endPos, MSCFModel::CalcReason::FUTURE));
2569 }
2570 }
2571 v = MIN2(v, stopSpeed);
2572 if (lane->isInternal()) {
2573 std::vector<MSLink*>::const_iterator exitLink = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
2574 assert(!lane->isLinkEnd(exitLink));
2575 bool dummySetRequest;
2576 double dummyVLinkWait;
2577 checkLinkLeaderCurrentAndParallel(*exitLink, lane, seen, lastLink, v, vLinkPass, dummyVLinkWait, dummySetRequest);
2578 }
2579
2580#ifdef DEBUG_PLAN_MOVE
2581 if (DEBUG_COND) {
2582 std::cout << "\n" << SIMTIME << " next stop: distance = " << stopDist << " requires stopSpeed = " << stopSpeed << "\n";
2583
2584 }
2585#endif
2586 if (isFirstStop) {
2587 newStopDist = stopDist;
2588 // if the vehicle is going to stop we don't need to look further
2589 // (except for trains that make use of further link-approach registration for safety purposes)
2590 if (!isWaypoint) {
2591 planningToStop = true;
2592 if (!isRail()) {
2593 lfLinks.emplace_back(v, stopDist);
2594 foundRealStop = true;
2595 break;
2596 }
2597 }
2598 }
2599 }
2600 }
2601 if (foundRealStop) {
2602 break;
2603 }
2604
2605 // move to next lane
2606 // get the next link used
2607 std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view + 1, *lane, bestLaneConts);
2608
2609 // Check whether this is a turn (to save info about the next upcoming turn)
2610 if (!encounteredTurn) {
2611 if (!lane->isLinkEnd(link) && lane->getLinkCont().size() > 1) {
2612 LinkDirection linkDir = (*link)->getDirection();
2613 switch (linkDir) {
2616 break;
2617 default:
2618 nextTurn.first = seen;
2619 nextTurn.second = *link;
2620 encounteredTurn = true;
2621#ifdef DEBUG_NEXT_TURN
2622 if (DEBUG_COND) {
2623 std::cout << SIMTIME << " veh '" << getID() << "' nextTurn: " << toString(linkDir)
2624 << " at " << nextTurn.first << "m." << std::endl;
2625 }
2626#endif
2627 }
2628 }
2629 }
2630
2631 // check whether the vehicle is on its final edge
2632 if (myCurrEdge + view + 1 == myRoute->end()
2633 || (myParameter->arrivalEdge >= 0 && getRoutePosition() + view == myParameter->arrivalEdge)) {
2634 const double arrivalSpeed = (myParameter->arrivalSpeedProcedure == ArrivalSpeedDefinition::GIVEN ?
2635 myParameter->arrivalSpeed : laneMaxV);
2636 // subtract the arrival speed from the remaining distance so we get one additional driving step with arrival speed
2637 // XXX: This does not work for ballistic update refs #2579
2638 const double distToArrival = seen + myArrivalPos - lane->getLength() - SPEED2DIST(arrivalSpeed);
2639 const double va = MAX2(NUMERICAL_EPS, cfModel.freeSpeed(this, getSpeed(), distToArrival, arrivalSpeed));
2640 v = MIN2(v, va);
2641 if (lastLink != nullptr) {
2642 lastLink->adaptLeaveSpeed(va);
2643 }
2644 lfLinks.push_back(DriveProcessItem(v, seen, lane->getEdge().isFringe() ? 1000 : 0));
2645 break;
2646 }
2647 // check whether the lane or the shadowLane is a dead end (allow some leeway on intersections)
2648 if (lane->isLinkEnd(link)
2649 || (MSGlobals::gSublane && brakeForOverlap(*link, lane))
2650 || (opposite && (*link)->getViaLaneOrLane()->getParallelOpposite() == nullptr
2652 double va = cfModel.stopSpeed(this, getSpeed(), seen);
2653 if (lastLink != nullptr) {
2654 lastLink->adaptLeaveSpeed(va);
2655 }
2658 } else {
2659 v = MIN2(va, v);
2660 }
2661#ifdef DEBUG_PLAN_MOVE
2662 if (DEBUG_COND) {
2663 std::cout << " braking for link end lane=" << lane->getID() << " seen=" << seen
2664 << " overlap=" << getLateralOverlap() << " va=" << va << " committed=" << myLaneChangeModel->getCommittedSpeed() << " v=" << v << "\n";
2665
2666 }
2667#endif
2668 if (lane->isLinkEnd(link)) {
2669 lfLinks.emplace_back(v, seen);
2670 break;
2671 }
2672 }
2673 lateralShift += (*link)->getLateralShift();
2674 const bool yellowOrRed = (*link)->haveRed() || (*link)->haveYellow();
2675 // We distinguish 3 cases when determining the point at which a vehicle stops:
2676 // - allway_stop: the vehicle should stop close to the stop line but may stop at larger distance
2677 // - red/yellow light: here the vehicle 'knows' that it will have priority eventually and does not need to stop on a precise spot
2678 // - other types of minor links: the vehicle needs to stop as close to the junction as necessary
2679 // to minimize the time window for passing the junction. If the
2680 // vehicle 'decides' to accelerate and cannot enter the junction in
2681 // the next step, new foes may appear and cause a collision (see #1096)
2682 // - major links: stopping point is irrelevant
2683 double laneStopOffset;
2684 const double majorStopOffset = MAX2(getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, DIST_TO_STOPLINE_EXPECT_PRIORITY), lane->getVehicleStopOffset(this));
2685 // override low desired decel at yellow and red
2686 const double stopDecel = yellowOrRed && !isRail() ? MAX2(MIN2(MSGlobals::gTLSYellowMinDecel, cfModel.getEmergencyDecel()), cfModel.getMaxDecel()) : cfModel.getMaxDecel();
2687 const double brakeDist = cfModel.brakeGap(myState.mySpeed, stopDecel, 0);
2688 const bool canBrakeBeforeLaneEnd = seen >= brakeDist;
2689 const bool canBrakeBeforeStopLine = seen - lane->getVehicleStopOffset(this) >= brakeDist;
2690 if (yellowOrRed) {
2691 // Wait at red traffic light with full distance if possible
2692 laneStopOffset = majorStopOffset;
2693 } else if ((*link)->havePriority()) {
2694 // On priority link, we should never stop below visibility distance
2695 laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, majorStopOffset);
2696 } else {
2697 double minorStopOffset = MAX2(lane->getVehicleStopOffset(this),
2698 getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_CROSSING_GAP, MSPModel::SAFETY_GAP) - (*link)->getDistToFoePedCrossing());
2699#ifdef DEBUG_PLAN_MOVE
2700 if (DEBUG_COND) {
2701 std::cout << " minorStopOffset=" << minorStopOffset << " distToFoePedCrossing=" << (*link)->getDistToFoePedCrossing() << "\n";
2702 }
2703#endif
2704 if ((*link)->getState() == LINKSTATE_ALLWAY_STOP) {
2705 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP, 0));
2706 } else {
2707 minorStopOffset = MAX2(minorStopOffset, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_STOPLINE_GAP_MINOR, 0));
2708 }
2709 // On minor link, we should likewise never stop below visibility distance
2710 laneStopOffset = MIN2((*link)->getFoeVisibilityDistance() - POSITION_EPS, minorStopOffset);
2711 }
2712#ifdef DEBUG_PLAN_MOVE
2713 if (DEBUG_COND) {
2714 std::cout << SIMTIME << " veh=" << getID() << " desired stopOffset on lane '" << lane->getID() << "' is " << laneStopOffset << "\n";
2715 }
2716#endif
2717 if (canBrakeBeforeLaneEnd) {
2718 // avoid emergency braking if possible
2719 laneStopOffset = MIN2(laneStopOffset, seen - brakeDist);
2720 }
2721 laneStopOffset = MAX2(POSITION_EPS, laneStopOffset);
2722 double stopDist = MAX2(0., seen - laneStopOffset);
2723 if (yellowOrRed && getDevice(typeid(MSDevice_GLOSA)) != nullptr
2724 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->getOverrideSafety()
2725 && static_cast<MSDevice_GLOSA*>(getDevice(typeid(MSDevice_GLOSA)))->isSpeedAdviceActive()) {
2726 stopDist = std::numeric_limits<double>::max();
2727 }
2728 if (newStopDist != std::numeric_limits<double>::max()) {
2729 stopDist = MAX2(stopDist, newStopDist);
2730 }
2731#ifdef DEBUG_PLAN_MOVE
2732 if (DEBUG_COND) {
2733 std::cout << SIMTIME << " veh=" << getID() << " effective stopOffset on lane '" << lane->getID()
2734 << "' is " << laneStopOffset << " (-> stopDist=" << stopDist << ")" << std::endl;
2735 }
2736#endif
2737 if (isRail()
2738 && !lane->isInternal()) {
2739 // check for train direction reversal
2740 if (lane->getBidiLane() != nullptr
2741 && (*link)->getLane()->getBidiLane() == lane) {
2742 double vMustReverse = getCarFollowModel().stopSpeed(this, getSpeed(), seen - POSITION_EPS);
2743 if (seen < 1) {
2744 mustSeeBeforeReversal = 2 * seen + getLength();
2745 }
2746 v = MIN2(v, vMustReverse);
2747 }
2748 // signal that is passed in the current step does not count
2749 foundRailSignal |= ((*link)->getTLLogic() != nullptr
2750 && (*link)->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL
2751 && seen > SPEED2DIST(v));
2752 }
2753
2754 bool canReverseEventually = false;
2755 const double vReverse = checkReversal(canReverseEventually, laneMaxV, seen);
2756 v = MIN2(v, vReverse);
2757#ifdef DEBUG_PLAN_MOVE
2758 if (DEBUG_COND) {
2759 std::cout << SIMTIME << " veh=" << getID() << " canReverseEventually=" << canReverseEventually << " v=" << v << "\n";
2760 }
2761#endif
2762
2763 // check whether we need to slow down in order to finish a continuous lane change
2765 if ( // slow down to finish lane change before a turn lane
2766 ((*link)->getDirection() == LinkDirection::LEFT || (*link)->getDirection() == LinkDirection::RIGHT) ||
2767 // slow down to finish lane change before the shadow lane ends
2768 (myLaneChangeModel->getShadowLane() != nullptr &&
2769 (*link)->getViaLaneOrLane()->getParallelLane(myLaneChangeModel->getShadowDirection()) == nullptr)) {
2770 // XXX maybe this is too harsh. Vehicles could cut some corners here
2771 const double timeRemaining = STEPS2TIME(myLaneChangeModel->remainingTime());
2772 assert(timeRemaining != 0);
2773 // XXX: Euler-logic (#860), but I couldn't identify problems from this yet (Leo). Refs. #2575
2774 const double va = MAX2(cfModel.stopSpeed(this, getSpeed(), seen - POSITION_EPS),
2775 (seen - POSITION_EPS) / timeRemaining);
2776#ifdef DEBUG_PLAN_MOVE
2777 if (DEBUG_COND) {
2778 std::cout << SIMTIME << " veh=" << getID() << " slowing down to finish continuous change before"
2779 << " link=" << (*link)->getViaLaneOrLane()->getID()
2780 << " timeRemaining=" << timeRemaining
2781 << " v=" << v
2782 << " va=" << va
2783 << std::endl;
2784 }
2785#endif
2786 v = MIN2(va, v);
2787 }
2788 }
2789
2790 // - always issue a request to leave the intersection we are currently on
2791 const bool leavingCurrentIntersection = myLane->getEdge().isInternal() && lastLink == nullptr;
2792 // - do not issue a request to enter an intersection after we already slowed down for an earlier one
2793 const bool abortRequestAfterMinor = slowedDownForMinor && (*link)->getInternalLaneBefore() == nullptr;
2794 // - even if red, if we cannot break we should issue a request
2795 bool setRequest = (v > NUMERICAL_EPS_SPEED && !abortRequestAfterMinor) || (leavingCurrentIntersection);
2796
2797 double stopSpeed = cfModel.stopSpeed(this, getSpeed(), stopDist, stopDecel, MSCFModel::CalcReason::CURRENT_WAIT);
2798 double vLinkWait = MIN2(v, stopSpeed);
2799#ifdef DEBUG_PLAN_MOVE
2800 if (DEBUG_COND) {
2801 std::cout
2802 << " stopDist=" << stopDist
2803 << " stopDecel=" << stopDecel
2804 << " vLinkWait=" << vLinkWait
2805 << " brakeDist=" << brakeDist
2806 << " seen=" << seen
2807 << " leaveIntersection=" << leavingCurrentIntersection
2808 << " setRequest=" << setRequest
2809 //<< std::setprecision(16)
2810 //<< " v=" << v
2811 //<< " speedEps=" << NUMERICAL_EPS_SPEED
2812 //<< std::setprecision(gPrecision)
2813 << "\n";
2814 }
2815#endif
2816
2817 if (yellowOrRed && canBrakeBeforeStopLine && !ignoreRed(*link, canBrakeBeforeStopLine) && seen >= mustSeeBeforeReversal) {
2818 if (lane->isInternal()) {
2819 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
2820 }
2821 // arrivalSpeed / arrivalTime when braking for red light is only relevent for rail signal switching
2822 const SUMOTime arrivalTime = getArrivalTime(t, seen, v, vLinkPass);
2823 // the vehicle is able to brake in front of a yellow/red traffic light
2824 lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, false, arrivalTime, vLinkWait, 0, seen, -1));
2825 //lfLinks.push_back(DriveProcessItem(0, vLinkWait, vLinkWait, false, 0, 0, stopDist));
2826 break;
2827 }
2828
2829 const MSLink* entryLink = (*link)->getCorrespondingEntryLink();
2830 if (entryLink->haveRed() && ignoreRed(*link, canBrakeBeforeStopLine) && STEPS2TIME(t - entryLink->getLastStateChange()) > 2) {
2831 // restrict speed when ignoring a red light
2832 const double redSpeed = MIN2(v, getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_RED_SPEED, v));
2833 const double va = MAX2(redSpeed, cfModel.freeSpeed(this, getSpeed(), seen, redSpeed));
2834 v = MIN2(va, v);
2835#ifdef DEBUG_PLAN_MOVE
2836 if (DEBUG_COND) std::cout
2837 << " ignoreRed spent=" << STEPS2TIME(t - (*link)->getLastStateChange())
2838 << " redSpeed=" << redSpeed
2839 << " va=" << va
2840 << " v=" << v
2841 << "\n";
2842#endif
2843 }
2844
2845 checkLinkLeaderCurrentAndParallel(*link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
2846
2847 if (lastLink != nullptr) {
2848 lastLink->adaptLeaveSpeed(laneMaxV);
2849 }
2850 double arrivalSpeed = vLinkPass;
2851 // vehicles should decelerate when approaching a minor link
2852 // - unless they are close enough to have clear visibility of all relevant foe lanes and may start to accelerate again
2853 // - and unless they are so close that stopping is impossible (i.e. when a green light turns to yellow when close to the junction)
2854
2855 // whether the vehicle/driver is close enough to the link to see all possible foes #2123
2856 const double visibilityDistance = (*link)->getFoeVisibilityDistance();
2857 const double determinedFoePresence = seen <= visibilityDistance;
2858// // VARIANT: account for time needed to recognize whether relevant vehicles are on the foe lanes. (Leo)
2859// double foeRecognitionTime = 0.0;
2860// double determinedFoePresence = seen < visibilityDistance - myState.mySpeed*foeRecognitionTime;
2861
2862#ifdef DEBUG_PLAN_MOVE
2863 if (DEBUG_COND) {
2864 std::cout << " approaching link=" << (*link)->getViaLaneOrLane()->getID() << " prio=" << (*link)->havePriority() << " seen=" << seen << " visibilityDistance=" << visibilityDistance << " brakeDist=" << brakeDist << "\n";
2865 }
2866#endif
2867
2868 const bool couldBrakeForMinor = !(*link)->havePriority() && brakeDist < seen && !(*link)->lastWasContMajor();
2869 if (couldBrakeForMinor && !determinedFoePresence) {
2870 // vehicle decelerates just enough to be able to stop if necessary and then accelerates
2871 double maxSpeedAtVisibilityDist = cfModel.maximumSafeStopSpeed(visibilityDistance, cfModel.getMaxDecel(), myState.mySpeed, false, 0., false);
2872 // XXX: estimateSpeedAfterDistance does not use euler-logic (thus returns a lower value than possible here...)
2873 double maxArrivalSpeed = cfModel.estimateSpeedAfterDistance(visibilityDistance, maxSpeedAtVisibilityDist, cfModel.getMaxAccel());
2874 arrivalSpeed = MIN2(vLinkPass, maxArrivalSpeed);
2875 slowedDownForMinor = true;
2876#ifdef DEBUG_PLAN_MOVE
2877 if (DEBUG_COND) {
2878 std::cout << " slowedDownForMinor maxSpeedAtVisDist=" << maxSpeedAtVisibilityDist << " maxArrivalSpeed=" << maxArrivalSpeed << " arrivalSpeed=" << arrivalSpeed << "\n";
2879 }
2880#endif
2881 } else if ((*link)->getState() == LINKSTATE_EQUAL && myWaitingTime > 0) {
2882 // check for deadlock (circular yielding)
2883 //std::cout << SIMTIME << " veh=" << getID() << " check rbl-deadlock\n";
2884 std::pair<const SUMOVehicle*, const MSLink*> blocker = (*link)->getFirstApproachingFoe(*link);
2885 //std::cout << " blocker=" << Named::getIDSecure(blocker.first) << "\n";
2886 int n = 100;
2887 while (blocker.second != nullptr && blocker.second != *link && n > 0) {
2888 blocker = blocker.second->getFirstApproachingFoe(*link);
2889 n--;
2890 //std::cout << " blocker=" << Named::getIDSecure(blocker.first) << "\n";
2891 }
2892 if (n == 0) {
2893 WRITE_WARNINGF(TL("Suspicious right_before_left junction '%'."), lane->getEdge().getToJunction()->getID());
2894 }
2895 //std::cout << " blockerLink=" << blocker.second << " link=" << *link << "\n";
2896 if (blocker.second == *link) {
2897 const double threshold = (*link)->getDirection() == LinkDirection::STRAIGHT ? 0.25 : 0.75;
2898 if (RandHelper::rand(getRNG()) < threshold) {
2899 //std::cout << " abort request, threshold=" << threshold << "\n";
2900 setRequest = false;
2901 }
2902 }
2903 }
2904
2905 const SUMOTime arrivalTime = getArrivalTime(t, seen, v, arrivalSpeed);
2906 if (couldBrakeForMinor && determinedFoePresence && (*link)->getLane()->getEdge().isRoundabout()) {
2907 const bool wasOpened = (*link)->opened(arrivalTime, arrivalSpeed, arrivalSpeed,
2909 getCarFollowModel().getMaxDecel(),
2911 nullptr, false, this);
2912 if (!wasOpened) {
2913 slowedDownForMinor = true;
2914 }
2915#ifdef DEBUG_PLAN_MOVE
2916 if (DEBUG_COND) {
2917 std::cout << " slowedDownForMinor at roundabout=" << (!wasOpened) << "\n";
2918 }
2919#endif
2920 }
2921
2922 // compute arrival speed and arrival time if vehicle starts braking now
2923 // if stopping is possible, arrivalTime can be arbitrarily large. A small value keeps fractional times (impatience) meaningful
2924 double arrivalSpeedBraking = 0;
2925 const double bGap = cfModel.brakeGap(v);
2926 if (seen < bGap && !isStopped() && !planningToStop) { // XXX: should this use the current speed (at least for the ballistic case)? (Leo) Refs. #2575
2927 // vehicle cannot come to a complete stop in time
2929 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeedEuler(seen, v);
2930 // due to discrete/continuous mismatch (when using Euler update) we have to ensure that braking actually helps
2931 arrivalSpeedBraking = MIN2(arrivalSpeedBraking, arrivalSpeed);
2932 } else {
2933 arrivalSpeedBraking = cfModel.getMinimalArrivalSpeed(seen, myState.mySpeed);
2934 }
2935 }
2936
2937 // estimate leave speed for passing time computation
2938 // l=linkLength, a=accel, t=continuousTime, v=vLeave
2939 // l=v*t + 0.5*a*t^2, solve for t and multiply with a, then add v
2940 const double estimatedLeaveSpeed = MIN2((*link)->getViaLaneOrLane()->getVehicleMaxSpeed(this),
2941 getCarFollowModel().estimateSpeedAfterDistance((*link)->getLength(), arrivalSpeed, getVehicleType().getCarFollowModel().getMaxAccel()));
2942 lfLinks.push_back(DriveProcessItem(*link, v, vLinkWait, setRequest,
2943 arrivalTime, arrivalSpeed,
2944 arrivalSpeedBraking,
2945 seen, estimatedLeaveSpeed));
2946 if ((*link)->getViaLane() == nullptr) {
2947 hadNonInternal = true;
2948 ++view;
2949 }
2950#ifdef DEBUG_PLAN_MOVE
2951 if (DEBUG_COND) {
2952 std::cout << " checkAbort setRequest=" << setRequest << " v=" << v << " seen=" << seen << " dist=" << dist
2953 << " seenNonInternal=" << seenNonInternal
2954 << " seenInternal=" << seenInternal << " length=" << vehicleLength << "\n";
2955 }
2956#endif
2957 // we need to look ahead far enough to see available space for checkRewindLinkLanes
2958 if ((!setRequest || v <= 0 || seen > dist) && hadNonInternal && seenNonInternal > MAX2(vehicleLength * CRLL_LOOK_AHEAD, vehicleLength + seenInternal) && foundRailSignal) {
2959 break;
2960 }
2961 // get the following lane
2962 lane = (*link)->getViaLaneOrLane();
2963 laneMaxV = lane->getVehicleMaxSpeed(this);
2965 laneMaxV = std::numeric_limits<double>::max();
2966 }
2967 // the link was passed
2968 // compute the velocity to use when the link is not blocked by other vehicles
2969 // the vehicle shall be not faster when reaching the next lane than allowed
2970 // speed limits are not emergencies (e.g. when the limit changes suddenly due to TraCI or a variableSpeedSignal)
2971 const double va = MAX2(cfModel.freeSpeed(this, getSpeed(), seen, laneMaxV), vMinComfortable);
2972 v = MIN2(va, v);
2973#ifdef DEBUG_PLAN_MOVE
2974 if (DEBUG_COND) {
2975 std::cout << " laneMaxV=" << laneMaxV << " freeSpeed=" << va << " v=" << v << "\n";
2976 }
2977#endif
2978 if (lane->getEdge().isInternal()) {
2979 seenInternal += lane->getLength();
2980 } else {
2981 seenNonInternal += lane->getLength();
2982 }
2983 // do not restrict results to the current vehicle to allow caching for the current time step
2984 leaderLane = opposite ? lane->getParallelOpposite() : lane;
2985 if (leaderLane == nullptr) {
2986
2987 break;
2988 }
2989 ahead = opposite ? MSLeaderInfo(leaderLane->getWidth()) : leaderLane->getLastVehicleInformation(nullptr, 0);
2990 seen += lane->getLength();
2991 vLinkPass = MIN2(cfModel.estimateSpeedAfterDistance(lane->getLength(), v, cfModel.getMaxAccel()), laneMaxV); // upper bound
2992 lastLink = &lfLinks.back();
2993 }
2994
2995//#ifdef DEBUG_PLAN_MOVE
2996// if(DEBUG_COND){
2997// std::cout << "planMoveInternal found safe speed v = " << v << std::endl;
2998// }
2999//#endif
3000
3001#ifdef PARALLEL_STOPWATCH
3002 myLane->getStopWatch()[0].stop();
3003#endif
3004}
3005
3006
3007double
3008MSVehicle::slowDownForSchedule(double vMinComfortable) const {
3009 const double sfp = getVehicleType().getParameter().speedFactorPremature;
3010 const MSStop& stop = myStops.front();
3011 std::pair<double, double> timeDist = estimateTimeToNextStop();
3012 double arrivalDelay = SIMTIME + timeDist.first - STEPS2TIME(stop.pars.arrival);
3013 double t = STEPS2TIME(stop.pars.arrival - SIMSTEP);
3016 arrivalDelay += STEPS2TIME(stop.pars.arrival - flexStart);
3017 t = STEPS2TIME(flexStart - SIMSTEP);
3018 } else if (stop.pars.started >= 0 && MSGlobals::gUseStopStarted) {
3019 arrivalDelay += STEPS2TIME(stop.pars.arrival - stop.pars.started);
3020 t = STEPS2TIME(stop.pars.started - SIMSTEP);
3021 }
3022 if (arrivalDelay < 0 && sfp < getChosenSpeedFactor()) {
3023 // we can slow down to better match the schedule (and increase energy efficiency)
3024 const double vSlowDownMin = MAX2(myLane->getSpeedLimit() * sfp, vMinComfortable);
3025 const double s = timeDist.second;
3026 const double b = getCarFollowModel().getMaxDecel();
3027 // x = speed for arriving in t seconds
3028 // u = time at full speed
3029 // u * x + (t - u) * 0.5 * x = s
3030 // t - u = x / b
3031 // eliminate u, solve x
3032 const double radicand = 4 * t * t * b * b - 8 * s * b;
3033 const double x = radicand >= 0 ? t * b - sqrt(radicand) * 0.5 : vSlowDownMin;
3034 double vSlowDown = x < vSlowDownMin ? vSlowDownMin : x;
3035#ifdef DEBUG_PLAN_MOVE
3036 if (DEBUG_COND) {
3037 std::cout << SIMTIME << " veh=" << getID() << " ad=" << arrivalDelay << " t=" << t << " vsm=" << vSlowDownMin
3038 << " r=" << radicand << " vs=" << vSlowDown << "\n";
3039 }
3040#endif
3041 return vSlowDown;
3042 } else if (arrivalDelay > 0 && sfp > getChosenSpeedFactor()) {
3043 // in principle we could up to catch up with the schedule
3044 // but at this point we can only lower the speed, the
3045 // information would have to be used when computing getVehicleMaxSpeed
3046 }
3047 return getMaxSpeed();
3048}
3049
3051MSVehicle::getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const {
3052 const MSCFModel& cfModel = getCarFollowModel();
3053 SUMOTime arrivalTime;
3055 // @note intuitively it would make sense to compare arrivalSpeed with getSpeed() instead of v
3056 // however, due to the current position update rule (ticket #860) the vehicle moves with v in this step
3057 // subtract DELTA_T because t is the time at the end of this step and the movement is not carried out yet
3058 arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, v, arrivalSpeed);
3059 } else {
3060 arrivalTime = t - DELTA_T + cfModel.getMinimalArrivalTime(seen, myState.mySpeed, arrivalSpeed);
3061 }
3062 if (isStopped()) {
3063 arrivalTime += MAX2((SUMOTime)0, myStops.front().duration);
3064 }
3065 return arrivalTime;
3066}
3067
3068
3069void
3070MSVehicle::adaptToLeaders(const MSLeaderInfo& ahead, double latOffset,
3071 const double seen, DriveProcessItem* const lastLink,
3072 const MSLane* const lane, double& v, double& vLinkPass) const {
3073 int rightmost;
3074 int leftmost;
3075 ahead.getSubLanes(this, latOffset, rightmost, leftmost);
3076#ifdef DEBUG_PLAN_MOVE
3077 if (DEBUG_COND) std::cout << SIMTIME
3078 << "\nADAPT_TO_LEADERS\nveh=" << getID()
3079 << " lane=" << lane->getID()
3080 << " latOffset=" << latOffset
3081 << " rm=" << rightmost
3082 << " lm=" << leftmost
3083 << " shift=" << ahead.getSublaneOffset()
3084 << " ahead=" << ahead.toString()
3085 << "\n";
3086#endif
3087 /*
3088 if (myLaneChangeModel->getCommittedSpeed() > 0) {
3089 v = MIN2(v, myLaneChangeModel->getCommittedSpeed());
3090 vLinkPass = MIN2(vLinkPass, myLaneChangeModel->getCommittedSpeed());
3091 #ifdef DEBUG_PLAN_MOVE
3092 if (DEBUG_COND) std::cout << " hasCommitted=" << myLaneChangeModel->getCommittedSpeed() << "\n";
3093 #endif
3094 return;
3095 }
3096 */
3097 for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
3098 const MSVehicle* pred = ahead[sublane];
3099 if (pred != nullptr && pred != this) {
3100 // @todo avoid multiple adaptations to the same leader
3101 const double predBack = pred->getBackPositionOnLane(lane);
3102 double gap = (lastLink == nullptr
3103 ? predBack - myState.myPos - getVehicleType().getMinGap()
3104 : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
3105 bool oncoming = false;
3107 if (pred->getLaneChangeModel().isOpposite() || lane == pred->getLaneChangeModel().getShadowLane()) {
3108 // ego might and leader are driving against lane
3109 gap = (lastLink == nullptr
3110 ? myState.myPos - predBack - getVehicleType().getMinGap()
3111 : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
3112 } else {
3113 // ego and leader are driving in the same direction as lane (shadowlane for ego)
3114 gap = (lastLink == nullptr
3115 ? predBack - (myLane->getLength() - myState.myPos) - getVehicleType().getMinGap()
3116 : predBack + seen - lane->getLength() - getVehicleType().getMinGap());
3117 }
3118 } else if (pred->getLaneChangeModel().isOpposite() && pred->getLaneChangeModel().getShadowLane() != lane) {
3119 // must react to stopped / dangerous oncoming vehicles
3120 gap += -pred->getVehicleType().getLength() + getVehicleType().getMinGap() - MAX2(getVehicleType().getMinGap(), pred->getVehicleType().getMinGap());
3121 // try to avoid collision in the next second
3122 const double predMaxDist = pred->getSpeed() + pred->getCarFollowModel().getMaxAccel();
3123#ifdef DEBUG_PLAN_MOVE
3124 if (DEBUG_COND) {
3125 std::cout << " fixedGap=" << gap << " predMaxDist=" << predMaxDist << "\n";
3126 }
3127#endif
3128 if (gap < predMaxDist + getSpeed() || pred->getLane() == lane->getBidiLane()) {
3129 gap -= predMaxDist;
3130 }
3131 } else if (pred->getLane() == lane->getBidiLane()) {
3132 gap -= pred->getVehicleType().getLengthWithGap();
3133 oncoming = true;
3134 }
3135#ifdef DEBUG_PLAN_MOVE
3136 if (DEBUG_COND) {
3137 std::cout << " pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << gap << " predBack=" << predBack << " seen=" << seen << " lane=" << lane->getID() << " myLane=" << myLane->getID() << " lastLink=" << (lastLink == nullptr ? "NULL" : lastLink->myLink->getDescription()) << " oncoming=" << oncoming << "\n";
3138 }
3139#endif
3140 if (oncoming && gap >= 0) {
3141 adaptToOncomingLeader(std::make_pair(pred, gap), lastLink, v, vLinkPass);
3142 } else {
3143 adaptToLeader(std::make_pair(pred, gap), seen, lastLink, v, vLinkPass);
3144 }
3145 }
3146 }
3147}
3148
3149void
3151 double seen,
3152 DriveProcessItem* const lastLink,
3153 double& v, double& vLinkPass) const {
3154 int rightmost;
3155 int leftmost;
3156 ahead.getSubLanes(this, latOffset, rightmost, leftmost);
3157#ifdef DEBUG_PLAN_MOVE
3158 if (DEBUG_COND) std::cout << SIMTIME
3159 << "\nADAPT_TO_LEADERS_DISTANCE\nveh=" << getID()
3160 << " latOffset=" << latOffset
3161 << " rm=" << rightmost
3162 << " lm=" << leftmost
3163 << " ahead=" << ahead.toString()
3164 << "\n";
3165#endif
3166 for (int sublane = rightmost; sublane <= leftmost; ++sublane) {
3167 CLeaderDist predDist = ahead[sublane];
3168 const MSVehicle* pred = predDist.first;
3169 if (pred != nullptr && pred != this) {
3170#ifdef DEBUG_PLAN_MOVE
3171 if (DEBUG_COND) {
3172 std::cout << " pred=" << pred->getID() << " predLane=" << pred->getLane()->getID() << " predPos=" << pred->getPositionOnLane() << " gap=" << predDist.second << "\n";
3173 }
3174#endif
3175 adaptToLeader(predDist, seen, lastLink, v, vLinkPass);
3176 }
3177 }
3178}
3179
3180
3181void
3182MSVehicle::adaptToLeader(const std::pair<const MSVehicle*, double> leaderInfo,
3183 double seen,
3184 DriveProcessItem* const lastLink,
3185 double& v, double& vLinkPass) const {
3186 if (leaderInfo.first != 0) {
3187 if (ignoreFoe(leaderInfo.first)) {
3188#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3189 if (DEBUG_COND) {
3190 std::cout << " foe ignored\n";
3191 }
3192#endif
3193 return;
3194 }
3195 const MSCFModel& cfModel = getCarFollowModel();
3196 double vsafeLeader = 0;
3198 vsafeLeader = -std::numeric_limits<double>::max();
3199 }
3200 bool backOnRoute = true;
3201 if (leaderInfo.second < 0 && lastLink != nullptr && lastLink->myLink != nullptr) {
3202 backOnRoute = false;
3203 // this can either be
3204 // a) a merging situation (leader back is is not our route) or
3205 // b) a minGap violation / collision
3206 MSLane* current = lastLink->myLink->getViaLaneOrLane();
3207 if (leaderInfo.first->getBackLane() == current) {
3208 backOnRoute = true;
3209 } else {
3210 for (MSLane* lane : getBestLanesContinuation()) {
3211 if (lane == current) {
3212 break;
3213 }
3214 if (leaderInfo.first->getBackLane() == lane) {
3215 backOnRoute = true;
3216 }
3217 }
3218 }
3219#ifdef DEBUG_PLAN_MOVE
3220 if (DEBUG_COND) {
3221 std::cout << SIMTIME << " current=" << current->getID() << " leaderBackLane=" << leaderInfo.first->getBackLane()->getID() << " backOnRoute=" << backOnRoute << "\n";
3222 }
3223#endif
3224 if (!backOnRoute) {
3225 double stopDist = seen - current->getLength() - POSITION_EPS;
3226 if (lastLink->myLink->getInternalLaneBefore() != nullptr) {
3227 // do not drive onto the junction conflict area
3228 stopDist -= lastLink->myLink->getInternalLaneBefore()->getLength();
3229 }
3230 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), stopDist);
3231 }
3232 }
3233 if (backOnRoute) {
3234 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
3235 }
3236 if (lastLink != nullptr) {
3237 const double futureVSafe = cfModel.followSpeed(this, lastLink->accelV, leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first, MSCFModel::CalcReason::FUTURE);
3238 lastLink->adaptLeaveSpeed(futureVSafe);
3239#ifdef DEBUG_PLAN_MOVE
3240 if (DEBUG_COND) {
3241 std::cout << " vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
3242 }
3243#endif
3244 }
3245 v = MIN2(v, vsafeLeader);
3246 vLinkPass = MIN2(vLinkPass, vsafeLeader);
3247#ifdef DEBUG_PLAN_MOVE
3248 if (DEBUG_COND) std::cout
3249 << SIMTIME
3250 //std::cout << std::setprecision(10);
3251 << " veh=" << getID()
3252 << " lead=" << leaderInfo.first->getID()
3253 << " leadSpeed=" << leaderInfo.first->getSpeed()
3254 << " gap=" << leaderInfo.second
3255 << " leadLane=" << leaderInfo.first->getLane()->getID()
3256 << " predPos=" << leaderInfo.first->getPositionOnLane()
3257 << " myLane=" << myLane->getID()
3258 << " v=" << v
3259 << " vSafeLeader=" << vsafeLeader
3260 << " vLinkPass=" << vLinkPass
3261 << "\n";
3262#endif
3263 }
3264}
3265
3266
3267void
3268MSVehicle::adaptToJunctionLeader(const std::pair<const MSVehicle*, double> leaderInfo,
3269 const double seen, DriveProcessItem* const lastLink,
3270 const MSLane* const lane, double& v, double& vLinkPass,
3271 double distToCrossing) const {
3272 if (leaderInfo.first != 0) {
3273 if (ignoreFoe(leaderInfo.first)) {
3274#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3275 if (DEBUG_COND) {
3276 std::cout << " junction foe ignored\n";
3277 }
3278#endif
3279 return;
3280 }
3281 const MSCFModel& cfModel = getCarFollowModel();
3282 double vsafeLeader = 0;
3284 vsafeLeader = -std::numeric_limits<double>::max();
3285 }
3286 if (leaderInfo.second >= 0) {
3287 if (hasDeparted()) {
3288 vsafeLeader = cfModel.followSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
3289 } else {
3290 // called in the context of MSLane::isInsertionSuccess
3291 vsafeLeader = cfModel.insertionFollowSpeed(this, getSpeed(), leaderInfo.second, leaderInfo.first->getSpeed(), leaderInfo.first->getCurrentApparentDecel(), leaderInfo.first);
3292 }
3293 } else if (leaderInfo.first != this) {
3294 // the leading, in-lapping vehicle is occupying the complete next lane
3295 // stop before entering this lane
3296 vsafeLeader = cfModel.stopSpeed(this, getSpeed(), seen - lane->getLength() - POSITION_EPS);
3297#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3298 if (DEBUG_COND) {
3299 std::cout << SIMTIME << " veh=" << getID() << " stopping before junction: lane=" << lane->getID() << " seen=" << seen
3300 << " laneLength=" << lane->getLength()
3301 << " stopDist=" << seen - lane->getLength() - POSITION_EPS
3302 << " vsafeLeader=" << vsafeLeader
3303 << " distToCrossing=" << distToCrossing
3304 << "\n";
3305 }
3306#endif
3307 }
3308 if (distToCrossing >= 0) {
3309 // can the leader still stop in the way?
3310 const double vStop = cfModel.stopSpeed(this, getSpeed(), distToCrossing - getVehicleType().getMinGap());
3311 if (leaderInfo.first == this) {
3312 // braking for pedestrian
3313 const double vStopCrossing = cfModel.stopSpeed(this, getSpeed(), distToCrossing);
3314 vsafeLeader = vStopCrossing;
3315#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3316 if (DEBUG_COND) {
3317 std::cout << " breaking for pedestrian distToCrossing=" << distToCrossing << " vStopCrossing=" << vStopCrossing << "\n";
3318 }
3319#endif
3320 if (lastLink != nullptr) {
3321 lastLink->adaptStopSpeed(vsafeLeader);
3322 }
3323 } else if (leaderInfo.second == -std::numeric_limits<double>::max()) {
3324 // drive up to the crossing point and stop
3325#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3326 if (DEBUG_COND) {
3327 std::cout << " stop at crossing point for critical leader vStop=" << vStop << "\n";
3328 };
3329#endif
3330 vsafeLeader = MAX2(vsafeLeader, vStop);
3331 } else {
3332 const double leaderDistToCrossing = distToCrossing - leaderInfo.second;
3333 // estimate the time at which the leader has gone past the crossing point
3334 const double leaderPastCPTime = leaderDistToCrossing / MAX2(leaderInfo.first->getSpeed(), SUMO_const_haltingSpeed);
3335 // reach distToCrossing after that time
3336 // avgSpeed * leaderPastCPTime = distToCrossing
3337 // ballistic: avgSpeed = (getSpeed + vFinal) / 2
3338 const double vFinal = MAX2(getSpeed(), 2 * (distToCrossing - getVehicleType().getMinGap()) / leaderPastCPTime - getSpeed());
3339 const double v2 = getSpeed() + ACCEL2SPEED((vFinal - getSpeed()) / leaderPastCPTime);
3340 vsafeLeader = MAX2(vsafeLeader, MIN2(v2, vStop));
3341#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3342 if (DEBUG_COND) {
3343 std::cout << " driving up to the crossing point (distToCrossing=" << distToCrossing << ")"
3344 << " leaderPastCPTime=" << leaderPastCPTime
3345 << " vFinal=" << vFinal
3346 << " v2=" << v2
3347 << " vStop=" << vStop
3348 << " vsafeLeader=" << vsafeLeader << "\n";
3349 }
3350#endif
3351 }
3352 }
3353 if (lastLink != nullptr) {
3354 lastLink->adaptLeaveSpeed(vsafeLeader);
3355 }
3356 v = MIN2(v, vsafeLeader);
3357 vLinkPass = MIN2(vLinkPass, vsafeLeader);
3358#ifdef DEBUG_PLAN_MOVE
3359 if (DEBUG_COND) std::cout
3360 << SIMTIME
3361 //std::cout << std::setprecision(10);
3362 << " veh=" << getID()
3363 << " lead=" << leaderInfo.first->getID()
3364 << " leadSpeed=" << leaderInfo.first->getSpeed()
3365 << " gap=" << leaderInfo.second
3366 << " leadLane=" << leaderInfo.first->getLane()->getID()
3367 << " predPos=" << leaderInfo.first->getPositionOnLane()
3368 << " seen=" << seen
3369 << " lane=" << lane->getID()
3370 << " myLane=" << myLane->getID()
3371 << " dTC=" << distToCrossing
3372 << " v=" << v
3373 << " vSafeLeader=" << vsafeLeader
3374 << " vLinkPass=" << vLinkPass
3375 << "\n";
3376#endif
3377 }
3378}
3379
3380
3381void
3382MSVehicle::adaptToOncomingLeader(const std::pair<const MSVehicle*, double> leaderInfo,
3383 DriveProcessItem* const lastLink,
3384 double& v, double& vLinkPass) const {
3385 if (leaderInfo.first != 0) {
3386 if (ignoreFoe(leaderInfo.first)) {
3387#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3388 if (DEBUG_COND) {
3389 std::cout << " oncoming foe ignored\n";
3390 }
3391#endif
3392 return;
3393 }
3394 const MSCFModel& cfModel = getCarFollowModel();
3395 const MSVehicle* lead = leaderInfo.first;
3396 const MSCFModel& cfModelL = lead->getCarFollowModel();
3397 // assume the leader reacts symmetrically (neither stopping instantly nor ignoring ego)
3398 const double leaderBrakeGap = cfModelL.brakeGap(lead->getSpeed(), cfModelL.getMaxDecel(), 0);
3399 const double egoBrakeGap = cfModel.brakeGap(getSpeed(), cfModel.getMaxDecel(), 0);
3400 const double gapSum = leaderBrakeGap + egoBrakeGap;
3401 // ensure that both vehicles can leave an intersection if they are currently on it
3402 double egoExit = getDistanceToLeaveJunction();
3403 const double leaderExit = lead->getDistanceToLeaveJunction();
3404 double gap = leaderInfo.second;
3405 if (egoExit + leaderExit < gap) {
3406 gap -= egoExit + leaderExit;
3407 } else {
3408 egoExit = 0;
3409 }
3410 // split any distance in excess of brakeGaps evenly
3411 const double freeGap = MAX2(0.0, gap - gapSum);
3412 const double splitGap = MIN2(gap, gapSum);
3413 // assume remaining distance is allocated in proportion to braking distance
3414 const double gapRatio = gapSum > 0 ? egoBrakeGap / gapSum : 0.5;
3415 const double vsafeLeader = cfModel.stopSpeed(this, getSpeed(), splitGap * gapRatio + egoExit + 0.5 * freeGap);
3416 if (lastLink != nullptr) {
3417 const double futureVSafe = cfModel.stopSpeed(this, lastLink->accelV, leaderInfo.second, MSCFModel::CalcReason::FUTURE);
3418 lastLink->adaptLeaveSpeed(futureVSafe);
3419#ifdef DEBUG_PLAN_MOVE
3420 if (DEBUG_COND) {
3421 std::cout << " vlinkpass=" << lastLink->myVLinkPass << " futureVSafe=" << futureVSafe << "\n";
3422 }
3423#endif
3424 }
3425 v = MIN2(v, vsafeLeader);
3426 vLinkPass = MIN2(vLinkPass, vsafeLeader);
3427#ifdef DEBUG_PLAN_MOVE
3428 if (DEBUG_COND) std::cout
3429 << SIMTIME
3430 //std::cout << std::setprecision(10);
3431 << " veh=" << getID()
3432 << " oncomingLead=" << lead->getID()
3433 << " leadSpeed=" << lead->getSpeed()
3434 << " gap=" << leaderInfo.second
3435 << " gap2=" << gap
3436 << " gapRatio=" << gapRatio
3437 << " leadLane=" << lead->getLane()->getID()
3438 << " predPos=" << lead->getPositionOnLane()
3439 << " myLane=" << myLane->getID()
3440 << " v=" << v
3441 << " vSafeLeader=" << vsafeLeader
3442 << " vLinkPass=" << vLinkPass
3443 << "\n";
3444#endif
3445 }
3446}
3447
3448
3449void
3450MSVehicle::checkLinkLeaderCurrentAndParallel(const MSLink* link, const MSLane* lane, double seen,
3451 DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest) const {
3453 // we want to pass the link but need to check for foes on internal lanes
3454 checkLinkLeader(link, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest);
3455 if (myLaneChangeModel->getShadowLane() != nullptr) {
3456 const MSLink* const parallelLink = link->getParallelLink(myLaneChangeModel->getShadowDirection());
3457 if (parallelLink != nullptr) {
3458 checkLinkLeader(parallelLink, lane, seen, lastLink, v, vLinkPass, vLinkWait, setRequest, true);
3459 }
3460 }
3461 }
3462
3463}
3464
3465void
3466MSVehicle::checkLinkLeader(const MSLink* link, const MSLane* lane, double seen,
3467 DriveProcessItem* const lastLink, double& v, double& vLinkPass, double& vLinkWait, bool& setRequest,
3468 bool isShadowLink) const {
3469#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3470 if (DEBUG_COND) {
3471 gDebugFlag1 = true; // See MSLink::getLeaderInfo
3472 }
3473#endif
3474 const MSLink::LinkLeaders linkLeaders = link->getLeaderInfo(this, seen, nullptr, isShadowLink);
3475#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3476 if (DEBUG_COND) {
3477 gDebugFlag1 = false; // See MSLink::getLeaderInfo
3478 }
3479#endif
3480 for (MSLink::LinkLeaders::const_iterator it = linkLeaders.begin(); it != linkLeaders.end(); ++it) {
3481 // the vehicle to enter the junction first has priority
3482 const MSVehicle* leader = (*it).vehAndGap.first;
3483 if (leader == nullptr) {
3484 // leader is a pedestrian. Passing 'this' as a dummy.
3485#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3486 if (DEBUG_COND) {
3487 std::cout << SIMTIME << " veh=" << getID() << " is blocked on link to " << link->getViaLaneOrLane()->getID() << " by pedestrian. dist=" << it->distToCrossing << "\n";
3488 }
3489#endif
3492#ifdef DEBUG_PLAN_MOVE
3493 if (DEBUG_COND) {
3494 std::cout << SIMTIME << " veh=" << getID() << " is ignoring pedestrian (jmIgnoreJunctionFoeProb)\n";
3495 }
3496#endif
3497 continue;
3498 }
3499 adaptToJunctionLeader(std::make_pair(this, -1), seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
3500 // if blocked by a pedestrian for too long we must yield our request
3502 setRequest = false;
3503#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3504 if (DEBUG_COND) {
3505 std::cout << " aborting request\n";
3506 }
3507#endif
3508 }
3509 } else if (isLeader(link, leader, (*it).vehAndGap.second) || (*it).inTheWay()) {
3512#ifdef DEBUG_PLAN_MOVE
3513 if (DEBUG_COND) {
3514 std::cout << SIMTIME << " veh=" << getID() << " is ignoring linkLeader=" << leader->getID() << " (jmIgnoreJunctionFoeProb)\n";
3515 }
3516#endif
3517 continue;
3518 }
3520 // sibling link (XXX: could also be partial occupator where this check fails)
3521 &leader->getLane()->getEdge() == &lane->getEdge()) {
3522 // check for sublane obstruction (trivial for sibling link leaders)
3523 const MSLane* conflictLane = link->getInternalLaneBefore();
3524 MSLeaderInfo linkLeadersAhead = MSLeaderInfo(conflictLane->getWidth());
3525 linkLeadersAhead.addLeader(leader, false, 0); // assume sibling lane has the same geometry as the leader lane
3526 const double latOffset = isShadowLink ? (getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge()) : 0;
3527 // leader is neither on lane nor conflictLane (the conflict is only established geometrically)
3528 adaptToLeaders(linkLeadersAhead, latOffset, seen, lastLink, leader->getLane(), v, vLinkPass);
3529#ifdef DEBUG_PLAN_MOVE
3530 if (DEBUG_COND) {
3531 std::cout << SIMTIME << " veh=" << getID()
3532 << " siblingFoe link=" << link->getViaLaneOrLane()->getID()
3533 << " isShadowLink=" << isShadowLink
3534 << " lane=" << lane->getID()
3535 << " foe=" << leader->getID()
3536 << " foeLane=" << leader->getLane()->getID()
3537 << " latOffset=" << latOffset
3538 << " latOffsetFoe=" << leader->getLatOffset(lane)
3539 << " linkLeadersAhead=" << linkLeadersAhead.toString()
3540 << "\n";
3541 }
3542#endif
3543 } else {
3544#ifdef DEBUG_PLAN_MOVE
3545 if (DEBUG_COND) {
3546 std::cout << SIMTIME << " veh=" << getID() << " linkLeader=" << leader->getID() << " gap=" << it->vehAndGap.second
3547 << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
3548 << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
3549 << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
3550 << "\n";
3551 }
3552#endif
3553 adaptToJunctionLeader(it->vehAndGap, seen, lastLink, lane, v, vLinkPass, it->distToCrossing);
3554 }
3555 if (lastLink != nullptr) {
3556 // we are not yet on the junction with this linkLeader.
3557 // at least we can drive up to the previous link and stop there
3558 v = MAX2(v, lastLink->myVLinkWait);
3559 }
3560 // if blocked by a leader from the same or next lane we must yield our request
3561 // also, if blocked by a stopped or blocked leader
3563 //&& leader->getSpeed() < SUMO_const_haltingSpeed
3565 || leader->getLane()->getLogicalPredecessorLane() == myLane
3566 || leader->isStopped()
3568 setRequest = false;
3569#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3570 if (DEBUG_COND) {
3571 std::cout << " aborting request\n";
3572 }
3573#endif
3574 if (lastLink != nullptr && leader->getLane()->getLogicalPredecessorLane() == myLane) {
3575 // we are not yet on the junction so must abort that request as well
3576 // (or maybe we are already on the junction and the leader is a partial occupator beyond)
3577 lastLink->mySetRequest = false;
3578#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3579 if (DEBUG_COND) {
3580 std::cout << " aborting previous request\n";
3581 }
3582#endif
3583 }
3584 }
3585 }
3586#ifdef DEBUG_PLAN_MOVE_LEADERINFO
3587 else {
3588 if (DEBUG_COND) {
3589 std::cout << SIMTIME << " veh=" << getID() << " ignoring leader " << leader->getID() << " gap=" << (*it).vehAndGap.second << " dtC=" << (*it).distToCrossing
3590 << " ET=" << myJunctionEntryTime << " lET=" << leader->myJunctionEntryTime
3591 << " ETN=" << myJunctionEntryTimeNeverYield << " lETN=" << leader->myJunctionEntryTimeNeverYield
3592 << " CET=" << myJunctionConflictEntryTime << " lCET=" << leader->myJunctionConflictEntryTime
3593 << "\n";
3594 }
3595 }
3596#endif
3597 }
3598 // if this is the link between two internal lanes we may have to slow down for pedestrians
3599 vLinkWait = MIN2(vLinkWait, v);
3600}
3601
3602
3603double
3604MSVehicle::getDeltaPos(const double accel) const {
3605 double vNext = myState.mySpeed + ACCEL2SPEED(accel);
3607 // apply implicit Euler positional update
3608 return SPEED2DIST(MAX2(vNext, 0.));
3609 } else {
3610 // apply ballistic update
3611 if (vNext >= 0) {
3612 // assume constant acceleration during this time step
3613 return SPEED2DIST(myState.mySpeed + 0.5 * ACCEL2SPEED(accel));
3614 } else {
3615 // negative vNext indicates a stop within the middle of time step
3616 // The corresponding stop time is s = mySpeed/deceleration \in [0,dt], and the
3617 // covered distance is therefore deltaPos = mySpeed*s - 0.5*deceleration*s^2.
3618 // Here, deceleration = (myState.mySpeed - vNext)/dt is the constant deceleration
3619 // until the vehicle stops.
3620 return -SPEED2DIST(0.5 * myState.mySpeed * myState.mySpeed / ACCEL2SPEED(accel));
3621 }
3622 }
3623}
3624
3625void
3626MSVehicle::processLinkApproaches(double& vSafe, double& vSafeMin, double& vSafeMinDist) {
3627
3628 // Speed limit due to zipper merging
3629 double vSafeZipper = std::numeric_limits<double>::max();
3630
3631 myHaveToWaitOnNextLink = false;
3632 bool canBrakeVSafeMin = false;
3633
3634 // Get safe velocities from DriveProcessItems.
3635 assert(myLFLinkLanes.size() != 0 || isRemoteControlled());
3636 for (const DriveProcessItem& dpi : myLFLinkLanes) {
3637 MSLink* const link = dpi.myLink;
3638
3639#ifdef DEBUG_EXEC_MOVE
3640 if (DEBUG_COND) {
3641 std::cout
3642 << SIMTIME
3643 << " veh=" << getID()
3644 << " link=" << (link == 0 ? "NULL" : link->getViaLaneOrLane()->getID())
3645 << " req=" << dpi.mySetRequest
3646 << " vP=" << dpi.myVLinkPass
3647 << " vW=" << dpi.myVLinkWait
3648 << " d=" << dpi.myDistance
3649 << "\n";
3650 gDebugFlag1 = true; // See MSLink_DEBUG_OPENED
3651 }
3652#endif
3653
3654 // the vehicle must change the lane on one of the next lanes (XXX: refs to code further below???, Leo)
3655 if (link != nullptr && dpi.mySetRequest) {
3656
3657 const LinkState ls = link->getState();
3658 // vehicles should brake when running onto a yellow light if the distance allows to halt in front
3659 const bool yellow = link->haveYellow();
3660 const bool canBrake = (dpi.myDistance > getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.)
3662 assert(link->getLaneBefore() != nullptr);
3663 const bool beyondStopLine = dpi.myDistance < link->getLaneBefore()->getVehicleStopOffset(this);
3664 const bool ignoreRedLink = ignoreRed(link, canBrake) || beyondStopLine;
3665 if (yellow && canBrake && !ignoreRedLink) {
3666 vSafe = dpi.myVLinkWait;
3668#ifdef DEBUG_CHECKREWINDLINKLANES
3669 if (DEBUG_COND) {
3670 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (yellow)\n";
3671 }
3672#endif
3673 break;
3674 }
3675 const bool influencerPrio = (myInfluencer != nullptr && !myInfluencer->getRespectJunctionPriority());
3676 MSLink::BlockingFoes collectFoes;
3677 bool opened = (yellow || influencerPrio
3678 || link->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
3680 canBrake ? getImpatience() : 1,
3683 ls == LINKSTATE_ZIPPER ? &collectFoes : nullptr,
3684 ignoreRedLink, this, dpi.myDistance));
3685 if (opened && myLaneChangeModel->getShadowLane() != nullptr) {
3686 const MSLink* const parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
3687 if (parallelLink != nullptr) {
3688 const double shadowLatPos = getLateralPositionOnLane() - myLaneChangeModel->getShadowDirection() * 0.5 * (
3690 opened = yellow || influencerPrio || (opened && parallelLink->opened(dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
3693 getWaitingTimeFor(link), shadowLatPos, nullptr,
3694 ignoreRedLink, this, dpi.myDistance));
3695#ifdef DEBUG_EXEC_MOVE
3696 if (DEBUG_COND) {
3697 std::cout << SIMTIME
3698 << " veh=" << getID()
3699 << " shadowLane=" << myLaneChangeModel->getShadowLane()->getID()
3700 << " shadowDir=" << myLaneChangeModel->getShadowDirection()
3701 << " parallelLink=" << (parallelLink == 0 ? "NULL" : parallelLink->getViaLaneOrLane()->getID())
3702 << " opened=" << opened
3703 << "\n";
3704 }
3705#endif
3706 }
3707 }
3708 // vehicles should decelerate when approaching a minor link
3709#ifdef DEBUG_EXEC_MOVE
3710 if (DEBUG_COND) {
3711 std::cout << SIMTIME
3712 << " opened=" << opened
3713 << " influencerPrio=" << influencerPrio
3714 << " linkPrio=" << link->havePriority()
3715 << " lastContMajor=" << link->lastWasContMajor()
3716 << " isCont=" << link->isCont()
3717 << " ignoreRed=" << ignoreRedLink
3718 << "\n";
3719 }
3720#endif
3721 double visibilityDistance = link->getFoeVisibilityDistance();
3722 bool determinedFoePresence = dpi.myDistance <= visibilityDistance;
3723 if (opened && !influencerPrio && !link->havePriority() && !link->lastWasContMajor() && !link->isCont() && !ignoreRedLink) {
3724 if (!determinedFoePresence && (canBrake || !yellow)) {
3725 vSafe = dpi.myVLinkWait;
3727#ifdef DEBUG_CHECKREWINDLINKLANES
3728 if (DEBUG_COND) {
3729 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (minor)\n";
3730 }
3731#endif
3732 break;
3733 } else {
3734 // past the point of no return. we need to drive fast enough
3735 // to make it across the link. However, minor slowdowns
3736 // should be permissible to follow leading traffic safely
3737 // basically, this code prevents dawdling
3738 // (it's harder to do this later using
3739 // SUMO_ATTR_JM_SIGMA_MINOR because we don't know whether the
3740 // vehicle is already too close to stop at that part of the code)
3741 //
3742 // XXX: There is a problem in subsecond simulation: If we cannot
3743 // make it across the minor link in one step, new traffic
3744 // could appear on a major foe link and cause a collision. Refs. #1845, #2123
3745 vSafeMinDist = dpi.myDistance; // distance that must be covered
3747 vSafeMin = MIN3((double)DIST2SPEED(vSafeMinDist + POSITION_EPS), dpi.myVLinkPass, getCarFollowModel().maxNextSafeMin(getSpeed(), this));
3748 } else {
3749 vSafeMin = MIN3((double)DIST2SPEED(2 * vSafeMinDist + NUMERICAL_EPS) - getSpeed(), dpi.myVLinkPass, getCarFollowModel().maxNextSafeMin(getSpeed(), this));
3750 }
3751 canBrakeVSafeMin = canBrake;
3752#ifdef DEBUG_EXEC_MOVE
3753 if (DEBUG_COND) {
3754 std::cout << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << " canBrake=" << canBrake << "\n";
3755 }
3756#endif
3757 }
3758 }
3759 // have waited; may pass if opened...
3760 if (opened) {
3761 vSafe = dpi.myVLinkPass;
3762 if (vSafe < getCarFollowModel().getMaxDecel() && vSafe <= dpi.myVLinkWait && vSafe < getCarFollowModel().maxNextSpeed(getSpeed(), this)) {
3763 // this vehicle is probably not gonna drive across the next junction (heuristic)
3765#ifdef DEBUG_CHECKREWINDLINKLANES
3766 if (DEBUG_COND) {
3767 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (very slow)\n";
3768 }
3769#endif
3770 }
3771 if (link->mustStop() && determinedFoePresence && myHaveStoppedFor == nullptr) {
3772 myHaveStoppedFor = link;
3773 }
3774 } else if (link->getState() == LINKSTATE_ZIPPER) {
3775 vSafeZipper = MIN2(vSafeZipper,
3776 link->getZipperSpeed(this, dpi.myDistance, dpi.myVLinkPass, dpi.myArrivalTime, &collectFoes));
3777 } else if (!canBrake
3778 // always brake hard for traffic lights (since an emergency stop is necessary anyway)
3779 && link->getTLLogic() == nullptr
3780 // cannot brake even with emergency deceleration
3781 && dpi.myDistance < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0.)) {
3782#ifdef DEBUG_EXEC_MOVE
3783 if (DEBUG_COND) {
3784 std::cout << SIMTIME << " too fast to brake for closed link\n";
3785 }
3786#endif
3787 vSafe = dpi.myVLinkPass;
3788 } else {
3789 vSafe = dpi.myVLinkWait;
3791#ifdef DEBUG_CHECKREWINDLINKLANES
3792 if (DEBUG_COND) {
3793 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (closed)\n";
3794 }
3795#endif
3796#ifdef DEBUG_EXEC_MOVE
3797 if (DEBUG_COND) {
3798 std::cout << SIMTIME << " braking for closed link=" << link->getViaLaneOrLane()->getID() << "\n";
3799 }
3800#endif
3801 break;
3802 }
3803 } else {
3804 if (link != nullptr && link->getInternalLaneBefore() != nullptr && myLane->isInternal() && link->getJunction() == myLane->getEdge().getToJunction()) {
3805 // blocked on the junction. yield request so other vehicles may
3806 // become junction leader
3807#ifdef DEBUG_EXEC_MOVE
3808 if (DEBUG_COND) {
3809 std::cout << SIMTIME << " resetting junctionEntryTime at junction '" << link->getJunction()->getID() << "' beause of non-request exitLink\n";
3810 }
3811#endif
3814 }
3815 // we have: i->link == 0 || !i->setRequest
3816 vSafe = dpi.myVLinkWait;
3817 if (vSafe < getSpeed()) {
3819#ifdef DEBUG_CHECKREWINDLINKLANES
3820 if (DEBUG_COND) {
3821 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, braking) vSafe=" << vSafe << "\n";
3822 }
3823#endif
3824 } else if (vSafe < SUMO_const_haltingSpeed) {
3826#ifdef DEBUG_CHECKREWINDLINKLANES
3827 if (DEBUG_COND) {
3828 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (no request, stopping)\n";
3829 }
3830#endif
3831 }
3832 if (link == nullptr && myLFLinkLanes.size() == 1
3833 && getBestLanesContinuation().size() > 1
3834 && getBestLanesContinuation()[1]->hadPermissionChanges()
3835 && myLane->getFirstAnyVehicle() == this) {
3836 // temporal lane closing without notification, visible to the
3837 // vehicle at the front of the queue
3838 updateBestLanes(true);
3839 //std::cout << SIMTIME << " veh=" << getID() << " updated bestLanes=" << toString(getBestLanesContinuation()) << "\n";
3840 }
3841 break;
3842 }
3843 }
3844
3845//#ifdef DEBUG_EXEC_MOVE
3846// if (DEBUG_COND) {
3847// std::cout << "\nvCurrent = " << toString(getSpeed(), 24) << "" << std::endl;
3848// std::cout << "vSafe = " << toString(vSafe, 24) << "" << std::endl;
3849// std::cout << "vSafeMin = " << toString(vSafeMin, 24) << "" << std::endl;
3850// std::cout << "vSafeMinDist = " << toString(vSafeMinDist, 24) << "" << std::endl;
3851//
3852// double gap = getLeader().second;
3853// std::cout << "gap = " << toString(gap, 24) << std::endl;
3854// std::cout << "vSafeStoppedLeader = " << toString(getCarFollowModel().stopSpeed(this, getSpeed(), gap, MSCFModel::CalcReason::FUTURE), 24)
3855// << "\n" << std::endl;
3856// }
3857//#endif
3858
3859 if ((MSGlobals::gSemiImplicitEulerUpdate && vSafe + NUMERICAL_EPS < vSafeMin)
3860 || (!MSGlobals::gSemiImplicitEulerUpdate && (vSafe + NUMERICAL_EPS < vSafeMin && vSafeMin != 0))) { // this might be good for the euler case as well
3861 // XXX: (Leo) This often called stopSpeed with vSafeMinDist==0 (for the ballistic update), since vSafe can become negative
3862 // For the Euler update the term '+ NUMERICAL_EPS' prevented a call here... Recheck, consider of -INVALID_SPEED instead of 0 to indicate absence of vSafeMin restrictions. Refs. #2577
3863#ifdef DEBUG_EXEC_MOVE
3864 if (DEBUG_COND) {
3865 std::cout << "vSafeMin Problem? vSafe=" << vSafe << " vSafeMin=" << vSafeMin << " vSafeMinDist=" << vSafeMinDist << std::endl;
3866 }
3867#endif
3868 if (canBrakeVSafeMin && vSafe < getSpeed()) {
3869 // cannot drive across a link so we need to stop before it
3870 vSafe = MIN2(vSafe, MAX2(getCarFollowModel().minNextSpeed(getSpeed(), this),
3871 getCarFollowModel().stopSpeed(this, getSpeed(), vSafeMinDist)));
3872 vSafeMin = 0;
3874#ifdef DEBUG_CHECKREWINDLINKLANES
3875 if (DEBUG_COND) {
3876 std::cout << SIMTIME << " veh=" << getID() << " haveToWait (vSafe=" << vSafe << " < vSafeMin=" << vSafeMin << ")\n";
3877 }
3878#endif
3879 } else {
3880 // if the link is yellow or visibility distance is large
3881 // then we might not make it across the link in one step anyway..
3882 // Possibly, the lane after the intersection has a lower speed limit so
3883 // we really need to drive slower already
3884 // -> keep driving without dawdling
3885 vSafeMin = vSafe;
3886 }
3887 }
3888
3889 // vehicles inside a roundabout should maintain their requests
3890 if (myLane->getEdge().isRoundabout()) {
3891 myHaveToWaitOnNextLink = false;
3892 }
3893
3894 vSafe = MIN2(vSafe, vSafeZipper);
3895}
3896
3897
3898double
3899MSVehicle::processTraCISpeedControl(double vSafe, double vNext) {
3900 if (myInfluencer != nullptr) {
3902#ifdef DEBUG_TRACI
3903 if DEBUG_COND2(this) {
3904 std::cout << SIMTIME << " MSVehicle::processTraCISpeedControl() for vehicle '" << getID() << "'"
3905 << " vSafe=" << vSafe << " (init)vNext=" << vNext << " keepStopping=" << keepStopping();
3906 }
3907#endif
3910 }
3911 const double vMax = getVehicleType().getCarFollowModel().maxNextSpeed(myState.mySpeed, this);
3914 vMin = MAX2(0., vMin);
3915 }
3916 vNext = myInfluencer->influenceSpeed(MSNet::getInstance()->getCurrentTimeStep(), vNext, vSafe, vMin, vMax);
3917 if (keepStopping() && myStops.front().getSpeed() == 0) {
3918 // avoid driving while stopped (unless it's actually a waypoint
3919 vNext = myInfluencer->getOriginalSpeed();
3920 }
3921#ifdef DEBUG_TRACI
3922 if DEBUG_COND2(this) {
3923 std::cout << " (processed)vNext=" << vNext << std::endl;
3924 }
3925#endif
3926 }
3927 return vNext;
3928}
3929
3930
3931void
3933#ifdef DEBUG_ACTIONSTEPS
3934 if (DEBUG_COND) {
3935 std::cout << SIMTIME << " veh=" << getID() << " removePassedDriveItems()\n"
3936 << " Current items: ";
3937 for (auto& j : myLFLinkLanes) {
3938 if (j.myLink == 0) {
3939 std::cout << "\n Stop at distance " << j.myDistance;
3940 } else {
3941 const MSLane* to = j.myLink->getViaLaneOrLane();
3942 const MSLane* from = j.myLink->getLaneBefore();
3943 std::cout << "\n Link at distance " << j.myDistance << ": '"
3944 << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
3945 }
3946 }
3947 std::cout << "\n myNextDriveItem: ";
3948 if (myLFLinkLanes.size() != 0) {
3949 if (myNextDriveItem->myLink == 0) {
3950 std::cout << "\n Stop at distance " << myNextDriveItem->myDistance;
3951 } else {
3952 const MSLane* to = myNextDriveItem->myLink->getViaLaneOrLane();
3953 const MSLane* from = myNextDriveItem->myLink->getLaneBefore();
3954 std::cout << "\n Link at distance " << myNextDriveItem->myDistance << ": '"
3955 << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
3956 }
3957 }
3958 std::cout << std::endl;
3959 }
3960#endif
3961 for (auto j = myLFLinkLanes.begin(); j != myNextDriveItem; ++j) {
3962#ifdef DEBUG_ACTIONSTEPS
3963 if (DEBUG_COND) {
3964 std::cout << " Removing item: ";
3965 if (j->myLink == 0) {
3966 std::cout << "Stop at distance " << j->myDistance;
3967 } else {
3968 const MSLane* to = j->myLink->getViaLaneOrLane();
3969 const MSLane* from = j->myLink->getLaneBefore();
3970 std::cout << "Link at distance " << j->myDistance << ": '"
3971 << (from == 0 ? "NONE" : from->getID()) << "' -> '" << (to == 0 ? "NONE" : to->getID()) << "'";
3972 }
3973 std::cout << std::endl;
3974 }
3975#endif
3976 if (j->myLink != nullptr) {
3977 j->myLink->removeApproaching(this);
3978 }
3979 }
3982}
3983
3984
3985void
3987#ifdef DEBUG_ACTIONSTEPS
3988 if (DEBUG_COND) {
3989 std::cout << SIMTIME << " updateDriveItems(), veh='" << getID() << "' (lane: '" << getLane()->getID() << "')\nCurrent drive items:" << std::endl;
3990 for (const auto& dpi : myLFLinkLanes) {
3991 std::cout
3992 << " vPass=" << dpi.myVLinkPass
3993 << " vWait=" << dpi.myVLinkWait
3994 << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
3995 << " request=" << dpi.mySetRequest
3996 << "\n";
3997 }
3998 std::cout << " myNextDriveItem's linked lane: " << (myNextDriveItem->myLink == 0 ? "NULL" : myNextDriveItem->myLink->getViaLaneOrLane()->getID()) << std::endl;
3999 }
4000#endif
4001 if (myLFLinkLanes.size() == 0) {
4002 // nothing to update
4003 return;
4004 }
4005 const MSLink* nextPlannedLink = nullptr;
4006// auto i = myLFLinkLanes.begin();
4007 auto i = myNextDriveItem;
4008 while (i != myLFLinkLanes.end() && nextPlannedLink == nullptr) {
4009 nextPlannedLink = i->myLink;
4010 ++i;
4011 }
4012
4013 if (nextPlannedLink == nullptr) {
4014 // No link for upcoming item -> no need for an update
4015#ifdef DEBUG_ACTIONSTEPS
4016 if (DEBUG_COND) {
4017 std::cout << "Found no link-related drive item." << std::endl;
4018 }
4019#endif
4020 return;
4021 }
4022
4023 if (getLane() == nextPlannedLink->getLaneBefore()) {
4024 // Current lane approaches the stored next link, i.e. no LC happend and no update is required.
4025#ifdef DEBUG_ACTIONSTEPS
4026 if (DEBUG_COND) {
4027 std::cout << "Continuing on planned lane sequence, no update required." << std::endl;
4028 }
4029#endif
4030 return;
4031 }
4032 // Lane must have been changed, determine the change direction
4033 const MSLink* parallelLink = nextPlannedLink->getParallelLink(1);
4034 if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
4035 // lcDir = 1;
4036 } else {
4037 parallelLink = nextPlannedLink->getParallelLink(-1);
4038 if (parallelLink != nullptr && parallelLink->getLaneBefore() == getLane()) {
4039 // lcDir = -1;
4040 } else {
4041 // If the vehicle's current lane is not the approaching lane for the next
4042 // drive process item's link, it is expected to lead to a parallel link,
4043 // XXX: What if the lc was an overtaking maneuver and there is no upcoming link?
4044 // Then a stop item should be scheduled! -> TODO!
4045 //assert(false);
4046 return;
4047 }
4048 }
4049#ifdef DEBUG_ACTIONSTEPS
4050 if (DEBUG_COND) {
4051 std::cout << "Changed lane. Drive items will be updated along the current lane continuation." << std::endl;
4052 }
4053#endif
4054 // Trace link sequence along current best lanes and transfer drive items to the corresponding links
4055// DriveItemVector::iterator driveItemIt = myLFLinkLanes.begin();
4056 DriveItemVector::iterator driveItemIt = myNextDriveItem;
4057 // In the loop below, lane holds the currently considered lane on the vehicles continuation (including internal lanes)
4058 const MSLane* lane = myLane;
4059 assert(myLane == parallelLink->getLaneBefore());
4060 // *lit is a pointer to the next lane in best continuations for the current lane (always non-internal)
4061 std::vector<MSLane*>::const_iterator bestLaneIt = getBestLanesContinuation().begin() + 1;
4062 // Pointer to the new link for the current drive process item
4063 MSLink* newLink = nullptr;
4064 while (driveItemIt != myLFLinkLanes.end()) {
4065 if (driveItemIt->myLink == nullptr) {
4066 // Items not related to a specific link are not updated
4067 // (XXX: when a stop item corresponded to a dead end, which is overcome by the LC that made
4068 // the update necessary, this may slow down the vehicle's continuation on the new lane...)
4069 ++driveItemIt;
4070 continue;
4071 }
4072 // Continuation links for current best lanes are less than for the former drive items (myLFLinkLanes)
4073 // We just remove the leftover link-items, as they cannot be mapped to new links.
4074 if (bestLaneIt == getBestLanesContinuation().end()) {
4075#ifdef DEBUG_ACTIONSTEPS
4076 if (DEBUG_COND) {
4077 std::cout << "Reached end of the new continuation sequence. Erasing leftover link-items." << std::endl;
4078 }
4079#endif
4080 while (driveItemIt != myLFLinkLanes.end()) {
4081 if (driveItemIt->myLink == nullptr) {
4082 ++driveItemIt;
4083 continue;
4084 } else {
4085 driveItemIt->myLink->removeApproaching(this);
4086 driveItemIt = myLFLinkLanes.erase(driveItemIt);
4087 }
4088 }
4089 break;
4090 }
4091 // Do the actual link-remapping for the item. And un/register approaching information on the corresponding links
4092 const MSLane* const target = *bestLaneIt;
4093 assert(!target->isInternal());
4094 newLink = nullptr;
4095 for (MSLink* const link : lane->getLinkCont()) {
4096 if (link->getLane() == target) {
4097 newLink = link;
4098 break;
4099 }
4100 }
4101
4102 if (newLink == driveItemIt->myLink) {
4103 // new continuation merged into previous - stop update
4104#ifdef DEBUG_ACTIONSTEPS
4105 if (DEBUG_COND) {
4106 std::cout << "Old and new continuation sequences merge at link\n"
4107 << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'"
4108 << "\nNo update beyond merge required." << std::endl;
4109 }
4110#endif
4111 break;
4112 }
4113
4114#ifdef DEBUG_ACTIONSTEPS
4115 if (DEBUG_COND) {
4116 std::cout << "lane=" << lane->getID() << "\nUpdating link\n '" << driveItemIt->myLink->getLaneBefore()->getID() << "'->'" << driveItemIt->myLink->getViaLaneOrLane()->getID() << "'"
4117 << "==> " << "'" << newLink->getLaneBefore()->getID() << "'->'" << newLink->getViaLaneOrLane()->getID() << "'" << std::endl;
4118 }
4119#endif
4120 newLink->setApproaching(this, driveItemIt->myLink->getApproaching(this));
4121 driveItemIt->myLink->removeApproaching(this);
4122 driveItemIt->myLink = newLink;
4123 lane = newLink->getViaLaneOrLane();
4124 ++driveItemIt;
4125 if (!lane->isInternal()) {
4126 ++bestLaneIt;
4127 }
4128 }
4129#ifdef DEBUG_ACTIONSTEPS
4130 if (DEBUG_COND) {
4131 std::cout << "Updated drive items:" << std::endl;
4132 for (const auto& dpi : myLFLinkLanes) {
4133 std::cout
4134 << " vPass=" << dpi.myVLinkPass
4135 << " vWait=" << dpi.myVLinkWait
4136 << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
4137 << " request=" << dpi.mySetRequest
4138 << "\n";
4139 }
4140 }
4141#endif
4142}
4143
4144
4145void
4147 // To avoid casual blinking brake lights at high speeds due to dawdling of the
4148 // leading vehicle, we don't show brake lights when the deceleration could be caused
4149 // by frictional forces and air resistance (i.e. proportional to v^2, coefficient could be adapted further)
4150 double pseudoFriction = (0.05 + 0.005 * getSpeed()) * getSpeed();
4151 bool brakelightsOn = vNext < getSpeed() - ACCEL2SPEED(pseudoFriction);
4152
4153 if (vNext <= SUMO_const_haltingSpeed) {
4154 brakelightsOn = true;
4155 }
4156 if (brakelightsOn && !isStopped()) {
4158 } else {
4160 }
4161}
4162
4163
4164void
4169 } else {
4170 myWaitingTime = 0;
4172 if (hasInfluencer()) {
4174 }
4175 }
4176}
4177
4178
4179void
4181 // update time loss (depends on the updated edge)
4182 if (!isStopped()) {
4183 const double vmax = myLane->getVehicleMaxSpeed(this);
4184 if (vmax > 0) {
4185 myTimeLoss += TS * (vmax - vNext) / vmax;
4186 }
4187 }
4188}
4189
4190
4191double
4192MSVehicle::checkReversal(bool& canReverse, double speedThreshold, double seen) const {
4193 const bool stopOk = (myStops.empty() || myStops.front().edge != myCurrEdge
4194 || (myStops.front().getSpeed() > 0 && myState.myPos > myStops.front().pars.endPos - 2 * POSITION_EPS));
4195#ifdef DEBUG_REVERSE_BIDI
4196 if (DEBUG_COND) std::cout << SIMTIME << " checkReversal lane=" << myLane->getID()
4197 << " pos=" << myState.myPos
4198 << " speed=" << std::setprecision(6) << getPreviousSpeed() << std::setprecision(gPrecision)
4199 << " speedThreshold=" << speedThreshold
4200 << " seen=" << seen
4201 << " isRail=" << isRail()
4202 << " speedOk=" << (getPreviousSpeed() <= speedThreshold)
4203 << " posOK=" << (myState.myPos <= myLane->getLength())
4204 << " normal=" << !myLane->isInternal()
4205 << " routeOK=" << ((myCurrEdge + 1) != myRoute->end())
4206 << " bidi=" << (myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1))
4207 << " stopOk=" << stopOk
4208 << "\n";
4209#endif
4210 if ((getVClass() & SVC_RAIL_CLASSES) != 0
4211 && getPreviousSpeed() <= speedThreshold
4212 && myState.myPos <= myLane->getLength()
4213 && !myLane->isInternal()
4214 && (myCurrEdge + 1) != myRoute->end()
4215 && myLane->getEdge().getBidiEdge() == *(myCurrEdge + 1)
4216 // ensure there are no further stops on this edge
4217 && stopOk
4218 ) {
4219 //if (isSelected()) std::cout << " check1 passed\n";
4220
4221 // ensure that the vehicle is fully on bidi edges that allow reversal
4222 const int neededFutureRoute = 1 + (int)(MSGlobals::gUsingInternalLanes
4223 ? myFurtherLanes.size()
4224 : ceil((double)myFurtherLanes.size() / 2.0));
4225 const int remainingRoute = int(myRoute->end() - myCurrEdge) - 1;
4226 if (remainingRoute < neededFutureRoute) {
4227#ifdef DEBUG_REVERSE_BIDI
4228 if (DEBUG_COND) {
4229 std::cout << " fail: remainingEdges=" << ((int)(myRoute->end() - myCurrEdge)) << " further=" << myFurtherLanes.size() << "\n";
4230 }
4231#endif
4232 return getMaxSpeed();
4233 }
4234 //if (isSelected()) std::cout << " check2 passed\n";
4235
4236 // ensure that the turn-around connection exists from the current edge to its bidi-edge
4237 const MSEdgeVector& succ = myLane->getEdge().getSuccessors();
4238 if (std::find(succ.begin(), succ.end(), myLane->getEdge().getBidiEdge()) == succ.end()) {
4239#ifdef DEBUG_REVERSE_BIDI
4240 if (DEBUG_COND) {
4241 std::cout << " noTurn (bidi=" << myLane->getEdge().getBidiEdge()->getID() << " succ=" << toString(succ) << "\n";
4242 }
4243#endif
4244 return getMaxSpeed();
4245 }
4246 //if (isSelected()) std::cout << " check3 passed\n";
4247
4248 // ensure that the vehicle front will not move past a stop on the bidi edge of the current edge
4249 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + 1)) {
4250 const double stopPos = myStops.front().getEndPos(*this);
4251 const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
4252 const double newPos = myLane->getLength() - (getBackPositionOnLane() + brakeDist);
4253 if (newPos > stopPos) {
4254#ifdef DEBUG_REVERSE_BIDI
4255 if (DEBUG_COND) {
4256 std::cout << " reversal would go past stop on " << myLane->getBidiLane()->getID() << "\n";
4257 }
4258#endif
4259 if (seen > MAX2(brakeDist, 1.0)) {
4260 return getMaxSpeed();
4261 } else {
4262#ifdef DEBUG_REVERSE_BIDI
4263 if (DEBUG_COND) {
4264 std::cout << " train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
4265 }
4266#endif
4267 }
4268 }
4269 }
4270 //if (isSelected()) std::cout << " check4 passed\n";
4271
4272 // ensure that bidi-edges exist for all further edges
4273 // and that no stops will be skipped when reversing
4274 // and that the train will not be on top of a red rail signal after reversal
4275 const MSLane* bidi = myLane->getBidiLane();
4276 int view = 2;
4277 for (MSLane* further : myFurtherLanes) {
4278 if (!further->getEdge().isInternal()) {
4279 if (further->getEdge().getBidiEdge() != *(myCurrEdge + view)) {
4280#ifdef DEBUG_REVERSE_BIDI
4281 if (DEBUG_COND) {
4282 std::cout << " noBidi view=" << view << " further=" << further->getID() << " furtherBidi=" << Named::getIDSecure(further->getEdge().getBidiEdge()) << " future=" << (*(myCurrEdge + view))->getID() << "\n";
4283 }
4284#endif
4285 return getMaxSpeed();
4286 }
4287 const MSLane* nextBidi = further->getBidiLane();
4288 const MSLink* toNext = bidi->getLinkTo(nextBidi);
4289 if (toNext == nullptr) {
4290 // can only happen if the route is invalid
4291 return getMaxSpeed();
4292 }
4293 if (toNext->haveRed()) {
4294#ifdef DEBUG_REVERSE_BIDI
4295 if (DEBUG_COND) {
4296 std::cout << " do not reverse on a red signal\n";
4297 }
4298#endif
4299 return getMaxSpeed();
4300 }
4301 bidi = nextBidi;
4302 if (!myStops.empty() && myStops.front().edge == (myCurrEdge + view)) {
4303 const double brakeDist = getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0);
4304 const double stopPos = myStops.front().getEndPos(*this);
4305 const double newPos = further->getLength() - (getBackPositionOnLane(further) + brakeDist);
4306 if (newPos > stopPos) {
4307#ifdef DEBUG_REVERSE_BIDI
4308 if (DEBUG_COND) {
4309 std::cout << " reversal would go past stop on further-opposite lane " << further->getBidiLane()->getID() << "\n";
4310 }
4311#endif
4312 if (seen > MAX2(brakeDist, 1.0)) {
4313 canReverse = false;
4314 return getMaxSpeed();
4315 } else {
4316#ifdef DEBUG_REVERSE_BIDI
4317 if (DEBUG_COND) {
4318 std::cout << " train is too long, skipping stop at " << stopPos << " cannot be avoided\n";
4319 }
4320#endif
4321 }
4322 }
4323 }
4324 view++;
4325 }
4326 }
4327 // reverse as soon as comfortably possible
4328 const double vMinComfortable = getCarFollowModel().minNextSpeed(getSpeed(), this);
4329#ifdef DEBUG_REVERSE_BIDI
4330 if (DEBUG_COND) {
4331 std::cout << SIMTIME << " seen=" << seen << " vReverseOK=" << vMinComfortable << "\n";
4332 }
4333#endif
4334 canReverse = true;
4335 return vMinComfortable;
4336 }
4337 return getMaxSpeed();
4338}
4339
4340
4341void
4342MSVehicle::processLaneAdvances(std::vector<MSLane*>& passedLanes, std::string& emergencyReason) {
4343 for (std::vector<MSLane*>::reverse_iterator i = myFurtherLanes.rbegin(); i != myFurtherLanes.rend(); ++i) {
4344 passedLanes.push_back(*i);
4345 }
4346 if (passedLanes.size() == 0 || passedLanes.back() != myLane) {
4347 passedLanes.push_back(myLane);
4348 }
4349 // let trains reverse direction
4350 bool reverseTrain = false;
4351 checkReversal(reverseTrain);
4352 if (reverseTrain) {
4353 // Train is 'reversing' so toggle the logical state
4355 // add some slack to ensure that the back of train does appear looped
4356 myState.myPos += 2 * (myLane->getLength() - myState.myPos) + myType->getLength() + NUMERICAL_EPS;
4357 myState.mySpeed = 0;
4358#ifdef DEBUG_REVERSE_BIDI
4359 if (DEBUG_COND) {
4360 std::cout << SIMTIME << " reversing train=" << getID() << " newPos=" << myState.myPos << "\n";
4361 }
4362#endif
4363 }
4364 // move on lane(s)
4365 if (myState.myPos > myLane->getLength()) {
4366 // The vehicle has moved at least to the next lane (maybe it passed even more than one)
4367 if (myCurrEdge != myRoute->end() - 1) {
4368 MSLane* approachedLane = myLane;
4369 // move the vehicle forward
4371 while (myNextDriveItem != myLFLinkLanes.end() && approachedLane != nullptr && myState.myPos > approachedLane->getLength()) {
4372 const MSLink* link = myNextDriveItem->myLink;
4373 const double linkDist = myNextDriveItem->myDistance;
4375 // check whether the vehicle was allowed to enter lane
4376 // otherwise it is decelerated and we do not need to test for it's
4377 // approach on the following lanes when a lane changing is performed
4378 // proceed to the next lane
4379 if (approachedLane->mustCheckJunctionCollisions()) {
4380 // vehicle moves past approachedLane within a single step, collision checking must still be done
4382 }
4383 if (link != nullptr) {
4384 if ((getVClass() & SVC_RAIL_CLASSES) != 0
4385 && !myLane->isInternal()
4386 && myLane->getBidiLane() != nullptr
4387 && link->getLane()->getBidiLane() == myLane
4388 && !reverseTrain) {
4389 emergencyReason = " because it must reverse direction";
4390 approachedLane = nullptr;
4391 break;
4392 }
4393 if ((getVClass() & SVC_RAIL_CLASSES) != 0
4394 && myState.myPos < myLane->getLength() + NUMERICAL_EPS
4395 && hasStops() && getNextStop().edge == myCurrEdge) {
4396 // avoid skipping stop due to numerical instability
4397 // this is a special case for rail vehicles because they
4398 // continue myLFLinkLanes past stops
4399 approachedLane = myLane;
4401 break;
4402 }
4403 approachedLane = link->getViaLaneOrLane();
4405 bool beyondStopLine = linkDist < link->getLaneBefore()->getVehicleStopOffset(this);
4406 if (link->haveRed() && !ignoreRed(link, false) && !beyondStopLine && !reverseTrain) {
4407 emergencyReason = " because of a red traffic light";
4408 break;
4409 }
4410 }
4411 if (reverseTrain && approachedLane->isInternal()) {
4412 // avoid getting stuck on a slow turn-around internal lane
4413 myState.myPos += approachedLane->getLength();
4414 }
4415 } else if (myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
4416 // avoid warning due to numerical instability
4417 approachedLane = myLane;
4419 } else if (reverseTrain) {
4420 approachedLane = (*(myCurrEdge + 1))->getLanes()[0];
4421 link = myLane->getLinkTo(approachedLane);
4422 assert(link != 0);
4423 while (link->getViaLane() != nullptr) {
4424 link = link->getViaLane()->getLinkCont()[0];
4425 }
4427 } else {
4428 emergencyReason = " because there is no connection to the next edge";
4429 approachedLane = nullptr;
4430 break;
4431 }
4432 if (approachedLane != myLane && approachedLane != nullptr) {
4435 assert(myState.myPos > 0);
4436 enterLaneAtMove(approachedLane);
4437 if (link->isEntryLink()) {
4440 myHaveStoppedFor = nullptr;
4441 }
4442 if (link->isConflictEntryLink()) {
4444 // renew yielded request
4446 }
4447 if (link->isExitLink()) {
4448 // passed junction, reset for approaching the next one
4452 }
4453#ifdef DEBUG_PLAN_MOVE_LEADERINFO
4454 if (DEBUG_COND) {
4455 std::cout << "Update junctionTimes link=" << link->getViaLaneOrLane()->getID()
4456 << " entry=" << link->isEntryLink() << " conflict=" << link->isConflictEntryLink() << " exit=" << link->isExitLink()
4457 << " ET=" << myJunctionEntryTime
4458 << " ETN=" << myJunctionEntryTimeNeverYield
4459 << " CET=" << myJunctionConflictEntryTime
4460 << "\n";
4461 }
4462#endif
4463 if (hasArrivedInternal()) {
4464 break;
4465 }
4468 // abort lane change
4469 WRITE_WARNING("Vehicle '" + getID() + "' could not finish continuous lane change (turn lane) time=" +
4470 time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
4472 }
4473 }
4474 if (approachedLane->getEdge().isVaporizing()) {
4476 break;
4477 }
4478 passedLanes.push_back(approachedLane);
4479 }
4480 }
4481 // NOTE: Passed drive items will be erased in the next simstep's planMove()
4482
4483#ifdef DEBUG_ACTIONSTEPS
4484 if (DEBUG_COND && myNextDriveItem != myLFLinkLanes.begin()) {
4485 std::cout << "Updated drive items:" << std::endl;
4486 for (DriveItemVector::iterator i = myLFLinkLanes.begin(); i != myLFLinkLanes.end(); ++i) {
4487 std::cout
4488 << " vPass=" << (*i).myVLinkPass
4489 << " vWait=" << (*i).myVLinkWait
4490 << " linkLane=" << ((*i).myLink == 0 ? "NULL" : (*i).myLink->getViaLaneOrLane()->getID())
4491 << " request=" << (*i).mySetRequest
4492 << "\n";
4493 }
4494 }
4495#endif
4496 } else if (!hasArrivedInternal() && myState.myPos < myLane->getLength() + NUMERICAL_EPS) {
4497 // avoid warning due to numerical instability when stopping at the end of the route
4499 }
4500
4501 }
4502}
4503
4504
4505
4506bool
4508#ifdef DEBUG_EXEC_MOVE
4509 if (DEBUG_COND) {
4510 std::cout << "\nEXECUTE_MOVE\n"
4511 << SIMTIME
4512 << " veh=" << getID()
4513 << " speed=" << getSpeed() // toString(getSpeed(), 24)
4514 << std::endl;
4515 }
4516#endif
4517
4518
4519 // Maximum safe velocity
4520 double vSafe = std::numeric_limits<double>::max();
4521 // Minimum safe velocity (lower bound).
4522 double vSafeMin = -std::numeric_limits<double>::max();
4523 // The distance to a link, which should either be crossed this step
4524 // or in front of which we need to stop.
4525 double vSafeMinDist = 0;
4526
4527 if (myActionStep) {
4528 // Actuate control (i.e. choose bounds for safe speed in current simstep (euler), resp. after current sim step (ballistic))
4529 processLinkApproaches(vSafe, vSafeMin, vSafeMinDist);
4530#ifdef DEBUG_ACTIONSTEPS
4531 if (DEBUG_COND) {
4532 std::cout << SIMTIME << " vehicle '" << getID() << "'\n"
4533 " vsafe from processLinkApproaches(): vsafe " << vSafe << std::endl;
4534 }
4535#endif
4536 } else {
4537 // Continue with current acceleration
4538 vSafe = getSpeed() + ACCEL2SPEED(myAcceleration);
4539#ifdef DEBUG_ACTIONSTEPS
4540 if (DEBUG_COND) {
4541 std::cout << SIMTIME << " vehicle '" << getID() << "' skips processLinkApproaches()\n"
4542 " continues with constant accel " << myAcceleration << "...\n"
4543 << "speed: " << getSpeed() << " -> " << vSafe << std::endl;
4544 }
4545#endif
4546 }
4547
4548
4549//#ifdef DEBUG_EXEC_MOVE
4550// if (DEBUG_COND) {
4551// std::cout << "vSafe = " << toString(vSafe,12) << "\n" << std::endl;
4552// }
4553//#endif
4554
4555 // Determine vNext = speed after current sim step (ballistic), resp. in current simstep (euler)
4556 // Call to finalizeSpeed applies speed reduction due to dawdling / lane changing but ensures minimum safe speed
4557 double vNext = vSafe;
4558 const double rawAccel = SPEED2ACCEL(MAX2(vNext, 0.) - myState.mySpeed);
4559 if (vNext <= SUMO_const_haltingSpeed * TS && myWaitingTime > MSGlobals::gStartupWaitThreshold && rawAccel <= accelThresholdForWaiting() && myActionStep) {
4561 } else if (isStopped()) {
4562 // do not apply startupDelay for waypoints
4563 if (getCarFollowModel().startupDelayStopped() && getNextStop().pars.speed <= 0) {
4565 } else {
4566 // do not apply startupDelay but signal that a stop has taken place
4568 }
4569 } else {
4570 // identify potential startup (before other effects reduce the speed again)
4572 }
4573 if (myActionStep) {
4574 vNext = getCarFollowModel().finalizeSpeed(this, vSafe);
4575 if (vNext > 0) {
4576 vNext = MAX2(vNext, vSafeMin);
4577 }
4578 }
4579 // (Leo) to avoid tiny oscillations (< 1e-10) of vNext in a standing vehicle column (observed for ballistic update), we cap off vNext
4580 // (We assure to do this only for vNext<<NUMERICAL_EPS since otherwise this would nullify the workaround for #2995
4581 // (Jakob) We also need to make sure to reach a stop at the start of the next edge
4582 if (fabs(vNext) < NUMERICAL_EPS_SPEED && (myStopDist > POSITION_EPS || (hasStops() && myCurrEdge == getNextStop().edge))) {
4583 vNext = 0.;
4584 }
4585#ifdef DEBUG_EXEC_MOVE
4586 if (DEBUG_COND) {
4587 std::cout << SIMTIME << " finalizeSpeed vSafe=" << vSafe << " vSafeMin=" << (vSafeMin == -std::numeric_limits<double>::max() ? "-Inf" : toString(vSafeMin))
4588 << " vNext=" << vNext << " (i.e. accel=" << SPEED2ACCEL(vNext - getSpeed()) << ")" << std::endl;
4589 }
4590#endif
4591
4592 // vNext may be higher than vSafe without implying a bug:
4593 // - when approaching a green light that suddenly switches to yellow
4594 // - when using unregulated junctions
4595 // - when using tau < step-size
4596 // - when using unsafe car following models
4597 // - when using TraCI and some speedMode / laneChangeMode settings
4598 //if (vNext > vSafe + NUMERICAL_EPS) {
4599 // WRITE_WARNING("vehicle '" + getID() + "' cannot brake hard enough to reach safe speed "
4600 // + toString(vSafe, 4) + ", moving at " + toString(vNext, 4) + " instead. time="
4601 // + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
4602 //}
4603
4605 vNext = MAX2(vNext, 0.);
4606 } else {
4607 // (Leo) Ballistic: negative vNext can be used to indicate a stop within next step.
4608 }
4609
4610 // Check for speed advices from the traci client
4611 vNext = processTraCISpeedControl(vSafe, vNext);
4612
4613 // the acceleration of a vehicle equipped with the elecHybrid device is restricted by the maximal power of the electric drive as well
4614 MSDevice_ElecHybrid* elecHybridOfVehicle = dynamic_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid)));
4615 if (elecHybridOfVehicle != nullptr) {
4616 // this is the consumption given by the car following model-computed acceleration
4617 elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
4618 // but the maximum power of the electric motor may be lower
4619 // it needs to be converted from [W] to [Wh/s] (3600s / 1h) so that TS can be taken into account
4620 double maxPower = getEmissionParameters()->getDoubleOptional(SUMO_ATTR_MAXIMUMPOWER, 100000.) / 3600;
4621 if (elecHybridOfVehicle->getConsum() / TS > maxPower) {
4622 // no, we cannot accelerate that fast, recompute the maximum possible acceleration
4623 double accel = elecHybridOfVehicle->acceleration(*this, maxPower, this->getSpeed());
4624 // and update the speed of the vehicle
4625 vNext = MIN2(vNext, this->getSpeed() + accel * TS);
4626 vNext = MAX2(vNext, 0.);
4627 // and set the vehicle consumption to reflect this
4628 elecHybridOfVehicle->setConsum(elecHybridOfVehicle->consumption(*this, (vNext - this->getSpeed()) / TS, vNext));
4629 }
4630 }
4631
4632 setBrakingSignals(vNext);
4633
4634 // update position and speed
4635 int oldLaneOffset = myLane->getEdge().getNumLanes() - myLane->getIndex();
4636 const MSLane* oldLaneMaybeOpposite = myLane;
4638 // transform to the forward-direction lane, move and then transform back
4641 }
4642 updateState(vNext);
4643 updateWaitingTime(vNext);
4644
4645 // Lanes, which the vehicle touched at some moment of the executed simstep
4646 std::vector<MSLane*> passedLanes;
4647 // remember previous lane (myLane is updated in processLaneAdvances)
4648 const MSLane* oldLane = myLane;
4649 // Reason for a possible emergency stop
4650 std::string emergencyReason;
4651 processLaneAdvances(passedLanes, emergencyReason);
4652
4653 updateTimeLoss(vNext);
4655
4657 if (myState.myPos > myLane->getLength()) {
4658 if (emergencyReason == "") {
4659 emergencyReason = TL(" for unknown reasons");
4660 }
4661 WRITE_WARNINGF(TL("Vehicle '%' performs emergency stop at the end of lane '%'% (decel=%, offset=%), time=%."),
4662 getID(), myLane->getID(), emergencyReason, myAcceleration - myState.mySpeed,
4667 myState.mySpeed = 0;
4668 myAcceleration = 0;
4669 }
4670 const MSLane* oldBackLane = getBackLane();
4672 passedLanes.clear(); // ignore back occupation
4673 }
4674#ifdef DEBUG_ACTIONSTEPS
4675 if (DEBUG_COND) {
4676 std::cout << SIMTIME << " veh '" << getID() << "' updates further lanes." << std::endl;
4677 }
4678#endif
4680 if (passedLanes.size() > 1 && isRail()) {
4681 for (auto pi = passedLanes.rbegin(); pi != passedLanes.rend(); ++pi) {
4682 MSLane* pLane = *pi;
4683 if (pLane != myLane && std::find(myFurtherLanes.begin(), myFurtherLanes.end(), pLane) == myFurtherLanes.end()) {
4685 }
4686 }
4687 }
4688 // bestLanes need to be updated before lane changing starts. NOTE: This call is also a presumption for updateDriveItems()
4690 if (myLane != oldLane || oldBackLane != getBackLane()) {
4691 if (myLaneChangeModel->getShadowLane() != nullptr || getLateralOverlap() > POSITION_EPS) {
4692 // shadow lane must be updated if the front or back lane changed
4693 // either if we already have a shadowLane or if there is lateral overlap
4695 }
4697 // The vehicles target lane must be also be updated if the front or back lane changed
4699 }
4700 }
4701 setBlinkerInformation(); // needs updated bestLanes
4702 //change the blue light only for emergency vehicles SUMOVehicleClass
4704 setEmergencyBlueLight(MSNet::getInstance()->getCurrentTimeStep());
4705 }
4706 // must be done before angle computation
4707 // State needs to be reset for all vehicles before the next call to MSEdgeControl::changeLanes
4708 if (myActionStep) {
4709 // check (#2681): Can this be skipped?
4711 } else {
4713#ifdef DEBUG_ACTIONSTEPS
4714 if (DEBUG_COND) {
4715 std::cout << SIMTIME << " veh '" << getID() << "' skips LCM->prepareStep()." << std::endl;
4716 }
4717#endif
4718 }
4721 }
4722
4723#ifdef DEBUG_EXEC_MOVE
4724 if (DEBUG_COND) {
4725 std::cout << SIMTIME << " executeMove finished veh=" << getID() << " lane=" << myLane->getID() << " myPos=" << getPositionOnLane() << " myPosLat=" << getLateralPositionOnLane() << "\n";
4726 gDebugFlag1 = false; // See MSLink_DEBUG_OPENED
4727 }
4728#endif
4730 // transform back to the opposite-direction lane
4731 MSLane* newOpposite = nullptr;
4732 const MSEdge* newOppositeEdge = myLane->getEdge().getOppositeEdge();
4733 if (newOppositeEdge != nullptr) {
4734 newOpposite = newOppositeEdge->getLanes()[newOppositeEdge->getNumLanes() - MAX2(1, oldLaneOffset)];
4735#ifdef DEBUG_EXEC_MOVE
4736 if (DEBUG_COND) {
4737 std::cout << SIMTIME << " newOppositeEdge=" << newOppositeEdge->getID() << " oldLaneOffset=" << oldLaneOffset << " leftMost=" << newOppositeEdge->getNumLanes() - 1 << " newOpposite=" << Named::getIDSecure(newOpposite) << "\n";
4738 }
4739#endif
4740 }
4741 if (newOpposite == nullptr) {
4743 // unusual overtaking at junctions is ok for emergency vehicles
4744 WRITE_WARNINGF(TL("Unexpected end of opposite lane for vehicle '%' at lane '%', time=%."),
4746 }
4748 if (myState.myPos < getLength()) {
4749 // further lanes is always cleared during opposite driving
4750 MSLane* oldOpposite = oldLane->getOpposite();
4751 if (oldOpposite != nullptr) {
4752 myFurtherLanes.push_back(oldOpposite);
4753 myFurtherLanesPosLat.push_back(0);
4754 // small value since the lane is going in the other direction
4757 } else {
4758 SOFT_ASSERT(false);
4759 }
4760 }
4761 } else {
4763 myLane = newOpposite;
4764 oldLane = oldLaneMaybeOpposite;
4765 //std::cout << SIMTIME << " updated myLane=" << Named::getIDSecure(myLane) << " oldLane=" << oldLane->getID() << "\n";
4768 }
4769 }
4771 // Return whether the vehicle did move to another lane
4772 return myLane != oldLane;
4773}
4774
4775void
4777 myState.myPos += dist;
4780
4781 const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(dist);
4783 for (int i = 0; i < (int)lanes.size(); i++) {
4784 MSLink* link = nullptr;
4785 if (i + 1 < (int)lanes.size()) {
4786 const MSLane* const to = lanes[i + 1];
4787 const bool internal = to->isInternal();
4788 for (MSLink* const l : lanes[i]->getLinkCont()) {
4789 if ((internal && l->getViaLane() == to) || (!internal && l->getLane() == to)) {
4790 link = l;
4791 break;
4792 }
4793 }
4794 }
4795 myLFLinkLanes.emplace_back(link, getSpeed(), getSpeed(), true, t, getSpeed(), 0, 0, dist);
4796 }
4797 // minimum execute move:
4798 std::vector<MSLane*> passedLanes;
4799 // Reason for a possible emergency stop
4800 if (lanes.size() > 1) {
4802 }
4803 std::string emergencyReason;
4804 processLaneAdvances(passedLanes, emergencyReason);
4805#ifdef DEBUG_EXTRAPOLATE_DEPARTPOS
4806 if (DEBUG_COND) {
4807 std::cout << SIMTIME << " veh=" << getID() << " executeFractionalMove dist=" << dist
4808 << " passedLanes=" << toString(passedLanes) << " lanes=" << toString(lanes)
4809 << " finalPos=" << myState.myPos
4810 << " speed=" << getSpeed()
4811 << " myFurtherLanes=" << toString(myFurtherLanes)
4812 << "\n";
4813 }
4814#endif
4816 if (lanes.size() > 1) {
4817 for (std::vector<MSLane*>::iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
4818#ifdef DEBUG_FURTHER
4819 if (DEBUG_COND) {
4820 std::cout << SIMTIME << " leaveLane \n";
4821 }
4822#endif
4823 (*i)->resetPartialOccupation(this);
4824 }
4825 myFurtherLanes.clear();
4826 myFurtherLanesPosLat.clear();
4828 }
4829}
4830
4831
4832void
4833MSVehicle::updateState(double vNext, bool parking) {
4834 // update position and speed
4835 double deltaPos; // positional change
4837 // euler
4838 deltaPos = SPEED2DIST(vNext);
4839 } else {
4840 // ballistic
4841 deltaPos = getDeltaPos(SPEED2ACCEL(vNext - myState.mySpeed));
4842 }
4843
4844 // the *mean* acceleration during the next step (probably most appropriate for emission calculation)
4845 // NOTE: for the ballistic update vNext may be negative, indicating a stop.
4847
4848#ifdef DEBUG_EXEC_MOVE
4849 if (DEBUG_COND) {
4850 std::cout << SIMTIME << " updateState() for veh '" << getID() << "': deltaPos=" << deltaPos
4851 << " pos=" << myState.myPos << " newPos=" << myState.myPos + deltaPos << std::endl;
4852 }
4853#endif
4854 double decelPlus = -myAcceleration - getCarFollowModel().getMaxDecel() - NUMERICAL_EPS;
4855 if (decelPlus > 0) {
4856 const double previousAcceleration = SPEED2ACCEL(myState.mySpeed - myState.myPreviousSpeed);
4857 if (myAcceleration + NUMERICAL_EPS < previousAcceleration) {
4858 // vehicle brakes beyond wished maximum deceleration (only warn at the start of the braking manoeuvre)
4859 decelPlus += 2 * NUMERICAL_EPS;
4860 const double emergencyFraction = decelPlus / MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel());
4861 if (emergencyFraction >= MSGlobals::gEmergencyDecelWarningThreshold) {
4862 WRITE_WARNINGF(TL("Vehicle '%' performs emergency braking on lane '%' with decel=%, wished=%, severity=%, time=%."),
4863 //+ " decelPlus=" + toString(decelPlus)
4864 //+ " prevAccel=" + toString(previousAcceleration)
4865 //+ " reserve=" + toString(MAX2(NUMERICAL_EPS, getCarFollowModel().getEmergencyDecel() - getCarFollowModel().getMaxDecel()))
4866 getID(), myLane->getID(), -myAcceleration, getCarFollowModel().getMaxDecel(), emergencyFraction, time2string(SIMSTEP));
4868 }
4869 }
4870 }
4871
4873 myState.mySpeed = MAX2(vNext, 0.);
4874
4875 if (isRemoteControlled()) {
4876 deltaPos = myInfluencer->implicitDeltaPosRemote(this);
4877 }
4878
4879 myState.myPos += deltaPos;
4880 myState.myLastCoveredDist = deltaPos;
4881 myNextTurn.first -= deltaPos;
4882
4883 if (!parking) {
4885 }
4886}
4887
4888void
4890 updateState(0, true);
4891 // deboard while parked
4892 if (myPersonDevice != nullptr) {
4894 }
4895 if (myContainerDevice != nullptr) {
4897 }
4898 for (MSVehicleDevice* const dev : myDevices) {
4899 dev->notifyParking();
4900 }
4901}
4902
4903
4904void
4910
4911
4912const MSLane*
4914 if (myFurtherLanes.size() > 0) {
4915 return myFurtherLanes.back();
4916 } else {
4917 return myLane;
4918 }
4919}
4920
4921
4922double
4923MSVehicle::updateFurtherLanes(std::vector<MSLane*>& furtherLanes, std::vector<double>& furtherLanesPosLat,
4924 const std::vector<MSLane*>& passedLanes) {
4925#ifdef DEBUG_SETFURTHER
4926 if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID()
4927 << " updateFurtherLanes oldFurther=" << toString(furtherLanes)
4928 << " oldFurtherPosLat=" << toString(furtherLanesPosLat)
4929 << " passed=" << toString(passedLanes)
4930 << "\n";
4931#endif
4932 for (MSLane* further : furtherLanes) {
4933 further->resetPartialOccupation(this);
4934 if (further->getBidiLane() != nullptr
4935 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
4936 further->getBidiLane()->resetPartialOccupation(this);
4937 }
4938 }
4939
4940 std::vector<MSLane*> newFurther;
4941 std::vector<double> newFurtherPosLat;
4942 double backPosOnPreviousLane = myState.myPos - getLength();
4943 bool widthShift = myFurtherLanesPosLat.size() > myFurtherLanes.size();
4944 if (passedLanes.size() > 1) {
4945 // There are candidates for further lanes. (passedLanes[-1] is the current lane, or current shadow lane in context of updateShadowLanes())
4946 std::vector<MSLane*>::const_iterator fi = furtherLanes.begin();
4947 std::vector<double>::const_iterator fpi = furtherLanesPosLat.begin();
4948 for (auto pi = passedLanes.rbegin() + 1; pi != passedLanes.rend() && backPosOnPreviousLane < 0; ++pi) {
4949 // As long as vehicle back reaches into passed lane, add it to the further lanes
4950 MSLane* further = *pi;
4951 newFurther.push_back(further);
4952 backPosOnPreviousLane += further->setPartialOccupation(this);
4953 if (further->getBidiLane() != nullptr
4954 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
4955 further->getBidiLane()->setPartialOccupation(this);
4956 }
4957 if (fi != furtherLanes.end() && further == *fi) {
4958 // Lateral position on this lane is already known. Assume constant and use old value.
4959 newFurtherPosLat.push_back(*fpi);
4960 ++fi;
4961 ++fpi;
4962 } else {
4963 // The lane *pi was not in furtherLanes before.
4964 // If it is downstream, we assume as lateral position the current position
4965 // If it is a new lane upstream (can appear as shadow further in case of LC-maneuvering, e.g.)
4966 // we assign the last known lateral position.
4967 if (newFurtherPosLat.size() == 0) {
4968 if (widthShift) {
4969 newFurtherPosLat.push_back(myFurtherLanesPosLat.back());
4970 } else {
4971 newFurtherPosLat.push_back(myState.myPosLat);
4972 }
4973 } else {
4974 newFurtherPosLat.push_back(newFurtherPosLat.back());
4975 }
4976 }
4977#ifdef DEBUG_SETFURTHER
4978 if (DEBUG_COND) {
4979 std::cout << SIMTIME << " updateFurtherLanes \n"
4980 << " further lane '" << further->getID() << "' backPosOnPreviousLane=" << backPosOnPreviousLane
4981 << std::endl;
4982 }
4983#endif
4984 }
4985 furtherLanes = newFurther;
4986 furtherLanesPosLat = newFurtherPosLat;
4987 } else {
4988 furtherLanes.clear();
4989 furtherLanesPosLat.clear();
4990 }
4991#ifdef DEBUG_SETFURTHER
4992 if (DEBUG_COND) std::cout
4993 << " newFurther=" << toString(furtherLanes)
4994 << " newFurtherPosLat=" << toString(furtherLanesPosLat)
4995 << " newBackPos=" << backPosOnPreviousLane
4996 << "\n";
4997#endif
4998 return backPosOnPreviousLane;
4999}
5000
5001
5002double
5003MSVehicle::getBackPositionOnLane(const MSLane* lane, bool calledByGetPosition) const {
5004#ifdef DEBUG_FURTHER
5005 if (DEBUG_COND) {
5006 std::cout << SIMTIME
5007 << " getBackPositionOnLane veh=" << getID()
5008 << " lane=" << Named::getIDSecure(lane)
5009 << " cbgP=" << calledByGetPosition
5010 << " pos=" << myState.myPos
5011 << " backPos=" << myState.myBackPos
5012 << " myLane=" << myLane->getID()
5013 << " myLaneBidi=" << Named::getIDSecure(myLane->getBidiLane())
5014 << " further=" << toString(myFurtherLanes)
5015 << " furtherPosLat=" << toString(myFurtherLanesPosLat)
5016 << "\n shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
5017 << " shadowFurther=" << toString(myLaneChangeModel->getShadowFurtherLanes())
5018 << " shadowFurtherPosLat=" << toString(myLaneChangeModel->getShadowFurtherLanesPosLat())
5019 << "\n targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
5020 << " furtherTargets=" << toString(myLaneChangeModel->getFurtherTargetLanes())
5021 << std::endl;
5022 }
5023#endif
5024 if (lane == myLane
5025 || lane == myLaneChangeModel->getShadowLane()
5026 || lane == myLaneChangeModel->getTargetLane()) {
5028 if (lane == myLaneChangeModel->getShadowLane()) {
5029 return lane->getLength() - myState.myPos - myType->getLength();
5030 } else {
5031 return myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
5032 }
5033 } else if (&lane->getEdge() != &myLane->getEdge()) {
5034 return lane->getLength() - myState.myPos + (calledByGetPosition ? -1 : 1) * myType->getLength();
5035 } else {
5036 // account for parallel lanes of different lengths in the most conservative manner (i.e. while turning)
5037 return myState.myPos - myType->getLength() + MIN2(0.0, lane->getLength() - myLane->getLength());
5038 }
5039 } else if (lane == myLane->getBidiLane()) {
5040 return lane->getLength() - myState.myPos + myType->getLength() * (calledByGetPosition ? -1 : 1);
5041 } else if (myFurtherLanes.size() > 0 && lane == myFurtherLanes.back()) {
5042 return myState.myBackPos;
5043 } else if ((myLaneChangeModel->getShadowFurtherLanes().size() > 0 && lane == myLaneChangeModel->getShadowFurtherLanes().back())
5044 || (myLaneChangeModel->getFurtherTargetLanes().size() > 0 && lane == myLaneChangeModel->getFurtherTargetLanes().back())) {
5045 assert(myFurtherLanes.size() > 0);
5046 if (lane->getLength() == myFurtherLanes.back()->getLength()) {
5047 return myState.myBackPos;
5048 } else {
5049 // interpolate
5050 //if (DEBUG_COND) {
5051 //if (myFurtherLanes.back()->getLength() != lane->getLength()) {
5052 // std::cout << SIMTIME << " veh=" << getID() << " lane=" << lane->getID() << " further=" << myFurtherLanes.back()->getID()
5053 // << " len=" << lane->getLength() << " fLen=" << myFurtherLanes.back()->getLength()
5054 // << " backPos=" << myState.myBackPos << " result=" << myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength() << "\n";
5055 //}
5056 return myState.myBackPos / myFurtherLanes.back()->getLength() * lane->getLength();
5057 }
5058 } else {
5059 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherLanes=" << toString(myFurtherLanes) << "\n";
5060 double leftLength = myType->getLength() - myState.myPos;
5061
5062 std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin();
5063 while (leftLength > 0 && i != myFurtherLanes.end()) {
5064 leftLength -= (*i)->getLength();
5065 //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
5066 if (*i == lane) {
5067 return -leftLength;
5068 } else if (*i == lane->getBidiLane()) {
5069 return lane->getLength() + leftLength - (calledByGetPosition ? 2 * myType->getLength() : 0);
5070 }
5071 ++i;
5072 }
5073 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
5074 leftLength = myType->getLength() - myState.myPos;
5076 while (leftLength > 0 && i != myLaneChangeModel->getShadowFurtherLanes().end()) {
5077 leftLength -= (*i)->getLength();
5078 //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
5079 if (*i == lane) {
5080 return -leftLength;
5081 }
5082 ++i;
5083 }
5084 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myFurtherTargetLanes=" << toString(myLaneChangeModel->getFurtherTargetLanes()) << "\n";
5085 leftLength = myType->getLength() - myState.myPos;
5086 i = getFurtherLanes().begin();
5087 const std::vector<MSLane*> furtherTargetLanes = myLaneChangeModel->getFurtherTargetLanes();
5088 auto j = furtherTargetLanes.begin();
5089 while (leftLength > 0 && j != furtherTargetLanes.end()) {
5090 leftLength -= (*i)->getLength();
5091 // if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
5092 if (*j == lane) {
5093 return -leftLength;
5094 }
5095 ++i;
5096 ++j;
5097 }
5098 WRITE_WARNING("Request backPos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane)
5099 + "' time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".")
5100 SOFT_ASSERT(false);
5101 return myState.myBackPos;
5102 }
5103}
5104
5105
5106double
5108 return getBackPositionOnLane(lane, true) + myType->getLength();
5109}
5110
5111
5112bool
5114 return lane == myLane || lane == myLaneChangeModel->getShadowLane() || lane == myLane->getBidiLane();
5115}
5116
5117
5118void
5119MSVehicle::checkRewindLinkLanes(const double lengthsInFront, DriveItemVector& lfLinks) const {
5121 double seenSpace = -lengthsInFront;
5122#ifdef DEBUG_CHECKREWINDLINKLANES
5123 if (DEBUG_COND) {
5124 std::cout << "\nCHECK_REWIND_LINKLANES\n" << " veh=" << getID() << " lengthsInFront=" << lengthsInFront << "\n";
5125 };
5126#endif
5127 bool foundStopped = false;
5128 // compute available space until a stopped vehicle is found
5129 // this is the sum of non-interal lane length minus in-between vehicle lengths
5130 for (int i = 0; i < (int)lfLinks.size(); ++i) {
5131 // skip unset links
5132 DriveProcessItem& item = lfLinks[i];
5133#ifdef DEBUG_CHECKREWINDLINKLANES
5134 if (DEBUG_COND) std::cout << SIMTIME
5135 << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5136 << " foundStopped=" << foundStopped;
5137#endif
5138 if (item.myLink == nullptr || foundStopped) {
5139 if (!foundStopped) {
5140 item.availableSpace += seenSpace;
5141 } else {
5142 item.availableSpace = seenSpace;
5143 }
5144#ifdef DEBUG_CHECKREWINDLINKLANES
5145 if (DEBUG_COND) {
5146 std::cout << " avail=" << item.availableSpace << "\n";
5147 }
5148#endif
5149 continue;
5150 }
5151 // get the next lane, determine whether it is an internal lane
5152 const MSLane* approachedLane = item.myLink->getViaLane();
5153 if (approachedLane != nullptr) {
5154 if (keepClear(item.myLink)) {
5155 seenSpace = seenSpace - approachedLane->getBruttoVehLenSum();
5156 if (approachedLane == myLane) {
5157 seenSpace += getVehicleType().getLengthWithGap();
5158 }
5159 } else {
5160 seenSpace = seenSpace + approachedLane->getSpaceTillLastStanding(this, foundStopped);// - approachedLane->getBruttoVehLenSum() + approachedLane->getLength();
5161 }
5162 item.availableSpace = seenSpace;
5163#ifdef DEBUG_CHECKREWINDLINKLANES
5164 if (DEBUG_COND) std::cout
5165 << " approached=" << approachedLane->getID()
5166 << " approachedBrutto=" << approachedLane->getBruttoVehLenSum()
5167 << " avail=" << item.availableSpace
5168 << " seenSpace=" << seenSpace
5169 << " hadStoppedVehicle=" << item.hadStoppedVehicle
5170 << " lengthsInFront=" << lengthsInFront
5171 << "\n";
5172#endif
5173 continue;
5174 }
5175 approachedLane = item.myLink->getLane();
5176 const MSVehicle* last = approachedLane->getLastAnyVehicle();
5177 if (last == nullptr || last == this) {
5178 if (approachedLane->getLength() > getVehicleType().getLength()
5179 || keepClear(item.myLink)) {
5180 seenSpace += approachedLane->getLength();
5181 }
5182 item.availableSpace = seenSpace;
5183#ifdef DEBUG_CHECKREWINDLINKLANES
5184 if (DEBUG_COND) {
5185 std::cout << " last=" << Named::getIDSecure(last) << " laneLength=" << approachedLane->getLength() << " avail=" << item.availableSpace << "\n";
5186 }
5187#endif
5188 } else {
5189 bool foundStopped2 = false;
5190 double spaceTillLastStanding = approachedLane->getSpaceTillLastStanding(this, foundStopped2);
5191 if (approachedLane->getBidiLane() != nullptr) {
5192 const MSVehicle* oncomingVeh = approachedLane->getBidiLane()->getFirstFullVehicle();
5193 if (oncomingVeh) {
5194 const double oncomingGap = approachedLane->getLength() - oncomingVeh->getPositionOnLane();
5195 const double oncomingBGap = oncomingVeh->getBrakeGap(true);
5196 // oncoming movement until ego enters the junction
5197 const double oncomingMove = STEPS2TIME(item.myArrivalTime - SIMSTEP) * oncomingVeh->getSpeed();
5198 const double spaceTillOncoming = oncomingGap - oncomingBGap - oncomingMove;
5199 spaceTillLastStanding = MIN2(spaceTillLastStanding, spaceTillOncoming);
5200 if (spaceTillOncoming <= getVehicleType().getLengthWithGap()) {
5201 foundStopped = true;
5202 }
5203#ifdef DEBUG_CHECKREWINDLINKLANES
5204 if (DEBUG_COND) {
5205 std::cout << " oVeh=" << oncomingVeh->getID()
5206 << " oGap=" << oncomingGap
5207 << " bGap=" << oncomingBGap
5208 << " mGap=" << oncomingMove
5209 << " sto=" << spaceTillOncoming;
5210 }
5211#endif
5212 }
5213 }
5214 seenSpace += spaceTillLastStanding;
5215 if (foundStopped2) {
5216 foundStopped = true;
5217 item.hadStoppedVehicle = true;
5218 }
5219 item.availableSpace = seenSpace;
5220 if (last->myHaveToWaitOnNextLink || last->isStopped()) {
5221 foundStopped = true;
5222 item.hadStoppedVehicle = true;
5223 }
5224#ifdef DEBUG_CHECKREWINDLINKLANES
5225 if (DEBUG_COND) std::cout
5226 << " approached=" << approachedLane->getID()
5227 << " last=" << last->getID()
5228 << " lastHasToWait=" << last->myHaveToWaitOnNextLink
5229 << " lastBrakeLight=" << last->signalSet(VEH_SIGNAL_BRAKELIGHT)
5230 << " lastBrakeGap=" << last->getCarFollowModel().brakeGap(last->getSpeed())
5231 << " lastGap=" << (last->getBackPositionOnLane(approachedLane) + last->getCarFollowModel().brakeGap(last->getSpeed()) - last->getSpeed() * last->getCarFollowModel().getHeadwayTime()
5232 // gap of last up to the next intersection
5233 - last->getVehicleType().getMinGap())
5234 << " stls=" << spaceTillLastStanding
5235 << " avail=" << item.availableSpace
5236 << " seenSpace=" << seenSpace
5237 << " foundStopped=" << foundStopped
5238 << " foundStopped2=" << foundStopped2
5239 << "\n";
5240#endif
5241 }
5242 }
5243
5244 // check which links allow continuation and add pass available to the previous item
5245 for (int i = ((int)lfLinks.size() - 1); i > 0; --i) {
5246 DriveProcessItem& item = lfLinks[i - 1];
5247 DriveProcessItem& nextItem = lfLinks[i];
5248 const bool canLeaveJunction = item.myLink->getViaLane() == nullptr || nextItem.myLink == nullptr || nextItem.mySetRequest;
5249 const bool opened = (item.myLink != nullptr
5250 && (canLeaveJunction || (
5251 // indirect bicycle turn
5252 nextItem.myLink != nullptr && nextItem.myLink->isInternalJunctionLink() && nextItem.myLink->haveRed()))
5253 && (
5254 item.myLink->havePriority()
5255 || i == 1 // the upcoming link (item 0) is checked in executeMove anyway. No need to use outdata approachData here
5257 || item.myLink->opened(item.myArrivalTime, item.myArrivalSpeed,
5260 bool allowsContinuation = (item.myLink == nullptr || item.myLink->isCont() || opened) && !item.hadStoppedVehicle;
5261#ifdef DEBUG_CHECKREWINDLINKLANES
5262 if (DEBUG_COND) std::cout
5263 << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5264 << " canLeave=" << canLeaveJunction
5265 << " opened=" << opened
5266 << " allowsContinuation=" << allowsContinuation
5267 << " foundStopped=" << foundStopped
5268 << "\n";
5269#endif
5270 if (!opened && item.myLink != nullptr) {
5271 foundStopped = true;
5272 if (i > 1) {
5273 DriveProcessItem& item2 = lfLinks[i - 2];
5274 if (item2.myLink != nullptr && item2.myLink->isCont()) {
5275 allowsContinuation = true;
5276 }
5277 }
5278 }
5279 if (allowsContinuation) {
5280 item.availableSpace = nextItem.availableSpace;
5281#ifdef DEBUG_CHECKREWINDLINKLANES
5282 if (DEBUG_COND) std::cout
5283 << " link=" << (item.myLink == nullptr ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5284 << " copy nextAvail=" << nextItem.availableSpace
5285 << "\n";
5286#endif
5287 }
5288 }
5289
5290 // find removalBegin
5291 int removalBegin = -1;
5292 for (int i = 0; foundStopped && i < (int)lfLinks.size() && removalBegin < 0; ++i) {
5293 // skip unset links
5294 const DriveProcessItem& item = lfLinks[i];
5295 if (item.myLink == nullptr) {
5296 continue;
5297 }
5298 /*
5299 double impatienceCorrection = MAX2(0., double(double(myWaitingTime)));
5300 if (seenSpace<getVehicleType().getLengthWithGap()-impatienceCorrection/10.&&nextSeenNonInternal!=0) {
5301 removalBegin = lastLinkToInternal;
5302 }
5303 */
5304
5305 const double leftSpace = item.availableSpace - getVehicleType().getLengthWithGap();
5306#ifdef DEBUG_CHECKREWINDLINKLANES
5307 if (DEBUG_COND) std::cout
5308 << SIMTIME
5309 << " veh=" << getID()
5310 << " link=" << (item.myLink == 0 ? "NULL" : item.myLink->getViaLaneOrLane()->getID())
5311 << " avail=" << item.availableSpace
5312 << " leftSpace=" << leftSpace
5313 << "\n";
5314#endif
5315 if (leftSpace < 0/* && item.myLink->willHaveBlockedFoe()*/) {
5316 double impatienceCorrection = 0;
5317 /*
5318 if(item.myLink->getState()==LINKSTATE_MINOR) {
5319 impatienceCorrection = MAX2(0., STEPS2TIME(myWaitingTime));
5320 }
5321 */
5322 // may ignore keepClear rules
5323 if (leftSpace < -impatienceCorrection / 10. && keepClear(item.myLink)) {
5324 removalBegin = i;
5325 }
5326 //removalBegin = i;
5327 }
5328 }
5329 // abort requests
5330 if (removalBegin != -1 && !(removalBegin == 0 && myLane->getEdge().isInternal())) {
5331 const double brakeGap = getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0.);
5332 while (removalBegin < (int)(lfLinks.size())) {
5333 DriveProcessItem& dpi = lfLinks[removalBegin];
5334 if (dpi.myLink == nullptr) {
5335 break;
5336 }
5337 dpi.myVLinkPass = dpi.myVLinkWait;
5338#ifdef DEBUG_CHECKREWINDLINKLANES
5339 if (DEBUG_COND) {
5340 std::cout << " removalBegin=" << removalBegin << " brakeGap=" << brakeGap << " dist=" << dpi.myDistance << " speed=" << myState.mySpeed << " a2s=" << ACCEL2SPEED(getCarFollowModel().getMaxDecel()) << "\n";
5341 }
5342#endif
5343 if (dpi.myDistance >= brakeGap + POSITION_EPS) {
5344 // always leave junctions after requesting to enter
5345 if (!dpi.myLink->isExitLink() || !lfLinks[removalBegin - 1].mySetRequest) {
5346 dpi.mySetRequest = false;
5347 }
5348 }
5349 ++removalBegin;
5350 }
5351 }
5352 }
5353}
5354
5355
5356void
5358 if (!myActionStep) {
5359 return;
5360 }
5362 for (DriveProcessItem& dpi : myLFLinkLanes) {
5363 if (dpi.myLink != nullptr) {
5364 if (dpi.myLink->getState() == LINKSTATE_ALLWAY_STOP) {
5365 dpi.myArrivalTime += (SUMOTime)RandHelper::rand((int)2, getRNG()); // tie braker
5366 }
5367 dpi.myLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
5368 dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance, getLateralPositionOnLane());
5369 }
5370 }
5371 if (isRail()) {
5372 for (DriveProcessItem& dpi : myLFLinkLanes) {
5373 if (dpi.myLink != nullptr && dpi.myLink->getTLLogic() != nullptr && dpi.myLink->getTLLogic()->getLogicType() == TrafficLightType::RAIL_SIGNAL) {
5375 }
5376 }
5377 }
5378 if (myLaneChangeModel->getShadowLane() != nullptr) {
5379 // register on all shadow links
5380 for (const DriveProcessItem& dpi : myLFLinkLanes) {
5381 if (dpi.myLink != nullptr) {
5382 MSLink* parallelLink = dpi.myLink->getParallelLink(myLaneChangeModel->getShadowDirection());
5383 if (parallelLink == nullptr && getLaneChangeModel().isOpposite() && dpi.myLink->isEntryLink()) {
5384 // register on opposite direction entry link to warn foes at minor side road
5385 parallelLink = dpi.myLink->getOppositeDirectionLink();
5386 }
5387 if (parallelLink != nullptr) {
5388 const double latOffset = getLane()->getRightSideOnEdge() - myLaneChangeModel->getShadowLane()->getRightSideOnEdge();
5389 parallelLink->setApproaching(this, dpi.myArrivalTime, dpi.myArrivalSpeed, dpi.getLeaveSpeed(),
5390 dpi.mySetRequest, dpi.myArrivalSpeedBraking, getWaitingTimeFor(dpi.myLink), dpi.myDistance,
5391 latOffset);
5393 }
5394 }
5395 }
5396 }
5397#ifdef DEBUG_PLAN_MOVE
5398 if (DEBUG_COND) {
5399 std::cout << SIMTIME
5400 << " veh=" << getID()
5401 << " after checkRewindLinkLanes\n";
5402 for (DriveProcessItem& dpi : myLFLinkLanes) {
5403 std::cout
5404 << " vPass=" << dpi.myVLinkPass
5405 << " vWait=" << dpi.myVLinkWait
5406 << " linkLane=" << (dpi.myLink == 0 ? "NULL" : dpi.myLink->getViaLaneOrLane()->getID())
5407 << " request=" << dpi.mySetRequest
5408 << " atime=" << dpi.myArrivalTime
5409 << "\n";
5410 }
5411 }
5412#endif
5413}
5414
5415
5416void
5418 DriveProcessItem dpi(0, dist);
5419 dpi.myLink = link;
5420 const double arrivalSpeedBraking = getCarFollowModel().getMinimalArrivalSpeedEuler(dist, getSpeed());
5421 link->setApproaching(this, SUMOTime_MAX, 0, 0, false, arrivalSpeedBraking, 0, dpi.myDistance, 0);
5422 // ensure cleanup in the next step
5423 myLFLinkLanes.push_back(dpi);
5425}
5426
5427
5428void
5429MSVehicle::enterLaneAtMove(MSLane* enteredLane, bool onTeleporting) {
5430 myAmOnNet = !onTeleporting;
5431 // vaporizing edge?
5432 /*
5433 if (enteredLane->getEdge().isVaporizing()) {
5434 // yep, let's do the vaporization...
5435 myLane = enteredLane;
5436 return true;
5437 }
5438 */
5439 // Adjust MoveReminder offset to the next lane
5440 adaptLaneEntering2MoveReminder(*enteredLane);
5441 // set the entered lane as the current lane
5442 MSLane* oldLane = myLane;
5443 myLane = enteredLane;
5444 myLastBestLanesEdge = nullptr;
5445
5446 // internal edges are not a part of the route...
5447 if (!enteredLane->getEdge().isInternal()) {
5448 ++myCurrEdge;
5450 }
5451 if (myInfluencer != nullptr) {
5453 }
5454 if (!onTeleporting) {
5457 // transform lateral position when the lane width changes
5458 assert(oldLane != nullptr);
5459 const MSLink* const link = oldLane->getLinkTo(myLane);
5460 if (link != nullptr) {
5462 myState.myPosLat += link->getLateralShift();
5463 }
5464 } else if (fabs(myState.myPosLat) > NUMERICAL_EPS) {
5465 const double overlap = MAX2(0.0, getLateralOverlap(myState.myPosLat, oldLane));
5466 const double range = (oldLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
5467 const double range2 = (myLane->getWidth() - getVehicleType().getWidth()) * 0.5 + overlap;
5468 myState.myPosLat *= range2 / range;
5469 }
5470 if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5471 // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
5472 // (unless the lane is shared with cars)
5474 }
5475 } else {
5476 // normal move() isn't called so reset position here. must be done
5477 // before calling reminders
5478 myState.myPos = 0;
5481 }
5482 // update via
5483 if (myParameter->via.size() > 0 && myLane->getEdge().getID() == myParameter->via.front()) {
5484 myParameter->via.erase(myParameter->via.begin());
5485 }
5486}
5487
5488
5489void
5491 myAmOnNet = true;
5492 myLane = enteredLane;
5494 // need to update myCurrentLaneInBestLanes
5496 // switch to and activate the new lane's reminders
5497 // keep OldLaneReminders
5498 for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
5499 addReminder(*rem);
5500 }
5502 MSLane* lane = myLane;
5503 double leftLength = getVehicleType().getLength() - myState.myPos;
5504 int deleteFurther = 0;
5505#ifdef DEBUG_SETFURTHER
5506 if (DEBUG_COND) {
5507 std::cout << SIMTIME << " enterLaneAtLaneChange entered=" << Named::getIDSecure(enteredLane) << " oldFurther=" << toString(myFurtherLanes) << "\n";
5508 }
5509#endif
5510 if (myLane->getBidiLane() != nullptr && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5511 // railways don't need to "see" each other when moving in opposite directions on the same track (efficiency)
5512 // (unless the lane is shared with cars)
5514 }
5515 for (int i = 0; i < (int)myFurtherLanes.size(); i++) {
5516 if (lane != nullptr) {
5518 }
5519#ifdef DEBUG_SETFURTHER
5520 if (DEBUG_COND) {
5521 std::cout << " enterLaneAtLaneChange i=" << i << " lane=" << Named::getIDSecure(lane) << " leftLength=" << leftLength << "\n";
5522 }
5523#endif
5524 if (leftLength > 0) {
5525 if (lane != nullptr) {
5527 if (myFurtherLanes[i]->getBidiLane() != nullptr
5528 && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5529 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
5530 }
5531 // lane changing onto longer lanes may reduce the number of
5532 // remaining further lanes
5533 myFurtherLanes[i] = lane;
5535 leftLength -= lane->setPartialOccupation(this);
5536 if (lane->getBidiLane() != nullptr
5537 && (!isRailway(getVClass()) || (lane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5538 lane->getBidiLane()->setPartialOccupation(this);
5539 }
5540 myState.myBackPos = -leftLength;
5541#ifdef DEBUG_SETFURTHER
5542 if (DEBUG_COND) {
5543 std::cout << SIMTIME << " newBackPos=" << myState.myBackPos << "\n";
5544 }
5545#endif
5546 } else {
5547 // keep the old values, but ensure there is no shadow
5550 }
5551 if (myState.myBackPos < 0) {
5552 myState.myBackPos += myFurtherLanes[i]->getLength();
5553 }
5554#ifdef DEBUG_SETFURTHER
5555 if (DEBUG_COND) {
5556 std::cout << SIMTIME << " i=" << i << " further=" << myFurtherLanes[i]->getID() << " newBackPos=" << myState.myBackPos << "\n";
5557 }
5558#endif
5559 }
5560 } else {
5561 myFurtherLanes[i]->resetPartialOccupation(this);
5562 if (myFurtherLanes[i]->getBidiLane() != nullptr
5563 && (!isRailway(getVClass()) || (myFurtherLanes[i]->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5564 myFurtherLanes[i]->getBidiLane()->resetPartialOccupation(this);
5565 }
5566 deleteFurther++;
5567 }
5568 }
5569 if (deleteFurther > 0) {
5570#ifdef DEBUG_SETFURTHER
5571 if (DEBUG_COND) {
5572 std::cout << SIMTIME << " veh=" << getID() << " shortening myFurtherLanes by " << deleteFurther << "\n";
5573 }
5574#endif
5575 myFurtherLanes.erase(myFurtherLanes.end() - deleteFurther, myFurtherLanes.end());
5576 myFurtherLanesPosLat.erase(myFurtherLanesPosLat.end() - deleteFurther, myFurtherLanesPosLat.end());
5577 }
5578#ifdef DEBUG_SETFURTHER
5579 if (DEBUG_COND) {
5580 std::cout << SIMTIME << " enterLaneAtLaneChange new furtherLanes=" << toString(myFurtherLanes)
5581 << " furterLanesPosLat=" << toString(myFurtherLanesPosLat) << "\n";
5582 }
5583#endif
5585}
5586
5587
5588void
5589MSVehicle::computeFurtherLanes(MSLane* enteredLane, double pos, bool collision) {
5590 // build the list of lanes the vehicle is lapping into
5591 if (!myLaneChangeModel->isOpposite()) {
5592 double leftLength = myType->getLength() - pos;
5593 MSLane* clane = enteredLane;
5594 int routeIndex = getRoutePosition();
5595 while (leftLength > 0) {
5596 if (routeIndex > 0 && clane->getEdge().isNormal()) {
5597 // get predecessor lane that corresponds to prior route
5598 routeIndex--;
5599 const MSEdge* fromRouteEdge = myRoute->getEdges()[routeIndex];
5600 MSLane* target = clane;
5601 clane = nullptr;
5602 for (auto ili : target->getIncomingLanes()) {
5603 if (ili.lane->getEdge().getNormalBefore() == fromRouteEdge) {
5604 clane = ili.lane;
5605 break;
5606 }
5607 }
5608 } else {
5609 clane = clane->getLogicalPredecessorLane();
5610 }
5611 if (clane == nullptr || clane == myLane || clane == myLane->getBidiLane()
5612 || (clane->isInternal() && (
5613 clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN
5614 || clane->getLinkCont()[0]->getDirection() == LinkDirection::TURN_LEFTHAND))) {
5615 break;
5616 }
5617 if (!collision || std::find(myFurtherLanes.begin(), myFurtherLanes.end(), clane) == myFurtherLanes.end()) {
5618 myFurtherLanes.push_back(clane);
5620 clane->setPartialOccupation(this);
5621 if (clane->getBidiLane() != nullptr
5622 && (!isRailway(getVClass()) || (clane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5623 clane->getBidiLane()->setPartialOccupation(this);
5624 }
5625 }
5626 leftLength -= clane->getLength();
5627 }
5628 myState.myBackPos = -leftLength;
5629#ifdef DEBUG_SETFURTHER
5630 if (DEBUG_COND) {
5631 std::cout << SIMTIME << " computeFurtherLanes veh=" << getID() << " pos=" << pos << " myFurtherLanes=" << toString(myFurtherLanes) << " backPos=" << myState.myBackPos << "\n";
5632 }
5633#endif
5634 } else {
5635 // clear partial occupation
5636 for (MSLane* further : myFurtherLanes) {
5637#ifdef DEBUG_SETFURTHER
5638 if (DEBUG_COND) {
5639 std::cout << SIMTIME << " opposite: resetPartialOccupation " << further->getID() << " \n";
5640 }
5641#endif
5642 further->resetPartialOccupation(this);
5643 if (further->getBidiLane() != nullptr
5644 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5645 further->getBidiLane()->resetPartialOccupation(this);
5646 }
5647 }
5648 myFurtherLanes.clear();
5649 myFurtherLanesPosLat.clear();
5650 }
5651}
5652
5653
5654void
5655MSVehicle::enterLaneAtInsertion(MSLane* enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification) {
5656 myState = State(pos, speed, posLat, pos - getVehicleType().getLength(), hasDeparted() ? myState.myPreviousSpeed : speed);
5658 onDepart();
5659 }
5661 assert(myState.myPos >= 0);
5662 assert(myState.mySpeed >= 0);
5663 myLane = enteredLane;
5664 myAmOnNet = true;
5665 // schedule action for the next timestep
5667 if (notification != MSMoveReminder::NOTIFICATION_TELEPORT) {
5668 if (notification == MSMoveReminder::NOTIFICATION_PARKING && myInfluencer != nullptr) {
5669 drawOutsideNetwork(false);
5670 }
5671 // set and activate the new lane's reminders, teleports already did that at enterLaneAtMove
5672 for (std::vector< MSMoveReminder* >::const_iterator rem = enteredLane->getMoveReminders().begin(); rem != enteredLane->getMoveReminders().end(); ++rem) {
5673 addReminder(*rem);
5674 }
5675 activateReminders(notification, enteredLane);
5676 } else {
5677 myLastBestLanesEdge = nullptr;
5680 while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()
5681 && myStops.front().pars.endPos < pos) {
5682 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
5683 time2string(MSNet::getInstance()->getCurrentTimeStep()));
5684 myStops.pop_front();
5685 }
5686
5687 }
5688 computeFurtherLanes(enteredLane, pos);
5692 } else if (MSGlobals::gLaneChangeDuration > 0) {
5694 }
5695 if (notification != MSMoveReminder::NOTIFICATION_LOAD_STATE) {
5698 myAngle += M_PI;
5699 }
5700 }
5701 if (MSNet::getInstance()->hasPersons()) {
5702 for (MSLane* further : myFurtherLanes) {
5703 if (further->mustCheckJunctionCollisions()) {
5705 }
5706 }
5707 }
5708}
5709
5710
5711void
5712MSVehicle::leaveLane(const MSMoveReminder::Notification reason, const MSLane* approachedLane) {
5713 for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
5714 if (rem->first->notifyLeave(*this, myState.myPos + rem->second, reason, approachedLane)) {
5715#ifdef _DEBUG
5716 if (myTraceMoveReminders) {
5717 traceMoveReminder("notifyLeave", rem->first, rem->second, true);
5718 }
5719#endif
5720 ++rem;
5721 } else {
5722#ifdef _DEBUG
5723 if (myTraceMoveReminders) {
5724 traceMoveReminder("notifyLeave", rem->first, rem->second, false);
5725 }
5726#endif
5727 rem = myMoveReminders.erase(rem);
5728 }
5729 }
5733 && myLane != nullptr) {
5735 }
5736 if (myLane != nullptr && myLane->getBidiLane() != nullptr && myAmOnNet
5737 && (!isRailway(getVClass()) || (myLane->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5739 }
5741 // @note. In case of lane change, myFurtherLanes and partial occupation
5742 // are handled in enterLaneAtLaneChange()
5743 for (MSLane* further : myFurtherLanes) {
5744#ifdef DEBUG_FURTHER
5745 if (DEBUG_COND) {
5746 std::cout << SIMTIME << " leaveLane \n";
5747 }
5748#endif
5749 further->resetPartialOccupation(this);
5750 if (further->getBidiLane() != nullptr
5751 && (!isRailway(getVClass()) || (further->getPermissions() & ~SVC_RAIL_CLASSES) != 0)) {
5752 further->getBidiLane()->resetPartialOccupation(this);
5753 }
5754 }
5755 myFurtherLanes.clear();
5756 myFurtherLanesPosLat.clear();
5757 }
5759 myAmOnNet = false;
5760 myWaitingTime = 0;
5761 }
5763 myStopDist = std::numeric_limits<double>::max();
5764 if (myPastStops.back().speed <= 0) {
5765 WRITE_WARNINGF(TL("Vehicle '%' aborts stop."), getID());
5766 }
5767 }
5769 while (!myStops.empty() && myStops.front().edge == myCurrEdge && &myStops.front().lane->getEdge() == &myLane->getEdge()) {
5770 if (myStops.front().getSpeed() <= 0) {
5771 WRITE_WARNINGF(TL("Vehicle '%' skips stop on lane '%' time=%."), getID(), myStops.front().lane->getID(),
5772 time2string(MSNet::getInstance()->getCurrentTimeStep()))
5773 if (MSStopOut::active()) {
5774 // clean up if stopBlocked was called
5776 }
5777 myStops.pop_front();
5778 } else {
5779 MSStop& stop = myStops.front();
5780 // passed waypoint at the end of the lane
5781 if (!stop.reached) {
5782 if (MSStopOut::active()) {
5784 }
5785 stop.reached = true;
5786 // enter stopping place so leaveFrom works as expected
5787 if (stop.busstop != nullptr) {
5788 // let the bus stop know the vehicle
5789 stop.busstop->enter(this, stop.pars.parking == ParkingType::OFFROAD);
5790 }
5791 if (stop.containerstop != nullptr) {
5792 // let the container stop know the vehicle
5794 }
5795 // do not enter parkingarea!
5796 if (stop.chargingStation != nullptr) {
5797 // let the container stop know the vehicle
5799 }
5800 }
5802 }
5803 myStopDist = std::numeric_limits<double>::max();
5804 }
5805 }
5806}
5807
5808
5809void
5811 for (MoveReminderCont::iterator rem = myMoveReminders.begin(); rem != myMoveReminders.end();) {
5812 if (rem->first->notifyLeaveBack(*this, reason, leftLane)) {
5813#ifdef _DEBUG
5814 if (myTraceMoveReminders) {
5815 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, true);
5816 }
5817#endif
5818 ++rem;
5819 } else {
5820#ifdef _DEBUG
5821 if (myTraceMoveReminders) {
5822 traceMoveReminder("notifyLeaveBack", rem->first, rem->second, false);
5823 }
5824#endif
5825 rem = myMoveReminders.erase(rem);
5826 }
5827 }
5828#ifdef DEBUG_MOVEREMINDERS
5829 if (DEBUG_COND) {
5830 std::cout << SIMTIME << " veh=" << getID() << " myReminders:";
5831 for (auto rem : myMoveReminders) {
5832 std::cout << rem.first->getDescription() << " ";
5833 }
5834 std::cout << "\n";
5835 }
5836#endif
5837}
5838
5839
5844
5845
5850
5851bool
5853 return (lane->isInternal()
5854 ? & (lane->getLinkCont()[0]->getLane()->getEdge()) != *(myCurrEdge + 1)
5855 : &lane->getEdge() != *myCurrEdge);
5856}
5857
5858const std::vector<MSVehicle::LaneQ>&
5860 return *myBestLanes.begin();
5861}
5862
5863
5864void
5865MSVehicle::updateBestLanes(bool forceRebuild, const MSLane* startLane) {
5866#ifdef DEBUG_BESTLANES
5867 if (DEBUG_COND) {
5868 std::cout << SIMTIME << " updateBestLanes veh=" << getID() << " force=" << forceRebuild << " startLane1=" << Named::getIDSecure(startLane) << " myLane=" << Named::getIDSecure(myLane) << "\n";
5869 }
5870#endif
5871 if (startLane == nullptr) {
5872 startLane = myLane;
5873 }
5874 assert(startLane != 0);
5876 // depending on the calling context, startLane might be the forward lane
5877 // or the reverse-direction lane. In the latter case we need to
5878 // transform it to the forward lane.
5879 if (isOppositeLane(startLane)) {
5880 // use leftmost lane of forward edge
5881 startLane = startLane->getEdge().getOppositeEdge()->getLanes().back();
5882 assert(startLane != 0);
5883#ifdef DEBUG_BESTLANES
5884 if (DEBUG_COND) {
5885 std::cout << " startLaneIsOpposite newStartLane=" << startLane->getID() << "\n";
5886 }
5887#endif
5888 }
5889 }
5890 if (forceRebuild) {
5891 myLastBestLanesEdge = nullptr;
5893 }
5894 if (myBestLanes.size() > 0 && !forceRebuild && myLastBestLanesEdge == &startLane->getEdge()) {
5896#ifdef DEBUG_BESTLANES
5897 if (DEBUG_COND) {
5898 std::cout << " only updateOccupancyAndCurrentBestLane\n";
5899 }
5900#endif
5901 return;
5902 }
5903 if (startLane->getEdge().isInternal()) {
5904 if (myBestLanes.size() == 0 || forceRebuild) {
5905 // rebuilt from previous non-internal lane (may backtrack twice if behind an internal junction)
5906 updateBestLanes(true, startLane->getLogicalPredecessorLane());
5907 }
5908 if (myLastBestLanesInternalLane == startLane && !forceRebuild) {
5909#ifdef DEBUG_BESTLANES
5910 if (DEBUG_COND) {
5911 std::cout << " nothing to do on internal\n";
5912 }
5913#endif
5914 return;
5915 }
5916 // adapt best lanes to fit the current internal edge:
5917 // keep the entries that are reachable from this edge
5918 const MSEdge* nextEdge = startLane->getNextNormal();
5919 assert(!nextEdge->isInternal());
5920 for (std::vector<std::vector<LaneQ> >::iterator it = myBestLanes.begin(); it != myBestLanes.end();) {
5921 std::vector<LaneQ>& lanes = *it;
5922 assert(lanes.size() > 0);
5923 if (&(lanes[0].lane->getEdge()) == nextEdge) {
5924 // keep those lanes which are successors of internal lanes from the edge of startLane
5925 std::vector<LaneQ> oldLanes = lanes;
5926 lanes.clear();
5927 const std::vector<MSLane*>& sourceLanes = startLane->getEdge().getLanes();
5928 for (std::vector<MSLane*>::const_iterator it_source = sourceLanes.begin(); it_source != sourceLanes.end(); ++it_source) {
5929 for (std::vector<LaneQ>::iterator it_lane = oldLanes.begin(); it_lane != oldLanes.end(); ++it_lane) {
5930 if ((*it_source)->getLinkCont()[0]->getLane() == (*it_lane).lane) {
5931 lanes.push_back(*it_lane);
5932 break;
5933 }
5934 }
5935 }
5936 assert(lanes.size() == startLane->getEdge().getLanes().size());
5937 // patch invalid bestLaneOffset and updated myCurrentLaneInBestLanes
5938 for (int i = 0; i < (int)lanes.size(); ++i) {
5939 if (i + lanes[i].bestLaneOffset < 0) {
5940 lanes[i].bestLaneOffset = -i;
5941 }
5942 if (i + lanes[i].bestLaneOffset >= (int)lanes.size()) {
5943 lanes[i].bestLaneOffset = (int)lanes.size() - i - 1;
5944 }
5945 assert(i + lanes[i].bestLaneOffset >= 0);
5946 assert(i + lanes[i].bestLaneOffset < (int)lanes.size());
5947 if (lanes[i].bestContinuations[0] != 0) {
5948 // patch length of bestContinuation to match expectations (only once)
5949 lanes[i].bestContinuations.insert(lanes[i].bestContinuations.begin(), (MSLane*)nullptr);
5950 }
5951 if (startLane->getLinkCont()[0]->getLane() == lanes[i].lane) {
5952 myCurrentLaneInBestLanes = lanes.begin() + i;
5953 }
5954 assert(&(lanes[i].lane->getEdge()) == nextEdge);
5955 }
5956 myLastBestLanesInternalLane = startLane;
5958#ifdef DEBUG_BESTLANES
5959 if (DEBUG_COND) {
5960 std::cout << " updated for internal\n";
5961 }
5962#endif
5963 return;
5964 } else {
5965 // remove passed edges
5966 it = myBestLanes.erase(it);
5967 }
5968 }
5969 assert(false); // should always find the next edge
5970 }
5971 // start rebuilding
5973 myLastBestLanesEdge = &startLane->getEdge();
5975
5976 // get information about the next stop
5977 MSRouteIterator nextStopEdge = myRoute->end();
5978 const MSLane* nextStopLane = nullptr;
5979 double nextStopPos = 0;
5980 bool nextStopIsWaypoint = false;
5981 if (!myStops.empty()) {
5982 const MSStop& nextStop = myStops.front();
5983 nextStopLane = nextStop.lane;
5984 if (nextStop.isOpposite) {
5985 // target leftmost lane in forward direction
5986 nextStopLane = nextStopLane->getEdge().getOppositeEdge()->getLanes().back();
5987 }
5988 nextStopEdge = nextStop.edge;
5989 nextStopPos = nextStop.pars.startPos;
5990 nextStopIsWaypoint = nextStop.getSpeed() > 0;
5991 }
5992 // myArrivalTime = -1 in the context of validating departSpeed with departLane=best
5993 if (myParameter->arrivalLaneProcedure >= ArrivalLaneDefinition::GIVEN && nextStopEdge == myRoute->end() && myArrivalLane >= 0) {
5994 nextStopEdge = (myRoute->end() - 1);
5995 nextStopLane = (*nextStopEdge)->getLanes()[myArrivalLane];
5996 nextStopPos = myArrivalPos;
5997 }
5998 if (nextStopEdge != myRoute->end()) {
5999 // make sure that the "wrong" lanes get a penalty. (penalty needs to be
6000 // large enough to overcome a magic threshold in MSLaneChangeModel::DK2004.cpp:383)
6001 nextStopPos = MAX2(POSITION_EPS, MIN2((double)nextStopPos, (double)(nextStopLane->getLength() - 2 * POSITION_EPS)));
6002 if (nextStopLane->isInternal()) {
6003 // switch to the correct lane before entering the intersection
6004 nextStopPos = (*nextStopEdge)->getLength();
6005 }
6006 }
6007
6008 // go forward along the next lanes;
6009 // trains do not have to deal with lane-changing for stops but their best
6010 // lanes lookahead is needed for rail signal control
6011 const bool continueAfterStop = nextStopIsWaypoint || isRailway(getVClass());
6012 int seen = 0;
6013 double seenLength = 0;
6014 bool progress = true;
6015 // bestLanes must cover the braking distance even when at the very end of the current lane to avoid unecessary slow down
6016 const double maxBrakeDist = startLane->getLength() + getCarFollowModel().getHeadwayTime() * getMaxSpeed() + getCarFollowModel().brakeGap(getMaxSpeed()) + getVehicleType().getMinGap();
6017 const double lookahead = getLaneChangeModel().getStrategicLookahead();
6018 for (MSRouteIterator ce = myCurrEdge; progress;) {
6019 std::vector<LaneQ> currentLanes;
6020 const std::vector<MSLane*>* allowed = nullptr;
6021 const MSEdge* nextEdge = nullptr;
6022 if (ce != myRoute->end() && ce + 1 != myRoute->end()) {
6023 nextEdge = *(ce + 1);
6024 allowed = (*ce)->allowedLanes(*nextEdge, myType->getVehicleClass());
6025 }
6026 const std::vector<MSLane*>& lanes = (*ce)->getLanes();
6027 for (std::vector<MSLane*>::const_iterator i = lanes.begin(); i != lanes.end(); ++i) {
6028 LaneQ q;
6029 MSLane* cl = *i;
6030 q.lane = cl;
6031 q.bestContinuations.push_back(cl);
6032 q.bestLaneOffset = 0;
6033 q.length = cl->allowsVehicleClass(myType->getVehicleClass()) ? (*ce)->getLength() : 0;
6034 q.currentLength = q.length;
6035 // if all lanes are forbidden (i.e. due to a dynamic closing) we want to express no preference
6036 q.allowsContinuation = allowed == nullptr || std::find(allowed->begin(), allowed->end(), cl) != allowed->end();
6037 q.occupation = 0;
6038 q.nextOccupation = 0;
6039 currentLanes.push_back(q);
6040 }
6041 //
6042 if (nextStopEdge == ce
6043 // already past the stop edge
6044 && !(ce == myCurrEdge && myLane != nullptr && myLane->isInternal())) {
6045 if (!nextStopLane->isInternal() && !continueAfterStop) {
6046 progress = false;
6047 }
6048 const MSLane* normalStopLane = nextStopLane->getNormalPredecessorLane();
6049 for (std::vector<LaneQ>::iterator q = currentLanes.begin(); q != currentLanes.end(); ++q) {
6050 if (nextStopLane != nullptr && normalStopLane != (*q).lane) {
6051 (*q).allowsContinuation = false;
6052 (*q).length = nextStopPos;
6053 (*q).currentLength = (*q).length;
6054 }
6055 }
6056 }
6057
6058 myBestLanes.push_back(currentLanes);
6059 ++seen;
6060 seenLength += currentLanes[0].lane->getLength();
6061 ++ce;
6062 if (lookahead >= 0) {
6063 progress &= (seen <= 2 || seenLength < lookahead); // custom (but we need to look at least one edge ahead)
6064 } else {
6065 progress &= (seen <= 4 || seenLength < MAX2(maxBrakeDist, 3000.0)); // motorway
6066 progress &= (seen <= 8 || seenLength < MAX2(maxBrakeDist, 200.0) || isRailway(getVClass())); // urban
6067 }
6068 progress &= ce != myRoute->end();
6069 /*
6070 if(progress) {
6071 progress &= (currentLanes.size()!=1||(*ce)->getLanes().size()!=1);
6072 }
6073 */
6074 }
6075
6076 // we are examining the last lane explicitly
6077 if (myBestLanes.size() != 0) {
6078 double bestLength = -1;
6079 // minimum and maximum lane index with best length
6080 int bestThisIndex = 0;
6081 int bestThisMaxIndex = 0;
6082 int index = 0;
6083 std::vector<LaneQ>& last = myBestLanes.back();
6084 for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
6085 if ((*j).length > bestLength) {
6086 bestLength = (*j).length;
6087 bestThisIndex = index;
6088 bestThisMaxIndex = index;
6089 } else if ((*j).length == bestLength) {
6090 bestThisMaxIndex = index;
6091 }
6092 }
6093 index = 0;
6094 bool requiredChangeRightForbidden = false;
6095 int requireChangeToLeftForbidden = -1;
6096 for (std::vector<LaneQ>::iterator j = last.begin(); j != last.end(); ++j, ++index) {
6097 if ((*j).length < bestLength) {
6098 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
6099 (*j).bestLaneOffset = bestThisIndex - index;
6100 } else {
6101 (*j).bestLaneOffset = bestThisMaxIndex - index;
6102 }
6103 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
6104 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
6105 || requiredChangeRightForbidden)) {
6106 // this lane and all further lanes to the left cannot be used
6107 requiredChangeRightForbidden = true;
6108 (*j).length = 0;
6109 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
6110 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
6111 // this lane and all previous lanes to the right cannot be used
6112 requireChangeToLeftForbidden = (*j).lane->getIndex();
6113 }
6114 }
6115 }
6116 for (int i = requireChangeToLeftForbidden; i >= 0; i--) {
6117 if (last[i].bestLaneOffset > 0) {
6118 last[i].length = 0;
6119 }
6120 }
6121#ifdef DEBUG_BESTLANES
6122 if (DEBUG_COND) {
6123 std::cout << " last edge=" << last.front().lane->getEdge().getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
6124 std::vector<LaneQ>& laneQs = myBestLanes.back();
6125 for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
6126 std::cout << " lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << "\n";
6127 }
6128 }
6129#endif
6130 }
6131 // go backward through the lanes
6132 // track back best lane and compute the best prior lane(s)
6133 for (std::vector<std::vector<LaneQ> >::reverse_iterator i = myBestLanes.rbegin() + 1; i != myBestLanes.rend(); ++i) {
6134 std::vector<LaneQ>& nextLanes = (*(i - 1));
6135 std::vector<LaneQ>& clanes = (*i);
6136 MSEdge* const cE = &clanes[0].lane->getEdge();
6137 int index = 0;
6138 double bestConnectedLength = -1;
6139 double bestLength = -1;
6140 for (const LaneQ& j : nextLanes) {
6141 if (j.lane->isApproachedFrom(cE) && bestConnectedLength < j.length) {
6142 bestConnectedLength = j.length;
6143 }
6144 if (bestLength < j.length) {
6145 bestLength = j.length;
6146 }
6147 }
6148 // compute index of the best lane (highest length and least offset from the best next lane)
6149 int bestThisIndex = 0;
6150 int bestThisMaxIndex = 0;
6151 if (bestConnectedLength > 0) {
6152 index = 0;
6153 for (LaneQ& j : clanes) {
6154 const LaneQ* bestConnectedNext = nullptr;
6155 if (j.allowsContinuation) {
6156 for (const LaneQ& m : nextLanes) {
6157 if ((m.lane->allowsVehicleClass(getVClass()) || m.lane->hadPermissionChanges())
6158 && m.lane->isApproachedFrom(cE, j.lane)) {
6159 if (betterContinuation(bestConnectedNext, m)) {
6160 bestConnectedNext = &m;
6161 }
6162 }
6163 }
6164 if (bestConnectedNext != nullptr) {
6165 if (bestConnectedNext->length == bestConnectedLength && abs(bestConnectedNext->bestLaneOffset) < 2) {
6166 j.length += bestLength;
6167 } else {
6168 j.length += bestConnectedNext->length;
6169 }
6170 j.bestLaneOffset = bestConnectedNext->bestLaneOffset;
6171 }
6172 }
6173 if (bestConnectedNext != nullptr && (bestConnectedNext->allowsContinuation || bestConnectedNext->length > 0)) {
6174 copy(bestConnectedNext->bestContinuations.begin(), bestConnectedNext->bestContinuations.end(), back_inserter(j.bestContinuations));
6175 } else {
6176 j.allowsContinuation = false;
6177 }
6178 if (clanes[bestThisIndex].length < j.length
6179 || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) > abs(j.bestLaneOffset))
6180 || (clanes[bestThisIndex].length == j.length && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset) &&
6181 nextLinkPriority(clanes[bestThisIndex].bestContinuations) < nextLinkPriority(j.bestContinuations))
6182 ) {
6183 bestThisIndex = index;
6184 bestThisMaxIndex = index;
6185 } else if (clanes[bestThisIndex].length == j.length
6186 && abs(clanes[bestThisIndex].bestLaneOffset) == abs(j.bestLaneOffset)
6187 && nextLinkPriority(clanes[bestThisIndex].bestContinuations) == nextLinkPriority(j.bestContinuations)) {
6188 bestThisMaxIndex = index;
6189 }
6190 index++;
6191 }
6192
6193 //vehicle with elecHybrid device prefers running under an overhead wire
6194 if (getDevice(typeid(MSDevice_ElecHybrid)) != nullptr) {
6195 index = 0;
6196 for (const LaneQ& j : clanes) {
6197 std::string overheadWireSegmentID = MSNet::getInstance()->getStoppingPlaceID(j.lane, j.currentLength / 2., SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
6198 if (overheadWireSegmentID != "") {
6199 bestThisIndex = index;
6200 bestThisMaxIndex = index;
6201 }
6202 index++;
6203 }
6204 }
6205
6206 } else {
6207 // only needed in case of disconnected routes
6208 int bestNextIndex = 0;
6209 int bestDistToNeeded = (int) clanes.size();
6210 index = 0;
6211 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
6212 if ((*j).allowsContinuation) {
6213 int nextIndex = 0;
6214 for (std::vector<LaneQ>::const_iterator m = nextLanes.begin(); m != nextLanes.end(); ++m, ++nextIndex) {
6215 if ((*m).lane->isApproachedFrom(cE, (*j).lane)) {
6216 if (bestDistToNeeded > abs((*m).bestLaneOffset)) {
6217 bestDistToNeeded = abs((*m).bestLaneOffset);
6218 bestThisIndex = index;
6219 bestThisMaxIndex = index;
6220 bestNextIndex = nextIndex;
6221 }
6222 }
6223 }
6224 }
6225 }
6226 clanes[bestThisIndex].length += nextLanes[bestNextIndex].length;
6227 copy(nextLanes[bestNextIndex].bestContinuations.begin(), nextLanes[bestNextIndex].bestContinuations.end(), back_inserter(clanes[bestThisIndex].bestContinuations));
6228
6229 }
6230 // set bestLaneOffset for all lanes
6231 index = 0;
6232 bool requiredChangeRightForbidden = false;
6233 int requireChangeToLeftForbidden = -1;
6234 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
6235 if ((*j).length < clanes[bestThisIndex].length
6236 || ((*j).length == clanes[bestThisIndex].length && abs((*j).bestLaneOffset) > abs(clanes[bestThisIndex].bestLaneOffset))
6237 || (nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)
6238 ) {
6239 if (abs(bestThisIndex - index) < abs(bestThisMaxIndex - index)) {
6240 (*j).bestLaneOffset = bestThisIndex - index;
6241 } else {
6242 (*j).bestLaneOffset = bestThisMaxIndex - index;
6243 }
6244 if ((nextLinkPriority((*j).bestContinuations)) < nextLinkPriority(clanes[bestThisIndex].bestContinuations)) {
6245 // try to move away from the lower-priority lane before it ends
6246 (*j).length = (*j).currentLength;
6247 }
6248 if ((*j).bestLaneOffset < 0 && (!(*j).lane->allowsChangingRight(getVClass())
6249 || !(*j).lane->getParallelLane(-1, false)->allowsVehicleClass(getVClass())
6250 || requiredChangeRightForbidden)) {
6251 // this lane and all further lanes to the left cannot be used
6252 requiredChangeRightForbidden = true;
6253 if ((*j).length == (*j).currentLength) {
6254 (*j).length = 0;
6255 }
6256 } else if ((*j).bestLaneOffset > 0 && (!(*j).lane->allowsChangingLeft(getVClass())
6257 || !(*j).lane->getParallelLane(1, false)->allowsVehicleClass(getVClass()))) {
6258 // this lane and all previous lanes to the right cannot be used
6259 requireChangeToLeftForbidden = (*j).lane->getIndex();
6260 }
6261 } else {
6262 (*j).bestLaneOffset = 0;
6263 }
6264 }
6265 for (int idx = requireChangeToLeftForbidden; idx >= 0; idx--) {
6266 if (clanes[idx].length == clanes[idx].currentLength) {
6267 clanes[idx].length = 0;
6268 };
6269 }
6270
6271 //vehicle with elecHybrid device prefers running under an overhead wire
6272 if (static_cast<MSDevice_ElecHybrid*>(getDevice(typeid(MSDevice_ElecHybrid))) != 0) {
6273 index = 0;
6274 std::string overheadWireID = MSNet::getInstance()->getStoppingPlaceID(clanes[bestThisIndex].lane, (clanes[bestThisIndex].currentLength) / 2, SUMO_TAG_OVERHEAD_WIRE_SEGMENT);
6275 if (overheadWireID != "") {
6276 for (std::vector<LaneQ>::iterator j = clanes.begin(); j != clanes.end(); ++j, ++index) {
6277 (*j).bestLaneOffset = bestThisIndex - index;
6278 }
6279 }
6280 }
6281
6282#ifdef DEBUG_BESTLANES
6283 if (DEBUG_COND) {
6284 std::cout << " edge=" << cE->getID() << " (bestIndex=" << bestThisIndex << " bestMaxIndex=" << bestThisMaxIndex << "):\n";
6285 std::vector<LaneQ>& laneQs = clanes;
6286 for (std::vector<LaneQ>::iterator j = laneQs.begin(); j != laneQs.end(); ++j) {
6287 std::cout << " lane=" << (*j).lane->getID() << " length=" << (*j).length << " bestOffset=" << (*j).bestLaneOffset << " allowCont=" << (*j).allowsContinuation << "\n";
6288 }
6289 }
6290#endif
6291
6292 }
6294#ifdef DEBUG_BESTLANES
6295 if (DEBUG_COND) {
6296 std::cout << SIMTIME << " veh=" << getID() << " bestCont=" << toString(getBestLanesContinuation()) << "\n";
6297 }
6298#endif
6299}
6300
6301void
6303 if (myLane != nullptr) {
6305 }
6306}
6307
6308bool
6309MSVehicle::betterContinuation(const LaneQ* bestConnectedNext, const LaneQ& m) const {
6310 if (bestConnectedNext == nullptr) {
6311 return true;
6312 } else if (m.lane->getBidiLane() != nullptr && bestConnectedNext->lane->getBidiLane() == nullptr) {
6313 return false;
6314 } else if (bestConnectedNext->lane->getBidiLane() != nullptr && m.lane->getBidiLane() == nullptr) {
6315 return true;
6316 } else if (bestConnectedNext->length < m.length) {
6317 return true;
6318 } else if (bestConnectedNext->length == m.length) {
6319 if (abs(bestConnectedNext->bestLaneOffset) > abs(m.bestLaneOffset)) {
6320 return true;
6321 }
6322 const double contRight = getVehicleType().getParameter().getLCParam(SUMO_ATTR_LCA_CONTRIGHT, 1);
6323 if (contRight < 1
6324 // if we don't check for adjacency, the rightmost line will get
6325 // multiple chances to be better which leads to an uninituitve distribution
6326 && (m.lane->getIndex() - bestConnectedNext->lane->getIndex()) == 1
6327 && RandHelper::rand(getRNG()) > contRight) {
6328 return true;
6329 }
6330 }
6331 return false;
6332}
6333
6334
6335int
6336MSVehicle::nextLinkPriority(const std::vector<MSLane*>& conts) {
6337 if (conts.size() < 2) {
6338 return -1;
6339 } else {
6340 const MSLink* const link = conts[0]->getLinkTo(conts[1]);
6341 if (link != nullptr) {
6342 return link->havePriority() ? 1 : 0;
6343 } else {
6344 // disconnected route
6345 return -1;
6346 }
6347 }
6348}
6349
6350
6351void
6353 std::vector<LaneQ>& currLanes = *myBestLanes.begin();
6354 std::vector<LaneQ>::iterator i;
6355 for (i = currLanes.begin(); i != currLanes.end(); ++i) {
6356 double nextOccupation = 0;
6357 for (std::vector<MSLane*>::const_iterator j = (*i).bestContinuations.begin() + 1; j != (*i).bestContinuations.end(); ++j) {
6358 nextOccupation += (*j)->getBruttoVehLenSum();
6359 }
6360 (*i).nextOccupation = nextOccupation;
6361#ifdef DEBUG_BESTLANES
6362 if (DEBUG_COND) {
6363 std::cout << " lane=" << (*i).lane->getID() << " nextOccupation=" << nextOccupation << "\n";
6364 }
6365#endif
6366 if ((*i).lane == startLane) {
6368 }
6369 }
6370}
6371
6372
6373const std::vector<MSLane*>&
6375 if (myBestLanes.empty() || myBestLanes[0].empty()) {
6376 return myEmptyLaneVector;
6377 }
6378 return (*myCurrentLaneInBestLanes).bestContinuations;
6379}
6380
6381
6382const std::vector<MSLane*>&
6384 const MSLane* lane = l;
6385 // XXX: shouldn't this be a "while" to cover more than one internal lane? (Leo) Refs. #2575
6386 if (lane->getEdge().isInternal()) {
6387 // internal edges are not kept inside the bestLanes structure
6388 lane = lane->getLinkCont()[0]->getLane();
6389 }
6390 if (myBestLanes.size() == 0) {
6391 return myEmptyLaneVector;
6392 }
6393 for (std::vector<LaneQ>::const_iterator i = myBestLanes[0].begin(); i != myBestLanes[0].end(); ++i) {
6394 if ((*i).lane == lane) {
6395 return (*i).bestContinuations;
6396 }
6397 }
6398 return myEmptyLaneVector;
6399}
6400
6401const std::vector<const MSLane*>
6402MSVehicle::getUpcomingLanesUntil(double distance) const {
6403 std::vector<const MSLane*> lanes;
6404
6405 if (distance <= 0. || hasArrived()) {
6406 // WRITE_WARNINGF(TL("MSVehicle::getUpcomingLanesUntil(): distance ('%') should be greater than 0."), distance);
6407 return lanes;
6408 }
6409
6410 if (!myLaneChangeModel->isOpposite()) {
6411 distance += getPositionOnLane();
6412 } else {
6413 distance += myLane->getOppositePos(getPositionOnLane());
6414 }
6416 while (lane->isInternal() && (distance > 0.)) { // include initial internal lanes
6417 lanes.insert(lanes.end(), lane);
6418 distance -= lane->getLength();
6419 lane = lane->getLinkCont().front()->getViaLaneOrLane();
6420 }
6421
6422 const std::vector<MSLane*>& contLanes = getBestLanesContinuation();
6423 if (contLanes.empty()) {
6424 return lanes;
6425 }
6426 auto contLanesIt = contLanes.begin();
6427 MSRouteIterator routeIt = myCurrEdge; // keep track of covered edges in myRoute
6428 while (distance > 0.) {
6429 MSLane* l = nullptr;
6430 if (contLanesIt != contLanes.end()) {
6431 l = *contLanesIt;
6432 if (l != nullptr) {
6433 assert(l->getEdge().getID() == (*routeIt)->getLanes().front()->getEdge().getID());
6434 }
6435 ++contLanesIt;
6436 if (l != nullptr || myLane->isInternal()) {
6437 ++routeIt;
6438 }
6439 if (l == nullptr) {
6440 continue;
6441 }
6442 } else if (routeIt != myRoute->end()) { // bestLanes didn't get us far enough
6443 // choose left-most lane as default (avoid sidewalks, bike lanes etc)
6444 l = (*routeIt)->getLanes().back();
6445 ++routeIt;
6446 } else { // the search distance goes beyond our route
6447 break;
6448 }
6449
6450 assert(l != nullptr);
6451
6452 // insert internal lanes if applicable
6453 const MSLane* internalLane = lanes.size() > 0 ? lanes.back()->getInternalFollowingLane(l) : nullptr;
6454 while ((internalLane != nullptr) && internalLane->isInternal() && (distance > 0.)) {
6455 lanes.insert(lanes.end(), internalLane);
6456 distance -= internalLane->getLength();
6457 internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
6458 }
6459 if (distance <= 0.) {
6460 break;
6461 }
6462
6463 lanes.insert(lanes.end(), l);
6464 distance -= l->getLength();
6465 }
6466
6467 return lanes;
6468}
6469
6470const std::vector<const MSLane*>
6471MSVehicle::getPastLanesUntil(double distance) const {
6472 std::vector<const MSLane*> lanes;
6473
6474 if (distance <= 0.) {
6475 // WRITE_WARNINGF(TL("MSVehicle::getPastLanesUntil(): distance ('%') should be greater than 0."), distance);
6476 return lanes;
6477 }
6478
6479 MSRouteIterator routeIt = myCurrEdge;
6480 if (!myLaneChangeModel->isOpposite()) {
6481 distance += myLane->getLength() - getPositionOnLane();
6482 } else {
6484 }
6486 while (lane->isInternal() && (distance > 0.)) { // include initial internal lanes
6487 lanes.insert(lanes.end(), lane);
6488 distance -= lane->getLength();
6489 lane = lane->getLogicalPredecessorLane();
6490 }
6491
6492 while (distance > 0.) {
6493 // choose left-most lane as default (avoid sidewalks, bike lanes etc)
6494 MSLane* l = (*routeIt)->getLanes().back();
6495
6496 // insert internal lanes if applicable
6497 const MSEdge* internalEdge = lanes.size() > 0 ? (*routeIt)->getInternalFollowingEdge(&(lanes.back()->getEdge()), getVClass()) : nullptr;
6498 const MSLane* internalLane = internalEdge != nullptr ? internalEdge->getLanes().front() : nullptr;
6499 std::vector<const MSLane*> internalLanes;
6500 while ((internalLane != nullptr) && internalLane->isInternal()) { // collect all internal successor lanes
6501 internalLanes.insert(internalLanes.begin(), internalLane);
6502 internalLane = internalLane->getLinkCont().front()->getViaLaneOrLane();
6503 }
6504 for (auto it = internalLanes.begin(); (it != internalLanes.end()) && (distance > 0.); ++it) { // check remaining distance in correct order
6505 lanes.insert(lanes.end(), *it);
6506 distance -= (*it)->getLength();
6507 }
6508 if (distance <= 0.) {
6509 break;
6510 }
6511
6512 lanes.insert(lanes.end(), l);
6513 distance -= l->getLength();
6514
6515 // NOTE: we're going backwards with the (bi-directional) Iterator
6516 // TODO: consider make reverse_iterator() when moving on to C++14 or later
6517 if (routeIt != myRoute->begin()) {
6518 --routeIt;
6519 } else { // we went backwards to begin() and already processed the first and final element
6520 break;
6521 }
6522 }
6523
6524 return lanes;
6525}
6526
6527
6528const std::vector<MSLane*>
6530 const std::vector<const MSLane*> routeLanes = getPastLanesUntil(myLane->getMaximumBrakeDist());
6531 std::vector<MSLane*> result;
6532 for (const MSLane* lane : routeLanes) {
6533 MSLane* opposite = lane->getOpposite();
6534 if (opposite != nullptr) {
6535 result.push_back(opposite);
6536 } else {
6537 break;
6538 }
6539 }
6540 return result;
6541}
6542
6543
6544int
6546 if (myBestLanes.empty() || myBestLanes[0].empty()) {
6547 return 0;
6548 } else {
6549 return (*myCurrentLaneInBestLanes).bestLaneOffset;
6550 }
6551}
6552
6553double
6555 if (myBestLanes.empty() || myBestLanes[0].empty()) {
6556 return -1;
6557 } else {
6558 return (*myCurrentLaneInBestLanes).length;
6559 }
6560}
6561
6562
6563
6564void
6565MSVehicle::adaptBestLanesOccupation(int laneIndex, double density) {
6566 std::vector<MSVehicle::LaneQ>& preb = myBestLanes.front();
6567 assert(laneIndex < (int)preb.size());
6568 preb[laneIndex].occupation = density + preb[laneIndex].nextOccupation;
6569}
6570
6571
6572void
6578
6579std::pair<const MSLane*, double>
6580MSVehicle::getLanePosAfterDist(double distance) const {
6581 if (distance == 0) {
6582 return std::make_pair(myLane, getPositionOnLane());
6583 }
6584 const std::vector<const MSLane*> lanes = getUpcomingLanesUntil(distance);
6585 distance += getPositionOnLane();
6586 for (const MSLane* lane : lanes) {
6587 if (lane->getLength() > distance) {
6588 return std::make_pair(lane, distance);
6589 }
6590 distance -= lane->getLength();
6591 }
6592 return std::make_pair(nullptr, -1);
6593}
6594
6595
6596double
6597MSVehicle::getDistanceToPosition(double destPos, const MSLane* destLane) const {
6598 if (isOnRoad() && destLane != nullptr) {
6599 return myRoute->getDistanceBetween(getPositionOnLane(), destPos, myLane, destLane);
6600 }
6601 return std::numeric_limits<double>::max();
6602}
6603
6604
6605std::pair<const MSVehicle* const, double>
6606MSVehicle::getLeader(double dist, bool considerCrossingFoes) const {
6607 if (myLane == nullptr) {
6608 return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
6609 }
6610 if (dist == 0) {
6612 }
6613 const MSVehicle* lead = nullptr;
6614 const MSLane* lane = myLane; // ensure lane does not change between getVehiclesSecure and releaseVehicles;
6615 const MSLane::VehCont& vehs = lane->getVehiclesSecure();
6616 // vehicle might be outside the road network
6617 MSLane::VehCont::const_iterator it = std::find(vehs.begin(), vehs.end(), this);
6618 if (it != vehs.end() && it + 1 != vehs.end()) {
6619 lead = *(it + 1);
6620 }
6621 if (lead != nullptr) {
6622 std::pair<const MSVehicle* const, double> result(
6623 lead, lead->getBackPositionOnLane(myLane) - getPositionOnLane() - getVehicleType().getMinGap());
6624 lane->releaseVehicles();
6625 return result;
6626 }
6627 const double seen = myLane->getLength() - getPositionOnLane();
6628 const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(myLane);
6629 std::pair<const MSVehicle* const, double> result = myLane->getLeaderOnConsecutive(dist, seen, getSpeed(), *this, bestLaneConts, considerCrossingFoes);
6630 lane->releaseVehicles();
6631 return result;
6632}
6633
6634
6635std::pair<const MSVehicle* const, double>
6636MSVehicle::getFollower(double dist) const {
6637 if (myLane == nullptr) {
6638 return std::make_pair(static_cast<const MSVehicle*>(nullptr), -1);
6639 }
6640 if (dist == 0) {
6641 dist = getCarFollowModel().brakeGap(myLane->getEdge().getSpeedLimit() * 2, 4.5, 0);
6642 }
6644}
6645
6646
6647double
6649 // calling getLeader with 0 would induce a dist calculation but we only want to look for the leaders on the current lane
6650 std::pair<const MSVehicle* const, double> leaderInfo = getLeader(-1);
6651 if (leaderInfo.first == nullptr || getSpeed() == 0) {
6652 return -1;
6653 }
6654 return (leaderInfo.second + getVehicleType().getMinGap()) / getSpeed();
6655}
6656
6657
6658void
6660 MSBaseVehicle::addTransportable(transportable);
6661 if (myStops.size() > 0 && myStops.front().reached) {
6662 if (transportable->isPerson()) {
6663 if (myStops.front().triggered && myStops.front().numExpectedPerson > 0) {
6664 myStops.front().numExpectedPerson -= (int)myStops.front().pars.awaitedPersons.count(transportable->getID());
6665 }
6666 } else {
6667 if (myStops.front().pars.containerTriggered && myStops.front().numExpectedContainer > 0) {
6668 myStops.front().numExpectedContainer -= (int)myStops.front().pars.awaitedContainers.count(transportable->getID());
6669 }
6670 }
6671 }
6672}
6673
6674
6675void
6678 int state = myLaneChangeModel->getOwnState();
6679 // do not set blinker for sublane changes or when blocked from changing to the right
6680 const bool blinkerManoeuvre = (((state & LCA_SUBLANE) == 0) && (
6681 (state & LCA_KEEPRIGHT) == 0 || (state & LCA_BLOCKED) == 0));
6685 // lane indices increase from left to right
6686 std::swap(left, right);
6687 }
6688 if ((state & LCA_LEFT) != 0 && blinkerManoeuvre) {
6689 switchOnSignal(left);
6690 } else if ((state & LCA_RIGHT) != 0 && blinkerManoeuvre) {
6691 switchOnSignal(right);
6692 } else if (myLaneChangeModel->isChangingLanes()) {
6694 switchOnSignal(left);
6695 } else {
6696 switchOnSignal(right);
6697 }
6698 } else {
6699 const MSLane* lane = getLane();
6700 std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, 1, *lane, getBestLanesContinuation());
6701 if (link != lane->getLinkCont().end() && lane->getLength() - getPositionOnLane() < lane->getVehicleMaxSpeed(this) * (double) 7.) {
6702 switch ((*link)->getDirection()) {
6707 break;
6711 break;
6712 default:
6713 break;
6714 }
6715 }
6716 }
6717 // stopping related signals
6718 if (hasStops()
6719 && (myStops.begin()->reached ||
6721 && myStopDist < getCarFollowModel().brakeGap(myLane->getVehicleMaxSpeed(this), getCarFollowModel().getMaxDecel(), 3)))) {
6722 if (myStops.begin()->lane->getIndex() > 0 && myStops.begin()->lane->getParallelLane(-1)->allowsVehicleClass(getVClass())) {
6723 // not stopping on the right. Activate emergency blinkers
6725 } else if (!myStops.begin()->reached && (myStops.begin()->pars.parking == ParkingType::OFFROAD)) {
6726 // signal upcoming parking stop on the current lane when within braking distance (~2 seconds before braking)
6728 }
6729 }
6730 if (myInfluencer != nullptr && myInfluencer->getSignals() >= 0) {
6732 myInfluencer->setSignals(-1); // overwrite computed signals only once
6733 }
6734}
6735
6736void
6738
6739 //TODO look if timestep ist SIMSTEP
6740 if (currentTime % 1000 == 0) {
6743 } else {
6745 }
6746 }
6747}
6748
6749
6750int
6752 return myLane == nullptr ? -1 : myLane->getIndex();
6753}
6754
6755
6756void
6757MSVehicle::setTentativeLaneAndPosition(MSLane* lane, double pos, double posLat) {
6758 myLane = lane;
6759 myState.myPos = pos;
6760 myState.myPosLat = posLat;
6762}
6763
6764
6765double
6767 return myState.myPosLat + 0.5 * myLane->getWidth() - 0.5 * getVehicleType().getWidth();
6768}
6769
6770
6771double
6773 return myState.myPosLat + 0.5 * myLane->getWidth() + 0.5 * getVehicleType().getWidth();
6774}
6775
6776
6777double
6779 return myState.myPosLat + 0.5 * lane->getWidth() - 0.5 * getVehicleType().getWidth();
6780}
6781
6782
6783double
6785 return myState.myPosLat + 0.5 * lane->getWidth() + 0.5 * getVehicleType().getWidth();
6786}
6787
6788
6789double
6791 return getCenterOnEdge(lane) - 0.5 * getVehicleType().getWidth();
6792}
6793
6794
6795double
6797 return getCenterOnEdge(lane) + 0.5 * getVehicleType().getWidth();
6798}
6799
6800
6801double
6803 if (lane == nullptr || &lane->getEdge() == &myLane->getEdge()) {
6805 } else if (lane == myLaneChangeModel->getShadowLane()) {
6806 if (myLaneChangeModel->isOpposite() && &lane->getEdge() != &myLane->getEdge()) {
6807 return lane->getRightSideOnEdge() + lane->getWidth() - myState.myPosLat + 0.5 * myLane->getWidth();
6808 }
6810 return lane->getRightSideOnEdge() + lane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
6811 } else {
6812 return lane->getRightSideOnEdge() - myLane->getWidth() + myState.myPosLat + 0.5 * myLane->getWidth();
6813 }
6814 } else if (lane == myLane->getBidiLane()) {
6815 return lane->getRightSideOnEdge() - myState.myPosLat + 0.5 * lane->getWidth();
6816 } else {
6817 assert(myFurtherLanes.size() == myFurtherLanesPosLat.size());
6818 for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
6819 if (myFurtherLanes[i] == lane) {
6820#ifdef DEBUG_FURTHER
6821 if (DEBUG_COND) std::cout << " getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat=" << myFurtherLanesPosLat[i]
6822 << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
6823 << "\n";
6824#endif
6825 return lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
6826 } else if (myFurtherLanes[i]->getBidiLane() == lane) {
6827#ifdef DEBUG_FURTHER
6828 if (DEBUG_COND) std::cout << " getCenterOnEdge veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " furtherLat(bidi)=" << myFurtherLanesPosLat[i]
6829 << " result=" << lane->getRightSideOnEdge() + myFurtherLanesPosLat[i] + 0.5 * lane->getWidth()
6830 << "\n";
6831#endif
6832 return lane->getRightSideOnEdge() - myFurtherLanesPosLat[i] + 0.5 * lane->getWidth();
6833 }
6834 }
6835 //if (DEBUG_COND) std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
6836 const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
6837 for (int i = 0; i < (int)shadowFurther.size(); ++i) {
6838 //if (DEBUG_COND) std::cout << " comparing i=" << (*i)->getID() << " lane=" << lane->getID() << "\n";
6839 if (shadowFurther[i] == lane) {
6840 assert(myLaneChangeModel->getShadowLane() != 0);
6841 return (lane->getRightSideOnEdge() + myLaneChangeModel->getShadowFurtherLanesPosLat()[i] + 0.5 * lane->getWidth()
6843 }
6844 }
6845 assert(false);
6846 throw ProcessError("Request lateral pos of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
6847 }
6848}
6849
6850
6851double
6853 assert(lane != 0);
6854 if (&lane->getEdge() == &myLane->getEdge()) {
6855 return myLane->getRightSideOnEdge() - lane->getRightSideOnEdge();
6856 } else if (myLane->getParallelOpposite() == lane) {
6857 return (myLane->getWidth() + lane->getWidth()) * 0.5 - 2 * getLateralPositionOnLane();
6858 } else if (myLane->getBidiLane() == lane) {
6859 return -2 * getLateralPositionOnLane();
6860 } else {
6861 // Check whether the lane is a further lane for the vehicle
6862 for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
6863 if (myFurtherLanes[i] == lane) {
6864#ifdef DEBUG_FURTHER
6865 if (DEBUG_COND) {
6866 std::cout << " getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherLat=" << myFurtherLanesPosLat[i] << "\n";
6867 }
6868#endif
6870 } else if (myFurtherLanes[i]->getBidiLane() == lane) {
6871#ifdef DEBUG_FURTHER
6872 if (DEBUG_COND) {
6873 std::cout << " getLatOffset veh=" << getID() << " lane=" << lane->getID() << " i=" << i << " posLat=" << myState.myPosLat << " furtherBidiLat=" << myFurtherLanesPosLat[i] << "\n";
6874 }
6875#endif
6876 return -2 * (myFurtherLanesPosLat[i] - myState.myPosLat);
6877 }
6878 }
6879#ifdef DEBUG_FURTHER
6880 if (DEBUG_COND) {
6881 std::cout << SIMTIME << " veh=" << getID() << " myShadowFurtherLanes=" << toString(myLaneChangeModel->getShadowFurtherLanes()) << "\n";
6882 }
6883#endif
6884 // Check whether the lane is a "shadow further lane" for the vehicle
6885 const std::vector<MSLane*>& shadowFurther = myLaneChangeModel->getShadowFurtherLanes();
6886 for (int i = 0; i < (int)shadowFurther.size(); ++i) {
6887 if (shadowFurther[i] == lane) {
6888#ifdef DEBUG_FURTHER
6889 if (DEBUG_COND) std::cout << " getLatOffset veh=" << getID()
6890 << " shadowLane=" << Named::getIDSecure(myLaneChangeModel->getShadowLane())
6891 << " lane=" << lane->getID()
6892 << " i=" << i
6893 << " posLat=" << myState.myPosLat
6894 << " shadowPosLat=" << getLatOffset(myLaneChangeModel->getShadowLane())
6895 << " shadowFurtherLat=" << myLaneChangeModel->getShadowFurtherLanesPosLat()[i]
6896 << "\n";
6897#endif
6899 }
6900 }
6901 // Check whether the vehicle issued a maneuverReservation on the lane.
6902 const std::vector<MSLane*>& furtherTargets = myLaneChangeModel->getFurtherTargetLanes();
6903 for (int i = 0; i < (int)myFurtherLanes.size(); ++i) {
6904 // Further target lanes are just neighboring lanes of the vehicle's further lanes, @see MSAbstractLaneChangeModel::updateTargetLane()
6905 MSLane* targetLane = furtherTargets[i];
6906 if (targetLane == lane) {
6907 const double targetDir = myLaneChangeModel->getManeuverDist() < 0 ? -1. : 1.;
6908 const double latOffset = myFurtherLanesPosLat[i] - myState.myPosLat + targetDir * 0.5 * (myFurtherLanes[i]->getWidth() + targetLane->getWidth());
6909#ifdef DEBUG_TARGET_LANE
6910 if (DEBUG_COND) {
6911 std::cout << " getLatOffset veh=" << getID()
6912 << " wrt targetLane=" << Named::getIDSecure(myLaneChangeModel->getTargetLane())
6913 << "\n i=" << i
6914 << " posLat=" << myState.myPosLat
6915 << " furtherPosLat=" << myFurtherLanesPosLat[i]
6916 << " maneuverDist=" << myLaneChangeModel->getManeuverDist()
6917 << " targetDir=" << targetDir
6918 << " latOffset=" << latOffset
6919 << std::endl;
6920 }
6921#endif
6922 return latOffset;
6923 }
6924 }
6925 assert(false);
6926 throw ProcessError("Request lateral offset of vehicle '" + getID() + "' for invalid lane '" + Named::getIDSecure(lane) + "'");
6927 }
6928}
6929
6930
6931double
6932MSVehicle::lateralDistanceToLane(const int offset) const {
6933 // compute the distance when changing to the neighboring lane
6934 // (ensure we do not lap into the line behind neighLane since there might be unseen blockers)
6935 assert(offset == 0 || offset == 1 || offset == -1);
6936 assert(myLane != nullptr);
6937 assert(myLane->getParallelLane(offset) != nullptr || myLane->getParallelOpposite() != nullptr);
6938 const double halfCurrentLaneWidth = 0.5 * myLane->getWidth();
6939 const double halfVehWidth = 0.5 * (getWidth() + NUMERICAL_EPS);
6940 const double latPos = getLateralPositionOnLane();
6941 const double oppositeSign = getLaneChangeModel().isOpposite() ? -1 : 1;
6942 double leftLimit = halfCurrentLaneWidth - halfVehWidth - oppositeSign * latPos;
6943 double rightLimit = -halfCurrentLaneWidth + halfVehWidth - oppositeSign * latPos;
6944 double latLaneDist = 0; // minimum distance to move the vehicle fully onto the new lane
6945 if (offset == 0) {
6946 if (latPos + halfVehWidth > halfCurrentLaneWidth) {
6947 // correct overlapping left
6948 latLaneDist = halfCurrentLaneWidth - latPos - halfVehWidth;
6949 } else if (latPos - halfVehWidth < -halfCurrentLaneWidth) {
6950 // correct overlapping right
6951 latLaneDist = -halfCurrentLaneWidth - latPos + halfVehWidth;
6952 }
6953 latLaneDist *= oppositeSign;
6954 } else if (offset == -1) {
6955 latLaneDist = rightLimit - (getWidth() + NUMERICAL_EPS);
6956 } else if (offset == 1) {
6957 latLaneDist = leftLimit + (getWidth() + NUMERICAL_EPS);
6958 }
6959#ifdef DEBUG_ACTIONSTEPS
6960 if (DEBUG_COND) {
6961 std::cout << SIMTIME
6962 << " veh=" << getID()
6963 << " halfCurrentLaneWidth=" << halfCurrentLaneWidth
6964 << " halfVehWidth=" << halfVehWidth
6965 << " latPos=" << latPos
6966 << " latLaneDist=" << latLaneDist
6967 << " leftLimit=" << leftLimit
6968 << " rightLimit=" << rightLimit
6969 << "\n";
6970 }
6971#endif
6972 return latLaneDist;
6973}
6974
6975
6976double
6977MSVehicle::getLateralOverlap(double posLat, const MSLane* lane) const {
6978 return (fabs(posLat) + 0.5 * getVehicleType().getWidth()
6979 - 0.5 * lane->getWidth());
6980}
6981
6982double
6986
6987double
6991
6992
6993void
6995 for (const DriveProcessItem& dpi : lfLinks) {
6996 if (dpi.myLink != nullptr) {
6997 dpi.myLink->removeApproaching(this);
6998 }
6999 }
7000 // unregister on all shadow links
7002}
7003
7004
7005bool
7006MSVehicle::unsafeLinkAhead(const MSLane* lane, double zipperDist) const {
7007 // the following links are unsafe:
7008 // - zipper links if they are close enough and have approaching vehicles in the relevant time range
7009 // - unprioritized links if the vehicle is currently approaching a prioritzed link and unable to stop in time
7010 double seen = myLane->getLength() - getPositionOnLane();
7011 const double dist = MAX2(zipperDist, getCarFollowModel().brakeGap(getSpeed(), getCarFollowModel().getMaxDecel(), 0));
7012 if (seen < dist) {
7013 const std::vector<MSLane*>& bestLaneConts = getBestLanesContinuation(lane);
7014 int view = 1;
7015 std::vector<MSLink*>::const_iterator link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
7016 DriveItemVector::const_iterator di = myLFLinkLanes.begin();
7017 while (!lane->isLinkEnd(link) && seen <= dist) {
7018 if ((!lane->isInternal()
7019 && (((*link)->getState() == LINKSTATE_ZIPPER && seen < (*link)->getFoeVisibilityDistance())
7020 || !(*link)->havePriority()))
7021 || (lane->isInternal() && zipperDist > 0)) {
7022 // find the drive item corresponding to this link
7023 bool found = false;
7024 while (di != myLFLinkLanes.end() && !found) {
7025 if ((*di).myLink != nullptr) {
7026 const MSLane* diPredLane = (*di).myLink->getLaneBefore();
7027 if (diPredLane != nullptr) {
7028 if (&diPredLane->getEdge() == &lane->getEdge()) {
7029 found = true;
7030 }
7031 }
7032 }
7033 if (!found) {
7034 di++;
7035 }
7036 }
7037 if (found) {
7038 const SUMOTime leaveTime = (*link)->getLeaveTime((*di).myArrivalTime, (*di).myArrivalSpeed,
7039 (*di).getLeaveSpeed(), getVehicleType().getLength());
7040 const MSLink* entry = (*link)->getCorrespondingEntryLink();
7041 //if (DEBUG_COND) {
7042 // std::cout << SIMTIME << " veh=" << getID() << " changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << " zipperDist=" << zipperDist << " aT=" << STEPS2TIME((*di).myArrivalTime) << " lT=" << STEPS2TIME(leaveTime) << "\n";
7043 //}
7044 if (entry->hasApproachingFoe((*di).myArrivalTime, leaveTime, (*di).myArrivalSpeed, getCarFollowModel().getMaxDecel())) {
7045 //std::cout << SIMTIME << " veh=" << getID() << " aborting changeTo=" << Named::getIDSecure(bestLaneConts.front()) << " linkState=" << toString((*link)->getState()) << " seen=" << seen << " dist=" << dist << "\n";
7046 return true;
7047 }
7048 }
7049 // no drive item is found if the vehicle aborts its request within dist
7050 }
7051 lane = (*link)->getViaLaneOrLane();
7052 if (!lane->getEdge().isInternal()) {
7053 view++;
7054 }
7055 seen += lane->getLength();
7056 link = MSLane::succLinkSec(*this, view, *lane, bestLaneConts);
7057 }
7058 }
7059 return false;
7060}
7061
7062
7064MSVehicle::getBoundingBox(double offset) const {
7065 PositionVector centerLine;
7066 Position pos = getPosition();
7067 centerLine.push_back(pos);
7068 switch (myType->getGuiShape()) {
7075 for (MSLane* lane : myFurtherLanes) {
7076 centerLine.push_back(lane->getShape().back());
7077 }
7078 break;
7079 }
7080 default:
7081 break;
7082 }
7083 double l = getLength();
7084 Position backPos = getBackPosition();
7085 if (pos.distanceTo2D(backPos) > l + NUMERICAL_EPS) {
7086 // getBackPosition may not match the visual back in networks without internal lanes
7087 double a = getAngle() + M_PI; // angle pointing backwards
7088 backPos = pos + Position(l * cos(a), l * sin(a));
7089 }
7090 centerLine.push_back(backPos);
7091 if (offset != 0) {
7092 centerLine.extrapolate2D(offset);
7093 }
7094 PositionVector result = centerLine;
7095 result.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
7096 centerLine.move2side(MIN2(0.0, -0.5 * myType->getWidth() - offset));
7097 result.append(centerLine.reverse(), POSITION_EPS);
7098 return result;
7099}
7100
7101
7103MSVehicle::getBoundingPoly(double offset) const {
7104 switch (myType->getGuiShape()) {
7110 // box with corners cut off
7111 PositionVector result;
7112 PositionVector centerLine;
7113 centerLine.push_back(getPosition());
7114 centerLine.push_back(getBackPosition());
7115 if (offset != 0) {
7116 centerLine.extrapolate2D(offset);
7117 }
7118 PositionVector line1 = centerLine;
7119 PositionVector line2 = centerLine;
7120 line1.move2side(MAX2(0.0, 0.3 * myType->getWidth() + offset));
7121 line2.move2side(MAX2(0.0, 0.5 * myType->getWidth() + offset));
7122 line2.scaleRelative(0.8);
7123 result.push_back(line1[0]);
7124 result.push_back(line2[0]);
7125 result.push_back(line2[1]);
7126 result.push_back(line1[1]);
7127 line1.move2side(MIN2(0.0, -0.6 * myType->getWidth() - offset));
7128 line2.move2side(MIN2(0.0, -1.0 * myType->getWidth() - offset));
7129 result.push_back(line1[1]);
7130 result.push_back(line2[1]);
7131 result.push_back(line2[0]);
7132 result.push_back(line1[0]);
7133 return result;
7134 }
7135 default:
7136 return getBoundingBox();
7137 }
7138}
7139
7140
7141bool
7143 for (std::vector<MSLane*>::const_iterator i = myFurtherLanes.begin(); i != myFurtherLanes.end(); ++i) {
7144 if (&(*i)->getEdge() == edge) {
7145 return true;
7146 }
7147 }
7148 return false;
7149}
7150
7151
7152bool
7153MSVehicle::isBidiOn(const MSLane* lane) const {
7154 return lane->getBidiLane() != nullptr && (
7155 myLane == lane->getBidiLane()
7156 || onFurtherEdge(&lane->getBidiLane()->getEdge()));
7157}
7158
7159
7160bool
7161MSVehicle::rerouteParkingArea(const std::string& parkingAreaID, std::string& errorMsg) {
7162 // this function is based on MSTriggeredRerouter::rerouteParkingArea in order to keep
7163 // consistency in the behaviour.
7164
7165 // get vehicle params
7166 MSParkingArea* destParkArea = getNextParkingArea();
7167 const MSRoute& route = getRoute();
7168 const MSEdge* lastEdge = route.getLastEdge();
7169
7170 if (destParkArea == nullptr) {
7171 // not driving towards a parking area
7172 errorMsg = "Vehicle " + getID() + " is not driving to a parking area so it cannot be rerouted.";
7173 return false;
7174 }
7175
7176 // if the current route ends at the parking area, the new route will also and at the new area
7177 bool newDestination = (&destParkArea->getLane().getEdge() == route.getLastEdge()
7178 && getArrivalPos() >= destParkArea->getBeginLanePosition()
7179 && getArrivalPos() <= destParkArea->getEndLanePosition());
7180
7181 // retrieve info on the new parking area
7183 parkingAreaID, SumoXMLTag::SUMO_TAG_PARKING_AREA);
7184
7185 if (newParkingArea == nullptr) {
7186 errorMsg = "Parking area ID " + toString(parkingAreaID) + " not found in the network.";
7187 return false;
7188 }
7189
7190 const MSEdge* newEdge = &(newParkingArea->getLane().getEdge());
7192
7193 // Compute the route from the current edge to the parking area edge
7194 ConstMSEdgeVector edgesToPark;
7195 router.compute(getEdge(), newEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesToPark);
7196
7197 // Compute the route from the parking area edge to the end of the route
7198 ConstMSEdgeVector edgesFromPark;
7199 if (!newDestination) {
7200 router.compute(newEdge, lastEdge, this, MSNet::getInstance()->getCurrentTimeStep(), edgesFromPark);
7201 } else {
7202 // adapt plans of any riders
7203 for (MSTransportable* p : getPersons()) {
7204 p->rerouteParkingArea(getNextParkingArea(), newParkingArea);
7205 }
7206 }
7207
7208 // we have a new destination, let's replace the vehicle route
7209 ConstMSEdgeVector edges = edgesToPark;
7210 if (edgesFromPark.size() > 0) {
7211 edges.insert(edges.end(), edgesFromPark.begin() + 1, edgesFromPark.end());
7212 }
7213
7214 if (newDestination) {
7215 SUMOVehicleParameter* newParameter = new SUMOVehicleParameter();
7216 *newParameter = getParameter();
7218 newParameter->arrivalPos = newParkingArea->getEndLanePosition();
7219 replaceParameter(newParameter);
7220 }
7221 const double routeCost = router.recomputeCosts(edges, this, MSNet::getInstance()->getCurrentTimeStep());
7222 ConstMSEdgeVector prevEdges(myCurrEdge, myRoute->end());
7223 const double savings = router.recomputeCosts(prevEdges, this, MSNet::getInstance()->getCurrentTimeStep());
7224 if (replaceParkingArea(newParkingArea, errorMsg)) {
7225 const bool onInit = myLane == nullptr;
7226 replaceRouteEdges(edges, routeCost, savings, "TraCI:" + toString(SUMO_TAG_PARKING_AREA_REROUTE), onInit, false, false);
7227 } else {
7228 WRITE_WARNING("Vehicle '" + getID() + "' could not reroute to new parkingArea '" + newParkingArea->getID()
7229 + "' reason=" + errorMsg + ", time=" + time2string(MSNet::getInstance()->getCurrentTimeStep()) + ".");
7230 return false;
7231 }
7232 return true;
7233}
7234
7235
7236bool
7238 const int numStops = (int)myStops.size();
7239 const bool result = MSBaseVehicle::addTraciStop(stop, errorMsg);
7240 if (myLane != nullptr && numStops != (int)myStops.size()) {
7241 updateBestLanes(true);
7242 }
7243 return result;
7244}
7245
7246
7247bool
7248MSVehicle::handleCollisionStop(MSStop& stop, const double distToStop) {
7249 if (myCurrEdge == stop.edge && distToStop + POSITION_EPS < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getMaxDecel(), 0)) {
7250 if (distToStop < getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)) {
7251 double vNew = getCarFollowModel().maximumSafeStopSpeed(distToStop, getCarFollowModel().getMaxDecel(), getSpeed(), false, 0);
7252 //std::cout << SIMTIME << " veh=" << getID() << " v=" << myState.mySpeed << " distToStop=" << distToStop
7253 // << " vMinNex=" << getCarFollowModel().minNextSpeed(getSpeed(), this)
7254 // << " bg1=" << getCarFollowModel().brakeGap(myState.mySpeed)
7255 // << " bg2=" << getCarFollowModel().brakeGap(myState.mySpeed, getCarFollowModel().getEmergencyDecel(), 0)
7256 // << " vNew=" << vNew
7257 // << "\n";
7258 myState.mySpeed = MIN2(myState.mySpeed, vNew + ACCEL2SPEED(getCarFollowModel().getEmergencyDecel()));
7261 if (myState.myPos < myType->getLength()) {
7265 myAngle += M_PI;
7266 }
7267 }
7268 }
7269 }
7270 return true;
7271}
7272
7273
7274bool
7276 if (isStopped()) {
7280 }
7281 MSStop& stop = myStops.front();
7282 // we have waited long enough and fulfilled any passenger-requirements
7283 if (stop.busstop != nullptr) {
7284 // inform bus stop about leaving it
7285 stop.busstop->leaveFrom(this);
7286 }
7287 // we have waited long enough and fulfilled any container-requirements
7288 if (stop.containerstop != nullptr) {
7289 // inform container stop about leaving it
7290 stop.containerstop->leaveFrom(this);
7291 }
7292 if (stop.parkingarea != nullptr && stop.getSpeed() <= 0) {
7293 // inform parking area about leaving it
7294 stop.parkingarea->leaveFrom(this);
7295 }
7296 if (stop.chargingStation != nullptr) {
7297 // inform charging station about leaving it
7298 stop.chargingStation->leaveFrom(this);
7299 }
7300 // the current stop is no longer valid
7301 myLane->getEdge().removeWaiting(this);
7302 // MSStopOut needs to know whether the stop had a loaded 'ended' value so we call this before replacing the value
7303 if (stop.pars.started == -1) {
7304 // waypoint edge was passed in a single step
7306 }
7307 if (MSStopOut::active()) {
7308 MSStopOut::getInstance()->stopEnded(this, stop.pars, stop.lane->getID());
7309 }
7311 for (const auto& rem : myMoveReminders) {
7312 rem.first->notifyStopEnded();
7313 }
7315 myCollisionImmunity = TIME2STEPS(5); // leave the conflict area
7316 }
7318 // reset lateral position to default
7319 myState.myPosLat = 0;
7320 }
7321 myPastStops.push_back(stop.pars);
7322 myPastStops.back().routeIndex = (int)(stop.edge - myRoute->begin());
7323 myStops.pop_front();
7324 myStopDist = std::numeric_limits<double>::max();
7325 // do not count the stopping time towards gridlock time.
7326 // Other outputs use an independent counter and are not affected.
7327 myWaitingTime = 0;
7328 // maybe the next stop is on the same edge; let's rebuild best lanes
7329 updateBestLanes(true);
7330 // continue as wished...
7333 return true;
7334 }
7335 return false;
7336}
7337
7338
7341 if (myInfluencer == nullptr) {
7342 myInfluencer = new Influencer();
7343 }
7344 return *myInfluencer;
7345}
7346
7351
7352
7355 return myInfluencer;
7356}
7357
7360 return myInfluencer;
7361}
7362
7363
7364double
7366 if (myInfluencer != nullptr && myInfluencer->getOriginalSpeed() >= 0) {
7367 // influencer original speed is -1 on initialization
7369 }
7370 return myState.mySpeed;
7371}
7372
7373
7374int
7376 if (hasInfluencer()) {
7378 MSNet::getInstance()->getCurrentTimeStep(),
7379 myLane->getEdge(),
7380 getLaneIndex(),
7381 state);
7382 }
7383 return state;
7384}
7385
7386
7387void
7391
7392
7393bool
7397
7398
7399bool
7403
7404
7405bool
7406MSVehicle::keepClear(const MSLink* link) const {
7407 if (link->hasFoes() && link->keepClear() /* && item.myLink->willHaveBlockedFoe()*/) {
7408 const double keepClearTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME, -1);
7409 //std::cout << SIMTIME << " veh=" << getID() << " keepClearTime=" << keepClearTime << " accWait=" << getAccumulatedWaitingSeconds() << " keepClear=" << (keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime) << "\n";
7410 return keepClearTime < 0 || getAccumulatedWaitingSeconds() < keepClearTime;
7411 } else {
7412 return false;
7413 }
7414}
7415
7416
7417bool
7418MSVehicle::ignoreRed(const MSLink* link, bool canBrake) const {
7419 if ((myInfluencer != nullptr && !myInfluencer->getEmergencyBrakeRedLight())) {
7420 return true;
7421 }
7422 const double ignoreRedTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME, -1);
7423#ifdef DEBUG_IGNORE_RED
7424 if (DEBUG_COND) {
7425 std::cout << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID() << " state=" << toString(link->getState()) << "\n";
7426 }
7427#endif
7428 if (ignoreRedTime < 0) {
7429 const double ignoreYellowTime = getVehicleType().getParameter().getJMParam(SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME, 0);
7430 if (ignoreYellowTime > 0 && link->haveYellow()) {
7431 assert(link->getTLLogic() != 0);
7432 const double yellowDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
7433 // when activating ignoreYellow behavior, vehicles will drive if they cannot brake
7434 return !canBrake || ignoreYellowTime > yellowDuration;
7435 } else {
7436 return false;
7437 }
7438 } else if (link->haveYellow()) {
7439 // always drive at yellow when ignoring red
7440 return true;
7441 } else if (link->haveRed()) {
7442 assert(link->getTLLogic() != 0);
7443 const double redDuration = STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep() - link->getLastStateChange());
7444#ifdef DEBUG_IGNORE_RED
7445 if (DEBUG_COND) {
7446 std::cout
7447 // << SIMTIME << " veh=" << getID() << " link=" << link->getViaLaneOrLane()->getID()
7448 << " ignoreRedTime=" << ignoreRedTime
7449 << " spentRed=" << redDuration
7450 << " canBrake=" << canBrake << "\n";
7451 }
7452#endif
7453 // when activating ignoreRed behavior, vehicles will always drive if they cannot brake
7454 return !canBrake || ignoreRedTime > redDuration;
7455 } else {
7456 return false;
7457 }
7458}
7459
7460bool
7463 return false;
7464 }
7465 for (const std::string& typeID : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_TYPES), "")).getVector()) {
7466 if (typeID == foe->getVehicleType().getID()) {
7467 return true;
7468 }
7469 }
7470 for (const std::string& id : StringTokenizer(getParameter().getParameter(toString(SUMO_ATTR_CF_IGNORE_IDS), "")).getVector()) {
7471 if (id == foe->getID()) {
7472 return true;
7473 }
7474 }
7475 return false;
7476}
7477
7478bool
7480 // either on an internal lane that was entered via minor link
7481 // or on approach to minor link below visibility distance
7482 if (myLane == nullptr) {
7483 return false;
7484 }
7485 if (myLane->getEdge().isInternal()) {
7486 return !myLane->getIncomingLanes().front().viaLink->havePriority();
7487 } else if (myLFLinkLanes.size() > 0 && myLFLinkLanes.front().myLink != nullptr) {
7488 MSLink* link = myLFLinkLanes.front().myLink;
7489 return !link->havePriority() && myLFLinkLanes.front().myDistance <= link->getFoeVisibilityDistance();
7490 }
7491 return false;
7492}
7493
7494bool
7495MSVehicle::isLeader(const MSLink* link, const MSVehicle* veh, const double gap) const {
7496 assert(link->fromInternalLane());
7497 if (veh == nullptr) {
7498 return false;
7499 }
7500 if (!myLane->isInternal() || myLane->getEdge().getToJunction() != link->getJunction()) {
7501 // if this vehicle is not yet on the junction, every vehicle is a leader
7502 return true;
7503 }
7504 if (veh->getLaneChangeModel().hasBlueLight()) {
7505 // blue light device automatically gets right of way
7506 return true;
7507 }
7508 const MSLane* foeLane = veh->getLane();
7509 if (foeLane->isInternal()) {
7510 if (foeLane->getEdge().getFromJunction() == link->getJunction()) {
7512 SUMOTime foeET = veh->myJunctionEntryTime;
7513 // check relationship between link and foeLane
7515 // we are entering the junction from the same lane
7517 foeET = veh->myJunctionEntryTimeNeverYield;
7520 }
7521 } else {
7522 const MSLink* foeLink = foeLane->getIncomingLanes()[0].viaLink;
7523 const MSJunctionLogic* logic = link->getJunction()->getLogic();
7524 assert(logic != nullptr);
7525 // determine who has right of way
7526 bool response; // ego response to foe
7527 bool response2; // foe response to ego
7528 // attempt 1: tlLinkState
7529 const MSLink* entry = link->getCorrespondingEntryLink();
7530 const MSLink* foeEntry = foeLink->getCorrespondingEntryLink();
7531 if (entry->haveRed() || foeEntry->haveRed()) {
7532 // ensure that vehicles which are stuck on the intersection may exit
7533 if (!foeEntry->haveRed() && veh->getSpeed() > SUMO_const_haltingSpeed && gap < 0) {
7534 // foe might be oncoming, don't drive unless foe can still brake safely
7535 const double foeNextSpeed = veh->getSpeed() + ACCEL2SPEED(veh->getCarFollowModel().getMaxAccel());
7536 const double foeBrakeGap = veh->getCarFollowModel().brakeGap(
7537 foeNextSpeed, veh->getCarFollowModel().getMaxDecel(), veh->getCarFollowModel().getHeadwayTime());
7538 // the minGap was subtracted from gap in MSLink::getLeaderInfo (enlarging the negative gap)
7539 // so the -2* makes it point in the right direction
7540 const double foeGap = -gap - veh->getLength() - 2 * getVehicleType().getMinGap();
7541#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7542 if (DEBUG_COND) {
7543 std::cout << " foeGap=" << foeGap << " foeBGap=" << foeBrakeGap << "\n";
7544
7545 }
7546#endif
7547 if (foeGap < foeBrakeGap) {
7548 response = true;
7549 response2 = false;
7550 } else {
7551 response = false;
7552 response2 = true;
7553 }
7554 } else {
7555 // brake for stuck foe
7556 response = foeEntry->haveRed();
7557 response2 = entry->haveRed();
7558 }
7559 } else if (entry->havePriority() != foeEntry->havePriority()) {
7560 response = !entry->havePriority();
7561 response2 = !foeEntry->havePriority();
7562 } else if (entry->haveYellow() && foeEntry->haveYellow()) {
7563 // let the faster vehicle keep moving
7564 response = veh->getSpeed() >= getSpeed();
7565 response2 = getSpeed() >= veh->getSpeed();
7566 } else {
7567 // fallback if pedestrian crossings are involved
7568 response = logic->getResponseFor(link->getIndex()).test(foeLink->getIndex());
7569 response2 = logic->getResponseFor(foeLink->getIndex()).test(link->getIndex());
7570 }
7571#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7572 if (DEBUG_COND) {
7573 std::cout << SIMTIME
7574 << " foeLane=" << foeLane->getID()
7575 << " foeLink=" << foeLink->getViaLaneOrLane()->getID()
7576 << " linkIndex=" << link->getIndex()
7577 << " foeLinkIndex=" << foeLink->getIndex()
7578 << " entryState=" << toString(entry->getState())
7579 << " entryState2=" << toString(foeEntry->getState())
7580 << " response=" << response
7581 << " response2=" << response2
7582 << "\n";
7583 }
7584#endif
7585 if (!response) {
7586 // if we have right of way over the foe, entryTime does not matter
7587 foeET = veh->myJunctionConflictEntryTime;
7588 egoET = myJunctionEntryTime;
7589 } else if (response && response2) {
7590 // in a mutual conflict scenario, use entry time to avoid deadlock
7591 foeET = veh->myJunctionConflictEntryTime;
7593 }
7594 }
7595 if (egoET == foeET) {
7596 // try to use speed as tie braker
7597 if (getSpeed() == veh->getSpeed()) {
7598 // use ID as tie braker
7599#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7600 if (DEBUG_COND) {
7601 std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
7602 << " foeIsLeaderByID=" << (getID() < veh->getID()) << "\n";
7603 }
7604#endif
7605 return getID() < veh->getID();
7606 } else {
7607#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7608 if (DEBUG_COND) {
7609 std::cout << SIMTIME << " veh=" << getID() << " equal ET " << egoET << " with foe " << veh->getID()
7610 << " foeIsLeaderBySpeed=" << (getSpeed() < veh->getSpeed())
7611 << " v=" << getSpeed() << " foeV=" << veh->getSpeed()
7612 << "\n";
7613 }
7614#endif
7615 return getSpeed() < veh->getSpeed();
7616 }
7617 } else {
7618 // leader was on the junction first
7619#ifdef DEBUG_PLAN_MOVE_LEADERINFO
7620 if (DEBUG_COND) {
7621 std::cout << SIMTIME << " veh=" << getID() << " egoET " << egoET << " with foe " << veh->getID()
7622 << " foeET=" << foeET << " isLeader=" << (egoET > foeET) << "\n";
7623 }
7624#endif
7625 return egoET > foeET;
7626 }
7627 } else {
7628 // vehicle can only be partially on the junction. Must be a leader
7629 return true;
7630 }
7631 } else {
7632 // vehicle can only be partially on the junction. Must be a leader
7633 return true;
7634 }
7635}
7636
7637void
7640 // here starts the vehicle internal part (see loading)
7641 std::vector<std::string> internals;
7642 internals.push_back(toString(myParameter->parametersSet));
7643 internals.push_back(toString(myDeparture));
7644 internals.push_back(toString(distance(myRoute->begin(), myCurrEdge)));
7645 internals.push_back(toString(myDepartPos));
7646 internals.push_back(toString(myWaitingTime));
7647 internals.push_back(toString(myTimeLoss));
7648 internals.push_back(toString(myLastActionTime));
7649 internals.push_back(toString(isStopped()));
7650 internals.push_back(toString(myPastStops.size()));
7651 out.writeAttr(SUMO_ATTR_STATE, internals);
7653 out.writeAttr(SUMO_ATTR_SPEED, std::vector<double> { myState.mySpeed, myState.myPreviousSpeed });
7658 // save past stops
7660 stop.write(out, false);
7661 // do not write started and ended twice
7662 if ((stop.parametersSet & STOP_STARTED_SET) == 0) {
7663 out.writeAttr(SUMO_ATTR_STARTED, time2string(stop.started));
7664 }
7665 if ((stop.parametersSet & STOP_ENDED_SET) == 0) {
7666 out.writeAttr(SUMO_ATTR_ENDED, time2string(stop.ended));
7667 }
7668 stop.writeParams(out);
7669 out.closeTag();
7670 }
7671 // save upcoming stops
7672 for (MSStop& stop : myStops) {
7673 stop.write(out);
7674 }
7675 // save parameters and device states
7677 for (MSVehicleDevice* const dev : myDevices) {
7678 dev->saveState(out);
7679 }
7680 out.closeTag();
7681}
7682
7683void
7685 if (!attrs.hasAttribute(SUMO_ATTR_POSITION)) {
7686 throw ProcessError(TL("Error: Invalid vehicles in state (may be a meso state)!"));
7687 }
7688 int routeOffset;
7689 bool stopped;
7690 int pastStops;
7691
7692 std::istringstream bis(attrs.getString(SUMO_ATTR_STATE));
7693 bis >> myParameter->parametersSet;
7694 bis >> myDeparture;
7695 bis >> routeOffset;
7696 bis >> myDepartPos;
7697 bis >> myWaitingTime;
7698 bis >> myTimeLoss;
7699 bis >> myLastActionTime;
7700 bis >> stopped;
7701 bis >> pastStops;
7702
7704 bool ok;
7705 myArrivalPos = attrs.get<double>(SUMO_ATTR_ARRIVALPOS_RANDOMIZED, getID().c_str(), ok);
7706 }
7707 // load stops
7708 myStops.clear();
7710
7711 if (hasDeparted()) {
7712 myCurrEdge = myRoute->begin() + routeOffset;
7713 myDeparture -= offset;
7714 // fix stops
7715 while (pastStops > 0) {
7716 myPastStops.push_back(myStops.front().pars);
7717 myPastStops.back().routeIndex = (int)(myStops.front().edge - myRoute->begin());
7718 myStops.pop_front();
7719 pastStops--;
7720 }
7721 // see MSBaseVehicle constructor
7724 }
7725 }
7728 WRITE_WARNINGF(TL("Action steps are out of sync for loaded vehicle '%'."), getID());
7729 }
7730 std::istringstream pis(attrs.getString(SUMO_ATTR_POSITION));
7732 std::istringstream sis(attrs.getString(SUMO_ATTR_SPEED));
7737 std::istringstream dis(attrs.getString(SUMO_ATTR_DISTANCE));
7738 dis >> myOdometer >> myNumberReroutes;
7740 if (stopped) {
7741 myStops.front().startedFromState = true;
7742 myStopDist = 0;
7743 }
7745 // no need to reset myCachedPosition here since state loading happens directly after creation
7746}
7747
7748void
7750 SUMOTime arrivalTime, double arrivalSpeed,
7751 double arrivalSpeedBraking,
7752 double dist, double leaveSpeed) {
7753 // ensure that approach information is reset on the next call to setApproachingForAllLinks
7754 myLFLinkLanes.push_back(DriveProcessItem(link, 0, 0, setRequest,
7755 arrivalTime, arrivalSpeed, arrivalSpeedBraking, dist, leaveSpeed));
7756
7757}
7758
7759
7760std::shared_ptr<MSSimpleDriverState>
7764
7765
7766double
7768 return myFrictionDevice == nullptr ? 1. : myFrictionDevice->getMeasuredFriction();
7769}
7770
7771
7772void
7773MSVehicle::setPreviousSpeed(double prevSpeed, double prevAcceleration) {
7774 myState.mySpeed = MAX2(0., prevSpeed);
7775 // also retcon acceleration
7776 if (prevAcceleration != std::numeric_limits<double>::min()) {
7777 myAcceleration = prevAcceleration;
7778 } else {
7780 }
7781}
7782
7783
7784double
7786 //return MAX2(-myAcceleration, getCarFollowModel().getApparentDecel());
7788}
7789
7790/****************************************************************************/
7791bool
7795
7796/* -------------------------------------------------------------------------
7797 * methods of MSVehicle::manoeuvre
7798 * ----------------------------------------------------------------------- */
7799
7800MSVehicle::Manoeuvre::Manoeuvre() : myManoeuvreStop(""), myManoeuvreStartTime(0), myManoeuvreCompleteTime(0), myManoeuvreType(MSVehicle::MANOEUVRE_NONE), myGUIIncrement(0) {}
7801
7802
7804 myManoeuvreStop = manoeuvre.myManoeuvreStop;
7805 myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
7806 myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
7807 myManoeuvreType = manoeuvre.myManoeuvreType;
7808 myGUIIncrement = manoeuvre.myGUIIncrement;
7809}
7810
7811
7814 myManoeuvreStop = manoeuvre.myManoeuvreStop;
7815 myManoeuvreStartTime = manoeuvre.myManoeuvreStartTime;
7816 myManoeuvreCompleteTime = manoeuvre.myManoeuvreCompleteTime;
7817 myManoeuvreType = manoeuvre.myManoeuvreType;
7818 myGUIIncrement = manoeuvre.myGUIIncrement;
7819 return *this;
7820}
7821
7822
7823bool
7825 return (myManoeuvreStop != manoeuvre.myManoeuvreStop ||
7826 myManoeuvreStartTime != manoeuvre.myManoeuvreStartTime ||
7827 myManoeuvreCompleteTime != manoeuvre.myManoeuvreCompleteTime ||
7828 myManoeuvreType != manoeuvre.myManoeuvreType ||
7829 myGUIIncrement != manoeuvre.myGUIIncrement
7830 );
7831}
7832
7833
7834double
7836 return (myGUIIncrement);
7837}
7838
7839
7842 return (myManoeuvreType);
7843}
7844
7845
7850
7851
7852void
7856
7857
7858void
7860 myManoeuvreType = mType;
7861}
7862
7863
7864bool
7866 if (!veh->hasStops()) {
7867 return false; // should never happen - checked before call
7868 }
7869
7870 const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
7871 const MSStop& stop = veh->getNextStop();
7872
7873 int manoeuverAngle = stop.parkingarea->getLastFreeLotAngle();
7874 double GUIAngle = stop.parkingarea->getLastFreeLotGUIAngle();
7875 if (abs(GUIAngle) < 0.1) {
7876 GUIAngle = -0.1; // Wiggle vehicle on parallel entry
7877 }
7878 myManoeuvreVehicleID = veh->getID();
7879 myManoeuvreStop = stop.parkingarea->getID();
7880 myManoeuvreType = MSVehicle::MANOEUVRE_ENTRY;
7881 myManoeuvreStartTime = currentTime;
7882 myManoeuvreCompleteTime = currentTime + veh->myType->getEntryManoeuvreTime(manoeuverAngle);
7883 myGUIIncrement = GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
7884
7885#ifdef DEBUG_STOPS
7886 if (veh->isSelected()) {
7887 std::cout << "ENTRY manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle << " Rotation angle=" << RAD2DEG(GUIAngle) << " Road Angle" << RAD2DEG(veh->getAngle()) << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime <<
7888 " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
7889 }
7890#endif
7891
7892 return (true);
7893}
7894
7895
7896bool
7898 // At the moment we only want to set for parking areas
7899 if (!veh->hasStops()) {
7900 return true;
7901 }
7902 if (veh->getNextStop().parkingarea == nullptr) {
7903 return true;
7904 }
7905
7906 if (myManoeuvreType != MSVehicle::MANOEUVRE_NONE) {
7907 return (false);
7908 }
7909
7910 const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
7911
7912 int manoeuverAngle = veh->getCurrentParkingArea()->getManoeuverAngle(*veh);
7913 double GUIAngle = veh->getCurrentParkingArea()->getGUIAngle(*veh);
7914 if (abs(GUIAngle) < 0.1) {
7915 GUIAngle = 0.1; // Wiggle vehicle on parallel exit
7916 }
7917
7918 myManoeuvreVehicleID = veh->getID();
7919 myManoeuvreStop = veh->getCurrentParkingArea()->getID();
7920 myManoeuvreType = MSVehicle::MANOEUVRE_EXIT;
7921 myManoeuvreStartTime = currentTime;
7922 myManoeuvreCompleteTime = currentTime + veh->myType->getExitManoeuvreTime(manoeuverAngle);
7923 myGUIIncrement = -GUIAngle / (STEPS2TIME(myManoeuvreCompleteTime - myManoeuvreStartTime) / TS);
7924 if (veh->remainingStopDuration() > 0) {
7925 myManoeuvreCompleteTime += veh->remainingStopDuration();
7926 }
7927
7928#ifdef DEBUG_STOPS
7929 if (veh->isSelected()) {
7930 std::cout << "EXIT manoeuvre start: vehicle=" << veh->getID() << " Manoeuvre Angle=" << manoeuverAngle << " increment=" << RAD2DEG(myGUIIncrement) << " currentTime=" << currentTime
7931 << " endTime=" << myManoeuvreCompleteTime << " manoeuvre time=" << myManoeuvreCompleteTime - currentTime << " parkArea=" << myManoeuvreStop << std::endl;
7932 }
7933#endif
7934
7935 return (true);
7936}
7937
7938
7939bool
7941 // At the moment we only want to consider parking areas - need to check because we could be setting up a manoeuvre
7942 if (!veh->hasStops()) {
7943 return (true);
7944 }
7945 MSStop* currentStop = &veh->myStops.front();
7946 if (currentStop->parkingarea == nullptr) {
7947 return true;
7948 } else if (currentStop->parkingarea->getID() != myManoeuvreStop || MSVehicle::MANOEUVRE_ENTRY != myManoeuvreType) {
7949 if (configureEntryManoeuvre(veh)) {
7951 return (false);
7952 } else { // cannot configure entry so stop trying
7953 return true;
7954 }
7955 } else if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
7956 return false;
7957 } else { // manoeuvre complete
7958 myManoeuvreType = MSVehicle::MANOEUVRE_NONE;
7959 return true;
7960 }
7961}
7962
7963
7964bool
7966 if (checkType != myManoeuvreType) {
7967 return true; // we're not maneuvering / wrong manoeuvre
7968 }
7969
7970 if (MSNet::getInstance()->getCurrentTimeStep() < myManoeuvreCompleteTime) {
7971 return false;
7972 } else {
7973 return true;
7974 }
7975}
7976
7977
7978bool
7980 return (MSNet::getInstance()->getCurrentTimeStep() >= myManoeuvreCompleteTime);
7981}
7982
7983
7984bool
7988
7989
7990std::pair<double, double>
7992 if (hasStops()) {
7993 MSLane* lane = myLane;
7994 if (lane == nullptr) {
7995 // not in network
7996 lane = getEdge()->getLanes()[0];
7997 }
7998 const MSStop& stop = myStops.front();
7999 auto it = myCurrEdge + 1;
8000 // drive to end of current edge
8001 double dist = (lane->getLength() - getPositionOnLane());
8002 double travelTime = lane->getEdge().getMinimumTravelTime(this) * dist / lane->getLength();
8003 // drive until stop edge
8004 while (it != myRoute->end() && it < stop.edge) {
8005 travelTime += (*it)->getMinimumTravelTime(this);
8006 dist += (*it)->getLength();
8007 it++;
8008 }
8009 // drive up to the stop position
8010 const double stopEdgeDist = stop.pars.endPos - (lane == stop.lane ? lane->getLength() : 0);
8011 dist += stopEdgeDist;
8012 travelTime += stop.lane->getEdge().getMinimumTravelTime(this) * (stopEdgeDist / stop.lane->getLength());
8013 // estimate time loss due to acceleration and deceleration
8014 // maximum speed is limited by available distance:
8015 const double a = getCarFollowModel().getMaxAccel();
8016 const double b = getCarFollowModel().getMaxDecel();
8017 const double c = getSpeed();
8018 const double d = dist;
8019 const double len = getVehicleType().getLength();
8020 const double vs = MIN2(MAX2(stop.getSpeed(), 0.0), stop.lane->getVehicleMaxSpeed(this));
8021 // distAccel = (v - c)^2 / (2a)
8022 // distDecel = (v + vs)*(v - vs) / 2b = (v^2 - vs^2) / (2b)
8023 // distAccel + distDecel < d
8024 const double maxVD = MAX2(c, ((sqrt(MAX2(0.0, pow(2 * c * b, 2) + (4 * ((b * ((a * (2 * d * (b + a) + (vs * vs) - (c * c))) - (b * (c * c))))
8025 + pow((a * vs), 2))))) * 0.5) + (c * b)) / (b + a));
8026 it = myCurrEdge;
8027 double v0 = c;
8028 bool v0Stable = getAcceleration() == 0 && v0 > 0;
8029 double timeLossAccel = 0;
8030 double timeLossDecel = 0;
8031 double timeLossLength = 0;
8032 while (it != myRoute->end() && it <= stop.edge) {
8033 double v = MIN2(maxVD, (*it)->getVehicleMaxSpeed(this));
8034 double edgeLength = (it == stop.edge ? stop.pars.endPos : (*it)->getLength()) - (it == myCurrEdge ? getPositionOnLane() : 0);
8035 if (edgeLength <= len && v0Stable && v0 < v) {
8036 const double lengthDist = MIN2(len, edgeLength);
8037 const double dTL = lengthDist / v0 - lengthDist / v;
8038 //std::cout << " e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " el=" << edgeLength << " lDist=" << lengthDist << " newTLL=" << dTL<< "\n";
8039 timeLossLength += dTL;
8040 }
8041 if (edgeLength > len) {
8042 const double dv = v - v0;
8043 if (dv > 0) {
8044 // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
8045 const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
8046 //std::cout << " e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
8047 timeLossAccel += dTA;
8048 // time loss from vehicle length
8049 } else if (dv < 0) {
8050 // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
8051 const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
8052 //std::cout << " e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
8053 timeLossDecel += dTD;
8054 }
8055 v0 = v;
8056 v0Stable = true;
8057 }
8058 it++;
8059 }
8060 // final deceleration to stop (may also be acceleration or deceleration to waypoint speed)
8061 double v = vs;
8062 const double dv = v - v0;
8063 if (dv > 0) {
8064 // timeLossAccel = timeAccel - timeMaxspeed = dv / a - distAccel / v
8065 const double dTA = dv / a - dv * (v + v0) / (2 * a * v);
8066 //std::cout << " final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLA=" << dTA << "\n";
8067 timeLossAccel += dTA;
8068 // time loss from vehicle length
8069 } else if (dv < 0) {
8070 // timeLossDecel = timeDecel - timeMaxspeed = dv / b - distDecel / v
8071 const double dTD = -dv / b + dv * (v + v0) / (2 * b * v0);
8072 //std::cout << " final e=" << (*it)->getID() << " v0=" << v0 << " v=" << v << " newTLD=" << dTD << "\n";
8073 timeLossDecel += dTD;
8074 }
8075 const double result = travelTime + timeLossAccel + timeLossDecel + timeLossLength;
8076 //std::cout << SIMTIME << " v=" << c << " a=" << a << " b=" << b << " maxVD=" << maxVD << " tt=" << travelTime
8077 // << " ta=" << timeLossAccel << " td=" << timeLossDecel << " tl=" << timeLossLength << " res=" << result << "\n";
8078 return {MAX2(0.0, result), dist};
8079 } else {
8081 }
8082}
8083
8084
8085double
8087 if (hasStops() && myStops.front().pars.until >= 0) {
8088 const MSStop& stop = myStops.front();
8089 SUMOTime estimatedDepart = MSNet::getInstance()->getCurrentTimeStep() - DELTA_T;
8090 if (stop.reached) {
8091 return STEPS2TIME(estimatedDepart + stop.duration - stop.pars.until);
8092 }
8093 if (stop.pars.duration > 0) {
8094 estimatedDepart += stop.pars.duration;
8095 }
8096 estimatedDepart += TIME2STEPS(estimateTimeToNextStop().first);
8097 const double result = MAX2(0.0, STEPS2TIME(estimatedDepart - stop.pars.until));
8098 return result;
8099 } else {
8100 // vehicles cannot drive before 'until' so stop delay can never be
8101 // negative and we can use -1 to signal "undefined"
8102 return -1;
8103 }
8104}
8105
8106
8107double
8109 if (hasStops() && myStops.front().pars.arrival >= 0) {
8110 const MSStop& stop = myStops.front();
8111 if (stop.reached) {
8112 return STEPS2TIME(stop.pars.started - stop.pars.arrival);
8113 } else {
8114 return STEPS2TIME(MSNet::getInstance()->getCurrentTimeStep()) + estimateTimeToNextStop().first - STEPS2TIME(stop.pars.arrival);
8115 }
8116 } else {
8117 // vehicles can arrival earlier than planned so arrival delay can be negative
8118 return INVALID_DOUBLE;
8119 }
8120}
8121
8122
8123const MSEdge*
8125 return myLane != nullptr ? &myLane->getEdge() : getEdge();
8126}
8127
8128
8129const MSEdge*
8131 if (myLane == nullptr || (myCurrEdge + 1) == myRoute->end()) {
8132 return nullptr;
8133 }
8134 if (myLane->isInternal()) {
8136 } else {
8137 const MSEdge* nextNormal = succEdge(1);
8138 const MSEdge* nextInternal = myLane->getEdge().getInternalFollowingEdge(nextNormal, getVClass());
8139 return nextInternal ? nextInternal : nextNormal;
8140 }
8141}
8142
8143
8144const MSLane*
8145MSVehicle::getPreviousLane(const MSLane* current, int& furtherIndex) const {
8146 if (furtherIndex < (int)myFurtherLanes.size()) {
8147 return myFurtherLanes[furtherIndex++];
8148 } else {
8149 // try to use route information
8150 int routeIndex = getRoutePosition();
8151 bool resultInternal;
8152 if (MSGlobals::gUsingInternalLanes && MSNet::getInstance()->hasInternalLinks()) {
8153 if (myLane->isInternal()) {
8154 if (furtherIndex % 2 == 0) {
8155 routeIndex -= (furtherIndex + 0) / 2;
8156 resultInternal = false;
8157 } else {
8158 routeIndex -= (furtherIndex + 1) / 2;
8159 resultInternal = false;
8160 }
8161 } else {
8162 if (furtherIndex % 2 != 0) {
8163 routeIndex -= (furtherIndex + 1) / 2;
8164 resultInternal = false;
8165 } else {
8166 routeIndex -= (furtherIndex + 2) / 2;
8167 resultInternal = true;
8168 }
8169 }
8170 } else {
8171 routeIndex -= furtherIndex;
8172 resultInternal = false;
8173 }
8174 furtherIndex++;
8175 if (routeIndex >= 0) {
8176 if (resultInternal) {
8177 const MSEdge* prevNormal = myRoute->getEdges()[routeIndex];
8178 for (MSLane* cand : prevNormal->getLanes()) {
8179 for (MSLink* link : cand->getLinkCont()) {
8180 if (link->getLane() == current) {
8181 if (link->getViaLane() != nullptr) {
8182 return link->getViaLane();
8183 } else {
8184 return const_cast<MSLane*>(link->getLaneBefore());
8185 }
8186 }
8187 }
8188 }
8189 } else {
8190 return myRoute->getEdges()[routeIndex]->getLanes()[0];
8191 }
8192 }
8193 }
8194 return current;
8195}
8196
8199 // this vehicle currently has the highest priority on the allway_stop
8200 return link == myHaveStoppedFor ? SUMOTime_MAX : getWaitingTime();
8201}
8202
8203
8204void
8206 bool diverged = false;
8207 const ConstMSEdgeVector& route = myRoute->getEdges();
8208 int ri = getRoutePosition();
8209 for (const DriveProcessItem& dpi : myLFLinkLanes) {
8210 if (dpi.myLink != nullptr) {
8211 if (!diverged) {
8212 const MSEdge* next = route[ri + 1];
8213 if (&dpi.myLink->getLane()->getEdge() != next) {
8214 diverged = true;
8215 } else {
8216 if (dpi.myLink->getViaLane() == nullptr) {
8217 ri++;
8218 }
8219 }
8220 }
8221 if (diverged) {
8222 dpi.myLink->removeApproaching(this);
8223 }
8224 }
8225 }
8226}
8227
8228/****************************************************************************/
long long int SUMOTime
Definition GUI.h:36
#define RAD2DEG(x)
Definition GeomHelper.h:36
#define DEBUG_COND2(obj)
Definition MESegment.cpp:53
std::vector< const MSEdge * > ConstMSEdgeVector
Definition MSEdge.h:74
std::vector< MSEdge * > MSEdgeVector
Definition MSEdge.h:73
std::pair< const MSVehicle *, double > CLeaderDist
std::pair< const MSPerson *, double > PersonDist
Definition MSPModel.h:41
ConstMSEdgeVector::const_iterator MSRouteIterator
Definition MSRoute.h:57
#define NUMERICAL_EPS_SPEED
#define STOPPING_PLACE_OFFSET
#define JUNCTION_BLOCKAGE_TIME
#define DIST_TO_STOPLINE_EXPECT_PRIORITY
#define CRLL_LOOK_AHEAD
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:288
#define WRITE_ERROR(msg)
Definition MsgHandler.h:296
#define WRITE_WARNING(msg)
Definition MsgHandler.h:287
#define TL(string)
Definition MsgHandler.h:305
std::shared_ptr< const MSRoute > ConstMSRoutePtr
Definition Route.h:32
SUMOTime DELTA_T
Definition SUMOTime.cpp:38
SUMOTime string2time(const std::string &r)
convert string to SUMOTime
Definition SUMOTime.cpp:46
std::string time2string(SUMOTime t, bool humanReadable)
convert SUMOTime to string (independently of global format setting)
Definition SUMOTime.cpp:91
#define STEPS2TIME(x)
Definition SUMOTime.h:55
#define SPEED2DIST(x)
Definition SUMOTime.h:45
#define SIMSTEP
Definition SUMOTime.h:61
#define ACCEL2SPEED(x)
Definition SUMOTime.h:51
#define SUMOTime_MAX
Definition SUMOTime.h:34
#define TS
Definition SUMOTime.h:42
#define SIMTIME
Definition SUMOTime.h:62
#define TIME2STEPS(x)
Definition SUMOTime.h:57
#define DIST2SPEED(x)
Definition SUMOTime.h:47
#define SPEED2ACCEL(x)
Definition SUMOTime.h:53
bool isRailway(SVCPermissions permissions)
Returns whether an edge with the given permissions is a (exclusive) railway edge.
@ RAIL_CARGO
render as a cargo train
@ RAIL
render as a rail
@ PASSENGER_VAN
render as a van
@ PASSENGER
render as a passenger vehicle
@ RAIL_CAR
render as a (city) rail without locomotive
@ PASSENGER_HATCHBACK
render as a hatchback passenger vehicle ("Fliessheck")
@ BUS_FLEXIBLE
render as a flexible city bus
@ TRUCK_1TRAILER
render as a transport vehicle with one trailer
@ PASSENGER_SEDAN
render as a sedan passenger vehicle ("Stufenheck")
@ PASSENGER_WAGON
render as a wagon passenger vehicle ("Combi")
@ TRUCK_SEMITRAILER
render as a semi-trailer transport vehicle ("Sattelschlepper")
@ SVC_RAIL_CLASSES
classes which drive on tracks
@ SVC_EMERGENCY
public emergency vehicles
const long long int VEHPARS_FORCE_REROUTE
@ GIVEN
The lane is given.
@ GIVEN
The speed is given.
@ SPLIT_FRONT
depart position for a split vehicle is in front of the continuing vehicle
const long long int VEHPARS_CFMODEL_PARAMS_SET
@ GIVEN
The arrival lane is given.
@ GIVEN
The speed is given.
const int STOP_ENDED_SET
@ GIVEN
The arrival position is given.
const int STOP_STARTED_SET
@ SUMO_TAG_PARKING_AREA_REROUTE
entry for an alternative parking zone
@ SUMO_TAG_PARKING_AREA
A parking area.
@ SUMO_TAG_OVERHEAD_WIRE_SEGMENT
An overhead wire segment.
LinkDirection
The different directions a link between two lanes may take (or a stream between two edges)....
@ PARTLEFT
The link is a partial left direction.
@ RIGHT
The link is a (hard) right direction.
@ TURN
The link is a 180 degree turn.
@ LEFT
The link is a (hard) left direction.
@ STRAIGHT
The link is a straight direction.
@ TURN_LEFTHAND
The link is a 180 degree turn (left-hand network)
@ PARTRIGHT
The link is a partial right direction.
@ NODIR
The link has no direction (is a dead end link)
LinkState
The right-of-way state of a link between two lanes used when constructing a NBTrafficLightLogic,...
@ LINKSTATE_ALLWAY_STOP
This is an uncontrolled, all-way stop link.
@ LINKSTATE_EQUAL
This is an uncontrolled, right-before-left link.
@ LINKSTATE_ZIPPER
This is an uncontrolled, zipper-merge link.
@ LCA_KEEPRIGHT
The action is due to the default of keeping right "Rechtsfahrgebot".
@ LCA_BLOCKED
blocked in all directions
@ LCA_URGENT
The action is urgent (to be defined by lc-model)
@ LCA_STAY
Needs to stay on the current lane.
@ LCA_SUBLANE
used by the sublane model
@ LCA_WANTS_LANECHANGE_OR_STAY
lane can change or stay
@ LCA_COOPERATIVE
The action is done to help someone else.
@ LCA_OVERLAPPING
The vehicle is blocked being overlapping.
@ LCA_LEFT
Wants go to the left.
@ LCA_STRATEGIC
The action is needed to follow the route (navigational lc)
@ LCA_TRACI
The action is due to a TraCI request.
@ LCA_SPEEDGAIN
The action is due to the wish to be faster (tactical lc)
@ LCA_RIGHT
Wants go to the right.
@ SUMO_ATTR_JM_STOPLINE_GAP_MINOR
@ SUMO_ATTR_JM_STOPLINE_CROSSING_GAP
@ SUMO_ATTR_JM_IGNORE_KEEPCLEAR_TIME
@ SUMO_ATTR_SPEED
@ SUMO_ATTR_STARTED
@ SUMO_ATTR_MAXIMUMPOWER
Maximum Power.
@ SUMO_ATTR_WAITINGTIME
@ SUMO_ATTR_CF_IGNORE_IDS
@ SUMO_ATTR_JM_STOPLINE_GAP
@ SUMO_ATTR_POSITION_LAT
@ SUMO_ATTR_JM_DRIVE_AFTER_RED_TIME
@ SUMO_ATTR_JM_DRIVE_AFTER_YELLOW_TIME
@ SUMO_ATTR_ENDED
@ SUMO_ATTR_LCA_CONTRIGHT
@ SUMO_ATTR_ANGLE
@ SUMO_ATTR_DISTANCE
@ SUMO_ATTR_CF_IGNORE_TYPES
@ SUMO_ATTR_ARRIVALPOS_RANDOMIZED
@ SUMO_ATTR_FLEX_ARRIVAL
@ SUMO_ATTR_JM_IGNORE_JUNCTION_FOE_PROB
@ SUMO_ATTR_POSITION
@ SUMO_ATTR_STATE
The state of a link.
@ SUMO_ATTR_JM_DRIVE_RED_SPEED
int gPrecision
the precision for floating point outputs
Definition StdDefs.cpp:26
bool gDebugFlag1
global utility flags for debugging
Definition StdDefs.cpp:37
const double INVALID_DOUBLE
invalid double
Definition StdDefs.h:64
const double SUMO_const_laneWidth
Definition StdDefs.h:48
T MIN3(T a, T b, T c)
Definition StdDefs.h:89
T MIN2(T a, T b)
Definition StdDefs.h:76
const double SUMO_const_haltingSpeed
the speed threshold at which vehicles are considered as halting
Definition StdDefs.h:58
T MAX2(T a, T b)
Definition StdDefs.h:82
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:46
#define SOFT_ASSERT(expr)
define SOFT_ASSERT raise an assertion in debug mode everywhere except on the windows test server
double getDoubleOptional(SumoXMLAttr attr, const double def) const
Returns the value for a given key with an optional default. SUMO_ATTR_MASS and SUMO_ATTR_FRONTSURFACE...
void setDynamicValues(const SUMOTime stopDuration, const bool parking, const SUMOTime waitingTime, const double angle)
Sets the values which change possibly in every simulation step and are relevant for emsssion calculat...
static double naviDegree(const double angle)
static double fromNaviDegree(const double angle)
Interface for lane-change models.
double getLaneChangeCompletion() const
Get the current lane change completion ratio.
const std::vector< double > & getShadowFurtherLanesPosLat() const
double getManeuverDist() const
Returns the remaining unblocked distance for the current maneuver. (only used by sublane model)
int getLaneChangeDirection() const
return the direction of the current lane change maneuver
void resetChanged()
reset the flag whether a vehicle already moved to false
MSLane * getShadowLane() const
Returns the lane the vehicle's shadow is on during continuous/sublane lane change.
virtual void saveState(OutputDevice &out) const
Save the state of the laneChangeModel.
void endLaneChangeManeuver(const MSMoveReminder::Notification reason=MSMoveReminder::NOTIFICATION_LANE_CHANGE)
void setNoShadowPartialOccupator(MSLane *lane)
MSLane * getTargetLane() const
Returns the lane the vehicle has committed to enter during a sublane lane change.
SUMOTime remainingTime() const
Compute the remaining time until LC completion.
void setShadowApproachingInformation(MSLink *link) const
set approach information for the shadow vehicle
static MSAbstractLaneChangeModel * build(LaneChangeModel lcm, MSVehicle &vehicle)
Factory method for instantiating new lane changing models.
void changedToOpposite()
called when a vehicle changes between lanes in opposite directions
int getShadowDirection() const
return the direction in which the current shadow lane lies
virtual void loadState(const SUMOSAXAttributes &attrs)
Loads the state of the laneChangeModel from the given attributes.
double calcAngleOffset()
return the angle offset during a continuous change maneuver
void setPreviousAngleOffset(const double angleOffset)
set the angle offset of the previous time step
const std::vector< MSLane * > & getFurtherTargetLanes() const
double getAngleOffset() const
return the angle offset resulting from lane change and sigma
const std::vector< MSLane * > & getShadowFurtherLanes() const
bool isChangingLanes() const
return true if the vehicle currently performs a lane change maneuver
void setExtraImpatience(double value)
Sets routing behavior.
The base class for microscopic and mesoscopic vehicles.
double getMaxSpeed() const
Returns the maximum speed (the minimum of desired and technical maximum speed)
bool haveValidStopEdges(bool silent=false) const
check whether all stop.edge MSRouteIterators are valid and in order
virtual bool isSelected() const
whether this vehicle is selected in the GUI
std::list< MSStop > myStops
The vehicle's list of stops.
double getImpatience() const
Returns this vehicles impatience.
const std::vector< MSTransportable * > & getPersons() const
retrieve riding persons
virtual void initDevices()
const MSEdge * succEdge(int nSuccs) const
Returns the nSuccs'th successor of edge the vehicle is currently at.
void calculateArrivalParams(bool onInit)
(Re-)Calculates the arrival position and lane from the vehicle parameters
virtual double getArrivalPos() const
Returns this vehicle's desired arrivalPos for its current route (may change on reroute)
MSVehicleType * myType
This vehicle's type.
MoveReminderCont myMoveReminders
Currently relevant move reminders.
double myDepartPos
The real depart position.
const SUMOVehicleParameter & getParameter() const
Returns the vehicle's parameter (including departure definition)
void replaceParameter(const SUMOVehicleParameter *newParameter)
replace the vehicle parameter (deleting the old one)
double getChosenSpeedFactor() const
Returns the precomputed factor by which the driver wants to be faster than the speed limit.
std::vector< MSVehicleDevice * > myDevices
The devices this vehicle has.
virtual void addTransportable(MSTransportable *transportable)
Adds a person or container to this vehicle.
const SUMOVehicleParameter::Stop * getNextStopParameter() const
return parameters for the next stop (SUMOVehicle Interface)
virtual bool replaceRoute(ConstMSRoutePtr route, const std::string &info, bool onInit=false, int offset=0, bool addRouteStops=true, bool removeStops=true, std::string *msgReturn=nullptr)
Replaces the current route by the given one.
bool isRail() const
MSVehicleType & getSingularType()
Replaces the current vehicle type with a new one used by this vehicle only.
virtual void replaceVehicleType(MSVehicleType *type)
Replaces the current vehicle type by the one given.
double getLength() const
Returns the vehicle's length.
bool isParking() const
Returns whether the vehicle is parking.
MSParkingArea * getCurrentParkingArea()
get the current parking area stop or nullptr
const MSEdge * getEdge() const
Returns the edge the vehicle is currently at.
int getPersonNumber() const
Returns the number of persons.
MSRouteIterator myCurrEdge
Iterator to current route-edge.
bool hasDeparted() const
Returns whether this vehicle has already departed.
ConstMSRoutePtr myRoute
This vehicle's route.
double getWidth() const
Returns the vehicle's width.
MSDevice_Transportable * myContainerDevice
The containers this vehicle may have.
const std::list< MSStop > & getStops() const
void addReminder(MSMoveReminder *rem, double pos=0)
Adds a MoveReminder dynamically.
SumoRNG * getRNG() const
SUMOTime getDeparture() const
Returns this vehicle's real departure time.
EnergyParams * getEmissionParameters() const
retrieve parameters for the energy consumption model
MSDevice_Transportable * myPersonDevice
The passengers this vehicle may have.
bool hasStops() const
Returns whether the vehicle has to stop somewhere.
virtual void activateReminders(const MSMoveReminder::Notification reason, const MSLane *enteredLane=0)
"Activates" all current move reminder
const MSStop & getNextStop() const
@ ROUTE_START_INVALID_PERMISSIONS
void addStops(const bool ignoreStopErrors, MSRouteIterator *searchStart=nullptr, bool addRouteStops=true)
Adds stops to the built vehicle.
SUMOVehicleClass getVClass() const
Returns the vehicle's access class.
MSParkingArea * getNextParkingArea()
get the upcoming parking area stop or nullptr
int myArrivalLane
The destination lane where the vehicle stops.
SUMOTime myDeparture
The real departure time.
bool isStoppedTriggered() const
Returns whether the vehicle is on a triggered stop.
std::vector< SUMOVehicleParameter::Stop > myPastStops
The list of stops that the vehicle has already reached.
void onDepart()
Called when the vehicle is inserted into the network.
virtual bool addTraciStop(SUMOVehicleParameter::Stop stop, std::string &errorMsg)
const MSRoute & getRoute() const
Returns the current route.
int getRoutePosition() const
return index of edge within route
bool replaceParkingArea(MSParkingArea *parkingArea, std::string &errorMsg)
replace the current parking area stop with a new stop with merge duration
static const SUMOTime NOT_YET_DEPARTED
bool myAmRegisteredAsWaiting
Whether this vehicle is registered as waiting for a person or container (for deadlock-recognition)
SUMOAbstractRouter< MSEdge, SUMOVehicle > & getRouterTT() const
EnergyParams * myEnergyParams
The emission parameters this vehicle may have.
const SUMOVehicleParameter * myParameter
This vehicle's parameter.
int myRouteValidity
status of the current vehicle route
const MSVehicleType & getVehicleType() const
Returns the vehicle's type definition.
bool isStopped() const
Returns whether the vehicle is at a stop.
MSDevice * getDevice(const std::type_info &type) const
Returns a device of the given type if it exists, nullptr otherwise.
int myNumberReroutes
The number of reroutings.
double myArrivalPos
The position on the destination lane where the vehicle stops.
virtual void saveState(OutputDevice &out)
Saves the (common) state of a vehicle.
double myOdometer
A simple odometer to keep track of the length of the route already driven.
int getContainerNumber() const
Returns the number of containers.
bool replaceRouteEdges(ConstMSEdgeVector &edges, double cost, double savings, const std::string &info, bool onInit=false, bool check=false, bool removeStops=true, std::string *msgReturn=nullptr)
Replaces the current route by the given edges.
The car-following model abstraction.
Definition MSCFModel.h:57
double estimateSpeedAfterDistance(const double dist, const double v, const double accel) const
virtual double maxNextSpeed(double speed, const MSVehicle *const veh) const
Returns the maximum speed given the current speed.
virtual double minNextSpeedEmergency(double speed, const MSVehicle *const veh=0) const
Returns the minimum speed after emergency braking, given the current speed (depends on the numerical ...
virtual VehicleVariables * createVehicleVariables() const
Returns model specific values which are stored inside a vehicle and must be used with casting.
Definition MSCFModel.h:252
double getEmergencyDecel() const
Get the vehicle type's maximal physically possible deceleration [m/s^2].
Definition MSCFModel.h:277
SUMOTime getStartupDelay() const
Get the vehicle type's startupDelay.
Definition MSCFModel.h:293
double getMinimalArrivalSpeed(double dist, double currentSpeed) const
Computes the minimal possible arrival speed after covering a given distance.
virtual void setHeadwayTime(double headwayTime)
Sets a new value for desired headway [s].
Definition MSCFModel.h:619
virtual double freeSpeed(const MSVehicle *const veh, double speed, double seen, double maxSpeed, const bool onInsertion=false, const CalcReason usage=CalcReason::CURRENT) const
Computes the vehicle's safe speed without a leader.
virtual double minNextSpeed(double speed, const MSVehicle *const veh=0) const
Returns the minimum speed given the current speed (depends on the numerical update scheme and its ste...
virtual double insertionFollowSpeed(const MSVehicle *const veh, double speed, double gap2pred, double predSpeed, double predMaxDecel, const MSVehicle *const pred=0) const
Computes the vehicle's safe speed (no dawdling) This method is used during the insertion stage....
SUMOTime getMinimalArrivalTime(double dist, double currentSpeed, double arrivalSpeed) const
Computes the minimal time needed to cover a distance given the desired speed at arrival.
virtual double finalizeSpeed(MSVehicle *const veh, double vPos) const
Applies interaction with stops and lane changing model influences. Called at most once per simulation...
@ FUTURE
the return value is used for calculating future speeds
Definition MSCFModel.h:83
@ CURRENT_WAIT
the return value is used for calculating junction stop speeds
Definition MSCFModel.h:85
double getApparentDecel() const
Get the vehicle type's apparent deceleration [m/s^2] (the one regarded by its followers.
Definition MSCFModel.h:285
double getMaxAccel() const
Get the vehicle type's maximum acceleration [m/s^2].
Definition MSCFModel.h:261
double brakeGap(const double speed) const
Returns the distance the vehicle needs to halt including driver's reaction time tau (i....
Definition MSCFModel.h:408
virtual double maximumLaneSpeedCF(const MSVehicle *const veh, double maxSpeed, double maxSpeedLane) const
Returns the maximum velocity the CF-model wants to achieve in the next step.
Definition MSCFModel.h:229
double maximumSafeStopSpeed(double gap, double decel, double currentSpeed, bool onInsertion=false, double headway=-1, bool relaxEmergency=true) const
Returns the maximum next velocity for stopping within gap.
double getMaxDecel() const
Get the vehicle type's maximal comfortable deceleration [m/s^2].
Definition MSCFModel.h:269
double getMinimalArrivalSpeedEuler(double dist, double currentSpeed) const
Computes the minimal possible arrival speed after covering a given distance for Euler update.
virtual double followSpeed(const MSVehicle *const veh, double speed, double gap2pred, double predSpeed, double predMaxDecel, const MSVehicle *const pred=0, const CalcReason usage=CalcReason::CURRENT) const =0
Computes the vehicle's follow speed (no dawdling)
double stopSpeed(const MSVehicle *const veh, const double speed, double gap, const CalcReason usage=CalcReason::CURRENT) const
Computes the vehicle's safe speed for approaching a non-moving obstacle (no dawdling)
Definition MSCFModel.h:173
virtual double getHeadwayTime() const
Get the driver's desired headway [s].
Definition MSCFModel.h:339
The ToC Device controls transition of control between automated and manual driving.
std::shared_ptr< MSSimpleDriverState > getDriverState() const
return internal state
void update()
update internal state
A device which collects info on the vehicle trip (mainly on departure and arrival)
double consumption(SUMOVehicle &veh, double a, double newSpeed)
return energy consumption in Wh (power multiplied by TS)
void setConsum(const double consumption)
double acceleration(SUMOVehicle &veh, double power, double oldSpeed)
double getConsum() const
Get consum.
A device which collects info on current friction Coefficient on the road.
A device which collects info on the vehicle trip (mainly on departure and arrival)
A device which collects info on the vehicle trip (mainly on departure and arrival)
void cancelCurrentCustomers()
remove the persons the taxi is currently waiting for from reservations
bool notifyMove(SUMOTrafficObject &veh, double oldPos, double newPos, double newSpeed)
Checks whether the vehicle is at a stop and transportable action is needed.
bool anyLeavingAtStop(const MSStop &stop) const
void transferAtSplitOrJoin(MSBaseVehicle *otherVeh)
transfers transportables that want to continue in the other train part (without boarding/loading dela...
void checkCollisionForInactive(MSLane *l)
trigger collision checking for inactive lane
A road/street connecting two junctions.
Definition MSEdge.h:77
static void clear()
Clears the dictionary.
Definition MSEdge.cpp:1092
const std::set< MSTransportable *, ComparatorNumericalIdLess > & getPersons() const
Returns this edge's persons set.
Definition MSEdge.h:204
const std::vector< MSLane * > & getLanes() const
Returns this edge's lanes.
Definition MSEdge.h:168
const MSEdge * getOppositeEdge() const
Returns the opposite direction edge if on exists else a nullptr.
Definition MSEdge.cpp:1340
bool isFringe() const
return whether this edge is at the fringe of the network
Definition MSEdge.h:761
const MSEdge * getNormalSuccessor() const
if this edge is an internal edge, return its first normal successor, otherwise the edge itself
Definition MSEdge.cpp:947
const std::vector< MSLane * > * allowedLanes(const MSEdge &destination, SUMOVehicleClass vclass=SVC_IGNORING, bool ignoreTransientPermissions=false) const
Get the allowed lanes to reach the destination-edge.
Definition MSEdge.cpp:479
const MSEdge * getBidiEdge() const
return opposite superposable/congruent edge, if it exist and 0 else
Definition MSEdge.h:282
bool isNormal() const
return whether this edge is an internal edge
Definition MSEdge.h:263
double getSpeedLimit() const
Returns the speed limit of the edge @caution The speed limit of the first lane is retured; should pro...
Definition MSEdge.cpp:1158
bool hasChangeProhibitions(SUMOVehicleClass svc, int index) const
return whether this edge prohibits changing for the given vClass when starting on the given lane inde...
Definition MSEdge.cpp:1362
const MSJunction * getToJunction() const
Definition MSEdge.h:418
const MSJunction * getFromJunction() const
Definition MSEdge.h:414
int getNumLanes() const
Definition MSEdge.h:172
double getMinimumTravelTime(const SUMOVehicle *const veh) const
returns the minimum travel time for the given vehicle
Definition MSEdge.h:476
bool isRoundabout() const
Definition MSEdge.h:721
bool isInternal() const
return whether this edge is an internal edge
Definition MSEdge.h:268
double getWidth() const
Returns the edges's width (sum over all lanes)
Definition MSEdge.h:656
bool isVaporizing() const
Returns whether vehicles on this edge shall be vaporized.
Definition MSEdge.h:434
void addWaiting(SUMOVehicle *vehicle) const
Adds a vehicle to the list of waiting vehicles.
Definition MSEdge.cpp:1451
const MSEdge * getInternalFollowingEdge(const MSEdge *followerAfterInternal, SUMOVehicleClass vClass) const
Definition MSEdge.cpp:900
void removeWaiting(const SUMOVehicle *vehicle) const
Removes a vehicle from the list of waiting vehicles.
Definition MSEdge.cpp:1460
const MSEdgeVector & getSuccessors(SUMOVehicleClass vClass=SVC_IGNORING) const
Returns the following edges, restricted by vClass.
Definition MSEdge.cpp:1258
static bool gModelParkingManoeuver
whether parking simulation includes manoeuver time and any associated lane blocking
Definition MSGlobals.h:162
static bool gUseMesoSim
Definition MSGlobals.h:106
static bool gUseStopStarted
Definition MSGlobals.h:134
static bool gCheckRoutes
Definition MSGlobals.h:91
static SUMOTime gStartupWaitThreshold
The minimum waiting time before applying startupDelay.
Definition MSGlobals.h:180
static double gTLSYellowMinDecel
The minimum deceleration at a yellow traffic light (only overruled by emergencyDecel)
Definition MSGlobals.h:171
static double gLateralResolution
Definition MSGlobals.h:100
static bool gSemiImplicitEulerUpdate
Definition MSGlobals.h:53
static bool gLefthand
Whether lefthand-drive is being simulated.
Definition MSGlobals.h:174
static bool gSublane
whether sublane simulation is enabled (sublane model or continuous lanechanging)
Definition MSGlobals.h:165
static SUMOTime gLaneChangeDuration
Definition MSGlobals.h:97
static double gEmergencyDecelWarningThreshold
threshold for warning about strong deceleration
Definition MSGlobals.h:152
static bool gUsingInternalLanes
Information whether the simulation regards internal lanes.
Definition MSGlobals.h:81
void add(SUMOVehicle *veh)
Adds a single vehicle for departure.
virtual const MSJunctionLogic * getLogic() const
Definition MSJunction.h:141
virtual const MSLogicJunction::LinkBits & getResponseFor(int linkIndex) const
Returns the response for the given link.
Representation of a lane in the micro simulation.
Definition MSLane.h:84
std::vector< StopWatch< std::chrono::nanoseconds > > & getStopWatch()
Definition MSLane.h:1286
const std::vector< MSMoveReminder * > & getMoveReminders() const
Return the list of this lane's move reminders.
Definition MSLane.h:323
std::pair< MSVehicle *const, double > getFollower(const MSVehicle *ego, double egoPos, double dist, MinorLinkMode mLinkMode) const
Find follower vehicle for the given ego vehicle (which may be on the opposite direction lane)
Definition MSLane.cpp:4368
std::pair< const MSPerson *, double > nextBlocking(double minPos, double minRight, double maxLeft, double stopTime=0, bool bidi=false) const
This is just a wrapper around MSPModel::nextBlocking. You should always check using hasPedestrians be...
Definition MSLane.cpp:4542
MSLane * getParallelLane(int offset, bool includeOpposite=true) const
Returns the lane with the given offset parallel to this one or 0 if it does not exist.
Definition MSLane.cpp:2824
virtual MSVehicle * removeVehicle(MSVehicle *remVehicle, MSMoveReminder::Notification notification, bool notify=true)
Definition MSLane.cpp:2806
int getVehicleNumber() const
Returns the number of vehicles on this lane (for which this lane is responsible)
Definition MSLane.h:456
MSVehicle * getFirstAnyVehicle() const
returns the first vehicle that is fully or partially on this lane
Definition MSLane.cpp:2654
const MSLink * getEntryLink() const
Returns the entry link if this is an internal lane, else nullptr.
Definition MSLane.cpp:2742
int getVehicleNumberWithPartials() const
Returns the number of vehicles on this lane (including partial occupators)
Definition MSLane.h:464
double getBruttoVehLenSum() const
Returns the sum of lengths of vehicles, including their minGaps, which were on the lane during the la...
Definition MSLane.h:1159
static std::vector< MSLink * >::const_iterator succLinkSec(const SUMOVehicle &veh, int nRouteSuccs, const MSLane &succLinkSource, const std::vector< MSLane * > &conts)
Definition MSLane.cpp:2668
void markRecalculateBruttoSum()
Set a flag to recalculate the brutto (including minGaps) occupancy of this lane (used if mingap is ch...
Definition MSLane.cpp:2407
const MSLink * getLinkTo(const MSLane *const) const
returns the link to the given lane or nullptr, if it is not connected
Definition MSLane.cpp:2719
void forceVehicleInsertion(MSVehicle *veh, double pos, MSMoveReminder::Notification notification, double posLat=0)
Inserts the given vehicle at the given position.
Definition MSLane.cpp:1366
double getVehicleStopOffset(const MSVehicle *veh) const
Returns vehicle class specific stopOffset for the vehicle.
Definition MSLane.cpp:3752
double getSpeedLimit() const
Returns the lane's maximum allowed speed.
Definition MSLane.h:592
std::vector< MSVehicle * > VehCont
Container for vehicles.
Definition MSLane.h:119
const MSEdge * getNextNormal() const
Returns the lane's follower if it is an internal lane, the edge of the lane otherwise.
Definition MSLane.cpp:2439
SVCPermissions getPermissions() const
Returns the vehicle class permissions for this lane.
Definition MSLane.h:614
const std::vector< IncomingLaneInfo > & getIncomingLanes() const
Definition MSLane.h:950
MSLane * getCanonicalPredecessorLane() const
Definition MSLane.cpp:3246
double getLength() const
Returns the lane's length.
Definition MSLane.h:606
double getMaximumBrakeDist() const
compute maximum braking distance on this lane
Definition MSLane.cpp:2881
const MSLane * getInternalFollowingLane(const MSLane *const) const
returns the internal lane leading to the given lane or nullptr, if there is none
Definition MSLane.cpp:2731
const MSLeaderInfo getLastVehicleInformation(const MSVehicle *ego, double latOffset, double minPos=0, bool allowCached=true) const
Returns the last vehicles on the lane.
Definition MSLane.cpp:1419
std::pair< MSVehicle *const, double > getLeaderOnConsecutive(double dist, double seen, double speed, const MSVehicle &veh, const std::vector< MSLane * > &bestLaneConts, bool considerCrossingFoes=true) const
Returns the immediate leader and the distance to him.
Definition MSLane.cpp:2965
bool isLinkEnd(std::vector< MSLink * >::const_iterator &i) const
Definition MSLane.h:853
bool allowsVehicleClass(SUMOVehicleClass vclass) const
Definition MSLane.h:925
virtual double setPartialOccupation(MSVehicle *v)
Sets the information about a vehicle lapping into this lane.
Definition MSLane.cpp:384
double getVehicleMaxSpeed(const SUMOTrafficObject *const veh) const
Returns the lane's maximum speed, given a vehicle's speed limit adaptation.
Definition MSLane.h:574
double getRightSideOnEdge() const
Definition MSLane.h:1195
bool hasPedestrians() const
whether the lane has pedestrians on it
Definition MSLane.cpp:4535
int getIndex() const
Returns the lane's index.
Definition MSLane.h:642
MSLane * getCanonicalSuccessorLane() const
Definition MSLane.cpp:3270
double getOppositePos(double pos) const
return the corresponding position on the opposite lane
Definition MSLane.cpp:4363
MSLane * getLogicalPredecessorLane() const
get the most likely precedecessor lane (sorted using by_connections_to_sorter). The result is cached ...
Definition MSLane.cpp:3190
double getCenterOnEdge() const
Definition MSLane.h:1203
bool isNormal() const
Definition MSLane.cpp:2600
MSVehicle * getLastAnyVehicle() const
returns the last vehicle that is fully or partially on this lane
Definition MSLane.cpp:2635
bool isInternal() const
Definition MSLane.cpp:2594
@ FOLLOW_NEVER
Definition MSLane.h:974
virtual void resetPartialOccupation(MSVehicle *v)
Removes the information about a vehicle lapping into this lane.
Definition MSLane.cpp:403
MSLane * getOpposite() const
return the neighboring opposite direction lane for lane changing or nullptr
Definition MSLane.cpp:4351
virtual const VehCont & getVehiclesSecure() const
Returns the vehicles container; locks it for microsimulation.
Definition MSLane.h:483
virtual void releaseVehicles() const
Allows to use the container for microsimulation again.
Definition MSLane.h:513
bool mustCheckJunctionCollisions() const
whether this lane must check for junction collisions
Definition MSLane.cpp:4653
double interpolateLanePosToGeometryPos(double lanePos) const
Definition MSLane.h:554
MSLane * getBidiLane() const
retrieve bidirectional lane or nullptr
Definition MSLane.cpp:4647
@ COLLISION_ACTION_WARN
Definition MSLane.h:203
virtual const PositionVector & getShape(bool) const
Definition MSLane.h:294
MSLane * getParallelOpposite() const
return the opposite direction lane of this lanes edge or nullptr
Definition MSLane.cpp:4357
MSEdge & getEdge() const
Returns the lane's edge.
Definition MSLane.h:764
double getSpaceTillLastStanding(const MSVehicle *ego, bool &foundStopped) const
return the empty space up to the last standing vehicle or the empty space on the whole lane if no veh...
Definition MSLane.cpp:4662
const MSLane * getNormalPredecessorLane() const
get normal lane leading to this internal lane, for normal lanes, the lane itself is returned
Definition MSLane.cpp:3215
MSLeaderDistanceInfo getFollowersOnConsecutive(const MSVehicle *ego, double backOffset, bool allSublanes, double searchDist=-1, MinorLinkMode mLinkMode=FOLLOW_ALWAYS) const
return the sublane followers with the largest missing rear gap among all predecessor lanes (within di...
Definition MSLane.cpp:3777
double getWidth() const
Returns the lane's width.
Definition MSLane.h:635
const std::vector< MSLink * > & getLinkCont() const
returns the container with all links !!!
Definition MSLane.h:724
MSVehicle * getFirstFullVehicle() const
returns the first vehicle for which this lane is responsible or 0
Definition MSLane.cpp:2626
const Position geometryPositionAtOffset(double offset, double lateralOffset=0) const
Definition MSLane.h:560
static CollisionAction getCollisionAction()
Definition MSLane.h:1357
saves leader/follower vehicles and their distances relative to an ego vehicle
virtual std::string toString() const
print a debugging representation
void fixOppositeGaps(bool isFollower)
subtract vehicle length from all gaps if the leader vehicle is driving in the opposite direction
virtual int addLeader(const MSVehicle *veh, double gap, double latOffset=0, int sublane=-1)
void setSublaneOffset(int offset)
set number of sublanes by which to shift positions
void removeOpposite(const MSLane *lane)
remove vehicles that are driving in the opposite direction (fully or partially) on the given lane
int numSublanes() const
virtual int addLeader(const MSVehicle *veh, bool beyond, double latOffset=0.)
virtual std::string toString() const
print a debugging representation
virtual void clear()
discard all information
bool hasVehicles() const
int getSublaneOffset() const
void getSubLanes(const MSVehicle *veh, double latOffset, int &rightmost, int &leftmost) const
Something on a lane to be noticed about vehicle movement.
Notification
Definition of a vehicle state.
@ NOTIFICATION_TELEPORT_ARRIVED
The vehicle was teleported out of the net.
@ NOTIFICATION_PARKING_REROUTE
The vehicle needs another parking area.
@ NOTIFICATION_DEPARTED
The vehicle has departed (was inserted into the network)
@ NOTIFICATION_LANE_CHANGE
The vehicle changes lanes (micro only)
@ NOTIFICATION_VAPORIZED_VAPORIZER
The vehicle got vaporized with a vaporizer.
@ NOTIFICATION_JUNCTION
The vehicle arrived at a junction.
@ NOTIFICATION_PARKING
The vehicle starts or ends parking.
@ NOTIFICATION_VAPORIZED_COLLISION
The vehicle got removed by a collision.
@ NOTIFICATION_LOAD_STATE
The vehicle has been loaded from a state file.
@ NOTIFICATION_TELEPORT
The vehicle is being teleported.
@ NOTIFICATION_TELEPORT_CONTINUATION
The vehicle continues being teleported past an edge.
The simulated network and simulation perfomer.
Definition MSNet.h:89
void removeVehicleStateListener(VehicleStateListener *listener)
Removes a vehicle states listener.
Definition MSNet.cpp:1277
VehicleState
Definition of a vehicle state.
Definition MSNet.h:613
@ STARTING_STOP
The vehicles starts to stop.
@ STARTING_PARKING
The vehicles starts to park.
@ STARTING_TELEPORT
The vehicle started to teleport.
@ ENDING_STOP
The vehicle ends to stop.
@ ARRIVED
The vehicle arrived at his destination (is deleted)
@ EMERGENCYSTOP
The vehicle had to brake harder than permitted.
@ MANEUVERING
Vehicle maneuvering either entering or exiting a parking space.
static MSNet * getInstance()
Returns the pointer to the unique instance of MSNet (singleton).
Definition MSNet.cpp:186
virtual MSTransportableControl & getContainerControl()
Returns the container control.
Definition MSNet.cpp:1210
std::string getStoppingPlaceID(const MSLane *lane, const double pos, const SumoXMLTag category) const
Returns the stop of the given category close to the given position.
Definition MSNet.cpp:1425
SUMOTime getCurrentTimeStep() const
Returns the current simulation step.
Definition MSNet.h:325
static bool hasInstance()
Returns whether the network was already constructed.
Definition MSNet.h:157
MSStoppingPlace * getStoppingPlace(const std::string &id, const SumoXMLTag category) const
Returns the named stopping place of the given category.
Definition MSNet.cpp:1404
void addVehicleStateListener(VehicleStateListener *listener)
Adds a vehicle states listener.
Definition MSNet.cpp:1269
bool hasContainers() const
Returns whether containers are simulated.
Definition MSNet.h:416
void informVehicleStateListener(const SUMOVehicle *const vehicle, VehicleState to, const std::string &info="")
Informs all added listeners about a vehicle's state change.
Definition MSNet.cpp:1286
bool hasPersons() const
Returns whether persons are simulated.
Definition MSNet.h:400
MSInsertionControl & getInsertionControl()
Returns the insertion control.
Definition MSNet.h:436
MSVehicleControl & getVehicleControl()
Returns the vehicle control.
Definition MSNet.h:383
virtual MSTransportableControl & getPersonControl()
Returns the person control.
Definition MSNet.cpp:1201
MSEdgeControl & getEdgeControl()
Returns the edge control.
Definition MSNet.h:426
bool hasElevation() const
return whether the network contains elevation data
Definition MSNet.h:795
static const double SAFETY_GAP
Definition MSPModel.h:59
A lane area vehicles can halt at.
int getOccupancyIncludingReservations(const SUMOVehicle *forVehicle) const
void leaveFrom(SUMOVehicle *what)
Called if a vehicle leaves this stop.
int getCapacity() const
Returns the area capacity.
void enter(SUMOVehicle *veh)
Called if a vehicle enters this stop.
int getLotIndex(const SUMOVehicle *veh) const
compute lot for this vehicle
int getLastFreeLotAngle() const
Return the angle of myLastFreeLot - the next parking lot only expected to be called after we have est...
bool parkOnRoad() const
whether vehicles park on the road
double getLastFreePosWithReservation(SUMOTime t, const SUMOVehicle &forVehicle, double brakePos)
Returns the last free position on this stop including reservations from the current lane and time ste...
double getLastFreeLotGUIAngle() const
Return the GUI angle of myLastFreeLot - the angle the GUI uses to rotate into the next parking lot as...
int getManoeuverAngle(const SUMOVehicle &forVehicle) const
Return the manoeuver angle of the lot where the vehicle is parked.
int getOccupancy() const
Returns the area occupancy.
double getGUIAngle(const SUMOVehicle &forVehicle) const
Return the GUI angle of the lot where the vehicle is parked.
void notifyApproach(const MSLink *link)
switch rail signal to active
static MSRailSignalControl & getInstance()
const ConstMSEdgeVector & getEdges() const
Definition MSRoute.h:125
const MSEdge * getLastEdge() const
returns the destination edge
Definition MSRoute.cpp:91
MSRouteIterator begin() const
Returns the begin of the list of edges to pass.
Definition MSRoute.cpp:73
const MSLane * lane
The lane to stop at (microsim only)
Definition MSStop.h:50
bool triggered
whether an arriving person lets the vehicle continue
Definition MSStop.h:69
bool containerTriggered
whether an arriving container lets the vehicle continue
Definition MSStop.h:71
SUMOTime timeToLoadNextContainer
The time at which the vehicle is able to load another container.
Definition MSStop.h:83
MSStoppingPlace * containerstop
(Optional) container stop if one is assigned to the stop
Definition MSStop.h:56
double getSpeed() const
return speed for passing waypoint / skipping on-demand stop
Definition MSStop.cpp:163
bool joinTriggered
whether coupling another vehicle (train) the vehicle continue
Definition MSStop.h:73
bool isOpposite
whether this an opposite-direction stop
Definition MSStop.h:87
SUMOTime getMinDuration(SUMOTime time) const
return minimum stop duration when starting stop at time
Definition MSStop.cpp:134
int numExpectedContainer
The number of still expected containers.
Definition MSStop.h:79
bool reached
Information whether the stop has been reached.
Definition MSStop.h:75
MSRouteIterator edge
The edge in the route to stop at.
Definition MSStop.h:48
SUMOTime timeToBoardNextPerson
The time at which the vehicle is able to board another person.
Definition MSStop.h:81
bool skipOnDemand
whether the decision to skip this stop has been made
Definition MSStop.h:89
const MSEdge * getEdge() const
Definition MSStop.cpp:54
double getReachedThreshold() const
return startPos taking into account opposite stopping
Definition MSStop.cpp:64
SUMOTime endBoarding
the maximum time at which persons may board this vehicle
Definition MSStop.h:85
double getEndPos(const SUMOVehicle &veh) const
return halting position for upcoming stop;
Definition MSStop.cpp:35
int numExpectedPerson
The number of still expected persons.
Definition MSStop.h:77
MSParkingArea * parkingarea
(Optional) parkingArea if one is assigned to the stop
Definition MSStop.h:58
bool startedFromState
whether the 'started' value was loaded from simulaton state
Definition MSStop.h:91
MSStoppingPlace * chargingStation
(Optional) charging station if one is assigned to the stop
Definition MSStop.h:60
SUMOTime duration
The stopping duration.
Definition MSStop.h:67
SUMOTime getUntil() const
return until / ended time
Definition MSStop.cpp:151
const SUMOVehicleParameter::Stop pars
The stop parameter.
Definition MSStop.h:65
MSStoppingPlace * busstop
(Optional) bus stop if one is assigned to the stop
Definition MSStop.h:54
void stopBlocked(const SUMOVehicle *veh, SUMOTime time)
Definition MSStopOut.cpp:66
static bool active()
Definition MSStopOut.h:54
void stopNotStarted(const SUMOVehicle *veh)
Definition MSStopOut.cpp:75
void stopStarted(const SUMOVehicle *veh, int numPersons, int numContainers, SUMOTime time)
Definition MSStopOut.cpp:82
void stopEnded(const SUMOVehicle *veh, const SUMOVehicleParameter::Stop &stop, const std::string &laneOrEdgeID, bool simEnd=false)
static MSStopOut * getInstance()
Definition MSStopOut.h:60
double getBeginLanePosition() const
Returns the begin position of this stop.
bool fits(double pos, const SUMOVehicle &veh) const
return whether the given vehicle fits at the given position
double getEndLanePosition() const
Returns the end position of this stop.
void enter(SUMOVehicle *veh, bool parking)
Called if a vehicle enters this stop.
const MSLane & getLane() const
Returns the lane this stop is located at.
void leaveFrom(SUMOVehicle *what)
Called if a vehicle leaves this stop.
bool hasAnyWaiting(const MSEdge *edge, SUMOVehicle *vehicle) const
check whether any transportables are waiting for the given vehicle
bool loadAnyWaiting(const MSEdge *edge, SUMOVehicle *vehicle, SUMOTime &timeToLoadNext, SUMOTime &stopDuration, MSTransportable *const force=nullptr)
load any applicable transportables Loads any person / container that is waiting on that edge for the ...
bool isPerson() const
Whether it is a person.
A static instance of this class in GapControlState deactivates gap control for vehicles whose referen...
Definition MSVehicle.h:1354
void vehicleStateChanged(const SUMOVehicle *const vehicle, MSNet::VehicleState to, const std::string &info="")
Called if a vehicle changes its state.
Changes the wished vehicle speed / lanes.
Definition MSVehicle.h:1349
void setLaneChangeMode(int value)
Sets lane changing behavior.
TraciLaneChangePriority myTraciLaneChangePriority
flags for determining the priority of traci lane change requests
Definition MSVehicle.h:1671
bool getEmergencyBrakeRedLight() const
Returns whether red lights shall be a reason to brake.
Definition MSVehicle.h:1519
SUMOTime getLaneTimeLineEnd()
void adaptLaneTimeLine(int indexShift)
Adapts lane timeline when moving to a new lane and the lane index changes.
void setRemoteControlled(Position xyPos, MSLane *l, double pos, double posLat, double angle, int edgeOffset, const ConstMSEdgeVector &route, SUMOTime t)
bool isRemoteAffected(SUMOTime t) const
int getSpeedMode() const
return the current speed mode
void deactivateGapController()
Deactivates the gap control.
Influencer()
Constructor.
void setSpeedMode(int speedMode)
Sets speed-constraining behaviors.
std::shared_ptr< GapControlState > myGapControlState
The gap control state.
Definition MSVehicle.h:1616
int getSignals() const
Definition MSVehicle.h:1587
bool myConsiderMaxDeceleration
Whether the maximum deceleration shall be regarded.
Definition MSVehicle.h:1637
void setLaneTimeLine(const std::vector< std::pair< SUMOTime, int > > &laneTimeLine)
Sets a new lane timeline.
bool myRespectJunctionLeaderPriority
Whether the junction priority rules are respected (within)
Definition MSVehicle.h:1646
void setOriginalSpeed(double speed)
Stores the originally longitudinal speed.
double myOriginalSpeed
The velocity before influence.
Definition MSVehicle.h:1619
bool myConsiderSpeedLimit
Whether the speed limit shall be regarded.
Definition MSVehicle.h:1631
double implicitDeltaPosRemote(const MSVehicle *veh)
return the change in longitudinal position that is implicit in the new remote position
double implicitSpeedRemote(const MSVehicle *veh, double oldSpeed)
return the speed that is implicit in the new remote position
void postProcessRemoteControl(MSVehicle *v)
update position from remote control
double gapControlSpeed(SUMOTime currentTime, const SUMOVehicle *veh, double speed, double vSafe, double vMin, double vMax)
Applies gap control logic on the speed.
void setSublaneChange(double latDist)
Sets a new sublane-change request.
double getOriginalSpeed() const
Returns the originally longitudinal speed to use.
SUMOTime myLastRemoteAccess
Definition MSVehicle.h:1655
bool getRespectJunctionLeaderPriority() const
Returns whether junction priority rules within the junction shall be respected (concerns vehicles wit...
Definition MSVehicle.h:1527
LaneChangeMode myStrategicLC
lane changing which is necessary to follow the current route
Definition MSVehicle.h:1660
LaneChangeMode mySpeedGainLC
lane changing to travel with higher speed
Definition MSVehicle.h:1664
void init()
Static initalization.
LaneChangeMode mySublaneLC
changing to the prefered lateral alignment
Definition MSVehicle.h:1668
bool getRespectJunctionPriority() const
Returns whether junction priority rules shall be respected (concerns approaching vehicles outside the...
Definition MSVehicle.h:1511
static void cleanup()
Static cleanup.
int getLaneChangeMode() const
return the current lane change mode
SUMOTime getLaneTimeLineDuration()
double influenceSpeed(SUMOTime currentTime, double speed, double vSafe, double vMin, double vMax)
Applies stored velocity information on the speed to use.
double changeRequestRemainingSeconds(const SUMOTime currentTime) const
Return the remaining number of seconds of the current laneTimeLine assuming one exists.
bool myConsiderSafeVelocity
Whether the safe velocity shall be regarded.
Definition MSVehicle.h:1628
bool mySpeedAdaptationStarted
Whether influencing the speed has already started.
Definition MSVehicle.h:1625
~Influencer()
Destructor.
void setSignals(int signals)
Definition MSVehicle.h:1583
double myLatDist
The requested lateral change.
Definition MSVehicle.h:1622
bool considerSpeedLimit() const
Returns whether speed limits shall be considered.
Definition MSVehicle.h:1538
bool myEmergencyBrakeRedLight
Whether red lights are a reason to brake.
Definition MSVehicle.h:1643
LaneChangeMode myRightDriveLC
changing to the rightmost lane
Definition MSVehicle.h:1666
void setSpeedTimeLine(const std::vector< std::pair< SUMOTime, double > > &speedTimeLine)
Sets a new velocity timeline.
void updateRemoteControlRoute(MSVehicle *v)
update route if provided by remote control
SUMOTime getLastAccessTimeStep() const
Definition MSVehicle.h:1563
bool myConsiderMaxAcceleration
Whether the maximum acceleration shall be regarded.
Definition MSVehicle.h:1634
LaneChangeMode myCooperativeLC
lane changing with the intent to help other vehicles
Definition MSVehicle.h:1662
bool isRemoteControlled() const
bool myRespectJunctionPriority
Whether the junction priority rules are respected (approaching)
Definition MSVehicle.h:1640
int influenceChangeDecision(const SUMOTime currentTime, const MSEdge &currentEdge, const int currentLaneIndex, int state)
Applies stored LaneChangeMode information and laneTimeLine.
void activateGapController(double originalTau, double newTimeHeadway, double newSpaceHeadway, double duration, double changeRate, double maxDecel, MSVehicle *refVeh=nullptr)
Activates the gap control with the given parameters,.
Container for manouevering time associated with stopping.
Definition MSVehicle.h:1273
SUMOTime myManoeuvreCompleteTime
Time at which this manoeuvre should complete.
Definition MSVehicle.h:1325
MSVehicle::ManoeuvreType getManoeuvreType() const
Accessor (get) for manoeuvre type.
std::string myManoeuvreStop
The name of the stop associated with the Manoeuvre - for debug output.
Definition MSVehicle.h:1319
bool manoeuvreIsComplete() const
Check if any manoeuver is ongoing and whether the completion time is beyond currentTime.
bool configureExitManoeuvre(MSVehicle *veh)
Setup the myManoeuvre for exiting (Sets completion time and manoeuvre type)
void setManoeuvreType(const MSVehicle::ManoeuvreType mType)
Accessor (set) for manoeuvre type.
Manoeuvre & operator=(const Manoeuvre &manoeuvre)
Assignment operator.
Manoeuvre()
Constructor.
ManoeuvreType myManoeuvreType
Manoeuvre type - currently entry, exit or none.
Definition MSVehicle.h:1328
double getGUIIncrement() const
Accessor for GUI rotation step when parking (radians)
SUMOTime myManoeuvreStartTime
Time at which the Manoeuvre for this stop started.
Definition MSVehicle.h:1322
bool operator!=(const Manoeuvre &manoeuvre)
Operator !=.
bool entryManoeuvreIsComplete(MSVehicle *veh)
Configure an entry manoeuvre if nothing is configured - otherwise check if complete.
bool manoeuvreIsComplete(const ManoeuvreType checkType) const
Check if specific manoeuver is ongoing and whether the completion time is beyond currentTime.
bool configureEntryManoeuvre(MSVehicle *veh)
Setup the entry manoeuvre for this vehicle (Sets completion time and manoeuvre type)
Container that holds the vehicles driving state (position+speed).
Definition MSVehicle.h:87
double myPosLat
the stored lateral position
Definition MSVehicle.h:140
State(double pos, double speed, double posLat, double backPos, double previousSpeed)
Constructor.
double myPreviousSpeed
the speed at the begin of the previous time step
Definition MSVehicle.h:148
double myPos
the stored position
Definition MSVehicle.h:134
bool operator!=(const State &state)
Operator !=.
double myLastCoveredDist
Definition MSVehicle.h:154
double mySpeed
the stored speed (should be >=0 at any time)
Definition MSVehicle.h:137
State & operator=(const State &state)
Assignment operator.
double pos() const
Position of this state.
Definition MSVehicle.h:107
double myBackPos
the stored back position
Definition MSVehicle.h:145
void passTime(SUMOTime dt, bool waiting)
const std::string getState() const
SUMOTime cumulatedWaitingTime(SUMOTime memory=-1) const
void setState(const std::string &state)
WaitingTimeCollector(SUMOTime memory=MSGlobals::gWaitingTimeMemory)
Constructor.
void registerEmergencyStop()
register emergency stop
SUMOVehicle * getVehicle(const std::string &id) const
Returns the vehicle with the given id.
void registerStopEnded()
register emergency stop
void registerEmergencyBraking()
register emergency stop
void removeVType(const MSVehicleType *vehType)
void registerOneWaiting()
increases the count of vehicles waiting for a transport to allow recognition of person / container re...
void unregisterOneWaiting()
decreases the count of vehicles waiting for a transport to allow recognition of person / container re...
void registerStopStarted()
register emergency stop
Abstract in-vehicle device.
Representation of a vehicle in the micro simulation.
Definition MSVehicle.h:77
void setManoeuvreType(const MSVehicle::ManoeuvreType mType)
accessor function to myManoeuvre equivalent
TraciLaneChangePriority
modes for prioritizing traci lane change requests
Definition MSVehicle.h:1151
@ LCP_OPPORTUNISTIC
Definition MSVehicle.h:1155
double getRightSideOnEdge(const MSLane *lane=0) const
Get the vehicle's lateral position on the edge of the given lane (or its current edge if lane == 0)
bool wasRemoteControlled(SUMOTime lookBack=DELTA_T) const
Returns the information whether the vehicle is fully controlled via TraCI within the lookBack time.
void processLinkApproaches(double &vSafe, double &vSafeMin, double &vSafeMinDist)
This method iterates through the driveprocess items for the vehicle and adapts the given in/out param...
const MSLane * getPreviousLane(const MSLane *current, int &furtherIndex) const
void checkLinkLeader(const MSLink *link, const MSLane *lane, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass, double &vLinkWait, bool &setRequest, bool isShadowLink=false) const
checks for link leaders on the given link
void checkRewindLinkLanes(const double lengthsInFront, DriveItemVector &lfLinks) const
runs heuristic for keeping the intersection clear in case of downstream jamming
bool willStop() const
Returns whether the vehicle will stop on the current edge.
bool hasDriverState() const
Whether this vehicle is equipped with a MSDriverState.
Definition MSVehicle.h:996
static int nextLinkPriority(const std::vector< MSLane * > &conts)
get a numerical value for the priority of the upcoming link
double getTimeGapOnLane() const
Returns the time gap in seconds to the leader of the vehicle on the same lane.
void updateBestLanes(bool forceRebuild=false, const MSLane *startLane=0)
computes the best lanes to use in order to continue the route
bool myAmIdling
Whether the vehicle is trying to enter the network (eg after parking so engine is running)
Definition MSVehicle.h:1930
SUMOTime myWaitingTime
The time the vehicle waits (is not faster than 0.1m/s) in seconds.
Definition MSVehicle.h:1866
double getStopDelay() const
Returns the public transport stop delay in seconds.
double computeAngle() const
compute the current vehicle angle
double myTimeLoss
the time loss in seconds due to driving with less than maximum speed
Definition MSVehicle.h:1870
SUMOTime myLastActionTime
Action offset (actions are taken at time myActionOffset + N*getActionStepLength()) Initialized to 0,...
Definition MSVehicle.h:1885
ConstMSEdgeVector::const_iterator getRerouteOrigin() const
Returns the starting point for reroutes (usually the current edge)
bool hasArrivedInternal(bool oppositeTransformed=true) const
Returns whether this vehicle has already arived (reached the arrivalPosition on its final edge) metho...
double getFriction() const
Returns the current friction on the road as perceived by the friction device.
bool ignoreFoe(const SUMOTrafficObject *foe) const
decide whether a given foe object may be ignored
void boardTransportables(MSStop &stop)
board persons and load transportables at the given stop
const std::vector< const MSLane * > getUpcomingLanesUntil(double distance) const
Returns the upcoming (best followed by default 0) sequence of lanes to continue the route starting at...
bool isOnRoad() const
Returns the information whether the vehicle is on a road (is simulated)
Definition MSVehicle.h:605
void adaptLaneEntering2MoveReminder(const MSLane &enteredLane)
Adapts the vehicle's entering of a new lane.
void addTransportable(MSTransportable *transportable)
Adds a person or container to this vehicle.
SUMOTime myJunctionConflictEntryTime
Definition MSVehicle.h:1948
double getLeftSideOnEdge(const MSLane *lane=0) const
Get the vehicle's lateral position on the edge of the given lane (or its current edge if lane == 0)
PositionVector getBoundingPoly(double offset=0) const
get bounding polygon
void setTentativeLaneAndPosition(MSLane *lane, double pos, double posLat=0)
set tentative lane and position during insertion to ensure that all cfmodels work (some of them requi...
bool brakeForOverlap(const MSLink *link, const MSLane *lane) const
handle with transitions
void workOnMoveReminders(double oldPos, double newPos, double newSpeed)
Processes active move reminder.
bool isStoppedOnLane() const
double getDistanceToPosition(double destPos, const MSLane *destLane) const
bool brokeDown() const
Returns how long the vehicle has been stopped already due to lack of energy.
double myAcceleration
The current acceleration after dawdling in m/s.
Definition MSVehicle.h:1912
void registerInsertionApproach(MSLink *link, double dist)
register approach on insertion
void cleanupFurtherLanes()
remove vehicle from further lanes (on leaving the network)
void adaptToLeaders(const MSLeaderInfo &ahead, double latOffset, const double seen, DriveProcessItem *const lastLink, const MSLane *const lane, double &v, double &vLinkPass) const
const MSLane * getBackLane() const
Returns the lane the where the rear of the object is currently at.
void enterLaneAtInsertion(MSLane *enteredLane, double pos, double speed, double posLat, MSMoveReminder::Notification notification)
Update when the vehicle enters a new lane in the emit step.
double getBackPositionOnLane() const
Get the vehicle's position relative to its current lane.
Definition MSVehicle.h:405
void setPreviousSpeed(double prevSpeed, double prevAcceleration)
Sets the influenced previous speed.
SUMOTime getArrivalTime(SUMOTime t, double seen, double v, double arrivalSpeed) const
double getAccumulatedWaitingSeconds() const
Returns the number of seconds waited (speed was lesser than 0.1m/s) within the last millisecs.
Definition MSVehicle.h:714
SUMOTime getWaitingTime(const bool accumulated=false) const
Returns the SUMOTime waited (speed was lesser than 0.1m/s)
Definition MSVehicle.h:670
bool isFrontOnLane(const MSLane *lane) const
Returns the information whether the front of the vehicle is on the given lane.
virtual ~MSVehicle()
Destructor.
void processLaneAdvances(std::vector< MSLane * > &passedLanes, std::string &emergencyReason)
This method checks if the vehicle has advanced over one or several lanes along its route and triggers...
MSAbstractLaneChangeModel & getLaneChangeModel()
void setEmergencyBlueLight(SUMOTime currentTime)
sets the blue flashing light for emergency vehicles
bool isActionStep(SUMOTime t) const
Returns whether the next simulation step will be an action point for the vehicle.
Definition MSVehicle.h:635
MSAbstractLaneChangeModel * myLaneChangeModel
Definition MSVehicle.h:1892
Position getPositionAlongBestLanes(double offset) const
Return the (x,y)-position, which the vehicle would reach if it continued along its best continuation ...
bool hasValidRouteStart(std::string &msg)
checks wether the vehicle can depart on the first edge
double getLeftSideOnLane() const
Get the lateral position of the vehicles left side on the lane:
std::vector< MSLane * > myFurtherLanes
The information into which lanes the vehicle laps into.
Definition MSVehicle.h:1919
bool signalSet(int which) const
Returns whether the given signal is on.
Definition MSVehicle.h:1187
MSCFModel::VehicleVariables * myCFVariables
The per vehicle variables of the car following model.
Definition MSVehicle.h:2160
bool betterContinuation(const LaneQ *bestConnectedNext, const LaneQ &m) const
comparison between different continuations from the same lane
bool addTraciStop(SUMOVehicleParameter::Stop stop, std::string &errorMsg)
void checkLinkLeaderCurrentAndParallel(const MSLink *link, const MSLane *lane, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass, double &vLinkWait, bool &setRequest) const
checks for link leaders of the current link as well as the parallel link (if there is one)
void planMoveInternal(const SUMOTime t, MSLeaderInfo ahead, DriveItemVector &lfLinks, double &myStopDist, std::pair< double, const MSLink * > &myNextTurn) const
std::pair< double, const MSLink * > myNextTurn
the upcoming turn for the vehicle
Definition MSVehicle.h:1916
double getDistanceToLeaveJunction() const
get the distance from the start of this lane to the start of the next normal lane (or 0 if this lane ...
int influenceChangeDecision(int state)
allow TraCI to influence a lane change decision
double getMaxSpeedOnLane() const
Returns the maximal speed for the vehicle on its current lane (including speed factor and deviation,...
bool isRemoteControlled() const
Returns the information whether the vehicle is fully controlled via TraCI.
bool myAmOnNet
Whether the vehicle is on the network (not parking, teleported, vaporized, or arrived)
Definition MSVehicle.h:1927
void enterLaneAtMove(MSLane *enteredLane, bool onTeleporting=false)
Update when the vehicle enters a new lane in the move step.
void adaptBestLanesOccupation(int laneIndex, double density)
update occupation from MSLaneChanger
std::pair< double, double > estimateTimeToNextStop() const
return time (s) and distance to the next stop
double accelThresholdForWaiting() const
maximum acceleration to consider a vehicle as 'waiting' at low speed
Definition MSVehicle.h:2074
void setAngle(double angle, bool straightenFurther=false)
Set a custom vehicle angle in rad, optionally updates furtherLanePosLat.
std::vector< LaneQ >::iterator myCurrentLaneInBestLanes
Definition MSVehicle.h:1907
void setApproachingForAllLinks()
Register junction approaches for all link items in the current plan.
double getDeltaPos(const double accel) const
calculates the distance covered in the next integration step given an acceleration and assuming the c...
const MSLane * myLastBestLanesInternalLane
Definition MSVehicle.h:1895
void updateOccupancyAndCurrentBestLane(const MSLane *startLane)
updates LaneQ::nextOccupation and myCurrentLaneInBestLanes
const std::vector< MSLane * > getUpstreamOppositeLanes() const
Returns the sequence of opposite lanes corresponding to past lanes.
WaitingTimeCollector myWaitingTimeCollector
Definition MSVehicle.h:1867
void setRemoteState(Position xyPos)
sets position outside the road network
void fixPosition()
repair errors in vehicle position after changing between internal edges
double getAcceleration() const
Returns the vehicle's acceleration in m/s (this is computed as the last step's mean acceleration in c...
Definition MSVehicle.h:514
double getSpeedWithoutTraciInfluence() const
Returns the uninfluenced velocity.
PositionVector getBoundingBox(double offset=0) const
get bounding rectangle
ManoeuvreType
flag identifying which, if any, manoeuvre is in progress
Definition MSVehicle.h:1246
@ MANOEUVRE_ENTRY
Manoeuvre into stopping place.
Definition MSVehicle.h:1248
@ MANOEUVRE_NONE
not manouevring
Definition MSVehicle.h:1252
@ MANOEUVRE_EXIT
Manoeuvre out of stopping place.
Definition MSVehicle.h:1250
const MSEdge * getNextEdgePtr() const
returns the next edge (possibly an internal edge)
Position getPosition(const double offset=0) const
Return current position (x/y, cartesian)
void setBrakingSignals(double vNext)
sets the braking lights on/off
const std::vector< MSLane * > & getBestLanesContinuation() const
Returns the best sequence of lanes to continue the route starting at myLane.
const MSEdge * myLastBestLanesEdge
Definition MSVehicle.h:1894
bool ignoreCollision() const
whether this vehicle is except from collision checks
Influencer * myInfluencer
An instance of a velocity/lane influencing instance; built in "getInfluencer".
Definition MSVehicle.h:2163
void saveState(OutputDevice &out)
Saves the states of a vehicle.
void onRemovalFromNet(const MSMoveReminder::Notification reason)
Called when the vehicle is removed from the network.
void planMove(const SUMOTime t, const MSLeaderInfo &ahead, const double lengthsInFront)
Compute safe velocities for the upcoming lanes based on positions and speeds from the last time step....
bool resumeFromStopping()
int getBestLaneOffset() const
void adaptToJunctionLeader(const std::pair< const MSVehicle *, double > leaderInfo, const double seen, DriveProcessItem *const lastLink, const MSLane *const lane, double &v, double &vLinkPass, double distToCrossing=-1) const
double lateralDistanceToLane(const int offset) const
Get the minimal lateral distance required to move fully onto the lane at given offset.
double getBackPositionOnLane(const MSLane *lane) const
Get the vehicle's position relative to the given lane.
Definition MSVehicle.h:398
void leaveLaneBack(const MSMoveReminder::Notification reason, const MSLane *leftLane)
Update of reminders if vehicle back leaves a lane during (during forward movement.
void resetActionOffset(const SUMOTime timeUntilNextAction=0)
Resets the action offset for the vehicle.
std::vector< DriveProcessItem > DriveItemVector
Container for used Links/visited Lanes during planMove() and executeMove.
Definition MSVehicle.h:2017
void interpolateLateralZ(Position &pos, double offset, double posLat) const
perform lateral z interpolation in elevated networks
void setBlinkerInformation()
sets the blue flashing light for emergency vehicles
const MSEdge * getCurrentEdge() const
Returns the edge the vehicle is currently at (possibly an internal edge or nullptr)
void adaptToLeaderDistance(const MSLeaderDistanceInfo &ahead, double latOffset, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass) const
DriveItemVector::iterator myNextDriveItem
iterator pointing to the next item in myLFLinkLanes
Definition MSVehicle.h:2030
bool unsafeLinkAhead(const MSLane *lane, double zipperDist) const
whether the vehicle may safely move to the given lane with regard to upcoming links
void leaveLane(const MSMoveReminder::Notification reason, const MSLane *approachedLane=0)
Update of members if vehicle leaves a new lane in the lane change step or at arrival.
const MSLink * myHaveStoppedFor
Definition MSVehicle.h:1952
bool isIdling() const
Returns whether a sim vehicle is waiting to enter a lane (after parking has completed)
Definition MSVehicle.h:621
std::shared_ptr< MSSimpleDriverState > getDriverState() const
Returns the vehicle driver's state.
void removeApproachingInformation(const DriveItemVector &lfLinks) const
unregister approach from all upcoming links
void replaceVehicleType(MSVehicleType *type)
Replaces the current vehicle type by the one given.
SUMOTime myJunctionEntryTimeNeverYield
Definition MSVehicle.h:1947
double getLatOffset(const MSLane *lane) const
Get the offset that that must be added to interpret myState.myPosLat for the given lane.
bool rerouteParkingArea(const std::string &parkingAreaID, std::string &errorMsg)
bool hasArrived() const
Returns whether this vehicle has already arived (reached the arrivalPosition on its final edge)
void switchOffSignal(int signal)
Switches the given signal off.
Definition MSVehicle.h:1170
double getStopArrivalDelay() const
Returns the estimated public transport stop arrival delay in seconds.
int mySignals
State of things of the vehicle that can be on or off.
Definition MSVehicle.h:1924
bool setExitManoeuvre()
accessor function to myManoeuvre equivalent
bool isOppositeLane(const MSLane *lane) const
whether the give lane is reverse direction of the current route or not
double myStopDist
distance to the next stop or doubleMax if there is none
Definition MSVehicle.h:1938
Signalling
Some boolean values which describe the state of some vehicle parts.
Definition MSVehicle.h:1105
@ VEH_SIGNAL_BLINKER_RIGHT
Right blinker lights are switched on.
Definition MSVehicle.h:1109
@ VEH_SIGNAL_BRAKELIGHT
The brake lights are on.
Definition MSVehicle.h:1115
@ VEH_SIGNAL_EMERGENCY_BLUE
A blue emergency light is on.
Definition MSVehicle.h:1131
@ VEH_SIGNAL_BLINKER_LEFT
Left blinker lights are switched on.
Definition MSVehicle.h:1111
SUMOTime getActionStepLength() const
Returns the vehicle's action step length in millisecs, i.e. the interval between two action points.
Definition MSVehicle.h:525
bool myHaveToWaitOnNextLink
Definition MSVehicle.h:1932
SUMOTime collisionStopTime() const
Returns the remaining time a vehicle needs to stop due to a collision. A negative value indicates tha...
const std::vector< const MSLane * > getPastLanesUntil(double distance) const
Returns the sequence of past lanes (right-most on edge) based on the route starting at the current la...
double getBestLaneDist() const
returns the distance that can be driven without lane change
void updateState(double vNext, bool parking=false)
updates the vehicles state, given a next value for its speed. This value can be negative in case of t...
double slowDownForSchedule(double vMinComfortable) const
optionally return an upper bound on speed to stay within the schedule
bool executeMove()
Executes planned vehicle movements with regards to right-of-way.
const MSLane * getLane() const
Returns the lane the vehicle is on.
Definition MSVehicle.h:581
std::pair< const MSVehicle *const, double > getFollower(double dist=0) const
Returns the follower of the vehicle looking for a fixed distance.
SUMOTime getWaitingTimeFor(const MSLink *link) const
getWaitingTime, but taking into account having stopped for a stop-link
ChangeRequest
Requests set via TraCI.
Definition MSVehicle.h:191
@ REQUEST_HOLD
vehicle want's to keep the current lane
Definition MSVehicle.h:199
@ REQUEST_LEFT
vehicle want's to change to left lane
Definition MSVehicle.h:195
@ REQUEST_NONE
vehicle doesn't want to change
Definition MSVehicle.h:193
@ REQUEST_RIGHT
vehicle want's to change to right lane
Definition MSVehicle.h:197
bool isLeader(const MSLink *link, const MSVehicle *veh, const double gap) const
whether the given vehicle must be followed at the given junction
void resetApproachOnReroute()
reset rail signal approach information
void computeFurtherLanes(MSLane *enteredLane, double pos, bool collision=false)
updates myFurtherLanes on lane insertion or after collision
MSLane * getMutableLane() const
Returns the lane the vehicle is on Non const version indicates that something volatile is going on.
Definition MSVehicle.h:589
std::pair< const MSLane *, double > getLanePosAfterDist(double distance) const
return lane and position along bestlanes at the given distance
SUMOTime myCollisionImmunity
amount of time for which the vehicle is immune from collisions
Definition MSVehicle.h:1941
bool passingMinor() const
decide whether the vehicle is passing a minor link or has comitted to do so
void updateWaitingTime(double vNext)
Updates the vehicle's waiting time counters (accumulated and consecutive)
void enterLaneAtLaneChange(MSLane *enteredLane)
Update when the vehicle enters a new lane in the laneChange step.
BaseInfluencer & getBaseInfluencer()
Returns the velocity/lane influencer.
Influencer & getInfluencer()
bool isBidiOn(const MSLane *lane) const
whether this vehicle is driving against lane
double getRightSideOnLane() const
Get the lateral position of the vehicles right side on the lane:
double getCurrentApparentDecel() const
get apparent deceleration based on vType parameters and current acceleration
double updateFurtherLanes(std::vector< MSLane * > &furtherLanes, std::vector< double > &furtherLanesPosLat, const std::vector< MSLane * > &passedLanes)
update a vector of further lanes and return the new backPos
DriveItemVector myLFLinkLanesPrev
planned speeds from the previous step for un-registering from junctions after the new container is fi...
Definition MSVehicle.h:2023
std::vector< std::vector< LaneQ > > myBestLanes
Definition MSVehicle.h:1902
void setActionStepLength(double actionStepLength, bool resetActionOffset=true)
Sets the action steplength of the vehicle.
double getLateralPositionOnLane() const
Get the vehicle's lateral position on the lane.
Definition MSVehicle.h:413
double getSlope() const
Returns the slope of the road at vehicle's position in degrees.
bool myActionStep
The flag myActionStep indicates whether the current time step is an action point for the vehicle.
Definition MSVehicle.h:1882
const Position getBackPosition() const
bool congested() const
void loadState(const SUMOSAXAttributes &attrs, const SUMOTime offset)
Loads the state of this vehicle from the given description.
SUMOTime myTimeSinceStartup
duration of driving (speed > SUMO_const_haltingSpeed) after the last halting episode
Definition MSVehicle.h:1951
double getSpeed() const
Returns the vehicle's current speed.
Definition MSVehicle.h:490
SUMOTime remainingStopDuration() const
Returns the remaining stop duration for a stopped vehicle or 0.
bool keepStopping(bool afterProcessing=false) const
Returns whether the vehicle is stopped and must continue to do so.
void workOnIdleReminders()
cycle through vehicle devices invoking notifyIdle
static std::vector< MSLane * > myEmptyLaneVector
Definition MSVehicle.h:1909
Position myCachedPosition
Definition MSVehicle.h:1943
bool replaceRoute(ConstMSRoutePtr route, const std::string &info, bool onInit=false, int offset=0, bool addStops=true, bool removeStops=true, std::string *msgReturn=nullptr)
Replaces the current route by the given one.
MSVehicle::ManoeuvreType getManoeuvreType() const
accessor function to myManoeuvre equivalent
double checkReversal(bool &canReverse, double speedThreshold=SUMO_const_haltingSpeed, double seen=0) const
void updateLaneBruttoSum()
Update the lane brutto occupancy after a change in minGap.
void removePassedDriveItems()
Erase passed drive items from myLFLinkLanes (and unregister approaching information for corresponding...
const std::vector< MSLane * > & getFurtherLanes() const
Definition MSVehicle.h:835
const std::vector< LaneQ > & getBestLanes() const
Returns the description of best lanes to use in order to continue the route.
std::vector< double > myFurtherLanesPosLat
lateral positions on further lanes
Definition MSVehicle.h:1921
bool checkActionStep(const SUMOTime t)
Returns whether the vehicle is supposed to take action in the current simulation step Updates myActio...
const MSCFModel & getCarFollowModel() const
Returns the vehicle's car following model definition.
Definition MSVehicle.h:969
Position validatePosition(Position result, double offset=0) const
ensure that a vehicle-relative position is not invalid
void loadPreviousApproaching(MSLink *link, bool setRequest, SUMOTime arrivalTime, double arrivalSpeed, double arrivalSpeedBraking, double dist, double leaveSpeed)
bool keepClear(const MSLink *link) const
decide whether the given link must be kept clear
bool manoeuvreIsComplete() const
accessor function to myManoeuvre equivalent
double processNextStop(double currentVelocity)
Processes stops, returns the velocity needed to reach the stop.
double myAngle
the angle in radians (
Definition MSVehicle.h:1935
bool ignoreRed(const MSLink *link, bool canBrake) const
decide whether a red (or yellow light) may be ignored
double getPositionOnLane() const
Get the vehicle's position along the lane.
Definition MSVehicle.h:374
void updateTimeLoss(double vNext)
Updates the vehicle's time loss.
MSDevice_DriverState * myDriverState
This vehicle's driver state.
Definition MSVehicle.h:1876
bool joinTrainPart(MSVehicle *veh)
try joining the given vehicle to the rear of this one (to resolve joinTriggered)
MSLane * myLane
The lane the vehicle is on.
Definition MSVehicle.h:1890
bool onFurtherEdge(const MSEdge *edge) const
whether this vehicle has its back (and no its front) on the given edge
double processTraCISpeedControl(double vSafe, double vNext)
Check for speed advices from the traci client and adjust the speed vNext in the current (euler) / aft...
Manoeuvre myManoeuvre
Definition MSVehicle.h:1335
double getLateralOverlap() const
return the amount by which the vehicle extends laterally outside it's primary lane
double getAngle() const
Returns the vehicle's direction in radians.
Definition MSVehicle.h:735
bool handleCollisionStop(MSStop &stop, const double distToStop)
bool hasInfluencer() const
whether the vehicle is individually influenced (via TraCI or special parameters)
Definition MSVehicle.h:1690
MSDevice_Friction * myFrictionDevice
This vehicle's friction perception.
Definition MSVehicle.h:1879
double getPreviousSpeed() const
Returns the vehicle's speed before the previous time step.
Definition MSVehicle.h:498
MSVehicle()
invalidated default constructor
bool joinTrainPartFront(MSVehicle *veh)
try joining the given vehicle to the front of this one (to resolve joinTriggered)
void updateActionOffset(const SUMOTime oldActionStepLength, const SUMOTime newActionStepLength)
Process an updated action step length value (only affects the vehicle's action offset,...
double getBrakeGap(bool delayed=false) const
get distance for coming to a stop (used for rerouting checks)
std::pair< const MSVehicle *const, double > getLeader(double dist=0, bool considerFoes=true) const
Returns the leader of the vehicle looking for a fixed distance.
void executeFractionalMove(double dist)
move vehicle forward by the given distance during insertion
LaneChangeMode
modes for resolving conflicts between external control (traci) and vehicle control over lane changing...
Definition MSVehicle.h:1143
virtual void drawOutsideNetwork(bool)
register vehicle for drawing while outside the network
Definition MSVehicle.h:1841
void initDevices()
void adaptToOncomingLeader(const std::pair< const MSVehicle *, double > leaderInfo, DriveProcessItem *const lastLink, double &v, double &vLinkPass) const
State myState
This Vehicles driving state (pos and speed)
Definition MSVehicle.h:1873
double getCenterOnEdge(const MSLane *lane=0) const
Get the vehicle's lateral position on the edge of the given lane (or its current edge if lane == 0)
void adaptToLeader(const std::pair< const MSVehicle *, double > leaderInfo, double seen, DriveProcessItem *const lastLink, double &v, double &vLinkPass) const
void switchOnSignal(int signal)
Switches the given signal on.
Definition MSVehicle.h:1162
static bool overlap(const MSVehicle *veh1, const MSVehicle *veh2)
Definition MSVehicle.h:763
int getLaneIndex() const
void updateParkingState()
update state while parking
DriveItemVector myLFLinkLanes
container for the planned speeds in the current step
Definition MSVehicle.h:2020
void updateDriveItems()
Check whether the drive items (myLFLinkLanes) are up to date, and update them if required.
SUMOTime myJunctionEntryTime
time at which the current junction was entered
Definition MSVehicle.h:1946
static MSVehicleTransfer * getInstance()
Returns the instance of this object.
void remove(MSVehicle *veh)
Remove a vehicle from this transfer object.
The car-following model and parameter.
double getLengthWithGap() const
Get vehicle's length including the minimum gap [m].
double getWidth() const
Get the width which vehicles of this class shall have when being drawn.
SUMOVehicleClass getVehicleClass() const
Get this vehicle type's vehicle class.
double getMaxSpeed() const
Get vehicle's (technical) maximum speed [m/s].
const std::string & getID() const
Returns the name of the vehicle type.
double getMinGap() const
Get the free space in front of vehicles of this class.
LaneChangeModel getLaneChangeModel() const
void setLength(const double &length)
Set a new value for this type's length.
SUMOTime getExitManoeuvreTime(const int angle) const
Accessor function for parameter equivalent returning exit time for a specific manoeuver angle.
const MSCFModel & getCarFollowModel() const
Returns the vehicle type's car following model definition (const version)
bool isVehicleSpecific() const
Returns whether this type belongs to a single vehicle only (was modified)
void setActionStepLength(const SUMOTime actionStepLength, bool resetActionOffset)
Set a new value for this type's action step length.
double getLength() const
Get vehicle's length [m].
SUMOVehicleShape getGuiShape() const
Get this vehicle type's shape.
SUMOTime getEntryManoeuvreTime(const int angle) const
Accessor function for parameter equivalent returning entry time for a specific manoeuver angle.
const SUMOVTypeParameter & getParameter() const
static std::string getIDSecure(const T *obj, const std::string &fallBack="NULL")
get an identifier for Named-like object which may be Null
Definition Named.h:67
const std::string & getID() const
Returns the id.
Definition Named.h:74
Static storage of an output device and its base (abstract) implementation.
OutputDevice & writeAttr(const SumoXMLAttr attr, const T &val)
writes a named attribute
bool closeTag(const std::string &comment="")
Closes the most recently opened tag and optionally adds a comment.
bool hasParameter(const std::string &key) const
Returns whether the parameter is set.
virtual const std::string getParameter(const std::string &key, const std::string defaultValue="") const
Returns the value for a given key.
void writeParams(OutputDevice &device) const
write Params in the given outputdevice
A point in 2D or 3D with translation and scaling methods.
Definition Position.h:37
double slopeTo2D(const Position &other) const
returns the slope of the vector pointing from here to the other position (in radians between -M_PI an...
Definition Position.h:288
static const Position INVALID
used to indicate that a position is valid
Definition Position.h:319
double distanceTo2D(const Position &p2) const
returns the euclidean distance in the x-y-plane
Definition Position.h:273
void setz(double z)
set position z
Definition Position.h:77
double z() const
Returns the z-position.
Definition Position.h:62
double angleTo2D(const Position &other) const
returns the angle in the plane of the vector pointing from here to the other position (in radians bet...
Definition Position.h:283
A list of positions.
double length2D() const
Returns the length.
void append(const PositionVector &v, double sameThreshold=2.0)
double rotationAtOffset(double pos) const
Returns the rotation at the given length.
Position positionAtOffset(double pos, double lateralOffset=0) const
Returns the position at the given length.
void move2side(double amount, double maxExtension=100)
move position vector to side using certain amount
double slopeDegreeAtOffset(double pos) const
Returns the slope at the given length.
void extrapolate2D(const double val, const bool onlyFirst=false)
extrapolate position vector in two dimensions (Z is ignored)
void scaleRelative(double factor)
enlarges/shrinks the polygon by a factor based at the centroid
PositionVector reverse() const
reverse position vector
static double rand(SumoRNG *rng=nullptr)
Returns a random real number in [0, 1)
virtual bool compute(const E *from, const E *to, const V *const vehicle, SUMOTime msTime, std::vector< const E * > &into, bool silent=false)=0
Builds the route between the given edges using the minimum effort at the given time The definition of...
virtual double recomputeCosts(const std::vector< const E * > &edges, const V *const v, SUMOTime msTime, double *lengthp=nullptr) const
Encapsulated SAX-Attributes.
virtual std::string getString(int id, bool *isPresent=nullptr) const =0
Returns the string-value of the named (by its enum-value) attribute.
T get(int attr, const char *objectid, bool &ok, bool report=true) const
Tries to read given attribute assuming it is an int.
virtual bool hasAttribute(int id) const =0
Returns the information whether the named (by its enum-value) attribute is within the current list.
double getFloat(int id) const
Returns the double-value of the named (by its enum-value) attribute.
Representation of a vehicle, person, or container.
virtual const MSVehicleType & getVehicleType() const =0
Returns the object's "vehicle" type.
virtual double getSpeed() const =0
Returns the object's current speed.
double locomotiveLength
the length of the locomotive
double speedFactorPremature
the possible speed reduction when a train is ahead of schedule
double getLCParam(const SumoXMLAttr attr, const double defaultValue) const
Returns the named value from the map, or the default if it is not contained there.
double getJMParam(const SumoXMLAttr attr, const double defaultValue) const
Returns the named value from the map, or the default if it is not contained there.
Representation of a vehicle.
Definition SUMOVehicle.h:62
Definition of vehicle stop (position and duration)
SUMOTime started
the time at which this stop was reached
ParkingType parking
whether the vehicle is removed from the net while stopping
SUMOTime extension
The maximum time extension for boarding / loading.
std::string split
the id of the vehicle (train portion) that splits of upon reaching this stop
double startPos
The stopping position start.
std::string line
the new line id of the trip within a cyclical public transport route
double posLat
the lateral offset when stopping
bool onDemand
whether the stop may be skipped
std::string join
the id of the vehicle (train portion) to which this vehicle shall be joined
SUMOTime until
The time at which the vehicle may continue its journey.
SUMOTime ended
the time at which this stop was ended
double endPos
The stopping position end.
SUMOTime waitUntil
The earliest pickup time for a taxi stop.
std::string tripId
id of the trip within a cyclical public transport route
bool collision
Whether this stop was triggered by a collision.
SUMOTime arrival
The (expected) time at which the vehicle reaches the stop.
SUMOTime duration
The stopping duration.
Structure representing possible vehicle parameter.
int departLane
(optional) The lane the vehicle shall depart from (index in edge)
ArrivalSpeedDefinition arrivalSpeedProcedure
Information how the vehicle's end speed shall be chosen.
double departSpeed
(optional) The initial speed of the vehicle
std::vector< std::string > via
List of the via-edges the vehicle must visit.
ArrivalLaneDefinition arrivalLaneProcedure
Information how the vehicle shall choose the lane to arrive on.
long long int parametersSet
Information for the router which parameter were set, TraCI may modify this (when changing color)
DepartLaneDefinition departLaneProcedure
Information how the vehicle shall choose the lane to depart from.
bool wasSet(long long int what) const
Returns whether the given parameter was set.
DepartSpeedDefinition departSpeedProcedure
Information how the vehicle's initial speed shall be chosen.
double arrivalPos
(optional) The position the vehicle shall arrive on
ArrivalPosDefinition arrivalPosProcedure
Information how the vehicle shall choose the arrival position.
double arrivalSpeed
(optional) The final speed of the vehicle (not used yet)
int arrivalEdge
(optional) The final edge within the route of the vehicle
DepartPosDefinition departPosProcedure
Information how the vehicle shall choose the departure position.
static SUMOTime processActionStepLength(double given)
Checks and converts given value for the action step length from seconds to miliseconds assuring it be...
std::vector< std::string > getVector()
return vector of strings
#define DEBUG_COND
Definition json.hpp:4471
NLOHMANN_BASIC_JSON_TPL_DECLARATION void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL &j1, nlohmann::NLOHMANN_BASIC_JSON_TPL &j2) noexcept(//NOLINT(readability-inconsistent-declaration-parameter-name) is_nothrow_move_constructible< nlohmann::NLOHMANN_BASIC_JSON_TPL >::value &&//NOLINT(misc-redundant-expression) is_nothrow_move_assignable< nlohmann::NLOHMANN_BASIC_JSON_TPL >::value)
exchanges the values of two JSON objects
Definition json.hpp:21884
#define M_PI
Definition odrSpiral.cpp:45
Drive process items represent bounds on the safe velocity corresponding to the upcoming links.
Definition MSVehicle.h:1959
void adaptStopSpeed(const double v)
Definition MSVehicle.h:2006
double getLeaveSpeed() const
Definition MSVehicle.h:2010
void adaptLeaveSpeed(const double v)
Definition MSVehicle.h:1998
static std::map< const MSVehicle *, GapControlState * > refVehMap
stores reference vehicles currently in use by a gapController
Definition MSVehicle.h:1408
static GapControlVehStateListener * myVehStateListener
Definition MSVehicle.h:1411
void activate(double tauOriginal, double tauTarget, double additionalGap, double duration, double changeRate, double maxDecel, const MSVehicle *refVeh)
Start gap control with given params.
static void cleanup()
Static cleanup (removes vehicle state listener)
void deactivate()
Stop gap control.
static void init()
Static initalization (adds vehicle state listener)
A structure representing the best lanes for continuing the current route starting at 'lane'.
Definition MSVehicle.h:857
double length
The overall length which may be driven when using this lane without a lane change.
Definition MSVehicle.h:861
bool allowsContinuation
Whether this lane allows to continue the drive.
Definition MSVehicle.h:871
double nextOccupation
As occupation, but without the first lane.
Definition MSVehicle.h:867
std::vector< MSLane * > bestContinuations
Definition MSVehicle.h:877
MSLane * lane
The described lane.
Definition MSVehicle.h:859
double currentLength
The length which may be driven on this lane.
Definition MSVehicle.h:863
int bestLaneOffset
The (signed) number of lanes to be crossed to get to the lane which allows to continue the drive.
Definition MSVehicle.h:869
double occupation
The overall vehicle sum on consecutive lanes which can be passed without a lane change.
Definition MSVehicle.h:865