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