]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
Report bad command-line args via message box.
[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("eta-seconds", 0, true);
298   destination->getChild("touchdown-time", 0, true);
299
300   alternate = fgGetNode(RM "alternate", true);
301   alternate->getChild("airport", 0, true);
302   alternate->getChild("runway", 0, true);
303   
304   cruise = fgGetNode(RM "cruise", true);
305   cruise->getChild("altitude-ft", 0, true);
306   cruise->setDoubleValue("altitude-ft", 10000.0);
307   cruise->getChild("flight-level", 0, true);
308   cruise->getChild("speed-kts", 0, true);
309   cruise->setDoubleValue("speed-kts", 160.0);
310   
311   totalDistance = fgGetNode(RM "total-distance", true);
312   totalDistance->setDoubleValue(0.0);
313   distanceToGo = fgGetNode(RM "distance-remaining-nm", true);
314   distanceToGo->setDoubleValue(0.0);
315   
316   ete = fgGetNode(RM "ete", true);
317   ete->setDoubleValue(0.0);
318   
319   elapsedFlightTime = fgGetNode(RM "flight-time", true);
320   elapsedFlightTime->setDoubleValue(0.0);
321   
322   active = fgGetNode(RM "active", true);
323   active->setBoolValue(false);
324   
325   airborne = fgGetNode(RM "airborne", true);
326   airborne->setBoolValue(false);
327     
328   _edited = fgGetNode(RM "signals/edited", true);
329   _flightplanChanged = fgGetNode(RM "signals/flightplan-changed", true);
330   
331   _currentWpt = fgGetNode(RM "current-wp", true);
332   _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
333     (*this, &FGRouteMgr::currentIndex, &FGRouteMgr::jumpToIndex));
334       
335   wp0 = fgGetNode(RM "wp", 0, true);
336   wp0->getChild("id", 0, true);
337   wp0->getChild("dist", 0, true);
338   wp0->getChild("eta", 0, true);
339   wp0->getChild("eta-seconds", 0, true);
340   wp0->getChild("bearing-deg", 0, true);
341   
342   wp1 = fgGetNode(RM "wp", 1, true);
343   wp1->getChild("id", 0, true);
344   wp1->getChild("dist", 0, true);
345   wp1->getChild("eta", 0, true);
346   wp1->getChild("eta-seconds", 0, true);
347   
348   wpn = fgGetNode(RM "wp-last", 0, true);
349   wpn->getChild("dist", 0, true);
350   wpn->getChild("eta", 0, true);
351   wpn->getChild("eta-seconds", 0, true);
352   
353   _pathNode = fgGetNode(RM "file-path", 0, true);
354 }
355
356
357 void FGRouteMgr::postinit()
358 {
359   setFlightPlan(new FlightPlan());
360   
361   SGPath path(_pathNode->getStringValue());
362   if (!path.isNull()) {
363     SG_LOG(SG_AUTOPILOT, SG_INFO, "loading flight-plan from: " << path.str());
364     loadRoute(path);
365   }
366   
367 // this code only matters for the --wp option now - perhaps the option
368 // should be deprecated in favour of an explicit flight-plan file?
369 // then the global initial waypoint list could die.
370   string_list *waypoints = globals->get_initial_waypoints();
371   if (waypoints) {
372     string_list::iterator it;
373     for (it = waypoints->begin(); it != waypoints->end(); ++it) {
374       WayptRef w = waypointFromString(*it);
375       if (w) {
376         _plan->insertWayptAtIndex(w, -1);
377       }
378     }
379     
380     SG_LOG(SG_AUTOPILOT, SG_INFO, "loaded initial waypoints:" << numLegs());
381     update_mirror();
382   }
383
384   weightOnWheels = fgGetNode("/gear/gear[0]/wow", true);
385   groundSpeed = fgGetNode("/velocities/groundspeed-kt", true);
386   
387   // check airbone flag agrees with presets
388 }
389
390 void FGRouteMgr::bind() { }
391 void FGRouteMgr::unbind() { }
392
393 bool FGRouteMgr::isRouteActive() const
394 {
395   return active->getBoolValue();
396 }
397
398 bool FGRouteMgr::saveRoute(const SGPath& p)
399 {
400   if (!_plan) {
401     return false;
402   }
403   
404   return _plan->save(p);
405 }
406
407 bool FGRouteMgr::loadRoute(const SGPath& p)
408 {
409   FlightPlan* fp = new FlightPlan;
410   if (!fp->load(p)) {
411     delete fp;
412     return false;
413   }
414   
415   setFlightPlan(fp);
416   return true;
417 }
418
419 FlightPlanRef FGRouteMgr::flightPlan() const
420 {
421   return _plan;
422 }
423
424 void FGRouteMgr::setFlightPlan(const FlightPlanRef& plan)
425 {
426   if (plan == _plan) {
427     return;
428   }
429   
430   if (_plan) {
431     _plan->removeDelegate(this);
432     active->setBoolValue(false);
433   }
434   
435   _plan = plan;
436   _plan->addDelegate(this);
437   
438   _flightplanChanged->fireValueChanged();
439   
440 // fire all the callbacks!
441   departureChanged();
442   arrivalChanged();
443   waypointsChanged();
444   currentWaypointChanged();
445 }
446
447 void FGRouteMgr::update( double dt )
448 {
449   if (dt <= 0.0) {
450     return; // paused, nothing to do here
451   }
452   
453   double gs = groundSpeed->getDoubleValue();
454   if (airborne->getBoolValue()) {
455     time_t now = time(NULL);
456     elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
457     
458     if (weightOnWheels->getBoolValue()) {
459       // touch down
460       destination->setIntValue("touchdown-time", time(NULL));
461       airborne->setBoolValue(false);
462     }
463   } else { // not airborne
464     if (weightOnWheels->getBoolValue() || (gs < 40)) {
465       // either taking-off or rolling-out after touchdown
466     } else {
467       airborne->setBoolValue(true);
468       _takeoffTime = time(NULL); // start the clock
469       departure->setIntValue("takeoff-time", _takeoffTime);
470     }
471   }
472   
473   if (!active->getBoolValue()) {
474     return;
475   }
476
477 // basic course/distance information
478   SGGeod currentPos = globals->get_aircraft_position();
479
480   FlightPlan::Leg* leg = _plan ? _plan->currentLeg() : NULL;
481   if (!leg) {
482     return;
483   }
484   
485   double courseDeg;
486   double distanceM;
487   boost::tie(courseDeg, distanceM) = leg->waypoint()->courseAndDistanceFrom(currentPos);
488   
489 // update wp0 / wp1 / wp-last
490   wp0->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
491   wp0->setDoubleValue("true-bearing-deg", courseDeg);
492   courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
493   wp0->setDoubleValue("bearing-deg", courseDeg);
494   setETAPropertyFromDistance(wp0, distanceM);
495   
496   double totalPathDistanceNm = _plan->totalDistanceNm();
497   double totalDistanceRemaining = distanceM * SG_METER_TO_NM; // distance to current waypoint
498   
499 // total distance to go, is direct distance to wp0, plus the remaining
500 // path distance from wp0
501   totalDistanceRemaining += (totalPathDistanceNm - leg->distanceAlongRoute());
502   
503   wp0->setDoubleValue("distance-along-route-nm", 
504                       leg->distanceAlongRoute());
505   wp0->setDoubleValue("remaining-distance-nm", 
506                       totalPathDistanceNm - leg->distanceAlongRoute());
507   
508   FlightPlan::Leg* nextLeg = _plan->nextLeg();
509   if (nextLeg) {
510     boost::tie(courseDeg, distanceM) = nextLeg->waypoint()->courseAndDistanceFrom(currentPos);
511      
512     wp1->setDoubleValue("dist", distanceM * SG_METER_TO_NM);
513     wp1->setDoubleValue("true-bearing-deg", courseDeg);
514     courseDeg -= magvar->getDoubleValue(); // expose magnetic bearing
515     wp1->setDoubleValue("bearing-deg", courseDeg);
516     setETAPropertyFromDistance(wp1, distanceM);    
517     wp1->setDoubleValue("distance-along-route-nm", 
518                         nextLeg->distanceAlongRoute());
519     wp1->setDoubleValue("remaining-distance-nm", 
520                         totalPathDistanceNm - nextLeg->distanceAlongRoute());
521   }
522   
523   distanceToGo->setDoubleValue(totalDistanceRemaining);
524   wpn->setDoubleValue("dist", totalDistanceRemaining);
525   ete->setDoubleValue(totalDistanceRemaining / gs * 3600.0);
526   setETAPropertyFromDistance(wpn, totalDistanceRemaining);
527 }
528
529 void FGRouteMgr::clearRoute()
530 {
531   if (_plan) {
532     _plan->clear();
533   }
534 }
535
536 Waypt* FGRouteMgr::currentWaypt() const
537 {
538   if (_plan && _plan->currentLeg()) {
539     return _plan->currentLeg()->waypoint();
540   }
541   
542   return NULL;
543 }
544
545 int FGRouteMgr::currentIndex() const
546 {
547   if (!_plan) {
548     return 0;
549   }
550   
551   return _plan->currentIndex();
552 }
553
554 Waypt* FGRouteMgr::wayptAtIndex(int index) const
555 {
556   if (!_plan) {
557     throw sg_range_exception("wayptAtindex: no flightplan");
558   }
559   
560   return _plan->legAtIndex(index)->waypoint();
561 }
562
563 int FGRouteMgr::numLegs() const
564 {
565   if (_plan) {
566     return _plan->numLegs();
567   }
568   
569   return 0;
570 }
571
572 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance)
573 {
574   double speed = groundSpeed->getDoubleValue();
575   if (speed < 1.0) {
576     aProp->setStringValue("--:--");
577     return;
578   }
579
580   char eta_str[64];
581   double eta = aDistance * SG_METER_TO_NM / speed;
582   aProp->getChild("eta-seconds")->setIntValue( eta * 3600 );
583   if ( eta >= 100.0 ) { 
584       eta = 99.999; // clamp
585   }
586   
587   if ( eta < (1.0/6.0) ) {
588     eta *= 60.0; // within 10 minutes, bump up to min/secs
589   }
590   
591   int major = (int)eta, 
592       minor = (int)((eta - (int)eta) * 60.0);
593   snprintf( eta_str, 64, "%d:%02d", major, minor );
594   aProp->getChild("eta")->setStringValue( eta_str );
595 }
596
597 void FGRouteMgr::removeLegAtIndex(int aIndex)
598 {
599   if (!_plan) {
600     return;
601   }
602   
603   _plan->deleteIndex(aIndex);
604 }
605   
606 void FGRouteMgr::waypointsChanged()
607 {
608   update_mirror();
609   _edited->fireValueChanged();
610 }
611
612 // mirror internal route to the property system for inspection by other subsystems
613 void FGRouteMgr::update_mirror()
614 {
615   mirror->removeChildren("wp");
616   NewGUI * gui = (NewGUI *)globals->get_subsystem("gui");
617   FGDialog* rmDlg = gui ? gui->getDialog("route-manager") : NULL;
618
619   if (!_plan) {
620     mirror->setIntValue("num", 0);
621     if (rmDlg) {
622       rmDlg->updateValues();
623     }
624     return;
625   }
626   
627   int num = _plan->numLegs();
628     
629   for (int i = 0; i < num; i++) {
630     FlightPlan::Leg* leg = _plan->legAtIndex(i);
631     WayptRef wp = leg->waypoint();
632     SGPropertyNode *prop = mirror->getChild("wp", i, 1);
633
634     const SGGeod& pos(wp->position());
635     prop->setStringValue("id", wp->ident().c_str());
636     prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
637     prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
638    
639     // leg course+distance
640
641     prop->setDoubleValue("leg-bearing-true-deg", leg->courseDeg());
642     prop->setDoubleValue("leg-distance-nm", leg->distanceNm());
643     prop->setDoubleValue("distance-along-route-nm", leg->distanceAlongRoute());
644     
645     if (leg->altitudeRestriction() != RESTRICT_NONE) {
646       double ft = leg->altitudeFt();
647       prop->setDoubleValue("altitude-m", ft * SG_FEET_TO_METER);
648       prop->setDoubleValue("altitude-ft", ft);
649       prop->setIntValue("flight-level", static_cast<int>(ft / 1000) * 10);
650     } else {
651       prop->setDoubleValue("altitude-m", -9999.9);
652       prop->setDoubleValue("altitude-ft", -9999.9);
653     }
654     
655     if (leg->speedRestriction() == SPEED_RESTRICT_MACH) {
656       prop->setDoubleValue("speed-mach", leg->speedMach());
657     } else if (leg->speedRestriction() != RESTRICT_NONE) {
658       prop->setDoubleValue("speed-kts", leg->speedKts());
659     }
660     
661     if (wp->flag(WPT_ARRIVAL)) {
662       prop->setBoolValue("arrival", true);
663     }
664     
665     if (wp->flag(WPT_DEPARTURE)) {
666       prop->setBoolValue("departure", true);
667     }
668     
669     if (wp->flag(WPT_MISS)) {
670       prop->setBoolValue("missed-approach", true);
671     }
672     
673     prop->setBoolValue("generated", wp->flag(WPT_GENERATED));
674   } // of waypoint iteration
675   
676   // set number as listener attachment point
677   mirror->setIntValue("num", _plan->numLegs());
678     
679   if (rmDlg) {
680     rmDlg->updateValues();
681   }
682   
683   totalDistance->setDoubleValue(_plan->totalDistanceNm());
684 }
685
686 // command interface /autopilot/route-manager/input:
687 //
688 //   @CLEAR             ... clear route
689 //   @POP               ... remove first entry
690 //   @DELETE3           ... delete 4th entry
691 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
692 //   KSFO@900           ... append "KSFO@900"
693 //
694 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
695 {
696     const char *s = prop->getStringValue();
697     if (strlen(s) == 0) {
698       return;
699     }
700     
701     if (!strcmp(s, "@CLEAR"))
702         mgr->clearRoute();
703     else if (!strcmp(s, "@ACTIVATE"))
704         mgr->activate();
705     else if (!strcmp(s, "@LOAD")) {
706       SGPath path(mgr->_pathNode->getStringValue());
707       mgr->loadRoute(path);
708     } else if (!strcmp(s, "@SAVE")) {
709       SGPath path(mgr->_pathNode->getStringValue());
710       mgr->saveRoute(path);
711     } else if (!strcmp(s, "@NEXT")) {
712       mgr->jumpToIndex(mgr->currentIndex() + 1);
713     } else if (!strcmp(s, "@PREVIOUS")) {
714       mgr->jumpToIndex(mgr->currentIndex() - 1);
715     } else if (!strncmp(s, "@JUMP", 5)) {
716       mgr->jumpToIndex(atoi(s + 5));
717     } else if (!strncmp(s, "@DELETE", 7))
718         mgr->removeLegAtIndex(atoi(s + 7));
719     else if (!strncmp(s, "@INSERT", 7)) {
720         char *r;
721         int pos = strtol(s + 7, &r, 10);
722         if (*r++ != ':')
723             return;
724         while (isspace(*r))
725             r++;
726         if (*r)
727             mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(r), pos);
728     } else
729       mgr->flightPlan()->insertWayptAtIndex(mgr->waypointFromString(s), -1);
730 }
731
732 bool FGRouteMgr::activate()
733 {
734   if (!_plan) {
735     SG_LOG(SG_AUTOPILOT, SG_WARN, "::activate, no flight plan defined");
736     return false;
737   }
738   
739   if (isRouteActive()) {
740     SG_LOG(SG_AUTOPILOT, SG_WARN, "duplicate route-activation, no-op");
741     return false;
742   }
743  
744   _plan->setCurrentIndex(0);
745   active->setBoolValue(true);
746   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
747   return true;
748 }
749
750 void FGRouteMgr::deactivate()
751 {
752   if (!isRouteActive()) {
753     return;
754   }
755   
756   SG_LOG(SG_AUTOPILOT, SG_INFO, "deactivating flight plan");
757   active->setBoolValue(false);
758 }
759
760 void FGRouteMgr::jumpToIndex(int index)
761 {
762   if (!_plan) {
763     return;
764   }
765   
766   _plan->setCurrentIndex(index);
767 }
768
769 void FGRouteMgr::currentWaypointChanged()
770 {
771   Waypt* cur = currentWaypt();
772   FlightPlan::Leg* next = _plan ? _plan->nextLeg() : NULL;
773
774   wp0->getChild("id")->setStringValue(cur ? cur->ident() : "");
775   wp1->getChild("id")->setStringValue(next ? next->waypoint()->ident() : "");
776   
777   _currentWpt->fireValueChanged();
778   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << currentIndex());
779 }
780
781 const char* FGRouteMgr::getDepartureICAO() const
782 {
783   if (!_plan || !_plan->departureAirport()) {
784     return "";
785   }
786   
787   return _plan->departureAirport()->ident().c_str();
788 }
789
790 const char* FGRouteMgr::getDepartureName() const
791 {
792   if (!_plan || !_plan->departureAirport()) {
793     return "";
794   }
795   
796   return _plan->departureAirport()->name().c_str();
797 }
798
799 const char* FGRouteMgr::getDepartureRunway() const
800 {
801   if (_plan && _plan->departureRunway()) {
802     return _plan->departureRunway()->ident().c_str();
803   }
804   
805   return "";
806 }
807
808 void FGRouteMgr::setDepartureRunway(const char* aIdent)
809 {
810     if (!_plan) {
811         return;
812     }
813     
814   FGAirport* apt = _plan->departureAirport();
815   if (!apt || (aIdent == NULL)) {
816     _plan->setDeparture(apt);
817   } else if (apt->hasRunwayWithIdent(aIdent)) {
818     _plan->setDeparture(apt->getRunwayByIdent(aIdent));
819   }
820 }
821
822 void FGRouteMgr::setDepartureICAO(const char* aIdent)
823 {
824     if (!_plan) {
825         return;
826     }
827     
828   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
829     _plan->setDeparture((FGAirport*) NULL);
830   } else {
831     _plan->setDeparture(FGAirport::findByIdent(aIdent));
832   }
833 }
834
835 const char* FGRouteMgr::getSID() const
836 {
837   if (_plan && _plan->sid()) {
838     return _plan->sid()->ident().c_str();
839   }
840   
841   return "";
842 }
843
844 static double headingDiffDeg(double a, double b)
845 {
846   double rawDiff = b - a;
847   SG_NORMALIZE_RANGE(rawDiff, -180.0, 180.0);
848   return rawDiff;
849 }
850
851 flightgear::SID* createDefaultSID(FGRunway* aRunway, double enrouteCourse)
852 {
853   if (!aRunway) {
854     return NULL;
855   }
856   
857   double runwayElevFt = aRunway->end().getElevationFt();
858   WayptVec wpts;
859   std::ostringstream ss;
860   ss << aRunway->ident() << "-3";
861   
862   SGGeod p = aRunway->pointOnCenterline(aRunway->lengthM() + (3.0 * SG_NM_TO_METER));
863   WayptRef w = new BasicWaypt(p, ss.str(), NULL);
864   w->setAltitude(runwayElevFt + 3000.0, RESTRICT_AT);
865   wpts.push_back(w);
866   
867   ss.str("");
868   ss << aRunway->ident() << "-6";
869   p = aRunway->pointOnCenterline(aRunway->lengthM() + (6.0 * SG_NM_TO_METER));
870   w = new BasicWaypt(p, ss.str(), NULL);
871   w->setAltitude(runwayElevFt + 6000.0, RESTRICT_AT);
872   wpts.push_back(w);
873
874   if (enrouteCourse >= 0.0) {
875     // valid enroute course
876     int index = 3;
877     double course = aRunway->headingDeg();
878     double diff;
879     while (fabs(diff = headingDiffDeg(course, enrouteCourse)) > 45.0) {
880       // turn in the sign of the heading change 45 degrees
881       course += copysign(45.0, diff);
882       ss.str("");
883       ss << "DEP-" << index++;
884       SGGeod pos = wpts.back()->position();
885       pos = SGGeodesy::direct(pos, course, 3.0 * SG_NM_TO_METER);
886       w = new BasicWaypt(pos, ss.str(), NULL);
887       wpts.push_back(w);
888     }
889   } else {
890     // no enroute course, just keep runway heading
891     ss.str("");
892     ss << aRunway->ident() << "-9";
893     p = aRunway->pointOnCenterline(aRunway->lengthM() + (9.0 * SG_NM_TO_METER));
894     w = new BasicWaypt(p, ss.str(), NULL);
895     w->setAltitude(runwayElevFt + 9000.0, RESTRICT_AT);
896     wpts.push_back(w);
897   }
898   
899   BOOST_FOREACH(Waypt* w, wpts) {
900     w->setFlag(WPT_DEPARTURE);
901     w->setFlag(WPT_GENERATED);
902   }
903   
904   return flightgear::SID::createTempSID("DEFAULT", aRunway, wpts);
905 }
906
907 void FGRouteMgr::setSID(const char* aIdent)
908 {
909     if (!_plan) {
910         return;
911     }
912     
913   FGAirport* apt = _plan->departureAirport();
914   if (!apt || (aIdent == NULL)) {
915     _plan->setSID((flightgear::SID*) NULL);
916     return;
917   } 
918   
919   if (!strcmp(aIdent, "DEFAULT")) {
920     double enrouteCourse = -1.0;
921     if (_plan->destinationAirport()) {
922       enrouteCourse = SGGeodesy::courseDeg(apt->geod(), _plan->destinationAirport()->geod());
923     }
924     
925     _plan->setSID(createDefaultSID(_plan->departureRunway(), enrouteCourse));
926     return;
927   }
928   
929   string ident(aIdent);
930   size_t hyphenPos = ident.find('-');
931   if (hyphenPos != string::npos) {
932     string sidIdent = ident.substr(0, hyphenPos);
933     string transIdent = ident.substr(hyphenPos + 1);
934     
935     flightgear::SID* sid = apt->findSIDWithIdent(sidIdent);
936     Transition* trans = sid ? sid->findTransitionByName(transIdent) : NULL;
937     _plan->setSID(trans);
938   } else {
939     _plan->setSID(apt->findSIDWithIdent(aIdent));
940   }
941 }
942
943 const char* FGRouteMgr::getDestinationICAO() const
944 {
945   if (!_plan || !_plan->destinationAirport()) {
946     return "";
947   }
948   
949   return _plan->destinationAirport()->ident().c_str();
950 }
951
952 const char* FGRouteMgr::getDestinationName() const
953 {
954   if (!_plan || !_plan->destinationAirport()) {
955     return "";
956   }
957   
958   return _plan->destinationAirport()->name().c_str();
959 }
960
961 void FGRouteMgr::setDestinationICAO(const char* aIdent)
962 {
963     if (!_plan) {
964         return;
965     }
966     
967   if ((aIdent == NULL) || (strlen(aIdent) < 4)) {
968     _plan->setDestination((FGAirport*) NULL);
969   } else {
970     _plan->setDestination(FGAirport::findByIdent(aIdent));
971   }
972 }
973
974 const char* FGRouteMgr::getDestinationRunway() const
975 {
976   if (_plan && _plan->destinationRunway()) {
977     return _plan->destinationRunway()->ident().c_str();
978   }
979   
980   return "";
981 }
982
983 void FGRouteMgr::setDestinationRunway(const char* aIdent)
984 {
985     if (!_plan) {
986         return;
987     }
988     
989   FGAirport* apt = _plan->destinationAirport();
990   if (!apt || (aIdent == NULL)) {
991     _plan->setDestination(apt);
992   } else if (apt->hasRunwayWithIdent(aIdent)) {
993     _plan->setDestination(apt->getRunwayByIdent(aIdent));
994   }
995 }
996
997 const char* FGRouteMgr::getApproach() const
998 {
999   if (_plan && _plan->approach()) {
1000     return _plan->approach()->ident().c_str();
1001   }
1002   
1003   return "";
1004 }
1005
1006 flightgear::Approach* createDefaultApproach(FGRunway* aRunway, double aEnrouteCourse)
1007 {
1008   if (!aRunway) {
1009     return NULL;
1010   }
1011
1012   double thresholdElevFt = aRunway->threshold().getElevationFt();
1013   const double approachHeightFt = 2000.0;
1014   double glideslopeDistanceM = (approachHeightFt * SG_FEET_TO_METER) /
1015     tan(3.0 * SG_DEGREES_TO_RADIANS);
1016   
1017   std::ostringstream ss;
1018   ss << aRunway->ident() << "-12";
1019   WayptVec wpts;
1020   SGGeod p = aRunway->pointOnCenterline(-12.0 * SG_NM_TO_METER);
1021   WayptRef w = new BasicWaypt(p, ss.str(), NULL);
1022   w->setAltitude(thresholdElevFt + 4000, RESTRICT_AT);
1023   wpts.push_back(w);
1024
1025 // work back form the first point on the centerline
1026   
1027   if (aEnrouteCourse >= 0.0) {
1028     // valid enroute course
1029     int index = 4;
1030     double course = aRunway->headingDeg();
1031     double diff;
1032     while (fabs(diff = headingDiffDeg(aEnrouteCourse, course)) > 45.0) {
1033       // turn in the sign of the heading change 45 degrees
1034       course -= copysign(45.0, diff);
1035       ss.str("");
1036       ss << "APP-" << index++;
1037       SGGeod pos = wpts.front()->position();
1038       pos = SGGeodesy::direct(pos, course + 180.0, 3.0 * SG_NM_TO_METER);
1039       w = new BasicWaypt(pos, ss.str(), NULL);
1040       wpts.insert(wpts.begin(), w);
1041     }
1042   }
1043     
1044   p = aRunway->pointOnCenterline(-8.0 * SG_NM_TO_METER);
1045   ss.str("");
1046   ss << aRunway->ident() << "-8";
1047   w = new BasicWaypt(p, ss.str(), NULL);
1048   w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1049   wpts.push_back(w);
1050   
1051   p = aRunway->pointOnCenterline(-glideslopeDistanceM);    
1052   ss.str("");
1053   ss << aRunway->ident() << "-GS";
1054   w = new BasicWaypt(p, ss.str(), NULL);
1055   w->setAltitude(thresholdElevFt + approachHeightFt, RESTRICT_AT);
1056   wpts.push_back(w);
1057     
1058   BOOST_FOREACH(Waypt* w, wpts) {
1059     w->setFlag(WPT_APPROACH);
1060     w->setFlag(WPT_GENERATED);
1061   }
1062   
1063   return Approach::createTempApproach("DEFAULT", aRunway, wpts);
1064 }
1065
1066 void FGRouteMgr::setApproach(const char* aIdent)
1067 {
1068     if (!_plan) {
1069         return;
1070     }
1071     
1072   FGAirport* apt = _plan->destinationAirport();
1073   if (!strcmp(aIdent, "DEFAULT")) {
1074     double enrouteCourse = -1.0;
1075     if (_plan->departureAirport()) {
1076       enrouteCourse = SGGeodesy::courseDeg(_plan->departureAirport()->geod(), apt->geod());
1077     }
1078     
1079     _plan->setApproach(createDefaultApproach(_plan->destinationRunway(), enrouteCourse));
1080     return;
1081   }
1082   
1083   if (!apt || (aIdent == NULL)) {
1084     _plan->setApproach(NULL);
1085   } else {
1086     _plan->setApproach(apt->findApproachWithIdent(aIdent));
1087   }
1088 }
1089
1090 const char* FGRouteMgr::getSTAR() const
1091 {
1092   if (_plan && _plan->star()) {
1093     return _plan->star()->ident().c_str();
1094   }
1095   
1096   return "";
1097 }
1098
1099 void FGRouteMgr::setSTAR(const char* aIdent)
1100 {
1101     if (!_plan) {
1102         return;
1103     }
1104     
1105   FGAirport* apt = _plan->destinationAirport();
1106   if (!apt || (aIdent == NULL)) {
1107     _plan->setSTAR((STAR*) NULL);
1108     return;
1109   } 
1110   
1111   string ident(aIdent);
1112   size_t hyphenPos = ident.find('-');
1113   if (hyphenPos != string::npos) {
1114     string starIdent = ident.substr(0, hyphenPos);
1115     string transIdent = ident.substr(hyphenPos + 1);
1116     
1117     STAR* star = apt->findSTARWithIdent(starIdent);
1118     Transition* trans = star ? star->findTransitionByName(transIdent) : NULL;
1119     _plan->setSTAR(trans);
1120   } else {
1121     _plan->setSTAR(apt->findSTARWithIdent(aIdent));
1122   }
1123 }
1124
1125 WayptRef FGRouteMgr::waypointFromString(const std::string& target)
1126 {
1127   return _plan->waypointFromString(target);
1128 }
1129
1130 double FGRouteMgr::getDepartureFieldElevation() const
1131 {
1132   if (!_plan || !_plan->departureAirport()) {
1133     return 0.0;
1134   }
1135   
1136   return _plan->departureAirport()->elevation();
1137 }
1138
1139 double FGRouteMgr::getDestinationFieldElevation() const
1140 {
1141   if (!_plan || !_plan->destinationAirport()) {
1142     return 0.0;
1143   }
1144   
1145   return _plan->destinationAirport()->elevation();
1146 }
1147
1148 SGPropertyNode_ptr FGRouteMgr::wayptNodeAtIndex(int index) const
1149 {
1150   if ((index < 0) || (index >= numWaypts())) {
1151     throw sg_range_exception("waypt index out of range", "FGRouteMgr::wayptAtIndex");
1152   }
1153   
1154   return mirror->getChild("wp", index);
1155 }
1156
1157 bool FGRouteMgr::commandDefineUserWaypoint(const SGPropertyNode* arg)
1158 {
1159     std::string ident = arg->getStringValue("ident");
1160     if (ident.empty()) {
1161         SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident defining user waypoint");
1162         return false;
1163     }
1164     
1165     // check for duplicate idents
1166     FGPositioned::TypeFilter f(FGPositioned::WAYPOINT);
1167     FGPositionedList dups = FGPositioned::findAllWithIdent(ident, &f);
1168     if (!dups.empty()) {
1169         SG_LOG(SG_AUTOPILOT, SG_WARN, "defineUserWaypoint: non-unique waypoint identifier:" << ident);
1170         return false;
1171     }
1172
1173     SGGeod pos(SGGeod::fromDeg(arg->getDoubleValue("longitude-deg"),
1174                                arg->getDoubleValue("latitude-deg")));
1175     FGPositioned::createUserWaypoint(ident, pos);
1176     return true;
1177 }
1178
1179 bool FGRouteMgr::commandDeleteUserWaypoint(const SGPropertyNode* arg)
1180 {
1181     std::string ident = arg->getStringValue("ident");
1182     if (ident.empty()) {
1183         SG_LOG(SG_AUTOPILOT, SG_WARN, "missing ident deleting user waypoint");
1184         return false;
1185     }
1186     
1187     return FGPositioned::deleteUserWaypoint(ident);
1188 }
1189