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