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