]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
628e4b8308e41f7c59a8bf9f05f57c02f7d93734
[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         // compute the target/selected radial in "true" heading
420         //////////////////////////////////////////////////////////
421         double trtrue = 0.0;
422         if ( is_loc ) {
423             // ILS localizers radials are already "true" in our
424             // database
425             trtrue = target_radial;
426         } else {
427             // VOR radials need to have that vor's offset added in
428             trtrue = target_radial + twist;
429         }
430
431         while ( trtrue < 0.0 ) { trtrue += 360.0; }
432         while ( trtrue > 360.0 ) { trtrue -= 360.0; }
433         target_radial_true_node->setDoubleValue( trtrue );
434
435         //////////////////////////////////////////////////////////
436         // adjust reception range for altitude
437         //////////////////////////////////////////////////////////
438         if ( is_loc ) {
439             double offset = radial - target_radial;
440             while ( offset < -180.0 ) { offset += 360.0; }
441             while ( offset > 180.0 ) { offset -= 360.0; }
442             // cout << "ils offset = " << offset << endl;
443             effective_range
444                 = adjustILSRange( nav_elev, elev, offset,
445                                   loc_dist * SG_METER_TO_NM );
446         } else {
447             effective_range = adjustNavRange( nav_elev, elev, range );
448         }
449         // cout << "nav range = " << effective_range
450         //      << " (" << range << ")" << endl;
451
452         if ( loc_dist < effective_range * SG_NM_TO_METER ) {
453             inrange = true;
454         } else if ( loc_dist < 2 * effective_range * SG_NM_TO_METER ) {
455             inrange = sg_random() < ( 2 * effective_range * SG_NM_TO_METER
456                                       - loc_dist )
457                                       / (effective_range * SG_NM_TO_METER);
458         } else {
459             inrange = false;
460         }
461         inrange_node->setBoolValue( inrange );
462
463         if ( !is_loc ) {
464             target_radial = sel_radial_node->getDoubleValue();
465         }
466
467         //////////////////////////////////////////////////////////
468         // compute to/from flag status
469         //////////////////////////////////////////////////////////
470         double value = false;
471         double offset = fabs(radial - target_radial);
472         if ( tofrom_serviceable ) {
473             if ( nav_slaved_to_gps_node->getBoolValue() ) {
474                 value = gps_to_flag_node->getBoolValue();
475             } else if ( inrange ) {
476                 if ( is_loc ) {
477                     value = true;
478                 } else {
479                     value = !(offset <= 90.0 || offset >= 270.0);
480                 }
481             }
482         } else {
483             value = false;
484         }
485         to_flag_node->setBoolValue( value );
486
487         value = false;
488         if ( tofrom_serviceable ) {
489             if ( nav_slaved_to_gps_node->getBoolValue() ) {
490                 value = gps_from_flag_node->getBoolValue();
491             } else if ( inrange ) {
492                 if ( is_loc ) {
493                     value = false;
494                 } else {
495                     value = !(offset > 90.0 && offset < 270.0);
496                 }
497             }
498         } else {
499             value = false;
500         }
501         from_flag_node->setBoolValue( value );
502
503         //////////////////////////////////////////////////////////
504         // compute the deflection of the CDI needle, clamped to the range
505         // of ( -10 , 10 )
506         //////////////////////////////////////////////////////////
507         double r = 0.0;
508         if ( cdi_serviceable ) {
509             if ( nav_slaved_to_gps_node->getBoolValue() ) {
510                 r = gps_cdi_deflection_node->getDoubleValue();
511                 // We want +- 5 dots deflection for the gps, so clamp
512                 // to -12.5/12.5
513                 if ( r < -12.5 ) { r = -12.5; }
514                 if ( r >  12.5 ) { r =  12.5; }
515             } else if ( inrange ) {
516                 r = radial - target_radial;
517                 // cout << "Target radial = " << target_radial 
518                 //      << "  Actual radial = " << radial << endl;
519                 
520                 while ( r >  180.0 ) { r -= 360.0;}
521                 while ( r < -180.0 ) { r += 360.0;}
522                 if ( fabs(r) > 90.0 ) {
523                     r = ( r<0.0 ? -r-180.0 : -r+180.0 );
524                 }
525
526                 // According to Robin Peel, the ILS is 4x more
527                 // sensitive than a vor
528                 r = -r;         // reverse, since radial is outbound
529                 if ( is_loc ) { r *= 4.0; }
530                 if ( r < -10.0 ) { r = -10.0; }
531                 if ( r >  10.0 ) { r =  10.0; }
532             }
533         }
534         cdi_deflection_node->setDoubleValue( r );
535
536         //////////////////////////////////////////////////////////
537         // compute the amount of cross track distance error in meters
538         //////////////////////////////////////////////////////////
539         double xtrack_error = 0.0;
540         if ( inrange && nav_serviceable && cdi_serviceable ) {
541             r = radial - target_radial;
542             // cout << "Target radial = " << target_radial 
543             //     << "  Actual radial = " << radial
544             //     << "  r = " << r << endl;
545     
546             while ( r >  180.0 ) { r -= 360.0;}
547             while ( r < -180.0 ) { r += 360.0;}
548             if ( fabs(r) > 90.0 ) {
549                 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
550             }
551
552             r = -r;             // reverse, since radial is outbound
553
554             xtrack_error = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
555         } else {
556             xtrack_error = 0.0;
557         }
558         cdi_xtrack_error_node->setDoubleValue( xtrack_error );
559
560         //////////////////////////////////////////////////////////
561         // compute an approximate ground track heading error
562         //////////////////////////////////////////////////////////
563         double hdg_error = 0.0;
564         if ( inrange && cdi_serviceable ) {
565             double ddist = last_loc_dist - loc_dist;
566             double dxtrack = last_xtrack_error - xtrack_error;
567             double a = atan2( dxtrack, ddist ) * SGD_RADIANS_TO_DEGREES;
568             if ( from_flag_node->getBoolValue() ) {
569                 a = 180.0 - a;
570                 if ( a > 180.0 ) { a -= 360.0; }
571                 if ( a < -180.0 ) { a += 360.0; }
572             }
573             SGPropertyNode *true_hdg
574                 = fgGetNode("/orientation/heading-deg", true);
575             cout << "true heading = " << true_hdg->getDoubleValue()
576                  << " selrad = " << sel_radial_node->getDoubleValue()
577                  << " artr = " << a
578                  << endl;
579             double est_hdg = trtrue + a;
580             if ( est_hdg < 0.0 ) { est_hdg += 360.0; }
581             if ( est_hdg >= 360.0 ) { est_hdg -= 360.0; }
582             hdg_error = est_hdg - true_hdg->getDoubleValue();
583         }
584         cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
585
586         //////////////////////////////////////////////////////////
587         // compute the time to intercept selected radial (based on
588         // current and last cross track errors and dt
589         //////////////////////////////////////////////////////////
590         double t = 0.0;
591         if ( inrange && cdi_serviceable ) {
592             double xrate_ms = (last_xtrack_error - xtrack_error) / dt;
593             if ( fabs(xrate_ms) > 0.00001 ) {
594                 t = xtrack_error / xrate_ms;
595             } else {
596                 t = 9999.9;
597             }
598         }
599         time_to_intercept->setDoubleValue( t );
600
601         //////////////////////////////////////////////////////////
602         // compute the amount of glide slope needle deflection
603         // (.i.e. the number of degrees we are off the glide slope * 5.0
604         //////////////////////////////////////////////////////////
605         r = 0.0;
606         if ( has_gs && gs_serviceable_node->getBoolValue() ) {
607             if ( nav_slaved_to_gps_node->getBoolValue() ) {
608                 // FIXME/FINISHME, what should be set here?
609             } else if ( inrange ) {
610                 double x = gs_dist_node->getDoubleValue();
611                 double y = (fgGetDouble("/position/altitude-ft") - nav_elev)
612                     * SG_FEET_TO_METER;
613                 // cout << "dist = " << x << " height = " << y << endl;
614                 double angle = asin( y / x ) * SGD_RADIANS_TO_DEGREES;
615                 r = (target_gs - angle) * 5.0;
616             }
617         }
618         gs_deflection_node->setDoubleValue( r );
619
620         //////////////////////////////////////////////////////////
621         // Calculate desired rate of climb for intercepting the GS
622         //////////////////////////////////////////////////////////
623         double x = gs_dist_node->getDoubleValue();
624         double y = (alt_node->getDoubleValue() - nav_elev)
625             * SG_FEET_TO_METER;
626         double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
627
628         double target_angle = target_gs;
629         double gs_diff = target_angle - current_angle;
630
631         // convert desired vertical path angle into a climb rate
632         double des_angle = current_angle - 10 * gs_diff;
633
634         // estimate horizontal speed towards ILS in meters per minute
635         double dist = last_x - x;
636         last_x = x;
637         if ( dt > 0.0 ) {
638             // avoid nan
639             double new_vel = ( dist / dt );
640  
641             horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
642             // double horiz_vel = cur_fdm_state->get_V_ground_speed()
643             //    * SG_FEET_TO_METER * 60.0;
644             // double horiz_vel = airspeed_node->getFloatValue()
645             //    * SG_FEET_TO_METER * 60.0;
646
647             gs_rate_of_climb_node
648                 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
649                                   * horiz_vel * SG_METER_TO_FEET );
650         }
651
652         //////////////////////////////////////////////////////////
653         // Calculate a suggested target heading to smoothly intercept
654         // a nav/ils radial.
655         //////////////////////////////////////////////////////////
656
657         // FIXME: this smells odd, there must be a better (or more
658         // linear) solution
659         //
660         // determine the heading adjustment needed.
661         // over 8km scale by 3.0 
662         //    (3 is chosen because max deflection is 10
663         //    and 30 is clamped angle to radial)
664         // under 8km scale by 10.0
665         //    because the overstated error helps drive it to the radial in a 
666         //    moderate cross wind.
667         double adjustment = 0.0;
668         if ( loc_dist > 8000 ) {
669             adjustment = cdi_deflection_node->getDoubleValue() * 3.0;
670         } else {
671             adjustment = cdi_deflection_node->getDoubleValue() * 10.0;
672         }
673         SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
674         
675         // determine the target heading to fly to intercept the
676         // tgt_radial = target radial (true) + cdi offset adjustmest -
677         // xtrack heading error adjustment
678         double nta_hdg = trtrue + adjustment - hdg_error; 
679         while ( nta_hdg <   0.0 ) { nta_hdg += 360.0; }
680         while ( nta_hdg > 360.0 ) { nta_hdg -= 360.0; }
681         target_auto_hdg_node->setDoubleValue( nta_hdg );
682
683         last_xtrack_error = xtrack_error;
684    } else {
685         inrange_node->setBoolValue( false );
686         cdi_deflection_node->setDoubleValue( 0.0 );
687         cdi_xtrack_error_node->setDoubleValue( 0.0 );
688         cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
689         time_to_intercept->setDoubleValue( 0.0 );
690         gs_deflection_node->setDoubleValue( 0.0 );
691         to_flag_node->setBoolValue( false );
692         from_flag_node->setBoolValue( false );
693         // cout << "not picking up vor. :-(" << endl;
694     }
695
696     // audio effects
697     if ( is_valid && inrange && nav_serviceable ) {
698         // play station ident via audio system if on + ident,
699         // otherwise turn it off
700         if ( power_btn
701              && (bus_power_node->getDoubleValue() > 1.0)
702              && ident_btn_node->getBoolValue()
703              && audio_btn_node->getBoolValue() )
704         {
705             SGSoundSample *sound;
706             sound = globals->get_soundmgr()->find( nav_fx_name );
707             double vol = vol_btn_node->getDoubleValue();
708             if ( vol < 0.0 ) { vol = 0.0; }
709             if ( vol > 1.0 ) { vol = 1.0; }
710             if ( sound != NULL ) {
711                 sound->set_volume( vol );
712             } else {
713                 SG_LOG( SG_COCKPIT, SG_ALERT,
714                         "Can't find nav-vor-ident sound" );
715             }
716             sound = globals->get_soundmgr()->find( dme_fx_name );
717             if ( sound != NULL ) {
718                 sound->set_volume( vol );
719             } else {
720                 SG_LOG( SG_COCKPIT, SG_ALERT,
721                         "Can't find nav-dme-ident sound" );
722             }
723             // cout << "last_time = " << last_time << " ";
724             // cout << "cur_time = "
725             //      << globals->get_time_params()->get_cur_time();
726             if ( last_time <
727                  globals->get_time_params()->get_cur_time() - 30 ) {
728                 last_time = globals->get_time_params()->get_cur_time();
729                 play_count = 0;
730             }
731             // cout << " play_count = " << play_count << endl;
732             // cout << "playing = "
733             //      << globals->get_soundmgr()->is_playing(nav_fx_name)
734             //      << endl;
735             if ( play_count < 4 ) {
736                 // play VOR ident
737                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) ) {
738                     globals->get_soundmgr()->play_once( nav_fx_name );
739                     ++play_count;
740                 }
741             } else if ( play_count < 5 && has_dme ) {
742                 // play DME ident
743                 if ( !globals->get_soundmgr()->is_playing(nav_fx_name) &&
744                      !globals->get_soundmgr()->is_playing(dme_fx_name) ) {
745                     globals->get_soundmgr()->play_once( dme_fx_name );
746                     ++play_count;
747                 }
748             }
749         } else {
750             globals->get_soundmgr()->stop( nav_fx_name );
751             globals->get_soundmgr()->stop( dme_fx_name );
752         }
753     }
754
755     last_loc_dist = loc_dist;
756 }
757
758
759 // Update current nav/adf radio stations based on current postition
760 void FGNavRadio::search() 
761 {
762
763     // reset search time
764     _time_before_search_sec = 1.0;
765
766     // cache values locally for speed
767     double lon = lon_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
768     double lat = lat_node->getDoubleValue() * SGD_DEGREES_TO_RADIANS;
769     double elev = alt_node->getDoubleValue() * SG_FEET_TO_METER;
770
771     FGNavRecord *nav = NULL;
772     FGNavRecord *loc = NULL;
773     FGNavRecord *dme = NULL;
774     FGNavRecord *gs = NULL;
775
776     ////////////////////////////////////////////////////////////////////////
777     // Nav.
778     ////////////////////////////////////////////////////////////////////////
779
780     double freq = freq_node->getDoubleValue();
781     nav = globals->get_navlist()->findByFreq(freq, lon, lat, elev);
782     dme = globals->get_dmelist()->findByFreq(freq, lon, lat, elev);
783     if ( nav == NULL ) {
784         loc = globals->get_loclist()->findByFreq(freq, lon, lat, elev);
785         gs = globals->get_gslist()->findByFreq(freq, lon, lat, elev);
786     }
787
788     string nav_id = "";
789
790     if ( loc != NULL ) {
791         nav_id = loc->get_ident();
792         nav_id_node->setStringValue( nav_id.c_str() );
793         // cout << "localizer = " << nav_id_node->getStringValue() << endl;
794         is_valid = true;
795         if ( last_nav_id != nav_id || last_nav_vor ) {
796             trans_ident = loc->get_trans_ident();
797             target_radial = loc->get_multiuse();
798             while ( target_radial <   0.0 ) { target_radial += 360.0; }
799             while ( target_radial > 360.0 ) { target_radial -= 360.0; }
800             loc_lon = loc->get_lon();
801             loc_lat = loc->get_lat();
802             nav_x = loc->get_x();
803             nav_y = loc->get_y();
804             nav_z = loc->get_z();
805             last_nav_id = nav_id;
806             last_nav_vor = false;
807             loc_node->setBoolValue( true );
808             has_dme = (dme != NULL);
809             if ( gs != NULL ) {
810                 has_gs_node->setBoolValue( true );
811                 gs_lon = gs->get_lon();
812                 gs_lat = gs->get_lat();
813                 nav_elev = gs->get_elev_ft();
814                 int tmp = (int)(gs->get_multiuse() / 1000.0);
815                 target_gs = (double)tmp / 100.0;
816                 gs_x = gs->get_x();
817                 gs_y = gs->get_y();
818                 gs_z = gs->get_z();
819
820                 // derive GS baseline (perpendicular to the runay
821                 // along the ground)
822                 double tlon, tlat, taz;
823                 geo_direct_wgs_84 ( 0.0, gs_lat, gs_lon,
824                                     target_radial + 90,  
825                                     100.0, &tlat, &tlon, &taz );
826                 // cout << "target_radial = " << target_radial << endl;
827                 // cout << "nav_loc = " << loc_node->getBoolValue() << endl;
828                 // cout << gs_lon << "," << gs_lat << "  "
829                 //      << tlon << "," << tlat << "  (" << nav_elev << ")"
830                 //      << endl;
831                 Point3D p1 = sgGeodToCart( Point3D(tlon*SGD_DEGREES_TO_RADIANS,
832                                                    tlat*SGD_DEGREES_TO_RADIANS,
833                                                    nav_elev*SG_FEET_TO_METER)
834                                            );
835                 // cout << gs_x << "," << gs_y << "," << gs_z
836                 //      << endl;
837                 // cout << p1 << endl;
838                 sgdSetVec3( gs_base_vec,
839                             p1.x()-gs_x, p1.y()-gs_y, p1.z()-gs_z );
840                 // cout << gs_base_vec[0] << "," << gs_base_vec[1] << ","
841                 //      << gs_base_vec[2] << endl;
842             } else {
843                 has_gs_node->setBoolValue( false );
844                 nav_elev = loc->get_elev_ft();
845             }
846             twist = 0;
847             range = FG_LOC_DEFAULT_RANGE;
848             effective_range = range;
849
850             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
851                 globals->get_soundmgr()->remove( nav_fx_name );
852             }
853             SGSoundSample *sound;
854             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
855             sound->set_volume( 0.3 );
856             globals->get_soundmgr()->add( sound, nav_fx_name );
857
858             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
859                 globals->get_soundmgr()->remove( dme_fx_name );
860             }
861             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
862             sound->set_volume( 0.3 );
863             globals->get_soundmgr()->add( sound, dme_fx_name );
864
865             int offset = (int)(sg_random() * 30.0);
866             play_count = offset / 4;
867             last_time = globals->get_time_params()->get_cur_time() -
868                 offset;
869             // cout << "offset = " << offset << " play_count = "
870             //      << play_count
871             //      << " last_time = " << last_time
872             //      << " current time = "
873             //      << globals->get_time_params()->get_cur_time() << endl;
874
875             // cout << "Found an loc station in range" << endl;
876             // cout << " id = " << loc->get_locident() << endl;
877         }
878     } else if ( nav != NULL ) {
879         nav_id = nav->get_ident();
880         nav_id_node->setStringValue( nav_id.c_str() );
881         // cout << "nav = " << nav_id << endl;
882         is_valid = true;
883         if ( last_nav_id != nav_id || !last_nav_vor ) {
884             last_nav_id = nav_id;
885             last_nav_vor = true;
886             trans_ident = nav->get_trans_ident();
887             loc_node->setBoolValue( false );
888             has_dme = (dme != NULL);
889             has_gs_node->setBoolValue( false );
890             loc_lon = nav->get_lon();
891             loc_lat = nav->get_lat();
892             nav_elev = nav->get_elev_ft();
893             twist = nav->get_multiuse();
894             range = nav->get_range();
895             effective_range = adjustNavRange(nav_elev, elev, range);
896             target_gs = 0.0;
897             target_radial = sel_radial_node->getDoubleValue();
898             nav_x = nav->get_x();
899             nav_y = nav->get_y();
900             nav_z = nav->get_z();
901
902             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
903                 globals->get_soundmgr()->remove( nav_fx_name );
904             }
905             SGSoundSample *sound;
906             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
907             sound->set_volume( 0.3 );
908             if ( globals->get_soundmgr()->add( sound, nav_fx_name ) ) {
909                 // cout << "Added nav-vor-ident sound" << endl;
910             } else {
911                 SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
912             }
913
914             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
915                 globals->get_soundmgr()->remove( dme_fx_name );
916             }
917             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
918             sound->set_volume( 0.3 );
919             globals->get_soundmgr()->add( sound, dme_fx_name );
920
921             int offset = (int)(sg_random() * 30.0);
922             play_count = offset / 4;
923             last_time = globals->get_time_params()->get_cur_time() - offset;
924             // cout << "offset = " << offset << " play_count = "
925             //      << play_count << " last_time = "
926             //      << last_time << " current time = "
927             //      << globals->get_time_params()->get_cur_time() << endl;
928
929             // cout << "Found a vor station in range" << endl;
930             // cout << " id = " << nav->get_ident() << endl;
931         }
932     } else {
933         is_valid = false;
934         nav_id_node->setStringValue( "" );
935         target_radial = 0;
936         trans_ident = "";
937         last_nav_id = "";
938         if ( ! globals->get_soundmgr()->remove( nav_fx_name ) ) {
939             SG_LOG(SG_COCKPIT, SG_WARN, "Failed to remove nav-vor-ident sound");
940         }
941         globals->get_soundmgr()->remove( dme_fx_name );
942         // cout << "not picking up vor1. :-(" << endl;
943     }
944
945     char tmpid[5];
946     strncpy( tmpid, nav_id.c_str(), 5 );
947     id_c1_node->setIntValue( (int)tmpid[0] );
948     id_c2_node->setIntValue( (int)tmpid[1] );
949     id_c3_node->setIntValue( (int)tmpid[2] );
950     id_c4_node->setIntValue( (int)tmpid[3] );
951 }