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.
36 #include <simgear/compiler.h>
38 #include "route_mgr.hxx"
40 #include <boost/algorithm/string/case_conv.hpp>
41 #include <boost/tuple/tuple.hpp>
42 #include <boost/foreach.hpp>
44 #include <simgear/misc/strutils.hxx>
45 #include <simgear/structure/exception.hxx>
46 #include <simgear/structure/commands.hxx>
47 #include <simgear/misc/sg_path.hxx>
48 #include <simgear/sg_inlines.h>
50 #include "Main/fg_props.hxx"
51 #include "Navaids/positioned.hxx"
52 #include <Navaids/waypoint.hxx>
53 #include <Navaids/procedure.hxx>
54 #include <Navaids/routePath.hxx>
56 #include "Airports/airport.hxx"
57 #include "Airports/runways.hxx"
58 #include <GUI/new_gui.hxx>
59 #include <GUI/dialog.hxx>
61 #define RM "/autopilot/route-manager/"
63 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* cmdMgr = globals->get_commands();
221 cmdMgr->addCommand("define-user-waypoint", this, &FGRouteMgr::commandDefineUserWaypoint);
222 cmdMgr->addCommand("delete-user-waypoint", this, &FGRouteMgr::commandDeleteUserWaypoint);
224 cmdMgr->addCommand("load-flightplan", commandLoadFlightPlan);
225 cmdMgr->addCommand("save-flightplan", commandSaveFlightPlan);
226 cmdMgr->addCommand("activate-flightplan", commandActivateFlightPlan);
227 cmdMgr->addCommand("clear-flightplan", commandClearFlightPlan);
228 cmdMgr->addCommand("set-active-waypt", commandSetActiveWaypt);
229 cmdMgr->addCommand("insert-waypt", commandInsertWaypt);
230 cmdMgr->addCommand("delete-waypt", commandDeleteWaypt);
234 FGRouteMgr::~FGRouteMgr()
236 input->removeChangeListener(listener);
240 _plan->removeDelegate(this);
243 SGCommandMgr* cmdMgr = globals->get_commands();
244 cmdMgr->removeCommand("define-user-waypoint");
245 cmdMgr->removeCommand("delete-user-waypoint");
246 cmdMgr->removeCommand("load-flightplan");
247 cmdMgr->removeCommand("save-flightplan");
248 cmdMgr->removeCommand("activate-flightplan");
249 cmdMgr->removeCommand("clear-flightplan");
250 cmdMgr->removeCommand("set-active-waypt");
251 cmdMgr->removeCommand("insert-waypt");
252 cmdMgr->removeCommand("delete-waypt");
256 void FGRouteMgr::init() {
257 SGPropertyNode_ptr rm(fgGetNode(RM));
259 magvar = fgGetNode("/environment/magnetic-variation-deg", true);
261 departure = fgGetNode(RM "departure", true);
262 departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
263 &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
264 departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
265 &FGRouteMgr::getDepartureRunway,
266 &FGRouteMgr::setDepartureRunway));
267 departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this,
269 &FGRouteMgr::setSID));
271 departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
272 &FGRouteMgr::getDepartureName, NULL));
273 departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
274 &FGRouteMgr::getDepartureFieldElevation, NULL));
275 departure->getChild("etd", 0, true);
276 departure->getChild("takeoff-time", 0, true);
278 destination = fgGetNode(RM "destination", true);
279 destination->getChild("airport", 0, true);
281 destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this,
282 &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
283 destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this,
284 &FGRouteMgr::getDestinationRunway,
285 &FGRouteMgr::setDestinationRunway));
286 destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this,
287 &FGRouteMgr::getSTAR,
288 &FGRouteMgr::setSTAR));
289 destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this,
290 &FGRouteMgr::getApproach,
291 &FGRouteMgr::setApproach));
293 destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this,
294 &FGRouteMgr::getDestinationName, NULL));
295 destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this,
296 &FGRouteMgr::getDestinationFieldElevation, NULL));
298 destination->getChild("eta", 0, true);
299 destination->getChild("eta-seconds", 0, true);
300 destination->getChild("touchdown-time", 0, true);
302 alternate = fgGetNode(RM "alternate", true);
303 alternate->getChild("airport", 0, true);
304 alternate->getChild("runway", 0, true);
306 cruise = fgGetNode(RM "cruise", true);
307 cruise->getChild("altitude-ft", 0, true);
308 cruise->setDoubleValue("altitude-ft", 10000.0);
309 cruise->getChild("flight-level", 0, true);
310 cruise->getChild("speed-kts", 0, true);
311 cruise->setDoubleValue("speed-kts", 160.0);
313 totalDistance = fgGetNode(RM "total-distance", true);
314 totalDistance->setDoubleValue(0.0);
315 distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
316 distanceToGo->setDoubleValue(0.0);
318 ete = fgGetNode(RM "ete", true);
319 ete->setDoubleValue(0.0);
321 elapsedFlightTime = fgGetNode(RM "flight-time", true);
322 elapsedFlightTime->setDoubleValue(0.0);
324 active = fgGetNode(RM "active", true);
325 active->setBoolValue(false);
327 airborne = fgGetNode(RM "airborne", true);
328 airborne->setBoolValue(false);
330 _edited = fgGetNode(RM "signals/edited", true);
331 _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
333 _currentWpt = fgGetNode(RM "current-wp", true);
334 _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
335 (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
337 wp0 = fgGetNode(RM "wp", 0, true);
338 wp0->getChild("id", 0, true);
339 wp0->getChild("dist", 0, true);
340 wp0->getChild("eta", 0, true);
341 wp0->getChild("eta-seconds", 0, true);
342 wp0->getChild("bearing-deg", 0, true);
344 wp1 = fgGetNode(RM "wp", 1, true);
345 wp1->getChild("id", 0, true);
346 wp1->getChild("dist", 0, true);
347 wp1->getChild("eta", 0, true);
348 wp1->getChild("eta-seconds", 0, true);
350 wpn = fgGetNode(RM "wp-last", 0, true);
351 wpn->getChild("dist", 0, true);
352 wpn->getChild("eta", 0, true);
353 wpn->getChild("eta-seconds", 0, true);
355 _pathNode = fgGetNode(RM "file-path", 0, true);
359 void FGRouteMgr::postinit()
361 setFlightPlan(new FlightPlan());
363 SGPath path(_pathNode->getStringValue());
364 if (!path.isNull()) {
365 SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
369 // this code only matters for the --wp option now - perhaps the option
370 // should be deprecated in favour of an explicit flight-plan file?
371 // then the global initial waypoint list could die.
372 string_list *waypoints = globals->get_initial_waypoints();
374 string_list::iterator it;
375 for (it = waypoints->begin(); it != waypoints->end(); ++it) {
376 WayptRef w = waypointFromString(*it);
378 _plan->insertWayptAtIndex(w, -1);
382 SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
386 weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
387 groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
389 // check airbone flag agrees with presets
392 void FGRouteMgr::bind() { }
393 void FGRouteMgr::unbind() { }
395 bool FGRouteMgr::isRouteActive() const
397 return active->getBoolValue();
400 bool FGRouteMgr::saveRoute(const SGPath& p)
406 return _plan->save(p);
409 bool FGRouteMgr::loadRoute(const SGPath& p)
411 FlightPlan* fp = new FlightPlan;
421 FlightPlanRef FGRouteMgr::flightPlan() const
426 void FGRouteMgr::setFlightPlan(const FlightPlanRef& plan)
433 _plan->removeDelegate(this);
434 active->setBoolValue(false);
438 _plan->addDelegate(this);
440 _flightplanChanged->fireValueChanged();
442 // fire all the callbacks!
446 currentWaypointChanged();
449 void FGRouteMgr::update( double dt )
452 return; // paused, nothing to do here
455 double gs = groundSpeed->getDoubleValue();
456 if (airborne->getBoolValue()) {
457 time_t now = time(NULL);
458 elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
460 if (weightOnWheels->getBoolValue()) {
462 destination->setIntValue("touchdown-time", time(NULL));
463 airborne->setBoolValue(false);
465 } else { // not airborne
466 if (weightOnWheels->getBoolValue() || (gs < 40)) {
467 // either taking-off or rolling-out after touchdown
469 airborne->setBoolValue(true);
470 _takeoffTime = time(NULL); // start the clock
471 departure->setIntValue("takeoff-time", _takeoffTime);
475 if (!active->getBoolValue()) {
479 // basic course/distance information
480 SGGeod currentPos = globals->get_aircraft_position();
482 FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
487 // use RoutePath to compute location of active WP
488 RoutePath path(_plan);
489 SGGeod wpPos = path.positionForIndex(_plan->currentIndex());
490 double courseDeg, az2, distanceM;
491 SGGeodesy::inverse(currentPos, wpPos, courseDeg, az2, distanceM);
493 // update wp0 / wp1 / wp-last
494 wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
495 wp0->setDoubleValue("true-bearing-deg", courseDeg);
496 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
497 wp0->setDoubleValue("bearing-deg", courseDeg);
498 setETAPropertyFromDistance(wp0, distanceM);
500 double totalPathDistanceNm = _plan->totalDistanceNm();
501 double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
503 // total distance to go, is direct distance to wp0, plus the remaining
504 // path distance from wp0
505 totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
507 wp0->setDoubleValue("distance-along-route-nm",
508 leg->distanceAlongRoute());
509 wp0->setDoubleValue("remaining-distance-nm",
510 totalPathDistanceNm - leg->distanceAlongRoute());
512 FlightPlan::Leg* nextLeg = _plan->nextLeg();
514 wpPos = path.positionForIndex(_plan->currentIndex() + 1);
515 SGGeodesy::inverse(currentPos, wpPos, courseDeg, az2, distanceM);
517 wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
518 wp1->setDoubleValue("true-bearing-deg", courseDeg);
519 courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
520 wp1->setDoubleValue("bearing-deg", courseDeg);
521 setETAPropertyFromDistance(wp1, distanceM);
522 wp1->setDoubleValue("distance-along-route-nm",
523 nextLeg->distanceAlongRoute());
524 wp1->setDoubleValue("remaining-distance-nm",
525 totalPathDistanceNm - nextLeg->distanceAlongRoute());
528 distanceToGo->setDoubleValue(totalDistanceRemaining);
529 wpn->setDoubleValue("dist", totalDistanceRemaining);
530 ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
531 setETAPropertyFromDistance(wpn, totalDistanceRemaining);
534 void FGRouteMgr::clearRoute()
541 Waypt* FGRouteMgr::currentWaypt() const
543 if (_plan && _plan->currentLeg()) {
544 return _plan->currentLeg()->waypoint();
550 int FGRouteMgr::currentIndex() const
556 return _plan->currentIndex();
559 Waypt* FGRouteMgr::wayptAtIndex(int index) const
562 throw sg_range_exception("wayptAtindex: no flightplan");
565 return _plan->legAtIndex(index)->waypoint();
568 int FGRouteMgr::numLegs() const
571 return _plan->numLegs();
577 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
579 double speed = groundSpeed->getDoubleValue();
581 aProp->setStringValue("--:--");
586 double eta = aDistance * SG_METER_TO_NM / speed;
587 aProp->getChild("eta-seconds")->setIntValue( eta * 3600 );
588 if ( eta >= 100.0 ) {
589 eta = 99.999; // clamp
592 if ( eta < (1.0/6.0) ) {
593 eta *= 60.0; // within 10 minutes, bump up to min/secs
596 int major = (int)eta,
597 minor = (int)((eta - (int)eta) * 60.0);
598 snprintf( eta_str, 64, "%d:%02d", major, minor );
599 aProp->getChild("eta")->setStringValue( eta_str );
602 void FGRouteMgr::removeLegAtIndex(int aIndex)
608 _plan->deleteIndex(aIndex);
611 void FGRouteMgr::waypointsChanged()
614 _edited->fireValueChanged();
617 // mirror internal route to the property system for inspection by other subsystems
618 void FGRouteMgr::update_mirror()
620 mirror->removeChildren("wp");
621 NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
622 FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
625 mirror->setIntValue("num", 0);
627 rmDlg->updateValues();
632 int num = _plan->numLegs();
634 for (int i = 0; i < num; i++) {
635 FlightPlan::Leg* leg = _plan->legAtIndex(i);
636 WayptRef wp = leg->waypoint();
637 SGPropertyNode *prop = mirror->getChild("wp", i, 1);
639 const SGGeod& pos(wp->position());
640 prop->setStringValue("id", wp->ident().c_str());
641 prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
642 prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
644 // leg course+distance
646 prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
647 prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
648 prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
650 if (leg->altitudeRestriction() != RESTRICT_NONE) {
651 double ft = leg->altitudeFt();
652 prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
653 prop->setDoubleValue("altitude-ft", ft);
654 prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
656 prop->setDoubleValue("altitude-m", -9999.9);
657 prop->setDoubleValue("altitude-ft", -9999.9);
660 if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
661 prop->setDoubleValue("speed-mach", leg->speedMach());
662 } else if (leg->speedRestriction() != RESTRICT_NONE) {
663 prop->setDoubleValue("speed-kts", leg->speedKts());
666 if (wp->flag(WPT_ARRIVAL)) {
667 prop->setBoolValue("arrival", true);
670 if (wp->flag(WPT_DEPARTURE)) {
671 prop->setBoolValue("departure", true);
674 if (wp->flag(WPT_MISS)) {
675 prop->setBoolValue("missed-approach", true);
678 prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
679 } // of waypoint iteration
681 // set number as listener attachment point
682 mirror->setIntValue("num", _plan->numLegs());
685 rmDlg->updateValues();
688 totalDistance->setDoubleValue(_plan->totalDistanceNm());
691 // command interface /autopilot/route-manager/input:
693 // @CLEAR ... clear route
694 // @POP ... remove first entry
695 // @DELETE3 ... delete 4th entry
696 // @INSERT2:KSFO@900 ... insert "KSFO@900" as 3rd entry
697 // KSFO@900 ... append "KSFO@900"
699 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
701 const char *s = prop->getStringValue();
702 if (strlen(s) == 0) {
706 if (!strcmp(s, "@CLEAR"))
708 else if (!strcmp(s, "@ACTIVATE"))
710 else if (!strcmp(s, "@LOAD")) {
711 SGPath path(mgr->_pathNode->getStringValue());
712 mgr->loadRoute(path);
713 } else if (!strcmp(s, "@SAVE")) {
714 SGPath path(mgr->_pathNode->getStringValue());
715 mgr->saveRoute(path);
716 } else if (!strcmp(s, "@NEXT")) {
717 mgr->jumpToIndex(mgr->currentIndex() + 1);
718 } else if (!strcmp(s, "@PREVIOUS")) {
719 mgr->jumpToIndex(mgr->currentIndex() - 1);
720 } else if (!strncmp(s, "@JUMP", 5)) {
721 mgr->jumpToIndex(atoi(s + 5));
722 } else if (!strncmp(s, "@DELETE", 7))
723 mgr->removeLegAtIndex(atoi(s + 7));
724 else if (!strncmp(s, "@INSERT", 7)) {
726 int pos = strtol(s + 7, &r, 10);
732 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
734 mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
737 bool FGRouteMgr::activate()
740 SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
744 if (isRouteActive()) {
745 SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
750 active->setBoolValue(true);
751 SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
755 void FGRouteMgr::deactivate()
757 if (!isRouteActive()) {
761 SG_LOG(SG_AUTOPILOT, SG_INFO, "deactivating flight plan");
762 active->setBoolValue(false);
765 void FGRouteMgr::jumpToIndex(int index)
771 _plan->setCurrentIndex(index);
774 void FGRouteMgr::currentWaypointChanged()
776 Waypt* cur = currentWaypt();
777 FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
779 wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
780 wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
782 _currentWpt->fireValueChanged();
783 SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
786 const char* FGRouteMgr::getDepartureICAO() const
788 if (!_plan || !_plan->departureAirport()) {
792 return _plan->departureAirport()->ident().c_str();
795 const char* FGRouteMgr::getDepartureName() const
797 if (!_plan || !_plan->departureAirport()) {
801 return _plan->departureAirport()->name().c_str();
804 const char* FGRouteMgr::getDepartureRunway() const
806 if (_plan && _plan->departureRunway()) {
807 return _plan->departureRunway()->ident().c_str();
813 void FGRouteMgr::setDepartureRunway(const char* aIdent)
819 FGAirport* apt = _plan->departureAirport();
820 if (!apt || (aIdent == NULL)) {
821 _plan->setDeparture(apt);
822 } else if (apt->hasRunwayWithIdent(aIdent)) {
823 _plan->setDeparture(apt->getRunwayByIdent(aIdent));
827 void FGRouteMgr::setDepartureICAO(const char* aIdent)
833 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
834 _plan->setDeparture((FGAirport*) NULL);
836 _plan->setDeparture(FGAirport::findByIdent(aIdent));
840 const char* FGRouteMgr::getSID() const
842 if (_plan && _plan->sid()) {
843 return _plan->sid()->ident().c_str();
849 static double headingDiffDeg(double a, double b)
851 double rawDiff = b - a;
852 SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
856 flightgear::SID* createDefaultSID(FGRunway* aRunway, double enrouteCourse)
862 double runwayElevFt = aRunway->end().getElevationFt();
864 std::ostringstream ss;
865 ss << aRunway->ident() << "-3";
867 SGGeod p = aRunway->pointOnCenterline(aRunway->lengthM() + (3.0 * SG_NM_TO_METER));
868 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
869 w->setAltitude(runwayElevFt + 3000.0, RESTRICT_AT);
873 ss << aRunway->ident() << "-6";
874 p = aRunway->pointOnCenterline(aRunway->lengthM() + (6.0 * SG_NM_TO_METER));
875 w = new BasicWaypt(p, ss.str(), NULL);
876 w->setAltitude(runwayElevFt + 6000.0, RESTRICT_AT);
879 if (enrouteCourse >= 0.0) {
880 // valid enroute course
882 double course = aRunway->headingDeg();
884 while (fabs(diff = headingDiffDeg(course, enrouteCourse)) > 45.0) {
885 // turn in the sign of the heading change 45 degrees
886 course += copysign(45.0, diff);
888 ss << "DEP-" << index++;
889 SGGeod pos = wpts.back()->position();
890 pos = SGGeodesy::direct(pos, course, 3.0 * SG_NM_TO_METER);
891 w = new BasicWaypt(pos, ss.str(), NULL);
895 // no enroute course, just keep runway heading
897 ss << aRunway->ident() << "-9";
898 p = aRunway->pointOnCenterline(aRunway->lengthM() + (9.0 * SG_NM_TO_METER));
899 w = new BasicWaypt(p, ss.str(), NULL);
900 w->setAltitude(runwayElevFt + 9000.0, RESTRICT_AT);
904 BOOST_FOREACH(Waypt* w, wpts) {
905 w->setFlag(WPT_DEPARTURE);
906 w->setFlag(WPT_GENERATED);
909 return flightgear::SID::createTempSID("DEFAULT", aRunway, wpts);
912 void FGRouteMgr::setSID(const char* aIdent)
918 FGAirport* apt = _plan->departureAirport();
919 if (!apt || (aIdent == NULL)) {
920 _plan->setSID((flightgear::SID*) NULL);
924 if (!strcmp(aIdent, "DEFAULT")) {
925 double enrouteCourse = -1.0;
926 if (_plan->destinationAirport()) {
927 enrouteCourse = SGGeodesy::courseDeg(apt->geod(), _plan->destinationAirport()->geod());
930 _plan->setSID(createDefaultSID(_plan->departureRunway(), enrouteCourse));
934 string ident(aIdent);
935 size_t hyphenPos = ident.find('-');
936 if (hyphenPos != string::npos) {
937 string sidIdent = ident.substr(0, hyphenPos);
938 string transIdent = ident.substr(hyphenPos + 1);
940 flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
941 Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
942 _plan->setSID(trans);
944 _plan->setSID(apt->findSIDWithIdent(aIdent));
948 const char* FGRouteMgr::getDestinationICAO() const
950 if (!_plan || !_plan->destinationAirport()) {
954 return _plan->destinationAirport()->ident().c_str();
957 const char* FGRouteMgr::getDestinationName() const
959 if (!_plan || !_plan->destinationAirport()) {
963 return _plan->destinationAirport()->name().c_str();
966 void FGRouteMgr::setDestinationICAO(const char* aIdent)
972 if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
973 _plan->setDestination((FGAirport*) NULL);
975 _plan->setDestination(FGAirport::findByIdent(aIdent));
979 const char* FGRouteMgr::getDestinationRunway() const
981 if (_plan && _plan->destinationRunway()) {
982 return _plan->destinationRunway()->ident().c_str();
988 void FGRouteMgr::setDestinationRunway(const char* aIdent)
994 FGAirport* apt = _plan->destinationAirport();
995 if (!apt || (aIdent == NULL)) {
996 _plan->setDestination(apt);
997 } else if (apt->hasRunwayWithIdent(aIdent)) {
998 _plan->setDestination(apt->getRunwayByIdent(aIdent));
1002 const char* FGRouteMgr::getApproach() const
1004 if (_plan && _plan->approach()) {
1005 return _plan->approach()->ident().c_str();
1011 flightgear::Approach* createDefaultApproach(FGRunway* aRunway, double aEnrouteCourse)
1017 double thresholdElevFt = aRunway->threshold().getElevationFt();
1018 const double approachHeightFt = 2000.0;
1019 double glideslopeDistanceM = (approachHeightFt * SG_FEET_TO_METER) /
1020 tan(3.0 * SG_DEGREES_TO_RADIANS);
1022 std::ostringstream ss;
1023 ss << aRunway->ident() << "-12";
1025 SGGeod p = aRunway->pointOnCenterline(-12.0 * SG_NM_TO_METER);
1026 WayptRef w = new BasicWaypt(p, ss.str(), NULL);
1027 w->setAltitude(thresholdElevFt + 4000, RESTRICT_AT);
1030 // work back form the first point on the centerline
1032 if (aEnrouteCourse >= 0.0) {
1033 // valid enroute course
1035 double course = aRunway->headingDeg();
1037 while (fabs(diff = headingDiffDeg(aEnrouteCourse, course)) > 45.0) {
1038 // turn in the sign of the heading change 45 degrees
1039 course -= copysign(45.0, diff);
1041 ss << "APP-" << index++;
1042 SGGeod pos = wpts.front()->position();
1043 pos = SGGeodesy::direct(pos, course + 180.0, 3.0 * SG_NM_TO_METER);
1044 w = new BasicWaypt(pos, ss.str(), NULL);
1045 wpts.insert(wpts.begin(), w);
1049 p = aRunway->pointOnCenterline(-8.0 * SG_NM_TO_METER);
1051 ss << aRunway->ident() << "-8";
1052 w = new BasicWaypt(p, ss.str(), NULL);
1053 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1056 p = aRunway->pointOnCenterline(-glideslopeDistanceM);
1058 ss << aRunway->ident() << "-GS";
1059 w = new BasicWaypt(p, ss.str(), NULL);
1060 w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1063 BOOST_FOREACH(Waypt* w, wpts) {
1064 w->setFlag(WPT_APPROACH);
1065 w->setFlag(WPT_GENERATED);
1068 return Approach::createTempApproach("DEFAULT", aRunway, wpts);
1071 void FGRouteMgr::setApproach(const char* aIdent)
1077 FGAirport* apt = _plan->destinationAirport();
1078 if (!strcmp(aIdent, "DEFAULT")) {
1079 double enrouteCourse = -1.0;
1080 if (_plan->departureAirport()) {
1081 enrouteCourse = SGGeodesy::courseDeg(_plan->departureAirport()->geod(), apt->geod());
1084 _plan->setApproach(createDefaultApproach(_plan->destinationRunway(), enrouteCourse));
1088 if (!apt || (aIdent == NULL)) {
1089 _plan->setApproach(NULL);
1091 _plan->setApproach(apt->findApproachWithIdent(aIdent));
1095 const char* FGRouteMgr::getSTAR() const
1097 if (_plan && _plan->star()) {
1098 return _plan->star()->ident().c_str();
1104 void FGRouteMgr::setSTAR(const char* aIdent)
1110 FGAirport* apt = _plan->destinationAirport();
1111 if (!apt || (aIdent == NULL)) {
1112 _plan->setSTAR((STAR*) NULL);
1116 string ident(aIdent);
1117 size_t hyphenPos = ident.find('-');
1118 if (hyphenPos != string::npos) {
1119 string starIdent = ident.substr(0, hyphenPos);
1120 string transIdent = ident.substr(hyphenPos + 1);
1122 STAR* star = apt->findSTARWithIdent(starIdent);
1123 Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1124 _plan->setSTAR(trans);
1126 _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1130 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1132 return _plan->waypointFromString(target);
1135 double FGRouteMgr::getDepartureFieldElevation() const
1137 if (!_plan || !_plan->departureAirport()) {
1141 return _plan->departureAirport()->elevation();
1144 double FGRouteMgr::getDestinationFieldElevation() const
1146 if (!_plan || !_plan->destinationAirport()) {
1150 return _plan->destinationAirport()->elevation();
1153 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1155 if ((index < 0) || (index >= numWaypts())) {
1156 throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1159 return mirror->getChild("wp", index);
1162 bool FGRouteMgr::commandDefineUserWaypoint(const SGPropertyNode* arg)
1164 std::string ident = arg->getStringValue("ident");
1165 if (ident.empty()) {
1166 SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident defining user waypoint");
1170 // check for duplicate idents
1171 FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1172 FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1173 if (!dups.empty()) {
1174 SG_LOG(SG_AUTOPILOT, SG_WARN, "defineUserWaypoint: non-unique waypoint identifier:" << ident);
1178 SGGeod pos(SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1179 arg->getDoubleValue("latitude-deg")));
1180 FGPositioned::createUserWaypoint(ident, pos);
1184 bool FGRouteMgr::commandDeleteUserWaypoint(const SGPropertyNode* arg)
1186 std::string ident = arg->getStringValue("ident");
1187 if (ident.empty()) {
1188 SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident deleting user waypoint");
1192 return FGPositioned::deleteUserWaypoint(ident);