]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
f7ba6fbb5b66df9dcc6badec86edbaca6d677792
[flightgear.git] / src / Instrumentation / navradio.cxx
1 // navradio.cxx -- class to manage a nav radio instance
2 //
3 // Written by Curtis Olson, started April 2000.
4 //
5 // Copyright (C) 2000 - 2002  Curtis L. Olson - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <iostream>
29 #include <string>
30 #include <sstream>
31
32 #include <simgear/compiler.h>
33 #include <simgear/sg_inlines.h>
34 #include <simgear/math/sg_random.h>
35 #include <simgear/math/vector.hxx>
36
37 #include <Aircraft/aircraft.hxx>
38 #include <Navaids/navlist.hxx>
39
40 #include "navradio.hxx"
41
42 #include <string>
43 SG_USING_STD(string);
44
45
46 // Constructor
47 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
48     lon_node(fgGetNode("/position/longitude-deg", true)),
49     lat_node(fgGetNode("/position/latitude-deg", true)),
50     alt_node(fgGetNode("/position/altitude-ft", true)),
51     power_btn_node(NULL),
52     freq_node(NULL),
53     alt_freq_node(NULL),
54     fmt_freq_node(NULL),
55     fmt_alt_freq_node(NULL),
56     sel_radial_node(NULL),
57     vol_btn_node(NULL),
58     ident_btn_node(NULL),
59     audio_btn_node(NULL),
60     nav_serviceable_node(NULL),
61     cdi_serviceable_node(NULL),
62     gs_serviceable_node(NULL),
63     tofrom_serviceable_node(NULL),
64     heading_node(NULL),
65     radial_node(NULL),
66     recip_radial_node(NULL),
67     target_radial_true_node(NULL),
68     target_auto_hdg_node(NULL),
69     time_to_intercept(NULL),
70     to_flag_node(NULL),
71     from_flag_node(NULL),
72     inrange_node(NULL),
73     cdi_deflection_node(NULL),
74     cdi_xtrack_error_node(NULL),
75     cdi_xtrack_hdg_err_node(NULL),
76     has_gs_node(NULL),
77     loc_node(NULL),
78     loc_dist_node(NULL),
79     gs_deflection_node(NULL),
80     gs_rate_of_climb_node(NULL),
81     gs_dist_node(NULL),
82     nav_id_node(NULL),
83     id_c1_node(NULL),
84     id_c2_node(NULL),
85     id_c3_node(NULL),
86     id_c4_node(NULL),
87     nav_slaved_to_gps_node(NULL),
88     gps_cdi_deflection_node(NULL),
89     gps_to_flag_node(NULL),
90     gps_from_flag_node(NULL),
91     last_nav_id(""),
92     last_nav_vor(false),
93     play_count(0),
94     last_time(0),
95     radial(0.0),
96     target_radial(0.0),
97     horiz_vel(0.0),
98     last_x(0.0),
99     last_loc_dist(0.0),
100     last_xtrack_error(0.0),
101     name("nav"),
102     num(0),
103     _time_before_search_sec(-1.0)
104 {
105     SGPath path( globals->get_fg_root() );
106     SGPath term = path;
107     term.append( "Navaids/range.term" );
108     SGPath low = path;
109     low.append( "Navaids/range.low" );
110     SGPath high = path;
111     high.append( "Navaids/range.high" );
112
113     term_tbl = new SGInterpTable( term.str() );
114     low_tbl = new SGInterpTable( low.str() );
115     high_tbl = new SGInterpTable( high.str() );
116
117     int i;
118     for ( i = 0; i < node->nChildren(); ++i ) {
119         SGPropertyNode *child = node->getChild(i);
120         string cname = child->getName();
121         string cval = child->getStringValue();
122         if ( cname == "name" ) {
123             name = cval;
124         } else if ( cname == "number" ) {
125             num = child->getIntValue();
126         } else {
127             SG_LOG( SG_INSTR, SG_WARN, 
128                     "Error in nav radio config logic" );
129             if ( name.length() ) {
130                 SG_LOG( SG_INSTR, SG_WARN, "Section = " << name );
131             }
132         }
133     }
134
135 }
136
137
138 // Destructor
139 FGNavRadio::~FGNavRadio() 
140 {
141     delete term_tbl;
142     delete low_tbl;
143     delete high_tbl;
144 }
145
146
147 void
148 FGNavRadio::init ()
149 {
150     morse.init();
151
152     string branch;
153     branch = "/instrumentation/" + name;
154
155     SGPropertyNode *node = fgGetNode(branch.c_str(), num, true );
156
157     bus_power_node = 
158         fgGetNode(("/systems/electrical/outputs/" + name).c_str(), true);
159
160     // inputs
161     power_btn_node = node->getChild("power-btn", 0, true);
162     power_btn_node->setBoolValue( true );
163     vol_btn_node = node->getChild("volume", 0, true);
164     ident_btn_node = node->getChild("ident", 0, true);
165     ident_btn_node->setBoolValue( true );
166     audio_btn_node = node->getChild("audio-btn", 0, true);
167     audio_btn_node->setBoolValue( true );
168     nav_serviceable_node = node->getChild("serviceable", 0, true);
169     cdi_serviceable_node = (node->getChild("cdi", 0, true))
170         ->getChild("serviceable", 0, true);
171     gs_serviceable_node = (node->getChild("gs", 0, true))
172         ->getChild("serviceable");
173     tofrom_serviceable_node = (node->getChild("to-from", 0, true))
174         ->getChild("serviceable", 0, true);
175
176     // frequencies
177     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
178     freq_node = subnode->getChild("selected-mhz", 0, true);
179     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
180     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
181     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
182
183     // radials
184     subnode = node->getChild("radials", 0, true);
185     sel_radial_node = subnode->getChild("selected-deg", 0, true);
186     radial_node = subnode->getChild("actual-deg", 0, true);
187     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
188     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
189     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
190
191     // outputs
192     heading_node = node->getChild("heading-deg", 0, true);
193     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
194     to_flag_node = node->getChild("to-flag", 0, true);
195     from_flag_node = node->getChild("from-flag", 0, true);
196     inrange_node = node->getChild("in-range", 0, true);
197     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
198     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
199     cdi_xtrack_hdg_err_node
200         = node->getChild("crosstrack-heading-error-deg", 0, true);
201     has_gs_node = node->getChild("has-gs", 0, true);
202     loc_node = node->getChild("nav-loc", 0, true);
203     loc_dist_node = node->getChild("nav-distance", 0, true);
204     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
205     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
206     gs_dist_node = node->getChild("gs-distance", 0, true);
207     nav_id_node = node->getChild("nav-id", 0, true);
208     id_c1_node = node->getChild("nav-id_asc1", 0, true);
209     id_c2_node = node->getChild("nav-id_asc2", 0, true);
210     id_c3_node = node->getChild("nav-id_asc3", 0, true);
211     id_c4_node = node->getChild("nav-id_asc4", 0, true);
212
213     // gps slaving support
214     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
215     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
216     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
217     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
218     
219     std::ostringstream temp;
220     temp << name << "nav-ident" << num;
221     nav_fx_name = temp.str();
222     temp << name << "dme-ident" << num;
223     dme_fx_name = temp.str();
224 }
225
226 void
227 FGNavRadio::bind ()
228 {
229     std::ostringstream temp;
230     string branch;
231     temp << num;
232     branch = "/instrumentation/" + name + "[" + temp.str() + "]";
233 }
234
235
236 void
237 FGNavRadio::unbind ()
238 {
239     std::ostringstream temp;
240     string branch;
241     temp << num;
242     branch = "/instrumentation/" + name + "[" + temp.str() + "]";
243 }
244
245
246 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
247 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
248                                  double nominalRange )
249 {
250     // extend out actual usable range to be 1.3x the published safe range
251     const double usability_factor = 1.3;
252
253     // assumptions we model the standard service volume, plus
254     // ... rather than specifying a cylinder, we model a cone that
255     // contains the cylinder.  Then we put an upside down cone on top
256     // to model diminishing returns at too-high altitudes.
257
258     // altitude difference
259     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
260     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
261     //      << " station elev = " << stationElev << endl;
262
263     if ( nominalRange < 25.0 + SG_EPSILON ) {
264         // Standard Terminal Service Volume
265         return term_tbl->interpolate( alt ) * usability_factor;
266     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
267         // Standard Low Altitude Service Volume
268         // table is based on range of 40, scale to actual range
269         return low_tbl->interpolate( alt ) * nominalRange / 40.0
270             * usability_factor;
271     } else {
272         // Standard High Altitude Service Volume
273         // table is based on range of 130, scale to actual range
274         return high_tbl->interpolate( alt ) * nominalRange / 130.0
275             * usability_factor;
276     }
277 }
278
279
280 // model standard ILS service volumes as per AIM 1-1-9
281 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
282                                  double offsetDegrees, double distance )
283 {
284     // assumptions we model the standard service volume, plus
285
286     // altitude difference
287     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
288 //     double offset = fabs( offsetDegrees );
289
290 //     if ( offset < 10 ) {
291 //      return FG_ILS_DEFAULT_RANGE;
292 //     } else if ( offset < 35 ) {
293 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
294 //     } else if ( offset < 45 ) {
295 //      return (45 - offset);
296 //     } else if ( offset > 170 ) {
297 //         return FG_ILS_DEFAULT_RANGE;
298 //     } else if ( offset > 145 ) {
299 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
300 //     } else if ( offset > 135 ) {
301 //         return (offset - 135);
302 //     } else {
303 //      return 0;
304 //     }
305     return FG_LOC_DEFAULT_RANGE;
306 }
307
308
309 //////////////////////////////////////////////////////////////////////////
310 // Update the various nav values based on position and valid tuned in navs
311 //////////////////////////////////////////////////////////////////////////
312 void 
313 FGNavRadio::update(double dt) 
314 {
315     // cache a few strategic values locally for speed
316     double lon = lon_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
317     double lat = lat_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
318     double elev = alt_node->getDoubleValue() * SG_FEET_TO_METER;
319     bool power_btn = power_btn_node->getBoolValue();
320     bool nav_serviceable = nav_serviceable_node->getBoolValue();
321     bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
322     bool tofrom_serviceable = tofrom_serviceable_node->getBoolValue();
323     bool inrange = inrange_node->getBoolValue();
324     bool has_gs = has_gs_node->getBoolValue();
325     bool is_loc = loc_node->getBoolValue();
326     double loc_dist = loc_dist_node->getDoubleValue();
327
328     Point3D aircraft = sgGeodToCart( Point3D( lon, lat, elev ) );
329     Point3D station;
330     double az1, az2, s;
331
332     // Create "formatted" versions of the nav frequencies for
333     // instrument displays.
334     char tmp[16];
335     sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
336     fmt_freq_node->setStringValue(tmp);
337     sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
338     fmt_alt_freq_node->setStringValue(tmp);
339
340     // Do a nav station search only once a second to reduce
341     // unnecessary work.
342     _time_before_search_sec -= dt;
343     if ( _time_before_search_sec < 0 ) {
344         search();
345     }
346
347     // cout << "is_valid = " << is_valid
348     //      << " power_btn = " << power_btn
349     //      << " bus_power = " << bus_power_node->getDoubleValue()
350     //      << " nav_serviceable = " << nav_serviceable
351     //      << endl;
352
353     if ( is_valid && power_btn && (bus_power_node->getDoubleValue() > 1.0)
354          && nav_serviceable )
355     {
356         station = Point3D( nav_x, nav_y, nav_z );
357         loc_dist = aircraft.distance3D( station );
358         loc_dist_node->setDoubleValue( loc_dist );
359         // cout << "station = " << station << " dist = " << loc_dist << endl;
360
361         if ( has_gs ) {
362             // find closest distance to the gs base line
363             sgdVec3 p;
364             sgdSetVec3( p, aircraft.x(), aircraft.y(), aircraft.z() );
365             sgdVec3 p0;
366             sgdSetVec3( p0, gs_x, gs_y, gs_z );
367             double dist = sgdClosestPointToLineDistSquared( p, p0,
368                                                             gs_base_vec );
369             gs_dist_node->setDoubleValue( sqrt( dist ) );
370             // cout << "gs_dist = " << gs_dist_node->getDoubleValue()
371             //      << endl;
372
373             Point3D tmp( gs_x, gs_y, gs_z );
374             // cout << " (" << aircraft.distance3D( tmp ) << ")" << endl;
375
376             // wgs84 heading to glide slope (to determine sign of distance)
377             geo_inverse_wgs_84( elev,
378                                 lat * SGD_RADIANS_TO_DEGREES,
379                                 lon * SGD_RADIANS_TO_DEGREES, 
380                                 gs_lat, gs_lon,
381                                 &az1, &az2, &s );
382             double r = az1 - target_radial;
383             while ( r >  180.0 ) { r -= 360.0;}
384             while ( r < -180.0 ) { r += 360.0;}
385             if ( r >= -90.0 && r <= 90.0 ) {
386                 gs_dist_signed = gs_dist_node->getDoubleValue();
387             } else {
388                 gs_dist_signed = -gs_dist_node->getDoubleValue();
389             }
390             /* cout << "Target Radial = " << target_radial 
391                  << "  Bearing = " << az1
392                  << "  dist (signed) = " << gs_dist_signed
393                  << endl; */
394             
395         } else {
396             gs_dist_node->setDoubleValue( 0.0 );
397         }
398         
399         //////////////////////////////////////////////////////////
400         // compute forward and reverse wgs84 headings to localizer
401         //////////////////////////////////////////////////////////
402         double hdg;
403         geo_inverse_wgs_84( elev,
404                             lat * SGD_RADIANS_TO_DEGREES,
405                             lon * SGD_RADIANS_TO_DEGREES, 
406                             loc_lat, loc_lon,
407                             &hdg, &az2, &s );
408         // cout << "az1 = " << az1 << " magvar = " << nav_magvar << endl;
409         heading_node->setDoubleValue( hdg );
410         radial = az2 - twist;
411         double recip = radial + 180.0;
412         if ( recip >= 360.0 ) { recip -= 360.0; }
413         radial_node->setDoubleValue( radial );
414         recip_radial_node->setDoubleValue( recip );
415         // cout << " heading = " << heading_node->getDoubleValue()
416         //      << " dist = " << nav_dist << endl;
417
418         //////////////////////////////////////////////////////////
419         // adjust reception range for altitude
420         //////////////////////////////////////////////////////////
421         if ( is_loc ) {
422             double offset = radial - target_radial;
423             while ( offset < -180.0 ) { offset += 360.0; }
424             while ( offset > 180.0 ) { offset -= 360.0; }
425             // cout << "ils offset = " << offset << endl;
426             effective_range
427                 = adjustILSRange( nav_elev, elev, offset,
428                                   loc_dist * SG_METER_TO_NM );
429         } else {
430             effective_range = adjustNavRange( nav_elev, elev, range );
431         }
432         // cout << "nav range = " << effective_range
433         //      << " (" << range << ")" << endl;
434
435         if ( loc_dist < effective_range * SG_NM_TO_METER ) {
436             inrange = true;
437         } else if ( loc_dist < 2 * effective_range * SG_NM_TO_METER ) {
438             inrange = sg_random() < ( 2 * effective_range * SG_NM_TO_METER
439                                       - loc_dist )
440                                       / (effective_range * SG_NM_TO_METER);
441         } else {
442             inrange = false;
443         }
444         inrange_node->setBoolValue( inrange );
445
446         if ( !is_loc ) {
447             target_radial = sel_radial_node->getDoubleValue();
448         }
449
450         //////////////////////////////////////////////////////////
451         // compute to/from flag status
452         //////////////////////////////////////////////////////////
453         double value = false;
454         double offset = fabs(radial - target_radial);
455         if ( tofrom_serviceable ) {
456             if ( nav_slaved_to_gps_node->getBoolValue() ) {
457                 value = gps_to_flag_node->getBoolValue();
458             } else if ( inrange ) {
459                 if ( is_loc ) {
460                     value = true;
461                 } else {
462                     value = !(offset <= 90.0 || offset >= 270.0);
463                 }
464             }
465         } else {
466             value = false;
467         }
468         to_flag_node->setBoolValue( value );
469
470         value = false;
471         if ( tofrom_serviceable ) {
472             if ( nav_slaved_to_gps_node->getBoolValue() ) {
473                 value = gps_from_flag_node->getBoolValue();
474             } else if ( inrange ) {
475                 if ( is_loc ) {
476                     value = false;
477                 } else {
478                     value = !(offset > 90.0 && offset < 270.0);
479                 }
480             }
481         } else {
482             value = false;
483         }
484         from_flag_node->setBoolValue( value );
485
486         //////////////////////////////////////////////////////////
487         // compute the deflection of the CDI needle, clamped to the range
488         // of ( -10 , 10 )
489         //////////////////////////////////////////////////////////
490         double r = 0.0;
491         if ( cdi_serviceable ) {
492             if ( nav_slaved_to_gps_node->getBoolValue() ) {
493                 r = gps_cdi_deflection_node->getDoubleValue();
494                 // We want +- 5 dots deflection for the gps, so clamp
495                 // to -12.5/12.5
496                 if ( r < -12.5 ) { r = -12.5; }
497                 if ( r >  12.5 ) { r =  12.5; }
498             } else if ( inrange ) {
499                 r = radial - target_radial;
500                 // cout << "Target radial = " << target_radial 
501                 //      << "  Actual radial = " << radial << endl;
502                 
503                 while ( r >  180.0 ) { r -= 360.0;}
504                 while ( r < -180.0 ) { r += 360.0;}
505                 if ( fabs(r) > 90.0 ) {
506                     r = ( r<0.0 ? -r-180.0 : -r+180.0 );
507                 }
508
509                 // According to Robin Peel, the ILS is 4x more
510                 // sensitive than a vor
511                 r = -r;         // reverse, since radial is outbound
512                 if ( is_loc ) { r *= 4.0; }
513                 if ( r < -10.0 ) { r = -10.0; }
514                 if ( r >  10.0 ) { r =  10.0; }
515             }
516         }
517         cdi_deflection_node->setDoubleValue( r );
518
519         //////////////////////////////////////////////////////////
520         // compute the amount of cross track distance error in meters
521         //////////////////////////////////////////////////////////
522         double xtrack_error = 0.0;
523         if ( inrange && nav_serviceable && cdi_serviceable ) {
524             r = radial - target_radial;
525             // cout << "Target radial = " << target_radial 
526             //     << "  Actual radial = " << radial
527             //     << "  r = " << r << endl;
528     
529             while ( r >  180.0 ) { r -= 360.0;}
530             while ( r < -180.0 ) { r += 360.0;}
531             if ( fabs(r) > 90.0 ) {
532                 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
533             }
534
535             r = -r;             // reverse, since radial is outbound
536
537             xtrack_error = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
538         } else {
539             xtrack_error = 0.0;
540         }
541         cdi_xtrack_error_node->setDoubleValue( xtrack_error );
542
543         //////////////////////////////////////////////////////////
544         // compute an approximate ground track heading error
545         //////////////////////////////////////////////////////////
546         double hdg_error = 0.0;
547         if ( inrange && cdi_serviceable ) {
548             double ddist = last_loc_dist - loc_dist;
549             double dxtrack = last_xtrack_error - xtrack_error;
550             double a = atan2( dxtrack, ddist ) * SGD_RADIANS_TO_DEGREES;
551             SGPropertyNode *maghead
552                 = fgGetNode("/orientation/heading-magnetic-deg", true);
553             cout << "heading = " << maghead->getDoubleValue()
554                  << " selrad = " << sel_radial_node->getDoubleValue()
555                  << " artr = " << a
556                  << endl;
557             double est_hdg = sel_radial_node->getDoubleValue() + a;
558             if ( est_hdg < 0.0 ) { est_hdg += 360.0; }
559             if ( est_hdg >= 360.0 ) { est_hdg -= 360.0; }
560             hdg_error = est_hdg - maghead->getDoubleValue();
561         }
562         cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
563
564         //////////////////////////////////////////////////////////
565         // compute the time to intercept selected radial (based on
566         // current and last cross track errors and dt
567         //////////////////////////////////////////////////////////
568         double t = 0.0;
569         if ( inrange && cdi_serviceable ) {
570             double xrate_ms = (last_xtrack_error - xtrack_error) / dt;
571             if ( fabs(xrate_ms) > 0.00001 ) {
572                 t = xtrack_error / xrate_ms;
573             } else {
574                 t = 9999.9;
575             }
576         }
577         time_to_intercept->setDoubleValue( t );
578
579         //////////////////////////////////////////////////////////
580         // compute the amount of glide slope needle deflection
581         // (.i.e. the number of degrees we are off the glide slope * 5.0
582         //////////////////////////////////////////////////////////
583         r = 0.0;
584         if ( has_gs && gs_serviceable_node->getBoolValue() ) {
585             if ( nav_slaved_to_gps_node->getBoolValue() ) {
586                 // FIXME/FINISHME, what should be set here?
587             } else if ( inrange ) {
588                 double x = gs_dist_node->getDoubleValue();
589                 double y = (fgGetDouble("/position/altitude-ft") - nav_elev)
590                     * SG_FEET_TO_METER;
591                 // cout << "dist = " << x << " height = " << y << endl;
592                 double angle = asin( y / x ) * SGD_RADIANS_TO_DEGREES;
593                 r = (target_gs - angle) * 5.0;
594             }
595         }
596         gs_deflection_node->setDoubleValue( r );
597
598         //////////////////////////////////////////////////////////
599         // Calculate desired rate of climb for intercepting the GS
600         //////////////////////////////////////////////////////////
601         double x = gs_dist_node->getDoubleValue();
602         double y = (alt_node->getDoubleValue() - nav_elev)
603             * SG_FEET_TO_METER;
604         double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
605
606         double target_angle = target_gs;
607         double gs_diff = target_angle - current_angle;
608
609         // convert desired vertical path angle into a climb rate
610         double des_angle = current_angle - 10 * gs_diff;
611
612         // estimate horizontal speed towards ILS in meters per minute
613         double dist = last_x - x;
614         last_x = x;
615         if ( dt > 0.0 ) {
616             // avoid nan
617             double new_vel = ( dist / dt );
618  
619             horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
620             // double horiz_vel = cur_fdm_state->get_V_ground_speed()
621             //    * SG_FEET_TO_METER * 60.0;
622             // double horiz_vel = airspeed_node->getFloatValue()
623             //    * SG_FEET_TO_METER * 60.0;
624
625             gs_rate_of_climb_node
626                 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
627                                   * horiz_vel * SG_METER_TO_FEET );
628         }
629
630         //////////////////////////////////////////////////////////
631         // Calculate a suggested target heading to smoothly intercept
632         // a nav/ils radial.
633         //////////////////////////////////////////////////////////
634
635         // determine the target radial in "true" heading
636         double trtrue = 0.0;
637         if ( is_loc ) {
638             // ILS localizers radials are already "true" in our
639             // database
640             trtrue = target_radial;
641         } else {
642             // VOR radials need to have that vor's offset added in
643             trtrue = target_radial + twist;
644         }
645
646         while ( trtrue < 0.0 ) { trtrue += 360.0; }
647         while ( trtrue > 360.0 ) { trtrue -= 360.0; }
648         target_radial_true_node->setDoubleValue( trtrue );
649
650         // FIXME: this smells odd, there must be a better (or more
651         // linear) solution
652         //
653         // determine the heading adjustment needed.
654         // over 8km scale by 3.0 
655         //    (3 is chosen because max deflection is 10
656         //    and 30 is clamped angle to radial)
657         // under 8km scale by 10.0
658         //    because the overstated error helps drive it to the radial in a 
659         //    moderate cross wind.
660         double adjustment = 0.0;
661         if ( loc_dist > 8000 ) {
662             adjustment = cdi_deflection_node->getDoubleValue() * 3.0;
663         } else {
664             adjustment = cdi_deflection_node->getDoubleValue() * 10.0;
665         }
666         SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
667         
668         // determine the target heading to fly to intercept the
669         // tgt_radial = target radial (true) + cdi offset adjustmest -
670         // xtrack heading error adjustment
671         double nta_hdg = trtrue + adjustment /* - hdg_error */; 
672         while ( nta_hdg <   0.0 ) { nta_hdg += 360.0; }
673         while ( nta_hdg > 360.0 ) { nta_hdg -= 360.0; }
674         target_auto_hdg_node->setDoubleValue( nta_hdg );
675
676         last_xtrack_error = xtrack_error;
677    } else {
678         inrange_node->setBoolValue( false );
679         cdi_deflection_node->setDoubleValue( 0.0 );
680         cdi_xtrack_error_node->setDoubleValue( 0.0 );
681         cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
682         time_to_intercept->setDoubleValue( 0.0 );
683         gs_deflection_node->setDoubleValue( 0.0 );
684         to_flag_node->setBoolValue( false );
685         from_flag_node->setBoolValue( false );
686         // cout << "not picking up vor. :-(" << endl;
687     }
688
689     // audio effects
690     if ( is_valid && inrange && nav_serviceable ) {
691         // play station ident via audio system if on + ident,
692         // otherwise turn it off
693         if ( power_btn
694              && (bus_power_node->getDoubleValue() > 1.0)
695              && ident_btn_node->getBoolValue()
696              && audio_btn_node->getBoolValue() )
697         {
698             SGSoundSample *sound;
699             sound = globals->get_soundmgr()->find( nav_fx_name );
700             double vol = vol_btn_node->getDoubleValue();
701             if ( vol < 0.0 ) { vol = 0.0; }
702             if ( vol > 1.0 ) { vol = 1.0; }
703             if ( sound != NULL ) {
704                 sound->set_volume( vol );
705             } else {
706                 SG_LOG( SG_COCKPIT, SG_ALERT,
707                         "Can't find nav-vor-ident sound" );
708             }
709             sound = globals->get_soundmgr()->find( dme_fx_name );
710             if ( sound != NULL ) {
711                 sound->set_volume( vol );
712             } else {
713                 SG_LOG( SG_COCKPIT, SG_ALERT,
714                         "Can't find nav-dme-ident sound" );
715             }
716             // cout << "last_time = " << last_time << " ";
717             // cout << "cur_time = "
718             //      << globals->get_time_params()->get_cur_time();
719             if ( last_time <
720                  globals->get_time_params()->get_cur_time() - 30 ) {
721                 last_time = globals->get_time_params()->get_cur_time();
722                 play_count = 0;
723             }
724             // cout << " play_count = " << play_count << endl;
725             // cout << "playing = "
726             //      << globals->get_soundmgr()->is_playing(nav_fx_name)
727             //      << endl;
728             if ( play_count < 4 ) {
729                 // play VOR ident
730                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) ) {
731                     globals->get_soundmgr()->play_once( nav_fx_name );
732                     ++play_count;
733                 }
734             } else if ( play_count < 5 && has_dme ) {
735                 // play DME ident
736                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) &&
737                      !globals->get_soundmgr()->is_playing(dme_fx_name) ) {
738                     globals->get_soundmgr()->play_once( dme_fx_name );
739                     ++play_count;
740                 }
741             }
742         } else {
743             globals->get_soundmgr()->stop( nav_fx_name );
744             globals->get_soundmgr()->stop( dme_fx_name );
745         }
746     }
747
748     last_loc_dist = loc_dist;
749 }
750
751
752 // Update current nav/adf radio stations based on current postition
753 void FGNavRadio::search() 
754 {
755
756     // reset search time
757     _time_before_search_sec = 1.0;
758
759     // cache values locally for speed
760     double lon = lon_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
761     double lat = lat_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
762     double elev = alt_node->getDoubleValue() * SG_FEET_TO_METER;
763
764     FGNavRecord *nav = NULL;
765     FGNavRecord *loc = NULL;
766     FGNavRecord *dme = NULL;
767     FGNavRecord *gs = NULL;
768
769     ////////////////////////////////////////////////////////////////////////
770     // Nav.
771     ////////////////////////////////////////////////////////////////////////
772
773     double freq = freq_node->getDoubleValue();
774     nav = globals->get_navlist()->findByFreq(freq, lon, lat, elev);
775     dme = globals->get_dmelist()->findByFreq(freq, lon, lat, elev);
776     if ( nav == NULL ) {
777         loc = globals->get_loclist()->findByFreq(freq, lon, lat, elev);
778         gs = globals->get_gslist()->findByFreq(freq, lon, lat, elev);
779     }
780
781     string nav_id = "";
782
783     if ( loc != NULL ) {
784         nav_id = loc->get_ident();
785         nav_id_node->setStringValue( nav_id.c_str() );
786         // cout << "localizer = " << nav_id_node->getStringValue() << endl;
787         is_valid = true;
788         if ( last_nav_id != nav_id || last_nav_vor ) {
789             trans_ident = loc->get_trans_ident();
790             target_radial = loc->get_multiuse();
791             while ( target_radial <   0.0 ) { target_radial += 360.0; }
792             while ( target_radial > 360.0 ) { target_radial -= 360.0; }
793             loc_lon = loc->get_lon();
794             loc_lat = loc->get_lat();
795             nav_x = loc->get_x();
796             nav_y = loc->get_y();
797             nav_z = loc->get_z();
798             last_nav_id = nav_id;
799             last_nav_vor = false;
800             loc_node->setBoolValue( true );
801             has_dme = (dme != NULL);
802             if ( gs != NULL ) {
803                 has_gs_node->setBoolValue( true );
804                 gs_lon = gs->get_lon();
805                 gs_lat = gs->get_lat();
806                 nav_elev = gs->get_elev_ft();
807                 int tmp = (int)(gs->get_multiuse() / 1000.0);
808                 target_gs = (double)tmp / 100.0;
809                 gs_x = gs->get_x();
810                 gs_y = gs->get_y();
811                 gs_z = gs->get_z();
812
813                 // derive GS baseline (perpendicular to the runay
814                 // along the ground)
815                 double tlon, tlat, taz;
816                 geo_direct_wgs_84 ( 0.0, gs_lat, gs_lon,
817                                     target_radial + 90,  
818                                     100.0, &tlat, &tlon, &taz );
819                 // cout << "target_radial = " << target_radial << endl;
820                 // cout << "nav_loc = " << loc_node->getBoolValue() << endl;
821                 // cout << gs_lon << "," << gs_lat << "  "
822                 //      << tlon << "," << tlat << "  (" << nav_elev << ")"
823                 //      << endl;
824                 Point3D p1 = sgGeodToCart( Point3D(tlon*SGD_DEGREES_TO_RADIANS,
825                                                    tlat*SGD_DEGREES_TO_RADIANS,
826                                                    nav_elev*SG_FEET_TO_METER)
827                                            );
828                 // cout << gs_x << "," << gs_y << "," << gs_z
829                 //      << endl;
830                 // cout << p1 << endl;
831                 sgdSetVec3( gs_base_vec,
832                             p1.x()-gs_x, p1.y()-gs_y, p1.z()-gs_z );
833                 // cout << gs_base_vec[0] << "," << gs_base_vec[1] << ","
834                 //      << gs_base_vec[2] << endl;
835             } else {
836                 has_gs_node->setBoolValue( false );
837                 nav_elev = loc->get_elev_ft();
838             }
839             twist = 0;
840             range = FG_LOC_DEFAULT_RANGE;
841             effective_range = range;
842
843             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
844                 globals->get_soundmgr()->remove( nav_fx_name );
845             }
846             SGSoundSample *sound;
847             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
848             sound->set_volume( 0.3 );
849             globals->get_soundmgr()->add( sound, nav_fx_name );
850
851             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
852                 globals->get_soundmgr()->remove( dme_fx_name );
853             }
854             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
855             sound->set_volume( 0.3 );
856             globals->get_soundmgr()->add( sound, dme_fx_name );
857
858             int offset = (int)(sg_random() * 30.0);
859             play_count = offset / 4;
860             last_time = globals->get_time_params()->get_cur_time() -
861                 offset;
862             // cout << "offset = " << offset << " play_count = "
863             //      << play_count
864             //      << " last_time = " << last_time
865             //      << " current time = "
866             //      << globals->get_time_params()->get_cur_time() << endl;
867
868             // cout << "Found an loc station in range" << endl;
869             // cout << " id = " << loc->get_locident() << endl;
870         }
871     } else if ( nav != NULL ) {
872         nav_id = nav->get_ident();
873         nav_id_node->setStringValue( nav_id.c_str() );
874         // cout << "nav = " << nav_id << endl;
875         is_valid = true;
876         if ( last_nav_id != nav_id || !last_nav_vor ) {
877             last_nav_id = nav_id;
878             last_nav_vor = true;
879             trans_ident = nav->get_trans_ident();
880             loc_node->setBoolValue( false );
881             has_dme = (dme != NULL);
882             has_gs_node->setBoolValue( false );
883             loc_lon = nav->get_lon();
884             loc_lat = nav->get_lat();
885             nav_elev = nav->get_elev_ft();
886             twist = nav->get_multiuse();
887             range = nav->get_range();
888             effective_range = adjustNavRange(nav_elev, elev, range);
889             target_gs = 0.0;
890             target_radial = sel_radial_node->getDoubleValue();
891             nav_x = nav->get_x();
892             nav_y = nav->get_y();
893             nav_z = nav->get_z();
894
895             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
896                 globals->get_soundmgr()->remove( nav_fx_name );
897             }
898             SGSoundSample *sound;
899             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
900             sound->set_volume( 0.3 );
901             if ( globals->get_soundmgr()->add( sound, nav_fx_name ) ) {
902                 // cout << "Added nav-vor-ident sound" << endl;
903             } else {
904                 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
905             }
906
907             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
908                 globals->get_soundmgr()->remove( dme_fx_name );
909             }
910             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
911             sound->set_volume( 0.3 );
912             globals->get_soundmgr()->add( sound, dme_fx_name );
913
914             int offset = (int)(sg_random() * 30.0);
915             play_count = offset / 4;
916             last_time = globals->get_time_params()->get_cur_time() - offset;
917             // cout << "offset = " << offset << " play_count = "
918             //      << play_count << " last_time = "
919             //      << last_time << " current time = "
920             //      << globals->get_time_params()->get_cur_time() << endl;
921
922             // cout << "Found a vor station in range" << endl;
923             // cout << " id = " << nav->get_ident() << endl;
924         }
925     } else {
926         is_valid = false;
927         nav_id_node->setStringValue( "" );
928         target_radial = 0;
929         trans_ident = "";
930         last_nav_id = "";
931         if ( ! globals->get_soundmgr()->remove( nav_fx_name ) ) {
932             SG_LOG(SG_COCKPIT, SG_WARN, "Failed to remove nav-vor-ident sound");
933         }
934         globals->get_soundmgr()->remove( dme_fx_name );
935         // cout << "not picking up vor1. :-(" << endl;
936     }
937
938     char tmpid[5];
939     strncpy( tmpid, nav_id.c_str(), 5 );
940     id_c1_node->setIntValue( (int)tmpid[0] );
941     id_c2_node->setIntValue( (int)tmpid[1] );
942     id_c3_node->setIntValue( (int)tmpid[2] );
943     id_c4_node->setIntValue( (int)tmpid[3] );
944 }