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