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>
40 #include <boost/foreach.hpp>
42 #include <simgear/misc/strutils.hxx>
43 #include <simgear/structure/exception.hxx>
44 #include <simgear/structure/commands.hxx>
45 #include <simgear/misc/sg_path.hxx>
46 #include <simgear/sg_inlines.h>
48 #include "Main/fg_props.hxx"
49 #include "Navaids/positioned.hxx"
50 #include <Navaids/waypoint.hxx>
51 #include <Navaids/procedure.hxx>
52 #include "Airports/simple.hxx"
53 #include "Airports/runways.hxx"
54 #include <GUI/new_gui.hxx>
55 #include <GUI/dialog.hxx>
57 #define RM "/autopilot/route-manager/"
59 using namespace flightgear;
62 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
64 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
65 SGPath path(arg->getStringValue("path"));
66 return self->loadRoute(path);
69 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
71 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
72 SGPath path(arg->getStringValue("path"));
73 return self->saveRoute(path);
76 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
78 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
79 bool activate = arg->getBoolValue("activate", true);
89 static bool commandClearFlightPlan(const SGPropertyNode*)
91 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
96 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
98 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
99 int index = arg->getIntValue("index");
100 if ((index < 0) || (index >= self->numLegs())) {
104 self->jumpToIndex(index);
108 static bool commandInsertWaypt(const SGPropertyNode* arg)
110 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
111 int index = arg->getIntValue("index");
112 std::string ident(arg->getStringValue("id"));
113 int alt = arg->getIntValue("altitude-ft", -999);
114 int ias = arg->getIntValue("speed-knots", -999);
117 // lat/lon may be supplied to narrow down navaid search, or to specify
120 if (arg->hasChild("longitude-deg")) {
121 pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
122 arg->getDoubleValue("latitude-deg"));
125 if (arg->hasChild("navaid")) {
126 FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
128 if (arg->hasChild("navaid", 1)) {
129 // intersection of two radials
130 FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
132 SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
136 double r1 = arg->getDoubleValue("radial"),
137 r2 = arg->getDoubleValue("radial[1]");
140 bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
142 SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident()
143 << "," << p2->ident());
147 std::string name = p->ident() + "-" + p2->ident();
148 wp = new BasicWaypt(intersection, name, NULL);
149 } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
150 // offset radial from navaid
151 double radial = arg->getDoubleValue("radial");
152 double distanceNm = arg->getDoubleValue("offset-nm");
153 //radial += magvar->getDoubleValue(); // convert to true bearing
154 wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
156 wp = new NavaidWaypoint(p, NULL);
158 } else if (arg->hasChild("airport")) {
159 const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
161 SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
165 if (arg->hasChild("runway")) {
166 if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
167 SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
171 FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
172 wp = new RunwayWaypt(runway, NULL);
174 wp = new NavaidWaypoint((FGAirport*) apt, NULL);
176 } else if (arg->hasChild("text")) {
177 wp = self->waypointFromString(arg->getStringValue("text"));
178 } else if (!(pos == SGGeod())) {
179 // just a raw lat/lon
180 wp = new BasicWaypt(pos, ident, NULL);
182 return false; // failed to build waypoint
185 FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
187 leg->setAltitude(RESTRICT_AT, alt);
191 leg->setSpeed(RESTRICT_AT, ias);
197 static bool commandDeleteWaypt(const SGPropertyNode* arg)
199 FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
200 int index = arg->getIntValue("index");
201 self->removeLegAtIndex(index);
205 /////////////////////////////////////////////////////////////////////////////
207 FGRouteMgr::FGRouteMgr() :
209 input(fgGetNode( RM "input", true )),
210 mirror(fgGetNode( RM "route", true ))
212 listener = new InputListener(this);
213 input->setStringValue("");
214 input->addChangeListener(listener);
216 SGCommandMgr::instance()->addCommand("load-flightplan", commandLoadFlightPlan);
217 SGCommandMgr::instance()->addCommand("save-flightplan", commandSaveFlightPlan);
218 SGCommandMgr::instance()->addCommand("activate-flightplan", commandActivateFlightPlan);
219 SGCommandMgr::instance()->addCommand("clear-flightplan", commandClearFlightPlan);
220 SGCommandMgr::instance()->addCommand("set-active-waypt", commandSetActiveWaypt);
221 SGCommandMgr::instance()->addCommand("insert-waypt", commandInsertWaypt);
222 SGCommandMgr::instance()->addCommand("delete-waypt", commandDeleteWaypt);
226 FGRouteMgr::~FGRouteMgr()
228 input->removeChangeListener(listener);
233 void FGRouteMgr::init() {
234 SGPropertyNode_ptr rm(fgGetNode(RM));
236 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
238 departure = fgGetNode(RM "departure", true);
239 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
240 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
241 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
242 &FGRouteMgr::getDepartureRunway,
243 &FGRouteMgr::setDepartureRunway));
244 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
246 &FGRouteMgr::setSID));
248 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
249 &FGRouteMgr::getDepartureName, NULL));
250 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
251 &FGRouteMgr::getDestinationFieldElevation, NULL));
252 departure->getChild("etd", 0, true);
253 departure->getChild("takeoff-time", 0, true);
255 destination = fgGetNode(RM "destination", true);
256 destination->getChild("airport", 0, true);
258 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
259 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
260 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
261 &FGRouteMgr::getDestinationRunway,
262 &FGRouteMgr::setDestinationRunway));
263 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
264 &FGRouteMgr::getSTAR,
265 &FGRouteMgr::setSTAR));
266 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
267 &FGRouteMgr::getApproach,
268 &FGRouteMgr::setApproach));
270 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
271 &FGRouteMgr::getDestinationName, NULL));
272 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
273 &FGRouteMgr::getDestinationFieldElevation, NULL));
275 destination->getChild("eta", 0, true);
276 destination->getChild("touchdown-time", 0, true);
278 alternate = fgGetNode(RM "alternate", true);
279 alternate->getChild("airport", 0, true);
280 alternate->getChild("runway", 0, true);
282 cruise = fgGetNode(RM "cruise", true);
283 cruise->getChild("altitude-ft", 0, true);
284 cruise->setDoubleValue("altitude-ft", 10000.0);
285 cruise->getChild("flight-level", 0, true);
286 cruise->getChild("speed-kts", 0, true);
287 cruise->setDoubleValue("speed-kts", 160.0);
289 totalDistance = fgGetNode(RM "total-distance", true);
290 totalDistance->setDoubleValue(0.0);
291 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
292 distanceToGo->setDoubleValue(0.0);
294 ete = fgGetNode(RM "ete", true);
295 ete->setDoubleValue(0.0);
297 elapsedFlightTime = fgGetNode(RM "flight-time", true);
298 elapsedFlightTime->setDoubleValue(0.0);
300 active = fgGetNode(RM "active", true);
301 active->setBoolValue(false);
303 airborne = fgGetNode(RM "airborne", true);
304 airborne->setBoolValue(false);
306 _edited = fgGetNode(RM "signals/edited", true);
307 _finished = fgGetNode(RM "signals/finished", true);
308 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
310 _currentWpt = fgGetNode(RM "current-wp", true);
311 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
312 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
314 // temporary distance / eta calculations, for backward-compatability
315 wp0 = fgGetNode(RM "wp", 0, true);
316 wp0->getChild("id", 0, true);
317 wp0->getChild("dist", 0, true);
318 wp0->getChild("eta", 0, true);
319 wp0->getChild("bearing-deg", 0, true);
321 wp1 = fgGetNode(RM "wp", 1, true);
322 wp1->getChild("id", 0, true);
323 wp1->getChild("dist", 0, true);
324 wp1->getChild("eta", 0, true);
326 wpn = fgGetNode(RM "wp-last", 0, true);
327 wpn->getChild("dist", 0, true);
328 wpn->getChild("eta", 0, true);
330 _pathNode = fgGetNode(RM "file-path", 0, true);
334 void FGRouteMgr::postinit()
336 setFlightPlan(new FlightPlan());
338 SGPath path(_pathNode->getStringValue());
339 if (!path.isNull()) {
340 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
344 // this code only matters for the --wp option now - perhaps the option
345 // should be deprecated in favour of an explicit flight-plan file?
346 // then the global initial waypoint list could die.
347 string_list *waypoints = globals->get_initial_waypoints();
349 string_list::iterator it;
350 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
351 WayptRef w = waypointFromString(*it);
353 _plan->insertWayptAtIndex(w, -1);
357 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
361 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
362 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
364 // check airbone flag agrees with presets
367 void FGRouteMgr::bind() { }
368 void FGRouteMgr::unbind() { }
370 bool FGRouteMgr::isRouteActive() const
372 return active->getBoolValue();
375 bool FGRouteMgr::saveRoute(const SGPath& p)
381 return _plan->save(p);
384 bool FGRouteMgr::loadRoute(const SGPath& p)
386 FlightPlan* fp = new FlightPlan;
396 FlightPlan* FGRouteMgr::flightPlan() const
401 void FGRouteMgr::setFlightPlan(FlightPlan* plan)
408 _plan->removeDelegate(this);
410 active->setBoolValue(false);
414 _plan->addDelegate(this);
416 _flightplanChanged->fireValueChanged();
418 // fire all the callbacks!
422 currentWaypointChanged();
425 void FGRouteMgr::update( double dt )
428 return; // paused, nothing to do here
431 double gs = groundSpeed->getDoubleValue();
432 if (airborne->getBoolValue()) {
433 time_t now = time(NULL);
434 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
436 if (weightOnWheels->getBoolValue()) {
438 destination->setIntValue("touchdown-time", time(NULL));
439 airborne->setBoolValue(false);
441 } else { // not airborne
442 if (weightOnWheels->getBoolValue() || (gs < 40)) {
443 // either taking-off or rolling-out after touchdown
445 airborne->setBoolValue(true);
446 _takeoffTime = time(NULL); // start the clock
447 departure->setIntValue("takeoff-time", _takeoffTime);
451 if (!active->getBoolValue()) {
455 if (checkFinished()) {
459 // basic course/distance information
460 SGGeod currentPos = globals->get_aircraft_position();
462 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
469 boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
471 // update wp0 / wp1 / wp-last
472 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
473 wp0->setDoubleValue("true-bearing-deg", courseDeg);
474 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
475 wp0->setDoubleValue("bearing-deg", courseDeg);
476 setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
478 double totalPathDistanceNm = _plan->totalDistanceNm();
479 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
481 // total distance to go, is direct distance to wp0, plus the remaining
482 // path distance from wp0
483 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
485 wp0->setDoubleValue("distance-along-route-nm",
486 leg->distanceAlongRoute());
487 wp0->setDoubleValue("remaining-distance-nm",
488 totalPathDistanceNm - leg->distanceAlongRoute());
490 FlightPlan::Leg* nextLeg = _plan->nextLeg();
492 boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
494 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
495 wp1->setDoubleValue("true-bearing-deg", courseDeg);
496 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
497 wp1->setDoubleValue("bearing-deg", courseDeg);
498 setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);
499 wp1->setDoubleValue("distance-along-route-nm",
500 nextLeg->distanceAlongRoute());
501 wp1->setDoubleValue("remaining-distance-nm",
502 totalPathDistanceNm - nextLeg->distanceAlongRoute());
505 distanceToGo->setDoubleValue(totalDistanceRemaining);
506 wpn->setDoubleValue("dist", totalDistanceRemaining);
507 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
508 setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
511 void FGRouteMgr::clearRoute()
518 Waypt* FGRouteMgr::currentWaypt() const
520 if (_plan && _plan->currentLeg()) {
521 return _plan->currentLeg()->waypoint();
527 int FGRouteMgr::currentIndex() const
533 return _plan->currentIndex();
536 Waypt* FGRouteMgr::wayptAtIndex(int index) const
539 throw sg_range_exception("wayptAtindex: no flightplan");
542 return _plan->legAtIndex(index)->waypoint();
545 int FGRouteMgr::numLegs() const
548 return _plan->numLegs();
554 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
556 double speed = groundSpeed->getDoubleValue();
558 aProp->setStringValue("--:--");
563 double eta = aDistance * SG_METER_TO_NM / speed;
564 if ( eta >= 100.0 ) {
565 eta = 99.999; // clamp
568 if ( eta < (1.0/6.0) ) {
569 eta *= 60.0; // within 10 minutes, bump up to min/secs
572 int major = (int)eta,
573 minor = (int)((eta - (int)eta) * 60.0);
574 snprintf( eta_str, 64, "%d:%02d", major, minor );
575 aProp->setStringValue( eta_str );
578 void FGRouteMgr::removeLegAtIndex(int aIndex)
584 _plan->deleteIndex(aIndex);
587 void FGRouteMgr::waypointsChanged()
590 _edited->fireValueChanged();
592 // removing waypoints, deactivate if we hit the end.
593 if (currentIndex() >= numLegs()) {
598 // mirror internal route to the property system for inspection by other subsystems
599 void FGRouteMgr::update_mirror()
601 mirror->removeChildren("wp");
602 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
603 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
606 mirror->setIntValue("num", 0);
608 rmDlg->updateValues();
613 int num = _plan->numLegs();
615 for (int i = 0; i < num; i++) {
616 FlightPlan::Leg* leg = _plan->legAtIndex(i);
617 WayptRef wp = leg->waypoint();
618 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
620 const SGGeod& pos(wp->position());
621 prop->setStringValue("id", wp->ident().c_str());
622 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
623 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
625 // leg course+distance
627 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
628 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
629 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
631 if (leg->altitudeRestriction() != RESTRICT_NONE) {
632 double ft = leg->altitudeFt();
633 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
634 prop->setDoubleValue("altitude-ft", ft);
635 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
637 prop->setDoubleValue("altitude-m", -9999.9);
638 prop->setDoubleValue("altitude-ft", -9999.9);
641 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
642 prop->setDoubleValue("speed-mach", leg->speedMach());
643 } else if (leg->speedRestriction() != RESTRICT_NONE) {
644 prop->setDoubleValue("speed-kts", leg->speedKts());
647 if (wp->flag(WPT_ARRIVAL)) {
648 prop->setBoolValue("arrival", true);
651 if (wp->flag(WPT_DEPARTURE)) {
652 prop->setBoolValue("departure", true);
655 if (wp->flag(WPT_MISS)) {
656 prop->setBoolValue("missed-approach", true);
659 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
660 } // of waypoint iteration
662 // set number as listener attachment point
663 mirror->setIntValue("num", _plan->numLegs());
666 rmDlg->updateValues();
669 totalDistance->setDoubleValue(_plan->totalDistanceNm());
672 // command interface /autopilot/route-manager/input:
674 // @CLEAR ... clear route
675 // @POP ... remove first entry
676 // @DELETE3 ... delete 4th entry
677 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
678 // KSFO@900 ... append "KSFO@900"
680 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
682 const char *s = prop->getStringValue();
683 if (strlen(s) == 0) {
687 if (!strcmp(s, "@CLEAR"))
689 else if (!strcmp(s, "@ACTIVATE"))
691 else if (!strcmp(s, "@LOAD")) {
692 SGPath path(mgr->_pathNode->getStringValue());
693 mgr->loadRoute(path);
694 } else if (!strcmp(s, "@SAVE")) {
695 SGPath path(mgr->_pathNode->getStringValue());
696 mgr->saveRoute(path);
697 } else if (!strcmp(s, "@NEXT")) {
698 mgr->jumpToIndex(mgr->currentIndex() + 1);
699 } else if (!strcmp(s, "@PREVIOUS")) {
700 mgr->jumpToIndex(mgr->currentIndex() - 1);
701 } else if (!strncmp(s, "@JUMP", 5)) {
702 mgr->jumpToIndex(atoi(s + 5));
703 } else if (!strncmp(s, "@DELETE", 7))
704 mgr->removeLegAtIndex(atoi(s + 7));
705 else if (!strncmp(s, "@INSERT", 7)) {
707 int pos = strtol(s + 7, &r, 10);
713 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
714 } else if (!strcmp(s, "@POSINIT")) {
715 mgr->initAtPosition();
717 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
720 void FGRouteMgr::initAtPosition()
722 if (isRouteActive()) {
723 return; // don't mess with the active route
726 if (haveUserWaypoints()) {
727 // user has already defined, loaded or entered a route, again
728 // don't interfere with it
732 if (airborne->getBoolValue()) {
733 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: airborne, clearing departure info");
734 _plan->setDeparture((FGAirport*) NULL);
739 SGGeod pos = globals->get_aircraft_position();
740 if (!_plan->departureAirport()) {
741 _plan->setDeparture(FGAirport::findClosest(pos, 20.0));
742 if (!_plan->departureAirport()) {
743 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: couldn't find an airport within 20nm");
748 std::string rwy = departure->getStringValue("runway");
751 r = _plan->departureAirport()->getRunwayByIdent(rwy);
753 r = _plan->departureAirport()->findBestRunwayForPos(pos);
760 _plan->setDeparture(r);
761 SG_LOG(SG_AUTOPILOT, SG_INFO, "initAtPosition: starting at "
762 << _plan->departureAirport()->ident() << " on runway " << r->ident());
765 bool FGRouteMgr::haveUserWaypoints() const
771 bool FGRouteMgr::activate()
774 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
778 if (isRouteActive()) {
779 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
783 _plan->setCurrentIndex(0);
784 active->setBoolValue(true);
785 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
789 void FGRouteMgr::deactivate()
791 if (!isRouteActive()) {
795 SG_LOG(SG_AUTOPILOT, SG_INFO, "deactivating flight plan");
796 active->setBoolValue(false);
799 void FGRouteMgr::sequence()
801 if (!_plan || !active->getBoolValue()) {
802 SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
806 int nextIndex = _plan->currentIndex() + 1;
807 if (nextIndex >= _plan->numLegs()) {
808 SG_LOG(SG_AUTOPILOT, SG_INFO, "sequenced on final leg, deactivating route");
813 _plan->setCurrentIndex(nextIndex);
816 void FGRouteMgr::endOfRoute()
818 SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
819 _finished->fireValueChanged();
820 active->setBoolValue(false);
823 bool FGRouteMgr::checkFinished()
830 // done if we're stopped on the destination runway
831 if (_plan->currentLeg() &&
832 (_plan->currentLeg()->waypoint()->source() == _plan->destinationRunway()))
834 double gs = groundSpeed->getDoubleValue();
835 done = weightOnWheels->getBoolValue() && (gs < 25);
839 SG_LOG(SG_AUTOPILOT, SG_INFO, "checkFinished: on the ground on destination runway, we're done");
845 void FGRouteMgr::jumpToIndex(int index)
851 _plan->setCurrentIndex(index);
854 void FGRouteMgr::currentWaypointChanged()
856 Waypt* cur = currentWaypt();
857 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
859 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
860 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
862 _currentWpt->fireValueChanged();
863 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
866 const char* FGRouteMgr::getDepartureICAO() const
868 if (!_plan || !_plan->departureAirport()) {
872 return _plan->departureAirport()->ident().c_str();
875 const char* FGRouteMgr::getDepartureName() const
877 if (!_plan || !_plan->departureAirport()) {
881 return _plan->departureAirport()->name().c_str();
884 const char* FGRouteMgr::getDepartureRunway() const
886 if (_plan && _plan->departureRunway()) {
887 return _plan->departureRunway()->ident().c_str();
893 void FGRouteMgr::setDepartureRunway(const char* aIdent)
895 FGAirport* apt = _plan->departureAirport();
896 if (!apt || (aIdent == NULL)) {
897 _plan->setDeparture(apt);
898 } else if (apt->hasRunwayWithIdent(aIdent)) {
899 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
903 void FGRouteMgr::setDepartureICAO(const char* aIdent)
905 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
906 _plan->setDeparture((FGAirport*) NULL);
908 _plan->setDeparture(FGAirport::findByIdent(aIdent));
912 const char* FGRouteMgr::getSID() const
914 if (_plan && _plan->sid()) {
915 return _plan->sid()->ident().c_str();
921 static double headingDiffDeg(double a, double b)
923 double rawDiff = b - a;
924 SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
928 flightgear::SID* createDefaultSID(FGRunway* aRunway, double enrouteCourse)
934 double runwayElevFt = aRunway->end().getElevationFt();
936 std::ostringstream ss;
937 ss << aRunway->ident() << "-3";
939 SGGeod p = aRunway->pointOnCenterline(aRunway->lengthM() + (3.0 * SG_NM_TO_METER));
940 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
941 w->setAltitude(runwayElevFt + 3000.0, RESTRICT_AT);
945 ss << aRunway->ident() << "-6";
946 p = aRunway->pointOnCenterline(aRunway->lengthM() + (6.0 * SG_NM_TO_METER));
947 w = new BasicWaypt(p, ss.str(), NULL);
948 w->setAltitude(runwayElevFt + 6000.0, RESTRICT_AT);
951 if (enrouteCourse >= 0.0) {
952 // valid enroute course
954 double course = aRunway->headingDeg();
956 while (fabs(diff = headingDiffDeg(course, enrouteCourse)) > 45.0) {
957 // turn in the sign of the heading change 45 degrees
958 course += copysign(45.0, diff);
960 ss << "DEP-" << index++;
961 SGGeod pos = wpts.back()->position();
962 pos = SGGeodesy::direct(pos, course, 3.0 * SG_NM_TO_METER);
963 w = new BasicWaypt(pos, ss.str(), NULL);
967 // no enroute course, just keep runway heading
969 ss << aRunway->ident() << "-9";
970 p = aRunway->pointOnCenterline(aRunway->lengthM() + (9.0 * SG_NM_TO_METER));
971 w = new BasicWaypt(p, ss.str(), NULL);
972 w->setAltitude(runwayElevFt + 9000.0, RESTRICT_AT);
976 BOOST_FOREACH(Waypt* w, wpts) {
977 w->setFlag(WPT_DEPARTURE);
978 w->setFlag(WPT_GENERATED);
981 return flightgear::SID::createTempSID("DEFAULT", aRunway, wpts);
984 void FGRouteMgr::setSID(const char* aIdent)
986 FGAirport* apt = _plan->departureAirport();
987 if (!apt || (aIdent == NULL)) {
988 _plan->setSID((flightgear::SID*) NULL);
992 if (!strcmp(aIdent, "DEFAULT")) {
993 double enrouteCourse = -1.0;
994 if (_plan->destinationAirport()) {
995 enrouteCourse = SGGeodesy::courseDeg(apt->geod(), _plan->destinationAirport()->geod());
998 _plan->setSID(createDefaultSID(_plan->departureRunway(), enrouteCourse));
1002 string ident(aIdent);
1003 size_t hyphenPos = ident.find('-');
1004 if (hyphenPos != string::npos) {
1005 string sidIdent = ident.substr(0, hyphenPos);
1006 string transIdent = ident.substr(hyphenPos + 1);
1008 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
1009 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
1010 _plan->setSID(trans);
1012 _plan->setSID(apt->findSIDWithIdent(aIdent));
1016 const char* FGRouteMgr::getDestinationICAO() const
1018 if (!_plan || !_plan->destinationAirport()) {
1022 return _plan->destinationAirport()->ident().c_str();
1025 const char* FGRouteMgr::getDestinationName() const
1027 if (!_plan || !_plan->destinationAirport()) {
1031 return _plan->destinationAirport()->name().c_str();
1034 void FGRouteMgr::setDestinationICAO(const char* aIdent)
1036 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
1037 _plan->setDestination((FGAirport*) NULL);
1039 _plan->setDestination(FGAirport::findByIdent(aIdent));
1043 const char* FGRouteMgr::getDestinationRunway() const
1045 if (_plan && _plan->destinationRunway()) {
1046 return _plan->destinationRunway()->ident().c_str();
1052 void FGRouteMgr::setDestinationRunway(const char* aIdent)
1054 FGAirport* apt = _plan->destinationAirport();
1055 if (!apt || (aIdent == NULL)) {
1056 _plan->setDestination(apt);
1057 } else if (apt->hasRunwayWithIdent(aIdent)) {
1058 _plan->setDestination(apt->getRunwayByIdent(aIdent));
1062 const char* FGRouteMgr::getApproach() const
1064 if (_plan && _plan->approach()) {
1065 return _plan->approach()->ident().c_str();
1071 flightgear::Approach* createDefaultApproach(FGRunway* aRunway, double aEnrouteCourse)
1077 double thresholdElevFt = aRunway->threshold().getElevationFt();
1078 const double approachHeightFt = 2000.0;
1079 double glideslopeDistanceM = (approachHeightFt * SG_FEET_TO_METER) /
1080 tan(3.0 * SG_DEGREES_TO_RADIANS);
1082 std::ostringstream ss;
1083 ss << aRunway->ident() << "-12";
1085 SGGeod p = aRunway->pointOnCenterline(-12.0 * SG_NM_TO_METER);
1086 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
1087 w->setAltitude(thresholdElevFt + 4000, RESTRICT_AT);
1090 // work back form the first point on the centerline
1092 if (aEnrouteCourse >= 0.0) {
1093 // valid enroute course
1095 double course = aRunway->headingDeg();
1097 while (fabs(diff = headingDiffDeg(aEnrouteCourse, course)) > 45.0) {
1098 // turn in the sign of the heading change 45 degrees
1099 course -= copysign(45.0, diff);
1101 ss << "APP-" << index++;
1102 SGGeod pos = wpts.front()->position();
1103 pos = SGGeodesy::direct(pos, course + 180.0, 3.0 * SG_NM_TO_METER);
1104 w = new BasicWaypt(pos, ss.str(), NULL);
1105 wpts.insert(wpts.begin(), w);
1109 p = aRunway->pointOnCenterline(-8.0 * SG_NM_TO_METER);
1111 ss << aRunway->ident() << "-8";
1112 w = new BasicWaypt(p, ss.str(), NULL);
1113 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1116 p = aRunway->pointOnCenterline(-glideslopeDistanceM);
1118 ss << aRunway->ident() << "-GS";
1119 w = new BasicWaypt(p, ss.str(), NULL);
1120 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1123 BOOST_FOREACH(Waypt* w, wpts) {
1124 w->setFlag(WPT_APPROACH);
1125 w->setFlag(WPT_GENERATED);
1128 return Approach::createTempApproach("DEFAULT", aRunway, wpts);
1131 void FGRouteMgr::setApproach(const char* aIdent)
1133 FGAirport* apt = _plan->destinationAirport();
1134 if (!strcmp(aIdent, "DEFAULT")) {
1135 double enrouteCourse = -1.0;
1136 if (_plan->departureAirport()) {
1137 enrouteCourse = SGGeodesy::courseDeg(_plan->departureAirport()->geod(), apt->geod());
1140 _plan->setApproach(createDefaultApproach(_plan->destinationRunway(), enrouteCourse));
1144 if (!apt || (aIdent == NULL)) {
1145 _plan->setApproach(NULL);
1147 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1151 const char* FGRouteMgr::getSTAR() const
1153 if (_plan && _plan->star()) {
1154 return _plan->star()->ident().c_str();
1160 void FGRouteMgr::setSTAR(const char* aIdent)
1162 FGAirport* apt = _plan->destinationAirport();
1163 if (!apt || (aIdent == NULL)) {
1164 _plan->setSTAR((STAR*) NULL);
1168 string ident(aIdent);
1169 size_t hyphenPos = ident.find('-');
1170 if (hyphenPos != string::npos) {
1171 string starIdent = ident.substr(0, hyphenPos);
1172 string transIdent = ident.substr(hyphenPos + 1);
1174 STAR* star = apt->findSTARWithIdent(starIdent);
1175 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1176 _plan->setSTAR(trans);
1178 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1182 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1184 return _plan->waypointFromString(target);
1187 double FGRouteMgr::getDepartureFieldElevation() const
1189 if (!_plan || !_plan->departureAirport()) {
1193 return _plan->departureAirport()->elevation();
1196 double FGRouteMgr::getDestinationFieldElevation() const
1198 if (!_plan || !_plan->destinationAirport()) {
1202 return _plan->destinationAirport()->elevation();
1205 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1207 if ((index < 0) || (index >= numWaypts())) {
1208 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1211 return mirror->getChild("wp", index);