LCOV - code coverage report
Current view: top level - src/mesosim - MELoop.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 97.3 % 150 146
Test Date: 2026-07-26 16:30:20 Functions: 93.3 % 15 14

            Line data    Source code
       1              : /****************************************************************************/
       2              : // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
       3              : // Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
       4              : // This program and the accompanying materials are made available under the
       5              : // terms of the Eclipse Public License 2.0 which is available at
       6              : // https://www.eclipse.org/legal/epl-2.0/
       7              : // This Source Code may also be made available under the following Secondary
       8              : // Licenses when the conditions for such availability set forth in the Eclipse
       9              : // Public License 2.0 are satisfied: GNU General Public License, version 2
      10              : // or later which is available at
      11              : // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
      12              : // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
      13              : /****************************************************************************/
      14              : /// @file    MELoop.cpp
      15              : /// @author  Daniel Krajzewicz
      16              : /// @date    Tue, May 2005
      17              : ///
      18              : // The main mesocopic simulation loop
      19              : /****************************************************************************/
      20              : #include <config.h>
      21              : 
      22              : #include <queue>
      23              : #include <vector>
      24              : #include <map>
      25              : #include <cmath>
      26              : 
      27              : #include <microsim/MSNet.h>
      28              : #include <microsim/MSEdge.h>
      29              : #include <microsim/MSGlobals.h>
      30              : #include <microsim/MSLane.h>
      31              : #include <microsim/MSVehicle.h>
      32              : #include <microsim/MSVehicleControl.h>
      33              : #include <utils/options/OptionsCont.h>
      34              : #include <utils/common/ToString.h>
      35              : #include <utils/common/FileHelpers.h>
      36              : #include <utils/common/SUMOTime.h>
      37              : #include <utils/common/RandHelper.h>
      38              : #include "MELoop.h"
      39              : #include "MESegment.h"
      40              : #include "MELSegment.h"
      41              : #include "MEVehicle.h"
      42              : 
      43              : 
      44              : // ===========================================================================
      45              : // method definitions
      46              : // ===========================================================================
      47         7002 : MELoop::MELoop(const SUMOTime recheckInterval) : myFullRecheckInterval(recheckInterval), myLinkRecheckInterval(TIME2STEPS(1)) {
      48         7002 : }
      49              : 
      50         6902 : MELoop::~MELoop() {
      51       355038 :     for (std::vector<MESegment*>::const_iterator j = myEdges2FirstSegments.begin(); j != myEdges2FirstSegments.end(); ++j) {
      52      1069934 :         for (MESegment* s = *j; s != nullptr;) {
      53              :             MESegment* n = s->getNextSegment();
      54       721798 :             delete s;
      55              :             s = n;
      56              :         }
      57              :     }
      58         6902 : }
      59              : 
      60              : 
      61              : void
      62     21604397 : MELoop::simulate(SUMOTime tMax) {
      63     58682676 :     while (!myLeaderCars.empty()) {
      64     49289408 :         const SUMOTime time = myLeaderCars.begin()->first;
      65     49289408 :         std::vector<MEVehicle*> vehs = myLeaderCars[time];
      66              :         assert(time > tMax - DELTA_T || vehs.size() == 0);
      67     49289408 :         if (time > tMax) {
      68              :             return;
      69              :         }
      70              :         myLeaderCars.erase(time);
      71     75589245 :         for (std::vector<MEVehicle*>::const_iterator i = vehs.begin(); i != vehs.end(); ++i) {
      72     38510966 :             checkCar(*i);
      73              :             assert(myLeaderCars.empty() || myLeaderCars.begin()->first >= time);
      74              :         }
      75     49289408 :     }
      76              : }
      77              : 
      78              : 
      79              : SUMOTime
      80     38525520 : MELoop::changeSegment(MEVehicle* veh, SUMOTime leaveTime, MESegment* const toSegment, MSMoveReminder::Notification reason, const bool ignoreLink) const {
      81     38525520 :     int qIdx = 0;
      82              :     MESegment* const onSegment = veh->getSegment();
      83              :     if (MESegment::isInvalid(toSegment)) {
      84       798160 :         if (veh->isStoppedTriggered()) {
      85         5398 :             return leaveTime + MAX2(SUMOTime(1), myLinkRecheckInterval);
      86              :         }
      87       792762 :         if (onSegment != nullptr) {
      88       789040 :             onSegment->send(veh, toSegment, qIdx, leaveTime, reason);
      89              :         } else {
      90        11166 :             WRITE_WARNINGF(TL("Vehicle '%' teleports beyond arrival edge '%', time=%."),
      91              :                            veh->getID(), veh->getEdge()->getID(), time2string(leaveTime));
      92              :         }
      93       792762 :         veh->setSegment(toSegment); // signal arrival
      94       792762 :         MSNet::getInstance()->getVehicleControl().scheduleVehicleRemoval(veh);
      95       792762 :         return leaveTime;
      96     37797515 :     } else if (!MSGlobals::gCheckRoutes && !ignoreLink && !MESegment::isInvalid(onSegment) && &onSegment->getEdge() != &toSegment->getEdge() &&
      97        30433 :                veh->getEdge()->allowedLanes(*veh->succEdge(1), veh->getVClass()) == nullptr) {
      98        27072 :         if (veh->isStopped()) {
      99            2 :             veh->processStop();
     100              :         }
     101              :         return SUMOTime_MAX;
     102              :     }
     103     37700288 :     toSegment->updateEntryBlockTime(leaveTime);
     104     37700288 :     const SUMOTime entry = toSegment->hasSpaceFor(veh, leaveTime, qIdx);
     105     37700288 :     if (entry == leaveTime && (ignoreLink || veh->mayProceed())) {
     106     25891355 :         if (onSegment != nullptr) {
     107     25890805 :             if (veh->getQueIndex() == MESegment::PARKING_QUEUE) { // parking or just aborted parking
     108         5653 :                 if (veh->isParking()) {
     109         5652 :                     veh->processStop();
     110              :                 }
     111         5653 :                 veh->getEdge()->getLanes()[0]->removeParking(veh);  // TODO for GUI only
     112              :             } else {
     113     46727465 :                 onSegment->send(veh, toSegment, qIdx, leaveTime, onSegment->getNextSegment() == nullptr ? MSMoveReminder::NOTIFICATION_JUNCTION : MSMoveReminder::NOTIFICATION_SEGMENT);
     114              :             }
     115     25890805 :             toSegment->receive(veh, qIdx, leaveTime, false, ignoreLink, &onSegment->getEdge() != &toSegment->getEdge());
     116              :         } else {
     117         1650 :             WRITE_WARNINGF(TL("Vehicle '%' ends teleporting on edge '%':%, time=%."),
     118              :                            veh->getID(), toSegment->getEdge().getID(), toSegment->getIndex(), time2string(leaveTime));
     119              :             // this is not quite correct but suffices for interrogation by
     120              :             // subsequent methods (veh->getSpeed() needs segment != 0)
     121          550 :             veh->setSegment(myEdges2FirstSegments[veh->getEdge()->getNumericalID()]);
     122              :             // clean up detectors (do not add traffic data)
     123              :             // note: updateDatector is not called if leaveTime == getLastEntryTime()
     124          550 :             veh->updateDetectors(veh->getLastEntryTime(), veh->getEventTime(), true, MSMoveReminder::NOTIFICATION_TELEPORT);
     125          550 :             toSegment->receive(veh, qIdx, leaveTime, false, true, true);
     126              :         }
     127     25891355 :         return entry;
     128              :     }
     129     11808933 :     if (entry == leaveTime && !ignoreLink) { // this is a long way of saying !veh->mayProceed() (which is a costly call)
     130      9503629 :         return entry + MAX2(SUMOTime(1), myLinkRecheckInterval);
     131              :     }
     132              :     return entry;
     133              : }
     134              : 
     135              : 
     136              : void
     137     38510966 : MELoop::checkCar(MEVehicle* veh) {
     138              :     const SUMOTime leaveTime = veh->getEventTime();
     139              :     MESegment* const onSegment = veh->getSegment();
     140     38510966 :     MESegment* const toSegment = veh->getQueIndex() == MESegment::PARKING_QUEUE ? onSegment : nextSegment(onSegment, veh);
     141     38510966 :     const bool teleporting = (onSegment == nullptr); // is the vehicle currently teleporting?
     142              :     // @note reason is only evaluated if toSegment == nullptr
     143     38510966 :     const SUMOTime nextEntry = changeSegment(veh, leaveTime, toSegment, MSMoveReminder::NOTIFICATION_ARRIVED, teleporting);
     144     38510966 :     if (nextEntry == leaveTime) {
     145              :         return;
     146              :     }
     147     11839181 :     const bool r1 = MSGlobals::gTimeToGridlock > 0 && veh->getWaitingTime() > MSGlobals::gTimeToGridlock;
     148     11839181 :     const bool r3 = MSGlobals::gTimeToTeleportDisconnected >= 0 && veh->getWaitingTime() > MSGlobals::gTimeToTeleportDisconnected;
     149     11839181 :     if (!veh->isStopped() && (r1 || r3)) {
     150         8412 :         const bool disconnected = (MSGlobals::gTimeToTeleportDisconnected >= 0
     151         1818 :                                    && veh->succEdge(1) != nullptr
     152        10230 :                                    && veh->getEdge()->allowedLanes(*veh->succEdge(1), veh->getVClass()) == nullptr);
     153         8412 :         if ((r1 && !disconnected) || (r3 && disconnected)) {
     154         6610 :             teleportVehicle(veh, toSegment, disconnected);
     155         6610 :             return;
     156              :         }
     157              :     }
     158     11832571 :     if (veh->getBlockTime() == SUMOTime_MAX && (!veh->isStopped()
     159      8561343 :                 || (!veh->isStoppedTriggered() && veh->isStoppedParking()))) {
     160              :         veh->setBlockTime(leaveTime);
     161              :     }
     162     11832571 :     if (nextEntry == SUMOTime_MAX) {
     163              :         // all usable queues on the next segment are full
     164      2081142 :         SUMOTime newEventTime = MAX3(toSegment->getEventTime() + 1, leaveTime + 1, leaveTime + myFullRecheckInterval);
     165      2081142 :         if (MSGlobals::gTimeToGridlock > 0) {
     166              :             // if teleporting is enabled, make sure we look at the vehicle when the gridlock-time is up
     167      1583977 :             const SUMOTime recheck = MSGlobals::gTimeToTeleportDisconnected >= 0 ? MIN2(MSGlobals::gTimeToGridlock, MSGlobals::gTimeToTeleportDisconnected) : MSGlobals::gTimeToGridlock;
     168      1583977 :             newEventTime = MAX2(MIN2(newEventTime, veh->getBlockTime() + recheck + 1), leaveTime + DELTA_T);
     169              :         }
     170              :         veh->setEventTime(newEventTime);
     171              :     } else {
     172              :         // receiving segment has recently received another vehicle or the junction is blocked
     173              :         veh->setEventTime(nextEntry);
     174              :     }
     175     11832571 :     addLeaderCar(veh, teleporting ? nullptr : onSegment->getLink(veh));
     176              : }
     177              : 
     178              : 
     179              : void
     180         6610 : MELoop::teleportVehicle(MEVehicle* veh, MESegment* const toSegment, bool disconnected) {
     181              :     const SUMOTime leaveTime = veh->getEventTime();
     182              :     MESegment* const onSegment = veh->getSegment();
     183         6610 :     if (MSGlobals::gRemoveGridlocked) {
     184           48 :         WRITE_WARNINGF(TL("Teleporting vehicle '%'; waited too long, from edge '%':%, time=%."),
     185              :                        veh->getID(), onSegment->getEdge().getID(), onSegment->getIndex(),
     186              :                        time2string(leaveTime));
     187           16 :         MSNet::getInstance()->getVehicleControl().registerTeleportJam();
     188              :         int qIdx = 0;
     189           16 :         onSegment->send(veh, nullptr, qIdx, leaveTime, MSMoveReminder::NOTIFICATION_TELEPORT_ARRIVED);
     190           16 :         veh->setSegment(nullptr);
     191           16 :         MSNet::getInstance()->getVehicleControl().scheduleVehicleRemoval(veh);
     192           16 :         return;
     193              :     }
     194              :     const bool teleporting = (onSegment == nullptr); // is the vehicle already teleporting?
     195              :     // try to find a place on the current edge
     196         6594 :     MESegment* teleSegment = disconnected ? toSegment : toSegment->getNextSegment();
     197         8816 :     while (teleSegment != nullptr && changeSegment(veh, leaveTime, teleSegment, MSMoveReminder::NOTIFICATION_TELEPORT, true) != leaveTime) {
     198              :         // @caution the time to get to the next segment here is ignored XXX
     199              :         teleSegment = teleSegment->getNextSegment();
     200              :     }
     201         6594 :     if (teleSegment != nullptr) {
     202          382 :         if (!teleporting) {
     203              :             // we managed to teleport in a single jump
     204          746 :             const std::string reason = disconnected ? " (disconnected)" : "";
     205         1134 :             WRITE_WARNINGF(TL("Teleporting vehicle '%'; waited too long%, from edge '%':% to edge '%':%, time=%."),
     206              :                            veh->getID(), reason, onSegment->getEdge().getID(), onSegment->getIndex(),
     207              :                            teleSegment->getEdge().getID(), teleSegment->getIndex(), time2string(leaveTime));
     208          378 :             MSNet::getInstance()->getVehicleControl().registerTeleportJam();
     209              :         }
     210              :     } else {
     211              :         // teleport across the current edge and try insertion later
     212         6212 :         if (!teleporting) {
     213              :             int qIdx = 0;
     214              :             // announce start of multi-step teleport, arrival will be announced in changeSegment()
     215        12906 :             WRITE_WARNINGF(TL("Teleporting vehicle '%'; waited too long, from edge '%':%, time=%."),
     216              :                            veh->getID(), onSegment->getEdge().getID(), onSegment->getIndex(), time2string(leaveTime));
     217         4302 :             MSNet::getInstance()->getVehicleControl().registerTeleportJam();
     218              :             // remove from current segment
     219         4302 :             onSegment->send(veh, nullptr, qIdx, leaveTime, MSMoveReminder::NOTIFICATION_TELEPORT);
     220              :             // mark veh as teleporting
     221         4302 :             veh->setSegment(nullptr);
     222              :         } else {
     223         1910 :             veh->updateDetectors(veh->getLastEntryTime(), leaveTime, true, MSMoveReminder::NOTIFICATION_TELEPORT);
     224              :         }
     225              :         // @caution microsim uses current travel time teleport duration
     226        18636 :         const SUMOTime teleArrival = leaveTime + TIME2STEPS(veh->getEdge()->getLength() / MAX2(veh->getEdge()->getSpeedLimit(), NUMERICAL_EPS));
     227         6212 :         const bool atDest = veh->moveRoutePointer();
     228         6212 :         if (atDest) {
     229              :             // teleporting to end of route
     230         3722 :             changeSegment(veh, teleArrival, nullptr, MSMoveReminder::NOTIFICATION_TELEPORT_ARRIVED, true);
     231              :         } else {
     232              :             veh->setEventTime(teleArrival);
     233         2490 :             addLeaderCar(veh, nullptr);
     234              :             // teleporting vehicles must react to rerouters
     235         2490 :             getSegmentForEdge(*veh->getEdge())->addReminders(veh);
     236         2490 :             veh->activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION);
     237              :         }
     238              :     }
     239              : }
     240              : 
     241              : 
     242              : void
     243     38520712 : MELoop::addLeaderCar(MEVehicle* veh, MSLink* link) {
     244     38520712 :     myLeaderCars[veh->getEventTime()].push_back(veh);
     245     38520712 :     veh->setApproaching(link);
     246     38520712 : }
     247              : 
     248              : 
     249              : void
     250           12 : MELoop::clearState() {
     251              :     myLeaderCars.clear();
     252           12 : }
     253              : 
     254              : 
     255              : bool
     256         8576 : MELoop::removeLeaderCar(MEVehicle* v) {
     257         8576 :     const auto candIt = myLeaderCars.find(v->getEventTime());
     258         8576 :     if (candIt != myLeaderCars.end()) {
     259         2419 :         std::vector<MEVehicle*>& cands = candIt->second;
     260         2419 :         auto it = find(cands.begin(), cands.end(), v);
     261         2419 :         if (it != cands.end()) {
     262              :             cands.erase(it);
     263              :             return true;
     264              :         }
     265              :     }
     266              :     return false;
     267              : }
     268              : 
     269              : 
     270              : void
     271            0 : MELoop::vaporizeCar(MEVehicle* v, MSMoveReminder::Notification reason) {
     272              :     int qIdx = 0;
     273            0 :     v->getSegment()->send(v, nullptr, qIdx, MSNet::getInstance()->getCurrentTimeStep(), reason);
     274            0 :     removeLeaderCar(v);
     275            0 : }
     276              : 
     277              : 
     278              : MESegment*
     279     38313882 : MELoop::nextSegment(MESegment* s, MEVehicle* v) {
     280     38313882 :     if (s != nullptr) { // vehicle is not teleporting
     281              :         MESegment* next = s->getNextSegment();
     282     38311420 :         if (next != nullptr) {
     283              :             // ok, the street continues
     284              :             return next;
     285              :         }
     286              :     }
     287              :     // we have to check the next edge in the vehicle's route
     288     16899567 :     const MSEdge* nextEdge = v->succEdge(1);
     289     16899567 :     if (nextEdge == nullptr) {
     290              :         // end of route
     291              :         return nullptr;
     292              :     }
     293     16113357 :     if (MSGlobals::gUsingInternalLanes && s != nullptr && s->getEdge().isNormal()) {
     294      3361426 :         const MSEdge* internal = s->getEdge().getInternalFollowingEdge(nextEdge, v->getVClass());
     295      3361426 :         if (internal) {
     296              :             nextEdge = internal;
     297              :         }
     298              :     }
     299     16113357 :     return myEdges2FirstSegments[nextEdge->getNumericalID()];
     300              : }
     301              : 
     302              : 
     303              : int
     304       512999 : MELoop::numSegmentsFor(const double length, const double sLength) {
     305       512999 :     int no = (int)floor(length / sLength + 0.5);
     306       512999 :     if (no == 0) { // assure there is at least one segment
     307              :         return 1;
     308              :     } else {
     309       202141 :         return no;
     310              :     }
     311              : }
     312              : 
     313              : 
     314              : void
     315       350648 : MELoop::buildSegmentsFor(const MSEdge& e, const OptionsCont& oc) {
     316       350648 :     const MESegment::MesoEdgeType& edgeType = MSNet::getInstance()->getMesoType(e.getEdgeType());
     317              :     const double length = e.getLength();
     318       350648 :     const int numSegments = numSegmentsFor(length, edgeType.edgeLength);
     319       350648 :     const double slength = length / (double)numSegments;
     320              :     MESegment* newSegment = nullptr;
     321              :     MESegment* nextSegment = nullptr;
     322       350648 :     const bool laneQueue = oc.getBool("meso-lane-queue");
     323       350648 :     const bool lift = oc.getBool("meso-ltm");
     324       677950 :     bool multiQueue = laneQueue || (oc.getBool("meso-multi-queue") && e.getLanes().size() > 1 && e.getNumSuccessors() > 1);
     325      1077318 :     for (int s = numSegments - 1; s >= 0; s--) {
     326      1453340 :         std::string id = e.getID() + ":" + toString(s);
     327              :         newSegment = lift
     328       726670 :             ? new MELSegment(id, e, nextSegment, slength, e.getLanes()[0]->getSpeedLimit(), s, multiQueue, edgeType)
     329       726670 :             : new MESegment(id, e, nextSegment, slength, e.getLanes()[0]->getSpeedLimit(), s, multiQueue, edgeType);
     330              :         multiQueue = laneQueue;
     331              :         nextSegment = newSegment;
     332              :     }
     333       701296 :     while (e.getNumericalID() >= static_cast<int>(myEdges2FirstSegments.size())) {
     334       350648 :         myEdges2FirstSegments.push_back(0);
     335              :     }
     336       350648 :     myEdges2FirstSegments[e.getNumericalID()] = newSegment;
     337       751355 :     for (MSLane* lane : e.getLanes()) {
     338       400707 :         lane->updateMesoGUISegments();
     339              :     }
     340       350648 : }
     341              : 
     342              : 
     343              : MESegment*
     344    175615105 : MELoop::getSegmentForEdge(const MSEdge& e, double pos) {
     345    175615105 :     if (e.getNumericalID() >= (int)myEdges2FirstSegments.size()) {
     346              :         return nullptr;
     347              :     }
     348    175615081 :     MESegment* s = myEdges2FirstSegments[e.getNumericalID()];
     349    175615081 :     if (pos > 0) {
     350              :         double cpos = 0;
     351       900198 :         while (s->getNextSegment() != nullptr && cpos + s->getLength() < pos) {
     352              :             cpos += s->getLength();
     353              :             s = s->getNextSegment();
     354              :         }
     355              :     }
     356              :     return s;
     357              : }
     358              : 
     359              : 
     360              : bool
     361       241190 : MELoop::isEnteringRoundabout(const MSEdge& e) {
     362       655201 :     for (const MSEdge* succ : e.getSuccessors()) {
     363       414023 :         if (succ->isRoundabout()) {
     364              :             return true;
     365              :         }
     366              :     }
     367              :     return false;
     368              : }
     369              : 
     370              : 
     371              : /****************************************************************************/
        

Generated by: LCOV version 2.0-1