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