]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
Torsten Dreyer:
[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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <sstream>
29
30 #include <simgear/sg_inlines.h>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/math/vector.hxx>
33 #include <simgear/math/sg_random.h>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/structure/exception.hxx>
36
37 #include <Navaids/navlist.hxx>
38 #include <Main/util.hxx>
39 #include "navradio.hxx"
40
41 using std::string;
42
43 // Constructor
44 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
45     lon_node(fgGetNode("/position/longitude-deg", true)),
46     lat_node(fgGetNode("/position/latitude-deg", true)),
47     alt_node(fgGetNode("/position/altitude-ft", true)),
48     is_valid_node(NULL),
49     power_btn_node(NULL),
50     freq_node(NULL),
51     alt_freq_node(NULL),
52     sel_radial_node(NULL),
53     vol_btn_node(NULL),
54     ident_btn_node(NULL),
55     audio_btn_node(NULL),
56     backcourse_node(NULL),
57     nav_serviceable_node(NULL),
58     cdi_serviceable_node(NULL),
59     gs_serviceable_node(NULL),
60     tofrom_serviceable_node(NULL),
61     fmt_freq_node(NULL),
62     fmt_alt_freq_node(NULL),
63     heading_node(NULL),
64     radial_node(NULL),
65     recip_radial_node(NULL),
66     target_radial_true_node(NULL),
67     target_auto_hdg_node(NULL),
68     time_to_intercept(NULL),
69     to_flag_node(NULL),
70     from_flag_node(NULL),
71     inrange_node(NULL),
72     signal_quality_norm_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(node->getStringValue("name", "nav")),
102     _num(node->getIntValue("number", 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
118
119 // Destructor
120 FGNavRadio::~FGNavRadio() 
121 {
122     delete term_tbl;
123     delete low_tbl;
124     delete high_tbl;
125 }
126
127
128 void
129 FGNavRadio::init ()
130 {
131     morse.init();
132
133     string branch;
134     branch = "/instrumentation/" + _name;
135
136     SGPropertyNode *node = fgGetNode(branch.c_str(), _num, true );
137
138     bus_power_node = 
139         fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
140
141     // inputs
142     is_valid_node = node->getChild("data-is-valid", 0, true);
143     power_btn_node = node->getChild("power-btn", 0, true);
144     power_btn_node->setBoolValue( true );
145     vol_btn_node = node->getChild("volume", 0, true);
146     ident_btn_node = node->getChild("ident", 0, true);
147     ident_btn_node->setBoolValue( true );
148     audio_btn_node = node->getChild("audio-btn", 0, true);
149     audio_btn_node->setBoolValue( true );
150     backcourse_node = node->getChild("back-course-btn", 0, true);
151     backcourse_node->setBoolValue( false );
152     nav_serviceable_node = node->getChild("serviceable", 0, true);
153     cdi_serviceable_node = (node->getChild("cdi", 0, true))
154         ->getChild("serviceable", 0, true);
155     gs_serviceable_node = (node->getChild("gs", 0, true))
156         ->getChild("serviceable");
157     tofrom_serviceable_node = (node->getChild("to-from", 0, true))
158         ->getChild("serviceable", 0, true);
159
160     // frequencies
161     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
162     freq_node = subnode->getChild("selected-mhz", 0, true);
163     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
164     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
165     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
166
167     // radials
168     subnode = node->getChild("radials", 0, true);
169     sel_radial_node = subnode->getChild("selected-deg", 0, true);
170     radial_node = subnode->getChild("actual-deg", 0, true);
171     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
172     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
173     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
174
175     // outputs
176     heading_node = node->getChild("heading-deg", 0, true);
177     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
178     to_flag_node = node->getChild("to-flag", 0, true);
179     from_flag_node = node->getChild("from-flag", 0, true);
180     inrange_node = node->getChild("in-range", 0, true);
181     signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
182     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
183     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
184     cdi_xtrack_hdg_err_node
185         = node->getChild("crosstrack-heading-error-deg", 0, true);
186     has_gs_node = node->getChild("has-gs", 0, true);
187     loc_node = node->getChild("nav-loc", 0, true);
188     loc_dist_node = node->getChild("nav-distance", 0, true);
189     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
190     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
191     gs_dist_node = node->getChild("gs-distance", 0, true);
192     nav_id_node = node->getChild("nav-id", 0, true);
193     id_c1_node = node->getChild("nav-id_asc1", 0, true);
194     id_c2_node = node->getChild("nav-id_asc2", 0, true);
195     id_c3_node = node->getChild("nav-id_asc3", 0, true);
196     id_c4_node = node->getChild("nav-id_asc4", 0, true);
197
198     // gps slaving support
199     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
200     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
201     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
202     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
203     
204     std::ostringstream temp;
205     temp << _name << "nav-ident" << _num;
206     nav_fx_name = temp.str();
207     temp << _name << "dme-ident" << _num;
208     dme_fx_name = temp.str();
209 }
210
211 void
212 FGNavRadio::bind ()
213 {
214     std::ostringstream temp;
215     string branch;
216     temp << _num;
217     branch = "/instrumentation/" + _name + "[" + temp.str() + "]";
218 }
219
220
221 void
222 FGNavRadio::unbind ()
223 {
224     std::ostringstream temp;
225     string branch;
226     temp << _num;
227     branch = "/instrumentation/" + _name + "[" + temp.str() + "]";
228 }
229
230
231 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
232 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
233                                  double nominalRange )
234 {
235     // extend out actual usable range to be 1.3x the published safe range
236     const double usability_factor = 1.3;
237
238     // assumptions we model the standard service volume, plus
239     // ... rather than specifying a cylinder, we model a cone that
240     // contains the cylinder.  Then we put an upside down cone on top
241     // to model diminishing returns at too-high altitudes.
242
243     // altitude difference
244     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
245     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
246     //      << " station elev = " << stationElev << endl;
247
248     if ( nominalRange < 25.0 + SG_EPSILON ) {
249         // Standard Terminal Service Volume
250         return term_tbl->interpolate( alt ) * usability_factor;
251     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
252         // Standard Low Altitude Service Volume
253         // table is based on range of 40, scale to actual range
254         return low_tbl->interpolate( alt ) * nominalRange / 40.0
255             * usability_factor;
256     } else {
257         // Standard High Altitude Service Volume
258         // table is based on range of 130, scale to actual range
259         return high_tbl->interpolate( alt ) * nominalRange / 130.0
260             * usability_factor;
261     }
262 }
263
264
265 // model standard ILS service volumes as per AIM 1-1-9
266 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
267                                  double offsetDegrees, double distance )
268 {
269     // assumptions we model the standard service volume, plus
270
271     // altitude difference
272     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
273 //     double offset = fabs( offsetDegrees );
274
275 //     if ( offset < 10 ) {
276 //      return FG_ILS_DEFAULT_RANGE;
277 //     } else if ( offset < 35 ) {
278 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
279 //     } else if ( offset < 45 ) {
280 //      return (45 - offset);
281 //     } else if ( offset > 170 ) {
282 //         return FG_ILS_DEFAULT_RANGE;
283 //     } else if ( offset > 145 ) {
284 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
285 //     } else if ( offset > 135 ) {
286 //         return (offset - 135);
287 //     } else {
288 //      return 0;
289 //     }
290     return FG_LOC_DEFAULT_RANGE;
291 }
292
293
294 //////////////////////////////////////////////////////////////////////////
295 // Update the various nav values based on position and valid tuned in navs
296 //////////////////////////////////////////////////////////////////////////
297 void 
298 FGNavRadio::update(double dt) 
299 {
300     // Do a nav station search only once a second to reduce
301     // unnecessary work. (Also, make sure to do this before caching
302     // any values!)
303     _time_before_search_sec -= dt;
304     if ( _time_before_search_sec < 0 ) {
305         search();
306     }
307
308     // cache a few strategic values locally for speed
309     SGGeod pos = SGGeod::fromDegFt(lon_node->getDoubleValue(),
310                                    lat_node->getDoubleValue(),
311                                    alt_node->getDoubleValue());
312     bool power_btn = power_btn_node->getBoolValue();
313     bool nav_serviceable = nav_serviceable_node->getBoolValue();
314     bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
315     bool tofrom_serviceable = tofrom_serviceable_node->getBoolValue();
316     bool inrange = inrange_node->getBoolValue();
317     bool has_gs = has_gs_node->getBoolValue();
318     bool is_loc = loc_node->getBoolValue();
319     double loc_dist = loc_dist_node->getDoubleValue();
320     double effective_range_m;
321     double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
322
323     double az1, az2, s;
324
325     // Create "formatted" versions of the nav frequencies for
326     // instrument displays.
327     char tmp[16];
328     sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
329     fmt_freq_node->setStringValue(tmp);
330     sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
331     fmt_alt_freq_node->setStringValue(tmp);
332
333     // cout << "is_valid = " << is_valid
334     //      << " power_btn = " << power_btn
335     //      << " bus_power = " << bus_power_node->getDoubleValue()
336     //      << " nav_serviceable = " << nav_serviceable
337     //      << endl;
338
339     if ( is_valid && power_btn && (bus_power_node->getDoubleValue() > 1.0)
340          && nav_serviceable )
341     {
342         SGVec3d aircraft = SGVec3d::fromGeod(pos);
343         loc_dist = dist(aircraft, nav_xyz);
344         loc_dist_node->setDoubleValue( loc_dist );
345         // cout << "dt = " << dt << " dist = " << loc_dist << endl;
346
347         if ( has_gs ) {
348             // find closest distance to the gs base line
349             SGVec3d p = aircraft;
350             double dist = sgdClosestPointToLineDistSquared(p.sg(), gs_xyz.sg(),
351                                                            gs_base_vec.sg());
352             gs_dist_node->setDoubleValue( sqrt( dist ) );
353             // cout << "gs_dist = " << gs_dist_node->getDoubleValue()
354             //      << endl;
355
356             // wgs84 heading to glide slope (to determine sign of distance)
357             geo_inverse_wgs_84( pos, SGGeod::fromDeg(gs_lon, gs_lat),
358                                 &az1, &az2, &s );
359             double r = az1 - target_radial;
360             while ( r >  180.0 ) { r -= 360.0;}
361             while ( r < -180.0 ) { r += 360.0;}
362             if ( r >= -90.0 && r <= 90.0 ) {
363                 gs_dist_signed = gs_dist_node->getDoubleValue();
364             } else {
365                 gs_dist_signed = -gs_dist_node->getDoubleValue();
366             }
367             /* cout << "Target Radial = " << target_radial 
368                  << "  Bearing = " << az1
369                  << "  dist (signed) = " << gs_dist_signed
370                  << endl; */
371             
372         } else {
373             gs_dist_node->setDoubleValue( 0.0 );
374         }
375         
376         //////////////////////////////////////////////////////////
377         // compute forward and reverse wgs84 headings to localizer
378         //////////////////////////////////////////////////////////
379         double hdg;
380         geo_inverse_wgs_84( pos, SGGeod::fromDeg(loc_lon, loc_lat),
381                             &hdg, &az2, &s );
382         // cout << "az1 = " << az1 << " magvar = " << nav_magvar << endl;
383         heading_node->setDoubleValue( hdg );
384         radial = az2 - twist;
385         double recip = radial + 180.0;
386         if ( recip >= 360.0 ) { recip -= 360.0; }
387         radial_node->setDoubleValue( radial );
388         recip_radial_node->setDoubleValue( recip );
389         // cout << " heading = " << heading_node->getDoubleValue()
390         //      << " dist = " << nav_dist << endl;
391
392         //////////////////////////////////////////////////////////
393         // compute the target/selected radial in "true" heading
394         //////////////////////////////////////////////////////////
395         double trtrue = 0.0;
396         if ( is_loc ) {
397             // ILS localizers radials are already "true" in our
398             // database
399             trtrue = target_radial;
400         } else {
401             // VOR radials need to have that vor's offset added in
402             trtrue = target_radial + twist;
403         }
404
405         while ( trtrue < 0.0 ) { trtrue += 360.0; }
406         while ( trtrue > 360.0 ) { trtrue -= 360.0; }
407         target_radial_true_node->setDoubleValue( trtrue );
408
409         //////////////////////////////////////////////////////////
410         // adjust reception range for altitude
411         // FIXME: make sure we are using the navdata range now that
412         //        it is valid in the data file
413         //////////////////////////////////////////////////////////
414         if ( is_loc ) {
415             double offset = radial - target_radial;
416             while ( offset < -180.0 ) { offset += 360.0; }
417             while ( offset > 180.0 ) { offset -= 360.0; }
418             // cout << "ils offset = " << offset << endl;
419             effective_range
420                 = adjustILSRange( nav_elev, pos.getElevationM(), offset,
421                                   loc_dist * SG_METER_TO_NM );
422         } else {
423             effective_range
424                 = adjustNavRange( nav_elev, pos.getElevationM(), range );
425         }
426
427         effective_range_m = effective_range * SG_NM_TO_METER;
428
429         // cout << "nav range = " << effective_range
430         //      << " (" << range << ")" << endl;
431
432         //////////////////////////////////////////////////////////
433         // compute signal quality
434         // 100% within effective_range
435         // decreases 1/x^2 further out
436         //////////////////////////////////////////////////////////
437         {
438             double last_signal_quality_norm = signal_quality_norm;
439
440             if ( loc_dist < effective_range_m ) {
441               signal_quality_norm = 1.0;
442             } else {
443               double range_exceed_norm = loc_dist/effective_range_m;
444               signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
445             }
446
447             signal_quality_norm = fgGetLowPass( last_signal_quality_norm, 
448                    signal_quality_norm, dt );
449         }
450         signal_quality_norm_node->setDoubleValue( signal_quality_norm );
451         inrange = signal_quality_norm > 0.2;
452         inrange_node->setBoolValue( inrange );
453
454         if ( !is_loc ) {
455             target_radial = sel_radial_node->getDoubleValue();
456         }
457
458         //////////////////////////////////////////////////////////
459         // compute to/from flag status
460         //////////////////////////////////////////////////////////
461         bool value = false;
462         double offset = fabs(radial - target_radial);
463         if ( tofrom_serviceable ) {
464             if ( nav_slaved_to_gps_node->getBoolValue() ) {
465                 value = gps_to_flag_node->getBoolValue();
466             } else if ( inrange ) {
467                 if ( is_loc ) {
468                     value = true;
469                 } else {
470                     value = !(offset <= 90.0 || offset >= 270.0);
471                 }
472             }
473         } else {
474             value = false;
475         }
476         to_flag_node->setBoolValue( value );
477
478         value = false;
479         if ( tofrom_serviceable ) {
480             if ( nav_slaved_to_gps_node->getBoolValue() ) {
481                 value = gps_from_flag_node->getBoolValue();
482             } else if ( inrange ) {
483                 if ( is_loc ) {
484                     value = false;
485                 } else {
486                     value = !(offset > 90.0 && offset < 270.0);
487                 }
488             }
489         } else {
490             value = false;
491         }
492         from_flag_node->setBoolValue( value );
493
494         //////////////////////////////////////////////////////////
495         // compute the deflection of the CDI needle, clamped to the range
496         // of ( -10 , 10 )
497         //////////////////////////////////////////////////////////
498         double r = 0.0;
499         bool loc_backside = false; // an in-code flag indicating that we are
500                                    // on a localizer backcourse.
501         if ( cdi_serviceable ) {
502             if ( nav_slaved_to_gps_node->getBoolValue() ) {
503                 r = gps_cdi_deflection_node->getDoubleValue();
504                 // We want +- 5 dots deflection for the gps, so clamp
505                 // to -12.5/12.5
506                 SG_CLAMP_RANGE( r, -12.5, 12.5 );
507             } else if ( inrange ) {
508                 r = radial - target_radial;
509                 // cout << "Target radial = " << target_radial 
510                 //      << "  Actual radial = " << radial << endl;
511                 
512                 while ( r >  180.0 ) { r -= 360.0;}
513                 while ( r < -180.0 ) { r += 360.0;}
514                 if ( fabs(r) > 90.0 ) {
515                     r = ( r<0.0 ? -r-180.0 : -r+180.0 );
516                 } else {
517                     if ( is_loc ) {
518                         loc_backside = true;
519                     }
520                 }
521
522                 r = -r;         // reverse, since radial is outbound
523                 if ( is_loc ) {
524                     // According to Robin Peel, the ILS is 4x more
525                     // sensitive than a vor
526                     r *= 4.0;
527                 }
528                 SG_CLAMP_RANGE( r, -10.0, 10.0 );
529                 r *= signal_quality_norm;
530             }
531         }
532         cdi_deflection_node->setDoubleValue( r );
533
534         //////////////////////////////////////////////////////////
535         // compute the amount of cross track distance error in meters
536         //////////////////////////////////////////////////////////
537         double xtrack_error = 0.0;
538         if ( inrange && nav_serviceable && cdi_serviceable ) {
539             r = radial - target_radial;
540             // cout << "Target radial = " << target_radial 
541             //     << "  Actual radial = " << radial
542             //     << "  r = " << r << endl;
543     
544             while ( r >  180.0 ) { r -= 360.0;}
545             while ( r < -180.0 ) { r += 360.0;}
546             if ( fabs(r) > 90.0 ) {
547                 r = ( r<0.0 ? -r-180.0 : -r+180.0 );
548             }
549
550             r = -r;             // reverse, since radial is outbound
551
552             xtrack_error = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
553         } else {
554             xtrack_error = 0.0;
555         }
556         cdi_xtrack_error_node->setDoubleValue( xtrack_error );
557
558         //////////////////////////////////////////////////////////
559         // compute an approximate ground track heading error
560         //////////////////////////////////////////////////////////
561         double hdg_error = 0.0;
562         if ( inrange && cdi_serviceable ) {
563             double vn = fgGetDouble( "/velocities/speed-north-fps" );
564             double ve = fgGetDouble( "/velocities/speed-east-fps" );
565             double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
566             if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
567
568             SGPropertyNode *true_hdg
569                 = fgGetNode("/orientation/heading-deg", true);
570             hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
571
572             // cout << "ground track = " << gnd_trk_true
573             //      << " orientation = " << true_hdg->getDoubleValue() << endl;
574         }
575         cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
576
577         //////////////////////////////////////////////////////////
578         // compute the time to intercept selected radial (based on
579         // current and last cross track errors and dt
580         //////////////////////////////////////////////////////////
581         double t = 0.0;
582         if ( inrange && cdi_serviceable ) {
583             double xrate_ms = (last_xtrack_error - xtrack_error) / dt;
584             if ( fabs(xrate_ms) > 0.00001 ) {
585                 t = xtrack_error / xrate_ms;
586             } else {
587                 t = 9999.9;
588             }
589         }
590         time_to_intercept->setDoubleValue( t );
591
592         //////////////////////////////////////////////////////////
593         // compute the amount of glide slope needle deflection
594         // (.i.e. the number of degrees we are off the glide slope * 5.0
595         //
596         // CLO - 13 Mar 2006: The glide slope needle should peg at
597         // +/-0.7 degrees off the ideal glideslope.  I'm not sure why
598         // we compute the factor the way we do (5*gs_error), but we
599         // need to compensate for our 'odd' number in the glideslope
600         // needle animation.  This means that the needle should peg
601         // when this values is +/-3.5.
602         //////////////////////////////////////////////////////////
603         r = 0.0;
604         if ( has_gs && gs_serviceable_node->getBoolValue() ) {
605             if ( nav_slaved_to_gps_node->getBoolValue() ) {
606                 // FIXME/FINISHME, what should be set here?
607             } else if ( inrange ) {
608                 double x = gs_dist_node->getDoubleValue();
609                 double y = (fgGetDouble("/position/altitude-ft") - nav_elev)
610                     * SG_FEET_TO_METER;
611                 // cout << "dist = " << x << " height = " << y << endl;
612                 double angle = asin( y / x ) * SGD_RADIANS_TO_DEGREES;
613                 r = (target_gs - angle) * 5.0;
614                 r *= signal_quality_norm;
615             }
616         }
617         gs_deflection_node->setDoubleValue( r );
618
619         //////////////////////////////////////////////////////////
620         // Calculate desired rate of climb for intercepting the GS
621         //////////////////////////////////////////////////////////
622         double x = gs_dist_node->getDoubleValue();
623         double y = (alt_node->getDoubleValue() - nav_elev)
624             * SG_FEET_TO_METER;
625         double current_angle = atan2( y, x ) * SGD_RADIANS_TO_DEGREES;
626
627         double target_angle = target_gs;
628         double gs_diff = target_angle - current_angle;
629
630         // convert desired vertical path angle into a climb rate
631         double des_angle = current_angle - 10 * gs_diff;
632
633         // estimate horizontal speed towards ILS in meters per minute
634         double dist = last_x - x;
635         last_x = x;
636         if ( dt > 0.0 ) {
637             // avoid nan
638             double new_vel = ( dist / dt );
639  
640             horiz_vel = 0.75 * horiz_vel + 0.25 * new_vel;
641             // double horiz_vel = cur_fdm_state->get_V_ground_speed()
642             //    * SG_FEET_TO_METER * 60.0;
643             // double horiz_vel = airspeed_node->getFloatValue()
644             //    * SG_FEET_TO_METER * 60.0;
645
646             gs_rate_of_climb_node
647                 ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
648                                   * horiz_vel * SG_METER_TO_FEET );
649         }
650
651         //////////////////////////////////////////////////////////
652         // Calculate a suggested target heading to smoothly intercept
653         // a nav/ils radial.
654         //////////////////////////////////////////////////////////
655
656         // Now that we have cross track heading adjustment built in,
657         // we shouldn't need to overdrive the heading angle within 8km
658         // of the station.
659         //
660         // The cdi deflection should be +/-10 for a full range of deflection
661         // so multiplying this by 3 gives us +/- 30 degrees heading
662         // compensation.
663         double adjustment = cdi_deflection_node->getDoubleValue() * 3.0;
664         SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
665
666         // determine the target heading to fly to intercept the
667         // tgt_radial = target radial (true) + cdi offset adjustmest -
668         // xtrack heading error adjustment
669         double nta_hdg;
670         if ( is_loc && backcourse_node->getBoolValue() ) {
671             // tuned to a localizer and backcourse mode activated
672             trtrue += 180.0;   // reverse the target localizer heading
673             while ( trtrue > 360.0 ) { trtrue -= 360.0; }
674             nta_hdg = trtrue - adjustment - hdg_error;
675         } else {
676             nta_hdg = trtrue + adjustment - hdg_error;
677         }
678
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_xyz = loc->get_cart();
803             last_nav_id = nav_id;
804             last_nav_vor = false;
805             loc_node->setBoolValue( true );
806             has_dme = (dme != NULL);
807             if ( gs != NULL ) {
808                 has_gs_node->setBoolValue( true );
809                 gs_lon = gs->get_lon();
810                 gs_lat = gs->get_lat();
811                 nav_elev = gs->get_elev_ft();
812                 int tmp = (int)(gs->get_multiuse() / 1000.0);
813                 target_gs = (double)tmp / 100.0;
814                 gs_xyz = gs->get_cart();
815
816                 // derive GS baseline (perpendicular to the runay
817                 // along the ground)
818                 double tlon, tlat, taz;
819                 geo_direct_wgs_84 ( 0.0, gs_lat, gs_lon,
820                                     target_radial + 90,
821                                     100.0, &tlat, &tlon, &taz );
822                 // cout << "target_radial = " << target_radial << endl;
823                 // cout << "nav_loc = " << loc_node->getBoolValue() << endl;
824                 // cout << gs_lon << "," << gs_lat << "  "
825                 //      << tlon << "," << tlat << "  (" << nav_elev << ")"
826                 //      << endl;
827                 SGGeod tpos = SGGeod::fromDegFt(tlon, tlat, nav_elev);
828                 SGVec3d p1 = SGVec3d::fromGeod(tpos);
829
830                 // cout << gs_xyz << endl;
831                 // cout << p1 << endl;
832                 gs_base_vec = p1 - gs_xyz;
833                 // cout << gs_base_vec << endl;
834             } else {
835                 has_gs_node->setBoolValue( false );
836                 nav_elev = loc->get_elev_ft();
837             }
838             twist = 0;
839             range = FG_LOC_DEFAULT_RANGE;
840             effective_range = range;
841
842             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
843                 globals->get_soundmgr()->remove( nav_fx_name );
844             }
845             SGSoundSample *sound;
846             sound = morse.make_ident( trans_ident, LO_FREQUENCY );
847             sound->set_volume( 0.3 );
848             globals->get_soundmgr()->add( sound, nav_fx_name );
849
850             if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
851                 globals->get_soundmgr()->remove( dme_fx_name );
852             }
853             sound = morse.make_ident( trans_ident, HI_FREQUENCY );
854             sound->set_volume( 0.3 );
855             globals->get_soundmgr()->add( sound, dme_fx_name );
856
857             int offset = (int)(sg_random() * 30.0);
858             play_count = offset / 4;
859             last_time = globals->get_time_params()->get_cur_time() -
860                 offset;
861             // cout << "offset = " << offset << " play_count = "
862             //      << play_count
863             //      << " last_time = " << last_time
864             //      << " current time = "
865             //      << globals->get_time_params()->get_cur_time() << endl;
866
867             // cout << "Found an loc station in range" << endl;
868             // cout << " id = " << loc->get_locident() << endl;
869         }
870     } else if ( nav != NULL ) {
871         nav_id = nav->get_ident();
872         nav_id_node->setStringValue( nav_id.c_str() );
873         // cout << "nav = " << nav_id << endl;
874         is_valid = true;
875         if ( last_nav_id != nav_id || !last_nav_vor ) {
876             last_nav_id = nav_id;
877             last_nav_vor = true;
878             trans_ident = nav->get_trans_ident();
879             loc_node->setBoolValue( false );
880             has_dme = (dme != NULL);
881             has_gs_node->setBoolValue( false );
882             loc_lon = nav->get_lon();
883             loc_lat = nav->get_lat();
884             nav_elev = nav->get_elev_ft();
885             twist = nav->get_multiuse();
886             range = nav->get_range();
887             effective_range = adjustNavRange(nav_elev, elev, range);
888             target_gs = 0.0;
889             target_radial = sel_radial_node->getDoubleValue();
890             nav_xyz = nav->get_cart();
891
892             if ( globals->get_soundmgr()->exists( nav_fx_name ) ) {
893                 globals->get_soundmgr()->remove( nav_fx_name );
894             }
895             try {
896                 SGSoundSample *sound;
897                 sound = morse.make_ident( trans_ident, LO_FREQUENCY );
898                 sound->set_volume( 0.3 );
899                 if ( globals->get_soundmgr()->add( sound, nav_fx_name ) ) {
900                     // cout << "Added nav-vor-ident sound" << endl;
901                 } else {
902                     SG_LOG(SG_COCKPIT, SG_WARN, "Failed to add v1-vor-ident sound");
903                 }
904
905                 if ( globals->get_soundmgr()->exists( dme_fx_name ) ) {
906                     globals->get_soundmgr()->remove( dme_fx_name );
907                 }
908                 sound = morse.make_ident( trans_ident, HI_FREQUENCY );
909                 sound->set_volume( 0.3 );
910                 globals->get_soundmgr()->add( sound, dme_fx_name );
911
912                 int offset = (int)(sg_random() * 30.0);
913                 play_count = offset / 4;
914                 last_time = globals->get_time_params()->get_cur_time() - offset;
915                 // cout << "offset = " << offset << " play_count = "
916                 //      << play_count << " last_time = "
917                 //      << last_time << " current time = "
918                 //      << globals->get_time_params()->get_cur_time() << endl;
919
920                 // cout << "Found a vor station in range" << endl;
921                 // cout << " id = " << nav->get_ident() << endl;
922             } catch ( sg_io_exception &e ) {
923                 SG_LOG(SG_GENERAL, SG_ALERT, e.getFormattedMessage());
924             }
925         }
926     } else {
927         is_valid = false;
928         nav_id_node->setStringValue( "" );
929         target_radial = 0;
930         trans_ident = "";
931         last_nav_id = "";
932         globals->get_soundmgr()->remove( nav_fx_name );
933         globals->get_soundmgr()->remove( dme_fx_name );
934     }
935
936     is_valid_node->setBoolValue( is_valid );
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 }