]> git.mxchange.org Git - flightgear.git/blob - src/Autopilot/route_mgr.cxx
Better idents for waypoints defined by lon/lat.
[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
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/structure/exception.hxx>
42
43 #include <simgear/props/props_io.hxx>
44 #include <simgear/misc/sg_path.hxx>
45 #include <simgear/route/route.hxx>
46 #include <simgear/sg_inlines.h>
47
48 #include "Main/fg_props.hxx"
49 #include "Navaids/positioned.hxx"
50 #include "Airports/simple.hxx"
51 #include "Airports/runways.hxx"
52
53 #include "FDM/flight.hxx" // for getting ground speed
54
55 #define RM "/autopilot/route-manager/"
56
57 static double get_ground_speed() {
58   // starts in ft/s so we convert to kts
59   static const SGPropertyNode * speedup_node = fgGetNode("/sim/speed-up");
60
61   double ft_s = cur_fdm_state->get_V_ground_speed()
62       * speedup_node->getIntValue();
63   double kts = ft_s * SG_FEET_TO_METER * 3600 * SG_METER_TO_NM;
64   return kts;
65 }
66
67 FGRouteMgr::FGRouteMgr() :
68     _route( new SGRoute ),
69     input(fgGetNode( RM "input", true )),
70     mirror(fgGetNode( RM "route", true ))
71 {
72     listener = new InputListener(this);
73     input->setStringValue("");
74     input->addChangeListener(listener);
75 }
76
77
78 FGRouteMgr::~FGRouteMgr() {
79     input->removeChangeListener(listener);
80     
81     delete listener;
82     delete _route;
83 }
84
85
86 void FGRouteMgr::init() {
87   SGPropertyNode_ptr rm(fgGetNode(RM));
88   
89   lon = fgGetNode( "/position/longitude-deg", true );
90   lat = fgGetNode( "/position/latitude-deg", true );
91   alt = fgGetNode( "/position/altitude-ft", true );
92   magvar = fgGetNode("/environment/magnetic-variation-deg", true);
93      
94   departure = fgGetNode(RM "departure", true);
95 // init departure information from current location
96   SGGeod pos = SGGeod::fromDegFt(lon->getDoubleValue(), lat->getDoubleValue(), alt->getDoubleValue());
97   FGAirport* apt = FGAirport::findClosest(pos, 20.0);
98   if (apt) {
99     departure->setStringValue("airport", apt->ident().c_str());
100     FGRunway* active = apt->getActiveRunwayForUsage();
101     departure->setStringValue("runway", active->ident().c_str());
102   } else {
103     departure->setStringValue("airport", "");
104     departure->setStringValue("runway", "");
105   }
106   
107   departure->getChild("etd", 0, true);
108   departure->getChild("takeoff-time", 0, true);
109
110   destination = fgGetNode(RM "destination", true);
111   destination->getChild("airport", 0, true);
112   destination->getChild("runway", 0, true);
113   destination->getChild("eta", 0, true);
114   destination->getChild("touchdown-time", 0, true);
115   
116   alternate = fgGetNode(RM "alternate", true);
117   alternate->getChild("airport", 0, true);
118   alternate->getChild("runway", 0, true);
119   
120   cruise = fgGetNode(RM "cruise", true);
121   cruise->getChild("altitude-ft", 0, true);
122   cruise->setDoubleValue("altitude-ft", 10000.0);
123   cruise->getChild("flight-level", 0, true);
124   cruise->getChild("speed-kts", 0, true);
125   cruise->setDoubleValue("speed-kts", 160.0);
126   
127   totalDistance = fgGetNode(RM "total-distance", true);
128   totalDistance->setDoubleValue(0.0);
129   
130   ete = fgGetNode(RM "ete", true);
131   ete->setDoubleValue(0.0);
132   
133   elapsedFlightTime = fgGetNode(RM "flight-time", true);
134   elapsedFlightTime->setDoubleValue(0.0);
135   
136   active = fgGetNode(RM "active", true);
137   active->setBoolValue(false);
138   
139   airborne = fgGetNode(RM "airborne", true);
140   airborne->setBoolValue(false);
141     
142   _edited = fgGetNode(RM "signals/edited", true);
143   _finished = fgGetNode(RM "signals/finished", true);
144   
145   _currentWpt = fgGetNode(RM "current-wp", true);
146   _currentWpt->tie(SGRawValueMethods<FGRouteMgr, int>
147     (*this, &FGRouteMgr::currentWaypoint, &FGRouteMgr::jumpToIndex));
148       
149   // temporary distance / eta calculations, for backward-compatability
150   wp0 = fgGetNode(RM "wp", 0, true);
151   wp0->getChild("id", 0, true);
152   wp0->getChild("dist", 0, true);
153   wp0->getChild("eta", 0, true);
154   wp0->getChild("bearing-deg", 0, true);
155   
156   wp1 = fgGetNode(RM "wp", 1, true);
157   wp1->getChild("id", 0, true);
158   wp1->getChild("dist", 0, true);
159   wp1->getChild("eta", 0, true);
160   
161   wpn = fgGetNode(RM "wp-last", 0, true);
162   wpn->getChild("dist", 0, true);
163   wpn->getChild("eta", 0, true);
164   
165   _route->clear();
166   update_mirror();
167   
168   _pathNode = fgGetNode(RM "file-path", 0, true);
169 }
170
171
172 void FGRouteMgr::postinit() {
173     string_list *waypoints = globals->get_initial_waypoints();
174     if (waypoints) {
175       vector<string>::iterator it;
176       for (it = waypoints->begin(); it != waypoints->end(); ++it)
177         new_waypoint(*it);
178     }
179
180     weightOnWheels = fgGetNode("/gear/gear[0]/wow", false);
181     // check airbone flag agrees with presets
182     
183 }
184
185
186 void FGRouteMgr::bind() { }
187 void FGRouteMgr::unbind() { }
188
189 bool FGRouteMgr::isRouteActive() const
190 {
191   return active->getBoolValue();
192 }
193
194 void FGRouteMgr::update( double dt ) {
195     if (dt <= 0.0) {
196       // paused, nothing to do here
197       return;
198     }
199   
200     if (!active->getBoolValue()) {
201       return;
202     }
203     
204     double groundSpeed = get_ground_speed();
205     if (airborne->getBoolValue()) {
206       time_t now = time(NULL);
207       elapsedFlightTime->setDoubleValue(difftime(now, _takeoffTime));
208     } else { // not airborne
209       if (weightOnWheels->getBoolValue() || (groundSpeed < 40)) {
210         return;
211       }
212       
213       airborne->setBoolValue(true);
214       _takeoffTime = time(NULL); // start the clock
215       departure->setIntValue("takeoff-time", _takeoffTime);
216     }
217     
218   // basic course/distance information
219     double wp_course, wp_distance;
220     SGWayPoint wp = _route->get_current();
221     wp.CourseAndDistance( lon->getDoubleValue(), lat->getDoubleValue(),
222                           alt->getDoubleValue(), &wp_course, &wp_distance );
223
224   // update wp0 / wp1 / wp-last for legacy users
225     wp0->setDoubleValue("dist", wp_distance * SG_METER_TO_NM);
226     wp_course -= magvar->getDoubleValue(); // expose magnetic bearing
227     wp0->setDoubleValue("bearing-deg", wp_course);
228     setETAPropertyFromDistance(wp0->getChild("eta"), wp_distance);
229     
230     if ((_route->current_index() + 1) < _route->size()) {
231       wp = _route->get_waypoint(_route->current_index() + 1);
232       double wp1_course, wp1_distance;
233       wp.CourseAndDistance(lon->getDoubleValue(), lat->getDoubleValue(),
234                           alt->getDoubleValue(), &wp1_course, &wp1_distance);
235     
236       wp1->setDoubleValue("dist", wp1_distance * SG_METER_TO_NM);
237       setETAPropertyFromDistance(wp1->getChild("eta"), wp1_distance);
238     }
239     
240     double totalDistanceRemaining = wp_distance; // distance to current waypoint
241     for (int i=_route->current_index() + 1; i<_route->size(); ++i) {
242       totalDistanceRemaining += _route->get_waypoint(i).get_distance();
243     }
244     
245     wpn->setDoubleValue("dist", totalDistanceRemaining * SG_METER_TO_NM);
246     ete->setDoubleValue(totalDistanceRemaining * SG_METER_TO_NM / groundSpeed * 3600.0);
247     setETAPropertyFromDistance(wpn->getChild("eta"), totalDistanceRemaining);
248     
249     // get time now at destination tz as tm struct
250     // add ete seconds
251     // convert to string ... and stash in property
252     //destination->setDoubleValue("eta", eta);
253 }
254
255
256 void FGRouteMgr::setETAPropertyFromDistance(SGPropertyNode_ptr aProp, double aDistance) {
257     double speed = get_ground_speed();
258     if (speed < 1.0) {
259       aProp->setStringValue("--:--");
260       return;
261     }
262   
263     char eta_str[64];
264     double eta = aDistance * SG_METER_TO_NM / get_ground_speed();
265     if ( eta >= 100.0 ) { 
266         eta = 99.999; // clamp
267     }
268     
269     if ( eta < (1.0/6.0) ) {
270       eta *= 60.0; // within 10 minutes, bump up to min/secs
271     }
272     
273     int major = (int)eta, 
274         minor = (int)((eta - (int)eta) * 60.0);
275     snprintf( eta_str, 64, "%d:%02d", major, minor );
276     aProp->setStringValue( eta_str );
277 }
278
279 void FGRouteMgr::add_waypoint( const SGWayPoint& wp, int n ) {
280   _route->add_waypoint( wp, n );
281     
282   if (_route->current_index() > n) {
283     _route->set_current(_route->current_index() + 1);
284   }
285   
286   update_mirror();
287   _edited->fireValueChanged();
288 }
289
290
291 SGWayPoint FGRouteMgr::pop_waypoint( int n ) {
292   if ( _route->size() <= 0 ) {
293     return SGWayPoint();
294   }
295   
296   if ( n < 0 ) {
297     n = _route->size() - 1;
298   }
299   
300   if (_route->current_index() > n) {
301     _route->set_current(_route->current_index() - 1);
302   }
303
304   SGWayPoint wp = _route->get_waypoint(n);
305   _route->delete_waypoint(n);
306     
307   update_mirror();
308   _edited->fireValueChanged();
309   checkFinished();
310   
311   return wp;
312 }
313
314
315 bool FGRouteMgr::build() {
316     return true;
317 }
318
319
320 void FGRouteMgr::new_waypoint( const string& target, int n ) {
321     SGWayPoint* wp = make_waypoint( target );
322     if (!wp) {
323         return;
324     }
325     
326     add_waypoint( *wp, n );
327     delete wp;
328 }
329
330
331 SGWayPoint* FGRouteMgr::make_waypoint(const string& tgt ) {
332     string target(boost::to_upper_copy(tgt));
333     
334     // extract altitude
335     double alt = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
336     
337     size_t pos = target.find( '@' );
338     if ( pos != string::npos ) {
339         alt = atof( target.c_str() + pos + 1 );
340         target = target.substr( 0, pos );
341         if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
342             alt *= SG_FEET_TO_METER;
343     }
344
345     // check for lon,lat
346     pos = target.find( ',' );
347     if ( pos != string::npos ) {
348         double lon = atof( target.substr(0, pos).c_str());
349         double lat = atof( target.c_str() + pos + 1);
350         char buf[32];
351         char ew = (lon < 0.0) ? 'W' : 'E';
352         char ns = (lat < 0.0) ? 'S' : 'N';
353         snprintf(buf, 32, "%c%03d%c%03d", ew, (int) fabs(lon), ns, (int)fabs(lat));
354         return new SGWayPoint( lon, lat, alt, SGWayPoint::WGS84, buf);
355     }    
356
357     SGGeod basePosition;
358     if (_route->size() > 0) {
359         SGWayPoint wp = get_waypoint(_route->size()-1);
360         basePosition = wp.get_target();
361     } else {
362         // route is empty, use current position
363         basePosition = SGGeod::fromDeg(
364             fgGetNode("/position/longitude-deg")->getDoubleValue(), 
365             fgGetNode("/position/latitude-deg")->getDoubleValue());
366     }
367     
368     vector<string> pieces(simgear::strutils::split(target, "/"));
369
370
371     FGPositionedRef p = FGPositioned::findClosestWithIdent(pieces.front(), basePosition);
372     if (!p) {
373       SG_LOG( SG_AUTOPILOT, SG_INFO, "Unable to find FGPositioned with ident:" << pieces.front());
374       return NULL;
375     }
376     
377     SGGeod geod = SGGeod::fromGeodM(p->geod(), alt);
378     if (pieces.size() == 1) {
379       // simple case
380       return new SGWayPoint(geod, target, p->name());
381     }
382         
383     if (pieces.size() == 3) {
384       // navaid/radial/distance-nm notation
385       double radial = atof(pieces[1].c_str()),
386         distanceNm = atof(pieces[2].c_str()),
387         az2;
388       radial += magvar->getDoubleValue(); // convert to true bearing
389       SGGeod offsetPos;
390       SGGeodesy::direct(geod, radial, distanceNm * SG_NM_TO_METER, offsetPos, az2);
391       offsetPos.setElevationM(alt);
392       
393       SG_LOG(SG_AUTOPILOT, SG_INFO, "final offset radial is " << radial);
394       return new SGWayPoint(offsetPos, p->ident() + pieces[2], target);
395     }
396     
397     if (pieces.size() == 2) {
398       FGAirport* apt = dynamic_cast<FGAirport*>(p.ptr());
399       if (!apt) {
400         SG_LOG(SG_AUTOPILOT, SG_INFO, "Waypoint is not an airport:" << pieces.front());
401         return NULL;
402       }
403       
404       if (!apt->hasRunwayWithIdent(pieces[1])) {
405         SG_LOG(SG_AUTOPILOT, SG_INFO, "No runway: " << pieces[1] << " at " << pieces[0]);
406         return NULL;
407       }
408       
409       FGRunway* runway = apt->getRunwayByIdent(pieces[1]);
410       SGGeod t = runway->threshold();
411       return new SGWayPoint(t.getLongitudeDeg(), t.getLatitudeDeg(), alt, SGWayPoint::WGS84, pieces[1]);
412     }
413     
414     SG_LOG(SG_AUTOPILOT, SG_INFO, "Unable to parse waypoint:" << target);
415     return NULL;
416 }
417
418
419 // mirror internal route to the property system for inspection by other subsystems
420 void FGRouteMgr::update_mirror() {
421     mirror->removeChildren("wp");
422     for (int i = 0; i < _route->size(); i++) {
423         SGWayPoint wp = _route->get_waypoint(i);
424         SGPropertyNode *prop = mirror->getChild("wp", i, 1);
425
426         const SGGeod& pos(wp.get_target());
427         prop->setStringValue("id", wp.get_id().c_str());
428         prop->setStringValue("name", wp.get_name().c_str());
429         prop->setDoubleValue("longitude-deg", pos.getLongitudeDeg());
430         prop->setDoubleValue("latitude-deg",pos.getLatitudeDeg());
431         prop->setDoubleValue("altitude-m", pos.getElevationM());
432         prop->setDoubleValue("altitude-ft", pos.getElevationFt());
433     }
434     // set number as listener attachment point
435     mirror->setIntValue("num", _route->size());
436 }
437
438 // command interface /autopilot/route-manager/input:
439 //
440 //   @CLEAR             ... clear route
441 //   @POP               ... remove first entry
442 //   @DELETE3           ... delete 4th entry
443 //   @INSERT2:KSFO@900  ... insert "KSFO@900" as 3rd entry
444 //   KSFO@900           ... append "KSFO@900"
445 //
446 void FGRouteMgr::InputListener::valueChanged(SGPropertyNode *prop)
447 {
448     const char *s = prop->getStringValue();
449     if (!strcmp(s, "@CLEAR"))
450         mgr->init();
451     else if (!strcmp(s, "@ACTIVATE"))
452         mgr->activate();
453     else if (!strcmp(s, "@LOAD")) {
454       mgr->loadRoute();
455     } else if (!strcmp(s, "@SAVE")) {
456       mgr->saveRoute();
457     } else if (!strcmp(s, "@POP"))
458         mgr->pop_waypoint(0);
459     else if (!strncmp(s, "@DELETE", 7))
460         mgr->pop_waypoint(atoi(s + 7));
461     else if (!strncmp(s, "@INSERT", 7)) {
462         char *r;
463         int pos = strtol(s + 7, &r, 10);
464         if (*r++ != ':')
465             return;
466         while (isspace(*r))
467             r++;
468         if (*r)
469             mgr->new_waypoint(r, pos);
470     } else
471         mgr->new_waypoint(s);
472 }
473
474 //    SGWayPoint( const double lon = 0.0, const double lat = 0.0,
475 //              const double alt = 0.0, const modetype m = WGS84,
476 //              const string& s = "", const string& n = "" );
477
478 bool FGRouteMgr::activate()
479 {
480   const FGAirport* depApt = fgFindAirportID(departure->getStringValue("airport"));
481   if (depApt) {
482     string runwayId(departure->getStringValue("runway"));
483     FGRunway* runway = NULL;
484     if (depApt->hasRunwayWithIdent(runwayId)) {
485       runway = depApt->getRunwayByIdent(runwayId);
486     } else {
487       SG_LOG(SG_AUTOPILOT, SG_INFO, 
488         "route-manager, departure runway not found:" << runwayId);
489       runway = depApt->getActiveRunwayForUsage();
490     }
491     
492     SGWayPoint swp(runway->threshold(), 
493       depApt->ident() + "-" + runway->ident(), runway->name());
494     add_waypoint(swp, 0);
495   }
496   
497   const FGAirport* destApt = fgFindAirportID(destination->getStringValue("airport"));
498   if (destApt) {
499     string runwayId = (destination->getStringValue("runway"));
500     if (destApt->hasRunwayWithIdent(runwayId)) {
501       FGRunway* runway = destApt->getRunwayByIdent(runwayId);
502       SGWayPoint swp(runway->end(), 
503         destApt->ident() + "-" + runway->ident(), runway->name());
504       add_waypoint(swp);
505     } else {
506       // quite likely, since destination runway may not be known until enroute
507       // probably want a listener on the 'destination' node to allow an enroute
508       // update
509       add_waypoint(SGWayPoint(destApt->geod(), destApt->ident(), destApt->name()));
510     }
511   }
512
513   _route->set_current(0);
514   
515   double routeDistanceNm = _route->total_distance() * SG_METER_TO_NM;
516   totalDistance->setDoubleValue(routeDistanceNm);
517   double cruiseSpeedKts = cruise->getDoubleValue("speed", 0.0);
518   if (cruiseSpeedKts > 1.0) {
519     // very very crude approximation, doesn't allow for climb / descent
520     // performance or anything else at all
521     ete->setDoubleValue(routeDistanceNm / cruiseSpeedKts * (60.0 * 60.0));
522   }
523   
524   active->setBoolValue(true);
525   SG_LOG(SG_AUTOPILOT, SG_INFO, "route-manager, activate route ok");
526   return true;
527 }
528
529
530 void FGRouteMgr::sequence()
531 {
532   if (!active->getBoolValue()) {
533     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
534     return;
535   }
536   
537   if (checkFinished()) {
538     return;
539   }
540   
541   _route->increment_current();
542   currentWaypointChanged();
543   _currentWpt->fireValueChanged();
544 }
545
546 bool FGRouteMgr::checkFinished()
547 {
548   int lastWayptIndex = _route->size() - 1;
549   if (_route->current_index() < lastWayptIndex) {
550     return false;
551   }
552   
553   SG_LOG(SG_AUTOPILOT, SG_INFO, "reached end of active route");
554   _finished->fireValueChanged();
555   active->setBoolValue(false);
556   return true;
557 }
558
559 void FGRouteMgr::jumpToIndex(int index)
560 {
561   if (!active->getBoolValue()) {
562     SG_LOG(SG_AUTOPILOT, SG_ALERT, "trying to sequence waypoints with no active route");
563     return;
564   }
565
566   if ((index < 0) || (index >= _route->size())) {
567     SG_LOG(SG_AUTOPILOT, SG_ALERT, "passed invalid index (" << 
568       index << ") to FGRouteMgr::jumpToIndex");
569     return;
570   }
571
572   if (_route->current_index() == index) {
573     return; // no-op
574   }
575   
576   _route->set_current(index);
577   currentWaypointChanged();
578 }
579
580 void FGRouteMgr::currentWaypointChanged()
581 {
582   SGWayPoint previous = _route->get_previous();
583   SGWayPoint cur = _route->get_current();
584   
585   wp0->getChild("id")->setStringValue(cur.get_id());
586   if ((_route->current_index() + 1) < _route->size()) {
587     wp1->getChild("id")->setStringValue(_route->get_next().get_id());
588   } else {
589     wp1->getChild("id")->setStringValue("");
590   }
591   
592   SG_LOG(SG_AUTOPILOT, SG_INFO, "route manager, current-wp is now " << _route->current_index());
593 }
594
595 int FGRouteMgr::findWaypoint(const SGGeod& aPos) const
596 {  
597   for (int i=0; i<_route->size(); ++i) {
598     double d = SGGeodesy::distanceM(aPos, _route->get_waypoint(i).get_target());
599     if (d < 200.0) { // 200 metres seems close enough
600       return i;
601     }
602   }
603   
604   return -1;
605 }
606
607 SGWayPoint FGRouteMgr::get_waypoint( int i ) const
608 {
609   return _route->get_waypoint(i);
610 }
611
612 int FGRouteMgr::size() const
613 {
614   return _route->size();
615 }
616
617 int FGRouteMgr::currentWaypoint() const
618 {
619   return _route->current_index();
620 }
621
622 void FGRouteMgr::saveRoute()
623 {
624   SGPath path(_pathNode->getStringValue());
625   SG_LOG(SG_IO, SG_INFO, "Saving route to " << path.str());
626   try {
627     writeProperties(path.str(), mirror, false, SGPropertyNode::ARCHIVE);
628   } catch (const sg_exception &e) {
629     SG_LOG(SG_IO, SG_WARN, "Error saving route:" << e.getMessage());
630     //guiErrorMessage("Error writing autosave.xml: ", e);
631   }
632 }
633
634 void FGRouteMgr::loadRoute()
635 {
636   try {
637     // deactivate route first
638     active->setBoolValue(false);
639     
640     SGPropertyNode_ptr routeData(new SGPropertyNode);
641     SGPath path(_pathNode->getStringValue());
642     
643     SG_LOG(SG_IO, SG_INFO, "going to read flight-plan from:" << path.str());
644     readProperties(path.str(), routeData);
645     
646   // departure nodes
647     SGPropertyNode* dep = routeData->getChild("departure");
648     if (!dep) {
649       throw sg_io_exception("malformed route file, no departure node");
650     }
651     
652     string depIdent = dep->getStringValue("airport");
653     const FGAirport* depApt = fgFindAirportID(depIdent);
654     if (!depApt) {
655       throw sg_io_exception("bad route file, unknown airport:" + depIdent);
656     }
657     
658     departure->setStringValue("runway", dep->getStringValue("runway"));
659     
660   // destination
661     SGPropertyNode* dst = routeData->getChild("destination");
662     if (!dst) {
663       throw sg_io_exception("malformed route file, no destination node");
664     }
665     
666     destination->setStringValue("airport", dst->getStringValue("airport"));
667     destination->setStringValue("runay", dst->getStringValue("runway"));
668
669   // alternate
670     SGPropertyNode* alt = routeData->getChild("alternate");
671     if (alt) {
672       alternate->setStringValue(alt->getStringValue("airport"));
673     } // of cruise data loading
674     
675   // cruise
676     SGPropertyNode* crs = routeData->getChild("cruise");
677     if (crs) {
678       cruise->setDoubleValue(crs->getDoubleValue("speed"));
679     } // of cruise data loading
680
681   // route nodes
682     _route->clear();
683     SGPropertyNode_ptr _route = routeData->getChild("route", 0);
684     SGGeod lastPos(depApt->geod());
685     
686     for (int i=0; i<_route->nChildren(); ++i) {
687       SGPropertyNode_ptr wp = _route->getChild("wp", i);
688       parseRouteWaypoint(wp);
689     } // of route iteration
690   } catch (sg_exception& e) {
691     SG_LOG(SG_IO, SG_WARN, "failed to load flight-plan (from '" << e.getOrigin()
692       << "'):" << e.getMessage());
693   }
694 }
695
696 void FGRouteMgr::parseRouteWaypoint(SGPropertyNode* aWP)
697 {
698   SGGeod lastPos;
699   if (_route->size() > 0) {
700     lastPos = get_waypoint(_route->size()-1).get_target();
701   } else {
702     // route is empty, use departure airport position
703     const FGAirport* apt = fgFindAirportID(departure->getStringValue("airport"));
704     assert(apt); // shouldn't have got this far with an invalid airport
705     lastPos = apt->geod();
706   }
707
708   SGPropertyNode_ptr altProp = aWP->getChild("altitude-ft");
709   double alt = cruise->getDoubleValue("altitude-ft") * SG_FEET_TO_METER;
710   if (altProp) {
711     alt = altProp->getDoubleValue();
712   }
713       
714   string ident(aWP->getStringValue("ident"));
715   if (aWP->hasChild("longitude-deg")) {
716     // explicit longitude/latitude
717     SGWayPoint swp(aWP->getDoubleValue("longitude-deg"),
718       aWP->getDoubleValue("latitude-deg"), alt, 
719       SGWayPoint::WGS84, ident, aWP->getStringValue("name"));
720     add_waypoint(swp);
721   } else if (aWP->hasChild("navid")) {
722     // lookup by navid (possibly with offset)
723     string nid(aWP->getStringValue("navid"));
724     FGPositionedRef p = FGPositioned::findClosestWithIdent(nid, lastPos);
725     if (!p) {
726       throw sg_io_exception("bad route file, unknown navid:" + nid);
727     }
728     
729     SGGeod pos(p->geod());
730     if (aWP->hasChild("offset-nm") && aWP->hasChild("offset-radial")) {
731       double radialDeg = aWP->getDoubleValue("offset-radial");
732       // convert magnetic radial to a true radial!
733       radialDeg += magvar->getDoubleValue();
734       double offsetNm = aWP->getDoubleValue("offset-nm");
735       double az2;
736       SGGeodesy::direct(p->geod(), radialDeg, offsetNm * SG_NM_TO_METER, pos, az2);
737     }
738     
739     SGWayPoint swp(pos.getLongitudeDeg(), pos.getLatitudeDeg(), alt, 
740       SGWayPoint::WGS84, ident, "");
741     add_waypoint(swp);
742   } else {
743     // lookup by ident (symbolic waypoint)
744     FGPositionedRef p = FGPositioned::findClosestWithIdent(ident, lastPos);
745     if (!p) {
746       throw sg_io_exception("bad route file, unknown waypoint:" + ident);
747     }
748     
749     SGWayPoint swp(p->longitude(), p->latitude(), alt, 
750       SGWayPoint::WGS84, p->ident(), p->name());
751     add_waypoint(swp);
752   }
753 }