]> git.mxchange.org Git - flightgear.git/blob - src/Instrumentation/navradio.cxx
Make the radio interpolation tables static.
[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
22 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #include <sstream>
27 #include <cstring>
28
29 #include <simgear/sg_inlines.h>
30 #include <simgear/timing/sg_time.hxx>
31 #include <simgear/math/sg_random.h>
32 #include <simgear/misc/sg_path.hxx>
33 #include <simgear/math/sg_geodesy.hxx>
34 #include <simgear/structure/exception.hxx>
35 #include <simgear/math/interpolater.hxx>
36 #include <simgear/misc/strutils.hxx>
37
38 #include <Navaids/navrecord.hxx>
39 #include <Sound/audioident.hxx>
40 #include <Airports/runways.hxx>
41 #include <Navaids/navlist.hxx>
42 #include <Main/util.hxx>
43
44 #include "navradio.hxx"
45
46 using std::string;
47
48 // General-purpose sawtooth function.  Graph looks like this:
49 //         /\                                    .
50 //       \/
51 // Odd symmetry, inversion symmetry about the origin.
52 // Unit slope at the origin.
53 // Max 1, min -1, period 4.
54 // Two zero-crossings per period, one with + slope, one with - slope.
55 // Useful for false localizer courses.
56 static double sawtooth(double xx)
57 {
58   return 4.0 * fabs(xx/4.0 + 0.25 - floor(xx/4.0 + 0.75)) - 1.0;
59 }
60
61 // Calculate a Cartesian unit vector in the
62 // local horizontal plane, i.e. tangent to the 
63 // surface of the earth at the local ground zero.
64 // The tangent vector passes through the given  <midpoint> 
65 // and points forward along the given <heading>.
66 // The <heading> is given in degrees.
67 static SGVec3d tangentVector(const SGGeod& midpoint, const double heading)
68 {
69 // The size of the delta is presumably chosen to give
70 // numerical stability.  I don't know how the value was chosen.
71 // It probably doesn't matter much.  It gets divided out.
72   double delta(100.0);          // in meters
73   SGGeod head, tail;
74   double az2;                   // ignored
75   SGGeodesy::direct(midpoint, heading,     delta, head, az2);
76   SGGeodesy::direct(midpoint, 180+heading, delta, tail, az2);
77   head.setElevationM(midpoint.getElevationM());
78   tail.setElevationM(midpoint.getElevationM());
79   SGVec3d head_xyz = SGVec3d::fromGeod(head);
80   SGVec3d tail_xyz = SGVec3d::fromGeod(tail);
81 // Awkward formula here, needed because vector-by-scalar
82 // multiplication is defined, but not vector-by-scalar division.
83   return (head_xyz - tail_xyz) * (0.5/delta);
84 }
85
86 // Create a "serviceable" node with a default value of "true"
87 SGPropertyNode_ptr createServiceableProp(SGPropertyNode* aParent, 
88         const char* aName)
89 {
90   SGPropertyNode_ptr n = 
91      aParent->getChild(aName, 0, true)->getChild("serviceable", 0, true);
92   simgear::props::Type typ = n->getType();
93   if ((typ == simgear::props::NONE) || (typ == simgear::props::UNSPECIFIED)) {
94     n->setBoolValue(true);
95   }
96   return n;  
97 }
98
99 static std::auto_ptr<SGInterpTable> static_terminalRangeInterp,
100   static_lowRangeInterp, static_highRangeInterp;
101
102 // Constructor
103 FGNavRadio::FGNavRadio(SGPropertyNode *node) :
104     _operable(false),
105     play_count(0),
106     _last_freq(0.0),
107     target_radial(0.0),
108     effective_range(0.0),
109     target_gs(0.0),
110     twist(0.0),
111     horiz_vel(0.0),
112     last_x(0.0),
113     last_xtrack_error(0.0),
114     xrate_ms(0.0),
115     _localizerWidth(5.0),
116     _name(node->getStringValue("name", "nav")),
117     _num(node->getIntValue("number", 0)),
118     _time_before_search_sec(-1.0),
119     _gsCart(SGVec3d::zeros()),
120     _gsAxis(SGVec3d::zeros()),
121     _gsVertical(SGVec3d::zeros()),
122     _toFlag(false),
123     _fromFlag(false),
124     _cdiDeflection(0.0),
125     _cdiCrossTrackErrorM(0.0),
126     _gsNeedleDeflection(0.0),
127     _gsNeedleDeflectionNorm(0.0),
128     _audioIdent(NULL)
129 {
130     if (!static_terminalRangeInterp.get()) {
131     // one-time interpolator init
132       SGPath path( globals->get_fg_root() );
133       SGPath term = path;
134       term.append( "Navaids/range.term" );
135       SGPath low = path;
136       low.append( "Navaids/range.low" );
137       SGPath high = path;
138       high.append( "Navaids/range.high" );
139       
140       static_terminalRangeInterp.reset(new SGInterpTable(term.str()));
141       static_lowRangeInterp.reset(new SGInterpTable(low.str()));
142       static_highRangeInterp.reset(new SGInterpTable(high.str()));
143     }
144   
145     string branch("/instrumentation/" + _name);
146     _radio_node = fgGetNode(branch.c_str(), _num, true);
147 }
148
149
150 // Destructor
151 FGNavRadio::~FGNavRadio() 
152 {
153     if (gps_course_node) {
154       gps_course_node->removeChangeListener(this);
155     }
156     
157     if (nav_slaved_to_gps_node) {
158       nav_slaved_to_gps_node->removeChangeListener(this);
159     }
160     
161     delete _audioIdent;
162 }
163
164
165 void
166 FGNavRadio::init ()
167 {
168     SGPropertyNode* node = _radio_node.get();
169     bus_power_node = 
170         fgGetNode(("/systems/electrical/outputs/" + _name).c_str(), true);
171
172     // inputs
173     is_valid_node = node->getChild("data-is-valid", 0, true);
174     power_btn_node = node->getChild("power-btn", 0, true);
175     power_btn_node->setBoolValue( true );
176     vol_btn_node = node->getChild("volume", 0, true);
177     ident_btn_node = node->getChild("ident", 0, true);
178     ident_btn_node->setBoolValue( true );
179     audio_btn_node = node->getChild("audio-btn", 0, true);
180     audio_btn_node->setBoolValue( true );
181     backcourse_node = node->getChild("back-course-btn", 0, true);
182     backcourse_node->setBoolValue( false );
183     
184     nav_serviceable_node = node->getChild("serviceable", 0, true);
185     cdi_serviceable_node = createServiceableProp(node, "cdi");
186     gs_serviceable_node = createServiceableProp(node, "gs");
187     tofrom_serviceable_node = createServiceableProp(node, "to-from");
188     
189     falseCoursesEnabledNode = 
190       fgGetNode("/sim/realism/false-radio-courses-enabled");
191     if (!falseCoursesEnabledNode) {
192       falseCoursesEnabledNode = 
193         fgGetNode("/sim/realism/false-radio-courses-enabled", true);
194       falseCoursesEnabledNode->setBoolValue(true);
195     }
196
197     // frequencies
198     SGPropertyNode *subnode = node->getChild("frequencies", 0, true);
199     freq_node = subnode->getChild("selected-mhz", 0, true);
200     alt_freq_node = subnode->getChild("standby-mhz", 0, true);
201     fmt_freq_node = subnode->getChild("selected-mhz-fmt", 0, true);
202     fmt_alt_freq_node = subnode->getChild("standby-mhz-fmt", 0, true);
203     is_loc_freq_node = subnode->getChild("is-localizer-frequency", 0, true );
204
205     // radials
206     subnode = node->getChild("radials", 0, true);
207     sel_radial_node = subnode->getChild("selected-deg", 0, true);
208     radial_node = subnode->getChild("actual-deg", 0, true);
209     recip_radial_node = subnode->getChild("reciprocal-radial-deg", 0, true);
210     target_radial_true_node = subnode->getChild("target-radial-deg", 0, true);
211     target_auto_hdg_node = subnode->getChild("target-auto-hdg-deg", 0, true);
212
213     // outputs
214     heading_node = node->getChild("heading-deg", 0, true);
215     time_to_intercept = node->getChild("time-to-intercept-sec", 0, true);
216     to_flag_node = node->getChild("to-flag", 0, true);
217     from_flag_node = node->getChild("from-flag", 0, true);
218     inrange_node = node->getChild("in-range", 0, true);
219     signal_quality_norm_node = node->getChild("signal-quality-norm", 0, true);
220     cdi_deflection_node = node->getChild("heading-needle-deflection", 0, true);
221     cdi_deflection_norm_node = node->getChild("heading-needle-deflection-norm", 0, true);
222     cdi_xtrack_error_node = node->getChild("crosstrack-error-m", 0, true);
223     cdi_xtrack_hdg_err_node
224         = node->getChild("crosstrack-heading-error-deg", 0, true);
225     has_gs_node = node->getChild("has-gs", 0, true);
226     loc_node = node->getChild("nav-loc", 0, true);
227     loc_dist_node = node->getChild("nav-distance", 0, true);
228     gs_deflection_node = node->getChild("gs-needle-deflection", 0, true);
229     gs_deflection_deg_node = node->getChild("gs-needle-deflection-deg", 0, true);
230     gs_deflection_norm_node = node->getChild("gs-needle-deflection-norm", 0, true);
231     gs_direct_node = node->getChild("gs-direct-deg", 0, true);
232     gs_rate_of_climb_node = node->getChild("gs-rate-of-climb", 0, true);
233     gs_rate_of_climb_fpm_node = node->getChild("gs-rate-of-climb-fpm", 0, true);
234     gs_dist_node = node->getChild("gs-distance", 0, true);
235     gs_inrange_node = node->getChild("gs-in-range", 0, true);
236     
237     nav_id_node = node->getChild("nav-id", 0, true);
238     id_c1_node = node->getChild("nav-id_asc1", 0, true);
239     id_c2_node = node->getChild("nav-id_asc2", 0, true);
240     id_c3_node = node->getChild("nav-id_asc3", 0, true);
241     id_c4_node = node->getChild("nav-id_asc4", 0, true);
242
243     // gps slaving support
244     nav_slaved_to_gps_node = node->getChild("slaved-to-gps", 0, true);
245     nav_slaved_to_gps_node->addChangeListener(this);
246     
247     gps_cdi_deflection_node = fgGetNode("/instrumentation/gps/cdi-deflection", true);
248     gps_to_flag_node = fgGetNode("/instrumentation/gps/to-flag", true);
249     gps_from_flag_node = fgGetNode("/instrumentation/gps/from-flag", true);
250     gps_has_gs_node = fgGetNode("/instrumentation/gps/has-gs", true);
251     gps_course_node = fgGetNode("/instrumentation/gps/desired-course-deg", true);
252     gps_course_node->addChangeListener(this);
253     
254     gps_xtrack_error_nm_node = fgGetNode("/instrumentation/gps/wp/wp[1]/course-error-nm", true);
255     _magvarNode = fgGetNode("/environment/magnetic-variation-deg", true);
256     
257     std::ostringstream temp;
258     temp << _name << "-ident-" << _num;
259     if( NULL == _audioIdent ) 
260         _audioIdent = new VORAudioIdent( temp.str() );
261     _audioIdent->init();
262
263     // dme-in-range is deprecated,
264     // temporarily create dme-in-range alias for instrumentation/dme[0]/in-range
265     // remove after flightgear 2.6.0
266     node->getNode( "dme-in-range", true )->alias( fgGetNode("/instrumentation/dme[0]/in-range", true ) );
267 }
268
269 void
270 FGNavRadio::reinit ()
271 {
272     _time_before_search_sec = -1.0;
273 }
274
275 void
276 FGNavRadio::bind ()
277 {
278     _radio_node->tie( "operable", SGRawValueMethods<FGNavRadio,bool>( *this, &FGNavRadio::isOperable ) );
279 }
280
281
282 void
283 FGNavRadio::unbind ()
284 {
285     _radio_node->untie("operable");
286 }
287
288
289 // model standard VOR/DME/TACAN service volumes as per AIM 1-1-8
290 double FGNavRadio::adjustNavRange( double stationElev, double aircraftElev,
291                                  double nominalRange )
292 {
293     if (nominalRange <= 0.0) {
294       nominalRange = FG_NAV_DEFAULT_RANGE;
295     }
296     
297     // extend out actual usable range to be 1.3x the published safe range
298     const double usability_factor = 1.3;
299
300     // assumptions we model the standard service volume, plus
301     // ... rather than specifying a cylinder, we model a cone that
302     // contains the cylinder.  Then we put an upside down cone on top
303     // to model diminishing returns at too-high altitudes.
304
305     // altitude difference
306     double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
307     // cout << "aircraft elev = " << aircraftElev * SG_METER_TO_FEET
308     //      << " station elev = " << stationElev << endl;
309
310     if ( nominalRange < 25.0 + SG_EPSILON ) {
311       // Standard Terminal Service Volume
312       return static_terminalRangeInterp->interpolate( alt ) * usability_factor;
313     } else if ( nominalRange < 50.0 + SG_EPSILON ) {
314         // Standard Low Altitude Service Volume
315         // table is based on range of 40, scale to actual range
316       return static_lowRangeInterp->interpolate( alt ) * nominalRange / 40.0
317             * usability_factor;
318     } else {
319         // Standard High Altitude Service Volume
320         // table is based on range of 130, scale to actual range
321       return static_highRangeInterp->interpolate( alt ) * nominalRange / 130.0
322             * usability_factor;
323     }
324 }
325
326
327 // model standard ILS service volumes as per AIM 1-1-9
328 double FGNavRadio::adjustILSRange( double stationElev, double aircraftElev,
329                                  double offsetDegrees, double distance )
330 {
331     // assumptions we model the standard service volume, plus
332
333     // altitude difference
334     // double alt = ( aircraftElev * SG_METER_TO_FEET - stationElev );
335 //     double offset = fabs( offsetDegrees );
336
337 //     if ( offset < 10 ) {
338 //      return FG_ILS_DEFAULT_RANGE;
339 //     } else if ( offset < 35 ) {
340 //      return 10 + (35 - offset) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
341 //     } else if ( offset < 45 ) {
342 //      return (45 - offset);
343 //     } else if ( offset > 170 ) {
344 //         return FG_ILS_DEFAULT_RANGE;
345 //     } else if ( offset > 145 ) {
346 //      return 10 + (offset - 145) * (FG_ILS_DEFAULT_RANGE - 10) / 25;
347 //     } else if ( offset > 135 ) {
348 //         return (offset - 135);
349 //     } else {
350 //      return 0;
351 //     }
352     return FG_LOC_DEFAULT_RANGE;
353 }
354
355 // Frequencies with odd 100kHz numbers in the range from 108.00 - 111.95
356 // are LOC/GS (ILS) frequency pairs
357 // (108.00, 108.05, 108.20, 108.25.. =VOR)
358 // (108.10, 108.15, 108.30, 108.35.. =ILS)
359 static inline bool IsLocalizerFrequency( double f )
360 {
361   if( f < 108.0 || f >= 112.00 ) return false;
362   return (((SGMiscd::roundToInt(f * 100.0) % 100)/10) % 2) != 0;
363 }
364
365
366 //////////////////////////////////////////////////////////////////////////
367 // Update the various nav values based on position and valid tuned in navs
368 //////////////////////////////////////////////////////////////////////////
369 void 
370 FGNavRadio::update(double dt) 
371 {
372   if (dt <= 0.0) {
373     return; // paused
374   }
375     
376   // Create "formatted" versions of the nav frequencies for
377   // instrument displays.
378   char tmp[16];
379   sprintf( tmp, "%.2f", freq_node->getDoubleValue() );
380   fmt_freq_node->setStringValue(tmp);
381   sprintf( tmp, "%.2f", alt_freq_node->getDoubleValue() );
382   fmt_alt_freq_node->setStringValue(tmp);
383   is_loc_freq_node->setBoolValue( IsLocalizerFrequency( freq_node->getDoubleValue() ));
384
385   if (power_btn_node->getBoolValue() 
386       && (bus_power_node->getDoubleValue() > 1.0)
387       && nav_serviceable_node->getBoolValue() )
388   {
389     _operable = true;
390     updateReceiver(dt);
391     updateCDI(dt);
392   } else {
393     clearOutputs();
394   }
395   
396   updateAudio( dt );
397 }
398
399 void FGNavRadio::clearOutputs()
400 {
401   inrange_node->setBoolValue( false );
402   signal_quality_norm_node->setDoubleValue( 0.0 );
403   cdi_deflection_node->setDoubleValue( 0.0 );
404   cdi_deflection_norm_node->setDoubleValue( 0.0 );
405   cdi_xtrack_error_node->setDoubleValue( 0.0 );
406   cdi_xtrack_hdg_err_node->setDoubleValue( 0.0 );
407   time_to_intercept->setDoubleValue( 0.0 );
408   heading_node->setDoubleValue(0.0);
409   gs_deflection_node->setDoubleValue( 0.0 );
410   gs_deflection_deg_node->setDoubleValue(0.0);
411   gs_deflection_norm_node->setDoubleValue(0.0);
412   gs_direct_node->setDoubleValue(0.0);
413   gs_inrange_node->setBoolValue( false );
414   loc_node->setBoolValue( false );
415   has_gs_node->setBoolValue(false);
416   
417   to_flag_node->setBoolValue( false );
418   from_flag_node->setBoolValue( false );
419   is_valid_node->setBoolValue(false);
420   nav_id_node->setStringValue("");
421   
422   _operable = false;
423   _navaid = NULL;
424 }
425
426 void FGNavRadio::updateReceiver(double dt)
427 {
428   SGVec3d aircraft = SGVec3d::fromGeod(globals->get_aircraft_position());
429   double loc_dist = 0;
430
431   // Do a nav station search only once a second to reduce
432   // unnecessary work. (Also, make sure to do this before caching
433   // any values!)
434   _time_before_search_sec -= dt;
435   if ( _time_before_search_sec < 0 ) {
436    search();
437   }
438
439   if (_navaid)
440   {
441       loc_dist = dist(aircraft, _navaid->cart());
442       loc_dist_node->setDoubleValue( loc_dist );
443   }
444
445   if (nav_slaved_to_gps_node->getBoolValue()) {
446     // when slaved to GPS: only allow stuff above: tune NAV station
447     // All other data driven by GPS only.
448     updateGPSSlaved();
449     return;
450   }
451
452   if (!_navaid) {
453     _cdiDeflection = 0.0;
454     _cdiCrossTrackErrorM = 0.0;
455     _toFlag = _fromFlag = false;
456     _gsNeedleDeflection = 0.0;
457     _gsNeedleDeflectionNorm = 0.0;
458     heading_node->setDoubleValue(0.0);
459     inrange_node->setBoolValue(false);
460     signal_quality_norm_node->setDoubleValue(0.0);
461     gs_dist_node->setDoubleValue( 0.0 );
462     gs_inrange_node->setBoolValue(false);
463     return;
464   }
465
466   double nav_elev = _navaid->get_elev_ft();
467
468   bool is_loc = loc_node->getBoolValue();
469   double signal_quality_norm = signal_quality_norm_node->getDoubleValue();
470   
471   double az2, s;
472   //////////////////////////////////////////////////////////
473         // compute forward and reverse wgs84 headings to localizer
474   //////////////////////////////////////////////////////////
475   double hdg;
476   SGGeodesy::inverse(globals->get_aircraft_position(), _navaid->geod(), hdg, az2, s);
477   heading_node->setDoubleValue(hdg);
478   double radial = az2 - twist;
479   double recip = radial + 180.0;
480   SG_NORMALIZE_RANGE(recip, 0.0, 360.0);
481   radial_node->setDoubleValue( radial );
482   recip_radial_node->setDoubleValue( recip );
483   
484   //////////////////////////////////////////////////////////
485   // compute the target/selected radial in "true" heading
486   //////////////////////////////////////////////////////////
487   if (!is_loc) {
488     target_radial = sel_radial_node->getDoubleValue();
489   }
490   
491   // VORs need twist (mag-var) added; ILS/LOCs don't but we set twist to 0.0
492   double trtrue = target_radial + twist;
493   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
494   target_radial_true_node->setDoubleValue( trtrue );
495
496   //////////////////////////////////////////////////////////
497   // adjust reception range for altitude
498   // FIXME: make sure we are using the navdata range now that
499   //        it is valid in the data file
500   //////////////////////////////////////////////////////////
501         if ( is_loc ) {
502             double offset = radial - target_radial;
503       SG_NORMALIZE_RANGE(offset, -180.0, 180.0);
504             effective_range
505                 = adjustILSRange( nav_elev, globals->get_aircraft_position().getElevationM(), offset,
506                                   loc_dist * SG_METER_TO_NM );
507         } else {
508             effective_range
509                 = adjustNavRange( nav_elev, globals->get_aircraft_position().getElevationM(), _navaid->get_range() );
510         }
511   
512   double effective_range_m = effective_range * SG_NM_TO_METER;
513
514   //////////////////////////////////////////////////////////
515   // compute signal quality
516   // 100% within effective_range
517   // decreases 1/x^2 further out
518   //////////////////////////////////////////////////////////  
519   double last_signal_quality_norm = signal_quality_norm;
520
521   if ( loc_dist < effective_range_m ) {
522     signal_quality_norm = 1.0;
523   } else {
524     double range_exceed_norm = loc_dist/effective_range_m;
525     signal_quality_norm = 1/(range_exceed_norm*range_exceed_norm);
526   }
527
528   signal_quality_norm = fgGetLowPass( last_signal_quality_norm, 
529            signal_quality_norm, dt );
530   
531   signal_quality_norm_node->setDoubleValue( signal_quality_norm );
532   bool inrange = signal_quality_norm > 0.2;
533   inrange_node->setBoolValue( inrange );
534   
535   //////////////////////////////////////////////////////////
536   // compute to/from flag status
537   //////////////////////////////////////////////////////////
538   if (inrange) {
539     if (is_loc) {
540       _toFlag = true;
541     } else {
542       double offset = fabs(radial - target_radial);
543       _toFlag = (offset > 90.0 && offset < 270.0);
544     }
545     _fromFlag = !_toFlag;
546   } else {
547     _toFlag = _fromFlag = false;
548   }
549   
550   // CDI deflection
551   double r = target_radial - radial;
552   SG_NORMALIZE_RANGE(r, -180.0, 180.0);
553   
554   if ( is_loc ) {
555     if (falseCoursesEnabledNode->getBoolValue()) {
556       // The factor of 30.0 gives a period of 120 which gives us 3 cycles and six 
557       // zeros i.e. six courses: one front course, one back course, and four 
558       // false courses. Three of the six are reverse sensing.
559       _cdiDeflection = 30.0 * sawtooth(r / 30.0);
560     } else {
561       // no false courses, but we do need to create a back course
562       if (fabs(r) > 90.0) { // front course
563         _cdiDeflection = r - copysign(180.0, r);
564       } else {
565         _cdiDeflection = r; // back course
566       }
567       
568       _cdiDeflection = -_cdiDeflection; // reverse for outbound radial
569     } // of false courses disabled
570     
571     const double VOR_FULL_ARC = 20.0; // VOR is -10 .. 10 degree swing
572     _cdiDeflection *= VOR_FULL_ARC / _localizerWidth; // increased localiser sensitivity
573     
574     if (backcourse_node->getBoolValue()) {
575       _cdiDeflection = -_cdiDeflection;
576     }
577   } else {
578     // handle the TO side of the VOR
579     if (fabs(r) > 90.0) {
580       r = ( r<0.0 ? -r-180.0 : -r+180.0 );
581     }
582     _cdiDeflection = r;
583   } // of non-localiser case
584   
585   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
586   _cdiDeflection *= signal_quality_norm;
587   
588   // cross-track error (in meters)
589   _cdiCrossTrackErrorM = loc_dist * sin(r * SGD_DEGREES_TO_RADIANS);
590   
591   updateGlideSlope(dt, aircraft, signal_quality_norm);
592 }
593
594 void FGNavRadio::updateGlideSlope(double dt, const SGVec3d& aircraft, double signal_quality_norm)
595 {
596   bool gsInRange = (_gs && inrange_node->getBoolValue());
597   double gsDist = 0;
598
599   if (gsInRange)
600   {
601     gsDist = dist(aircraft, _gsCart);
602     gsInRange = (gsDist < (_gs->get_range() * SG_NM_TO_METER));
603   }
604
605   gs_inrange_node->setBoolValue(gsInRange);
606   gs_dist_node->setDoubleValue( gsDist );
607
608   if (!gsInRange)
609   {
610     _gsNeedleDeflection = 0.0;
611     _gsNeedleDeflectionNorm = 0.0;
612     return;
613   }
614   
615   SGVec3d pos = aircraft - _gsCart; // relative vector from gs antenna to aircraft
616   // The positive GS axis points along the runway in the landing direction,
617   // toward the far end, not toward the approach area, so we need a - sign here:
618   double comp_h = -dot(pos, _gsAxis);      // component in horiz direction
619   double comp_v = dot(pos, _gsVertical);   // component in vertical direction
620   //double comp_b = dot(pos, _gsBaseline);   // component in baseline direction
621   //if (comp_b) {}                           // ... (useful for debugging)
622
623 // _gsDirect represents the angle of elevation of the aircraft
624 // as seen by the GS transmitter.
625   _gsDirect = atan2(comp_v, comp_h) * SGD_RADIANS_TO_DEGREES;
626 // At this point, if the aircraft is centered on the glide slope,
627 // _gsDirect will be a small positive number, e.g. 3.0 degrees
628
629 // Aim the branch cut straight down 
630 // into the ground below the GS transmitter:
631   if (_gsDirect < -90.0) _gsDirect += 360.0;
632
633   double deflectionAngle = target_gs - _gsDirect;
634   
635   if (falseCoursesEnabledNode->getBoolValue()) {
636     // Construct false glideslopes.  The scale factor of 1.5 
637     // in the sawtooth gives a period of 6 degrees.
638     // There will be zeros at 3, 6r, 9, 12r et cetera
639     // where "r" indicates reverse sensing.
640     // This is is consistent with conventional pilot lore
641     // e.g. http://www.allstar.fiu.edu/aerojava/ILS.htm
642     // but inconsistent with
643     // http://www.freepatentsonline.com/3757338.html
644     //
645     // It may be that some of each exist.
646     if (deflectionAngle < 0) {
647       deflectionAngle = 1.5 * sawtooth(deflectionAngle / 1.5);
648     } else {
649       // no false GS below the true GS
650     }
651   }
652   
653 // GS is documented to be 1.4 degrees thick, 
654 // i.e. plus or minus 0.7 degrees from the midline:
655   SG_CLAMP_RANGE(deflectionAngle, -0.7, 0.7);
656
657 // Many older instrument xml frontends depend on
658 // the un-normalized gs-needle-deflection.
659 // Apparently the interface standard is plus or minus 3.5 "volts"
660 // for a full-scale deflection:
661   _gsNeedleDeflection = deflectionAngle * 5.0;
662   _gsNeedleDeflection *= signal_quality_norm;
663   
664   _gsNeedleDeflectionNorm = (deflectionAngle / 0.7) * signal_quality_norm;
665   
666   //////////////////////////////////////////////////////////
667   // Calculate desired rate of climb for intercepting the GS
668   //////////////////////////////////////////////////////////
669   double gs_diff = target_gs - _gsDirect;
670   // convert desired vertical path angle into a climb rate
671   double des_angle = _gsDirect - 10 * gs_diff;
672   /* printf("target_gs=%.1f angle=%.1f gs_diff=%.1f des_angle=%.1f\n",
673      target_gs, _gsDirect, gs_diff, des_angle); */
674
675   // estimate horizontal speed towards ILS in meters per minute
676   double elapsedDistance = last_x - gsDist;
677   last_x = gsDist;
678       
679   double new_vel = ( elapsedDistance / dt );
680   horiz_vel = 0.99 * horiz_vel + 0.01 * new_vel;
681   /* printf("vel=%.1f (dist=%.1f dt=%.2f)\n", horiz_vel, elapsedDistance, dt);*/
682
683   gs_rate_of_climb_node
684       ->setDoubleValue( -sin( des_angle * SGD_DEGREES_TO_RADIANS )
685                         * horiz_vel * SG_METER_TO_FEET );
686   gs_rate_of_climb_fpm_node
687       ->setDoubleValue( gs_rate_of_climb_node->getDoubleValue() * 60 );
688 }
689
690 void FGNavRadio::valueChanged (SGPropertyNode* prop)
691 {
692   if (prop == gps_course_node) {
693     if (!nav_slaved_to_gps_node->getBoolValue()) {
694       return;
695     }
696   
697     // GPS desired course has changed, sync up our selected-course
698     double v = prop->getDoubleValue();
699     if (v != sel_radial_node->getDoubleValue()) {
700       sel_radial_node->setDoubleValue(v);
701     }
702   } else if (prop == nav_slaved_to_gps_node) {
703     if (prop->getBoolValue()) {
704       // slaved-to-GPS activated, clear obsolete NAV outputs and sync up selected course
705       clearOutputs();
706       sel_radial_node->setDoubleValue(gps_course_node->getDoubleValue());
707     }
708     // slave-to-GPS enabled/disabled, resync NAV station (update all outputs)
709     _navaid = NULL;
710     _time_before_search_sec = 0;
711   }
712 }
713
714 void FGNavRadio::updateGPSSlaved()
715 {
716   has_gs_node->setBoolValue(gps_has_gs_node->getBoolValue());
717  
718   _toFlag = gps_to_flag_node->getBoolValue();
719   _fromFlag = gps_from_flag_node->getBoolValue();
720
721   bool gpsValid = (_toFlag | _fromFlag);
722   inrange_node->setBoolValue(gpsValid);
723   if (!gpsValid) {
724     signal_quality_norm_node->setDoubleValue(0.0);
725     _cdiDeflection = 0.0;
726     _cdiCrossTrackErrorM = 0.0;
727     _gsNeedleDeflection = 0.0;
728     _gsNeedleDeflectionNorm = 0.0;
729     return;
730   }
731   
732   // this is unfortunate, but panel instruments use this value to decide
733   // if the navradio output is valid.
734   signal_quality_norm_node->setDoubleValue(1.0);
735   
736   _cdiDeflection =  gps_cdi_deflection_node->getDoubleValue();
737   // clmap to some range (+/- 10 degrees) as the regular deflection
738   SG_CLAMP_RANGE(_cdiDeflection, -10.0, 10.0 );
739   
740   _cdiCrossTrackErrorM = gps_xtrack_error_nm_node->getDoubleValue() * SG_NM_TO_METER;
741   _gsNeedleDeflection = 0.0; // FIXME, supply this
742   
743   double trtrue = gps_course_node->getDoubleValue() + _magvarNode->getDoubleValue();
744   SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
745   target_radial_true_node->setDoubleValue( trtrue );
746 }
747
748 void FGNavRadio::updateCDI(double dt)
749 {
750   bool cdi_serviceable = cdi_serviceable_node->getBoolValue();
751   bool inrange = inrange_node->getBoolValue();
752                                
753   if (tofrom_serviceable_node->getBoolValue()) {
754     to_flag_node->setBoolValue(_toFlag);
755     from_flag_node->setBoolValue(_fromFlag);
756   } else {
757     to_flag_node->setBoolValue(false);
758     from_flag_node->setBoolValue(false);
759   }
760   
761   if (!cdi_serviceable) {
762     _cdiDeflection = 0.0;
763     _cdiCrossTrackErrorM = 0.0;
764   }
765   
766   cdi_deflection_node->setDoubleValue(_cdiDeflection);
767   cdi_deflection_norm_node->setDoubleValue(_cdiDeflection * 0.1);
768   cdi_xtrack_error_node->setDoubleValue(_cdiCrossTrackErrorM);
769
770   //////////////////////////////////////////////////////////
771   // compute an approximate ground track heading error
772   //////////////////////////////////////////////////////////
773   double hdg_error = 0.0;
774   if ( inrange && cdi_serviceable ) {
775     double vn = fgGetDouble( "/velocities/speed-north-fps" );
776     double ve = fgGetDouble( "/velocities/speed-east-fps" );
777     double gnd_trk_true = atan2( ve, vn ) * SGD_RADIANS_TO_DEGREES;
778     if ( gnd_trk_true < 0.0 ) { gnd_trk_true += 360.0; }
779
780     SGPropertyNode *true_hdg
781         = fgGetNode("/orientation/heading-deg", true);
782     hdg_error = gnd_trk_true - true_hdg->getDoubleValue();
783
784     // cout << "ground track = " << gnd_trk_true
785     //      << " orientation = " << true_hdg->getDoubleValue() << endl;
786   }
787   cdi_xtrack_hdg_err_node->setDoubleValue( hdg_error );
788
789   //////////////////////////////////////////////////////////
790   // Calculate a suggested target heading to smoothly intercept
791   // a nav/ils radial.
792   //////////////////////////////////////////////////////////
793
794   // Now that we have cross track heading adjustment built in,
795   // we shouldn't need to overdrive the heading angle within 8km
796   // of the station.
797   //
798   // The cdi deflection should be +/-10 for a full range of deflection
799   // so multiplying this by 3 gives us +/- 30 degrees heading
800   // compensation.
801   double adjustment = _cdiDeflection * 3.0;
802   SG_CLAMP_RANGE( adjustment, -30.0, 30.0 );
803
804   // determine the target heading to fly to intercept the
805   // tgt_radial = target radial (true) + cdi offset adjustment -
806   // xtrack heading error adjustment
807   double nta_hdg;
808   double trtrue = target_radial_true_node->getDoubleValue();
809   if ( loc_node->getBoolValue() && backcourse_node->getBoolValue() ) {
810       // tuned to a localizer and backcourse mode activated
811       trtrue += 180.0;   // reverse the target localizer heading
812       SG_NORMALIZE_RANGE(trtrue, 0.0, 360.0);
813       nta_hdg = trtrue - adjustment - hdg_error;
814   } else {
815       nta_hdg = trtrue + adjustment - hdg_error;
816   }
817
818   SG_NORMALIZE_RANGE(nta_hdg, 0.0, 360.0);
819   target_auto_hdg_node->setDoubleValue( nta_hdg );
820
821   //////////////////////////////////////////////////////////
822   // compute the time to intercept selected radial (based on
823   // current and last cross track errors and dt)
824   //////////////////////////////////////////////////////////
825   double t = 0.0;
826   if ( inrange && cdi_serviceable ) {
827     double cur_rate = (last_xtrack_error - _cdiCrossTrackErrorM) / dt;
828     xrate_ms = 0.99 * xrate_ms + 0.01 * cur_rate;
829     if ( fabs(xrate_ms) > 0.00001 ) {
830         t = _cdiCrossTrackErrorM / xrate_ms;
831     } else {
832         t = 9999.9;
833     }
834   }
835   time_to_intercept->setDoubleValue( t );
836
837   if (!gs_serviceable_node->getBoolValue() ) {
838     _gsNeedleDeflection = 0.0;
839     _gsNeedleDeflectionNorm = 0.0;
840   }
841   gs_deflection_node->setDoubleValue(_gsNeedleDeflection);
842   gs_deflection_deg_node->setDoubleValue(_gsNeedleDeflectionNorm * 0.7);
843   gs_deflection_norm_node->setDoubleValue(_gsNeedleDeflectionNorm);
844   gs_direct_node->setDoubleValue(_gsDirect);
845   
846   last_xtrack_error = _cdiCrossTrackErrorM;
847 }
848
849 void FGNavRadio::updateAudio( double dt )
850 {
851   if (!_navaid || !inrange_node->getBoolValue() || !nav_serviceable_node->getBoolValue()) {
852     _audioIdent->setIdent("", 0.0 );
853     return;
854   }
855   
856         // play station ident via audio system if on + ident,
857         // otherwise turn it off
858   if (!power_btn_node->getBoolValue()
859       || !(bus_power_node->getDoubleValue() > 1.0)
860       || !ident_btn_node->getBoolValue()
861       || !audio_btn_node->getBoolValue() ) {
862     _audioIdent->setIdent("", 0.0 );
863     return;
864   }
865
866   _audioIdent->setIdent( _navaid->get_trans_ident(), vol_btn_node->getFloatValue() );
867
868   _audioIdent->update( dt );
869 }
870
871 FGNavRecord* FGNavRadio::findPrimaryNavaid(const SGGeod& aPos, double aFreqMHz)
872 {
873   return FGNavList::findByFreq(aFreqMHz, aPos, FGNavList::navFilter());
874 }
875
876 // Update current nav/adf radio stations based on current position
877 void FGNavRadio::search() 
878 {
879   // set delay for next search
880   _time_before_search_sec = 1.0;
881
882   double freq = freq_node->getDoubleValue();
883
884   // immediate NAV search when frequency has changed (toggle between nav and g/s search otherwise)
885   _nav_search |= (_last_freq != freq);
886
887   // do we need to search a new NAV station in this iteration?
888   if (_nav_search)
889   {
890       _last_freq = freq;
891       FGNavRecord* nav = findPrimaryNavaid(globals->get_aircraft_position(), freq);
892       if (nav == _navaid) {
893         if (nav && (nav->type() != FGPositioned::VOR))
894             _nav_search = false;  // search glideslope on next iteration
895         return; // nav hasn't changed, we're done
896       }
897       // remember new navaid station
898       _navaid = nav;
899   }
900
901   // search glideslope station
902   if ((_navaid.valid()) && (_navaid->type() != FGPositioned::VOR))
903   {
904     FGNavList::TypeFilter gsFilter(FGPositioned::GS);
905     FGNavRecord* gs = FGNavList::findByFreq(freq, globals->get_aircraft_position(),
906                                            &gsFilter);
907       if ((!_nav_search) && (gs == _gs))
908       {
909           _nav_search = true; // search NAV on next iteration
910           return; // g/s hasn't changed, neither has nav - we're done
911       }
912       // remember new glideslope station
913       _gs = gs;
914   }
915
916   _nav_search = true; // search NAV on next iteration
917
918   // nav or gs station has changed
919   updateNav();
920 }
921
922 // Update current nav/adf/glideslope outputs when station has changed
923 void FGNavRadio::updateNav()
924 {
925   // update necessary, nav and/or gs has changed
926   FGNavRecord* nav = _navaid;
927   string identBuffer(4, ' ');
928   if (nav) {
929     nav_id_node->setStringValue(nav->get_ident());
930     identBuffer =  simgear::strutils::rpad( nav->ident(), 4, ' ' );
931     
932     effective_range = adjustNavRange(nav->get_elev_ft(), globals->get_aircraft_position().getElevationM(), nav->get_range());
933     loc_node->setBoolValue(nav->type() != FGPositioned::VOR);
934     twist = nav->get_multiuse();
935
936     if (nav->type() == FGPositioned::VOR) {
937       target_radial = sel_radial_node->getDoubleValue();
938       _gs = NULL;
939     } else { // ILS or LOC
940       _localizerWidth = nav->localizerWidth();
941       twist = 0.0;
942       effective_range = nav->get_range();
943       
944       target_radial = nav->get_multiuse();
945       SG_NORMALIZE_RANGE(target_radial, 0.0, 360.0);
946
947       if (_gs) {
948         int tmp = (int)(_gs->get_multiuse() / 1000.0);
949         target_gs = (double)tmp / 100.0;
950
951         double gs_radial = fmod(_gs->get_multiuse(), 1000.0);
952         SG_NORMALIZE_RANGE(gs_radial, 0.0, 360.0);
953         _gsCart = _gs->cart();
954                 
955         // GS axis unit tangent vector 
956         // (along the runway):
957         _gsAxis = tangentVector(_gs->geod(), gs_radial);
958
959         // GS baseline unit tangent vector
960         // (transverse to the runway along the ground)
961         _gsBaseline = tangentVector(_gs->geod(), gs_radial + 90.0);
962         _gsVertical = cross(_gsBaseline, _gsAxis);
963       } // of have glideslope
964     } // of found LOC or ILS
965     
966   } else { // found nothing
967     _gs = NULL;
968     nav_id_node->setStringValue("");
969     loc_node->setBoolValue(false);
970     _audioIdent->setIdent("", 0.0 );
971   }
972
973   has_gs_node->setBoolValue(_gs != NULL);
974   is_valid_node->setBoolValue(nav != NULL);
975   id_c1_node->setIntValue( (int)identBuffer[0] );
976   id_c2_node->setIntValue( (int)identBuffer[1] );
977   id_c3_node->setIntValue( (int)identBuffer[2] );
978   id_c4_node->setIntValue( (int)identBuffer[3] );
979 }