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/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 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
67 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
68 SGPath path(arg->getStringValue("path"));
69 return self->loadRoute(path);
72 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
74 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
75 SGPath path(arg->getStringValue("path"));
76 return self->saveRoute(path);
79 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
81 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
82 bool activate = arg->getBoolValue("activate", true);
92 static bool commandClearFlightPlan(const SGPropertyNode*)
94 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
99 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
101 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
102 int index = arg->getIntValue("index");
103 if ((index < 0) || (index >= self->numLegs())) {
107 self->jumpToIndex(index);
111 static bool commandInsertWaypt(const SGPropertyNode* arg)
113 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
114 int index = arg->getIntValue("index");
115 std::string ident(arg->getStringValue("id"));
116 int alt = arg->getIntValue("altitude-ft", -999);
117 int ias = arg->getIntValue("speed-knots", -999);
120 // lat/lon may be supplied to narrow down navaid search, or to specify
123 if (arg->hasChild("longitude-deg")) {
124 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
125 arg->getDoubleValue("latitude-deg"));
128 if (arg->hasChild("navaid")) {
129 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
131 if (arg->hasChild("navaid", 1)) {
132 // intersection of two radials
133 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
135 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
139 double r1 = arg->getDoubleValue("radial"),
140 r2 = arg->getDoubleValue("radial[1]");
143 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
145 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
146 << "," << p2->ident());
150 std::string name = p->ident() + "-" + p2->ident();
151 wp = new BasicWaypt(intersection, name, NULL);
152 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
153 // offset radial from navaid
154 double radial = arg->getDoubleValue("radial");
155 double distanceNm = arg->getDoubleValue("offset-nm");
156 //radial += magvar->getDoubleValue(); // convert to true bearing
157 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
159 wp = new NavaidWaypoint(p, NULL);
161 } else if (arg->hasChild("airport")) {
162 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
164 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
168 if (arg->hasChild("runway")) {
169 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
170 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
174 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
175 wp = new RunwayWaypt(runway, NULL);
177 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
179 } else if (arg->hasChild("text")) {
180 wp = self->waypointFromString(arg->getStringValue("text"));
181 } else if (!(pos == SGGeod())) {
182 // just a raw lat/lon
183 wp = new BasicWaypt(pos, ident, NULL);
185 return false; // failed to build waypoint
188 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
190 leg->setAltitude(RESTRICT_AT, alt);
194 leg->setSpeed(RESTRICT_AT, ias);
200 static bool commandDeleteWaypt(const SGPropertyNode* arg)
202 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
203 int index = arg->getIntValue("index");
204 self->removeLegAtIndex(index);
208 /////////////////////////////////////////////////////////////////////////////
210 FGRouteMgr::FGRouteMgr() :
212 input(fgGetNode( RM "input", true )),
213 mirror(fgGetNode( RM "route", true ))
215 listener = new InputListener(this);
216 input->setStringValue("");
217 input->addChangeListener(listener);
219 SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
220 SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
221 SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
222 SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
223 SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
224 SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
225 SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
229 FGRouteMgr::~FGRouteMgr()
231 input->removeChangeListener(listener);
236 void FGRouteMgr::init() {
237 SGPropertyNode_ptr rm(fgGetNode(RM));
239 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
241 departure = fgGetNode(RM "departure", true);
242 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
243 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
244 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
245 &FGRouteMgr::getDepartureRunway,
246 &FGRouteMgr::setDepartureRunway));
247 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
249 &FGRouteMgr::setSID));
251 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
252 &FGRouteMgr::getDepartureName, NULL));
253 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
254 &FGRouteMgr::getDestinationFieldElevation, NULL));
255 departure->getChild("etd", 0, true);
256 departure->getChild("takeoff-time", 0, true);
258 destination = fgGetNode(RM "destination", true);
259 destination->getChild("airport", 0, true);
261 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
262 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
263 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
264 &FGRouteMgr::getDestinationRunway,
265 &FGRouteMgr::setDestinationRunway));
266 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
267 &FGRouteMgr::getSTAR,
268 &FGRouteMgr::setSTAR));
269 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
270 &FGRouteMgr::getApproach,
271 &FGRouteMgr::setApproach));
273 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
274 &FGRouteMgr::getDestinationName, NULL));
275 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
276 &FGRouteMgr::getDestinationFieldElevation, NULL));
278 destination->getChild("eta", 0, true);
279 destination->getChild("touchdown-time", 0, true);
281 alternate = fgGetNode(RM "alternate", true);
282 alternate->getChild("airport", 0, true);
283 alternate->getChild("runway", 0, true);
285 cruise = fgGetNode(RM "cruise", true);
286 cruise->getChild("altitude-ft", 0, true);
287 cruise->setDoubleValue("altitude-ft", 10000.0);
288 cruise->getChild("flight-level", 0, true);
289 cruise->getChild("speed-kts", 0, true);
290 cruise->setDoubleValue("speed-kts", 160.0);
292 totalDistance = fgGetNode(RM "total-distance", true);
293 totalDistance->setDoubleValue(0.0);
294 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
295 distanceToGo->setDoubleValue(0.0);
297 ete = fgGetNode(RM "ete", true);
298 ete->setDoubleValue(0.0);
300 elapsedFlightTime = fgGetNode(RM "flight-time", true);
301 elapsedFlightTime->setDoubleValue(0.0);
303 active = fgGetNode(RM "active", true);
304 active->setBoolValue(false);
306 airborne = fgGetNode(RM "airborne", true);
307 airborne->setBoolValue(false);
309 _edited = fgGetNode(RM "signals/edited", true);
310 _finished = fgGetNode(RM "signals/finished", true);
311 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
313 _currentWpt = fgGetNode(RM "current-wp", true);
314 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
315 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
317 // temporary distance / eta calculations, for backward-compatability
318 wp0 = fgGetNode(RM "wp", 0, true);
319 wp0->getChild("id", 0, true);
320 wp0->getChild("dist", 0, true);
321 wp0->getChild("eta", 0, true);
322 wp0->getChild("bearing-deg", 0, true);
324 wp1 = fgGetNode(RM "wp", 1, true);
325 wp1->getChild("id", 0, true);
326 wp1->getChild("dist", 0, true);
327 wp1->getChild("eta", 0, true);
329 wpn = fgGetNode(RM "wp-last", 0, true);
330 wpn->getChild("dist", 0, true);
331 wpn->getChild("eta", 0, true);
333 _pathNode = fgGetNode(RM "file-path", 0, true);
334 setFlightPlan(new FlightPlan());
338 void FGRouteMgr::postinit()
340 SGPath path(_pathNode->getStringValue());
341 if (!path.isNull()) {
342 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
346 // this code only matters for the --wp option now - perhaps the option
347 // should be deprecated in favour of an explicit flight-plan file?
348 // then the global initial waypoint list could die.
349 string_list *waypoints = globals->get_initial_waypoints();
351 string_list::iterator it;
352 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
353 WayptRef w = waypointFromString(*it);
355 _plan->insertWayptAtIndex(w, -1);
359 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
363 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
364 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
366 // check airbone flag agrees with presets
369 void FGRouteMgr::bind() { }
370 void FGRouteMgr::unbind() { }
372 bool FGRouteMgr::isRouteActive() const
374 return active->getBoolValue();
377 bool FGRouteMgr::saveRoute(const SGPath& p)
383 return _plan->save(p);
386 bool FGRouteMgr::loadRoute(const SGPath& p)
388 FlightPlan* fp = new FlightPlan;
398 FlightPlan* FGRouteMgr::flightPlan() const
403 void FGRouteMgr::setFlightPlan(FlightPlan* plan)
411 active->setBoolValue(false);
415 _plan->setDelegate(this);
417 _flightplanChanged->fireValueChanged();
419 // fire all the callbacks!
423 currentWaypointChanged();
426 void FGRouteMgr::update( double dt )
429 return; // paused, nothing to do here
432 double gs = groundSpeed->getDoubleValue();
433 if (airborne->getBoolValue()) {
434 time_t now = time(NULL);
435 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
437 if (weightOnWheels->getBoolValue()) {
439 destination->setIntValue("touchdown-time", time(NULL));
440 airborne->setBoolValue(false);
442 } else { // not airborne
443 if (weightOnWheels->getBoolValue() || (gs < 40)) {
444 // either taking-off or rolling-out after touchdown
446 airborne->setBoolValue(true);
447 _takeoffTime = time(NULL); // start the clock
448 departure->setIntValue("takeoff-time", _takeoffTime);
452 if (!active->getBoolValue()) {
456 if (checkFinished()) {
460 // basic course/distance information
461 SGGeod currentPos = globals->get_aircraft_position();
463 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
470 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
472 // update wp0 / wp1 / wp-last
473 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
474 wp0->setDoubleValue("true-bearing-deg", courseDeg);
475 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
476 wp0->setDoubleValue("bearing-deg", courseDeg);
477 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
479 double totalPathDistanceNm = _plan->totalDistanceNm();
480 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
482 // total distance to go, is direct distance to wp0, plus the remaining
483 // path distance from wp0
484 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
486 wp0->setDoubleValue("distance-along-route-nm",
487 leg->distanceAlongRoute());
488 wp0->setDoubleValue("remaining-distance-nm",
489 totalPathDistanceNm - leg->distanceAlongRoute());
491 FlightPlan::Leg* nextLeg = _plan->nextLeg();
493 boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
495 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
496 wp1->setDoubleValue("true-bearing-deg", courseDeg);
497 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
498 wp1->setDoubleValue("bearing-deg", courseDeg);
499 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
500 wp1->setDoubleValue("distance-along-route-nm",
501 nextLeg->distanceAlongRoute());
502 wp1->setDoubleValue("remaining-distance-nm",
503 totalPathDistanceNm - nextLeg->distanceAlongRoute());
506 distanceToGo->setDoubleValue(totalDistanceRemaining);
507 wpn->setDoubleValue("dist", totalDistanceRemaining);
508 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
509 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
512 void FGRouteMgr::clearRoute()
519 Waypt* FGRouteMgr::currentWaypt() const
521 if (_plan && _plan->currentLeg()) {
522 return _plan->currentLeg()->waypoint();
528 int FGRouteMgr::currentIndex() const
534 return _plan->currentIndex();
537 Waypt* FGRouteMgr::wayptAtIndex(int index) const
540 FlightPlan::Leg* leg = _plan->legAtIndex(index);
542 return leg->waypoint();
549 int FGRouteMgr::numLegs() const
552 return _plan->numLegs();
558 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
560 double speed = fgGetDouble("/velocities/groundspeed-kt", 0.0);
562 aProp->setStringValue("--:--");
567 double eta = aDistance * SG_METER_TO_NM / speed;
568 if ( eta >= 100.0 ) {
569 eta = 99.999; // clamp
572 if ( eta < (1.0/6.0) ) {
573 eta *= 60.0; // within 10 minutes, bump up to min/secs
576 int major = (int)eta,
577 minor = (int)((eta - (int)eta) * 60.0);
578 snprintf( eta_str, 64, "%d:%02d", major, minor );
579 aProp->setStringValue( eta_str );
582 void FGRouteMgr::removeLegAtIndex(int aIndex)
588 _plan->deleteIndex(aIndex);
591 void FGRouteMgr::departureChanged()
593 _plan->clearWayptsWithFlag(WPT_DEPARTURE);
596 buildDeparture(enroute, wps);
597 _plan->insertWayptsAtIndex(wps, 0);
600 void FGRouteMgr::buildDeparture(WayptRef enroute, WayptVec& wps)
602 if (!_plan->departureAirport()) {
606 if (!_plan->departureRunway()) {
607 // valid airport, but no runway selected, so just the airport _plan itself
608 WayptRef w = new NavaidWaypoint(_plan->departureAirport(), _plan);
609 w->setFlag(WPT_DEPARTURE);
614 WayptRef rwyWaypt = new RunwayWaypt(_plan->departureRunway(), _plan);
615 rwyWaypt->setFlag(WPT_DEPARTURE);
616 wps.push_back(rwyWaypt);
622 _plan->sid()->route(_plan->departureRunway(), _plan->sidTransition(), wps);
625 void FGRouteMgr::arrivalChanged()
627 _plan->clearWayptsWithFlag(WPT_ARRIVAL);
628 _plan->clearWayptsWithFlag(WPT_APPROACH);
631 buildArrival(enroute, wps);
632 _plan->insertWayptsAtIndex(wps, -1);
635 void FGRouteMgr::buildArrival(WayptRef enroute, WayptVec& wps)
637 FGAirportRef apt = _plan->destinationAirport();
642 if (!_plan->destinationRunway()) {
643 WayptRef w = new NavaidWaypoint(apt.ptr(), _plan);
644 w->setFlag(WPT_ARRIVAL);
650 _plan->star()->route(_plan->destinationRunway(), _plan->starTransition(), wps);
653 if (_plan->approach()) {
654 _plan->approach()->route(wps.back(), wps);
656 WayptRef w = new RunwayWaypt(_plan->destinationRunway(), _plan);
657 w->setFlag(WPT_APPROACH);
662 void FGRouteMgr::waypointsChanged()
665 _edited->fireValueChanged();
669 // mirror internal route to the property system for inspection by other subsystems
670 void FGRouteMgr::update_mirror()
672 mirror->removeChildren("wp");
673 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
674 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
677 mirror->setIntValue("num", 0);
679 rmDlg->updateValues();
684 int num = _plan->numLegs();
686 for (int i = 0; i < num; i++) {
687 FlightPlan::Leg* leg = _plan->legAtIndex(i);
688 WayptRef wp = leg->waypoint();
689 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
691 const SGGeod& pos(wp->position());
692 prop->setStringValue("id", wp->ident().c_str());
693 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
694 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
696 // leg course+distance
698 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
699 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
700 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
702 if (leg->altitudeRestriction() != RESTRICT_NONE) {
703 double ft = leg->altitudeFt();
704 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
705 prop->setDoubleValue("altitude-ft", ft);
706 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
708 prop->setDoubleValue("altitude-m", -9999.9);
709 prop->setDoubleValue("altitude-ft", -9999.9);
712 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
713 prop->setDoubleValue("speed-mach", leg->speedMach());
714 } else if (leg->speedRestriction() != RESTRICT_NONE) {
715 prop->setDoubleValue("speed-kts", leg->speedKts());
718 if (wp->flag(WPT_ARRIVAL)) {
719 prop->setBoolValue("arrival", true);
722 if (wp->flag(WPT_DEPARTURE)) {
723 prop->setBoolValue("departure", true);
726 if (wp->flag(WPT_MISS)) {
727 prop->setBoolValue("missed-approach", true);
730 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
731 } // of waypoint iteration
733 // set number as listener attachment point
734 mirror->setIntValue("num", _plan->numLegs());
737 rmDlg->updateValues();
740 totalDistance->setDoubleValue(_plan->totalDistanceNm());
743 // command interface /autopilot/route-manager/input:
745 // @CLEAR ... clear route
746 // @POP ... remove first entry
747 // @DELETE3 ... delete 4th entry
748 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
749 // KSFO@900 ... append "KSFO@900"
751 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
753 const char *s = prop->getStringValue();
754 if (strlen(s) == 0) {
758 if (!strcmp(s, "@CLEAR"))
760 else if (!strcmp(s, "@ACTIVATE"))
762 else if (!strcmp(s, "@LOAD")) {
763 SGPath path(mgr->_pathNode->getStringValue());
764 mgr->loadRoute(path);
765 } else if (!strcmp(s, "@SAVE")) {
766 SGPath path(mgr->_pathNode->getStringValue());
767 mgr->saveRoute(path);
768 } else if (!strcmp(s, "@NEXT")) {
769 mgr->jumpToIndex(mgr->currentIndex() + 1);
770 } else if (!strcmp(s, "@PREVIOUS")) {
771 mgr->jumpToIndex(mgr->currentIndex() - 1);
772 } else if (!strncmp(s, "@JUMP", 5)) {
773 mgr->jumpToIndex(atoi(s + 5));
774 } else if (!strncmp(s, "@DELETE", 7))
775 mgr->removeLegAtIndex(atoi(s + 7));
776 else if (!strncmp(s, "@INSERT", 7)) {
778 int pos = strtol(s + 7, &r, 10);
784 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
785 } else if (!strcmp(s, "@POSINIT")) {
786 mgr->initAtPosition();
788 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
791 void FGRouteMgr::initAtPosition()
793 if (isRouteActive()) {
794 return; // don't mess with the active route
797 if (haveUserWaypoints()) {
798 // user has already defined, loaded or entered a route, again
799 // don't interfere with it
803 if (airborne->getBoolValue()) {
804 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
805 _plan->setDeparture((FGAirport*) NULL);
810 SGGeod pos = globals->get_aircraft_position();
811 if (!_plan->departureAirport()) {
812 _plan->setDeparture(FGAirport::findClosest(pos, 20.0));
813 if (!_plan->departureAirport()) {
814 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
819 std::string rwy = departure->getStringValue("runway");
822 r = _plan->departureAirport()->getRunwayByIdent(rwy);
824 r = _plan->departureAirport()->findBestRunwayForPos(pos);
831 _plan->setDeparture(r);
832 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
833 << _plan->departureAirport()->ident() << " on runway " << r->ident());
836 bool FGRouteMgr::haveUserWaypoints() const
842 bool FGRouteMgr::activate()
845 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
849 if (isRouteActive()) {
850 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
854 _plan->setCurrentIndex(0);
855 active->setBoolValue(true);
856 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
861 void FGRouteMgr::sequence()
863 if (!_plan || !active->getBoolValue()) {
864 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
868 if (checkFinished()) {
872 _plan->setCurrentIndex(_plan->currentIndex() + 1);
875 bool FGRouteMgr::checkFinished()
882 // done if we're stopped on the destination runway
883 if (_plan->currentLeg() &&
884 (_plan->currentLeg()->waypoint()->source() == _plan->destinationRunway()))
886 double gs = groundSpeed->getDoubleValue();
887 done = weightOnWheels->getBoolValue() && (gs < 25);
890 // also done if we hit the final waypoint
891 if (_plan->currentIndex() >= _plan->numLegs()) {
896 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
897 _finished->fireValueChanged();
898 active->setBoolValue(false);
904 void FGRouteMgr::jumpToIndex(int index)
910 _plan->setCurrentIndex(index);
913 void FGRouteMgr::currentWaypointChanged()
915 Waypt* cur = currentWaypt();
916 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
918 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
919 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
921 _currentWpt->fireValueChanged();
922 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
925 const char* FGRouteMgr::getDepartureICAO() const
927 if (!_plan || !_plan->departureAirport()) {
931 return _plan->departureAirport()->ident().c_str();
934 const char* FGRouteMgr::getDepartureName() const
936 if (!_plan || !_plan->departureAirport()) {
940 return _plan->departureAirport()->name().c_str();
943 const char* FGRouteMgr::getDepartureRunway() const
945 if (_plan && _plan->departureRunway()) {
946 return _plan->departureRunway()->ident().c_str();
952 void FGRouteMgr::setDepartureRunway(const char* aIdent)
954 FGAirport* apt = _plan->departureAirport();
955 if (!apt || (aIdent == NULL)) {
956 _plan->setDeparture(apt);
957 } else if (apt->hasRunwayWithIdent(aIdent)) {
958 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
962 void FGRouteMgr::setDepartureICAO(const char* aIdent)
964 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
965 _plan->setDeparture((FGAirport*) NULL);
967 _plan->setDeparture(FGAirport::findByIdent(aIdent));
971 const char* FGRouteMgr::getSID() const
973 if (_plan && _plan->sid()) {
974 return _plan->sid()->ident().c_str();
980 void FGRouteMgr::setSID(const char* aIdent)
982 FGAirport* apt = _plan->departureAirport();
983 if (!apt || (aIdent == NULL)) {
984 _plan->setSID((flightgear::SID*) NULL);
988 string ident(aIdent);
989 size_t hyphenPos = ident.find('-');
990 if (hyphenPos != string::npos) {
991 string sidIdent = ident.substr(0, hyphenPos);
992 string transIdent = ident.substr(hyphenPos + 1);
994 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
995 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
996 _plan->setSID(trans);
998 _plan->setSID(apt->findSIDWithIdent(aIdent));
1002 const char* FGRouteMgr::getDestinationICAO() const
1004 if (!_plan || !_plan->destinationAirport()) {
1008 return _plan->destinationAirport()->ident().c_str();
1011 const char* FGRouteMgr::getDestinationName() const
1013 if (!_plan || !_plan->destinationAirport()) {
1017 return _plan->destinationAirport()->name().c_str();
1020 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1022 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1023 _plan->setDestination((FGAirport*) NULL);
1025 _plan->setDestination(FGAirport::findByIdent(aIdent));
1029 const char* FGRouteMgr::getDestinationRunway() const
1031 if (_plan && _plan->destinationRunway()) {
1032 return _plan->destinationRunway()->ident().c_str();
1038 void FGRouteMgr::setDestinationRunway(const char* aIdent)
1040 FGAirport* apt = _plan->destinationAirport();
1041 if (!apt || (aIdent == NULL)) {
1042 _plan->setDestination(apt);
1043 } else if (apt->hasRunwayWithIdent(aIdent)) {
1044 _plan->setDestination(apt->getRunwayByIdent(aIdent));
1048 const char* FGRouteMgr::getApproach() const
1050 if (_plan && _plan->approach()) {
1051 return _plan->approach()->ident().c_str();
1057 void FGRouteMgr::setApproach(const char* aIdent)
1059 FGAirport* apt = _plan->destinationAirport();
1060 if (!apt || (aIdent == NULL)) {
1061 _plan->setApproach(NULL);
1063 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1067 const char* FGRouteMgr::getSTAR() const
1069 if (_plan && _plan->star()) {
1070 return _plan->star()->ident().c_str();
1076 void FGRouteMgr::setSTAR(const char* aIdent)
1078 FGAirport* apt = _plan->destinationAirport();
1079 if (!apt || (aIdent == NULL)) {
1080 _plan->setSTAR((STAR*) NULL);
1084 string ident(aIdent);
1085 size_t hyphenPos = ident.find('-');
1086 if (hyphenPos != string::npos) {
1087 string starIdent = ident.substr(0, hyphenPos);
1088 string transIdent = ident.substr(hyphenPos + 1);
1090 STAR* star = apt->findSTARWithIdent(starIdent);
1091 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1092 _plan->setSTAR(trans);
1094 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1098 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1100 return _plan->waypointFromString(target);
1103 double FGRouteMgr::getDepartureFieldElevation() const
1105 if (!_plan || !_plan->departureAirport()) {
1109 return _plan->departureAirport()->elevation();
1112 double FGRouteMgr::getDestinationFieldElevation() const
1114 if (!_plan || !_plan->destinationAirport()) {
1118 return _plan->destinationAirport()->elevation();
1121 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1123 if ((index < 0) || (index >= numWaypts())) {
1124 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1127 return mirror->getChild("wp", index);