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