1 // route_mgr.cxx - manage a route (i.e. a collection of waypoints)
3 // Written by Curtis Olson, started January 2004.
7 // Copyright (C) 2004 Curtis L. Olson - http://www.flightgear.org/~curt
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
34 #include <simgear/compiler.h>
36 #include "route_mgr.hxx"
38 #include <boost/algorithm/string/case_conv.hpp>
39 #include <boost/tuple/tuple.hpp>
41 #include <simgear/misc/strutils.hxx>
42 #include <simgear/structure/exception.hxx>
43 #include <simgear/misc/sgstream.hxx>
45 #include <simgear/props/props_io.hxx>
46 #include <simgear/misc/sg_path.hxx>
47 #include <simgear/route/route.hxx>
48 #include <simgear/sg_inlines.h>
50 #include "Main/fg_props.hxx"
51 #include "Navaids/positioned.hxx"
52 #include <Navaids/waypoint.hxx>
53 #include <Navaids/airways.hxx>
54 #include <Navaids/procedure.hxx>
55 #include "Airports/simple.hxx"
56 #include "Airports/runways.hxx"
58 #define RM "/autopilot/route-manager/"
60 #include <GUI/new_gui.hxx>
61 #include <GUI/dialog.hxx>
63 using namespace flightgear;
65 class PropertyWatcher : public SGPropertyChangeListener
68 void watch(SGPropertyNode* p)
70 p->addChangeListener(this, false);
73 virtual void valueChanged(SGPropertyNode*)
78 virtual void fire() = 0;
82 * Template adapter, created by convenience helper below
85 class MethodPropertyWatcher : public PropertyWatcher
88 typedef void (T::*fire_method)();
90 MethodPropertyWatcher(T* obj, fire_method m) :
97 { // dispatch to the object method we're helping
98 (_object->*_method)();
107 PropertyWatcher* createWatcher(T* obj, void (T::*m)())
109 return new MethodPropertyWatcher<T>(obj, m);
112 FGRouteMgr::FGRouteMgr() :
114 input(fgGetNode( RM "input", true )),
115 mirror(fgGetNode( RM "route", true ))
117 listener = new InputListener(this);
118 input->setStringValue("");
119 input->addChangeListener(listener);
123 FGRouteMgr::~FGRouteMgr()
125 input->removeChangeListener(listener);
130 void FGRouteMgr::init() {
131 SGPropertyNode_ptr rm(fgGetNode(RM));
133 lon = fgGetNode( "/position/longitude-deg", true );
134 lat = fgGetNode( "/position/latitude-deg", true );
135 alt = fgGetNode( "/position/altitude-ft", true );
136 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
138 departure = fgGetNode(RM "departure", true);
139 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
140 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
141 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
142 &FGRouteMgr::getDepartureName, NULL));
143 departure->setStringValue("runway", "");
145 _departureWatcher = createWatcher(this, &FGRouteMgr::departureChanged);
146 _departureWatcher->watch(departure->getChild("runway"));
148 departure->getChild("etd", 0, true);
149 _departureWatcher->watch(departure->getChild("sid", 0, true));
150 departure->getChild("takeoff-time", 0, true);
152 destination = fgGetNode(RM "destination", true);
153 destination->getChild("airport", 0, true);
155 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
156 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
157 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
158 &FGRouteMgr::getDestinationName, NULL));
160 _arrivalWatcher = createWatcher(this, &FGRouteMgr::arrivalChanged);
161 _arrivalWatcher->watch(destination->getChild("runway", 0, true));
163 destination->getChild("eta", 0, true);
164 _arrivalWatcher->watch(destination->getChild("star", 0, true));
165 _arrivalWatcher->watch(destination->getChild("transition", 0, true));
166 destination->getChild("touchdown-time", 0, true);
168 alternate = fgGetNode(RM "alternate", true);
169 alternate->getChild("airport", 0, true);
170 alternate->getChild("runway", 0, true);
172 cruise = fgGetNode(RM "cruise", true);
173 cruise->getChild("altitude-ft", 0, true);
174 cruise->setDoubleValue("altitude-ft", 10000.0);
175 cruise->getChild("flight-level", 0, true);
176 cruise->getChild("speed-kts", 0, true);
177 cruise->setDoubleValue("speed-kts", 160.0);
179 _routingType = cruise->getChild("routing", 0, true);
180 _routingType->setIntValue(ROUTE_HIGH_AIRWAYS);
182 totalDistance = fgGetNode(RM "total-distance", true);
183 totalDistance->setDoubleValue(0.0);
185 ete = fgGetNode(RM "ete", true);
186 ete->setDoubleValue(0.0);
188 elapsedFlightTime = fgGetNode(RM "flight-time", true);
189 elapsedFlightTime->setDoubleValue(0.0);
191 active = fgGetNode(RM "active", true);
192 active->setBoolValue(false);
194 airborne = fgGetNode(RM "airborne", true);
195 airborne->setBoolValue(false);
197 _edited = fgGetNode(RM "signals/edited", true);
198 _finished = fgGetNode(RM "signals/finished", true);
200 _currentWpt = fgGetNode(RM "current-wp", true);
201 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
202 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
204 // temporary distance / eta calculations, for backward-compatability
205 wp0 = fgGetNode(RM "wp", 0, true);
206 wp0->getChild("id", 0, true);
207 wp0->getChild("dist", 0, true);
208 wp0->getChild("eta", 0, true);
209 wp0->getChild("bearing-deg", 0, true);
211 wp1 = fgGetNode(RM "wp", 1, true);
212 wp1->getChild("id", 0, true);
213 wp1->getChild("dist", 0, true);
214 wp1->getChild("eta", 0, true);
216 wpn = fgGetNode(RM "wp-last", 0, true);
217 wpn->getChild("dist", 0, true);
218 wpn->getChild("eta", 0, true);
221 _pathNode = fgGetNode(RM "file-path", 0, true);
225 void FGRouteMgr::postinit()
227 string_list *waypoints = globals->get_initial_waypoints();
229 string_list::iterator it;
230 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
231 WayptRef w = waypointFromString(*it);
237 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << _route.size());
240 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
241 // check airbone flag agrees with presets
244 void FGRouteMgr::bind() { }
245 void FGRouteMgr::unbind() { }
247 bool FGRouteMgr::isRouteActive() const
249 return active->getBoolValue();
252 void FGRouteMgr::update( double dt )
255 return; // paused, nothing to do here
258 double groundSpeed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
259 if (airborne->getBoolValue()) {
260 time_t now = time(NULL);
261 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
262 } else { // not airborne
263 if (weightOnWheels->getBoolValue() || (groundSpeed < 40)) {
267 airborne->setBoolValue(true);
268 _takeoffTime = time(NULL); // start the clock
269 departure->setIntValue("takeoff-time", _takeoffTime);
272 if (!active->getBoolValue()) {
276 // basic course/distance information
277 SGGeod currentPos = SGGeod::fromDegFt(lon->getDoubleValue(),
278 lat->getDoubleValue(),alt->getDoubleValue());
280 Waypt* curWpt = currentWaypt();
287 boost::tie(courseDeg, distanceM) = curWpt->courseAndDistanceFrom(currentPos);
289 // update wp0 / wp1 / wp-last for legacy users
290 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
291 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
292 wp0->setDoubleValue("bearing-deg", courseDeg);
293 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
295 double totalDistanceRemaining = distanceM; // distance to current waypoint
297 Waypt* nextWpt = nextWaypt();
299 boost::tie(courseDeg, distanceM) = nextWpt->courseAndDistanceFrom(currentPos);
301 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
302 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
303 wp1->setDoubleValue("bearing-deg", courseDeg);
304 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
307 Waypt* prev = curWpt;
308 for (unsigned int i=_currentIndex + 1; i<_route.size(); ++i) {
309 Waypt* w = _route[i];
310 if (w->flag(WPT_DYNAMIC)) continue;
311 totalDistanceRemaining += SGGeodesy::distanceM(prev->position(), w->position());
317 wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
318 ete->setDoubleValue(totalDistanceRemaining * SG_METER_TO_NM / groundSpeed * 3600.0);
319 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
322 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
324 double speed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
326 aProp->setStringValue("--:--");
331 double eta = aDistance * SG_METER_TO_NM / speed;
332 if ( eta >= 100.0 ) {
333 eta = 99.999; // clamp
336 if ( eta < (1.0/6.0) ) {
337 eta *= 60.0; // within 10 minutes, bump up to min/secs
340 int major = (int)eta,
341 minor = (int)((eta - (int)eta) * 60.0);
342 snprintf( eta_str, 64, "%d:%02d", major, minor );
343 aProp->setStringValue( eta_str );
346 flightgear::WayptRef FGRouteMgr::removeWayptAtIndex(int aIndex)
349 if (aIndex < 0) { // negative indices count the the end
350 index = _route.size() + index;
353 if ((index < 0) || (index >= numWaypts())) {
354 SG_LOG(SG_AUTOPILOT, SG_WARN, "removeWayptAtIndex with invalid index:" << aIndex);
357 WayptVec::iterator it = _route.begin();
360 WayptRef w = *it; // hold a ref now, in case _route is the only other owner
365 if (_currentIndex == index) {
366 currentWaypointChanged(); // current waypoint was removed
369 if (_currentIndex > index) {
370 --_currentIndex; // shift current index down if necessary
373 _edited->fireValueChanged();
379 void FGRouteMgr::clearRoute()
385 active->setBoolValue(false);
386 _edited->fireValueChanged();
390 * route between index-1 and index, using airways.
392 bool FGRouteMgr::routeToIndex(int index, RouteType aRouteType)
398 index = _route.size(); // can still be zero, of course
403 SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no departure set");
407 wp1 = new NavaidWaypoint(_departure.get(), NULL);
409 wp1 = wayptAtIndex(index - 1);
412 if (index >= numWaypts()) {
414 SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no destination set");
418 wp2 = new NavaidWaypoint(_destination.get(), NULL);
420 wp2 = wayptAtIndex(index);
423 double distNm = SGGeodesy::distanceNm(wp1->position(), wp2->position());
424 if (distNm < 100.0) {
425 SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: existing waypoints are nearby, direct route");
430 switch (aRouteType) {
431 case ROUTE_HIGH_AIRWAYS:
432 Airway::highLevel()->route(wp1, wp2, r);
435 case ROUTE_LOW_AIRWAYS:
436 Airway::lowLevel()->route(wp1, wp2, r);
440 throw sg_exception("VOR routing not supported yet");
444 SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: no route found");
448 WayptVec::iterator it = _route.begin();
450 _route.insert(it, r.begin(), r.end());
453 _edited->fireValueChanged();
457 void FGRouteMgr::autoRoute()
459 if (!_departure || !_destination) {
463 string runwayId(departure->getStringValue("runway"));
464 FGRunway* runway = NULL;
465 if (_departure->hasRunwayWithIdent(runwayId)) {
466 runway = _departure->getRunwayByIdent(runwayId);
469 FGRunway* dstRunway = NULL;
470 runwayId = destination->getStringValue("runway");
471 if (_destination->hasRunwayWithIdent(runwayId)) {
472 dstRunway = _destination->getRunwayByIdent(runwayId);
475 _route.clear(); // clear out the existing, first
477 flightgear::SID* sid;
480 boost::tie(sid, sidTrans) = _departure->selectSID(_destination->geod(), runway);
482 SG_LOG(SG_AUTOPILOT, SG_INFO, "selected SID " << sid->ident());
484 SG_LOG(SG_AUTOPILOT, SG_INFO, "\tvia " << sidTrans->ident() << " transition");
487 sid->route(runway, sidTrans, _route);
488 departure->setStringValue("sid", sid->ident());
490 // use airport location for airway search
491 sidTrans = new NavaidWaypoint(_departure.get(), NULL);
492 departure->setStringValue("sid", "");
496 destination->setStringValue("transition", "");
497 destination->setStringValue("star", "");
501 boost::tie(star, starTrans) = _destination->selectSTAR(_departure->geod(), dstRunway);
503 SG_LOG(SG_AUTOPILOT, SG_INFO, "selected STAR " << star->ident());
505 SG_LOG(SG_AUTOPILOT, SG_INFO, "\tvia " << starTrans->ident() << " transition");
506 destination->setStringValue("transition", starTrans->ident());
508 destination->setStringValue("star", star->ident());
510 // use airport location for search
511 starTrans = new NavaidWaypoint(_destination.get(), NULL);
514 // route between them
515 WayptVec airwayRoute;
516 if (Airway::highLevel()->route(sidTrans, starTrans, airwayRoute)) {
517 _route.insert(_route.end(), airwayRoute.begin(), airwayRoute.end());
520 // add the STAR if we have one
522 _destination->buildApproach(starTrans, star, dstRunway, _route);
526 _edited->fireValueChanged();
529 void FGRouteMgr::departureChanged()
531 // remove existing departure waypoints
532 WayptVec::iterator it = _route.begin();
533 for (; it != _route.end(); ++it) {
534 if (!(*it)->flag(WPT_DEPARTURE)) {
539 // erase() invalidates iterators, so grab now
541 if (it == _route.end()) {
543 enroute = new NavaidWaypoint(_destination.get(), NULL);
549 _route.erase(_route.begin(), it);
556 buildDeparture(enroute, wps);
557 for (it = wps.begin(); it != wps.end(); ++it) {
558 (*it)->setFlag(WPT_DEPARTURE);
559 (*it)->setFlag(WPT_GENERATED);
561 _route.insert(_route.begin(), wps.begin(), wps.end());
567 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
569 string runwayId(departure->getStringValue("runway"));
570 if (!_departure->hasRunwayWithIdent(runwayId)) {
571 // valid airport, but no runway selected, so just the airport noide itself
572 wps.push_back(new NavaidWaypoint(_departure.get(), NULL));
576 FGRunway* r = _departure->getRunwayByIdent(runwayId);
577 string sidId = departure->getStringValue("sid");
578 flightgear::SID* sid = _departure->findSIDWithIdent(sidId);
580 // valid runway, but no SID selected/found, so just the runway node for now
581 if (!sidId.empty() && (sidId != "(none)")) {
582 SG_LOG(SG_AUTOPILOT, SG_INFO, "SID not found:" << sidId);
585 wps.push_back(new RunwayWaypt(r, NULL));
589 // we have a valid SID, awesome
590 string trans(departure->getStringValue("transition"));
591 WayptRef t = sid->findTransitionByName(trans);
593 t = sid->findBestTransition(enroute->position());
596 sid->route(r, t, wps);
597 if (!wps.empty() && wps.front()->flag(WPT_DYNAMIC)) {
598 // ensure first waypoint is static, to simplify other computations
599 wps.insert(wps.begin(), new RunwayWaypt(r, NULL));
603 void FGRouteMgr::arrivalChanged()
605 // remove existing arrival waypoints
606 WayptVec::reverse_iterator rit = _route.rbegin();
607 for (; rit != _route.rend(); ++rit) {
608 if (!(*rit)->flag(WPT_ARRIVAL)) {
613 // erase() invalidates iterators, so grab now
615 WayptVec::iterator it;
617 if (rit != _route.rend()) {
619 it = rit.base(); // convert to fwd iterator
624 _route.erase(it, _route.end());
627 buildArrival(enroute, wps);
628 for (it = wps.begin(); it != wps.end(); ++it) {
629 (*it)->setFlag(WPT_ARRIVAL);
630 (*it)->setFlag(WPT_GENERATED);
632 _route.insert(_route.end(), wps.begin(), wps.end());
638 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
644 string runwayId(destination->getStringValue("runway"));
645 if (!_destination->hasRunwayWithIdent(runwayId)) {
646 // valid airport, but no runway selected, so just the airport node itself
647 wps.push_back(new NavaidWaypoint(_destination.get(), NULL));
651 FGRunway* r = _destination->getRunwayByIdent(runwayId);
652 string starId = destination->getStringValue("star");
653 STAR* star = _destination->findSTARWithIdent(starId);
655 // valid runway, but no STAR selected/found, so just the runway node for now
656 wps.push_back(new RunwayWaypt(r, NULL));
660 // we have a valid STAR
661 string trans(destination->getStringValue("transition"));
662 WayptRef t = star->findTransitionByName(trans);
664 t = star->findBestTransition(enroute->position());
667 _destination->buildApproach(t, star, r, wps);
670 void FGRouteMgr::waypointsChanged()
675 void FGRouteMgr::insertWayptAtIndex(Waypt* aWpt, int aIndex)
682 if ((aIndex == -1) || (aIndex > (int) _route.size())) {
683 index = _route.size();
686 WayptVec::iterator it = _route.begin();
689 if (_currentIndex >= index) {
693 _route.insert(it, aWpt);
696 _edited->fireValueChanged();
699 WayptRef FGRouteMgr::waypointFromString(const string& tgt )
701 string target(boost::to_upper_copy(tgt));
705 double altFt = cruise->getDoubleValue("altitude-ft");
706 RouteRestriction altSetting = RESTRICT_NONE;
708 size_t pos = target.find( '@' );
709 if ( pos != string::npos ) {
710 altFt = atof( target.c_str() + pos + 1 );
711 target = target.substr( 0, pos );
712 if ( !strcmp(fgGetString("/sim/startup/units"), "meter") )
713 altFt *= SG_METER_TO_FEET;
714 altSetting = RESTRICT_AT;
718 pos = target.find( ',' );
719 if ( pos != string::npos ) {
720 double lon = atof( target.substr(0, pos).c_str());
721 double lat = atof( target.c_str() + pos + 1);
723 char ew = (lon < 0.0) ? 'W' : 'E';
724 char ns = (lat < 0.0) ? 'S' : 'N';
725 snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
727 wpt = new BasicWaypt(SGGeod::fromDeg(lon, lat), buf, NULL);
728 if (altSetting != RESTRICT_NONE) {
729 wpt->setAltitude(altFt, altSetting);
735 if (_route.empty()) {
736 // route is empty, use current position
737 basePosition = SGGeod::fromDeg(lon->getDoubleValue(), lat->getDoubleValue());
739 basePosition = _route.back()->position();
742 string_list pieces(simgear::strutils::split(target, "/"));
743 FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
745 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
749 if (pieces.size() == 1) {
750 wpt = new NavaidWaypoint(p, NULL);
751 } else if (pieces.size() == 3) {
752 // navaid/radial/distance-nm notation
753 double radial = atof(pieces[1].c_str()),
754 distanceNm = atof(pieces[2].c_str());
755 radial += magvar->getDoubleValue(); // convert to true bearing
756 wpt = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
757 } else if (pieces.size() == 2) {
758 FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
760 SG_LOG(SG_AUTOPILOT, SG_INFO, "Waypoint is not an airport:" << pieces.front());
764 if (!apt->hasRunwayWithIdent(pieces[1])) {
765 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
769 FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
770 wpt = new NavaidWaypoint(runway, NULL);
771 } else if (pieces.size() == 4) {
772 // navid/radial/navid/radial notation
773 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(pieces[2], basePosition);
775 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces[2]);
779 double r1 = atof(pieces[1].c_str()),
780 r2 = atof(pieces[3].c_str());
781 r1 += magvar->getDoubleValue();
782 r2 += magvar->getDoubleValue();
785 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
787 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << target);
791 std::string name = p->ident() + "-" + p2->ident();
792 wpt = new BasicWaypt(intersection, name, NULL);
796 SG_LOG(SG_AUTOPILOT, SG_INFO, "Unable to parse waypoint:" << target);
800 if (altSetting != RESTRICT_NONE) {
801 wpt->setAltitude(altFt, altSetting);
806 // mirror internal route to the property system for inspection by other subsystems
807 void FGRouteMgr::update_mirror()
809 mirror->removeChildren("wp");
811 int num = numWaypts();
812 for (int i = 0; i < num; i++) {
813 Waypt* wp = _route[i];
814 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
816 const SGGeod& pos(wp->position());
817 prop->setStringValue("id", wp->ident().c_str());
818 //prop->setStringValue("name", wp.get_name().c_str());
819 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
820 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
822 // leg course+distance
824 Waypt* next = _route[i+1];
825 std::pair<double, double> crsDist =
826 next->courseAndDistanceFrom(pos);
827 prop->setDoubleValue("leg-bearing-true-deg", crsDist.first);
828 prop->setDoubleValue("leg-distance-nm", crsDist.second * SG_METER_TO_NM);
831 if (wp->altitudeRestriction() != RESTRICT_NONE) {
832 double ft = wp->altitudeFt();
833 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
834 prop->setDoubleValue("altitude-ft", ft);
836 prop->setDoubleValue("altitude-m", -9999.9);
837 prop->setDoubleValue("altitude-ft", -9999.9);
840 if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
841 prop->setDoubleValue("speed-mach", wp->speedMach());
842 } else if (wp->speedRestriction() != RESTRICT_NONE) {
843 prop->setDoubleValue("speed-kts", wp->speedKts());
846 if (wp->flag(WPT_ARRIVAL)) {
847 prop->setBoolValue("arrival", true);
850 if (wp->flag(WPT_DEPARTURE)) {
851 prop->setBoolValue("departure", true);
854 if (wp->flag(WPT_MISS)) {
855 prop->setBoolValue("missed-approach", true);
858 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
859 } // of waypoint iteration
861 // set number as listener attachment point
862 mirror->setIntValue("num", _route.size());
864 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
865 FGDialog* rmDlg = gui->getDialog("route-manager");
867 rmDlg->updateValues();
871 // command interface /autopilot/route-manager/input:
873 // @CLEAR ... clear route
874 // @POP ... remove first entry
875 // @DELETE3 ... delete 4th entry
876 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
877 // KSFO@900 ... append "KSFO@900"
879 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
881 const char *s = prop->getStringValue();
882 if (strlen(s) == 0) {
886 if (!strcmp(s, "@CLEAR"))
888 else if (!strcmp(s, "@ACTIVATE"))
890 else if (!strcmp(s, "@LOAD")) {
892 } else if (!strcmp(s, "@SAVE")) {
894 } else if (!strcmp(s, "@POP")) {
895 SG_LOG(SG_AUTOPILOT, SG_WARN, "route-manager @POP command is deprecated");
896 } else if (!strcmp(s, "@NEXT")) {
897 mgr->jumpToIndex(mgr->_currentIndex + 1);
898 } else if (!strcmp(s, "@PREVIOUS")) {
899 mgr->jumpToIndex(mgr->_currentIndex - 1);
900 } else if (!strncmp(s, "@JUMP", 5)) {
901 mgr->jumpToIndex(atoi(s + 5));
902 } else if (!strncmp(s, "@DELETE", 7))
903 mgr->removeWayptAtIndex(atoi(s + 7));
904 else if (!strncmp(s, "@INSERT", 7)) {
906 int pos = strtol(s + 7, &r, 10);
912 mgr->insertWayptAtIndex(mgr->waypointFromString(r), pos);
913 } else if (!strncmp(s, "@ROUTE", 6)) {
915 int endIndex = strtol(s + 6, &r, 10);
916 RouteType rt = (RouteType) mgr->_routingType->getIntValue();
917 mgr->routeToIndex(endIndex, rt);
918 } else if (!strcmp(s, "@AUTOROUTE")) {
920 } else if (!strcmp(s, "@POSINIT")) {
921 mgr->initAtPosition();
923 mgr->insertWayptAtIndex(mgr->waypointFromString(s), -1);
926 void FGRouteMgr::initAtPosition()
928 if (isRouteActive()) {
929 return; // don't mess with the active route
932 if (haveUserWaypoints()) {
933 // user has already defined, loaded or entered a route, again
934 // don't interfere with it
938 if (airborne->getBoolValue()) {
939 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
941 departure->setStringValue("runway", "");
946 SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(),
947 lat->getDoubleValue(), alt->getDoubleValue());
949 _departure = FGAirport::findClosest(pos, 20.0);
951 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
952 departure->setStringValue("runway", "");
957 std::string rwy = departure->getStringValue("runway");
959 // runway already set, fine
963 FGRunway* r = _departure->findBestRunwayForPos(pos);
968 departure->setStringValue("runway", r->ident().c_str());
969 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
970 << _departure->ident() << " on runway " << r->ident());
973 bool FGRouteMgr::haveUserWaypoints() const
975 for (int i = 0; i < numWaypts(); i++) {
976 if (!_route[i]->flag(WPT_GENERATED)) {
977 // have a non-generated waypoint, we're done
982 // all waypoints are generated
986 bool FGRouteMgr::activate()
988 if (isRouteActive()) {
989 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
994 currentWaypointChanged();
996 /* double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
997 totalDistance->setDoubleValue(routeDistanceNm);
998 double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
999 if (cruiseSpeedKts > 1.0) {
1000 // very very crude approximation, doesn't allow for climb / descent
1001 // performance or anything else at all
1002 ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
1005 active->setBoolValue(true);
1006 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
1011 void FGRouteMgr::sequence()
1013 if (!active->getBoolValue()) {
1014 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
1018 if (checkFinished()) {
1023 currentWaypointChanged();
1026 bool FGRouteMgr::checkFinished()
1028 if (_currentIndex < (int) _route.size()) {
1032 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
1033 _finished->fireValueChanged();
1034 active->setBoolValue(false);
1038 void FGRouteMgr::jumpToIndex(int index)
1040 if ((index < 0) || (index >= (int) _route.size())) {
1041 SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" <<
1042 index << ") to FGRouteMgr::jumpToIndex");
1046 if (_currentIndex == index) {
1050 // all the checks out the way, go ahead and update state
1051 _currentIndex = index;
1052 currentWaypointChanged();
1053 _currentWpt->fireValueChanged();
1056 void FGRouteMgr::currentWaypointChanged()
1058 Waypt* cur = currentWaypt();
1059 Waypt* next = nextWaypt();
1061 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
1062 wp1->getChild("id")->setStringValue(next ? next->ident() : "");
1064 _currentWpt->fireValueChanged();
1065 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _currentIndex);
1068 int FGRouteMgr::findWayptIndex(const SGGeod& aPos) const
1070 for (int i=0; i<numWaypts(); ++i) {
1071 if (_route[i]->matches(aPos)) {
1079 Waypt* FGRouteMgr::currentWaypt() const
1081 if ((_currentIndex < 0) || (_currentIndex >= numWaypts()))
1083 return wayptAtIndex(_currentIndex);
1086 Waypt* FGRouteMgr::previousWaypt() const
1088 if (_currentIndex == 0) {
1092 return wayptAtIndex(_currentIndex - 1);
1095 Waypt* FGRouteMgr::nextWaypt() const
1097 if ((_currentIndex < 0) || ((_currentIndex + 1) >= numWaypts())) {
1101 return wayptAtIndex(_currentIndex + 1);
1104 Waypt* FGRouteMgr::wayptAtIndex(int index) const
1106 if ((index < 0) || (index >= numWaypts())) {
1107 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1110 return _route[index];
1113 void FGRouteMgr::saveRoute()
1115 SGPath path(_pathNode->getStringValue());
1116 SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
1118 SGPropertyNode_ptr d(new SGPropertyNode);
1119 SGPath path(_pathNode->getStringValue());
1120 d->setIntValue("version", 2);
1123 d->setStringValue("departure/airport", _departure->ident());
1124 d->setStringValue("departure/sid", departure->getStringValue("sid"));
1125 d->setStringValue("departure/runway", departure->getStringValue("runway"));
1129 d->setStringValue("destination/airport", _destination->ident());
1130 d->setStringValue("destination/star", destination->getStringValue("star"));
1131 d->setStringValue("destination/transition", destination->getStringValue("transition"));
1132 d->setStringValue("destination/runway", destination->getStringValue("runway"));
1136 SGPropertyNode* routeNode = d->getChild("route", 0, true);
1137 for (unsigned int i=0; i<_route.size(); ++i) {
1138 Waypt* wpt = _route[i];
1139 wpt->saveAsNode(routeNode->getChild("wp", i, true));
1140 } // of waypoint iteration
1141 writeProperties(path.str(), d, true /* write-all */);
1142 } catch (sg_exception& e) {
1143 SG_LOG(SG_IO, SG_WARN, "failed to save flight-plan:" << e.getMessage());
1147 void FGRouteMgr::loadRoute()
1149 // deactivate route first
1150 active->setBoolValue(false);
1152 SGPropertyNode_ptr routeData(new SGPropertyNode);
1153 SGPath path(_pathNode->getStringValue());
1155 SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
1158 readProperties(path.str(), routeData);
1159 } catch (sg_exception& ) {
1160 // if XML parsing fails, the file might be simple textual list of waypoints
1161 loadPlainTextRoute(path);
1166 int version = routeData->getIntValue("version", 1);
1168 loadVersion1XMLRoute(routeData);
1169 } else if (version == 2) {
1170 loadVersion2XMLRoute(routeData);
1172 throw sg_io_exception("unsupported XML route version");
1174 } catch (sg_exception& e) {
1175 SG_LOG(SG_IO, SG_WARN, "failed to load flight-plan (from '" << e.getOrigin()
1176 << "'):" << e.getMessage());
1180 void FGRouteMgr::loadXMLRouteHeader(SGPropertyNode_ptr routeData)
1183 SGPropertyNode* dep = routeData->getChild("departure");
1185 string depIdent = dep->getStringValue("airport");
1186 _departure = (FGAirport*) fgFindAirportID(depIdent);
1187 departure->setStringValue("runway", dep->getStringValue("runway"));
1188 departure->setStringValue("sid", dep->getStringValue("sid"));
1189 departure->setStringValue("transition", dep->getStringValue("transition"));
1193 SGPropertyNode* dst = routeData->getChild("destination");
1195 _destination = (FGAirport*) fgFindAirportID(dst->getStringValue("airport"));
1196 destination->setStringValue("runway", dst->getStringValue("runway"));
1197 destination->setStringValue("star", dst->getStringValue("star"));
1198 destination->setStringValue("transition", dst->getStringValue("transition"));
1202 SGPropertyNode* alt = routeData->getChild("alternate");
1204 alternate->setStringValue(alt->getStringValue("airport"));
1205 } // of cruise data loading
1208 SGPropertyNode* crs = routeData->getChild("cruise");
1210 cruise->setDoubleValue("speed-kts", crs->getDoubleValue("speed-kts"));
1211 cruise->setDoubleValue("mach", crs->getDoubleValue("mach"));
1212 cruise->setDoubleValue("altitude-ft", crs->getDoubleValue("altitude-ft"));
1213 } // of cruise data loading
1217 void FGRouteMgr::loadVersion2XMLRoute(SGPropertyNode_ptr routeData)
1219 loadXMLRouteHeader(routeData);
1223 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
1224 for (int i=0; i<routeNode->nChildren(); ++i) {
1225 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
1226 WayptRef wpt = Waypt::createFromProperties(NULL, wpNode);
1227 wpts.push_back(wpt);
1228 } // of route iteration
1233 void FGRouteMgr::loadVersion1XMLRoute(SGPropertyNode_ptr routeData)
1235 loadXMLRouteHeader(routeData);
1239 SGPropertyNode_ptr routeNode = routeData->getChild("route", 0);
1240 for (int i=0; i<routeNode->nChildren(); ++i) {
1241 SGPropertyNode_ptr wpNode = routeNode->getChild("wp", i);
1242 WayptRef wpt = parseVersion1XMLWaypt(wpNode);
1243 wpts.push_back(wpt);
1244 } // of route iteration
1249 WayptRef FGRouteMgr::parseVersion1XMLWaypt(SGPropertyNode* aWP)
1252 if (!_route.empty()) {
1253 lastPos = _route.back()->position();
1254 } else if (_departure) {
1255 lastPos = _departure->geod();
1259 string ident(aWP->getStringValue("ident"));
1260 if (aWP->hasChild("longitude-deg")) {
1261 // explicit longitude/latitude
1262 w = new BasicWaypt(SGGeod::fromDeg(aWP->getDoubleValue("longitude-deg"),
1263 aWP->getDoubleValue("latitude-deg")), ident, NULL);
1266 string nid = aWP->getStringValue("navid", ident.c_str());
1267 FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
1269 throw sg_io_exception("bad route file, unknown navid:" + nid);
1272 SGGeod pos(p->geod());
1273 if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
1274 double radialDeg = aWP->getDoubleValue("offset-radial");
1275 // convert magnetic radial to a true radial!
1276 radialDeg += magvar->getDoubleValue();
1277 double offsetNm = aWP->getDoubleValue("offset-nm");
1279 SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
1282 w = new BasicWaypt(pos, ident, NULL);
1285 double altFt = aWP->getDoubleValue("altitude-ft", -9999.9);
1286 if (altFt > -9990.0) {
1287 w->setAltitude(altFt, RESTRICT_AT);
1293 void FGRouteMgr::loadPlainTextRoute(const SGPath& path)
1295 sg_gzifstream in(path.str().c_str());
1296 if (!in.is_open()) {
1304 getline(in, line, '\n');
1305 // trim CR from end of line, if found
1306 if (line[line.size() - 1] == '\r') {
1307 line.erase(line.size() - 1, 1);
1310 line = simgear::strutils::strip(line);
1311 if (line.empty() || (line[0] == '#')) {
1312 continue; // ignore empty/comment lines
1315 WayptRef w = waypointFromString(line);
1317 throw sg_io_exception("failed to create waypoint from line:" + line);
1321 } // of line iteration
1324 } catch (sg_exception& e) {
1325 SG_LOG(SG_IO, SG_WARN, "failed to load route from:" << path.str() << ":" << e.getMessage());
1329 const char* FGRouteMgr::getDepartureICAO() const
1335 return _departure->ident().c_str();
1338 const char* FGRouteMgr::getDepartureName() const
1344 return _departure->name().c_str();
1347 void FGRouteMgr::setDepartureICAO(const char* aIdent)
1349 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1352 _departure = FGAirport::findByIdent(aIdent);
1358 const char* FGRouteMgr::getDestinationICAO() const
1360 if (!_destination) {
1364 return _destination->ident().c_str();
1367 const char* FGRouteMgr::getDestinationName() const
1369 if (!_destination) {
1373 return _destination->name().c_str();
1376 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1378 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1379 _destination = NULL;
1381 _destination = FGAirport::findByIdent(aIdent);