]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
Fix a FlightPlan lifetime issue.
[flightgear.git] / src / Autopilot / route_mgr.cxx
1 // route_mgr.cxx - manage a route (i.e. a collection of waypoints)
2 //
3 // Written by Curtis Olson, started January 2004.
4 //            Norman Vine
5 //            Melchior FRANZ
6 //
7 // Copyright (C) 2004  Curtis L. Olson  - http://www.flightgear.org/~curt
8 //
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.
13 //
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.
18 //
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.
22 //
23 // $Id$
24
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #ifdef HAVE_WINDOWS_H
31 #include <time.h>
32 #endif
33
34 #include <cstdio>
35
36 #include <simgear/compiler.h>
37
38 #include "route_mgr.hxx"
39
40 #include <boost/algorithm/string/case_conv.hpp>
41 #include <boost/tuple/tuple.hpp>
42 #include <boost/foreach.hpp>
43
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>
49
50 #include "Main/fg_props.hxx"
51 #include "Navaids/positioned.hxx"
52 #include <Navaids/waypoint.hxx>
53 #include <Navaids/procedure.hxx>
54 #include "Airports/airport.hxx"
55 #include "Airports/runways.hxx"
56 #include <GUI/new_gui.hxx>
57 #include <GUI/dialog.hxx>
58
59 #define RM "/autopilot/route-manager/"
60
61 using namespace flightgear;
62 using std::string;
63
64 static bool commandLoadFlightPlan(const SGPropertyNode* arg)
65 {
66   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
67   SGPath path(arg->getStringValue("path"));
68   return self->loadRoute(path);
69 }
70
71 static bool commandSaveFlightPlan(const SGPropertyNode* arg)
72 {
73   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
74   SGPath path(arg->getStringValue("path"));
75   return self->saveRoute(path);
76 }
77
78 static bool commandActivateFlightPlan(const SGPropertyNode* arg)
79 {
80   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
81   bool activate = arg->getBoolValue("activate", true);
82   if (activate) {
83     self->activate();
84   } else {
85     self->deactivate();
86   }
87   
88   return true;
89 }
90
91 static bool commandClearFlightPlan(const SGPropertyNode*)
92 {
93   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
94   self->clearRoute();
95   return true;
96 }
97
98 static bool commandSetActiveWaypt(const SGPropertyNode* arg)
99 {
100   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
101   int index = arg->getIntValue("index");
102   if ((index < 0) || (index >= self->numLegs())) {
103     return false;
104   }
105   
106   self->jumpToIndex(index);
107   return true;
108 }
109
110 static bool commandInsertWaypt(const SGPropertyNode* arg)
111 {
112   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
113   int index = arg->getIntValue("index");
114   std::string ident(arg->getStringValue("id"));
115   int alt = arg->getIntValue("altitude-ft", -999);
116   int ias = arg->getIntValue("speed-knots", -999);
117   
118   WayptRef wp;
119 // lat/lon may be supplied to narrow down navaid search, or to specify
120 // a raw waypoint
121   SGGeod pos;
122   if (arg->hasChild("longitude-deg")) {
123     pos = SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
124                                arg->getDoubleValue("latitude-deg"));
125   }
126   
127   if (arg->hasChild("navaid")) {
128     FGPositionedRef p = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid"), pos);
129     
130     if (arg->hasChild("navaid", 1)) {
131       // intersection of two radials
132       FGPositionedRef p2 = FGPositioned::findClosestWithIdent(arg->getStringValue("navaid[1]"), pos);
133       if (!p2) {
134         SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << arg->getStringValue("navaid[1]"));
135         return false;
136       }
137       
138       double r1 = arg->getDoubleValue("radial"),
139         r2 = arg->getDoubleValue("radial[1]");
140       
141       SGGeod intersection;
142       bool ok = SGGeodesy::radialIntersection(p->geod(), r1, p2->geod(), r2, intersection);
143       if (!ok) {
144         SG_LOG(SG_AUTOPILOT, SG_INFO, "no valid intersection for:" << p->ident() 
145                 << "," << p2->ident());
146         return false;
147       }
148       
149       std::string name = p->ident() + "-" + p2->ident();
150       wp = new BasicWaypt(intersection, name, NULL);
151     } else if (arg->hasChild("offset-nm") && arg->hasChild("radial")) {
152       // offset radial from navaid
153       double radial = arg->getDoubleValue("radial");
154       double distanceNm = arg->getDoubleValue("offset-nm");
155       //radial += magvar->getDoubleValue(); // convert to true bearing
156       wp = new OffsetNavaidWaypoint(p, NULL, radial, distanceNm);
157     } else {
158       wp = new NavaidWaypoint(p, NULL);
159     }
160   } else if (arg->hasChild("airport")) {
161     const FGAirport* apt = fgFindAirportID(arg->getStringValue("airport"));
162     if (!apt) {
163       SG_LOG(SG_AUTOPILOT, SG_INFO, "no such airport" << arg->getStringValue("airport"));
164       return false;
165     }
166     
167     if (arg->hasChild("runway")) {
168       if (!apt->hasRunwayWithIdent(arg->getStringValue("runway"))) {
169         SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << arg->getStringValue("runway") << " at " << apt->ident());
170         return false;
171       }
172       
173       FGRunway* runway = apt->getRunwayByIdent(arg->getStringValue("runway"));
174       wp = new RunwayWaypt(runway, NULL);
175     } else {
176       wp = new NavaidWaypoint((FGAirport*) apt, NULL);
177     }
178   } else if (arg->hasChild("text")) {
179     wp = self->waypointFromString(arg->getStringValue("text"));
180   } else if (!(pos == SGGeod())) {
181     // just a raw lat/lon
182     wp = new BasicWaypt(pos, ident, NULL);
183   } else {
184     return false; // failed to build waypoint
185   }
186
187   FlightPlan::Leg* leg = self->flightPlan()->insertWayptAtIndex(wp, index);
188   if (alt >= 0) {
189     leg->setAltitude(RESTRICT_AT, alt);
190   }
191   
192   if (ias > 0) {
193     leg->setSpeed(RESTRICT_AT, ias);
194   }
195   
196   return true;
197 }
198
199 static bool commandDeleteWaypt(const SGPropertyNode* arg)
200 {
201   FGRouteMgr* self = (FGRouteMgr*) globals->get_subsystem("route-manager");
202   int index = arg->getIntValue("index");
203   self->removeLegAtIndex(index);
204   return true;
205 }
206
207 /////////////////////////////////////////////////////////////////////////////
208
209 FGRouteMgr::FGRouteMgr() :
210   _plan(NULL),
211   input(fgGetNode( RM "input", true )),
212   mirror(fgGetNode( RM "route", true ))
213 {
214   listener = new InputListener(this);
215   input->setStringValue("");
216   input->addChangeListener(listener);
217   
218   SGCommandMgr* cmdMgr = SGCommandMgr::instance();
219   cmdMgr->addCommand("define-user-waypoint", this, &FGRouteMgr::commandDefineUserWaypoint);
220   cmdMgr->addCommand("delete-user-waypoint", this, &FGRouteMgr::commandDeleteUserWaypoint);
221     
222   cmdMgr->addCommand("load-flightplan", commandLoadFlightPlan);
223   cmdMgr->addCommand("save-flightplan", commandSaveFlightPlan);
224   cmdMgr->addCommand("activate-flightplan", commandActivateFlightPlan);
225   cmdMgr->addCommand("clear-flightplan", commandClearFlightPlan);
226   cmdMgr->addCommand("set-active-waypt", commandSetActiveWaypt);
227   cmdMgr->addCommand("insert-waypt", commandInsertWaypt);
228   cmdMgr->addCommand("delete-waypt", commandDeleteWaypt);
229 }
230
231
232 FGRouteMgr::~FGRouteMgr()
233 {
234   input->removeChangeListener(listener);
235   delete listener;
236     
237   SGCommandMgr* cmdMgr = SGCommandMgr::instance();
238   //cmdMgr->removeCommand("define-user-waypoint");
239     
240 }
241
242
243 void FGRouteMgr::init() {
244   SGPropertyNode_ptr rm(fgGetNode(RM));
245   
246   magvar = fgGetNode("/environment/magnetic-variation-deg", true);
247      
248   departure = fgGetNode(RM "departure", true);
249   departure->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
250     &FGRouteMgr::getDepartureICAO, &FGRouteMgr::setDepartureICAO));
251   departure->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
252                                                                        &FGRouteMgr::getDepartureRunway, 
253                                                                       &FGRouteMgr::setDepartureRunway));
254   departure->tie("sid", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
255                                                                       &FGRouteMgr::getSID, 
256                                                                       &FGRouteMgr::setSID));
257   
258   departure->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
259     &FGRouteMgr::getDepartureName, NULL));
260   departure->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this, 
261                                                                                &FGRouteMgr::getDestinationFieldElevation, NULL));
262   departure->getChild("etd", 0, true);
263   departure->getChild("takeoff-time", 0, true);
264
265   destination = fgGetNode(RM "destination", true);
266   destination->getChild("airport", 0, true);
267   
268   destination->tie("airport", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
269     &FGRouteMgr::getDestinationICAO, &FGRouteMgr::setDestinationICAO));
270   destination->tie("runway", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
271                              &FGRouteMgr::getDestinationRunway, 
272                             &FGRouteMgr::setDestinationRunway));
273   destination->tie("star", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
274                                                                         &FGRouteMgr::getSTAR, 
275                                                                         &FGRouteMgr::setSTAR));
276   destination->tie("approach", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
277                                                                         &FGRouteMgr::getApproach, 
278                                                                         &FGRouteMgr::setApproach));
279   
280   destination->tie("name", SGRawValueMethods<FGRouteMgr, const char*>(*this, 
281     &FGRouteMgr::getDestinationName, NULL));
282   destination->tie("field-elevation-ft", SGRawValueMethods<FGRouteMgr, double>(*this, 
283                                                                       &FGRouteMgr::getDestinationFieldElevation, NULL));
284   
285   destination->getChild("eta", 0, true);
286   destination->getChild("touchdown-time", 0, true);
287
288   alternate = fgGetNode(RM "alternate", true);
289   alternate->getChild("airport", 0, true);
290   alternate->getChild("runway", 0, true);
291   
292   cruise = fgGetNode(RM "cruise", true);
293   cruise->getChild("altitude-ft", 0, true);
294   cruise->setDoubleValue("altitude-ft", 10000.0);
295   cruise->getChild("flight-level", 0, true);
296   cruise->getChild("speed-kts", 0, true);
297   cruise->setDoubleValue("speed-kts", 160.0);
298   
299   totalDistance = fgGetNode(RM "total-distance", true);
300   totalDistance->setDoubleValue(0.0);
301   distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
302   distanceToGo->setDoubleValue(0.0);
303   
304   ete = fgGetNode(RM "ete", true);
305   ete->setDoubleValue(0.0);
306   
307   elapsedFlightTime = fgGetNode(RM "flight-time", true);
308   elapsedFlightTime->setDoubleValue(0.0);
309   
310   active = fgGetNode(RM "active", true);
311   active->setBoolValue(false);
312   
313   airborne = fgGetNode(RM "airborne", true);
314   airborne->setBoolValue(false);
315     
316   _edited = fgGetNode(RM "signals/edited", true);
317   _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
318   
319   _currentWpt = fgGetNode(RM "current-wp", true);
320   _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
321     (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
322       
323   wp0 = fgGetNode(RM "wp", 0, true);
324   wp0->getChild("id", 0, true);
325   wp0->getChild("dist", 0, true);
326   wp0->getChild("eta", 0, true);
327   wp0->getChild("bearing-deg", 0, true);
328   
329   wp1 = fgGetNode(RM "wp", 1, true);
330   wp1->getChild("id", 0, true);
331   wp1->getChild("dist", 0, true);
332   wp1->getChild("eta", 0, true);
333   
334   wpn = fgGetNode(RM "wp-last", 0, true);
335   wpn->getChild("dist", 0, true);
336   wpn->getChild("eta", 0, true);
337   
338   _pathNode = fgGetNode(RM "file-path", 0, true);
339 }
340
341
342 void FGRouteMgr::postinit()
343 {
344   setFlightPlan(new FlightPlan());
345   
346   SGPath path(_pathNode->getStringValue());
347   if (!path.isNull()) {
348     SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
349     loadRoute(path);
350   }
351   
352 // this code only matters for the --wp option now - perhaps the option
353 // should be deprecated in favour of an explicit flight-plan file?
354 // then the global initial waypoint list could die.
355   string_list *waypoints = globals->get_initial_waypoints();
356   if (waypoints) {
357     string_list::iterator it;
358     for (it = waypoints->begin(); it != waypoints->end(); ++it) {
359       WayptRef w = waypointFromString(*it);
360       if (w) {
361         _plan->insertWayptAtIndex(w, -1);
362       }
363     }
364     
365     SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
366     update_mirror();
367   }
368
369   weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
370   groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
371   
372   // check airbone flag agrees with presets
373 }
374
375 void FGRouteMgr::bind() { }
376 void FGRouteMgr::unbind() { }
377
378 bool FGRouteMgr::isRouteActive() const
379 {
380   return active->getBoolValue();
381 }
382
383 bool FGRouteMgr::saveRoute(const SGPath& p)
384 {
385   if (!_plan) {
386     return false;
387   }
388   
389   return _plan->save(p);
390 }
391
392 bool FGRouteMgr::loadRoute(const SGPath& p)
393 {
394   FlightPlan* fp = new FlightPlan;
395   if (!fp->load(p)) {
396     delete fp;
397     return false;
398   }
399   
400   setFlightPlan(fp);
401   return true;
402 }
403
404 FlightPlanRef FGRouteMgr::flightPlan() const
405 {
406   return _plan;
407 }
408
409 void FGRouteMgr::setFlightPlan(const FlightPlanRef& plan)
410 {
411   if (plan == _plan) {
412     return;
413   }
414   
415   if (_plan) {
416     _plan->removeDelegate(this);
417     active->setBoolValue(false);
418   }
419   
420   _plan = plan;
421   _plan->addDelegate(this);
422   
423   _flightplanChanged->fireValueChanged();
424   
425 // fire all the callbacks!
426   departureChanged();
427   arrivalChanged();
428   waypointsChanged();
429   currentWaypointChanged();
430 }
431
432 void FGRouteMgr::update( double dt )
433 {
434   if (dt <= 0.0) {
435     return; // paused, nothing to do here
436   }
437   
438   double gs = groundSpeed->getDoubleValue();
439   if (airborne->getBoolValue()) {
440     time_t now = time(NULL);
441     elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
442     
443     if (weightOnWheels->getBoolValue()) {
444       // touch down
445       destination->setIntValue("touchdown-time", time(NULL));
446       airborne->setBoolValue(false);
447     }
448   } else { // not airborne
449     if (weightOnWheels->getBoolValue() || (gs < 40)) {
450       // either taking-off or rolling-out after touchdown
451     } else {
452       airborne->setBoolValue(true);
453       _takeoffTime = time(NULL); // start the clock
454       departure->setIntValue("takeoff-time", _takeoffTime);
455     }
456   }
457   
458   if (!active->getBoolValue()) {
459     return;
460   }
461
462 // basic course/distance information
463   SGGeod currentPos = globals->get_aircraft_position();
464
465   FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
466   if (!leg) {
467     return;
468   }
469   
470   double courseDeg;
471   double distanceM;
472   boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
473   
474 // update wp0 / wp1 / wp-last
475   wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
476   wp0->setDoubleValue("true-bearing-deg", courseDeg);
477   courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
478   wp0->setDoubleValue("bearing-deg", courseDeg);
479   setETAPropertyFromDistance(wp0->getChild("eta"), distanceM);
480   
481   double totalPathDistanceNm = _plan->totalDistanceNm();
482   double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
483   
484 // total distance to go, is direct distance to wp0, plus the remaining
485 // path distance from wp0
486   totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
487   
488   wp0->setDoubleValue("distance-along-route-nm", 
489                       leg->distanceAlongRoute());
490   wp0->setDoubleValue("remaining-distance-nm", 
491                       totalPathDistanceNm - leg->distanceAlongRoute());
492   
493   FlightPlan::Leg* nextLeg = _plan->nextLeg();
494   if (nextLeg) {
495     boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
496      
497     wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
498     wp1->setDoubleValue("true-bearing-deg", courseDeg);
499     courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
500     wp1->setDoubleValue("bearing-deg", courseDeg);
501     setETAPropertyFromDistance(wp1->getChild("eta"), distanceM);    
502     wp1->setDoubleValue("distance-along-route-nm", 
503                         nextLeg->distanceAlongRoute());
504     wp1->setDoubleValue("remaining-distance-nm", 
505                         totalPathDistanceNm - nextLeg->distanceAlongRoute());
506   }
507   
508   distanceToGo->setDoubleValue(totalDistanceRemaining);
509   wpn->setDoubleValue("dist", totalDistanceRemaining);
510   ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
511   setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
512 }
513
514 void FGRouteMgr::clearRoute()
515 {
516   if (_plan) {
517     _plan->clear();
518   }
519 }
520
521 Waypt* FGRouteMgr::currentWaypt() const
522 {
523   if (_plan && _plan->currentLeg()) {
524     return _plan->currentLeg()->waypoint();
525   }
526   
527   return NULL;
528 }
529
530 int FGRouteMgr::currentIndex() const
531 {
532   if (!_plan) {
533     return 0;
534   }
535   
536   return _plan->currentIndex();
537 }
538
539 Waypt* FGRouteMgr::wayptAtIndex(int index) const
540 {
541   if (!_plan) {
542     throw sg_range_exception("wayptAtindex: no flightplan");
543   }
544   
545   return _plan->legAtIndex(index)->waypoint();
546 }
547
548 int FGRouteMgr::numLegs() const
549 {
550   if (_plan) {
551     return _plan->numLegs();
552   }
553   
554   return 0;
555 }
556
557 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
558 {
559   double speed = groundSpeed->getDoubleValue();
560   if (speed < 1.0) {
561     aProp->setStringValue("--:--");
562     return;
563   }
564
565   char eta_str[64];
566   double eta = aDistance * SG_METER_TO_NM / speed;
567   if ( eta >= 100.0 ) { 
568       eta = 99.999; // clamp
569   }
570   
571   if ( eta < (1.0/6.0) ) {
572     eta *= 60.0; // within 10 minutes, bump up to min/secs
573   }
574   
575   int major = (int)eta, 
576       minor = (int)((eta - (int)eta) * 60.0);
577   snprintf( eta_str, 64, "%d:%02d", major, minor );
578   aProp->setStringValue( eta_str );
579 }
580
581 void FGRouteMgr::removeLegAtIndex(int aIndex)
582 {
583   if (!_plan) {
584     return;
585   }
586   
587   _plan->deleteIndex(aIndex);
588 }
589   
590 void FGRouteMgr::waypointsChanged()
591 {
592   update_mirror();
593   _edited->fireValueChanged();
594 }
595
596 // mirror internal route to the property system for inspection by other subsystems
597 void FGRouteMgr::update_mirror()
598 {
599   mirror->removeChildren("wp");
600   NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
601   FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
602
603   if (!_plan) {
604     mirror->setIntValue("num", 0);
605     if (rmDlg) {
606       rmDlg->updateValues();
607     }
608     return;
609   }
610   
611   int num = _plan->numLegs();
612     
613   for (int i = 0; i < num; i++) {
614     FlightPlan::Leg* leg = _plan->legAtIndex(i);
615     WayptRef wp = leg->waypoint();
616     SGPropertyNode *prop = mirror->getChild("wp", i, 1);
617
618     const SGGeod& pos(wp->position());
619     prop->setStringValue("id", wp->ident().c_str());
620     prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
621     prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
622    
623     // leg course+distance
624
625     prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
626     prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
627     prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
628     
629     if (leg->altitudeRestriction() != RESTRICT_NONE) {
630       double ft = leg->altitudeFt();
631       prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
632       prop->setDoubleValue("altitude-ft", ft);
633       prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
634     } else {
635       prop->setDoubleValue("altitude-m", -9999.9);
636       prop->setDoubleValue("altitude-ft", -9999.9);
637     }
638     
639     if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
640       prop->setDoubleValue("speed-mach", leg->speedMach());
641     } else if (leg->speedRestriction() != RESTRICT_NONE) {
642       prop->setDoubleValue("speed-kts", leg->speedKts());
643     }
644     
645     if (wp->flag(WPT_ARRIVAL)) {
646       prop->setBoolValue("arrival", true);
647     }
648     
649     if (wp->flag(WPT_DEPARTURE)) {
650       prop->setBoolValue("departure", true);
651     }
652     
653     if (wp->flag(WPT_MISS)) {
654       prop->setBoolValue("missed-approach", true);
655     }
656     
657     prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
658   } // of waypoint iteration
659   
660   // set number as listener attachment point
661   mirror->setIntValue("num", _plan->numLegs());
662     
663   if (rmDlg) {
664     rmDlg->updateValues();
665   }
666   
667   totalDistance->setDoubleValue(_plan->totalDistanceNm());
668 }
669
670 // command interface /autopilot/route-manager/input:
671 //
672 //   @CLEAR             ... clear route
673 //   @POP               ... remove first entry
674 //   @DELETE3           ... delete 4th entry
675 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
676 //   KSFO@900           ... append "KSFO@900"
677 //
678 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
679 {
680     const char *s = prop->getStringValue();
681     if (strlen(s) == 0) {
682       return;
683     }
684     
685     if (!strcmp(s, "@CLEAR"))
686         mgr->clearRoute();
687     else if (!strcmp(s, "@ACTIVATE"))
688         mgr->activate();
689     else if (!strcmp(s, "@LOAD")) {
690       SGPath path(mgr->_pathNode->getStringValue());
691       mgr->loadRoute(path);
692     } else if (!strcmp(s, "@SAVE")) {
693       SGPath path(mgr->_pathNode->getStringValue());
694       mgr->saveRoute(path);
695     } else if (!strcmp(s, "@NEXT")) {
696       mgr->jumpToIndex(mgr->currentIndex() + 1);
697     } else if (!strcmp(s, "@PREVIOUS")) {
698       mgr->jumpToIndex(mgr->currentIndex() - 1);
699     } else if (!strncmp(s, "@JUMP", 5)) {
700       mgr->jumpToIndex(atoi(s + 5));
701     } else if (!strncmp(s, "@DELETE", 7))
702         mgr->removeLegAtIndex(atoi(s + 7));
703     else if (!strncmp(s, "@INSERT", 7)) {
704         char *r;
705         int pos = strtol(s + 7, &r, 10);
706         if (*r++ != ':')
707             return;
708         while (isspace(*r))
709             r++;
710         if (*r)
711             mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
712     } else
713       mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
714 }
715
716 bool FGRouteMgr::activate()
717 {
718   if (!_plan) {
719     SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
720     return false;
721   }
722   
723   if (isRouteActive()) {
724     SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
725     return false;
726   }
727  
728   _plan->setCurrentIndex(0);
729   active->setBoolValue(true);
730   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
731   return true;
732 }
733
734 void FGRouteMgr::deactivate()
735 {
736   if (!isRouteActive()) {
737     return;
738   }
739   
740   SG_LOG(SG_AUTOPILOT, SG_INFO, "deactivating flight plan");
741   active->setBoolValue(false);
742 }
743
744 void FGRouteMgr::jumpToIndex(int index)
745 {
746   if (!_plan) {
747     return;
748   }
749   
750   _plan->setCurrentIndex(index);
751 }
752
753 void FGRouteMgr::currentWaypointChanged()
754 {
755   Waypt* cur = currentWaypt();
756   FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
757
758   wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
759   wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
760   
761   _currentWpt->fireValueChanged();
762   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
763 }
764
765 const char* FGRouteMgr::getDepartureICAO() const
766 {
767   if (!_plan || !_plan->departureAirport()) {
768     return "";
769   }
770   
771   return _plan->departureAirport()->ident().c_str();
772 }
773
774 const char* FGRouteMgr::getDepartureName() const
775 {
776   if (!_plan || !_plan->departureAirport()) {
777     return "";
778   }
779   
780   return _plan->departureAirport()->name().c_str();
781 }
782
783 const char* FGRouteMgr::getDepartureRunway() const
784 {
785   if (_plan && _plan->departureRunway()) {
786     return _plan->departureRunway()->ident().c_str();
787   }
788   
789   return "";
790 }
791
792 void FGRouteMgr::setDepartureRunway(const char* aIdent)
793 {
794   FGAirport* apt = _plan->departureAirport();
795   if (!apt || (aIdent == NULL)) {
796     _plan->setDeparture(apt);
797   } else if (apt->hasRunwayWithIdent(aIdent)) {
798     _plan->setDeparture(apt->getRunwayByIdent(aIdent));
799   }
800 }
801
802 void FGRouteMgr::setDepartureICAO(const char* aIdent)
803 {
804   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
805     _plan->setDeparture((FGAirport*) NULL);
806   } else {
807     _plan->setDeparture(FGAirport::findByIdent(aIdent));
808   }
809 }
810
811 const char* FGRouteMgr::getSID() const
812 {
813   if (_plan && _plan->sid()) {
814     return _plan->sid()->ident().c_str();
815   }
816   
817   return "";
818 }
819
820 static double headingDiffDeg(double a, double b)
821 {
822   double rawDiff = b - a;
823   SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
824   return rawDiff;
825 }
826
827 flightgear::SID* createDefaultSID(FGRunway* aRunway, double enrouteCourse)
828 {
829   if (!aRunway) {
830     return NULL;
831   }
832   
833   double runwayElevFt = aRunway->end().getElevationFt();
834   WayptVec wpts;
835   std::ostringstream ss;
836   ss << aRunway->ident() << "-3";
837   
838   SGGeod p = aRunway->pointOnCenterline(aRunway->lengthM() + (3.0 * SG_NM_TO_METER));
839   WayptRef w = new BasicWaypt(p, ss.str(), NULL);
840   w->setAltitude(runwayElevFt + 3000.0, RESTRICT_AT);
841   wpts.push_back(w);
842   
843   ss.str("");
844   ss << aRunway->ident() << "-6";
845   p = aRunway->pointOnCenterline(aRunway->lengthM() + (6.0 * SG_NM_TO_METER));
846   w = new BasicWaypt(p, ss.str(), NULL);
847   w->setAltitude(runwayElevFt + 6000.0, RESTRICT_AT);
848   wpts.push_back(w);
849
850   if (enrouteCourse >= 0.0) {
851     // valid enroute course
852     int index = 3;
853     double course = aRunway->headingDeg();
854     double diff;
855     while (fabs(diff = headingDiffDeg(course, enrouteCourse)) > 45.0) {
856       // turn in the sign of the heading change 45 degrees
857       course += copysign(45.0, diff);
858       ss.str("");
859       ss << "DEP-" << index++;
860       SGGeod pos = wpts.back()->position();
861       pos = SGGeodesy::direct(pos, course, 3.0 * SG_NM_TO_METER);
862       w = new BasicWaypt(pos, ss.str(), NULL);
863       wpts.push_back(w);
864     }
865   } else {
866     // no enroute course, just keep runway heading
867     ss.str("");
868     ss << aRunway->ident() << "-9";
869     p = aRunway->pointOnCenterline(aRunway->lengthM() + (9.0 * SG_NM_TO_METER));
870     w = new BasicWaypt(p, ss.str(), NULL);
871     w->setAltitude(runwayElevFt + 9000.0, RESTRICT_AT);
872     wpts.push_back(w);
873   }
874   
875   BOOST_FOREACH(Waypt* w, wpts) {
876     w->setFlag(WPT_DEPARTURE);
877     w->setFlag(WPT_GENERATED);
878   }
879   
880   return flightgear::SID::createTempSID("DEFAULT", aRunway, wpts);
881 }
882
883 void FGRouteMgr::setSID(const char* aIdent)
884 {
885   FGAirport* apt = _plan->departureAirport();
886   if (!apt || (aIdent == NULL)) {
887     _plan->setSID((flightgear::SID*) NULL);
888     return;
889   } 
890   
891   if (!strcmp(aIdent, "DEFAULT")) {
892     double enrouteCourse = -1.0;
893     if (_plan->destinationAirport()) {
894       enrouteCourse = SGGeodesy::courseDeg(apt->geod(), _plan->destinationAirport()->geod());
895     }
896     
897     _plan->setSID(createDefaultSID(_plan->departureRunway(), enrouteCourse));
898     return;
899   }
900   
901   string ident(aIdent);
902   size_t hyphenPos = ident.find('-');
903   if (hyphenPos != string::npos) {
904     string sidIdent = ident.substr(0, hyphenPos);
905     string transIdent = ident.substr(hyphenPos + 1);
906     
907     flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
908     Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
909     _plan->setSID(trans);
910   } else {
911     _plan->setSID(apt->findSIDWithIdent(aIdent));
912   }
913 }
914
915 const char* FGRouteMgr::getDestinationICAO() const
916 {
917   if (!_plan || !_plan->destinationAirport()) {
918     return "";
919   }
920   
921   return _plan->destinationAirport()->ident().c_str();
922 }
923
924 const char* FGRouteMgr::getDestinationName() const
925 {
926   if (!_plan || !_plan->destinationAirport()) {
927     return "";
928   }
929   
930   return _plan->destinationAirport()->name().c_str();
931 }
932
933 void FGRouteMgr::setDestinationICAO(const char* aIdent)
934 {
935   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
936     _plan->setDestination((FGAirport*) NULL);
937   } else {
938     _plan->setDestination(FGAirport::findByIdent(aIdent));
939   }
940 }
941
942 const char* FGRouteMgr::getDestinationRunway() const
943 {
944   if (_plan && _plan->destinationRunway()) {
945     return _plan->destinationRunway()->ident().c_str();
946   }
947   
948   return "";
949 }
950
951 void FGRouteMgr::setDestinationRunway(const char* aIdent)
952 {
953   FGAirport* apt = _plan->destinationAirport();
954   if (!apt || (aIdent == NULL)) {
955     _plan->setDestination(apt);
956   } else if (apt->hasRunwayWithIdent(aIdent)) {
957     _plan->setDestination(apt->getRunwayByIdent(aIdent));
958   }
959 }
960
961 const char* FGRouteMgr::getApproach() const
962 {
963   if (_plan && _plan->approach()) {
964     return _plan->approach()->ident().c_str();
965   }
966   
967   return "";
968 }
969
970 flightgear::Approach* createDefaultApproach(FGRunway* aRunway, double aEnrouteCourse)
971 {
972   if (!aRunway) {
973     return NULL;
974   }
975
976   double thresholdElevFt = aRunway->threshold().getElevationFt();
977   const double approachHeightFt = 2000.0;
978   double glideslopeDistanceM = (approachHeightFt * SG_FEET_TO_METER) /
979     tan(3.0 * SG_DEGREES_TO_RADIANS);
980   
981   std::ostringstream ss;
982   ss << aRunway->ident() << "-12";
983   WayptVec wpts;
984   SGGeod p = aRunway->pointOnCenterline(-12.0 * SG_NM_TO_METER);
985   WayptRef w = new BasicWaypt(p, ss.str(), NULL);
986   w->setAltitude(thresholdElevFt + 4000, RESTRICT_AT);
987   wpts.push_back(w);
988
989 // work back form the first point on the centerline
990   
991   if (aEnrouteCourse >= 0.0) {
992     // valid enroute course
993     int index = 4;
994     double course = aRunway->headingDeg();
995     double diff;
996     while (fabs(diff = headingDiffDeg(aEnrouteCourse, course)) > 45.0) {
997       // turn in the sign of the heading change 45 degrees
998       course -= copysign(45.0, diff);
999       ss.str("");
1000       ss << "APP-" << index++;
1001       SGGeod pos = wpts.front()->position();
1002       pos = SGGeodesy::direct(pos, course + 180.0, 3.0 * SG_NM_TO_METER);
1003       w = new BasicWaypt(pos, ss.str(), NULL);
1004       wpts.insert(wpts.begin(), w);
1005     }
1006   }
1007     
1008   p = aRunway->pointOnCenterline(-8.0 * SG_NM_TO_METER);
1009   ss.str("");
1010   ss << aRunway->ident() << "-8";
1011   w = new BasicWaypt(p, ss.str(), NULL);
1012   w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1013   wpts.push_back(w);
1014   
1015   p = aRunway->pointOnCenterline(-glideslopeDistanceM);    
1016   ss.str("");
1017   ss << aRunway->ident() << "-GS";
1018   w = new BasicWaypt(p, ss.str(), NULL);
1019   w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1020   wpts.push_back(w);
1021     
1022   BOOST_FOREACH(Waypt* w, wpts) {
1023     w->setFlag(WPT_APPROACH);
1024     w->setFlag(WPT_GENERATED);
1025   }
1026   
1027   return Approach::createTempApproach("DEFAULT", aRunway, wpts);
1028 }
1029
1030 void FGRouteMgr::setApproach(const char* aIdent)
1031 {
1032   FGAirport* apt = _plan->destinationAirport();
1033   if (!strcmp(aIdent, "DEFAULT")) {
1034     double enrouteCourse = -1.0;
1035     if (_plan->departureAirport()) {
1036       enrouteCourse = SGGeodesy::courseDeg(_plan->departureAirport()->geod(), apt->geod());
1037     }
1038     
1039     _plan->setApproach(createDefaultApproach(_plan->destinationRunway(), enrouteCourse));
1040     return;
1041   }
1042   
1043   if (!apt || (aIdent == NULL)) {
1044     _plan->setApproach(NULL);
1045   } else {
1046     _plan->setApproach(apt->findApproachWithIdent(aIdent));
1047   }
1048 }
1049
1050 const char* FGRouteMgr::getSTAR() const
1051 {
1052   if (_plan && _plan->star()) {
1053     return _plan->star()->ident().c_str();
1054   }
1055   
1056   return "";
1057 }
1058
1059 void FGRouteMgr::setSTAR(const char* aIdent)
1060 {
1061   FGAirport* apt = _plan->destinationAirport();
1062   if (!apt || (aIdent == NULL)) {
1063     _plan->setSTAR((STAR*) NULL);
1064     return;
1065   } 
1066   
1067   string ident(aIdent);
1068   size_t hyphenPos = ident.find('-');
1069   if (hyphenPos != string::npos) {
1070     string starIdent = ident.substr(0, hyphenPos);
1071     string transIdent = ident.substr(hyphenPos + 1);
1072     
1073     STAR* star = apt->findSTARWithIdent(starIdent);
1074     Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1075     _plan->setSTAR(trans);
1076   } else {
1077     _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1078   }
1079 }
1080
1081 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1082 {
1083   return _plan->waypointFromString(target);
1084 }
1085
1086 double FGRouteMgr::getDepartureFieldElevation() const
1087 {
1088   if (!_plan || !_plan->departureAirport()) {
1089     return 0.0;
1090   }
1091   
1092   return _plan->departureAirport()->elevation();
1093 }
1094
1095 double FGRouteMgr::getDestinationFieldElevation() const
1096 {
1097   if (!_plan || !_plan->destinationAirport()) {
1098     return 0.0;
1099   }
1100   
1101   return _plan->destinationAirport()->elevation();
1102 }
1103
1104 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1105 {
1106   if ((index < 0) || (index >= numWaypts())) {
1107     throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1108   }
1109   
1110   return mirror->getChild("wp", index);
1111 }
1112
1113 bool FGRouteMgr::commandDefineUserWaypoint(const SGPropertyNode* arg)
1114 {
1115     std::string ident = arg->getStringValue("ident");
1116     if (ident.empty()) {
1117         SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident defining user waypoint");
1118         return false;
1119     }
1120     
1121     // check for duplicate idents
1122     FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1123     FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1124     if (!dups.empty()) {
1125         SG_LOG(SG_AUTOPILOT, SG_WARN, "defineUserWaypoint: non-unique waypoint identifier:" << ident);
1126         return false;
1127     }
1128
1129     SGGeod pos(SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1130                                arg->getDoubleValue("latitude-deg")));
1131     FGPositioned::createUserWaypoint(ident, pos);
1132     return true;
1133 }
1134
1135 bool FGRouteMgr::commandDeleteUserWaypoint(const SGPropertyNode* arg)
1136 {
1137     std::string ident = arg->getStringValue("ident");
1138     if (ident.empty()) {
1139         SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident deleting user waypoint");
1140         return false;
1141     }
1142     
1143     return FGPositioned::deleteUserWaypoint(ident);
1144 }
1145