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