forked from eclipse-sumo/sumo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMSLaneChanger.cpp
1603 lines (1472 loc) · 70.8 KB
/
MSLaneChanger.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************/
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
// Copyright (C) 2002-2019 German Aerospace Center (DLR) and others.
// This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v2.0
// which accompanies this distribution, and is available at
// http://www.eclipse.org/legal/epl-v20.html
// SPDX-License-Identifier: EPL-2.0
/****************************************************************************/
/// @file MSLaneChanger.cpp
/// @author Christian Roessel
/// @author Daniel Krajzewicz
/// @author Laura Bieker
/// @author Michael Behrisch
/// @author Friedemann Wesner
/// @author Jakob Erdmann
/// @date Fri, 01 Feb 2002
/// @version $Id$
///
// Performs lane changing of vehicles
/****************************************************************************/
// ===========================================================================
// included modules
// ===========================================================================
#include <config.h>
#include "MSLaneChanger.h"
#include "MSNet.h"
#include "MSVehicle.h"
#include "MSVehicleType.h"
#include "MSVehicleTransfer.h"
#include "MSGlobals.h"
#include <cassert>
#include <iterator>
#include <cstdlib>
#include <cmath>
#include <microsim/lcmodels/MSAbstractLaneChangeModel.h>
#include <microsim/pedestrians/MSPModel.h>
#include <utils/common/MsgHandler.h>
#define OPPOSITE_OVERTAKING_SAFE_TIMEGAP 0.0
#define OPPOSITE_OVERTAKING_SAFETYGAP_HEADWAY_FACTOR 0.0
#define OPPOSITE_OVERTAKING_SAFETY_FACTOR 1.2
// XXX maxLookAhead should be higher if all leaders are stopped and lower when they are jammed/queued
#define OPPOSITE_OVERTAKING_MAX_LOOKAHEAD 150.0 // just a guess
#define OPPOSITE_OVERTAKING_MAX_LOOKAHEAD_EMERGENCY 1000.0 // just a guess
// this is used for finding oncoming vehicles while driving in the opposite direction
#define OPPOSITE_OVERTAKING_ONCOMING_LOOKAHEAD 200.0 // just a guess
// ===========================================================================
// debug defines
// ===========================================================================
//#define DEBUG_CONTINUE_CHANGE
//#define DEBUG_CHECK_CHANGE
//#define DEBUG_SURROUNDING_VEHICLES // debug getRealFollower() and getRealLeader()
//#define DEBUG_CHANGE_OPPOSITE
//#define DEBUG_CHANGE_OPPOSITE_OVERTAKINGTIME
//#define DEBUG_ACTIONSTEPS
//#define DEBUG_STATE
//#define DEBUG_CANDIDATE
//#define DEBUG_COND (vehicle->getLaneChangeModel().debugVehicle())
#define DEBUG_COND (vehicle->isSelected())
// ===========================================================================
// ChangeElem member method definitions
// ===========================================================================
MSLaneChanger::ChangeElem::ChangeElem(MSLane* _lane) :
lead(nullptr),
lane(_lane),
hoppedVeh(nullptr),
lastBlocked(nullptr),
firstBlocked(nullptr),
ahead(lane),
aheadNext(lane, nullptr, 0) {
}
void
MSLaneChanger::ChangeElem::registerHop(MSVehicle* vehicle) {
lane->myTmpVehicles.insert(lane->myTmpVehicles.begin(), vehicle);
dens += vehicle->getVehicleType().getLengthWithGap();
hoppedVeh = vehicle;
}
// ===========================================================================
// member method definitions
// ===========================================================================
MSLaneChanger::MSLaneChanger(const std::vector<MSLane*>* lanes, bool allowChanging) :
myAllowsChanging(allowChanging),
myChangeToOpposite(lanes->front()->getEdge().canChangeToOpposite()) {
// Fill the changer with the lane-data.
myChanger.reserve(lanes->size());
for (std::vector<MSLane*>::const_iterator lane = lanes->begin(); lane != lanes->end(); ++lane) {
myChanger.push_back(ChangeElem(*lane));
myChanger.back().mayChangeRight = lane != lanes->begin();
myChanger.back().mayChangeLeft = (lane + 1) != lanes->end();
// avoid changing on internal sibling lane
if ((*lane)->isInternal()) {
if (myChanger.back().mayChangeRight && (*lane)->getLogicalPredecessorLane() == (*(lane - 1))->getLogicalPredecessorLane()) {
myChanger.back().mayChangeRight = false;
}
if (myChanger.back().mayChangeLeft && (*lane)->getLogicalPredecessorLane() == (*(lane + 1))->getLogicalPredecessorLane()) {
myChanger.back().mayChangeLeft = false;
}
}
}
}
MSLaneChanger::~MSLaneChanger() {
}
void
MSLaneChanger::laneChange(SUMOTime t) {
// This is what happens in one timestep. After initialization of the
// changer, each vehicle will try to change. After that the changer
// needs an update to prevent multiple changes of one vehicle.
// Finally, the change-result has to be given back to the lanes.
initChanger();
try {
while (vehInChanger()) {
const bool haveChanged = change();
updateChanger(haveChanged);
}
updateLanes(t);
} catch (const ProcessError&) {
// clean up locks or the gui may hang
for (ChangerIt ce = myChanger.begin(); ce != myChanger.end(); ++ce) {
ce->lane->releaseVehicles();
}
throw;
}
}
void
MSLaneChanger::initChanger() {
// Prepare myChanger with a safe state.
for (ChangerIt ce = myChanger.begin(); ce != myChanger.end(); ++ce) {
ce->lead = nullptr;
ce->hoppedVeh = nullptr;
ce->lastBlocked = nullptr;
ce->firstBlocked = nullptr;
ce->dens = 0;
ce->lane->getVehiclesSecure();
//std::cout << SIMTIME << " initChanger lane=" << ce->lane->getID() << " vehicles=" << toString(ce->lane->myVehicles) << "\n";
}
}
void
MSLaneChanger::updateChanger(bool vehHasChanged) {
assert(veh(myCandi) != 0);
// "Push" the vehicles to the back, i.e. follower becomes vehicle,
// vehicle becomes leader, and leader becomes predecessor of vehicle,
// if it exists.
if (!vehHasChanged) {
//std::cout << SIMTIME << " updateChanger: lane=" << myCandi->lane->getID() << " has new lead=" << veh(myCandi)->getID() << "\n";
myCandi->lead = veh(myCandi);
}
MSLane::VehCont& vehicles = myCandi->lane->myVehicles;
vehicles.pop_back();
//std::cout << SIMTIME << " updateChanger lane=" << myCandi->lane->getID() << " vehicles=" << toString(myCandi->lane->myVehicles) << "\n";
}
void
MSLaneChanger::updateLanes(SUMOTime t) {
// Update the lane's vehicle-container.
// First: it is bad style to change other classes members, but for
// this release, other attempts were too time-consuming. In a next
// release we will change from this lane-centered design to a vehicle-
// centered. This will solve many problems.
// Second: this swap would be faster if vehicle-containers would have
// been pointers, but then I had to change too much of the MSLane code.
for (ChangerIt ce = myChanger.begin(); ce != myChanger.end(); ++ce) {
//std::cout << SIMTIME << " updateLanes lane=" << ce->lane->getID() << " myVehicles=" << toString(ce->lane->myVehicles) << " myTmpVehicles=" << toString(ce->lane->myTmpVehicles) << "\n";
ce->lane->swapAfterLaneChange(t);
ce->lane->releaseVehicles();
}
}
MSLaneChanger::ChangerIt
MSLaneChanger::findCandidate() {
// Find the vehicle in myChanger with the largest position. If there
// is no vehicle in myChanger (shouldn't happen) , return myChanger.end().
ChangerIt max = myChanger.end();
#ifdef DEBUG_CANDIDATE
std::cout << SIMTIME << " findCandidate() on edge " << myChanger.begin()->lane->getEdge().getID() << std::endl;
#endif
for (ChangerIt ce = myChanger.begin(); ce != myChanger.end(); ++ce) {
if (veh(ce) == nullptr) {
continue;
}
#ifdef DEBUG_CANDIDATE
std::cout << " lane = " << ce->lane->getID() << "\n";
std::cout << " check vehicle=" << veh(ce)->getID() << " pos=" << veh(ce)->getPositionOnLane() << " lane=" << ce->lane->getID() << " isFrontOnLane=" << veh(ce)->isFrontOnLane(ce->lane) << "\n";
#endif
if (max == myChanger.end()) {
#ifdef DEBUG_CANDIDATE
std::cout << " new max vehicle=" << veh(ce)->getID() << " pos=" << veh(ce)->getPositionOnLane() << " lane=" << ce->lane->getID() << " isFrontOnLane=" << veh(ce)->isFrontOnLane(ce->lane) << "\n";
#endif
max = ce;
continue;
}
assert(veh(ce) != 0);
assert(veh(max) != 0);
if (veh(max)->getPositionOnLane() < veh(ce)->getPositionOnLane()) {
#ifdef DEBUG_CANDIDATE
std::cout << " new max vehicle=" << veh(ce)->getID() << " pos=" << veh(ce)->getPositionOnLane() << " lane=" << ce->lane->getID() << " isFrontOnLane=" << veh(ce)->isFrontOnLane(ce->lane) << " oldMaxPos=" << veh(max)->getPositionOnLane() << "\n";
#endif
max = ce;
}
}
assert(max != myChanger.end());
assert(veh(max) != 0);
return max;
}
bool
MSLaneChanger::mayChange(int direction) const {
if (direction == 0) {
return true;
}
if (!myAllowsChanging) {
return false;
}
if (direction == -1) {
return myCandi->mayChangeRight && (myCandi - 1)->lane->allowsVehicleClass(veh(myCandi)->getVehicleType().getVehicleClass());
} else if (direction == 1) {
return myCandi->mayChangeLeft && (myCandi + 1)->lane->allowsVehicleClass(veh(myCandi)->getVehicleType().getVehicleClass());
} else {
return false;
}
}
bool
MSLaneChanger::change() {
// Find change-candidate. If it is on an allowed lane, try to change
// to the right (there is a rule in Germany that you have to change
// to the right, unless you are overtaking). If change to the right
// isn't possible, check if there is a possibility to overtake (on the
// left.
// If candidate isn't on an allowed lane, changing to an allowed has
// priority.
#ifdef DEBUG_ACTIONSTEPS
// std::cout<< "\nCHANGE" << std::endl;
#endif
myCandi = findCandidate();
MSVehicle* vehicle = veh(myCandi);
vehicle->getLaneChangeModel().clearNeighbors();
if (vehicle->getLaneChangeModel().isChangingLanes()) {
return continueChange(vehicle, myCandi);
}
if (!myAllowsChanging || vehicle->getLaneChangeModel().alreadyChanged() || vehicle->isStoppedOnLane()) {
registerUnchanged(vehicle);
return false;
}
if (!vehicle->isActive()) {
#ifdef DEBUG_ACTIONSTEPS
if DEBUG_COND {
std::cout << SIMTIME << " veh '" << vehicle->getID() << "' skips regular change checks." << std::endl;
}
#endif
bool changed = false;
const int oldstate = vehicle->getLaneChangeModel().getOwnState();
// let TraCI influence the wish to change lanes during non-actionsteps
checkTraCICommands(vehicle);
if (oldstate != vehicle->getLaneChangeModel().getOwnState()) {
changed = applyTraCICommands(vehicle);
}
if (!changed) {
registerUnchanged(vehicle);
}
return changed;
}
// Check for changes to the opposite lane if vehicle is active
std::pair<MSVehicle* const, double> leader = getRealLeader(myCandi);
if (myChanger.size() == 1 || vehicle->getLaneChangeModel().isOpposite() || (!mayChange(-1) && !mayChange(1))) {
if (changeOpposite(leader)) {
return true;
}
registerUnchanged(vehicle);
return false;
}
vehicle->updateBestLanes(); // needed?
for (int i = 0; i < (int) myChanger.size(); ++i) {
vehicle->adaptBestLanesOccupation(i, myChanger[i].dens);
}
const std::vector<MSVehicle::LaneQ>& preb = vehicle->getBestLanes();
// check whether the vehicle wants and is able to change to right lane
int stateRight = 0;
if (mayChange(-1)) {
stateRight = checkChangeWithinEdge(-1, leader, preb);
// change if the vehicle wants to and is allowed to change
if ((stateRight & LCA_RIGHT) != 0 && (stateRight & LCA_BLOCKED) == 0) {
vehicle->getLaneChangeModel().setOwnState(stateRight);
return startChange(vehicle, myCandi, -1);
}
if ((stateRight & LCA_RIGHT) != 0 && (stateRight & LCA_URGENT) != 0) {
(myCandi - 1)->lastBlocked = vehicle;
if ((myCandi - 1)->firstBlocked == nullptr) {
(myCandi - 1)->firstBlocked = vehicle;
}
}
}
// check whether the vehicle wants and is able to change to left lane
int stateLeft = 0;
if (mayChange(1)) {
stateLeft = checkChangeWithinEdge(1, leader, preb);
// change if the vehicle wants to and is allowed to change
if ((stateLeft & LCA_LEFT) != 0 && (stateLeft & LCA_BLOCKED) == 0) {
vehicle->getLaneChangeModel().setOwnState(stateLeft);
return startChange(vehicle, myCandi, 1);
}
if ((stateLeft & LCA_LEFT) != 0 && (stateLeft & LCA_URGENT) != 0) {
(myCandi + 1)->lastBlocked = vehicle;
if ((myCandi + 1)->firstBlocked == nullptr) {
(myCandi + 1)->firstBlocked = vehicle;
}
}
}
if ((stateRight & LCA_URGENT) != 0 && (stateLeft & LCA_URGENT) != 0) {
// ... wants to go to the left AND to the right
// just let them go to the right lane...
stateLeft = 0;
}
vehicle->getLaneChangeModel().setOwnState(stateRight | stateLeft);
// only emergency vehicles should change to the opposite side on a
// multi-lane road
if (vehicle->getVehicleType().getVehicleClass() == SVC_EMERGENCY
&& changeOpposite(leader)) {
return true;
}
registerUnchanged(vehicle);
return false;
}
void
MSLaneChanger::registerUnchanged(MSVehicle* vehicle) {
myCandi->lane->myTmpVehicles.insert(myCandi->lane->myTmpVehicles.begin(), veh(myCandi));
myCandi->dens += vehicle->getVehicleType().getLengthWithGap();
vehicle->getLaneChangeModel().unchanged();
}
void
MSLaneChanger::checkTraCICommands(MSVehicle* vehicle) {
#ifdef DEBUG_STATE
const int oldstate = vehicle->getLaneChangeModel().getOwnState();
#endif
vehicle->getLaneChangeModel().checkTraCICommands();
#ifdef DEBUG_STATE
if (DEBUG_COND) {
const int newstate = vehicle->getLaneChangeModel().getOwnState();
std::cout << SIMTIME
<< " veh=" << vehicle->getID()
<< " oldState=" << toString((LaneChangeAction) oldstate)
<< " newState=" << toString((LaneChangeAction) newstate)
<< ((newstate & LCA_BLOCKED) != 0 ? " (blocked)" : "")
<< ((newstate & LCA_OVERLAPPING) != 0 ? " (overlap)" : "")
<< "\n";
}
#endif
}
bool
MSLaneChanger::applyTraCICommands(MSVehicle* vehicle) {
// Execute request if not blocked
bool changed = false;
const int state = vehicle->getLaneChangeModel().getOwnState();
const int dir = (state & LCA_RIGHT) != 0 ? -1 : ((state & LCA_LEFT) != 0 ? 1 : 0);
const bool execute = dir != 0 && ((state & LCA_BLOCKED) == 0);
if (execute) {
ChangerIt to = myCandi + dir;
bool continuous = vehicle->getLaneChangeModel().startLaneChangeManeuver(myCandi->lane, to->lane, dir);
if (continuous) {
changed = continueChange(vehicle, myCandi);
} else {
// insert vehicle into target lane
to->registerHop(vehicle);
changed = true;
}
}
return changed;
}
bool
MSLaneChanger::startChange(MSVehicle* vehicle, ChangerIt& from, int direction) {
if (vehicle->isRemoteControlled()) {
registerUnchanged(vehicle);
return false;
}
ChangerIt to = from + direction;
// @todo delay entering the target lane until the vehicle intersects it
// physically (considering lane width and vehicle width)
//if (to->lane->getID() == "beg_1") std::cout << SIMTIME << " startChange to lane=" << to->lane->getID() << " myTmpVehiclesBefore=" << toString(to->lane->myTmpVehicles) << "\n";
const bool continuous = vehicle->getLaneChangeModel().startLaneChangeManeuver(from->lane, to->lane, direction);
if (continuous) {
return continueChange(vehicle, myCandi);
} else {
to->registerHop(vehicle);
to->lane->requireCollisionCheck();
return true;
}
}
bool
MSLaneChanger::continueChange(MSVehicle* vehicle, ChangerIt& from) {
MSAbstractLaneChangeModel& lcm = vehicle->getLaneChangeModel();
const int direction = lcm.getLaneChangeDirection();
const bool pastMidpoint = lcm.updateCompletion();
vehicle->myState.myPosLat += SPEED2DIST(lcm.getSpeedLat());
vehicle->myCachedPosition = Position::INVALID;
if (pastMidpoint) {
ChangerIt to = from + direction;
MSLane* source = myCandi->lane;
MSLane* target = to->lane;
vehicle->myState.myPosLat -= direction * 0.5 * (source->getWidth() + target->getWidth());
lcm.primaryLaneChanged(source, target, direction);
to->registerHop(vehicle);
to->lane->requireCollisionCheck();
} else {
from->registerHop(vehicle);
from->lane->requireCollisionCheck();
}
if (!lcm.isChangingLanes()) {
vehicle->myState.myPosLat = 0;
lcm.endLaneChangeManeuver();
}
lcm.updateShadowLane();
if (lcm.getShadowLane() != nullptr) {
// set as hoppedVeh on the shadow lane so it is found as leader on both lanes
ChangerIt shadow = pastMidpoint ? from : from + lcm.getShadowDirection();
shadow->hoppedVeh = vehicle;
lcm.getShadowLane()->requireCollisionCheck();
}
vehicle->myAngle = vehicle->computeAngle();
#ifdef DEBUG_CONTINUE_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME
<< " continueChange veh=" << vehicle->getID()
<< " from=" << Named::getIDSecure(from->lane)
<< " dir=" << direction
<< " pastMidpoint=" << pastMidpoint
<< " posLat=" << vehicle->getLateralPositionOnLane()
//<< " completion=" << lcm.getLaneChangeCompletion()
<< " shadowLane=" << Named::getIDSecure(lcm.getShadowLane())
//<< " shadowHopped=" << Named::getIDSecure(shadow->lane)
<< "\n";
}
#endif
return pastMidpoint && lcm.getShadowLane() == nullptr;
}
std::pair<MSVehicle* const, double>
MSLaneChanger::getRealLeader(const ChangerIt& target) const {
assert(veh(myCandi) != 0);
MSVehicle* vehicle = veh(myCandi);
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << SIMTIME << " veh '" << vehicle->getID() << "' looks for leader on lc-target lane '" << target->lane->getID() << "'." << std::endl;
}
#endif
// get the leading vehicle on the lane to change to
MSVehicle* neighLead = target->lead;
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
if (neighLead != 0) {
std::cout << "Considering '" << neighLead->getID() << "' at position " << neighLead->getPositionOnLane() << std::endl;
}
}
#endif
//if (veh(myCandi)->getID() == "disabled") std::cout << SIMTIME
// << " target=" << target->lane->getID()
// << " neighLead=" << Named::getIDSecure(neighLead)
// << " hopped=" << Named::getIDSecure(target->hoppedVeh)
// << " (416)\n";
// check whether the hopped vehicle became the leader
if (target->hoppedVeh != nullptr) {
double hoppedPos = target->hoppedVeh->getPositionOnLane();
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << "Considering hopped vehicle '" << target->hoppedVeh->getID() << "' at position " << hoppedPos << std::endl;
}
#endif
if (hoppedPos > veh(myCandi)->getPositionOnLane() && (neighLead == nullptr || neighLead->getPositionOnLane() > hoppedPos)) {
neighLead = target->hoppedVeh;
//if (veh(myCandi)->getID() == "flow.21") std::cout << SIMTIME << " neighLead=" << Named::getIDSecure(neighLead) << " (422)\n";
}
}
if (neighLead == nullptr) {
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << "Looking for leader on consecutive lanes." << std::endl;
}
#endif
// There's no leader on the target lane. Look for leaders on consecutive lanes.
// (there might also be partial leaders due to continuous lane changing)
MSLane* targetLane = target->lane;
const double egoBack = vehicle->getBackPositionOnLane();
double leaderBack = targetLane->getLength();
for (MSVehicle* pl : targetLane->myPartialVehicles) {
double plBack = pl->getBackPositionOnLane(targetLane);
if (plBack < leaderBack &&
pl->getPositionOnLane(targetLane) + pl->getVehicleType().getMinGap() >= egoBack) {
neighLead = pl;
leaderBack = plBack;
}
}
if (neighLead != nullptr) {
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << " found leader=" << neighLead->getID() << " (partial)\n";
}
#endif
return std::pair<MSVehicle*, double>(neighLead, leaderBack - vehicle->getPositionOnLane() - vehicle->getVehicleType().getMinGap());
}
double seen = myCandi->lane->getLength() - veh(myCandi)->getPositionOnLane();
double speed = veh(myCandi)->getSpeed();
double dist = veh(myCandi)->getCarFollowModel().brakeGap(speed) + veh(myCandi)->getVehicleType().getMinGap();
// always check for link leaders while on an internal lane
if (seen > dist && !myCandi->lane->isInternal()) {
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << " found no leader within dist=" << dist << "\n";
}
#endif
return std::pair<MSVehicle* const, double>(static_cast<MSVehicle*>(nullptr), -1);
}
const std::vector<MSLane*>& bestLaneConts = veh(myCandi)->getBestLanesContinuation(targetLane);
std::pair<MSVehicle* const, double> result = target->lane->getLeaderOnConsecutive(dist, seen, speed, *veh(myCandi), bestLaneConts);
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << " found consecutiveLeader=" << Named::getIDSecure(result.first) << "\n";
}
#endif
return result;
} else {
MSVehicle* candi = veh(myCandi);
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << " found leader=" << neighLead->getID() << "\n";
}
#endif
return std::pair<MSVehicle* const, double>(neighLead, neighLead->getBackPositionOnLane(target->lane) - candi->getPositionOnLane() - candi->getVehicleType().getMinGap());
}
}
std::pair<MSVehicle* const, double>
MSLaneChanger::getRealFollower(const ChangerIt& target) const {
assert(veh(myCandi) != 0);
#ifdef DEBUG_SURROUNDING_VEHICLES
MSVehicle* vehicle = veh(myCandi);
if (DEBUG_COND) {
std::cout << SIMTIME << " veh '" << vehicle->getID() << "' looks for follower on lc-target lane '" << target->lane->getID() << "'." << std::endl;
}
#endif
MSVehicle* candi = veh(myCandi);
const double candiPos = candi->getPositionOnLane();
MSVehicle* neighFollow = veh(target);
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
if (neighFollow != 0) {
std::cout << "veh(target) returns '" << neighFollow->getID() << "' at position " << neighFollow->getPositionOnLane() << std::endl;
} else {
std::cout << "veh(target) returns none." << std::endl;
}
}
#endif
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
if (getCloserFollower(candiPos, neighFollow, target->hoppedVeh) != neighFollow) {
std::cout << "Hopped vehicle '" << target->hoppedVeh->getID() << "' at position " << target->hoppedVeh->getPositionOnLane() << " is closer." << std::endl;
}
}
#endif
// check whether the hopped vehicle became the follower
neighFollow = getCloserFollower(candiPos, neighFollow, target->hoppedVeh);
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
MSVehicle* partialBehind = getCloserFollower(candiPos, neighFollow, target->lane->getPartialBehind(candi));
if (partialBehind != 0 && partialBehind != neighFollow) {
std::cout << "'Partial behind'-vehicle '" << target->lane->getPartialBehind(candi)->getID() << "' at position " << partialBehind->getPositionOnLane() << " is closer." << std::endl;
}
}
#endif
// or a follower which is partially lapping into the target lane
neighFollow = getCloserFollower(candiPos, neighFollow, target->lane->getPartialBehind(candi));
if (neighFollow == nullptr) {
CLeaderDist consecutiveFollower = target->lane->getFollowersOnConsecutive(candi, candi->getBackPositionOnLane(), true)[0];
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
if (consecutiveFollower.first == 0) {
std::cout << "no follower found." << std::endl;
} else {
std::cout << "found follower '" << consecutiveFollower.first->getID() << "' on consecutive lanes." << std::endl;
}
}
#endif
return std::make_pair(const_cast<MSVehicle*>(consecutiveFollower.first), consecutiveFollower.second);
} else {
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << "found follower '" << neighFollow->getID() << "'." << std::endl;
}
#endif
MSVehicle* candi = veh(myCandi);
return std::pair<MSVehicle* const, double>(neighFollow,
candi->getPositionOnLane() - candi->getVehicleType().getLength() - neighFollow->getPositionOnLane() - neighFollow->getVehicleType().getMinGap());
}
}
MSVehicle*
MSLaneChanger::getCloserFollower(const double maxPos, MSVehicle* follow1, MSVehicle* follow2) {
if (follow1 == nullptr || follow1->getPositionOnLane() > maxPos) {
return follow2;
} else if (follow2 == nullptr || follow2->getPositionOnLane() > maxPos) {
return follow1;
} else {
if (follow1->getPositionOnLane() > follow2->getPositionOnLane()) {
return follow1;
} else {
return follow2;
}
}
}
int
MSLaneChanger::checkChangeWithinEdge(
int laneOffset,
const std::pair<MSVehicle* const, double>& leader,
const std::vector<MSVehicle::LaneQ>& preb) const {
std::pair<MSVehicle* const, double> neighLead = getRealLeader(myCandi + laneOffset);
std::pair<MSVehicle*, double> neighFollow = getRealFollower(myCandi + laneOffset);
if (neighLead.first != nullptr && neighLead.first == neighFollow.first) {
// vehicles should not be leader and follower at the same time to avoid
// contradictory behavior
neighFollow.first = 0;
}
ChangerIt target = myCandi + laneOffset;
return checkChange(laneOffset, target->lane, leader, neighLead, neighFollow, preb);
}
int
MSLaneChanger::checkChange(
int laneOffset,
const MSLane* targetLane,
const std::pair<MSVehicle* const, double>& leader,
const std::pair<MSVehicle* const, double>& neighLead,
const std::pair<MSVehicle* const, double>& neighFollow,
const std::vector<MSVehicle::LaneQ>& preb) const {
MSVehicle* vehicle = veh(myCandi);
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout
<< "\n" << SIMTIME << " checkChange() for vehicle '" << vehicle->getID() << "'"
<< std::endl;
}
#endif
int blocked = 0;
int blockedByLeader = (laneOffset == -1 ? LCA_BLOCKED_BY_RIGHT_LEADER : LCA_BLOCKED_BY_LEFT_LEADER);
int blockedByFollower = (laneOffset == -1 ? LCA_BLOCKED_BY_RIGHT_FOLLOWER : LCA_BLOCKED_BY_LEFT_FOLLOWER);
// overlap
if (neighFollow.first != nullptr && neighFollow.second < 0) {
blocked |= (blockedByFollower | LCA_OVERLAPPING);
// Debug (Leo)
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME
<< " overlapping with follower..."
<< std::endl;
}
#endif
}
if (neighLead.first != nullptr && neighLead.second < 0) {
blocked |= (blockedByLeader | LCA_OVERLAPPING);
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME
<< " overlapping with leader..."
<< std::endl;
}
#endif
}
double secureFrontGap = MSAbstractLaneChangeModel::NO_NEIGHBOR;
double secureBackGap = MSAbstractLaneChangeModel::NO_NEIGHBOR;
double secureOrigFrontGap = MSAbstractLaneChangeModel::NO_NEIGHBOR;
const double tauRemainder = vehicle->getActionStepLength() == DELTA_T ? 0 : MAX2(vehicle->getCarFollowModel().getHeadwayTime() - TS, 0.);
// safe back gap
if ((blocked & blockedByFollower) == 0 && neighFollow.first != nullptr) {
// Calculate secure gap conservatively with vNextFollower / vNextLeader as
// extrapolated speeds after the driver's expected reaction time (tau).
// NOTE: there exists a possible source for collisions if the follower and the leader
// have desynchronized action steps as the extrapolated speeds can be exceeded in this case
// Expected reaction time (tau) for the follower-vehicle.
// (substracted TS since at this point the vehicles' states are already updated)
const double vNextFollower = neighFollow.first->getSpeed() + MAX2(0., tauRemainder * neighFollow.first->getAcceleration());
const double vNextLeader = vehicle->getSpeed() + MIN2(0., tauRemainder * vehicle->getAcceleration());
// !!! eigentlich: vsafe braucht die Max. Geschwindigkeit beider Spuren
secureBackGap = neighFollow.first->getCarFollowModel().getSecureGap(vNextFollower,
vNextLeader, vehicle->getCarFollowModel().getMaxDecel());
if (neighFollow.second < secureBackGap * vehicle->getLaneChangeModel().getSafetyFactor()) {
blocked |= blockedByFollower;
// Debug (Leo)
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME
<< " back gap unsafe: "
<< "gap = " << neighFollow.second
<< " vNextFollower=" << vNextFollower
<< " vNextEgo=" << vNextLeader
<< ", secureGap = "
<< neighFollow.first->getCarFollowModel().getSecureGap(vNextFollower,
vNextLeader, vehicle->getCarFollowModel().getMaxDecel())
<< std::endl;
}
#endif
}
}
// safe front gap
if ((blocked & blockedByLeader) == 0 && neighLead.first != nullptr) {
// Calculate secure gap conservatively with vNextFollower / vNextLeader as
// extrapolated speeds after the driver's expected reaction time (tau).
// NOTE: there exists a possible source for collisions if the follower and the leader
// have desynchronized action steps as the extrapolated speeds can be exceeded in this case
// Expected reaction time (tau) for the follower-vehicle.
// (substracted TS since at this point the vehicles' states are already updated)
const double vNextFollower = vehicle->getSpeed() + MAX2(0., tauRemainder * vehicle->getAcceleration());
const double vNextLeader = neighLead.first->getSpeed() + MIN2(0., tauRemainder * neighLead.first->getAcceleration());
// !!! eigentlich: vsafe braucht die Max. Geschwindigkeit beider Spuren
secureFrontGap = vehicle->getCarFollowModel().getSecureGap(vNextFollower,
vNextLeader, neighLead.first->getCarFollowModel().getMaxDecel());
if (neighLead.second < secureFrontGap * vehicle->getLaneChangeModel().getSafetyFactor()) {
blocked |= blockedByLeader;
// Debug (Leo)
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME
<< " front gap unsafe: "
<< "gap = " << neighLead.second
<< " vNextLeader=" << vNextLeader
<< " vNextEgo=" << vNextFollower
<< ", secureGap = "
<< vehicle->getCarFollowModel().getSecureGap(vNextFollower,
vNextLeader, neighLead.first->getCarFollowModel().getMaxDecel())
<< std::endl;
}
#endif
}
}
if (blocked == 0 && MSPModel::getModel()->hasPedestrians(targetLane)) {
PersonDist leader = MSPModel::getModel()->nextBlocking(targetLane, vehicle->getBackPositionOnLane(),
vehicle->getRightSideOnLane(), vehicle->getRightSideOnLane() + vehicle->getVehicleType().getWidth(),
ceil(vehicle->getSpeed() / vehicle->getCarFollowModel().getMaxDecel()));
if (leader.first != 0) {
const double brakeGap = vehicle->getCarFollowModel().brakeGap(vehicle->getSpeed());
// returned gap value is relative to backPosition
const double gap = leader.second - vehicle->getVehicleType().getLengthWithGap();
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME << " pedestrian on road " + leader.first->getID() << " gap=" << gap << " brakeGap=" << brakeGap << "\n";
}
#endif
if (brakeGap > gap) {
blocked |= blockedByLeader;
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME << " blocked by pedestrian " + leader.first->getID() << "\n";
}
#endif
}
}
}
if (leader.first != nullptr) {
secureOrigFrontGap = vehicle->getCarFollowModel().getSecureGap(vehicle->getSpeed(), leader.first->getSpeed(), leader.first->getCarFollowModel().getMaxDecel());
}
MSAbstractLaneChangeModel::MSLCMessager msg(leader.first, neighLead.first, neighFollow.first);
int state = blocked | vehicle->getLaneChangeModel().wantsChange(
laneOffset, msg, blocked, leader, neighLead, neighFollow, *targetLane, preb, &(myCandi->lastBlocked), &(myCandi->firstBlocked));
if (blocked == 0 && (state & LCA_WANTS_LANECHANGE) != 0 && neighLead.first != nullptr) {
// do a more careful (but expensive) check to ensure that a
// safety-critical leader is not being overlooked
// while changing on an intersection, it is not sufficient to abort the
// search with a leader on the current lane because all linkLeaders must
// be considered as well
const double seen = myCandi->lane->getLength() - vehicle->getPositionOnLane();
const double speed = vehicle->getSpeed();
const double dist = vehicle->getCarFollowModel().brakeGap(speed) + vehicle->getVehicleType().getMinGap();
if (seen < dist || myCandi->lane->isInternal()) {
std::pair<MSVehicle* const, double> neighLead2 = targetLane->getCriticalLeader(dist, seen, speed, *vehicle);
if (neighLead2.first != nullptr && neighLead2.first != neighLead.first) {
const double secureGap = vehicle->getCarFollowModel().getSecureGap(vehicle->getSpeed(),
neighLead2.first->getSpeed(), neighLead2.first->getCarFollowModel().getMaxDecel());
const double secureGap2 = secureGap * vehicle->getLaneChangeModel().getSafetyFactor();
#ifdef DEBUG_SURROUNDING_VEHICLES
if (DEBUG_COND) {
std::cout << SIMTIME << " found critical leader=" << neighLead2.first->getID()
<< " gap=" << neighLead2.second << " secGap=" << secureGap << " secGap2=" << secureGap2 << "\n";
}
#endif
if (neighLead2.second < secureGap2) {
state |= blockedByLeader;
}
}
}
}
if (blocked == 0 && (state & LCA_WANTS_LANECHANGE)) {
// ensure that merging is safe for any upcoming zipper links after changing
if (vehicle->unsafeLinkAhead(targetLane)) {
state |= blockedByLeader;
}
}
if ((state & LCA_BLOCKED) == 0 && (state & LCA_WANTS_LANECHANGE) != 0 && MSGlobals::gLaneChangeDuration > DELTA_T) {
// Ensure that a continuous lane change manoeuvre can be completed before the next turning movement.
// Assume lateral position == 0. (If this should change in the future add + laneOffset*vehicle->getLateralPositionOnLane() to distToNeighLane)
const double distToNeighLane = 0.5 * (vehicle->getLane()->getWidth() + targetLane->getWidth());
// Extrapolate the LC duration if operating with speed dependent lateral speed.
const MSAbstractLaneChangeModel& lcm = vehicle->getLaneChangeModel();
const double assumedDecel = lcm.getAssumedDecelForLaneChangeDuration();
const double estimatedLCDuration = lcm.estimateLCDuration(vehicle->getSpeed(), distToNeighLane, assumedDecel);
if (estimatedLCDuration == -1) {
// Can't guarantee that LC will succeed if vehicle is braking -> assert(lcm.myMaxSpeedLatStanding==0)
#ifdef DEBUG_CHECK_CHANGE
if DEBUG_COND {
std::cout << SIMTIME << " checkChange() too slow to guarantee completion of continuous lane change."
<< "\nestimatedLCDuration=" << estimatedLCDuration
<< "\ndistToNeighLane=" << distToNeighLane
<< std::endl;
}
#endif
state |= LCA_INSUFFICIENT_SPEED;
} else {
// Compute covered distance, when braking for the whole lc duration
const double decel = vehicle->getCarFollowModel().getMaxDecel() * estimatedLCDuration;
const double avgSpeed = 0.5 * (
MAX2(0., vehicle->getSpeed() - ACCEL2SPEED(vehicle->getCarFollowModel().getMaxDecel())) +
MAX2(0., vehicle->getSpeed() - decel));
// Distance required for lane change.
const double space2change = avgSpeed * estimatedLCDuration;
// Available distance for LC maneuver (distance till next turn)
double seen = myCandi->lane->getLength() - vehicle->getPositionOnLane();
#ifdef DEBUG_CHECK_CHANGE
if DEBUG_COND {
std::cout << SIMTIME << " checkChange() checking continuous lane change..."
<< "\ndistToNeighLane=" << distToNeighLane
<< " estimatedLCDuration=" << estimatedLCDuration
<< " space2change=" << space2change
<< " avgSpeed=" << avgSpeed
<< std::endl;
}
#endif
// for finding turns it doesn't matter whether we look along the current lane or the target lane
const std::vector<MSLane*>& bestLaneConts = vehicle->getBestLanesContinuation();
int view = 1;
MSLane* nextLane = vehicle->getLane();
MSLinkCont::const_iterator link = MSLane::succLinkSec(*vehicle, view, *nextLane, bestLaneConts);
while (!nextLane->isLinkEnd(link) && seen <= space2change) {
if ((*link)->getDirection() == LINKDIR_LEFT || (*link)->getDirection() == LINKDIR_RIGHT
// the lanes after an internal junction are on different
// edges and do not allow lane-changing
|| (nextLane->getEdge().isInternal() && (*link)->getViaLaneOrLane()->getEdge().isInternal())
) {
state |= LCA_INSUFFICIENT_SPACE;
break;
}
if ((*link)->getViaLane() == nullptr) {
view++;
}
nextLane = (*link)->getViaLaneOrLane();
seen += nextLane->getLength();
// get the next link used
link = MSLane::succLinkSec(*vehicle, view, *nextLane, bestLaneConts);
}
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << " available distance=" << seen << std::endl;
}
#endif
if (nextLane->isLinkEnd(link) && seen < space2change) {
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME << " checkChange insufficientSpace: seen=" << seen << " space2change=" << space2change << "\n";
}
#endif
state |= LCA_INSUFFICIENT_SPACE;
}
if ((state & LCA_BLOCKED) == 0) {
// check for dangerous leaders in case the target lane changes laterally between
// now and the lane-changing midpoint
const double speed = vehicle->getSpeed();
seen = myCandi->lane->getLength() - vehicle->getPositionOnLane();
nextLane = vehicle->getLane();
view = 1;
const double dist = vehicle->getCarFollowModel().brakeGap(speed) + vehicle->getVehicleType().getMinGap();
MSLinkCont::const_iterator link = MSLane::succLinkSec(*vehicle, view, *nextLane, bestLaneConts);
while (!nextLane->isLinkEnd(link) && seen <= space2change && seen <= dist) {
nextLane = (*link)->getViaLaneOrLane();
MSLane* targetLane = nextLane->getParallelLane(laneOffset);
if (targetLane == nullptr) {
state |= LCA_INSUFFICIENT_SPACE;
break;
} else {
std::pair<MSVehicle* const, double> neighLead2 = targetLane->getLeader(vehicle, -seen, std::vector<MSLane*>());
if (neighLead2.first != nullptr && neighLead2.first != neighLead.first
&& (neighLead2.second < vehicle->getCarFollowModel().getSecureGap(
vehicle->getSpeed(), neighLead2.first->getSpeed(), neighLead2.first->getCarFollowModel().getMaxDecel()))) {
state |= blockedByLeader;
break;
}
}
if ((*link)->getViaLane() == nullptr) {
view++;
}
seen += nextLane->getLength();
// get the next link used
link = MSLane::succLinkSec(*vehicle, view, *nextLane, bestLaneConts);
}
}
}
}
const int oldstate = state;
// let TraCI influence the wish to change lanes and the security to take
state = vehicle->influenceChangeDecision(state);
#ifdef DEBUG_CHECK_CHANGE
if (DEBUG_COND) {
std::cout << SIMTIME
<< " veh=" << vehicle->getID()
<< " oldState=" << toString((LaneChangeAction)oldstate)
<< " newState=" << toString((LaneChangeAction)state)
<< ((blocked & LCA_BLOCKED) ? " (blocked)" : "")
<< ((blocked & LCA_OVERLAPPING) ? " (overlap)" : "")
<< "\n";