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