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