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