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>
52 #include <Navaids/routePath.hxx>
59 namespace flightgear {
61 typedef std::vector<FlightPlan::DelegateFactory*> FPDelegateFactoryVec;
62 static FPDelegateFactoryVec static_delegateFactories;
64 FlightPlan::FlightPlan() :
67 _followLegTrackToFix(true),
68 _aircraftCategory(ICAO_AIRCRAFT_CATEGORY_C),
69 _departureRunway(NULL),
70 _destinationRunway(NULL),
77 _departureChanged = _arrivalChanged = _waypointsChanged = _currentWaypointChanged = false;
79 BOOST_FOREACH(DelegateFactory* factory, static_delegateFactories) {
80 Delegate* d = factory->createFlightPlanDelegate(this);
81 if (d) { // factory might not always create a delegate
82 d->_deleteWithPlan = true;
88 FlightPlan::~FlightPlan()
90 // delete all delegates which we own.
91 Delegate* d = _delegate;
95 if (cur->_deleteWithPlan) {
101 BOOST_FOREACH(Leg* l, _legs) {
106 FlightPlan* FlightPlan::clone(const string& newIdent) const
108 FlightPlan* c = new FlightPlan();
109 c->_ident = newIdent.empty() ? _ident : newIdent;
112 // copy destination / departure data.
113 c->setDeparture(_departure);
114 c->setDeparture(_departureRunway);
117 c->setApproach(_approach);
118 } else if (_destinationRunway) {
119 c->setDestination(_destinationRunway);
120 } else if (_destination) {
121 c->setDestination(_destination);
128 c->_waypointsChanged = true;
129 for (int l=0; l < numLegs(); ++l) {
130 c->_legs.push_back(_legs[l]->cloneFor(c));
136 void FlightPlan::setIdent(const string& s)
141 string FlightPlan::ident() const
146 FlightPlan::Leg* FlightPlan::insertWayptAtIndex(Waypt* aWpt, int aIndex)
156 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
157 index = _legs.size();
160 insertWayptsAtIndex(wps, index);
161 return legAtIndex(index);
164 void FlightPlan::insertWayptsAtIndex(const WayptVec& wps, int aIndex)
171 if ((aIndex == -1) || (aIndex > (int) _legs.size())) {
172 index = _legs.size();
175 LegVec::iterator it = _legs.begin();
178 int endIndex = index + wps.size() - 1;
179 if (_currentIndex >= endIndex) {
180 _currentIndex += wps.size();
184 BOOST_FOREACH(WayptRef wp, wps) {
185 newLegs.push_back(new Leg(this, wp));
189 _waypointsChanged = true;
190 _legs.insert(it, newLegs.begin(), newLegs.end());
194 void FlightPlan::deleteIndex(int aIndex)
197 if (aIndex < 0) { // negative indices count the the end
198 index = _legs.size() + index;
201 if ((index < 0) || (index >= numLegs())) {
202 SG_LOG(SG_NAVAID, SG_WARN, "removeAtIndex with invalid index:" << aIndex);
207 _waypointsChanged = true;
209 LegVec::iterator it = _legs.begin();
215 if (_currentIndex == index) {
216 // current waypoint was removed
217 _currentWaypointChanged = true;
218 } else if (_currentIndex > index) {
219 --_currentIndex; // shift current index down if necessary
225 void FlightPlan::clear()
228 _waypointsChanged = true;
229 _currentWaypointChanged = true;
230 _arrivalChanged = true;
231 _departureChanged = true;
234 BOOST_FOREACH(Leg* l, _legs) {
240 _delegate->runCleared();
248 RemoveWithFlag(WayptFlag f) : flag(f), delCount(0) { }
250 int numDeleted() const { return delCount; }
252 bool operator()(FlightPlan::Leg* leg) const
254 if (leg->waypoint()->flag(flag)) {
264 mutable int delCount;
267 int FlightPlan::clearWayptsWithFlag(WayptFlag flag)
270 // first pass, fix up currentIndex
271 for (int i=0; i<_currentIndex; ++i) {
273 if (l->waypoint()->flag(flag)) {
278 // test if the current leg will be removed
279 bool currentIsBeingCleared = false;
280 Leg* curLeg = currentLeg();
282 currentIsBeingCleared = curLeg->waypoint()->flag(flag);
285 _currentIndex -= count;
287 // if we're clearing the current waypoint, what shall we do with the
288 // index? there's various options, but safest is to select no waypoint
289 // and let the use re-activate.
290 // http://code.google.com/p/flightgear-bugs/issues/detail?id=1134
291 if (currentIsBeingCleared) {
292 SG_LOG(SG_GENERAL, SG_INFO, "currentIsBeingCleared:" << currentIsBeingCleared);
296 // now delete and remove
297 RemoveWithFlag rf(flag);
298 LegVec::iterator it = std::remove_if(_legs.begin(), _legs.end(), rf);
299 if (it == _legs.end()) {
300 return 0; // nothing was cleared, don't fire the delegate
304 _waypointsChanged = true;
305 if ((count > 0) || currentIsBeingCleared) {
306 _currentWaypointChanged = true;
309 _legs.erase(it, _legs.end());
311 if (_legs.empty()) { // maybe all legs were deleted
313 _delegate->runCleared();
318 return rf.numDeleted();
321 void FlightPlan::setCurrentIndex(int index)
323 if ((index < -1) || (index >= numLegs())) {
324 throw sg_range_exception("invalid leg index", "FlightPlan::setCurrentIndex");
327 if (index == _currentIndex) {
332 _currentIndex = index;
333 _currentWaypointChanged = true;
337 void FlightPlan::activate()
342 _currentWaypointChanged = true;
345 _delegate->runActivated();
351 void FlightPlan::finish()
353 if (_currentIndex == -1) {
359 _currentWaypointChanged = true;
362 _delegate->runFinished();
368 int FlightPlan::findWayptIndex(const SGGeod& aPos) const
370 for (int i=0; i<numLegs(); ++i) {
371 if (_legs[i]->waypoint()->matches(aPos)) {
379 int FlightPlan::findWayptIndex(const FGPositionedRef aPos) const
381 for (int i=0; i<numLegs(); ++i) {
382 if (_legs[i]->waypoint()->source() == aPos) {
390 FlightPlan::Leg* FlightPlan::currentLeg() const
392 if ((_currentIndex < 0) || (_currentIndex >= numLegs()))
394 return legAtIndex(_currentIndex);
397 FlightPlan::Leg* FlightPlan::previousLeg() const
399 if (_currentIndex <= 0) {
403 return legAtIndex(_currentIndex - 1);
406 FlightPlan::Leg* FlightPlan::nextLeg() const
408 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numLegs())) {
412 return legAtIndex(_currentIndex + 1);
415 FlightPlan::Leg* FlightPlan::legAtIndex(int index) const
417 if ((index < 0) || (index >= numLegs())) {
418 throw sg_range_exception("index out of range", "FlightPlan::legAtIndex");
424 int FlightPlan::findLegIndex(const Leg *l) const
426 for (unsigned int i=0; i<_legs.size(); ++i) {
435 void FlightPlan::setDeparture(FGAirport* apt)
437 if (apt == _departure) {
442 _departureChanged = true;
444 _departureRunway = NULL;
449 void FlightPlan::setDeparture(FGRunway* rwy)
451 if (_departureRunway == rwy) {
456 _departureChanged = true;
458 _departureRunway = rwy;
459 if (rwy->airport() != _departure) {
460 _departure = rwy->airport();
466 void FlightPlan::setSID(SID* sid, const std::string& transition)
473 _departureChanged = true;
475 _sidTransition = transition;
479 void FlightPlan::setSID(Transition* trans)
486 if (trans->parent()->type() != PROCEDURE_SID)
487 throw sg_exception("FlightPlan::setSID: transition does not belong to a SID");
489 setSID((SID*) trans->parent(), trans->ident());
492 Transition* FlightPlan::sidTransition() const
494 if (!_sid || _sidTransition.empty()) {
498 return _sid->findTransitionByName(_sidTransition);
501 void FlightPlan::setDestination(FGAirport* apt)
503 if (apt == _destination) {
508 _arrivalChanged = true;
510 _destinationRunway = NULL;
511 setSTAR((STAR*)NULL);
516 void FlightPlan::setDestination(FGRunway* rwy)
518 if (_destinationRunway == rwy) {
523 _arrivalChanged = true;
524 _destinationRunway = rwy;
525 if (_destination != rwy->airport()) {
526 _destination = rwy->airport();
527 setSTAR((STAR*)NULL);
533 void FlightPlan::setSTAR(STAR* star, const std::string& transition)
540 _arrivalChanged = true;
542 _starTransition = transition;
546 void FlightPlan::setSTAR(Transition* trans)
549 setSTAR((STAR*) NULL);
553 if (trans->parent()->type() != PROCEDURE_STAR)
554 throw sg_exception("FlightPlan::setSTAR: transition does not belong to a STAR");
556 setSTAR((STAR*) trans->parent(), trans->ident());
559 Transition* FlightPlan::starTransition() const
561 if (!_star || _starTransition.empty()) {
565 return _star->findTransitionByName(_starTransition);
568 void FlightPlan::setApproach(flightgear::Approach *app)
570 if (_approach == app) {
575 _arrivalChanged = true;
578 // keep runway + airport in sync
579 if (_destinationRunway != _approach->runway()) {
580 _destinationRunway = _approach->runway();
583 if (_destination != _destinationRunway->airport()) {
584 _destination = _destinationRunway->airport();
590 bool FlightPlan::save(const SGPath& path)
592 SG_LOG(SG_NAVAID, SG_INFO, "Saving route to " << path.str());
594 SGPropertyNode_ptr d(new SGPropertyNode);
595 d->setIntValue("version", 2);
598 d->setStringValue("departure/airport", _departure->ident());
600 d->setStringValue("departure/sid", _sid->ident());
603 if (_departureRunway) {
604 d->setStringValue("departure/runway", _departureRunway->ident());
609 d->setStringValue("destination/airport", _destination->ident());
611 d->setStringValue("destination/star", _star->ident());
615 d->setStringValue("destination/approach", _approach->ident());
618 //d->setStringValue("destination/transition", destination->getStringValue("transition"));
620 if (_destinationRunway) {
621 d->setStringValue("destination/runway", _destinationRunway->ident());
626 SGPropertyNode* routeNode = d->getChild("route", 0, true);
627 for (unsigned int i=0; i<_legs.size(); ++i) {
628 Waypt* wpt = _legs[i]->waypoint();
629 wpt->saveAsNode(routeNode->getChild("wp", i, true));
630 } // of waypoint iteration
631 writeProperties(path.str(), d, true /* write-all */);
633 } catch (sg_exception& e) {
634 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to save flight-plan '" << path.str() << "'. " << e.getMessage());
639 bool FlightPlan::load(const SGPath& path)
643 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << path.str()
644 << "'. The file does not exist.");
648 SG_LOG(SG_NAVAID, SG_INFO, "going to read flight-plan from:" << path.str());
653 // try different file formats
654 if (loadGpxFormat(path)) // GPX format
657 if (loadXmlFormat(path)) // XML property data
660 if (loadPlainTextFormat(path)) // simple textual list of waypoints
663 _waypointsChanged = true;
669 /** XML loader for GPX file format */
670 class GpxXmlVisitor : public XMLVisitor
673 GpxXmlVisitor(FlightPlan* fp) : _fp(fp), _lat(-9999), _lon(-9999) {}
675 virtual void startElement (const char * name, const XMLAttributes &atts);
676 virtual void endElement (const char * name);
677 virtual void data (const char * s, int length);
686 void GpxXmlVisitor::startElement(const char * name, const XMLAttributes &atts)
689 if (strcmp(name, "rtept")==0)
694 const char* slat = atts.getValue("lat");
695 const char* slon = atts.getValue("lon");
704 void GpxXmlVisitor::data(const char * s, int length)
706 // use "name" when given, otherwise use "cmt" (comment) as ID
707 if ((_element == "name")||
708 ((_waypoint == "")&&(_element == "cmt")))
710 char* buf = (char*) malloc(length+1);
711 memcpy(buf, s, length);
718 void GpxXmlVisitor::endElement(const char * name)
721 if (strcmp(name, "rtept") == 0)
725 _fp->insertWayptAtIndex(new BasicWaypt(SGGeod::fromDeg(_lon, _lat), _waypoint.c_str(), NULL), -1);
730 /** Load a flightplan in GPX format */
731 bool FlightPlan::loadGpxFormat(const SGPath& path)
733 if (path.lower_extension() != "gpx")
735 // not a valid GPX file
740 GpxXmlVisitor gpxVistor(this);
743 readXML(path.str(), gpxVistor);
744 } catch (sg_exception& e)
746 // XML parsing fails => not a GPX XML file
747 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan in GPX format: '" << e.getOrigin()
748 << "'. " << e.getMessage());
754 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan in GPX format. No route found.");
761 /** Load a flightplan in FlightGear XML property format */
762 bool FlightPlan::loadXmlFormat(const SGPath& path)
764 SGPropertyNode_ptr routeData(new SGPropertyNode);
766 readProperties(path.str(), routeData);
767 } catch (sg_exception& e) {
768 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
769 << "'. " << e.getMessage());
770 // XML parsing fails => not a property XML file
774 if (routeData.valid())
777 int version = routeData->getIntValue("version", 1);
779 loadVersion1XMLRoute(routeData);
780 } else if (version == 2) {
781 loadVersion2XMLRoute(routeData);
783 throw sg_io_exception("unsupported XML route version");
786 } catch (sg_exception& e) {
787 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load flight-plan '" << e.getOrigin()
788 << "'. " << e.getMessage());
795 void FlightPlan::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
798 SGPropertyNode* dep = routeData->getChild("departure");
800 string depIdent = dep->getStringValue("airport");
801 setDeparture((FGAirport*) fgFindAirportID(depIdent));
803 string rwy(dep->getStringValue("runway"));
804 if (_departure->hasRunwayWithIdent(rwy)) {
805 setDeparture(_departure->getRunwayByIdent(rwy));
808 if (dep->hasChild("sid")) {
809 setSID(_departure->findSIDWithIdent(dep->getStringValue("sid")));
811 // departure->setStringValue("transition", dep->getStringValue("transition"));
816 SGPropertyNode* dst = routeData->getChild("destination");
818 setDestination((FGAirport*) fgFindAirportID(dst->getStringValue("airport")));
820 string rwy(dst->getStringValue("runway"));
821 if (_destination->hasRunwayWithIdent(rwy)) {
822 setDestination(_destination->getRunwayByIdent(rwy));
825 if (dst->hasChild("star")) {
826 setSTAR(_destination->findSTARWithIdent(dst->getStringValue("star")));
829 if (dst->hasChild("approach")) {
830 setApproach(_destination->findApproachWithIdent(dst->getStringValue("approach")));
834 // destination->setStringValue("transition", dst->getStringValue("transition"));
838 SGPropertyNode* alt = routeData->getChild("alternate");
840 //alternate->setStringValue(alt->getStringValue("airport"));
844 SGPropertyNode* crs = routeData->getChild("cruise");
846 // cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
847 // cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
848 // cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
849 } // of cruise data loading
853 void FlightPlan::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
855 loadXMLRouteHeader(routeData);
859 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
860 if (routeNode.valid()) {
861 for (int i=0; i<routeNode->nChildren(); ++i) {
862 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
863 Leg* l = new Leg(this, Waypt::createFromProperties(NULL, wpNode));
865 } // of route iteration
867 _waypointsChanged = true;
870 void FlightPlan::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
872 loadXMLRouteHeader(routeData);
876 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
877 for (int i=0; i<routeNode->nChildren(); ++i) {
878 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
879 Leg* l = new Leg(this, parseVersion1XMLWaypt(wpNode));
881 } // of route iteration
882 _waypointsChanged = true;
885 WayptRef FlightPlan::parseVersion1XMLWaypt(SGPropertyNode* aWP)
888 if (!_legs.empty()) {
889 lastPos = _legs.back()->waypoint()->position();
890 } else if (_departure) {
891 lastPos = _departure->geod();
895 string ident(aWP->getStringValue("ident"));
896 if (aWP->hasChild("longitude-deg")) {
897 // explicit longitude/latitude
898 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
899 aWP->getDoubleValue("latitude-deg")), ident, NULL);
902 string nid = aWP->getStringValue("navid", ident.c_str());
903 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
909 SG_LOG(SG_GENERAL, SG_WARN, "unknown navaid in flightplan:" << nid);
910 pos = SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
911 aWP->getDoubleValue("latitude-deg"));
914 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
915 double radialDeg = aWP->getDoubleValue("offset-radial");
916 // convert magnetic radial to a true radial!
917 radialDeg += magvarDegAt(pos);
918 double offsetNm = aWP->getDoubleValue("offset-nm");
920 SGGeodesy::direct(pos, radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
923 w = new BasicWaypt(pos, ident, NULL);
926 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
927 if (altFt > -9990.0) {
928 w->setAltitude(altFt, RESTRICT_AT);
934 /** Load a flightplan in FlightGear plain-text format */
935 bool FlightPlan::loadPlainTextFormat(const SGPath& path)
938 sg_gzifstream in(path.str().c_str());
940 throw sg_io_exception("Cannot open file for reading.");
946 getline(in, line, '\n');
947 // trim CR from end of line, if found
948 if (line[line.size() - 1] == '\r') {
949 line.erase(line.size() - 1, 1);
952 line = simgear::strutils::strip(line);
953 if (line.empty() || (line[0] == '#')) {
954 continue; // ignore empty/comment lines
957 WayptRef w = waypointFromString(line);
959 throw sg_io_exception("Failed to create waypoint from line '" + line + "'.");
962 _legs.push_back(new Leg(this, w));
963 } // of line iteration
964 } catch (sg_exception& e) {
965 SG_LOG(SG_NAVAID, SG_ALERT, "Failed to load route from: '" << path.str() << "'. " << e.getMessage());
973 double FlightPlan::magvarDegAt(const SGGeod& pos) const
975 double jd = globals->get_time_params()->getJD();
976 return sgGetMagVar(pos, jd) * SG_RADIANS_TO_DEGREES;
979 WayptRef FlightPlan::waypointFromString(const string& tgt )
981 string target(boost::to_upper_copy(tgt));
986 RouteRestriction altSetting = RESTRICT_NONE;
988 size_t pos = target.find( '@' );
989 if ( pos != string::npos ) {
990 altFt = atof( target.c_str() + pos + 1 );
991 target = target.substr( 0, pos );
992 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
993 altFt *= SG_METER_TO_FEET;
994 altSetting = RESTRICT_AT;
998 pos = target.find( ',' );
999 if ( pos != string::npos ) {
1000 double lon = atof( target.substr(0, pos).c_str());
1001 double lat = atof( target.c_str() + pos + 1);
1003 char ew = (lon < 0.0) ? 'W' : 'E';
1004 char ns = (lat < 0.0) ? 'S' : 'N';
1005 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
1007 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
1008 if (altSetting != RESTRICT_NONE) {
1009 wpt->setAltitude(altFt, altSetting);
1014 SGGeod basePosition;
1015 if (_legs.empty()) {
1016 // route is empty, use current position
1017 basePosition = globals->get_aircraft_position();
1019 basePosition = _legs.back()->waypoint()->position();
1022 string_list pieces(simgear::strutils::split(target, "/"));
1023 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
1025 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
1029 double magvar = magvarDegAt(basePosition);
1031 if (pieces.size() == 1) {
1032 wpt = new NavaidWaypoint(p, NULL);
1033 } else if (pieces.size() == 3) {
1034 // navaid/radial/distance-nm notation
1035 double radial = atof(pieces[1].c_str()),
1036 distanceNm = atof(pieces[2].c_str());
1038 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
1039 } else if (pieces.size() == 2) {
1040 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
1042 SG_LOG(SG_NAVAID, SG_INFO, "Waypoint is not an airport:" << pieces.front());
1046 if (!apt->hasRunwayWithIdent(pieces[1])) {
1047 SG_LOG(SG_NAVAID, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
1051 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
1052 wpt = new NavaidWaypoint(runway, NULL);
1053 } else if (pieces.size() == 4) {
1054 // navid/radial/navid/radial notation
1055 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
1057 SG_LOG( SG_NAVAID, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
1061 double r1 = atof(pieces[1].c_str()),
1062 r2 = atof(pieces[3].c_str());
1066 SGGeod intersection;
1067 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
1069 SG_LOG(SG_NAVAID, SG_INFO, "no valid intersection for:" << target);
1073 std::string name = p->ident() + "-" + p2->ident();
1074 wpt = new BasicWaypt(intersection, name, NULL);
1078 SG_LOG(SG_NAVAID, SG_INFO, "Unable to parse waypoint:" << target);
1082 if (altSetting != RESTRICT_NONE) {
1083 wpt->setAltitude(altFt, altSetting);
1088 FlightPlan::Leg::Leg(FlightPlan* owner, WayptRef wpt) :
1090 _speedRestrict(RESTRICT_NONE),
1091 _altRestrict(RESTRICT_NONE),
1095 throw sg_exception("can't create FlightPlan::Leg without underlying waypoint");
1097 _speed = _altitudeFt = 0;
1100 FlightPlan::Leg* FlightPlan::Leg::cloneFor(FlightPlan* owner) const
1102 Leg* c = new Leg(owner, _waypt);
1105 c->_speedRestrict = _speedRestrict;
1106 c->_altitudeFt = _altitudeFt;
1107 c->_altRestrict = _altRestrict;
1112 FlightPlan::Leg* FlightPlan::Leg::nextLeg() const
1114 return _parent->legAtIndex(index() + 1);
1117 unsigned int FlightPlan::Leg::index() const
1119 return _parent->findLegIndex(this);
1122 int FlightPlan::Leg::altitudeFt() const
1124 if (_altRestrict != RESTRICT_NONE) {
1128 return _waypt->altitudeFt();
1131 int FlightPlan::Leg::speed() const
1133 if (_speedRestrict != RESTRICT_NONE) {
1137 return _waypt->speed();
1140 int FlightPlan::Leg::speedKts() const
1145 double FlightPlan::Leg::speedMach() const
1147 if (!isMachRestrict(_speedRestrict)) {
1151 return -(_speed / 100.0);
1154 RouteRestriction FlightPlan::Leg::altitudeRestriction() const
1156 if (_altRestrict != RESTRICT_NONE) {
1157 return _altRestrict;
1160 return _waypt->altitudeRestriction();
1163 RouteRestriction FlightPlan::Leg::speedRestriction() const
1165 if (_speedRestrict != RESTRICT_NONE) {
1166 return _speedRestrict;
1169 return _waypt->speedRestriction();
1172 void FlightPlan::Leg::setSpeed(RouteRestriction ty, double speed)
1174 _speedRestrict = ty;
1175 if (isMachRestrict(ty)) {
1176 _speed = (speed * -100);
1182 void FlightPlan::Leg::setAltitude(RouteRestriction ty, int altFt)
1185 _altitudeFt = altFt;
1188 double FlightPlan::Leg::courseDeg() const
1193 double FlightPlan::Leg::distanceNm() const
1195 return _pathDistance;
1198 double FlightPlan::Leg::distanceAlongRoute() const
1200 return _distanceAlongPath;
1203 void FlightPlan::rebuildLegData()
1205 _totalDistance = 0.0;
1206 double totalDistanceIncludingMissed = 0.0;
1207 RoutePath path(this);
1209 for (unsigned int l=0; l<_legs.size(); ++l) {
1210 _legs[l]->_courseDeg = path.trackForIndex(l);
1211 _legs[l]->_pathDistance = path.distanceForIndex(l) * SG_METER_TO_NM;
1213 totalDistanceIncludingMissed += _legs[l]->_pathDistance;
1214 // distance along path includes our own leg distance
1215 _legs[l]->_distanceAlongPath = totalDistanceIncludingMissed;
1217 // omit missed-approach waypoints from total distance calculation
1218 if (!_legs[l]->waypoint()->flag(WPT_MISS)) {
1219 _totalDistance += _legs[l]->_pathDistance;
1221 } // of legs iteration
1225 SGGeod FlightPlan::pointAlongRoute(int aIndex, double aOffsetNm) const
1228 return rp.positionForDistanceFrom(aIndex, aOffsetNm * 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 void FlightPlan::Delegate::runActivated()
1381 if (_inner) _inner->runActivated();
1385 void FlightPlan::setFollowLegTrackToFixes(bool tf)
1387 _followLegTrackToFix = tf;
1390 bool FlightPlan::followLegTrackToFixes() const
1392 return _followLegTrackToFix;
1395 std::string FlightPlan::icaoAircraftCategory() const
1398 r.push_back(_aircraftCategory);
1402 void FlightPlan::setIcaoAircraftCategory(const std::string& cat)
1405 throw sg_range_exception("Invalid ICAO aircraft category:", cat);
1408 if ((cat[0] < ICAO_AIRCRAFT_CATEGORY_A) || (cat[0] > ICAO_AIRCRAFT_CATEGORY_E)) {
1409 throw sg_range_exception("Invalid ICAO aircraft category:", cat);
1412 _aircraftCategory = cat[0];
1416 } // of namespace flightgear