1 // FlightPlan.cxx - flight plan object
3 // Written by James Turner, started 2012.
5 // Copyright (C) 2012 Curtis L. Olson
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 #include "FlightPlan.hxx"
33 #include <boost/algorithm/string/case_conv.hpp>
34 #include <boost/algorithm/string.hpp>
35 #include <boost/foreach.hpp>
38 #include <simgear/structure/exception.hxx>
39 #include <simgear/misc/sg_path.hxx>
40 #include <simgear/magvar/magvar.hxx>
41 #include <simgear/timing/sg_time.hxx>
42 #include <simgear/misc/sgstream.hxx>
43 #include <simgear/misc/strutils.hxx>
44 #include <simgear/props/props_io.hxx>
47 #include <Main/globals.hxx>
48 #include "Main/fg_props.hxx"
49 #include <Navaids/procedure.hxx>
50 #include <Navaids/waypoint.hxx>
57 namespace flightgear {
59 typedef std::vector<FlightPlan::DelegateFactory*> FPDelegateFactoryVec;
60 static FPDelegateFactoryVec static_delegateFactories;
62 FlightPlan::FlightPlan() :
65 _departureRunway(NULL),
66 _destinationRunway(NULL),
72 _departureChanged = _arrivalChanged = _waypointsChanged = _currentWaypointChanged = false;
74 BOOST_FOREACH(DelegateFactory* factory, static_delegateFactories) {
75 Delegate* d = factory->createFlightPlanDelegate(this);
76 if (d) { // factory might not always create a delegate
77 d->_deleteWithPlan = true;
83 FlightPlan::~FlightPlan()
85 // delete all delegates which we own.
86 Delegate* d = _delegate;
90 if (cur->_deleteWithPlan) {
96 FlightPlan* FlightPlan::clone(const string& newIdent) const
98 FlightPlan* c = new FlightPlan();
99 c->_ident = newIdent.empty() ? _ident : newIdent;
102 // copy destination / departure data.
103 c->setDeparture(_departure);
104 c->setDeparture(_departureRunway);
107 c->setApproach(_approach);
108 } else if (_destinationRunway) {
109 c->setDestination(_destinationRunway);
110 } else if (_destination) {
111 c->setDestination(_destination);
118 c->_waypointsChanged = true;
119 for (int l=0; l < numLegs(); ++l) {
120 c->_legs.push_back(_legs[l]->cloneFor(c));
126 void FlightPlan::setIdent(const string& s)
131 string FlightPlan::ident() const
136 FlightPlan::Leg* FlightPlan::insertWayptAtIndex(Waypt* aWpt, int aIndex)
146 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
147 index = _legs.size();
150 insertWayptsAtIndex(wps, index);
151 return legAtIndex(index);
154 void FlightPlan::insertWayptsAtIndex(const WayptVec& wps, int aIndex)
161 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
162 index = _legs.size();
165 LegVec::iterator it = _legs.begin();
168 int endIndex = index + wps.size() - 1;
169 if (_currentIndex >= endIndex) {
170 _currentIndex += wps.size();
174 BOOST_FOREACH(WayptRef wp, wps) {
175 newLegs.push_back(new Leg(this, wp));
179 _waypointsChanged = true;
180 _legs.insert(it, newLegs.begin(), newLegs.end());
184 void FlightPlan::deleteIndex(int aIndex)
187 if (aIndex < 0) { // negative indices count the the end
188 index = _legs.size() + index;
191 if ((index < 0) || (index >= numLegs())) {
192 SG_LOG(SG_NAVAID, SG_WARN, "removeAtIndex with invalid index:" << aIndex);
197 _waypointsChanged = true;
199 LegVec::iterator it = _legs.begin();
205 if (_currentIndex == index) {
206 // current waypoint was removed
207 _currentWaypointChanged = true;
208 } else if (_currentIndex > index) {
209 --_currentIndex; // shift current index down if necessary
215 void FlightPlan::clear()
218 _waypointsChanged = true;
219 _currentWaypointChanged = true;
220 _arrivalChanged = true;
221 _departureChanged = true;
224 BOOST_FOREACH(Leg* l, _legs) {
230 _delegate->runCleared();
238 RemoveWithFlag(WayptFlag f) : flag(f), delCount(0) { }
240 int numDeleted() const { return delCount; }
242 bool operator()(FlightPlan::Leg* leg) const
244 if (leg->waypoint()->flag(flag)) {
254 mutable int delCount;
257 int FlightPlan::clearWayptsWithFlag(WayptFlag flag)
260 // first pass, fix up currentIndex
261 for (int i=0; i<_currentIndex; ++i) {
263 if (l->waypoint()->flag(flag)) {
268 _currentIndex -= count;
270 // now delete and remove
271 RemoveWithFlag rf(flag);
272 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
273 if (it == _legs.end()) {
274 return 0; // nothing was cleared, don't fire the delegate
278 _waypointsChanged = true;
280 _currentWaypointChanged = true;
283 _legs.erase(it, _legs.end());
285 return rf.numDeleted();
288 void FlightPlan::setCurrentIndex(int index)
290 if ((index < -1) || (index >= numLegs())) {
291 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
294 if (index == _currentIndex) {
299 _currentIndex = index;
300 _currentWaypointChanged = true;
304 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
306 for (int i=0; i<numLegs(); ++i) {
307 if (_legs[i]->waypoint()->matches(aPos)) {
315 FlightPlan::Leg* FlightPlan::currentLeg() const
317 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
319 return legAtIndex(_currentIndex);
322 FlightPlan::Leg* FlightPlan::previousLeg() const
324 if (_currentIndex <= 0) {
328 return legAtIndex(_currentIndex - 1);
331 FlightPlan::Leg* FlightPlan::nextLeg() const
333 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
337 return legAtIndex(_currentIndex + 1);
340 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
342 if ((index < 0) || (index >= numLegs())) {
343 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
349 int FlightPlan::findLegIndex(const Leg *l) const
351 for (unsigned int i=0; i<_legs.size(); ++i) {
360 void FlightPlan::setDeparture(FGAirport* apt)
362 if (apt == _departure) {
367 _departureChanged = true;
369 _departureRunway = NULL;
374 void FlightPlan::setDeparture(FGRunway* rwy)
376 if (_departureRunway == rwy) {
381 _departureChanged = true;
383 _departureRunway = rwy;
384 if (rwy->airport() != _departure) {
385 _departure = rwy->airport();
391 void FlightPlan::setSID(SID* sid, const std::string& transition)
398 _departureChanged = true;
400 _sidTransition = transition;
404 void FlightPlan::setSID(Transition* trans)
411 if (trans->parent()->type() != PROCEDURE_SID)
412 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
414 setSID((SID*) trans->parent(), trans->ident());
417 Transition* FlightPlan::sidTransition() const
419 if (!_sid || _sidTransition.empty()) {
423 return _sid->findTransitionByName(_sidTransition);
426 void FlightPlan::setDestination(FGAirport* apt)
428 if (apt == _destination) {
433 _arrivalChanged = true;
435 _destinationRunway = NULL;
436 setSTAR((STAR*)NULL);
441 void FlightPlan::setDestination(FGRunway* rwy)
443 if (_destinationRunway == rwy) {
448 _arrivalChanged = true;
449 _destinationRunway = rwy;
450 if (_destination != rwy->airport()) {
451 _destination = rwy->airport();
452 setSTAR((STAR*)NULL);
458 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
465 _arrivalChanged = true;
467 _starTransition = transition;
471 void FlightPlan::setSTAR(Transition* trans)
474 setSTAR((STAR*) NULL);
478 if (trans->parent()->type() != PROCEDURE_STAR)
479 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
481 setSTAR((STAR*) trans->parent(), trans->ident());
484 Transition* FlightPlan::starTransition() const
486 if (!_star || _starTransition.empty()) {
490 return _star->findTransitionByName(_starTransition);
493 void FlightPlan::setApproach(flightgear::Approach *app)
495 if (_approach == app) {
500 _arrivalChanged = true;
503 // keep runway + airport in sync
504 if (_destinationRunway != _approach->runway()) {
505 _destinationRunway = _approach->runway();
508 if (_destination != _destinationRunway->airport()) {
509 _destination = _destinationRunway->airport();
515 bool FlightPlan::save(const SGPath& path)
517 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
519 SGPropertyNode_ptr d(new SGPropertyNode);
520 d->setIntValue("version", 2);
523 d->setStringValue("departure/airport", _departure->ident());
525 d->setStringValue("departure/sid", _sid->ident());
528 if (_departureRunway) {
529 d->setStringValue("departure/runway", _departureRunway->ident());
534 d->setStringValue("destination/airport", _destination->ident());
536 d->setStringValue("destination/star", _star->ident());
540 d->setStringValue("destination/approach", _approach->ident());
543 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
545 if (_destinationRunway) {
546 d->setStringValue("destination/runway", _destinationRunway->ident());
551 SGPropertyNode* routeNode = d->getChild("route", 0, true);
552 for (unsigned int i=0; i<_legs.size(); ++i) {
553 Waypt* wpt = _legs[i]->waypoint();
554 wpt->saveAsNode(routeNode->getChild("wp", i, true));
555 } // of waypoint iteration
556 writeProperties(path.str(), d, true /* write-all */);
558 } catch (sg_exception& e) {
559 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
564 bool FlightPlan::load(const SGPath& path)
568 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
569 << "'. The file does not exist.");
573 SGPropertyNode_ptr routeData(new SGPropertyNode);
574 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
579 readProperties(path.str(), routeData);
580 } catch (sg_exception& ) {
581 // if XML parsing fails, the file might be simple textual list of waypoints
582 Status = loadPlainTextRoute(path);
584 _waypointsChanged = true;
587 if (routeData.valid())
590 int version = routeData->getIntValue("version", 1);
592 loadVersion1XMLRoute(routeData);
593 } else if (version == 2) {
594 loadVersion2XMLRoute(routeData);
596 throw sg_io_exception("unsupported XML route version");
599 } catch (sg_exception& e) {
600 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
601 << "'. " << e.getMessage());
610 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
613 SGPropertyNode* dep = routeData->getChild("departure");
615 string depIdent = dep->getStringValue("airport");
616 setDeparture((FGAirport*) fgFindAirportID(depIdent));
618 string rwy(dep->getStringValue("runway"));
619 if (_departure->hasRunwayWithIdent(rwy)) {
620 setDeparture(_departure->getRunwayByIdent(rwy));
623 if (dep->hasChild("sid")) {
624 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
626 // departure->setStringValue("transition", dep->getStringValue("transition"));
631 SGPropertyNode* dst = routeData->getChild("destination");
633 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
635 string rwy(dst->getStringValue("runway"));
636 if (_destination->hasRunwayWithIdent(rwy)) {
637 setDestination(_destination->getRunwayByIdent(rwy));
640 if (dst->hasChild("star")) {
641 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
644 if (dst->hasChild("approach")) {
645 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
649 // destination->setStringValue("transition", dst->getStringValue("transition"));
653 SGPropertyNode* alt = routeData->getChild("alternate");
655 //alternate->setStringValue(alt->getStringValue("airport"));
659 SGPropertyNode* crs = routeData->getChild("cruise");
661 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
662 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
663 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
664 } // of cruise data loading
668 void FlightPlan::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
670 loadXMLRouteHeader(routeData);
674 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
675 for (int i=0; i<routeNode->nChildren(); ++i) {
676 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
677 Leg* l = new Leg(this, Waypt::createFromProperties(NULL, wpNode));
679 } // of route iteration
680 _waypointsChanged = true;
683 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
685 loadXMLRouteHeader(routeData);
689 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
690 for (int i=0; i<routeNode->nChildren(); ++i) {
691 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
692 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
694 } // of route iteration
695 _waypointsChanged = true;
698 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
701 if (!_legs.empty()) {
702 lastPos = _legs.back()->waypoint()->position();
703 } else if (_departure) {
704 lastPos = _departure->geod();
708 string ident(aWP->getStringValue("ident"));
709 if (aWP->hasChild("longitude-deg")) {
710 // explicit longitude/latitude
711 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
712 aWP->getDoubleValue("latitude-deg")), ident, NULL);
715 string nid = aWP->getStringValue("navid", ident.c_str());
716 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
722 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
723 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
724 aWP->getDoubleValue("latitude-deg"));
727 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
728 double radialDeg = aWP->getDoubleValue("offset-radial");
729 // convert magnetic radial to a true radial!
730 radialDeg += magvarDegAt(pos);
731 double offsetNm = aWP->getDoubleValue("offset-nm");
733 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
736 w = new BasicWaypt(pos, ident, NULL);
739 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
740 if (altFt > -9990.0) {
741 w->setAltitude(altFt, RESTRICT_AT);
747 bool FlightPlan::loadPlainTextRoute(const SGPath& path)
750 sg_gzifstream in(path.str().c_str());
752 throw sg_io_exception("Cannot open file for reading.");
758 getline(in, line, '\n');
759 // trim CR from end of line, if found
760 if (line[line.size() - 1] == '\r') {
761 line.erase(line.size() - 1, 1);
764 line = simgear::strutils::strip(line);
765 if (line.empty() || (line[0] == '#')) {
766 continue; // ignore empty/comment lines
769 WayptRef w = waypointFromString(line);
771 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
774 _legs.push_back(new Leg(this, w));
775 } // of line iteration
776 } catch (sg_exception& e) {
777 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
785 double FlightPlan::magvarDegAt(const SGGeod& pos) const
787 double jd = globals->get_time_params()->getJD();
788 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
791 WayptRef FlightPlan::waypointFromString(const string& tgt )
793 string target(boost::to_upper_copy(tgt));
798 RouteRestriction altSetting = RESTRICT_NONE;
800 size_t pos = target.find( '@' );
801 if ( pos != string::npos ) {
802 altFt = atof( target.c_str() + pos + 1 );
803 target = target.substr( 0, pos );
804 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
805 altFt *= SG_METER_TO_FEET;
806 altSetting = RESTRICT_AT;
810 pos = target.find( ',' );
811 if ( pos != string::npos ) {
812 double lon = atof( target.substr(0, pos).c_str());
813 double lat = atof( target.c_str() + pos + 1);
815 char ew = (lon < 0.0) ? 'W' : 'E';
816 char ns = (lat < 0.0) ? 'S' : 'N';
817 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
819 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
820 if (altSetting != RESTRICT_NONE) {
821 wpt->setAltitude(altFt, altSetting);
828 // route is empty, use current position
829 basePosition = globals->get_aircraft_position();
831 basePosition = _legs.back()->waypoint()->position();
834 string_list pieces(simgear::strutils::split(target, "/"));
835 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
837 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
841 double magvar = magvarDegAt(basePosition);
843 if (pieces.size() == 1) {
844 wpt = new NavaidWaypoint(p, NULL);
845 } else if (pieces.size() == 3) {
846 // navaid/radial/distance-nm notation
847 double radial = atof(pieces[1].c_str()),
848 distanceNm = atof(pieces[2].c_str());
850 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
851 } else if (pieces.size() == 2) {
852 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
854 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
858 if (!apt->hasRunwayWithIdent(pieces[1])) {
859 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
863 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
864 wpt = new NavaidWaypoint(runway, NULL);
865 } else if (pieces.size() == 4) {
866 // navid/radial/navid/radial notation
867 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
869 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
873 double r1 = atof(pieces[1].c_str()),
874 r2 = atof(pieces[3].c_str());
879 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
881 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
885 std::string name = p->ident() + "-" + p2->ident();
886 wpt = new BasicWaypt(intersection, name, NULL);
890 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
894 if (altSetting != RESTRICT_NONE) {
895 wpt->setAltitude(altFt, altSetting);
900 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
902 _speedRestrict(RESTRICT_NONE),
903 _altRestrict(RESTRICT_NONE),
907 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
909 _speed = _altitudeFt = 0;
912 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
914 Leg* c = new Leg(owner, _waypt);
917 c->_speedRestrict = _speedRestrict;
918 c->_altitudeFt = _altitudeFt;
919 c->_altRestrict = _altRestrict;
924 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
926 return _parent->legAtIndex(index() + 1);
929 unsigned int FlightPlan::Leg::index() const
931 return _parent->findLegIndex(this);
934 int FlightPlan::Leg::altitudeFt() const
936 if (_altRestrict != RESTRICT_NONE) {
940 return _waypt->altitudeFt();
943 int FlightPlan::Leg::speed() const
945 if (_speedRestrict != RESTRICT_NONE) {
949 return _waypt->speed();
952 int FlightPlan::Leg::speedKts() const
957 double FlightPlan::Leg::speedMach() const
959 if (!isMachRestrict(_speedRestrict)) {
963 return -(_speed / 100.0);
966 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
968 if (_altRestrict != RESTRICT_NONE) {
972 return _waypt->altitudeRestriction();
975 RouteRestriction FlightPlan::Leg::speedRestriction() const
977 if (_speedRestrict != RESTRICT_NONE) {
978 return _speedRestrict;
981 return _waypt->speedRestriction();
984 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
987 if (isMachRestrict(ty)) {
988 _speed = (speed * -100);
994 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1000 double FlightPlan::Leg::courseDeg() const
1005 double FlightPlan::Leg::distanceNm() const
1007 return _pathDistance;
1010 double FlightPlan::Leg::distanceAlongRoute() const
1012 return _distanceAlongPath;
1015 void FlightPlan::rebuildLegData()
1017 _totalDistance = 0.0;
1018 int lastLeg = static_cast<int>(_legs.size()) - 1;
1019 for (int l=0; l<lastLeg; ++l) {
1020 Leg* cur = _legs[l];
1021 Leg* next = _legs[l + 1];
1023 std::pair<double, double> crsDist =
1024 next->waypoint()->courseAndDistanceFrom(cur->waypoint()->position());
1025 _legs[l]->_courseDeg = crsDist.first;
1026 _legs[l]->_pathDistance = crsDist.second * SG_METER_TO_NM;
1027 _legs[l]->_distanceAlongPath = _totalDistance;
1028 _totalDistance += crsDist.second * SG_METER_TO_NM;
1029 } // of legs iteration
1031 // set some data on the final leg
1033 // keep the same course as the final leg, when passing the final
1035 _legs[lastLeg]->_courseDeg = _legs[lastLeg - 1]->_courseDeg;
1036 _legs[lastLeg]->_pathDistance = 0.0;
1037 _legs[lastLeg]->_distanceAlongPath = _totalDistance;
1041 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1043 if (aIndex >= (int) _legs.size()) {
1044 throw sg_range_exception();
1047 const int lastLeg = static_cast<int>(_legs.size()) - 1;
1048 // convert the relative offset and leg index into an absolute, positive
1049 // distance in nm from the route origin. This means we can simply walk
1050 // forwards to find the actual leg.
1051 Leg* leg = _legs[(aIndex >= 0) ? aIndex : lastLeg];
1052 double absolutePathDistance = leg->_distanceAlongPath + aOffsetNm;
1053 if (absolutePathDistance < 0.0) {
1054 return _legs[0]->waypoint()->position(); // begining of route
1057 if (absolutePathDistance > _totalDistance) {
1058 return _legs[lastLeg]->waypoint()->position(); // end of route
1061 // find the leg containing the absolute distance
1062 for (int l=0; l<lastLeg; ++l) {
1064 if (absolutePathDistance < leg->_pathDistance) {
1065 break; // found our matching leg
1067 absolutePathDistance -= leg->_pathDistance;
1068 } // of forwards walk along route to find leg
1070 return SGGeodesy::direct(leg->waypoint()->position(),
1071 leg->_courseDeg, absolutePathDistance * SG_NM_TO_METER);
1074 void FlightPlan::lockDelegate()
1076 if (_delegateLock == 0) {
1077 assert(!_departureChanged && !_arrivalChanged &&
1078 !_waypointsChanged && !_currentWaypointChanged);
1084 void FlightPlan::unlockDelegate()
1086 assert(_delegateLock > 0);
1087 if (_delegateLock > 1) {
1092 if (_departureChanged) {
1093 _departureChanged = false;
1095 _delegate->runDepartureChanged();
1099 if (_arrivalChanged) {
1100 _arrivalChanged = false;
1102 _delegate->runArrivalChanged();
1106 if (_waypointsChanged) {
1107 _waypointsChanged = false;
1110 _delegate->runWaypointsChanged();
1114 if (_currentWaypointChanged) {
1115 _currentWaypointChanged = false;
1117 _delegate->runCurrentWaypointChanged();
1124 void FlightPlan::registerDelegateFactory(DelegateFactory* df)
1126 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1127 static_delegateFactories.end(), df);
1128 if (it != static_delegateFactories.end()) {
1129 throw sg_exception("duplicate delegate factory registration");
1132 static_delegateFactories.push_back(df);
1135 void FlightPlan::unregisterDelegateFactory(DelegateFactory* df)
1137 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1138 static_delegateFactories.end(), df);
1139 if (it == static_delegateFactories.end()) {
1143 static_delegateFactories.erase(it);
1146 void FlightPlan::addDelegate(Delegate* d)
1148 // wrap any existing delegate(s) in the new one
1149 d->_inner = _delegate;
1153 void FlightPlan::removeDelegate(Delegate* d)
1155 if (d == _delegate) {
1156 _delegate = _delegate->_inner;
1157 } else if (_delegate) {
1158 _delegate->removeInner(d);
1162 FlightPlan::Delegate::Delegate() :
1163 _deleteWithPlan(false),
1169 FlightPlan::Delegate::~Delegate()
1174 void FlightPlan::Delegate::removeInner(Delegate* d)
1181 // replace with grand-child
1183 } else { // recurse downwards
1184 _inner->removeInner(d);
1188 void FlightPlan::Delegate::runDepartureChanged()
1190 if (_inner) _inner->runDepartureChanged();
1194 void FlightPlan::Delegate::runArrivalChanged()
1196 if (_inner) _inner->runArrivalChanged();
1200 void FlightPlan::Delegate::runWaypointsChanged()
1202 if (_inner) _inner->runWaypointsChanged();
1206 void FlightPlan::Delegate::runCurrentWaypointChanged()
1208 if (_inner) _inner->runCurrentWaypointChanged();
1209 currentWaypointChanged();
1212 void FlightPlan::Delegate::runCleared()
1214 if (_inner) _inner->runCleared();
1218 } // of namespace flightgear