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/structure/commands.hxx>
44 #include <simgear/misc/sgstream.hxx>
46 #include <simgear/props/props_io.hxx>
47 #include <simgear/misc/sg_path.hxx>
48 #include <simgear/route/route.hxx>
49 #include <simgear/sg_inlines.h>
51 #include "Main/fg_props.hxx"
52 #include "Navaids/positioned.hxx"
53 #include <Navaids/waypoint.hxx>
54 #include <Navaids/airways.hxx>
55 #include <Navaids/procedure.hxx>
56 #include "Airports/simple.hxx"
57 #include "Airports/runways.hxx"
59 #define RM "/autopilot/route-manager/"
61 #include <GUI/new_gui.hxx>
62 #include <GUI/dialog.hxx>
64 using namespace flightgear;
66 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
68 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
69 SGPath path(arg->getStringValue("path"));
70 return self->loadRoute(path);
73 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
75 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
76 SGPath path(arg->getStringValue("path"));
77 return self->saveRoute(path);
80 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
82 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
83 bool activate = arg->getBoolValue("activate", true);
93 static bool commandClearFlightPlan(const SGPropertyNode*)
95 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
100 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
102 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
103 int index = arg->getIntValue("index");
104 if ((index < 0) || (index >= self->numLegs())) {
108 self->jumpToIndex(index);
112 static bool commandInsertWaypt(const SGPropertyNode* arg)
114 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
115 int index = arg->getIntValue("index");
116 std::string ident(arg->getStringValue("id"));
117 int alt = arg->getIntValue("altitude-ft", -999);
118 int ias = arg->getIntValue("speed-knots", -999);
121 // lat/lon may be supplied to narrow down navaid search, or to specify
124 if (arg->hasChild("longitude-deg")) {
125 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
126 arg->getDoubleValue("latitude-deg"));
129 if (arg->hasChild("navaid")) {
130 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
132 if (arg->hasChild("navaid", 1)) {
133 // intersection of two radials
134 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
136 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
140 double r1 = arg->getDoubleValue("radial"),
141 r2 = arg->getDoubleValue("radial[1]");
144 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
146 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
147 << "," << p2->ident());
151 std::string name = p->ident() + "-" + p2->ident();
152 wp = new BasicWaypt(intersection, name, NULL);
153 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
154 // offset radial from navaid
155 double radial = arg->getDoubleValue("radial");
156 double distanceNm = arg->getDoubleValue("offset-nm");
157 //radial += magvar->getDoubleValue(); // convert to true bearing
158 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
160 wp = new NavaidWaypoint(p, NULL);
162 } else if (arg->hasChild("airport")) {
163 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
165 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
169 if (arg->hasChild("runway")) {
170 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
171 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
175 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
176 wp = new RunwayWaypt(runway, NULL);
178 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
180 } else if (arg->hasChild("text")) {
181 wp = self->waypointFromString(arg->getStringValue("text"));
182 } else if (!(pos == SGGeod())) {
183 // just a raw lat/lon
184 wp = new BasicWaypt(pos, ident, NULL);
186 return false; // failed to build waypoint
189 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
191 leg->setAltitude(RESTRICT_AT, alt);
195 leg->setSpeed(RESTRICT_AT, ias);
201 static bool commandDeleteWaypt(const SGPropertyNode* arg)
203 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
204 int index = arg->getIntValue("index");
205 self->removeLegAtIndex(index);
209 /////////////////////////////////////////////////////////////////////////////
211 FGRouteMgr::FGRouteMgr() :
213 input(fgGetNode( RM "input", true )),
214 mirror(fgGetNode( RM "route", true ))
216 listener = new InputListener(this);
217 input->setStringValue("");
218 input->addChangeListener(listener);
220 SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
221 SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
222 SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
223 SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
224 SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
225 SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
226 SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
230 FGRouteMgr::~FGRouteMgr()
232 input->removeChangeListener(listener);
237 void FGRouteMgr::init() {
238 SGPropertyNode_ptr rm(fgGetNode(RM));
240 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
242 departure = fgGetNode(RM "departure", true);
243 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
244 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
245 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
246 &FGRouteMgr::getDepartureRunway,
247 &FGRouteMgr::setDepartureRunway));
248 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
250 &FGRouteMgr::setSID));
252 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
253 &FGRouteMgr::getDepartureName, NULL));
254 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
255 &FGRouteMgr::getDestinationFieldElevation, NULL));
256 departure->getChild("etd", 0, true);
257 departure->getChild("takeoff-time", 0, true);
259 destination = fgGetNode(RM "destination", true);
260 destination->getChild("airport", 0, true);
262 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
263 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
264 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
265 &FGRouteMgr::getDestinationRunway,
266 &FGRouteMgr::setDestinationRunway));
267 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
268 &FGRouteMgr::getSTAR,
269 &FGRouteMgr::setSTAR));
270 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
271 &FGRouteMgr::getApproach,
272 &FGRouteMgr::setApproach));
274 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
275 &FGRouteMgr::getDestinationName, NULL));
276 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
277 &FGRouteMgr::getDestinationFieldElevation, NULL));
279 destination->getChild("eta", 0, true);
280 destination->getChild("touchdown-time", 0, true);
282 alternate = fgGetNode(RM "alternate", true);
283 alternate->getChild("airport", 0, true);
284 alternate->getChild("runway", 0, true);
286 cruise = fgGetNode(RM "cruise", true);
287 cruise->getChild("altitude-ft", 0, true);
288 cruise->setDoubleValue("altitude-ft", 10000.0);
289 cruise->getChild("flight-level", 0, true);
290 cruise->getChild("speed-kts", 0, true);
291 cruise->setDoubleValue("speed-kts", 160.0);
293 _routingType = cruise->getChild("routing", 0, true);
294 _routingType->setIntValue(ROUTE_HIGH_AIRWAYS);
296 totalDistance = fgGetNode(RM "total-distance", true);
297 totalDistance->setDoubleValue(0.0);
298 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
299 distanceToGo->setDoubleValue(0.0);
301 ete = fgGetNode(RM "ete", true);
302 ete->setDoubleValue(0.0);
304 elapsedFlightTime = fgGetNode(RM "flight-time", true);
305 elapsedFlightTime->setDoubleValue(0.0);
307 active = fgGetNode(RM "active", true);
308 active->setBoolValue(false);
310 airborne = fgGetNode(RM "airborne", true);
311 airborne->setBoolValue(false);
313 _edited = fgGetNode(RM "signals/edited", true);
314 _finished = fgGetNode(RM "signals/finished", true);
315 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
317 _currentWpt = fgGetNode(RM "current-wp", true);
318 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
319 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
321 // temporary distance / eta calculations, for backward-compatability
322 wp0 = fgGetNode(RM "wp", 0, true);
323 wp0->getChild("id", 0, true);
324 wp0->getChild("dist", 0, true);
325 wp0->getChild("eta", 0, true);
326 wp0->getChild("bearing-deg", 0, true);
328 wp1 = fgGetNode(RM "wp", 1, true);
329 wp1->getChild("id", 0, true);
330 wp1->getChild("dist", 0, true);
331 wp1->getChild("eta", 0, true);
333 wpn = fgGetNode(RM "wp-last", 0, true);
334 wpn->getChild("dist", 0, true);
335 wpn->getChild("eta", 0, true);
337 _pathNode = fgGetNode(RM "file-path", 0, true);
338 setFlightPlan(new FlightPlan());
342 void FGRouteMgr::postinit()
344 SGPath path(_pathNode->getStringValue());
345 if (!path.isNull()) {
346 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
350 // this code only matters for the --wp option now - perhaps the option
351 // should be deprecated in favour of an explicit flight-plan file?
352 // then the global initial waypoint list could die.
353 string_list *waypoints = globals->get_initial_waypoints();
355 string_list::iterator it;
356 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
357 WayptRef w = waypointFromString(*it);
359 _plan->insertWayptAtIndex(w, -1);
363 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
367 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
368 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
370 // check airbone flag agrees with presets
373 void FGRouteMgr::bind() { }
374 void FGRouteMgr::unbind() { }
376 bool FGRouteMgr::isRouteActive() const
378 return active->getBoolValue();
381 bool FGRouteMgr::saveRoute(const SGPath& p)
387 return _plan->save(p);
390 bool FGRouteMgr::loadRoute(const SGPath& p)
392 FlightPlan* fp = new FlightPlan;
402 FlightPlan* FGRouteMgr::flightPlan() const
407 void FGRouteMgr::setFlightPlan(FlightPlan* plan)
415 active->setBoolValue(false);
419 _plan->setDelegate(this);
421 _flightplanChanged->fireValueChanged();
423 // fire all the callbacks!
427 currentWaypointChanged();
430 void FGRouteMgr::update( double dt )
433 return; // paused, nothing to do here
436 double gs = groundSpeed->getDoubleValue();
437 if (airborne->getBoolValue()) {
438 time_t now = time(NULL);
439 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
441 if (weightOnWheels->getBoolValue()) {
443 destination->setIntValue("touchdown-time", time(NULL));
444 airborne->setBoolValue(false);
446 } else { // not airborne
447 if (weightOnWheels->getBoolValue() || (gs < 40)) {
451 airborne->setBoolValue(true);
452 _takeoffTime = time(NULL); // start the clock
453 departure->setIntValue("takeoff-time", _takeoffTime);
456 if (!active->getBoolValue()) {
460 if (checkFinished()) {
464 // basic course/distance information
465 SGGeod currentPos = globals->get_aircraft_position();
467 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
474 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
476 // update wp0 / wp1 / wp-last
477 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
478 wp0->setDoubleValue("true-bearing-deg", courseDeg);
479 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
480 wp0->setDoubleValue("bearing-deg", courseDeg);
481 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
483 double totalPathDistanceNm = _plan->totalDistanceNm();
484 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
486 // total distance to go, is direct distance to wp0, plus the remaining
487 // path distance from wp0
488 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
490 wp0->setDoubleValue("distance-along-route-nm",
491 leg->distanceAlongRoute());
492 wp0->setDoubleValue("remaining-distance-nm",
493 totalPathDistanceNm - leg->distanceAlongRoute());
495 FlightPlan::Leg* nextLeg = _plan->nextLeg();
497 boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
499 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
500 wp1->setDoubleValue("true-bearing-deg", courseDeg);
501 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
502 wp1->setDoubleValue("bearing-deg", courseDeg);
503 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
504 wp1->setDoubleValue("distance-along-route-nm",
505 nextLeg->distanceAlongRoute());
506 wp1->setDoubleValue("remaining-distance-nm",
507 totalPathDistanceNm - nextLeg->distanceAlongRoute());
510 distanceToGo->setDoubleValue(totalDistanceRemaining);
511 wpn->setDoubleValue("dist", totalDistanceRemaining);
512 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
513 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
516 void FGRouteMgr::clearRoute()
523 Waypt* FGRouteMgr::currentWaypt() const
525 if (_plan && _plan->currentLeg()) {
526 return _plan->currentLeg()->waypoint();
532 int FGRouteMgr::currentIndex() const
538 return _plan->currentIndex();
541 Waypt* FGRouteMgr::wayptAtIndex(int index) const
544 FlightPlan::Leg* leg = _plan->legAtIndex(index);
546 return leg->waypoint();
553 int FGRouteMgr::numLegs() const
556 return _plan->numLegs();
562 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
564 double speed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
566 aProp->setStringValue("--:--");
571 double eta = aDistance * SG_METER_TO_NM / speed;
572 if ( eta >= 100.0 ) {
573 eta = 99.999; // clamp
576 if ( eta < (1.0/6.0) ) {
577 eta *= 60.0; // within 10 minutes, bump up to min/secs
580 int major = (int)eta,
581 minor = (int)((eta - (int)eta) * 60.0);
582 snprintf( eta_str, 64, "%d:%02d", major, minor );
583 aProp->setStringValue( eta_str );
586 void FGRouteMgr::removeLegAtIndex(int aIndex)
592 _plan->deleteIndex(aIndex);
596 * route between index-1 and index, using airways.
598 bool FGRouteMgr::routeToIndex(int index, RouteType aRouteType)
608 if (!_plan->departureAirport()) {
609 SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no departure set");
613 wp1 = new NavaidWaypoint(_plan->departureAirport().get(), NULL);
615 wp1 = wayptAtIndex(index - 1);
618 if (index >= numLegs()) {
619 if (!_plan->destinationAirport()) {
620 SG_LOG(SG_AUTOPILOT, SG_WARN, "routeToIndex: no destination set");
624 wp2 = new NavaidWaypoint(_plan->destinationAirport().get(), NULL);
626 wp2 = wayptAtIndex(index);
629 double distNm = SGGeodesy::distanceNm(wp1->position(), wp2->position());
630 if (distNm < 100.0) {
631 SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: existing waypoints are nearby, direct route");
636 switch (aRouteType) {
637 case ROUTE_HIGH_AIRWAYS:
638 Airway::highLevel()->route(wp1, wp2, r);
641 case ROUTE_LOW_AIRWAYS:
642 Airway::lowLevel()->route(wp1, wp2, r);
646 throw sg_exception("VOR routing not supported yet");
650 SG_LOG(SG_AUTOPILOT, SG_INFO, "routeToIndex: no route found");
654 _plan->insertWayptsAtIndex(r, index);
658 void FGRouteMgr::departureChanged()
660 _plan->clearWayptsWithFlag(WPT_DEPARTURE);
663 buildDeparture(enroute, wps);
664 _plan->insertWayptsAtIndex(wps, 0);
667 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
669 if (!_plan->departureAirport()) {
673 if (!_plan->departureRunway()) {
674 // valid airport, but no runway selected, so just the airport _plan itself
675 WayptRef w = new NavaidWaypoint(_plan->departureAirport(), _plan);
676 w->setFlag(WPT_DEPARTURE);
681 WayptRef rwyWaypt = new RunwayWaypt(_plan->departureRunway(), _plan);
682 rwyWaypt->setFlag(WPT_DEPARTURE);
683 wps.push_back(rwyWaypt);
689 _plan->sid()->route(_plan->departureRunway(), _plan->sidTransition(), wps);
692 void FGRouteMgr::arrivalChanged()
694 _plan->clearWayptsWithFlag(WPT_ARRIVAL);
695 _plan->clearWayptsWithFlag(WPT_APPROACH);
698 buildArrival(enroute, wps);
699 _plan->insertWayptsAtIndex(wps, -1);
702 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
704 FGAirportRef apt = _plan->destinationAirport();
709 if (!_plan->destinationRunway()) {
710 WayptRef w = new NavaidWaypoint(apt.ptr(), _plan);
711 w->setFlag(WPT_ARRIVAL);
717 _plan->star()->route(_plan->destinationRunway(), _plan->starTransition(), wps);
720 if (_plan->approach()) {
721 _plan->approach()->route(wps.back(), wps);
723 WayptRef w = new RunwayWaypt(_plan->destinationRunway(), _plan);
724 w->setFlag(WPT_APPROACH);
729 void FGRouteMgr::waypointsChanged()
732 _edited->fireValueChanged();
736 // mirror internal route to the property system for inspection by other subsystems
737 void FGRouteMgr::update_mirror()
739 mirror->removeChildren("wp");
740 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
741 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
744 mirror->setIntValue("num", 0);
746 rmDlg->updateValues();
751 int num = _plan->numLegs();
753 for (int i = 0; i < num; i++) {
754 FlightPlan::Leg* leg = _plan->legAtIndex(i);
755 WayptRef wp = leg->waypoint();
756 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
758 const SGGeod& pos(wp->position());
759 prop->setStringValue("id", wp->ident().c_str());
760 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
761 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
763 // leg course+distance
765 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
766 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
767 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
769 if (leg->altitudeRestriction() != RESTRICT_NONE) {
770 double ft = leg->altitudeFt();
771 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
772 prop->setDoubleValue("altitude-ft", ft);
773 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
775 prop->setDoubleValue("altitude-m", -9999.9);
776 prop->setDoubleValue("altitude-ft", -9999.9);
779 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
780 prop->setDoubleValue("speed-mach", leg->speedMach());
781 } else if (leg->speedRestriction() != RESTRICT_NONE) {
782 prop->setDoubleValue("speed-kts", leg->speedKts());
785 if (wp->flag(WPT_ARRIVAL)) {
786 prop->setBoolValue("arrival", true);
789 if (wp->flag(WPT_DEPARTURE)) {
790 prop->setBoolValue("departure", true);
793 if (wp->flag(WPT_MISS)) {
794 prop->setBoolValue("missed-approach", true);
797 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
798 } // of waypoint iteration
800 // set number as listener attachment point
801 mirror->setIntValue("num", _plan->numLegs());
804 rmDlg->updateValues();
807 totalDistance->setDoubleValue(_plan->totalDistanceNm());
810 // command interface /autopilot/route-manager/input:
812 // @CLEAR ... clear route
813 // @POP ... remove first entry
814 // @DELETE3 ... delete 4th entry
815 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
816 // KSFO@900 ... append "KSFO@900"
818 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
820 const char *s = prop->getStringValue();
821 if (strlen(s) == 0) {
825 if (!strcmp(s, "@CLEAR"))
827 else if (!strcmp(s, "@ACTIVATE"))
829 else if (!strcmp(s, "@LOAD")) {
830 SGPath path(mgr->_pathNode->getStringValue());
831 mgr->loadRoute(path);
832 } else if (!strcmp(s, "@SAVE")) {
833 SGPath path(mgr->_pathNode->getStringValue());
834 mgr->saveRoute(path);
835 } else if (!strcmp(s, "@NEXT")) {
836 mgr->jumpToIndex(mgr->currentIndex() + 1);
837 } else if (!strcmp(s, "@PREVIOUS")) {
838 mgr->jumpToIndex(mgr->currentIndex() - 1);
839 } else if (!strncmp(s, "@JUMP", 5)) {
840 mgr->jumpToIndex(atoi(s + 5));
841 } else if (!strncmp(s, "@DELETE", 7))
842 mgr->removeLegAtIndex(atoi(s + 7));
843 else if (!strncmp(s, "@INSERT", 7)) {
845 int pos = strtol(s + 7, &r, 10);
851 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
852 } else if (!strncmp(s, "@ROUTE", 6)) {
854 int endIndex = strtol(s + 6, &r, 10);
855 RouteType rt = (RouteType) mgr->_routingType->getIntValue();
856 mgr->routeToIndex(endIndex, rt);
857 } else if (!strcmp(s, "@POSINIT")) {
858 mgr->initAtPosition();
860 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
863 void FGRouteMgr::initAtPosition()
865 if (isRouteActive()) {
866 return; // don't mess with the active route
869 if (haveUserWaypoints()) {
870 // user has already defined, loaded or entered a route, again
871 // don't interfere with it
875 if (airborne->getBoolValue()) {
876 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
877 _plan->setDeparture((FGAirport*) NULL);
882 SGGeod pos = globals->get_aircraft_position();
883 if (!_plan->departureAirport()) {
884 _plan->setDeparture(FGAirport::findClosest(pos, 20.0));
885 if (!_plan->departureAirport()) {
886 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
891 std::string rwy = departure->getStringValue("runway");
894 r = _plan->departureAirport()->getRunwayByIdent(rwy);
896 r = _plan->departureAirport()->findBestRunwayForPos(pos);
903 _plan->setDeparture(r);
904 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
905 << _plan->departureAirport()->ident() << " on runway " << r->ident());
908 bool FGRouteMgr::haveUserWaypoints() const
914 bool FGRouteMgr::activate()
917 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
921 if (isRouteActive()) {
922 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
926 _plan->setCurrentIndex(0);
927 active->setBoolValue(true);
928 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
933 void FGRouteMgr::sequence()
935 if (!_plan || !active->getBoolValue()) {
936 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
940 if (checkFinished()) {
944 _plan->setCurrentIndex(_plan->currentIndex() + 1);
947 bool FGRouteMgr::checkFinished()
954 // done if we're stopped on the destination runway
955 if (_plan->currentLeg() &&
956 (_plan->currentLeg()->waypoint()->source() == _plan->destinationRunway()))
958 double gs = groundSpeed->getDoubleValue();
959 done = weightOnWheels->getBoolValue() && (gs < 25);
962 // also done if we hit the final waypoint
963 if (_plan->currentIndex() >= _plan->numLegs()) {
968 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
969 _finished->fireValueChanged();
970 active->setBoolValue(false);
976 void FGRouteMgr::jumpToIndex(int index)
982 _plan->setCurrentIndex(index);
985 void FGRouteMgr::currentWaypointChanged()
987 Waypt* cur = currentWaypt();
988 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
990 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
991 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
993 _currentWpt->fireValueChanged();
994 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
997 const char* FGRouteMgr::getDepartureICAO() const
999 if (!_plan || !_plan->departureAirport()) {
1003 return _plan->departureAirport()->ident().c_str();
1006 const char* FGRouteMgr::getDepartureName() const
1008 if (!_plan || !_plan->departureAirport()) {
1012 return _plan->departureAirport()->name().c_str();
1015 const char* FGRouteMgr::getDepartureRunway() const
1017 if (_plan && _plan->departureRunway()) {
1018 return _plan->departureRunway()->ident().c_str();
1024 void FGRouteMgr::setDepartureRunway(const char* aIdent)
1026 FGAirport* apt = _plan->departureAirport();
1027 if (!apt || (aIdent == NULL)) {
1028 _plan->setDeparture(apt);
1029 } else if (apt->hasRunwayWithIdent(aIdent)) {
1030 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
1034 void FGRouteMgr::setDepartureICAO(const char* aIdent)
1036 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1037 _plan->setDeparture((FGAirport*) NULL);
1039 _plan->setDeparture(FGAirport::findByIdent(aIdent));
1043 const char* FGRouteMgr::getSID() const
1045 if (_plan && _plan->sid()) {
1046 return _plan->sid()->ident().c_str();
1052 void FGRouteMgr::setSID(const char* aIdent)
1054 FGAirport* apt = _plan->departureAirport();
1055 if (!apt || (aIdent == NULL)) {
1056 _plan->setSID((flightgear::SID*) NULL);
1060 string ident(aIdent);
1061 size_t hyphenPos = ident.find('-');
1062 if (hyphenPos != string::npos) {
1063 string sidIdent = ident.substr(0, hyphenPos);
1064 string transIdent = ident.substr(hyphenPos + 1);
1066 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
1067 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
1068 _plan->setSID(trans);
1070 _plan->setSID(apt->findSIDWithIdent(aIdent));
1074 const char* FGRouteMgr::getDestinationICAO() const
1076 if (!_plan || !_plan->destinationAirport()) {
1080 return _plan->destinationAirport()->ident().c_str();
1083 const char* FGRouteMgr::getDestinationName() const
1085 if (!_plan || !_plan->destinationAirport()) {
1089 return _plan->destinationAirport()->name().c_str();
1092 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1094 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1095 _plan->setDestination((FGAirport*) NULL);
1097 _plan->setDestination(FGAirport::findByIdent(aIdent));
1101 const char* FGRouteMgr::getDestinationRunway() const
1103 if (_plan && _plan->destinationRunway()) {
1104 return _plan->destinationRunway()->ident().c_str();
1110 void FGRouteMgr::setDestinationRunway(const char* aIdent)
1112 FGAirport* apt = _plan->destinationAirport();
1113 if (!apt || (aIdent == NULL)) {
1114 _plan->setDestination(apt);
1115 } else if (apt->hasRunwayWithIdent(aIdent)) {
1116 _plan->setDestination(apt->getRunwayByIdent(aIdent));
1120 const char* FGRouteMgr::getApproach() const
1122 if (_plan && _plan->approach()) {
1123 return _plan->approach()->ident().c_str();
1129 void FGRouteMgr::setApproach(const char* aIdent)
1131 FGAirport* apt = _plan->destinationAirport();
1132 if (!apt || (aIdent == NULL)) {
1133 _plan->setApproach(NULL);
1135 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1139 const char* FGRouteMgr::getSTAR() const
1141 if (_plan && _plan->star()) {
1142 return _plan->star()->ident().c_str();
1148 void FGRouteMgr::setSTAR(const char* aIdent)
1150 FGAirport* apt = _plan->destinationAirport();
1151 if (!apt || (aIdent == NULL)) {
1152 _plan->setSTAR((STAR*) NULL);
1156 string ident(aIdent);
1157 size_t hyphenPos = ident.find('-');
1158 if (hyphenPos != string::npos) {
1159 string starIdent = ident.substr(0, hyphenPos);
1160 string transIdent = ident.substr(hyphenPos + 1);
1162 STAR* star = apt->findSTARWithIdent(starIdent);
1163 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1164 _plan->setSTAR(trans);
1166 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1170 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1172 return _plan->waypointFromString(target);
1175 double FGRouteMgr::getDepartureFieldElevation() const
1177 if (!_plan || !_plan->departureAirport()) {
1181 return _plan->departureAirport()->elevation();
1184 double FGRouteMgr::getDestinationFieldElevation() const
1186 if (!_plan || !_plan->destinationAirport()) {
1190 return _plan->destinationAirport()->elevation();
1193 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1195 if ((index < 0) || (index >= numWaypts())) {
1196 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1199 return mirror->getChild("wp", index);