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