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/sg_path.hxx>
45 #include <simgear/sg_inlines.h>
47 #include "Main/fg_props.hxx"
48 #include "Navaids/positioned.hxx"
49 #include <Navaids/waypoint.hxx>
50 #include <Navaids/procedure.hxx>
51 #include "Airports/simple.hxx"
52 #include "Airports/runways.hxx"
53 #include <GUI/new_gui.hxx>
54 #include <GUI/dialog.hxx>
56 #define RM "/autopilot/route-manager/"
58 using namespace flightgear;
60 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
62 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
63 SGPath path(arg->getStringValue("path"));
64 return self->loadRoute(path);
67 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
69 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
70 SGPath path(arg->getStringValue("path"));
71 return self->saveRoute(path);
74 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
76 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
77 bool activate = arg->getBoolValue("activate", true);
87 static bool commandClearFlightPlan(const SGPropertyNode*)
89 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
94 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
96 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
97 int index = arg->getIntValue("index");
98 if ((index < 0) || (index >= self->numLegs())) {
102 self->jumpToIndex(index);
106 static bool commandInsertWaypt(const SGPropertyNode* arg)
108 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
109 int index = arg->getIntValue("index");
110 std::string ident(arg->getStringValue("id"));
111 int alt = arg->getIntValue("altitude-ft", -999);
112 int ias = arg->getIntValue("speed-knots", -999);
115 // lat/lon may be supplied to narrow down navaid search, or to specify
118 if (arg->hasChild("longitude-deg")) {
119 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
120 arg->getDoubleValue("latitude-deg"));
123 if (arg->hasChild("navaid")) {
124 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
126 if (arg->hasChild("navaid", 1)) {
127 // intersection of two radials
128 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
130 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
134 double r1 = arg->getDoubleValue("radial"),
135 r2 = arg->getDoubleValue("radial[1]");
138 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
140 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
141 << "," << p2->ident());
145 std::string name = p->ident() + "-" + p2->ident();
146 wp = new BasicWaypt(intersection, name, NULL);
147 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
148 // offset radial from navaid
149 double radial = arg->getDoubleValue("radial");
150 double distanceNm = arg->getDoubleValue("offset-nm");
151 //radial += magvar->getDoubleValue(); // convert to true bearing
152 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
154 wp = new NavaidWaypoint(p, NULL);
156 } else if (arg->hasChild("airport")) {
157 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
159 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
163 if (arg->hasChild("runway")) {
164 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
165 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
169 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
170 wp = new RunwayWaypt(runway, NULL);
172 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
174 } else if (arg->hasChild("text")) {
175 wp = self->waypointFromString(arg->getStringValue("text"));
176 } else if (!(pos == SGGeod())) {
177 // just a raw lat/lon
178 wp = new BasicWaypt(pos, ident, NULL);
180 return false; // failed to build waypoint
183 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
185 leg->setAltitude(RESTRICT_AT, alt);
189 leg->setSpeed(RESTRICT_AT, ias);
195 static bool commandDeleteWaypt(const SGPropertyNode* arg)
197 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
198 int index = arg->getIntValue("index");
199 self->removeLegAtIndex(index);
203 /////////////////////////////////////////////////////////////////////////////
205 FGRouteMgr::FGRouteMgr() :
207 input(fgGetNode( RM "input", true )),
208 mirror(fgGetNode( RM "route", true ))
210 listener = new InputListener(this);
211 input->setStringValue("");
212 input->addChangeListener(listener);
214 SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
215 SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
216 SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
217 SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
218 SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
219 SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
220 SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
224 FGRouteMgr::~FGRouteMgr()
226 input->removeChangeListener(listener);
231 void FGRouteMgr::init() {
232 SGPropertyNode_ptr rm(fgGetNode(RM));
234 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
236 departure = fgGetNode(RM "departure", true);
237 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
238 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
239 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
240 &FGRouteMgr::getDepartureRunway,
241 &FGRouteMgr::setDepartureRunway));
242 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
244 &FGRouteMgr::setSID));
246 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
247 &FGRouteMgr::getDepartureName, NULL));
248 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
249 &FGRouteMgr::getDestinationFieldElevation, NULL));
250 departure->getChild("etd", 0, true);
251 departure->getChild("takeoff-time", 0, true);
253 destination = fgGetNode(RM "destination", true);
254 destination->getChild("airport", 0, true);
256 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
257 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
258 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
259 &FGRouteMgr::getDestinationRunway,
260 &FGRouteMgr::setDestinationRunway));
261 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
262 &FGRouteMgr::getSTAR,
263 &FGRouteMgr::setSTAR));
264 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
265 &FGRouteMgr::getApproach,
266 &FGRouteMgr::setApproach));
268 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
269 &FGRouteMgr::getDestinationName, NULL));
270 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
271 &FGRouteMgr::getDestinationFieldElevation, NULL));
273 destination->getChild("eta", 0, true);
274 destination->getChild("touchdown-time", 0, true);
276 alternate = fgGetNode(RM "alternate", true);
277 alternate->getChild("airport", 0, true);
278 alternate->getChild("runway", 0, true);
280 cruise = fgGetNode(RM "cruise", true);
281 cruise->getChild("altitude-ft", 0, true);
282 cruise->setDoubleValue("altitude-ft", 10000.0);
283 cruise->getChild("flight-level", 0, true);
284 cruise->getChild("speed-kts", 0, true);
285 cruise->setDoubleValue("speed-kts", 160.0);
287 totalDistance = fgGetNode(RM "total-distance", true);
288 totalDistance->setDoubleValue(0.0);
289 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
290 distanceToGo->setDoubleValue(0.0);
292 ete = fgGetNode(RM "ete", true);
293 ete->setDoubleValue(0.0);
295 elapsedFlightTime = fgGetNode(RM "flight-time", true);
296 elapsedFlightTime->setDoubleValue(0.0);
298 active = fgGetNode(RM "active", true);
299 active->setBoolValue(false);
301 airborne = fgGetNode(RM "airborne", true);
302 airborne->setBoolValue(false);
304 _edited = fgGetNode(RM "signals/edited", true);
305 _finished = fgGetNode(RM "signals/finished", true);
306 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
308 _currentWpt = fgGetNode(RM "current-wp", true);
309 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
310 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
312 // temporary distance / eta calculations, for backward-compatability
313 wp0 = fgGetNode(RM "wp", 0, true);
314 wp0->getChild("id", 0, true);
315 wp0->getChild("dist", 0, true);
316 wp0->getChild("eta", 0, true);
317 wp0->getChild("bearing-deg", 0, true);
319 wp1 = fgGetNode(RM "wp", 1, true);
320 wp1->getChild("id", 0, true);
321 wp1->getChild("dist", 0, true);
322 wp1->getChild("eta", 0, true);
324 wpn = fgGetNode(RM "wp-last", 0, true);
325 wpn->getChild("dist", 0, true);
326 wpn->getChild("eta", 0, true);
328 _pathNode = fgGetNode(RM "file-path", 0, true);
332 void FGRouteMgr::postinit()
334 setFlightPlan(new FlightPlan());
336 SGPath path(_pathNode->getStringValue());
337 if (!path.isNull()) {
338 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
342 // this code only matters for the --wp option now - perhaps the option
343 // should be deprecated in favour of an explicit flight-plan file?
344 // then the global initial waypoint list could die.
345 string_list *waypoints = globals->get_initial_waypoints();
347 string_list::iterator it;
348 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
349 WayptRef w = waypointFromString(*it);
351 _plan->insertWayptAtIndex(w, -1);
355 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
359 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
360 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
362 // check airbone flag agrees with presets
365 void FGRouteMgr::bind() { }
366 void FGRouteMgr::unbind() { }
368 bool FGRouteMgr::isRouteActive() const
370 return active->getBoolValue();
373 bool FGRouteMgr::saveRoute(const SGPath& p)
379 return _plan->save(p);
382 bool FGRouteMgr::loadRoute(const SGPath& p)
384 FlightPlan* fp = new FlightPlan;
394 FlightPlan* FGRouteMgr::flightPlan() const
399 void FGRouteMgr::setFlightPlan(FlightPlan* plan)
406 _plan->removeDelegate(this);
408 active->setBoolValue(false);
412 _plan->addDelegate(this);
414 _flightplanChanged->fireValueChanged();
416 // fire all the callbacks!
420 currentWaypointChanged();
423 void FGRouteMgr::update( double dt )
426 return; // paused, nothing to do here
429 double gs = groundSpeed->getDoubleValue();
430 if (airborne->getBoolValue()) {
431 time_t now = time(NULL);
432 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
434 if (weightOnWheels->getBoolValue()) {
436 destination->setIntValue("touchdown-time", time(NULL));
437 airborne->setBoolValue(false);
439 } else { // not airborne
440 if (weightOnWheels->getBoolValue() || (gs < 40)) {
441 // either taking-off or rolling-out after touchdown
443 airborne->setBoolValue(true);
444 _takeoffTime = time(NULL); // start the clock
445 departure->setIntValue("takeoff-time", _takeoffTime);
449 if (!active->getBoolValue()) {
453 if (checkFinished()) {
457 // basic course/distance information
458 SGGeod currentPos = globals->get_aircraft_position();
460 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
467 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
469 // update wp0 / wp1 / wp-last
470 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
471 wp0->setDoubleValue("true-bearing-deg", courseDeg);
472 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
473 wp0->setDoubleValue("bearing-deg", courseDeg);
474 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
476 double totalPathDistanceNm = _plan->totalDistanceNm();
477 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
479 // total distance to go, is direct distance to wp0, plus the remaining
480 // path distance from wp0
481 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
483 wp0->setDoubleValue("distance-along-route-nm",
484 leg->distanceAlongRoute());
485 wp0->setDoubleValue("remaining-distance-nm",
486 totalPathDistanceNm - leg->distanceAlongRoute());
488 FlightPlan::Leg* nextLeg = _plan->nextLeg();
490 boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
492 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
493 wp1->setDoubleValue("true-bearing-deg", courseDeg);
494 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
495 wp1->setDoubleValue("bearing-deg", courseDeg);
496 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
497 wp1->setDoubleValue("distance-along-route-nm",
498 nextLeg->distanceAlongRoute());
499 wp1->setDoubleValue("remaining-distance-nm",
500 totalPathDistanceNm - nextLeg->distanceAlongRoute());
503 distanceToGo->setDoubleValue(totalDistanceRemaining);
504 wpn->setDoubleValue("dist", totalDistanceRemaining);
505 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
506 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
509 void FGRouteMgr::clearRoute()
516 Waypt* FGRouteMgr::currentWaypt() const
518 if (_plan && _plan->currentLeg()) {
519 return _plan->currentLeg()->waypoint();
525 int FGRouteMgr::currentIndex() const
531 return _plan->currentIndex();
534 Waypt* FGRouteMgr::wayptAtIndex(int index) const
537 FlightPlan::Leg* leg = _plan->legAtIndex(index);
539 return leg->waypoint();
546 int FGRouteMgr::numLegs() const
549 return _plan->numLegs();
555 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
557 double speed = groundSpeed->getDoubleValue();
559 aProp->setStringValue("--:--");
564 double eta = aDistance * SG_METER_TO_NM / speed;
565 if ( eta >= 100.0 ) {
566 eta = 99.999; // clamp
569 if ( eta < (1.0/6.0) ) {
570 eta *= 60.0; // within 10 minutes, bump up to min/secs
573 int major = (int)eta,
574 minor = (int)((eta - (int)eta) * 60.0);
575 snprintf( eta_str, 64, "%d:%02d", major, minor );
576 aProp->setStringValue( eta_str );
579 void FGRouteMgr::removeLegAtIndex(int aIndex)
585 _plan->deleteIndex(aIndex);
588 void FGRouteMgr::departureChanged()
590 _plan->clearWayptsWithFlag(WPT_DEPARTURE);
593 buildDeparture(enroute, wps);
594 _plan->insertWayptsAtIndex(wps, 0);
597 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
599 if (!_plan->departureAirport()) {
603 if (!_plan->departureRunway()) {
604 // valid airport, but no runway selected, so just the airport _plan itself
605 WayptRef w = new NavaidWaypoint(_plan->departureAirport(), _plan);
606 w->setFlag(WPT_DEPARTURE);
611 WayptRef rwyWaypt = new RunwayWaypt(_plan->departureRunway(), _plan);
612 rwyWaypt->setFlag(WPT_DEPARTURE);
613 wps.push_back(rwyWaypt);
619 _plan->sid()->route(_plan->departureRunway(), _plan->sidTransition(), wps);
622 void FGRouteMgr::arrivalChanged()
624 _plan->clearWayptsWithFlag(WPT_ARRIVAL);
625 _plan->clearWayptsWithFlag(WPT_APPROACH);
628 buildArrival(enroute, wps);
629 _plan->insertWayptsAtIndex(wps, -1);
632 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
634 FGAirportRef apt = _plan->destinationAirport();
639 if (!_plan->destinationRunway()) {
640 WayptRef w = new NavaidWaypoint(apt.ptr(), _plan);
641 w->setFlag(WPT_ARRIVAL);
647 _plan->star()->route(_plan->destinationRunway(), _plan->starTransition(), wps);
650 if (_plan->approach()) {
651 _plan->approach()->route(wps.back(), wps);
653 WayptRef w = new RunwayWaypt(_plan->destinationRunway(), _plan);
654 w->setFlag(WPT_APPROACH);
659 void FGRouteMgr::waypointsChanged()
662 _edited->fireValueChanged();
666 // mirror internal route to the property system for inspection by other subsystems
667 void FGRouteMgr::update_mirror()
669 mirror->removeChildren("wp");
670 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
671 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
674 mirror->setIntValue("num", 0);
676 rmDlg->updateValues();
681 int num = _plan->numLegs();
683 for (int i = 0; i < num; i++) {
684 FlightPlan::Leg* leg = _plan->legAtIndex(i);
685 WayptRef wp = leg->waypoint();
686 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
688 const SGGeod& pos(wp->position());
689 prop->setStringValue("id", wp->ident().c_str());
690 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
691 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
693 // leg course+distance
695 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
696 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
697 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
699 if (leg->altitudeRestriction() != RESTRICT_NONE) {
700 double ft = leg->altitudeFt();
701 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
702 prop->setDoubleValue("altitude-ft", ft);
703 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
705 prop->setDoubleValue("altitude-m", -9999.9);
706 prop->setDoubleValue("altitude-ft", -9999.9);
709 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
710 prop->setDoubleValue("speed-mach", leg->speedMach());
711 } else if (leg->speedRestriction() != RESTRICT_NONE) {
712 prop->setDoubleValue("speed-kts", leg->speedKts());
715 if (wp->flag(WPT_ARRIVAL)) {
716 prop->setBoolValue("arrival", true);
719 if (wp->flag(WPT_DEPARTURE)) {
720 prop->setBoolValue("departure", true);
723 if (wp->flag(WPT_MISS)) {
724 prop->setBoolValue("missed-approach", true);
727 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
728 } // of waypoint iteration
730 // set number as listener attachment point
731 mirror->setIntValue("num", _plan->numLegs());
734 rmDlg->updateValues();
737 totalDistance->setDoubleValue(_plan->totalDistanceNm());
740 // command interface /autopilot/route-manager/input:
742 // @CLEAR ... clear route
743 // @POP ... remove first entry
744 // @DELETE3 ... delete 4th entry
745 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
746 // KSFO@900 ... append "KSFO@900"
748 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
750 const char *s = prop->getStringValue();
751 if (strlen(s) == 0) {
755 if (!strcmp(s, "@CLEAR"))
757 else if (!strcmp(s, "@ACTIVATE"))
759 else if (!strcmp(s, "@LOAD")) {
760 SGPath path(mgr->_pathNode->getStringValue());
761 mgr->loadRoute(path);
762 } else if (!strcmp(s, "@SAVE")) {
763 SGPath path(mgr->_pathNode->getStringValue());
764 mgr->saveRoute(path);
765 } else if (!strcmp(s, "@NEXT")) {
766 mgr->jumpToIndex(mgr->currentIndex() + 1);
767 } else if (!strcmp(s, "@PREVIOUS")) {
768 mgr->jumpToIndex(mgr->currentIndex() - 1);
769 } else if (!strncmp(s, "@JUMP", 5)) {
770 mgr->jumpToIndex(atoi(s + 5));
771 } else if (!strncmp(s, "@DELETE", 7))
772 mgr->removeLegAtIndex(atoi(s + 7));
773 else if (!strncmp(s, "@INSERT", 7)) {
775 int pos = strtol(s + 7, &r, 10);
781 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
782 } else if (!strcmp(s, "@POSINIT")) {
783 mgr->initAtPosition();
785 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
788 void FGRouteMgr::initAtPosition()
790 if (isRouteActive()) {
791 return; // don't mess with the active route
794 if (haveUserWaypoints()) {
795 // user has already defined, loaded or entered a route, again
796 // don't interfere with it
800 if (airborne->getBoolValue()) {
801 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
802 _plan->setDeparture((FGAirport*) NULL);
807 SGGeod pos = globals->get_aircraft_position();
808 if (!_plan->departureAirport()) {
809 _plan->setDeparture(FGAirport::findClosest(pos, 20.0));
810 if (!_plan->departureAirport()) {
811 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
816 std::string rwy = departure->getStringValue("runway");
819 r = _plan->departureAirport()->getRunwayByIdent(rwy);
821 r = _plan->departureAirport()->findBestRunwayForPos(pos);
828 _plan->setDeparture(r);
829 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
830 << _plan->departureAirport()->ident() << " on runway " << r->ident());
833 bool FGRouteMgr::haveUserWaypoints() const
839 bool FGRouteMgr::activate()
842 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
846 if (isRouteActive()) {
847 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
851 _plan->setCurrentIndex(0);
852 active->setBoolValue(true);
853 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
858 void FGRouteMgr::sequence()
860 if (!_plan || !active->getBoolValue()) {
861 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
865 if (checkFinished()) {
869 _plan->setCurrentIndex(_plan->currentIndex() + 1);
872 bool FGRouteMgr::checkFinished()
879 // done if we're stopped on the destination runway
880 if (_plan->currentLeg() &&
881 (_plan->currentLeg()->waypoint()->source() == _plan->destinationRunway()))
883 double gs = groundSpeed->getDoubleValue();
884 done = weightOnWheels->getBoolValue() && (gs < 25);
887 // also done if we hit the final waypoint
888 if (_plan->currentIndex() >= _plan->numLegs()) {
893 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
894 _finished->fireValueChanged();
895 active->setBoolValue(false);
901 void FGRouteMgr::jumpToIndex(int index)
907 _plan->setCurrentIndex(index);
910 void FGRouteMgr::currentWaypointChanged()
912 Waypt* cur = currentWaypt();
913 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
915 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
916 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
918 _currentWpt->fireValueChanged();
919 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
922 const char* FGRouteMgr::getDepartureICAO() const
924 if (!_plan || !_plan->departureAirport()) {
928 return _plan->departureAirport()->ident().c_str();
931 const char* FGRouteMgr::getDepartureName() const
933 if (!_plan || !_plan->departureAirport()) {
937 return _plan->departureAirport()->name().c_str();
940 const char* FGRouteMgr::getDepartureRunway() const
942 if (_plan && _plan->departureRunway()) {
943 return _plan->departureRunway()->ident().c_str();
949 void FGRouteMgr::setDepartureRunway(const char* aIdent)
951 FGAirport* apt = _plan->departureAirport();
952 if (!apt || (aIdent == NULL)) {
953 _plan->setDeparture(apt);
954 } else if (apt->hasRunwayWithIdent(aIdent)) {
955 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
959 void FGRouteMgr::setDepartureICAO(const char* aIdent)
961 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
962 _plan->setDeparture((FGAirport*) NULL);
964 _plan->setDeparture(FGAirport::findByIdent(aIdent));
968 const char* FGRouteMgr::getSID() const
970 if (_plan && _plan->sid()) {
971 return _plan->sid()->ident().c_str();
977 void FGRouteMgr::setSID(const char* aIdent)
979 FGAirport* apt = _plan->departureAirport();
980 if (!apt || (aIdent == NULL)) {
981 _plan->setSID((flightgear::SID*) NULL);
985 string ident(aIdent);
986 size_t hyphenPos = ident.find('-');
987 if (hyphenPos != string::npos) {
988 string sidIdent = ident.substr(0, hyphenPos);
989 string transIdent = ident.substr(hyphenPos + 1);
991 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
992 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
993 _plan->setSID(trans);
995 _plan->setSID(apt->findSIDWithIdent(aIdent));
999 const char* FGRouteMgr::getDestinationICAO() const
1001 if (!_plan || !_plan->destinationAirport()) {
1005 return _plan->destinationAirport()->ident().c_str();
1008 const char* FGRouteMgr::getDestinationName() const
1010 if (!_plan || !_plan->destinationAirport()) {
1014 return _plan->destinationAirport()->name().c_str();
1017 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1019 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1020 _plan->setDestination((FGAirport*) NULL);
1022 _plan->setDestination(FGAirport::findByIdent(aIdent));
1026 const char* FGRouteMgr::getDestinationRunway() const
1028 if (_plan && _plan->destinationRunway()) {
1029 return _plan->destinationRunway()->ident().c_str();
1035 void FGRouteMgr::setDestinationRunway(const char* aIdent)
1037 FGAirport* apt = _plan->destinationAirport();
1038 if (!apt || (aIdent == NULL)) {
1039 _plan->setDestination(apt);
1040 } else if (apt->hasRunwayWithIdent(aIdent)) {
1041 _plan->setDestination(apt->getRunwayByIdent(aIdent));
1045 const char* FGRouteMgr::getApproach() const
1047 if (_plan && _plan->approach()) {
1048 return _plan->approach()->ident().c_str();
1054 void FGRouteMgr::setApproach(const char* aIdent)
1056 FGAirport* apt = _plan->destinationAirport();
1057 if (!apt || (aIdent == NULL)) {
1058 _plan->setApproach(NULL);
1060 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1064 const char* FGRouteMgr::getSTAR() const
1066 if (_plan && _plan->star()) {
1067 return _plan->star()->ident().c_str();
1073 void FGRouteMgr::setSTAR(const char* aIdent)
1075 FGAirport* apt = _plan->destinationAirport();
1076 if (!apt || (aIdent == NULL)) {
1077 _plan->setSTAR((STAR*) NULL);
1081 string ident(aIdent);
1082 size_t hyphenPos = ident.find('-');
1083 if (hyphenPos != string::npos) {
1084 string starIdent = ident.substr(0, hyphenPos);
1085 string transIdent = ident.substr(hyphenPos + 1);
1087 STAR* star = apt->findSTARWithIdent(starIdent);
1088 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1089 _plan->setSTAR(trans);
1091 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1095 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1097 return _plan->waypointFromString(target);
1100 double FGRouteMgr::getDepartureFieldElevation() const
1102 if (!_plan || !_plan->departureAirport()) {
1106 return _plan->departureAirport()->elevation();
1109 double FGRouteMgr::getDestinationFieldElevation() const
1111 if (!_plan || !_plan->destinationAirport()) {
1115 return _plan->destinationAirport()->elevation();
1118 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1120 if ((index < 0) || (index >= numWaypts())) {
1121 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1124 return mirror->getChild("wp", index);