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