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>
45 #include <simgear/xml/easyxml.hxx>
48 #include <Main/globals.hxx>
49 #include "Main/fg_props.hxx"
50 #include <Navaids/procedure.hxx>
51 #include <Navaids/waypoint.hxx>
58 namespace flightgear {
60 typedef std::vector<FlightPlan::DelegateFactory*> FPDelegateFactoryVec;
61 static FPDelegateFactoryVec static_delegateFactories;
63 FlightPlan::FlightPlan() :
66 _departureRunway(NULL),
67 _destinationRunway(NULL),
73 _departureChanged = _arrivalChanged = _waypointsChanged = _currentWaypointChanged = false;
75 BOOST_FOREACH(DelegateFactory* factory, static_delegateFactories) {
76 Delegate* d = factory->createFlightPlanDelegate(this);
77 if (d) { // factory might not always create a delegate
78 d->_deleteWithPlan = true;
84 FlightPlan::~FlightPlan()
86 // delete all delegates which we own.
87 Delegate* d = _delegate;
91 if (cur->_deleteWithPlan) {
97 BOOST_FOREACH(Leg* l, _legs) {
102 FlightPlan* FlightPlan::clone(const string& newIdent) const
104 FlightPlan* c = new FlightPlan();
105 c->_ident = newIdent.empty() ? _ident : newIdent;
108 // copy destination / departure data.
109 c->setDeparture(_departure);
110 c->setDeparture(_departureRunway);
113 c->setApproach(_approach);
114 } else if (_destinationRunway) {
115 c->setDestination(_destinationRunway);
116 } else if (_destination) {
117 c->setDestination(_destination);
124 c->_waypointsChanged = true;
125 for (int l=0; l < numLegs(); ++l) {
126 c->_legs.push_back(_legs[l]->cloneFor(c));
132 void FlightPlan::setIdent(const string& s)
137 string FlightPlan::ident() const
142 FlightPlan::Leg* FlightPlan::insertWayptAtIndex(Waypt* aWpt, int aIndex)
152 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
153 index = _legs.size();
156 insertWayptsAtIndex(wps, index);
157 return legAtIndex(index);
160 void FlightPlan::insertWayptsAtIndex(const WayptVec& wps, int aIndex)
167 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
168 index = _legs.size();
171 LegVec::iterator it = _legs.begin();
174 int endIndex = index + wps.size() - 1;
175 if (_currentIndex >= endIndex) {
176 _currentIndex += wps.size();
180 BOOST_FOREACH(WayptRef wp, wps) {
181 newLegs.push_back(new Leg(this, wp));
185 _waypointsChanged = true;
186 _legs.insert(it, newLegs.begin(), newLegs.end());
190 void FlightPlan::deleteIndex(int aIndex)
193 if (aIndex < 0) { // negative indices count the the end
194 index = _legs.size() + index;
197 if ((index < 0) || (index >= numLegs())) {
198 SG_LOG(SG_NAVAID, SG_WARN, "removeAtIndex with invalid index:" << aIndex);
203 _waypointsChanged = true;
205 LegVec::iterator it = _legs.begin();
211 if (_currentIndex == index) {
212 // current waypoint was removed
213 _currentWaypointChanged = true;
214 } else if (_currentIndex > index) {
215 --_currentIndex; // shift current index down if necessary
221 void FlightPlan::clear()
224 _waypointsChanged = true;
225 _currentWaypointChanged = true;
226 _arrivalChanged = true;
227 _departureChanged = true;
230 BOOST_FOREACH(Leg* l, _legs) {
236 _delegate->runCleared();
244 RemoveWithFlag(WayptFlag f) : flag(f), delCount(0) { }
246 int numDeleted() const { return delCount; }
248 bool operator()(FlightPlan::Leg* leg) const
250 if (leg->waypoint()->flag(flag)) {
260 mutable int delCount;
263 int FlightPlan::clearWayptsWithFlag(WayptFlag flag)
266 // first pass, fix up currentIndex
267 for (int i=0; i<_currentIndex; ++i) {
269 if (l->waypoint()->flag(flag)) {
274 // test if the current leg will be removed
275 bool currentIsBeingCleared = false;
276 Leg* curLeg = currentLeg();
278 currentIsBeingCleared = curLeg->waypoint()->flag(flag);
281 _currentIndex -= count;
283 // if we're clearing the current waypoint, what shall we do with the
284 // index? there's various options, but safest is to select no waypoint
285 // and let the use re-activate.
286 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1134
287 if (currentIsBeingCleared) {
288 SG_LOG(SG_GENERAL, SG_INFO, "currentIsBeingCleared:" << currentIsBeingCleared);
292 // now delete and remove
293 RemoveWithFlag rf(flag);
294 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
295 if (it == _legs.end()) {
296 return 0; // nothing was cleared, don't fire the delegate
300 _waypointsChanged = true;
301 if ((count > 0) || currentIsBeingCleared) {
302 _currentWaypointChanged = true;
305 _legs.erase(it, _legs.end());
307 if (_legs.empty()) { // maybe all legs were deleted
309 _delegate->runCleared();
314 return rf.numDeleted();
317 void FlightPlan::setCurrentIndex(int index)
319 if ((index < -1) || (index >= numLegs())) {
320 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
323 if (index == _currentIndex) {
328 _currentIndex = index;
329 _currentWaypointChanged = true;
333 void FlightPlan::finish()
335 if (_currentIndex == -1) {
341 _currentWaypointChanged = true;
344 _delegate->runFinished();
350 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
352 for (int i=0; i<numLegs(); ++i) {
353 if (_legs[i]->waypoint()->matches(aPos)) {
361 FlightPlan::Leg* FlightPlan::currentLeg() const
363 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
365 return legAtIndex(_currentIndex);
368 FlightPlan::Leg* FlightPlan::previousLeg() const
370 if (_currentIndex <= 0) {
374 return legAtIndex(_currentIndex - 1);
377 FlightPlan::Leg* FlightPlan::nextLeg() const
379 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
383 return legAtIndex(_currentIndex + 1);
386 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
388 if ((index < 0) || (index >= numLegs())) {
389 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
395 int FlightPlan::findLegIndex(const Leg *l) const
397 for (unsigned int i=0; i<_legs.size(); ++i) {
406 void FlightPlan::setDeparture(FGAirport* apt)
408 if (apt == _departure) {
413 _departureChanged = true;
415 _departureRunway = NULL;
420 void FlightPlan::setDeparture(FGRunway* rwy)
422 if (_departureRunway == rwy) {
427 _departureChanged = true;
429 _departureRunway = rwy;
430 if (rwy->airport() != _departure) {
431 _departure = rwy->airport();
437 void FlightPlan::setSID(SID* sid, const std::string& transition)
444 _departureChanged = true;
446 _sidTransition = transition;
450 void FlightPlan::setSID(Transition* trans)
457 if (trans->parent()->type() != PROCEDURE_SID)
458 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
460 setSID((SID*) trans->parent(), trans->ident());
463 Transition* FlightPlan::sidTransition() const
465 if (!_sid || _sidTransition.empty()) {
469 return _sid->findTransitionByName(_sidTransition);
472 void FlightPlan::setDestination(FGAirport* apt)
474 if (apt == _destination) {
479 _arrivalChanged = true;
481 _destinationRunway = NULL;
482 setSTAR((STAR*)NULL);
487 void FlightPlan::setDestination(FGRunway* rwy)
489 if (_destinationRunway == rwy) {
494 _arrivalChanged = true;
495 _destinationRunway = rwy;
496 if (_destination != rwy->airport()) {
497 _destination = rwy->airport();
498 setSTAR((STAR*)NULL);
504 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
511 _arrivalChanged = true;
513 _starTransition = transition;
517 void FlightPlan::setSTAR(Transition* trans)
520 setSTAR((STAR*) NULL);
524 if (trans->parent()->type() != PROCEDURE_STAR)
525 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
527 setSTAR((STAR*) trans->parent(), trans->ident());
530 Transition* FlightPlan::starTransition() const
532 if (!_star || _starTransition.empty()) {
536 return _star->findTransitionByName(_starTransition);
539 void FlightPlan::setApproach(flightgear::Approach *app)
541 if (_approach == app) {
546 _arrivalChanged = true;
549 // keep runway + airport in sync
550 if (_destinationRunway != _approach->runway()) {
551 _destinationRunway = _approach->runway();
554 if (_destination != _destinationRunway->airport()) {
555 _destination = _destinationRunway->airport();
561 bool FlightPlan::save(const SGPath& path)
563 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
565 SGPropertyNode_ptr d(new SGPropertyNode);
566 d->setIntValue("version", 2);
569 d->setStringValue("departure/airport", _departure->ident());
571 d->setStringValue("departure/sid", _sid->ident());
574 if (_departureRunway) {
575 d->setStringValue("departure/runway", _departureRunway->ident());
580 d->setStringValue("destination/airport", _destination->ident());
582 d->setStringValue("destination/star", _star->ident());
586 d->setStringValue("destination/approach", _approach->ident());
589 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
591 if (_destinationRunway) {
592 d->setStringValue("destination/runway", _destinationRunway->ident());
597 SGPropertyNode* routeNode = d->getChild("route", 0, true);
598 for (unsigned int i=0; i<_legs.size(); ++i) {
599 Waypt* wpt = _legs[i]->waypoint();
600 wpt->saveAsNode(routeNode->getChild("wp", i, true));
601 } // of waypoint iteration
602 writeProperties(path.str(), d, true /* write-all */);
604 } catch (sg_exception& e) {
605 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
610 bool FlightPlan::load(const SGPath& path)
614 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
615 << "'. The file does not exist.");
619 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
624 // try different file formats
625 if (loadGpxFormat(path)) // GPX format
628 if (loadXmlFormat(path)) // XML property data
631 if (loadPlainTextFormat(path)) // simple textual list of waypoints
634 _waypointsChanged = true;
640 /** XML loader for GPX file format */
641 class GpxXmlVisitor : public XMLVisitor
644 GpxXmlVisitor(FlightPlan* fp) : _fp(fp), _lat(-9999), _lon(-9999) {}
646 virtual void startElement (const char * name, const XMLAttributes &atts);
647 virtual void endElement (const char * name);
648 virtual void data (const char * s, int length);
657 void GpxXmlVisitor::startElement(const char * name, const XMLAttributes &atts)
660 if (strcmp(name, "rtept")==0)
665 const char* slat = atts.getValue("lat");
666 const char* slon = atts.getValue("lon");
675 void GpxXmlVisitor::data(const char * s, int length)
677 // use "name" when given, otherwise use "cmt" (comment) as ID
678 if ((_element == "name")||
679 ((_waypoint == "")&&(_element == "cmt")))
681 char* buf = (char*) malloc(length+1);
682 memcpy(buf, s, length);
689 void GpxXmlVisitor::endElement(const char * name)
692 if (strcmp(name, "rtept") == 0)
696 _fp->insertWayptAtIndex(new BasicWaypt(SGGeod::fromDeg(_lon, _lat), _waypoint.c_str(), NULL), -1);
701 /** Load a flightplan in GPX format */
702 bool FlightPlan::loadGpxFormat(const SGPath& path)
704 if (path.lower_extension() != "gpx")
706 // not a valid GPX file
711 GpxXmlVisitor gpxVistor(this);
714 readXML(path.str(), gpxVistor);
715 } catch (sg_exception& e)
717 // XML parsing fails => not a GPX XML file
718 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan in GPX format: '" << e.getOrigin()
719 << "'. " << e.getMessage());
725 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan in GPX format. No route found.");
732 /** Load a flightplan in FlightGear XML property format */
733 bool FlightPlan::loadXmlFormat(const SGPath& path)
735 SGPropertyNode_ptr routeData(new SGPropertyNode);
737 readProperties(path.str(), routeData);
738 } catch (sg_exception& e) {
739 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
740 << "'. " << e.getMessage());
741 // XML parsing fails => not a property XML file
745 if (routeData.valid())
748 int version = routeData->getIntValue("version", 1);
750 loadVersion1XMLRoute(routeData);
751 } else if (version == 2) {
752 loadVersion2XMLRoute(routeData);
754 throw sg_io_exception("unsupported XML route version");
757 } catch (sg_exception& e) {
758 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
759 << "'. " << e.getMessage());
766 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
769 SGPropertyNode* dep = routeData->getChild("departure");
771 string depIdent = dep->getStringValue("airport");
772 setDeparture((FGAirport*) fgFindAirportID(depIdent));
774 string rwy(dep->getStringValue("runway"));
775 if (_departure->hasRunwayWithIdent(rwy)) {
776 setDeparture(_departure->getRunwayByIdent(rwy));
779 if (dep->hasChild("sid")) {
780 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
782 // departure->setStringValue("transition", dep->getStringValue("transition"));
787 SGPropertyNode* dst = routeData->getChild("destination");
789 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
791 string rwy(dst->getStringValue("runway"));
792 if (_destination->hasRunwayWithIdent(rwy)) {
793 setDestination(_destination->getRunwayByIdent(rwy));
796 if (dst->hasChild("star")) {
797 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
800 if (dst->hasChild("approach")) {
801 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
805 // destination->setStringValue("transition", dst->getStringValue("transition"));
809 SGPropertyNode* alt = routeData->getChild("alternate");
811 //alternate->setStringValue(alt->getStringValue("airport"));
815 SGPropertyNode* crs = routeData->getChild("cruise");
817 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
818 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
819 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
820 } // of cruise data loading
824 void FlightPlan::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
826 loadXMLRouteHeader(routeData);
830 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
831 for (int i=0; i<routeNode->nChildren(); ++i) {
832 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
833 Leg* l = new Leg(this, Waypt::createFromProperties(NULL, wpNode));
835 } // of route iteration
836 _waypointsChanged = true;
839 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
841 loadXMLRouteHeader(routeData);
845 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
846 for (int i=0; i<routeNode->nChildren(); ++i) {
847 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
848 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
850 } // of route iteration
851 _waypointsChanged = true;
854 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
857 if (!_legs.empty()) {
858 lastPos = _legs.back()->waypoint()->position();
859 } else if (_departure) {
860 lastPos = _departure->geod();
864 string ident(aWP->getStringValue("ident"));
865 if (aWP->hasChild("longitude-deg")) {
866 // explicit longitude/latitude
867 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
868 aWP->getDoubleValue("latitude-deg")), ident, NULL);
871 string nid = aWP->getStringValue("navid", ident.c_str());
872 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
878 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
879 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
880 aWP->getDoubleValue("latitude-deg"));
883 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
884 double radialDeg = aWP->getDoubleValue("offset-radial");
885 // convert magnetic radial to a true radial!
886 radialDeg += magvarDegAt(pos);
887 double offsetNm = aWP->getDoubleValue("offset-nm");
889 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
892 w = new BasicWaypt(pos, ident, NULL);
895 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
896 if (altFt > -9990.0) {
897 w->setAltitude(altFt, RESTRICT_AT);
903 /** Load a flightplan in FlightGear plain-text format */
904 bool FlightPlan::loadPlainTextFormat(const SGPath& path)
907 sg_gzifstream in(path.str().c_str());
909 throw sg_io_exception("Cannot open file for reading.");
915 getline(in, line, '\n');
916 // trim CR from end of line, if found
917 if (line[line.size() - 1] == '\r') {
918 line.erase(line.size() - 1, 1);
921 line = simgear::strutils::strip(line);
922 if (line.empty() || (line[0] == '#')) {
923 continue; // ignore empty/comment lines
926 WayptRef w = waypointFromString(line);
928 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
931 _legs.push_back(new Leg(this, w));
932 } // of line iteration
933 } catch (sg_exception& e) {
934 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
942 double FlightPlan::magvarDegAt(const SGGeod& pos) const
944 double jd = globals->get_time_params()->getJD();
945 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
948 WayptRef FlightPlan::waypointFromString(const string& tgt )
950 string target(boost::to_upper_copy(tgt));
955 RouteRestriction altSetting = RESTRICT_NONE;
957 size_t pos = target.find( '@' );
958 if ( pos != string::npos ) {
959 altFt = atof( target.c_str() + pos + 1 );
960 target = target.substr( 0, pos );
961 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
962 altFt *= SG_METER_TO_FEET;
963 altSetting = RESTRICT_AT;
967 pos = target.find( ',' );
968 if ( pos != string::npos ) {
969 double lon = atof( target.substr(0, pos).c_str());
970 double lat = atof( target.c_str() + pos + 1);
972 char ew = (lon < 0.0) ? 'W' : 'E';
973 char ns = (lat < 0.0) ? 'S' : 'N';
974 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
976 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
977 if (altSetting != RESTRICT_NONE) {
978 wpt->setAltitude(altFt, altSetting);
985 // route is empty, use current position
986 basePosition = globals->get_aircraft_position();
988 basePosition = _legs.back()->waypoint()->position();
991 string_list pieces(simgear::strutils::split(target, "/"));
992 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
994 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
998 double magvar = magvarDegAt(basePosition);
1000 if (pieces.size() == 1) {
1001 wpt = new NavaidWaypoint(p, NULL);
1002 } else if (pieces.size() == 3) {
1003 // navaid/radial/distance-nm notation
1004 double radial = atof(pieces[1].c_str()),
1005 distanceNm = atof(pieces[2].c_str());
1007 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
1008 } else if (pieces.size() == 2) {
1009 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
1011 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
1015 if (!apt->hasRunwayWithIdent(pieces[1])) {
1016 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
1020 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
1021 wpt = new NavaidWaypoint(runway, NULL);
1022 } else if (pieces.size() == 4) {
1023 // navid/radial/navid/radial notation
1024 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
1026 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
1030 double r1 = atof(pieces[1].c_str()),
1031 r2 = atof(pieces[3].c_str());
1035 SGGeod intersection;
1036 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
1038 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
1042 std::string name = p->ident() + "-" + p2->ident();
1043 wpt = new BasicWaypt(intersection, name, NULL);
1047 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
1051 if (altSetting != RESTRICT_NONE) {
1052 wpt->setAltitude(altFt, altSetting);
1057 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
1059 _speedRestrict(RESTRICT_NONE),
1060 _altRestrict(RESTRICT_NONE),
1064 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
1066 _speed = _altitudeFt = 0;
1069 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
1071 Leg* c = new Leg(owner, _waypt);
1074 c->_speedRestrict = _speedRestrict;
1075 c->_altitudeFt = _altitudeFt;
1076 c->_altRestrict = _altRestrict;
1081 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
1083 return _parent->legAtIndex(index() + 1);
1086 unsigned int FlightPlan::Leg::index() const
1088 return _parent->findLegIndex(this);
1091 int FlightPlan::Leg::altitudeFt() const
1093 if (_altRestrict != RESTRICT_NONE) {
1097 return _waypt->altitudeFt();
1100 int FlightPlan::Leg::speed() const
1102 if (_speedRestrict != RESTRICT_NONE) {
1106 return _waypt->speed();
1109 int FlightPlan::Leg::speedKts() const
1114 double FlightPlan::Leg::speedMach() const
1116 if (!isMachRestrict(_speedRestrict)) {
1120 return -(_speed / 100.0);
1123 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
1125 if (_altRestrict != RESTRICT_NONE) {
1126 return _altRestrict;
1129 return _waypt->altitudeRestriction();
1132 RouteRestriction FlightPlan::Leg::speedRestriction() const
1134 if (_speedRestrict != RESTRICT_NONE) {
1135 return _speedRestrict;
1138 return _waypt->speedRestriction();
1141 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
1143 _speedRestrict = ty;
1144 if (isMachRestrict(ty)) {
1145 _speed = (speed * -100);
1151 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1154 _altitudeFt = altFt;
1157 double FlightPlan::Leg::courseDeg() const
1162 double FlightPlan::Leg::distanceNm() const
1164 return _pathDistance;
1167 double FlightPlan::Leg::distanceAlongRoute() const
1169 return _distanceAlongPath;
1172 void FlightPlan::rebuildLegData()
1174 _totalDistance = 0.0;
1175 int lastLeg = static_cast<int>(_legs.size()) - 1;
1176 for (int l=0; l<lastLeg; ++l) {
1177 Leg* cur = _legs[l];
1178 Leg* next = _legs[l + 1];
1180 std::pair<double, double> crsDist =
1181 next->waypoint()->courseAndDistanceFrom(cur->waypoint()->position());
1182 _legs[l]->_courseDeg = crsDist.first;
1183 _legs[l]->_pathDistance = crsDist.second * SG_METER_TO_NM;
1184 _legs[l]->_distanceAlongPath = _totalDistance;
1185 _totalDistance += crsDist.second * SG_METER_TO_NM;
1186 } // of legs iteration
1188 // set some data on the final leg
1190 // keep the same course as the final leg, when passing the final
1192 _legs[lastLeg]->_courseDeg = _legs[lastLeg - 1]->_courseDeg;
1193 _legs[lastLeg]->_pathDistance = 0.0;
1194 _legs[lastLeg]->_distanceAlongPath = _totalDistance;
1198 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1200 if (aIndex >= (int) _legs.size()) {
1201 throw sg_range_exception();
1204 const int lastLeg = static_cast<int>(_legs.size()) - 1;
1205 // convert the relative offset and leg index into an absolute, positive
1206 // distance in nm from the route origin. This means we can simply walk
1207 // forwards to find the actual leg.
1208 Leg* leg = _legs[(aIndex >= 0) ? aIndex : lastLeg];
1209 double absolutePathDistance = leg->_distanceAlongPath + aOffsetNm;
1210 if (absolutePathDistance < 0.0) {
1211 return _legs[0]->waypoint()->position(); // begining of route
1214 if (absolutePathDistance > _totalDistance) {
1215 return _legs[lastLeg]->waypoint()->position(); // end of route
1218 // find the leg containing the absolute distance
1219 for (int l=0; l<lastLeg; ++l) {
1221 if (absolutePathDistance < leg->_pathDistance) {
1222 break; // found our matching leg
1224 absolutePathDistance -= leg->_pathDistance;
1225 } // of forwards walk along route to find leg
1227 return SGGeodesy::direct(leg->waypoint()->position(),
1228 leg->_courseDeg, absolutePathDistance * SG_NM_TO_METER);
1231 void FlightPlan::lockDelegate()
1233 if (_delegateLock == 0) {
1234 assert(!_departureChanged && !_arrivalChanged &&
1235 !_waypointsChanged && !_currentWaypointChanged);
1241 void FlightPlan::unlockDelegate()
1243 assert(_delegateLock > 0);
1244 if (_delegateLock > 1) {
1249 if (_departureChanged) {
1250 _departureChanged = false;
1252 _delegate->runDepartureChanged();
1256 if (_arrivalChanged) {
1257 _arrivalChanged = false;
1259 _delegate->runArrivalChanged();
1263 if (_waypointsChanged) {
1264 _waypointsChanged = false;
1267 _delegate->runWaypointsChanged();
1271 if (_currentWaypointChanged) {
1272 _currentWaypointChanged = false;
1274 _delegate->runCurrentWaypointChanged();
1281 void FlightPlan::registerDelegateFactory(DelegateFactory* df)
1283 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1284 static_delegateFactories.end(), df);
1285 if (it != static_delegateFactories.end()) {
1286 throw sg_exception("duplicate delegate factory registration");
1289 static_delegateFactories.push_back(df);
1292 void FlightPlan::unregisterDelegateFactory(DelegateFactory* df)
1294 FPDelegateFactoryVec::iterator it = std::find(static_delegateFactories.begin(),
1295 static_delegateFactories.end(), df);
1296 if (it == static_delegateFactories.end()) {
1300 static_delegateFactories.erase(it);
1303 void FlightPlan::addDelegate(Delegate* d)
1305 // wrap any existing delegate(s) in the new one
1306 d->_inner = _delegate;
1310 void FlightPlan::removeDelegate(Delegate* d)
1312 if (d == _delegate) {
1313 _delegate = _delegate->_inner;
1314 } else if (_delegate) {
1315 _delegate->removeInner(d);
1319 FlightPlan::Delegate::Delegate() :
1320 _deleteWithPlan(false),
1325 FlightPlan::Delegate::~Delegate()
1329 void FlightPlan::Delegate::removeInner(Delegate* d)
1332 throw sg_exception("FlightPlan delegate not found");
1336 // replace with grand-child
1338 } else { // recurse downwards
1339 _inner->removeInner(d);
1343 void FlightPlan::Delegate::runDepartureChanged()
1345 if (_inner) _inner->runDepartureChanged();
1349 void FlightPlan::Delegate::runArrivalChanged()
1351 if (_inner) _inner->runArrivalChanged();
1355 void FlightPlan::Delegate::runWaypointsChanged()
1357 if (_inner) _inner->runWaypointsChanged();
1361 void FlightPlan::Delegate::runCurrentWaypointChanged()
1363 if (_inner) _inner->runCurrentWaypointChanged();
1364 currentWaypointChanged();
1367 void FlightPlan::Delegate::runCleared()
1369 if (_inner) _inner->runCleared();
1373 void FlightPlan::Delegate::runFinished()
1375 if (_inner) _inner->runFinished();
1379 } // of namespace flightgear